Repository navigation
Fixes #4930: cap Titan Bedrock embedding input to avoid ValidationException (#29920) #30021
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+151
to
+153
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When oversized text has an emoji or other non-BMP character across the 16384-char boundary,
Suggested change
Context Used: CLAUDE.md (source)
Comment on lines
+151
to
+153
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If a caller passes
Suggested change
Context Used: CLAUDE.md (source) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 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"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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)); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Edge Case: cap() can split a surrogate pair at the 16384-char boundary
cap()usesStringUtils.truncate(text, 16384)which does a plainsubstring; if a high surrogate lands at index 16383, the pair is split and a lone surrogate is sent ininputText. The PR carefully guards against this inhalveInputbut not incap, so the emoji/CJK safety claim doesn't hold for the initial cap. Impact is low (lone surrogate at an exact boundary, serialized as an invalid escape), but for consistency trim a trailing high surrogate after truncation, e.g.String out = StringUtils.truncate(text, TITAN_MAX_INPUT_CHARS); if (!out.isEmpty() && Character.isHighSurrogate(out.charAt(out.length()-1))) out = out.substring(0, out.length()-1); return out;.Was this helpful? React with 👍 / 👎