Repository navigation
[Fix][Transform-V2] Honor Amazon embedding retry options - #12193
Conversation
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
The AMAZON (Bedrock) branch of EmbeddingTransform.open() built its BedrockModel through the legacy 7-arg constructor BedrockModel(accessKey, secretKey, region, endpoint, modelId, dimension, batchSize). That constructor internally delegates to BedrockModel(client, modelId, dimension, batchSize), which falls back to ModelInvocationOptions.defaults() (seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/remote/amazon/BedrockModel.java:144-152). This means that no matter what a user configured for model_retry_max_attempts / model_retry_backoff_ms / model_retry_max_backoff_ms, the Bedrock path always ran with exactly one SeaTunnel attempt.
Example: a user configures model_provider = AMAZON with model_retry_max_attempts = 3 to ride out transient ModelErrorException (HTTP 424) responses from Bedrock. Every other provider (OpenAI, Doubao, Qianfan, Zhipu, Custom) already honors this setting because their construction calls pass invocationOptions through (EmbeddingTransform.java:118-174). Amazon silently didn't - the job would fail on the very first transient error instead of retrying, even though the user's config said otherwise.
The fix threads the already-existing ModelInvocationOptions invocationOptions (built once per open() at EmbeddingTransform.java:92) into the Bedrock construction path by calling the existing BedrockModel.createBedrockClient(...) factory directly and using the existing BedrockModel(client, modelId, dimension, batchSize, invocationOptions) overload (EmbeddingTransform.java:175-191, constructor at BedrockModel.java:163-176). No new class, constructor, or config option is introduced; the fix simply calls a constructor overload that already existed for exactly this purpose (added by #10863) but was never wired up for Amazon.
1. Code Change Review
1.1 Core Logic Analysis
I traced the full runtime path this PR touches:
EmbeddingTransform.open()buildsModelInvocationOptions invocationOptions = ModelInvocationOptions.fromConfig(config)once (EmbeddingTransform.java:92), readingMODEL_RETRY_MAX_ATTEMPTS/MODEL_RETRY_BACKOFF_MS/MODEL_RETRY_MAX_BACKOFF_MS/MODEL_REQUEST_TIMEOUT_MS(ModelInvocationOptions.java:53-59).- Before this PR, the
AMAZONcase (old code) dropped that object entirely and called the legacy constructor, which hardcodesModelInvocationOptions.defaults()(BedrockModel.java:144-152,DEFAULT_RETRY_MAX_ATTEMPTS = 1atModelInvocationOptions.java:24). AbstractModelwraps every provider'svector()call throughModelInvocationRuntime.invoke()->invokeWithRetries()(ModelInvocationRuntime.java:84-118), which is the single place that actually loopsfor (attempt = 1; attempt <= options.getRetryMaxAttempts(); attempt++). Since Bedrock'sinvocationRuntimewas always constructed with the 1-attempt default, this loop could never iterate more than once for Bedrock, regardless of user config - confirming the bug is real and lives exactly where the PR fixes it.- After the fix,
bedrockBatchSize/bedrockModelId/bedrockDimensionare read into locals first (EmbeddingTransform.java:176-179), thenBedrockModel.createBedrockClient(...)builds the client (BedrockModel.java:234-253) and the 5-arg constructor storesinvocationOptionsinto the sharedModelInvocationRuntimeviaAbstractModel's constructor (AbstractModel.java:43-47). From that point on, Bedrock goes through exactly the same retry/backoff/metrics/logging pipeline as every other provider.
This is a normal-path fix, not a boundary/recovery-path-only fix: any AMAZON-provider job that sets model_retry_max_attempts > 1 hits this code on every single open() call (which happens once per task via tryOpen(), EmbeddingTransform.java:83-86), not just under some rare race or restart condition.
1.2 Compatibility Impact
Classification: Fully compatible, with one explicitly-documented and correctly-scoped behavior change.
- Default behavior is unchanged:
ModelInvocationOptions.defaults()andModelInvocationOptions.fromConfig(...)both resolve toretryMaxAttempts = 1when the user hasn't setmodel_retry_max_attempts(ModelInvocationOptions.java:24,39,45-59), so any existing job that never touched these options keeps issuing exactly one attempt, exactly as before. This is directly verified by the newshouldKeepSingleSeaTunnelAttemptByDefaulttest. - The behavior change only activates for users who had already configured
model_retry_max_attempts > 1for anAMAZONembedding - previously a no-op for them, now it actually retries. That is precisely a bug fix, not a new incompatible default, and it is called out correctly in bothdocs/en/introduction/concepts/incompatible-changes.mdand the zh equivalent as a "Behavior change" with migration guidance (set it back to1to opt out). - No public API, SPI, or
Optionis added, renamed, or removed.BedrockModel's constructors are all untouched (diff contains zero changes toBedrockModel.java); the PR only changes which already-existing overloadEmbeddingTransformcalls into.createBedrockClientwas alreadypublic staticbefore this PR. - No checkpoint/savepoint or serialized state is involved -
EmbeddingTransform/BedrockModelare stateless request-response constructs re-created per task viatryOpen(), so there is no historical-state-restore compatibility concern here. - The one caveat the PR explicitly and correctly discloses (not glossed over) is that
model_request_timeout_msstill is not applied to Bedrock:context.getRequestTimeoutMs()(ModelInvocationContext, consumed atModelInvocationRuntime.java:93) is only used for logging context inBedrockModel, whereasOpenAIModel's embedding path actually applies it toRequestConfig.setConnectTimeout/setSocketTimeoutper call (seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/remote/openai/OpenAIModel.java:143-144).createBedrockClient(BedrockModel.java:234-253) has no per-call timeout wiring at all - this is an accurate limitation statement, not new breakage, since Bedrock never enforced this option even before this PR.
1.3 Performance / Side-Effect Analysis
- No new object allocation pattern of consequence: one extra pair of
int/Stringlocals peropen()call, which already happens once per task lifecycle, not per record. - The actual behavioral/performance consequence is the intended one: for AMAZON jobs that configure
model_retry_max_attempts > 1, a transient Bedrock error (ThrottlingException,ServiceQuotaExceededException,InternalServerException,ServiceUnavailableException,ModelNotReadyException,ModelErrorException, genericSdkClientException- seemapAwsException,BedrockModel.java:437-469) will now causeThread.sleepbackoff (ModelInvocationRuntime.sleepBeforeRetry,ModelInvocationRuntime.java:261-281) and a repeat HTTP call, exactly mirroring what already happens for OpenAI/Doubao/Qianfan/Zhipu/Custom. This is bounded by the sameretryMaxAttempts/backoff-cap options users already control, so there's no unbounded-retry or resource-leak risk introduced. client.close()ownership (BedrockModel.java:518-523) is untouched; the client is still created once inopen()and closed once via the transform's lifecycle, so no extra client/connection churn is introduced by this change.- No new locks, threads, or queues are introduced.
1.4 Error Handling and Logging
- Exception classification (
mapAwsException,BedrockModel.java:437-497) is untouched by this diff - retryable vs. non-retryable categorization for Bedrock errors is unaffected; the PR only changes whether the retry loop actually gets more than one attempt to use that classification. - Logging on the shared path already avoids leaking secrets:
ModelInvocationRuntime.logInvocationFailure(ModelInvocationRuntime.java:244-259) only logs provider/model/batchSize/attempt/errorType/retryable/elapsed - no request/response bodies or credentials. The newshouldNotRetryAuthenticationFailuretest explicitly asserts the exception message does not contain the injectedprivate-api/private-secretfixture values, which is good evidence this path doesn't regress on secret-leakage. - The only checked exception involved (
URISyntaxExceptionfromcreateBedrockClient) is still caught the same way as before, inEmbeddingTransform.open()'s existingcatch (URISyntaxException e) { throw new RuntimeException(e); }(unchanged block right after theswitch).
2. Code Quality Assessment
2.1 Coding Standards
- Follows AOSP/Google-Java-Format conventions consistent with the surrounding file; no wildcard imports; no new dependency (
mockwebserverused in the test was already aseatunnel-transforms-v2test dependency prior to this PR - confirmed viagrep -n mockwebserver seatunnel-transforms-v2/pom.xml, unchanged by this diff). - The three extracted locals (
bedrockModelId,bedrockDimension,bedrockBatchSize) are a nice small readability improvement over the previous fully-inlined constructor call, and they make the constructor call itself easy to diff against the other providers' calls just above it. - No ASF license header issue (no new production file was added; the new test file correctly carries the standard ASF header).
2.2 Test Coverage and Test Stability
Explicit stability rating: Stable, with one test worth a closer look (Risk present, not blocking).
The new AmazonEmbeddingInvocationTest (314 lines, 8 @Test methods) is a strong, faithful regression suite:
- It exercises the real runtime path, not a mock of
EmbeddingTransform:transform.getProducedCatalogTable()triggerstransformCatalogTable()->getOutputColumns()->tryOpen()->open()(AbstractSeaTunnelTransform.java:48-56,MultipleFieldOutputTransform.java:90callinggetOutputColumns(),EmbeddingTransform.java:279-282), so the tests genuinely go through the same code this PR touches, using a realBedrockRuntimeClientpointed at a localMockWebServer(no AWS account needed, matches PR description). shouldApplyConfiguredRetriesThroughTransformis the actual regression test for the bug: 2x HTTP 424 (ModelErrorException, mapped toTEMPORARY_REMOTE_ERROR/retryable bymapAwsException) then success, withmodel_retry_max_attempts = 3. On the pre-fix code this fails after the first 424 because Bedrock always got the 1-attempt default; the PR description states this was confirmed against the original code, which is consistent with everything I traced above.shouldKeepSingleSeaTunnelAttemptByDefaultis the compatibility guard: without settingmodel_retry_max_attempts, only 1 request is made even though a retryable error occurred - this is the test that proves the fix does not change default/existing-job behavior.shouldNotRetryAuthenticationFailure,shouldNotRetryMissingVector,shouldNotRetryMalformedResponsecover the non-retryable classification paths, and the auth one additionally asserts secret-key/api-key redaction - good defensive coverage that also protectsmapAwsException's classification against an accidental future regression.shouldReadBatchSizeBeforeConstructingClient: this one asserts a specific evaluation order (batch-size config parsing failing before the invalidapi_pathURI is parsed). This is arguably testing an implementation detail (Java left-to-right argument evaluation / local-variable ordering) rather than a user-facing contract, and - based on my read of the old code path (the old 7-arg constructor also evaluated allconfig.get(...)arguments, includingSINGLE_VECTORIZED_INPUT_NUMBER, beforecreateBedrockClient's ownnew URI(...)call ever ran, since Java fully evaluates outer-call arguments before entering the delegating constructor's body) - it's not fully clear this test actually discriminates old vs. new code. This isn't a blocker (the assertion is still true and harmless), just a nit: consider dropping it or reframing its purpose/name if it turns out to pass unmodified againstdev.shouldPreserveExternalInterruptionWithoutAnotherHttpRequestis the one I'd flag as "Risk present" rather than fully stable: it relies oncaller.interrupt()being called from theMockWebServerdispatcher thread while the main test thread is blocked inside the Apache-HTTP-Client-backedclient.invokeModel(...)call, and then asserts bothThread.currentThread().isInterrupted()staystrueandserver.getRequestCount() == 1(i.e., no retry was attempted). Since the test'smodel_retry_backoff_ms/model_retry_max_backoff_msare left at0,sleepBeforeRetry(ModelInvocationRuntime.java:261-269) returns immediately without ever callingThread.sleep, so the "no second HTTP request" outcome depends entirely on whateverIOException/RuntimeExceptionthe AWS SDK / Apache HttpClient transport raises for an externally-interrupted blocking socket read being classified as non-retryable (or the loop otherwise stopping) - behavior that isn't part of this PR's own code and isn't guaranteed by the SDK's documented contract for classic (non-async) clients. This is a plausible source of CI flakiness on slower or differently-scheduled runners (a race between whendispatch()fires the interrupt and when the client thread is actually blocked in the socket read), and it also carries a@Timeout(60)per-test safety net rather than a shorter, more deterministic bound. It's not something introduced by the production code change (it tests library/runtime interaction, not new logic), so I would not block the PR on it, but it is worth watching for occasional CI flakiness reports, and a more deterministic simulation (e.g., a fakeBedrockRuntimeClient/adapter that throwsInterruptedIOExceptionsynchronously instead of a real socket race) would remove the timing dependency entirely.- All eight tests correctly
transform.close()in afinallyblock, and eachMockWebServeris opened via try-with-resources, so there's no resource-leak risk in the test suite itself.
2.3 Documentation Updates
Both docs/en and docs/zh are updated and consistent with the code:
docs/en/transforms/embedding.mdanddocs/zh/transforms/embedding.mdcorrectly soften the previous (apparently already slightly inaccurate) claim that Bedrock's common path handles "retry, timeout, response parsing" - the updated text correctly drops "timeout" from that list and adds an explicit paragraph on themodel_retry_max_attemptssemantics and the disclosedmodel_request_timeout_mslimitation, matching what I verified inBedrockModel.java/OpenAIModel.java.docs/en/introduction/concepts/incompatible-changes.md/ zh equivalent add a correctly-scoped "Behavior change" entry (affected component, description, impact/migration) rather than a[BREAKING]tag, which is the right severity given the default is unchanged and only previously-ineffective configuration now takes effect.- I did not find any other doc (e.g., connector-list tables, provider comparison matrices) that references the old "Bedrock now uses timeout" wording that would need a matching update - the two touched files are the only ones that made that claim (checked via
git diffscope; no additional grep hits needed beyond the changed files since the PR's diff is fully self-contained to these two doc pairs plus the source/test).
3. Architectural Soundness
3.1 Elegance of the Solution
This is about as minimal and well-targeted as a fix can be: it reuses an already-existing constructor overload and an already-existing public factory method, changes zero public signatures, and brings the Amazon branch in line with the pattern every other provider already follows in the same switch statement. There is no over-abstraction, no new class hierarchy, and no connector-specific logic leaking into shared code - if anything, this removes a special case (Amazon being the only provider not passing invocationOptions) rather than adding one.
3.2 Maintainability
Future readers scanning the switch in EmbeddingTransform.open() will now see a uniform pattern across all six provider branches (all pass invocationOptions as the last constructor argument), which reduces the chance of the same class of bug (a provider silently missing invocation options) being reintroduced for a future provider added via copy-paste of a "wrong" branch.
3.3 Extensibility
No impact on extensibility - no new SPI, no new provider-facing contract change. Any future embedding provider addition should follow the now fully-uniform pattern established here.
3.4 Historical-Version Compatibility
Not applicable in the Whale/2.6-3.0 upgrade sense (this is the Apache SeaTunnel dev mainline, not a Whale-branch upgrade path). Within this repository's own compatibility model: existing saved job configs for AMAZON embeddings continue to produce identical behavior unless they had already set model_retry_max_attempts > 1 and silently relied on (or were unaware of) that setting being a no-op - which is exactly the class of user this fix is meant to help, and is correctly documented as a behavior change with migration guidance.
4. Issue Summary
Issue 1 (Low, informational - not a blocker)
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/AmazonEmbeddingInvocationTest.java,shouldPreserveExternalInterruptionWithoutAnotherHttpRequest - Problem: The test's "no additional HTTP request after external interrupt" assertion depends on undocumented interrupt-handling behavior of the AWS SDK v2 / Apache HttpClient transport under a real socket race with
MockWebServer, rather than on any logic added by this PR. - Potential risk: Possible occasional CI flakiness on slower/differently-scheduled runners (interrupt delivered before or after the client thread reaches the blocking read), though a genuine failure would surface as a clear, non-silent test failure/timeout rather than a false pass.
- Best improvement: Option A (minimal) - leave as-is and just monitor for flakiness reports. Option B (more deterministic) - replace the real socket race with a fake HTTP transport/adapter that synchronously throws
InterruptedIOException/anSdkClientExceptionwrapping an interrupt, removing the timing dependency while still verifying "no additional retry attempt after interruption." - Severity: Low
- Raised by another reviewer: No
Issue 2 (Low, informational - not a blocker)
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/AmazonEmbeddingInvocationTest.java,shouldReadBatchSizeBeforeConstructingClient - Problem: The test pins a specific argument/local-variable evaluation order (batch-size parsing failing before URI parsing) that, based on my reading of the pre-fix constructor delegation chain, may already have held true on the original code too, making it more of an implementation-detail characterization test than a regression test for this specific bug.
- Potential risk: Low - the assertion is harmless and still true for the new code, it's just not clearly earning its keep as a "regression" test the way the PR description's "eight regressions" framing might suggest for all eight tests.
- Best improvement: Either confirm (e.g., by mentally/CI-diffing against
dev) that this test does discriminate old vs. new behavior, or reword the test name/intent to "documents/pins config-validation ordering" rather than implying it's a regression guard for the retry bug. - Severity: Low
- Raised by another reviewer: No
No Medium or High severity issues were found. The core fix (EmbeddingTransform.java:175-191) is correct, minimal, backward compatible, and directly reuses existing, already-tested (BedrockModel) infrastructure rather than inventing anything new.
5. Merge Recommendation
This is a clean, narrowly-scoped bug fix: it correctly identifies that the AMAZON embedding provider was the sole holdout not receiving ModelInvocationOptions (confirmed by tracing BedrockModel's constructor chain and ModelInvocationRuntime's retry loop), fixes it by reusing an existing constructor overload with zero API/behavioral-default changes, documents the one legitimate behavior change (configured retries now actually apply) in both English and Chinese incompatible-changes docs, and ships a thorough, realistic regression suite that reproduces the original bug end-to-end through the real transform lifecycle. The two issues raised above are test-quality nits, not correctness or compatibility concerns, and neither blocks merge.
The only outstanding item at review time is that CI (Build) on the fork was still queued/in-progress - please make sure it turns green (and specifically watch AmazonEmbeddingInvocationTest, in particular shouldPreserveExternalInterruptionWithoutAnotherHttpRequest, for any flakiness) before merging.
Nice, focused piece of work - thank you for the clear reproduction in #12190 and for tracing this all the way back to the exact constructor mismatch rather than papering over it with a workaround. Appreciate the bilingual docs updates too.
Conclusion: Ready to merge after fixes
- None (no blocking issues) - please just confirm the fork's CI run finishes green before merge, since it was still queued at review time.
Recommended fixes (non-blocking, optional):
- Consider a more deterministic simulation for
shouldPreserveExternalInterruptionWithoutAnotherHttpRequest(Issue 1) to remove the real-socket-interrupt race. - Double-check whether
shouldReadBatchSizeBeforeConstructingClient(Issue 2) actually discriminates old vs. new behavior, and adjust its name/intent if not.
DanielLeens
left a comment
There was a problem hiding this comment.
Follow-up: at my last review the only open item was confirming that the fork's Build run (still queued at the time) finished green. I just rechecked the current head (fbfed10e0d) and Build has now completed successfully, with no new commits since.
Conclusion: Ready to merge
No blockers. I have read-only review rights on this repository, so a write-capable maintainer still needs to give the final approval before this is merged.
Nice work, @Kareemingit — thanks for the clean fix and the bilingual docs.
Purpose of this pull request
Closes #12190.
The
AMAZONbranch ofEmbeddingTransformcreatesBedrockModelwithout the configured invocation options. It falls back to one SeaTunnel attempt even whenmodel_retry_max_attemptsis greater than 1.This follow-up to #10863 passes the options through the existing client factory and model constructor, allowing the common runtime to use the configured retry and backoff settings. No public API or dependency is added.
Does this PR introduce any user-facing change?
Yes. Amazon embedding honors configured SeaTunnel retry and backoff settings. With three configured attempts, two retryable model errors followed by a successful response now succeed; previously the transform failed on the first response.
The default remains one SeaTunnel attempt. Configured additional attempts can incur additional model charges. The AWS SDK may retry HTTP calls within each SeaTunnel attempt; its existing retry policy is unchanged.
Existing constructors, credentials, endpoint handling, batching, output schema and client ownership are preserved. SDK timeout behavior is also unchanged:
model_request_timeout_msis not currently applied to Bedrock calls. Timeout enforcement is outside this patch. English and Chinese documentation and upgrade notes describe the correction and limitation.How was this patch tested?
Added eight regressions through the actual transform: retry recovery and exhaustion, default single attempt, authentication failure, malformed JSON, missing vectors, external-interrupt preservation without additional HTTP requests, and configuration validation before client construction. HTTP fixtures use the real AWS SDK with synthetic local responses; no AWS account or model service is required. HTTP 424 fixtures distinguish SeaTunnel retries from SDK internal HTTP retries.
The retry regression fails on the original code on Java 8 and Java 11. The complete transform unit suite passes on both runtimes: 1,117 tests, zero failures, errors or skips.
./mvnw -B -ntp -pl seatunnel-transforms-v2 -Dskip.spotless=true clean testRun with Java 8 and Java 11. Repository-wide
./mvnw spotless:applyand./mvnw -q -DskipTests verifyalso pass, with the latter run on Java 11. The full-repository build skips tests; it is separate from the transform unit-suite results above.Check list
New License Guide — No new dependency.
incompatible-changes.mdto describe the incompatibility caused by this PR. — English and Chinese upgrade notes added.