Skip to content

[Fix][Transform-V2] Honor Amazon embedding retry options - #12193

Merged
davidzollo merged 1 commit into
apache:devfrom
goutamadwant:fix/amazon-embedding-retries
Sep 10, 2026
Merged

davidzollo merged 1 commit into
apache:devfrom
goutamadwant:fix/amazon-embedding-retries

Conversation

@goutamadwant

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Closes #12190.

The AMAZON branch of EmbeddingTransform creates BedrockModel without the configured invocation options. It falls back to one SeaTunnel attempt even when model_retry_max_attempts is 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_ms is 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 test

Run with Java 8 and Java 11. Repository-wide ./mvnw spotless:apply and ./mvnw -q -DskipTests verify also 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

  • If any new Jar binary package adding in your PR, please add License Notice according
    New License Guide — No new dependency.
  • If necessary, please update the documentation to describe the new feature. https://github.com/apache/seatunnel/tree/dev/docs — English and Chinese embedding documentation updated.
  • If necessary, please update incompatible-changes.md to describe the incompatibility caused by this PR. — English and Chinese upgrade notes added.
  • If you are contributing the connector code, please check that the following files are updated: — Not applicable; this changes an existing transform.
    1. Update plugin-mapping.properties and add new connector information in it — Not applicable.
    2. Update the pom file of seatunnel-dist — Not applicable.
    3. Add ci label in label-scope-conf — Not applicable.
    4. Add e2e testcase in seatunnel-e2e — Local SDK/transform regression fixtures cover the changed path; no new connector.
    5. Update connector plugin_config — Not applicable.

Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() builds ModelInvocationOptions invocationOptions = ModelInvocationOptions.fromConfig(config) once (EmbeddingTransform.java:92), reading MODEL_RETRY_MAX_ATTEMPTS / MODEL_RETRY_BACKOFF_MS / MODEL_RETRY_MAX_BACKOFF_MS / MODEL_REQUEST_TIMEOUT_MS (ModelInvocationOptions.java:53-59).
  • Before this PR, the AMAZON case (old code) dropped that object entirely and called the legacy constructor, which hardcodes ModelInvocationOptions.defaults() (BedrockModel.java:144-152, DEFAULT_RETRY_MAX_ATTEMPTS = 1 at ModelInvocationOptions.java:24).
  • AbstractModel wraps every provider's vector() call through ModelInvocationRuntime.invoke() -> invokeWithRetries() (ModelInvocationRuntime.java:84-118), which is the single place that actually loops for (attempt = 1; attempt <= options.getRetryMaxAttempts(); attempt++). Since Bedrock's invocationRuntime was 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/bedrockDimension are read into locals first (EmbeddingTransform.java:176-179), then BedrockModel.createBedrockClient(...) builds the client (BedrockModel.java:234-253) and the 5-arg constructor stores invocationOptions into the shared ModelInvocationRuntime via AbstractModel'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() and ModelInvocationOptions.fromConfig(...) both resolve to retryMaxAttempts = 1 when the user hasn't set model_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 new shouldKeepSingleSeaTunnelAttemptByDefault test.
  • The behavior change only activates for users who had already configured model_retry_max_attempts > 1 for an AMAZON embedding - 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 both docs/en/introduction/concepts/incompatible-changes.md and the zh equivalent as a "Behavior change" with migration guidance (set it back to 1 to opt out).
  • No public API, SPI, or Option is added, renamed, or removed. BedrockModel's constructors are all untouched (diff contains zero changes to BedrockModel.java); the PR only changes which already-existing overload EmbeddingTransform calls into. createBedrockClient was already public static before this PR.
  • No checkpoint/savepoint or serialized state is involved - EmbeddingTransform/BedrockModel are stateless request-response constructs re-created per task via tryOpen(), 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_ms still is not applied to Bedrock: context.getRequestTimeoutMs() (ModelInvocationContext, consumed at ModelInvocationRuntime.java:93) is only used for logging context in BedrockModel, whereas OpenAIModel's embedding path actually applies it to RequestConfig.setConnectTimeout/setSocketTimeout per 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/String locals per open() 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, generic SdkClientException - see mapAwsException, BedrockModel.java:437-469) will now cause Thread.sleep backoff (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 same retryMaxAttempts/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 in open() 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 new shouldNotRetryAuthenticationFailure test explicitly asserts the exception message does not contain the injected private-api/private-secret fixture values, which is good evidence this path doesn't regress on secret-leakage.
  • The only checked exception involved (URISyntaxException from createBedrockClient) is still caught the same way as before, in EmbeddingTransform.open()'s existing catch (URISyntaxException e) { throw new RuntimeException(e); } (unchanged block right after the switch).

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 (mockwebserver used in the test was already a seatunnel-transforms-v2 test dependency prior to this PR - confirmed via grep -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() triggers transformCatalogTable() -> getOutputColumns() -> tryOpen() -> open() (AbstractSeaTunnelTransform.java:48-56, MultipleFieldOutputTransform.java:90 calling getOutputColumns(), EmbeddingTransform.java:279-282), so the tests genuinely go through the same code this PR touches, using a real BedrockRuntimeClient pointed at a local MockWebServer (no AWS account needed, matches PR description).
  • shouldApplyConfiguredRetriesThroughTransform is the actual regression test for the bug: 2x HTTP 424 (ModelErrorException, mapped to TEMPORARY_REMOTE_ERROR/retryable by mapAwsException) then success, with model_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.
  • shouldKeepSingleSeaTunnelAttemptByDefault is the compatibility guard: without setting model_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, shouldNotRetryMalformedResponse cover the non-retryable classification paths, and the auth one additionally asserts secret-key/api-key redaction - good defensive coverage that also protects mapAwsException's classification against an accidental future regression.
  • shouldReadBatchSizeBeforeConstructingClient: this one asserts a specific evaluation order (batch-size config parsing failing before the invalid api_path URI 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 all config.get(...) arguments, including SINGLE_VECTORIZED_INPUT_NUMBER, before createBedrockClient's own new 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 against dev.
  • shouldPreserveExternalInterruptionWithoutAnotherHttpRequest is the one I'd flag as "Risk present" rather than fully stable: it relies on caller.interrupt() being called from the MockWebServer dispatcher thread while the main test thread is blocked inside the Apache-HTTP-Client-backed client.invokeModel(...) call, and then asserts both Thread.currentThread().isInterrupted() stays true and server.getRequestCount() == 1 (i.e., no retry was attempted). Since the test's model_retry_backoff_ms/model_retry_max_backoff_ms are left at 0, sleepBeforeRetry (ModelInvocationRuntime.java:261-269) returns immediately without ever calling Thread.sleep, so the "no second HTTP request" outcome depends entirely on whatever IOException/RuntimeException the 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 when dispatch() 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 fake BedrockRuntimeClient/adapter that throws InterruptedIOException synchronously instead of a real socket race) would remove the timing dependency entirely.
  • All eight tests correctly transform.close() in a finally block, and each MockWebServer is 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.md and docs/zh/transforms/embedding.md correctly 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 the model_retry_max_attempts semantics and the disclosed model_request_timeout_ms limitation, matching what I verified in BedrockModel.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 diff scope; 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/an SdkClientException wrapping 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

  1. 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 DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@goutamadwant goutamadwant self-assigned this Sep 10, 2026

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1
LGTM

@davidzollo
davidzollo added this pull request to the merge queue Sep 10, 2026
Merged via the queue into apache:dev with commit cf67b54 Sep 10, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Transform-V2] Amazon embedding ignores configured retry attempts

3 participants