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.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-17 21:02:15 -04:00
1 parent 0dedd49f79
commit a1de0ee905
3 files changed
+304 -3

No files matched your search

@@ -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<JsonNode> indexTieOrder(TableDefinition table, DynamoDbAccessPath accessPath) {
List<String> hashed = new ArrayList<>();
if (accessPath.isGlobalSecondaryIndex()) {
hashed.add(table.getPartitionKeyName());
}
if (table.getSortKeyName() != null) {
hashed.add(table.getSortKeyName());
}
Map<JsonNode, byte[]> hashes = new IdentityHashMap<>();
return Comparator.comparing(item -> hashes.computeIfAbsent(item, ignored -> of(item, hashed)),
Arrays::compareUnsigned);
}
static byte[] of(JsonNode item, List<String> 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;
}
}
@@ -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<String> orderKeyNames = new ArrayList<>(sortKeyNames);
if (accessPath.isIndex()) {
orderKeyNames.add(table.getPartitionKeyName());
@@ -1660,7 +1660,11 @@ public class DynamoDbService {
orderKeyNames.add(table.getSortKeyName());
}
}
Comparator<JsonNode> keyOrder = (a, b) -> compareKeyAttributes(a, b, orderKeyNames);
Comparator<JsonNode> sortKeyOrder = (a, b) -> compareKeyAttributes(a, b, sortKeyNames);
Comparator<JsonNode> 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);