You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/10 10:17:19 UTC

(seatunnel) 01/01: [Fix][Transform-V2] Honor Amazon embedding retry options (#12193)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12193-ea1fb0d850c70a38fc2d6447e45071b05b1174e8
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit cf67b549a7a6c35fa0beb12d83c62892427ea919
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Thu Sep 10 10:16:53 2026 +0000

    [Fix][Transform-V2] Honor Amazon embedding retry options (#12193)
    
    Signed-off-by: Goutam Adwant <wo...@gmail.com>
---
 .../introduction/concepts/incompatible-changes.md  |   5 +
 docs/en/transforms/embedding.md                    |   7 +-
 .../introduction/concepts/incompatible-changes.md  |   5 +
 docs/zh/transforms/embedding.md                    |   6 +-
 .../nlpmodel/embedding/EmbeddingTransform.java     |  22 +-
 .../embedding/AmazonEmbeddingInvocationTest.java   | 314 +++++++++++++++++++++
 6 files changed, 348 insertions(+), 11 deletions(-)

diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md
index 79ce8ea56c..42ae00db16 100644
--- a/docs/en/introduction/concepts/incompatible-changes.md
+++ b/docs/en/introduction/concepts/incompatible-changes.md
@@ -186,6 +186,11 @@ You need to check this document before you upgrade to related version.
 
 ### Transform Changes
 
+- **Behavior change: AMAZON embedding honors retry options**
+  - **Affected component**: `Embedding` transform with `model_provider = AMAZON`.
+  - **Description**: Configured SeaTunnel retry and backoff options now reach the Bedrock runtime. Previously, the transform ignored these settings and used one SeaTunnel attempt.
+  - **Impact and migration**: Configured `model_retry_max_attempts` values greater than 1 now enable SeaTunnel retries, which may incur additional model charges; use 1 to retain a single SeaTunnel attempt. The default remains 1. The SDK's own retry and timeout behavior is unchanged; `model_request_timeout_ms` is not currently applied to Bedrock calls.
+
 - **[BREAKING]** SQL Transform `PARSEDATETIME`, `TO_DATE`, and `IS_DATE` functions now only accept whitelisted datetime format patterns. Custom format patterns that were previously accepted will now fail at runtime. The supported patterns are:
   - DateTime: `yyyy-MM-dd HH:mm:ss`, `yyyy-MM-dd HH:mm:ss.SSS`, `yyyy-MM-dd'T'HH:mm:ss`, `yyyy-MM-dd'T'HH:mm:ss.SSS`, `yyyy/MM/dd HH:mm:ss`, `yyyy/MM/dd HH:mm:ss.SSS`, `yyyyMMddHHmmss`
   - Date: `yyyy-MM-dd`, `yyyy/MM/dd`, `yyyyMMdd`
diff --git a/docs/en/transforms/embedding.md b/docs/en/transforms/embedding.md
index 6823332d4e..6060d1be28 100644
--- a/docs/en/transforms/embedding.md
+++ b/docs/en/transforms/embedding.md
@@ -85,9 +85,14 @@ The runtime records safe diagnostic context such as provider, model, batch size,
 retryable flag, and elapsed time. It does not log API keys, secret keys, full source text chunks, binary payloads, or full
 provider response bodies.
 
-Bedrock now uses the same common runtime path as the other embedding providers, so retry, timeout, response parsing,
+Bedrock uses the same common runtime path as the other embedding providers, so retry, response parsing,
 and response-count validation behave consistently across providers.
 
+For `AMAZON`, `model_retry_max_attempts` counts SeaTunnel attempts. The AWS SDK can perform its own HTTP retries within
+each attempt; its retry policy is unchanged. Configured retry and backoff options now reach the Bedrock runtime instead
+of being ignored by the transform. The default remains one SeaTunnel attempt. `model_request_timeout_ms` is not currently
+applied to Bedrock SDK calls; this change preserves the existing SDK timeout behavior.
+
 The runtime also has a cache boundary. When a cache implementation is wired in, keys are built from provider, model,
 output configuration, modality, format, normalized metadata, and a SHA-256 digest of normalized input content. The
 default production wiring still uses `ModelInvocationCache.NOOP`, so existing jobs keep the previous behavior unless an
diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md
index 9e16201b6f..d653c20908 100644
--- a/docs/zh/introduction/concepts/incompatible-changes.md
+++ b/docs/zh/introduction/concepts/incompatible-changes.md
@@ -170,6 +170,11 @@
 
 ### 转换变更
 
+- **行为变更:AMAZON 向量化遵循重试选项**
+  - **影响范围**:配置 `model_provider = AMAZON` 的 `Embedding` 转换。
+  - **变更说明**:配置的 SeaTunnel 重试和退避选项现在会传递到 Bedrock 运行时。此前 Transform 忽略这些设置,只执行一次 SeaTunnel 尝试。
+  - **影响及迁移**:大于 1 的 `model_retry_max_attempts` 现在会启用 SeaTunnel 重试,可能产生额外模型费用;设置为 1 可保留单次 SeaTunnel 尝试,默认值仍为 1。SDK 自身的重试和超时行为保持不变;`model_request_timeout_ms` 目前不应用于 Bedrock 调用。
+
 - **[BREAKING]** SQL Transform 的 `PARSEDATETIME`、`TO_DATE` 和 `IS_DATE` 函数现在只接受白名单中的日期时间格式模式。以前接受的自定义格式模式现在将在运行时失败。支持的模式有:
   - DateTime: `yyyy-MM-dd HH:mm:ss`, `yyyy-MM-dd HH:mm:ss.SSS`, `yyyy-MM-dd'T'HH:mm:ss`, `yyyy-MM-dd'T'HH:mm:ss.SSS`, `yyyy/MM/dd HH:mm:ss`, `yyyy/MM/dd HH:mm:ss.SSS`, `yyyyMMddHHmmss`
   - Date: `yyyy-MM-dd`, `yyyy/MM/dd`, `yyyyMMdd`
diff --git a/docs/zh/transforms/embedding.md b/docs/zh/transforms/embedding.md
index e80f96a575..e078682c41 100644
--- a/docs/zh/transforms/embedding.md
+++ b/docs/zh/transforms/embedding.md
@@ -75,7 +75,11 @@ provider 侧副作用。该配置不会改变下游 Sink 的幂等语义。
 运行时会记录 provider、model、batch size、attempt number、error category、retryable flag、elapsed time 等安全诊断上下文。
 日志不会记录 API key、secret key、完整源文本 chunk、二进制 payload 或完整 provider response body。
 
-Bedrock 现在也走统一的 common runtime 路径,因此 retry、timeout、响应解析和返回数量校验在各个 provider 之间保持一致。
+Bedrock 也走统一的 common runtime 路径,因此 retry、响应解析和返回数量校验在各个 provider 之间保持一致。
+
+对于 `AMAZON`,`model_retry_max_attempts` 统计 SeaTunnel 层的尝试次数。AWS SDK 在每次尝试内部仍可能执行 HTTP 重试,
+SDK 的重试策略保持不变。配置的重试和退避选项现在会传递到 Bedrock 运行时,而不再被 Transform 忽略。
+默认仍只执行一次 SeaTunnel 尝试。`model_request_timeout_ms` 目前不应用于 Bedrock SDK 调用;本次修改保留现有的 SDK 超时行为。
 
 运行时也提供了一个 cache 边界。当接入 cache 实现时,key 由 provider、model、输出配置、modality、format、规范化后的 metadata,
 以及规范化输入内容的 SHA-256 摘要组成。默认的生产 wiring 仍然使用 `ModelInvocationCache.NOOP`,因此在接入层显式启用缓存之前,
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/EmbeddingTransform.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/EmbeddingTransform.java
index bcf09b67bb..4d65ce742f 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/EmbeddingTransform.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/nlpmodel/embedding/EmbeddingTransform.java
@@ -173,17 +173,21 @@ public class EmbeddingTransform extends MultipleFieldOutputTransform {
                                     invocationOptions);
                     break;
                 case AMAZON:
+                    String bedrockModelId = config.get(ModelTransformConfig.MODEL);
+                    int bedrockDimension = config.get(ModelTransformConfig.DIMENSION);
+                    int bedrockBatchSize =
+                            config.get(EmbeddingTransformConfig.SINGLE_VECTORIZED_INPUT_NUMBER);
                     model =
                             new BedrockModel(
-                                    config.get(ModelTransformConfig.API_KEY),
-                                    config.get(ModelTransformConfig.SECRET_KEY),
-                                    config.get(ModelTransformConfig.AWS_REGION),
-                                    config.get(ModelTransformConfig.API_PATH),
-                                    config.get(ModelTransformConfig.MODEL),
-                                    config.get(ModelTransformConfig.DIMENSION),
-                                    config.get(
-                                            EmbeddingTransformConfig
-                                                    .SINGLE_VECTORIZED_INPUT_NUMBER));
+                                    BedrockModel.createBedrockClient(
+                                            config.get(ModelTransformConfig.API_KEY),
+                                            config.get(ModelTransformConfig.SECRET_KEY),
+                                            config.get(ModelTransformConfig.AWS_REGION),
+                                            config.get(ModelTransformConfig.API_PATH)),
+                                    bedrockModelId,
+                                    bedrockDimension,
+                                    bedrockBatchSize,
+                                    invocationOptions);
                     break;
                 case LOCAL:
                 default:
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/AmazonEmbeddingInvocationTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/AmazonEmbeddingInvocationTest.java
new file mode 100644
index 0000000000..da3f8a65a3
--- /dev/null
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/embedding/AmazonEmbeddingInvocationTest.java
@@ -0,0 +1,314 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.transform.embedding;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.common.utils.VectorUtils;
+import org.apache.seatunnel.transform.nlpmodel.ModelInvocationErrorType;
+import org.apache.seatunnel.transform.nlpmodel.ModelInvocationException;
+import org.apache.seatunnel.transform.nlpmodel.embedding.EmbeddingTransform;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import okhttp3.mockwebserver.Dispatcher;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
+import okhttp3.mockwebserver.SocketPolicy;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@Timeout(60)
+class AmazonEmbeddingInvocationTest {
+
+    @Test
+    void shouldReadBatchSizeBeforeConstructingClient() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            Map<String, Object> overrides = new HashMap<>();
+            overrides.put("single_vectorized_input_number", "not-a-number");
+            // Invalid endpoint parsing must not precede the existing configuration failure.
+            overrides.put("api_path", "not a URI");
+            EmbeddingTransform transform = transform(server, 3, null, overrides);
+            try {
+                IllegalArgumentException failure =
+                        assertThrows(
+                                IllegalArgumentException.class, transform::getProducedCatalogTable);
+                assertTrue(failure.getMessage().contains("not-a-number"));
+                assertEquals(0, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldApplyConfiguredRetriesThroughTransform() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            // HTTP 424 is retried by SeaTunnel's adapter, not the SDK's default HTTP retry policy.
+            server.enqueue(modelError());
+            server.enqueue(modelError());
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, 3, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                assertVector(transform.map(row()));
+                assertEquals(3, server.getRequestCount());
+                String payload = request(server).getBody().readUtf8();
+                assertEquals(payload, request(server).getBody().readUtf8());
+                assertEquals(payload, request(server).getBody().readUtf8());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldKeepSingleSeaTunnelAttemptByDefault() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            server.enqueue(modelError());
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, null, null);
+            try {
+                transform.getProducedCatalogTable();
+                ModelInvocationException failure = failure(transform);
+                assertEquals(
+                        ModelInvocationErrorType.TEMPORARY_REMOTE_ERROR, failure.getErrorType());
+                assertTrue(failure.isRetryable());
+                assertEquals(1, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldStopAfterConfiguredAttempts() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            server.enqueue(modelError());
+            server.enqueue(modelError());
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, 2, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                ModelInvocationException failure = failure(transform);
+                assertEquals(
+                        ModelInvocationErrorType.TEMPORARY_REMOTE_ERROR, failure.getErrorType());
+                assertEquals(2, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldNotRetryAuthenticationFailure() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            server.enqueue(
+                    error(
+                            403,
+                            "AccessDeniedException",
+                            "api_key=private-api secret_key=private-secret"));
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, 3, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                ModelInvocationException failure = failure(transform);
+                assertEquals(ModelInvocationErrorType.AUTHENTICATION_ERROR, failure.getErrorType());
+                assertFalse(failure.isRetryable());
+                assertFalse(failure.getMessage().contains("private-api"));
+                assertFalse(failure.getMessage().contains("private-secret"));
+                assertEquals(1, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldNotRetryMissingVector() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            server.enqueue(new MockResponse().setBody("{}"));
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, 3, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                ModelInvocationException failure = failure(transform);
+                assertEquals(
+                        ModelInvocationErrorType.RESPONSE_COUNT_MISMATCH, failure.getErrorType());
+                assertFalse(failure.isRetryable());
+                assertEquals(1, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldNotRetryMalformedResponse() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            server.enqueue(new MockResponse().setBody("not-json"));
+            server.enqueue(success());
+            EmbeddingTransform transform = transform(server, 3, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                ModelInvocationException failure = failure(transform);
+                assertEquals(ModelInvocationErrorType.RESPONSE_PARSE_ERROR, failure.getErrorType());
+                assertFalse(failure.isRetryable());
+                assertEquals(1, server.getRequestCount());
+            } finally {
+                transform.close();
+            }
+        }
+    }
+
+    @Test
+    void shouldPreserveExternalInterruptionWithoutAnotherHttpRequest() throws Exception {
+        try (MockWebServer server = new MockWebServer()) {
+            Thread caller = Thread.currentThread();
+            AtomicBoolean interruptFirstRequest = new AtomicBoolean(true);
+            server.setDispatcher(
+                    new Dispatcher() {
+                        @Override
+                        public MockResponse dispatch(RecordedRequest request) {
+                            if (interruptFirstRequest.compareAndSet(true, false)) {
+                                caller.interrupt();
+                            }
+                            return new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE);
+                        }
+                    });
+            EmbeddingTransform transform = transform(server, 3, 5000);
+            try {
+                transform.getProducedCatalogTable();
+                failure(transform);
+                assertTrue(
+                        Thread.currentThread().isInterrupted(),
+                        "External interrupt was cleared; observed HTTP requests: "
+                                + server.getRequestCount());
+                assertEquals(1, server.getRequestCount());
+            } finally {
+                // Clear only the test-owned interrupt before client/server teardown.
+                Thread.interrupted();
+                transform.close();
+            }
+        }
+    }
+
+    private static EmbeddingTransform transform(
+            MockWebServer server, Integer attempts, Integer timeout) {
+        return transform(server, attempts, timeout, Collections.emptyMap());
+    }
+
+    private static EmbeddingTransform transform(
+            MockWebServer server,
+            Integer attempts,
+            Integer timeout,
+            Map<String, Object> overrides) {
+        Map<String, Object> options = new HashMap<>();
+        options.put("model_provider", "AMAZON");
+        options.put("model", "amazon.titan-embed-text-v2:0");
+        options.put("aws_region", "us-east-1");
+        options.put("api_key", "test-access-key");
+        options.put("secret_key", "test-secret-key");
+        options.put("api_path", server.url("/").toString());
+        options.put("dimension", 2);
+        options.put("vectorization_fields", Collections.singletonMap("vector", "text"));
+        options.put("model_retry_backoff_ms", 0);
+        options.put("model_retry_max_backoff_ms", 0);
+        if (attempts != null) {
+            options.put("model_retry_max_attempts", attempts);
+        }
+        if (timeout != null) {
+            options.put("model_request_timeout_ms", timeout);
+        }
+        options.putAll(overrides);
+        CatalogTable table =
+                CatalogTable.of(
+                        TableIdentifier.of("catalog", "database", "documents"),
+                        TableSchema.builder()
+                                .column(
+                                        PhysicalColumn.of(
+                                                "text",
+                                                BasicType.STRING_TYPE,
+                                                1024L,
+                                                true,
+                                                null,
+                                                ""))
+                                .build(),
+                        Collections.emptyMap(),
+                        Collections.emptyList(),
+                        "");
+        return new EmbeddingTransform(ReadonlyConfig.fromMap(options), table);
+    }
+
+    private static SeaTunnelRow row() {
+        return new SeaTunnelRow(new Object[] {"test document"});
+    }
+
+    private static void assertVector(SeaTunnelRow row) {
+        assertEquals("test document", row.getField(0));
+        assertEquals(
+                VectorUtils.toByteBuffer(new Float[] {0.25F, 0.5F}), (ByteBuffer) row.getField(1));
+    }
+
+    private static ModelInvocationException failure(EmbeddingTransform transform) {
+        RuntimeException failure = assertThrows(RuntimeException.class, () -> transform.map(row()));
+        assertEquals("Failed to data vectorization", failure.getMessage());
+        assertTrue(failure.getCause() instanceof ModelInvocationException);
+        return (ModelInvocationException) failure.getCause();
+    }
+
+    private static MockResponse success() {
+        return new MockResponse().setBody("{\"embedding\":[0.25,0.5]}");
+    }
+
+    private static MockResponse modelError() {
+        return error(424, "ModelErrorException", "Temporary model failure");
+    }
+
+    private static MockResponse error(int status, String type, String message) {
+        return new MockResponse()
+                .setResponseCode(status)
+                .setHeader("Content-Type", "application/json")
+                .setHeader("x-amzn-errortype", type)
+                .setBody("{\"message\":\"" + message + "\"}");
+    }
+
+    private static RecordedRequest request(MockWebServer server) throws InterruptedException {
+        RecordedRequest request = server.takeRequest(5, TimeUnit.SECONDS);
+        assertNotNull(request);
+        return request;
+    }
+}