From 35a962f7b379300f06035c804c0cb707c4a90d5b Mon Sep 17 00:00:00 2001 From: Mohit Yadav <105265192+mohityadav766@users.noreply.github.com> Date: Mon, 13 Jul 2026 16:32:05 +0530 Subject: [PATCH] Fixes #4930: cap Titan Bedrock embedding input to avoid ValidationException (#29920) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backport of #29920 to 1.13. Titan text-embedding models accept at most 8192 input tokens and expose no request-side truncate directive, so oversized chunks were rejected by Bedrock with a ValidationException. Cap the input at 16384 chars up front, and on a token-limit ValidationException halve the (already capped) input and retry — a content-agnostic guarantee the char cap alone cannot provide for token-dense scripts (CJK, emoji). Adapted from the original: 1.13's BedrockEmbeddingClient predates the embedding-family refactor (Cohere support, doEmbedQuery, per-family request builders), so the fix is applied to the Titan-only shape that exists here. The family/Cohere portions of the upstream change and its tests are omitted. (cherry picked from commit 86909c4efa93a1615188b9e519fec72fd8599ed6) Co-Authored-By: Claude Opus 4.8 (1M context) --- .../vector/client/BedrockEmbeddingClient.java | 126 +++++++++++++---- .../client/BedrockEmbeddingClientTest.java | 129 ++++++++++++++++++ 2 files changed, 230 insertions(+), 25 deletions(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClientTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClient.java index ef9a8315f973..3784d04e257d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClient.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; +import java.util.Locale; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.openmetadata.schema.security.credentials.AWSBaseConfig; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; import org.openmetadata.schema.service.configuration.elasticsearch.NaturalLanguageSearchConfiguration; @@ -16,11 +18,31 @@ import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse; +import software.amazon.awssdk.services.bedrockruntime.model.ValidationException; @Slf4j public final class BedrockEmbeddingClient extends EmbeddingClient implements AutoCloseable { private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String FIELD_INPUT_TEXT = "inputText"; + private static final String FIELD_DIMENSIONS = "dimensions"; + private static final String FIELD_EMBEDDING = "embedding"; + + // Titan text-embedding models accept at most 8192 input tokens and expose no request-side + // truncate directive, so oversized text throws a ValidationException (issue #4930). Capping at + // 16384 chars keeps even token-dense input (~2 chars/token worst case) under the limit while + // staying well above the 380-word chunk bound, so normal text is never truncated. + // ponytail: char/token ratio is empirical — lower this knob if a denser corpus still overflows. + private static final int TITAN_MAX_INPUT_CHARS = 16384; + + // The char cap is a fast-path that keeps typical English input to a single call; token-dense + // scripts (CJK, emoji) where chars approx tokens can still exceed it. AWS lumps token overflow + // under a generic ValidationException with no machine-readable code, so detection matches the + // message marker; the amount, though, we don't parse — we cap the input up front and then halve + // the *capped* value on each retry, so halving converges within these retries. + private static final int MAX_TOKEN_LIMIT_RETRIES = 3; + private static final String TOKEN_LIMIT_ERROR_MARKER = "input token"; + private final BedrockRuntimeClient bedrockClient; private final String modelId; private final int dimension; @@ -61,36 +83,90 @@ public BedrockEmbeddingClient(ElasticSearchConfiguration config) { awsConfig.getRegion()); } + BedrockEmbeddingClient(BedrockRuntimeClient bedrockClient, String modelId, int dimension) { + super(1); + this.bedrockClient = bedrockClient; + this.modelId = modelId; + this.dimension = dimension; + } + @Override protected float[] doEmbed(String text) { - try { - ObjectNode payload = MAPPER.createObjectNode(); - payload.put("inputText", text); - payload.put("dimensions", dimension); - String body = MAPPER.writeValueAsString(payload); - - InvokeModelRequest request = - InvokeModelRequest.builder() - .modelId(modelId) - .contentType("application/json") - .accept("application/json") - .body(SdkBytes.fromUtf8String(body)) - .build(); - - InvokeModelResponse response = bedrockClient.invokeModel(request); - return parseEmbeddingResponse(response.body().asUtf8String()); - } catch (AwsServiceException e) { + String input = cap(text); + float[] embedding = null; + int attempt = 0; + while (embedding == null) { + try { + embedding = invokeOnce(input); + } catch (AwsServiceException e) { + requireRetryable(e, attempt++); + input = halveInput(input); + LOG.warn("Bedrock rejected oversized input; retrying at {} chars", input.length()); + } catch (SdkClientException e) { + LOG.error("SDK client error calling Bedrock: {}", e.getMessage(), e); + throw new RuntimeException("Bedrock embedding generation failed (SDK client error)", e); + } catch (IOException e) { + LOG.error("IO error calling Bedrock: {}", e.getMessage(), e); + throw new RuntimeException("Bedrock embedding generation failed (IO error)", e); + } + } + return embedding; + } + + private float[] invokeOnce(String text) throws IOException { + String body = buildRequestBody(text, dimension); + InvokeModelRequest request = + InvokeModelRequest.builder() + .modelId(modelId) + .contentType("application/json") + .accept("application/json") + .body(SdkBytes.fromUtf8String(body)) + .build(); + InvokeModelResponse response = bedrockClient.invokeModel(request); + return parseEmbeddingResponse(response.body().asUtf8String()); + } + + /** + * Rethrow unless the call is worth retrying: only a token-limit {@link ValidationException} within + * the retry budget is, since halving the input is the only thing that can help it. Everything else + * (throttling, auth, non-token validation) is surfaced immediately. The input is already capped to + * {@link #TITAN_MAX_INPUT_CHARS} up front, so halving quickly converges below the token limit even + * for token-dense scripts (CJK, emoji) that the char cap alone can't bound. + */ + private void requireRetryable(AwsServiceException e, int attempt) { + boolean retryable = attempt < MAX_TOKEN_LIMIT_RETRIES && isTokenLimitError(e); + if (!retryable) { LOG.error("AWS service error calling Bedrock: {}", e.getMessage(), e); throw new RuntimeException("Bedrock embedding generation failed (AWS service error)", e); - } catch (SdkClientException e) { - LOG.error("SDK client error calling Bedrock: {}", e.getMessage(), e); - throw new RuntimeException("Bedrock embedding generation failed (SDK client error)", e); - } catch (IOException e) { - LOG.error("IO error calling Bedrock: {}", e.getMessage(), e); - throw new RuntimeException("Bedrock embedding generation failed (IO error)", e); } } + private static boolean isTokenLimitError(AwsServiceException e) { + String message = e.getMessage(); + return e instanceof ValidationException + && message != null + && message.toLowerCase(Locale.ROOT).contains(TOKEN_LIMIT_ERROR_MARKER); + } + + static String cap(String text) { + return StringUtils.truncate(text, TITAN_MAX_INPUT_CHARS); + } + + static String halveInput(String input) { + int cut = input.length() / 2; + if (cut > 0 && Character.isHighSurrogate(input.charAt(cut - 1))) { + cut--; + } + return input.substring(0, cut); + } + + static String buildRequestBody(String text, int dimension) throws IOException { + ObjectNode payload = MAPPER.createObjectNode(); + payload.put(FIELD_INPUT_TEXT, text); + payload.put(FIELD_DIMENSIONS, dimension); + return MAPPER.writeValueAsString(payload); + } + @Override public int getDimension() { return dimension; @@ -108,10 +184,10 @@ public void close() { } } - private float[] parseEmbeddingResponse(String responseBody) { + static float[] parseEmbeddingResponse(String responseBody) { try { JsonNode root = MAPPER.readTree(responseBody); - JsonNode embeddingNode = root.get("embedding"); + JsonNode embeddingNode = root.get(FIELD_EMBEDDING); if (embeddingNode == null || !embeddingNode.isArray()) { throw new RuntimeException("Invalid Bedrock response: no embedding array found"); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClientTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClientTest.java new file mode 100644 index 000000000000..81a09708b087 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/client/BedrockEmbeddingClientTest.java @@ -0,0 +1,129 @@ +package org.openmetadata.service.search.vector.client; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; +import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest; +import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse; +import software.amazon.awssdk.services.bedrockruntime.model.ValidationException; + +class BedrockEmbeddingClientTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final float DELTA = 1e-6f; + + @Test + void titanCapsOversizedInputToStayUnderTokenLimit() throws Exception { + JsonNode payload = buildPayload("x".repeat(20000), 512); + + assertEquals(16384, payload.get("inputText").asText().length()); + } + + @Test + void titanLeavesInputWithinLimitUntouched() throws Exception { + JsonNode payload = buildPayload("short text", 512); + + assertEquals("short text", payload.get("inputText").asText()); + assertEquals(512, payload.get("dimensions").asInt()); + } + + @Test + void halvesOversizedInputForRetry() { + String input = "x".repeat(16384); + + String shorter = BedrockEmbeddingClient.halveInput(input); + + assertEquals(8192, shorter.length()); + } + + @Test + void halveInputHandlesShortAndEmptyWithoutThrowing() { + assertEquals("a", BedrockEmbeddingClient.halveInput("ab")); + assertEquals("", BedrockEmbeddingClient.halveInput("a")); + assertEquals("", BedrockEmbeddingClient.halveInput("")); + } + + @Test + void halveInputNeverSplitsASurrogatePair() { + String emojis = "😀".repeat(3); + + String shorter = BedrockEmbeddingClient.halveInput(emojis); + + assertEquals("😀", shorter); + } + + @Test + void tokenLimitErrorTriggersHalvedRetryThenSucceeds() { + BedrockRuntimeClient mockClient = mock(BedrockRuntimeClient.class); + when(mockClient.invokeModel(any(InvokeModelRequest.class))) + .thenThrow(tokenLimitException()) + .thenReturn(titanResponse()); + BedrockEmbeddingClient client = titanClient(mockClient); + + float[] result = client.embed("x".repeat(30000)); + + assertArrayEquals(new float[] {0.1f, 0.2f}, result, DELTA); + verify(mockClient, times(2)).invokeModel(any(InvokeModelRequest.class)); + } + + @Test + void nonTokenValidationErrorRethrowsWithoutRetry() { + BedrockRuntimeClient mockClient = mock(BedrockRuntimeClient.class); + when(mockClient.invokeModel(any(InvokeModelRequest.class))) + .thenThrow(ValidationException.builder().message("Malformed input request").build()); + BedrockEmbeddingClient client = titanClient(mockClient); + + assertThrows(RuntimeException.class, () -> client.embed("hello")); + verify(mockClient, times(1)).invokeModel(any(InvokeModelRequest.class)); + } + + @Test + void persistentTokenLimitErrorExhaustsRetriesThenThrows() { + BedrockRuntimeClient mockClient = mock(BedrockRuntimeClient.class); + when(mockClient.invokeModel(any(InvokeModelRequest.class))).thenThrow(tokenLimitException()); + BedrockEmbeddingClient client = titanClient(mockClient); + + assertThrows(RuntimeException.class, () -> client.embed("hello")); + verify(mockClient, times(4)).invokeModel(any(InvokeModelRequest.class)); + } + + @Test + void parseTitanResponse() { + float[] embedding = + BedrockEmbeddingClient.parseEmbeddingResponse( + "{\"embedding\":[0.6,0.7],\"inputTextTokenCount\":2}"); + + assertArrayEquals(new float[] {0.6f, 0.7f}, embedding, DELTA); + } + + private static BedrockEmbeddingClient titanClient(BedrockRuntimeClient mockClient) { + return new BedrockEmbeddingClient(mockClient, "amazon.titan-embed-text-v2:0", 512); + } + + private static ValidationException tokenLimitException() { + return ValidationException.builder() + .message("Too many input tokens. Max input tokens: 8192, request input token count: 18338") + .build(); + } + + private static InvokeModelResponse titanResponse() { + return InvokeModelResponse.builder() + .body(SdkBytes.fromUtf8String("{\"embedding\":[0.1,0.2]}")) + .build(); + } + + private static JsonNode buildPayload(String text, int dimension) throws Exception { + return MAPPER.readTree( + BedrockEmbeddingClient.buildRequestBody(BedrockEmbeddingClient.cap(text), dimension)); + } +}