From a1de0ee9056d72388da6dda01b779b0df3c052e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Wed, 18 Nov 2026 10:02:15 +0900 Subject: [PATCH] fix(dynamodb): order items tied on an index key by their key hash (#8798) A Query or a PartiQL read of a secondary index returned items tied on the index key in table-key order, while DynamoDB returns them in the order of a hash of the table key: MD5 over the bytes "Outliers" followed by the key bytes. A local secondary index hashes the table sort key alone and a global secondary index the partition key followed by the sort key. A string hashes as its UTF-8 bytes, a binary value as its own bytes and a number in the layout of an Oracle NUMBER. A descending read reverses that order, and the table key still settles a tie of the hash, so ExclusiveStartKey and the end of a page follow the same order. --- .../services/dynamodb/DynamoDbKeyHash.java | 100 +++++++++ .../services/dynamodb/DynamoDbService.java | 10 +- .../DynamoDbIndexTieOrderIntegrationTest.java | 197 ++++++++++++++++++ 3 files changed, 304 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java create mode 100644 src/test/java/io/floci/aws/services/dynamodb/DynamoDbIndexTieOrderIntegrationTest.java diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java new file mode 100644 index 0000000000..985a42fcd5 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbKeyHash.java @@ -0,0 +1,100 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.Digests; +import io.floci.aws.services.dynamodb.model.TableDefinition; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +/** The hash DynamoDB places and orders keys by: MD5 over "Outliers" and the bytes of the key values. */ +final class DynamoDbKeyHash { + + private static final byte[] SALT = "Outliers".getBytes(StandardCharsets.US_ASCII); + private static final int TERMINATED_BELOW_PAIRS = 20; + + private DynamoDbKeyHash() { + } + + /** + * Orders items tied on an index key. DynamoDB hashes the table sort key alone on an LSI, whose + * items share the partition key, and the partition key followed by the sort key on a GSI. + */ + static Comparator indexTieOrder(TableDefinition table, DynamoDbAccessPath accessPath) { + List hashed = new ArrayList<>(); + if (accessPath.isGlobalSecondaryIndex()) { + hashed.add(table.getPartitionKeyName()); + } + if (table.getSortKeyName() != null) { + hashed.add(table.getSortKeyName()); + } + Map hashes = new IdentityHashMap<>(); + return Comparator.comparing(item -> hashes.computeIfAbsent(item, ignored -> of(item, hashed)), + Arrays::compareUnsigned); + } + + static byte[] of(JsonNode item, List keyNames) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + bytes.writeBytes(SALT); + for (String name : keyNames) { + JsonNode value = item.get(name); + if (value != null) { + bytes.writeBytes(bytesOf(value)); + } + } + return Digests.md5(bytes.toByteArray()); + } + + private static byte[] bytesOf(JsonNode value) { + if (value.has("S")) { + return value.get("S").asText().getBytes(StandardCharsets.UTF_8); + } + if (value.has("B")) { + return Base64.getDecoder().decode(value.get("B").asText()); + } + if (value.has("N")) { + return numberBytes(new BigDecimal(value.get("N").asText())); + } + return new byte[0]; + } + + // A number is hashed in the layout of an Oracle NUMBER: an exponent byte, then two decimal digits + // per byte. A negative number inverts both and ends with 102 when it has fewer than 20 digit bytes. + static byte[] numberBytes(BigDecimal number) { + if (number.signum() == 0) { + return new byte[] {(byte) 0x80}; + } + boolean negative = number.signum() < 0; + BigDecimal magnitude = number.abs().stripTrailingZeros(); + String digits = magnitude.unscaledValue().toString(); + int digitsBeforePoint = digits.length() - magnitude.scale(); + if (Math.floorMod(digitsBeforePoint, 2) != 0) { + digits = "0" + digits; + digitsBeforePoint++; + } + if (digits.length() % 2 != 0) { + digits = digits + "0"; + } + int pairs = digits.length() / 2; + boolean terminated = negative && pairs < TERMINATED_BELOW_PAIRS; + byte[] bytes = new byte[1 + pairs + (terminated ? 1 : 0)]; + int exponent = digitsBeforePoint / 2 - 64; + bytes[0] = (byte) (negative ? ~exponent : exponent); + for (int i = 0; i < pairs; i++) { + int pair = Integer.parseInt(digits, 2 * i, 2 * i + 2, 10); + bytes[1 + i] = (byte) (negative ? 101 - pair : pair + 1); + } + if (terminated) { + bytes[bytes.length - 1] = 102; + } + return bytes; + } +} diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java index 00de3a0b7a..14f67ed8d9 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -1651,8 +1651,8 @@ public class DynamoDbService { } // Order by the full (possibly composite) sort key, comparing each attribute in key-schema - // order (floci-io/floci#1675), then, on an index, by the table key, which is what - // tells apart items whose index keys tie. + // order (floci-io/floci#1675). On an index, items whose index keys tie follow the hash of + // their table key, and the table key itself settles a tie of that hash. List orderKeyNames = new ArrayList<>(sortKeyNames); if (accessPath.isIndex()) { orderKeyNames.add(table.getPartitionKeyName()); @@ -1660,7 +1660,11 @@ public class DynamoDbService { orderKeyNames.add(table.getSortKeyName()); } } - Comparator keyOrder = (a, b) -> compareKeyAttributes(a, b, orderKeyNames); + Comparator sortKeyOrder = (a, b) -> compareKeyAttributes(a, b, sortKeyNames); + Comparator keyOrder = accessPath.isIndex() + ? sortKeyOrder.thenComparing(DynamoDbKeyHash.indexTieOrder(table, accessPath)) + .thenComparing((a, b) -> compareKeyAttributes(a, b, orderKeyNames)) + : sortKeyOrder; int direction = Boolean.FALSE.equals(scanIndexForward) ? -1 : 1; if (!orderKeyNames.isEmpty()) { results = new ArrayList<>(results); diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIndexTieOrderIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIndexTieOrderIntegrationTest.java new file mode 100644 index 0000000000..5e7f788e50 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbIndexTieOrderIntegrationTest.java @@ -0,0 +1,197 @@ +package io.floci.aws.services.dynamodb; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.BillingMode; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; +import software.amazon.awssdk.services.dynamodb.model.Projection; +import software.amazon.awssdk.services.dynamodb.model.ProjectionType; +import software.amazon.awssdk.services.dynamodb.model.QueryRequest; +import software.amazon.awssdk.services.dynamodb.model.QueryResponse; +import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class DynamoDbIndexTieOrderIntegrationTest { + + private static final List NUMBERS = List.of("-1", "7", "0", "0.5", "-0.5", "100", "-1.5", "1E-130", + "-1E+125", "9.9999999999999999999999999999999999999E+125", "-12345678901234567890123456789012345678", + "1234567890123456789012345678901234567.8"); + private static final List NUMBERS_IN_HASH_ORDER = List.of("-1", "7", + "-12345678901234567890123456789012345678", "9.9999999999999999999999999999999999999E+125", "100", "1E-130", + "-1E+125", "-1.5", "0.5", "-0.5", "1234567890123456789012345678901234567.8", "0"); + + @Test + void queryReturnsIndexTiesInTheOrderOfTheirTableKeyHash() { + try (DynamoDbClient client = client()) { + String table = createTable(client, ScalarAttributeType.S, ScalarAttributeType.S); + for (String sk : List.of("row-d", "row-f", "row-a", "row-c", "row-e", "row-b")) { + client.putItem(r -> r.tableName(table) + .item(Map.of("pk", text("tie"), "sk", text(sk), "l", text("t"), "g", text("tie")))); + } + List lsi = List.of("row-b", "row-a", "row-c", "row-f", "row-d", "row-e"); + List gsi = List.of("row-a", "row-f", "row-b", "row-e", "row-d", "row-c"); + Function sortKey = AttributeValue::s; + + assertEquals(lsi, query(client, table, "l-all", "pk", text("tie"), true, null, "sk", sortKey)); + assertEquals(lsi.reversed(), query(client, table, "l-all", "pk", text("tie"), false, null, "sk", sortKey)); + assertEquals(gsi, query(client, table, "g-all", "g", text("tie"), true, null, "sk", sortKey)); + assertEquals(gsi.reversed(), query(client, table, "g-all", "g", text("tie"), false, null, "sk", sortKey)); + assertEquals(lsi, query(client, table, "l-all", "pk", text("tie"), true, 1, "sk", sortKey)); + assertEquals(gsi.reversed(), query(client, table, "g-all", "g", text("tie"), false, 2, "sk", sortKey)); + assertEquals(lsi, client.executeStatement(r -> r.statement( + "SELECT sk FROM \"" + table + "\".\"l-all\" WHERE pk = 'tie' AND l = 't'")) + .items().stream().map(item -> item.get("sk").s()).toList()); + } + } + + @Test + void queryOrdersTiedNumberKeysByTheHashOfTheirDigits() { + try (DynamoDbClient client = client()) { + String table = createTable(client, ScalarAttributeType.S, ScalarAttributeType.N); + for (String number : NUMBERS) { + client.putItem(r -> r.tableName(table) + .item(Map.of("pk", text("tie"), "sk", number(number), "l", text("t"), "g", text("g")))); + } + Function sortKey = value -> plain(value.n()); + + assertEquals(plain(NUMBERS_IN_HASH_ORDER), + query(client, table, "l-all", "pk", text("tie"), true, null, "sk", sortKey)); + assertEquals(plain(List.of("100", "-0.5", "-1", "7", "-12345678901234567890123456789012345678", "0.5", + "9.9999999999999999999999999999999999999E+125", "0", "1E-130", + "1234567890123456789012345678901234567.8", "-1E+125", "-1.5")), + query(client, table, "g-all", "g", text("g"), true, null, "sk", sortKey)); + } + } + + @Test + void queryOrdersGsiTiesOfATableWithoutSortKeyByThePartitionKeyHash() { + try (DynamoDbClient client = client()) { + String table = createTable(client, ScalarAttributeType.N, null); + for (String number : NUMBERS) { + client.putItem(r -> r.tableName(table).item(Map.of("pk", number(number), "l", text("t"), "g", text("g")))); + } + + assertEquals(plain(NUMBERS_IN_HASH_ORDER), + query(client, table, "g-all", "g", text("g"), true, null, "pk", value -> plain(value.n()))); + } + } + + @Test + void queryOrdersGsiTiesByTheHashOfThePartitionKeyBytesThenTheSortKeyBytes() { + try (DynamoDbClient client = client()) { + String table = createTable(client, ScalarAttributeType.B, ScalarAttributeType.S); + for (String pk : List.of("00", "0000", "ff", "010203")) { + for (String sk : List.of("a", "é", "日本", "😀")) { + client.putItem(r -> r.tableName(table).item(Map.of("pk", bytes(pk), "sk", text(sk), + "l", text("t"), "g", text("g")))); + } + } + List rows = new ArrayList<>(); + for (Map item : queryItems(client, table, "g-all", "g", text("g"), true, null)) { + rows.add(HexFormat.of().formatHex(item.get("pk").b().asByteArray()) + "|" + item.get("sk").s()); + } + + assertEquals(List.of("ff|é", "ff|😀", "0000|a", "010203|日本", "0000|日本", "0000|é", "00|a", "010203|é", + "00|😀", "ff|a", "010203|a", "00|é", "0000|😀", "00|日本", "ff|日本", "010203|😀"), rows); + } + } + + private static DynamoDbClient client() { + return AwsTestClients.create(DynamoDbClient.builder(), "test", Region.US_EAST_1); + } + + private static String createTable(DynamoDbClient client, ScalarAttributeType pkType, ScalarAttributeType skType) { + String table = "tie-order-" + UUID.randomUUID(); + List attributes = new ArrayList<>(List.of(definition("pk", pkType), + definition("l", ScalarAttributeType.S), definition("g", ScalarAttributeType.S))); + List key = new ArrayList<>(List.of(element("pk", KeyType.HASH))); + CreateTableRequest.Builder request = CreateTableRequest.builder().tableName(table) + .billingMode(BillingMode.PAY_PER_REQUEST) + .globalSecondaryIndexes(GlobalSecondaryIndex.builder().indexName("g-all") + .keySchema(element("g", KeyType.HASH), element("l", KeyType.RANGE)) + .projection(Projection.builder().projectionType(ProjectionType.ALL).build()).build()); + if (skType != null) { + attributes.add(definition("sk", skType)); + key.add(element("sk", KeyType.RANGE)); + request.localSecondaryIndexes(LocalSecondaryIndex.builder().indexName("l-all") + .keySchema(element("pk", KeyType.HASH), element("l", KeyType.RANGE)) + .projection(Projection.builder().projectionType(ProjectionType.ALL).build()).build()); + } + client.createTable(request.attributeDefinitions(attributes).keySchema(key).build()); + return table; + } + + private static List query(DynamoDbClient client, String table, String index, String hashName, + AttributeValue hashValue, boolean forward, Integer limit, String field, + Function show) { + return queryItems(client, table, index, hashName, hashValue, forward, limit).stream() + .map(item -> show.apply(item.get(field))) + .toList(); + } + + private static List> queryItems(DynamoDbClient client, String table, String index, + String hashName, AttributeValue hashValue, + boolean forward, Integer limit) { + List> items = new ArrayList<>(); + Map cursor = null; + do { + QueryResponse response = client.query(QueryRequest.builder().tableName(table).indexName(index) + .keyConditionExpression("#h = :h AND l = :l") + .expressionAttributeNames(Map.of("#h", hashName)) + .expressionAttributeValues(Map.of(":h", hashValue, ":l", text("t"))) + .scanIndexForward(forward).limit(limit).exclusiveStartKey(cursor).build()); + items.addAll(response.items()); + cursor = response.hasLastEvaluatedKey() && !response.lastEvaluatedKey().isEmpty() + ? response.lastEvaluatedKey() : null; + } while (cursor != null); + return items; + } + + private static List plain(List numbers) { + return numbers.stream().map(DynamoDbIndexTieOrderIntegrationTest::plain).toList(); + } + + private static String plain(String number) { + return new BigDecimal(number).stripTrailingZeros().toPlainString(); + } + + private static AttributeDefinition definition(String name, ScalarAttributeType type) { + return AttributeDefinition.builder().attributeName(name).attributeType(type).build(); + } + + private static KeySchemaElement element(String name, KeyType type) { + return KeySchemaElement.builder().attributeName(name).keyType(type).build(); + } + + private static AttributeValue text(String value) { + return AttributeValue.builder().s(value).build(); + } + + private static AttributeValue number(String value) { + return AttributeValue.builder().n(value).build(); + } + + private static AttributeValue bytes(String hex) { + return AttributeValue.builder().b(SdkBytes.fromByteArray(HexFormat.of().parseHex(hex))).build(); + } +}