From 39a8c341e4ae87528ac19dcaed8478799edd9a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Tue, 17 Nov 2026 12:46:53 +0900 Subject: [PATCH] fix(dynamodb): read each PartiQL sort-key branch on its own (#8672) --- .../dynamodb/DynamoDbPartiQLHandler.java | 103 ++++++++-- .../dynamodb/DynamoDbPartiQLKeyPlan.java | 27 ++- ...oDbPartiQLSortKeyReadsIntegrationTest.java | 184 ++++++++++++++++++ 3 files changed, 295 insertions(+), 19 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLSortKeyReadsIntegrationTest.java diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java index 52211ffe2b..88d88f23cb 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLHandler.java @@ -97,9 +97,22 @@ class DynamoDbPartiQLHandler { Routing routing = routingOf(stmt.where(), keys, accessPath.partitionKeyName(), accessPath.sortKeyName()); Supplier startKey = () -> decodeNextToken(ctx.nextToken(), ctx.tokenBinding()); - Page page = stmt.orderBy().isEmpty() - ? readPage(stmt, table, accessPath, routing, startKey, ctx.limit(), region) - : readOrdered(stmt, table, accessPath, routing, startKey.get(), ctx.limit(), region); + boolean descending = directionOf(stmt.orderBy(), accessPath.sortKeyName()).orElse(false); + Optional> sortKeyReads = routing.partition() == null + ? Optional.empty() + : keys.sortKeyReads(descending); + Page page; + if (sortKeyReads.isPresent()) { + if (!stmt.orderBy().isEmpty()) { + requireOrderByShape(stmt, accessPath); + } + page = readSortKeyReads(stmt, table, accessPath, routing.partition(), sortKeyReads.get(), descending, + startKey.get(), ctx.limit(), region); + } else if (stmt.orderBy().isEmpty()) { + page = readPage(stmt, table, accessPath, routing, startKey, ctx.limit(), region); + } else { + page = readOrdered(stmt, table, accessPath, routing, startKey.get(), ctx.limit(), region); + } List items = page.items(); JsonNode lastEvaluatedKey = page.lastEvaluatedKey(); @@ -136,7 +149,9 @@ class DynamoDbPartiQLHandler { private static DynamoDbWriteCapacity.Cost readCapacity(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, Page page, boolean consistentRead) { - double units = NativeDynamoDbJsonHandler.readCapacityUnits(page.scannedBytes(), consistentRead); + double units = page.readBytes().stream() + .mapToDouble(bytes -> NativeDynamoDbJsonHandler.readCapacityUnits(bytes, consistentRead)) + .sum(); if (!accessPath.isIndex()) { return new DynamoDbWriteCapacity.Cost(units, Map.of(), Map.of()); } @@ -191,7 +206,8 @@ class DynamoDbPartiQLHandler { return new Routing(pkEq, skCond, filterConds, null); } - private record Page(List items, JsonNode lastEvaluatedKey, long scannedBytes, + // readBytes holds the bytes of each read DynamoDB charges on its own. + private record Page(List items, JsonNode lastEvaluatedKey, List readBytes, List scannedItems) {} private Page readPage(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, @@ -227,7 +243,8 @@ class DynamoDbPartiQLHandler { List matching = partialProjection ? matchingIndexView(result.items(), scanFilters, accessPath, table) : result.items(); - return new Page(matching, result.lastEvaluatedKey(), result.scannedBytes(), result.scannedItems()); + return new Page(matching, result.lastEvaluatedKey(), List.of(result.scannedBytes()), + result.scannedItems()); } if (accessPath.kind() == DynamoDbAccessPath.Kind.TABLE && skName == null && skCond == null && filterConds.isEmpty()) { @@ -235,13 +252,14 @@ class DynamoDbPartiQLHandler { key.set(pkName, toTypedNode(pkEq.val())); JsonNode item = service.getItem(stmt.table(), key, region); if (item == null) { - return new Page(Collections.emptyList(), null, 0, List.of()); + return new Page(Collections.emptyList(), null, List.of(0L), List.of()); } - return new Page(List.of(item), null, DynamoDbItemSize.billedItemSize(table, item), List.of(item)); + return new Page(List.of(item), null, List.of((long) DynamoDbItemSize.billedItemSize(table, item)), + List.of(item)); } ExprAttrBuilder eav = new ExprAttrBuilder(); ExprAttrNameBuilder ean = new ExprAttrNameBuilder(); - String kce = buildKce(pkEq, skCond, pkName, skName, eav, ean); + String kce = buildKce(pkEq.val(), skCond, pkName, skName, eav, ean); String fe = buildFe(filterConds, eav, ean); JsonNode exclusiveStartKey = startKey.get(); DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath); @@ -249,20 +267,73 @@ class DynamoDbPartiQLHandler { stmt.table(), null, eav.toNode(mapper), kce, fe, limit, null, accessPath.indexName(), exclusiveStartKey, ean.isEmpty() ? null : ean.toNode(mapper), region); - return new Page(result.items(), result.lastEvaluatedKey(), result.scannedBytes(), result.scannedItems()); + return new Page(result.items(), result.lastEvaluatedKey(), List.of(result.scannedBytes()), + result.scannedItems()); } private Page readPartition(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, Routing routing, Supplier startKey, Integer limit, String region) { ExprAttrBuilder eav = new ExprAttrBuilder(); ExprAttrNameBuilder ean = new ExprAttrNameBuilder(); - String kce = ean.alias(accessPath.partitionKeyName()) + " = " + eav.add(toTypedNode(routing.partition())); + String kce = buildKce(routing.partition(), null, accessPath.partitionKeyName(), accessPath.sortKeyName(), + eav, ean); JsonNode exclusiveStartKey = startKey.get(); DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath); DynamoDbService.QueryResult result = service.query(stmt.table(), null, eav.toNode(mapper), kce, null, limit, null, accessPath.indexName(), exclusiveStartKey, ean.toNode(mapper), region); List matching = matchingIndexView(result.items(), routing.filterConds(), accessPath, table); - return new Page(matching, result.lastEvaluatedKey(), result.scannedBytes(), result.items()); + return new Page(matching, result.lastEvaluatedKey(), List.of(result.scannedBytes()), result.items()); + } + + // DynamoDB reads each sort-key branch of one partition as a Query of its own, in key order, and + // charges each read on its own. The token names the read to go on with, and the key to resume + // from when the page stopped inside it. + private Page readSortKeyReads(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath, + PVal partition, List reads, boolean descending, JsonNode cursor, + Integer limit, String region) { + int read = cursor == null ? 0 : readIndex(cursor, reads.size()); + JsonNode exclusiveStartKey = cursor == null ? null : cursor.get("k"); + List rows = new ArrayList<>(); + List readBytes = new ArrayList<>(); + List scannedItems = new ArrayList<>(); + for (; read < reads.size(); read++) { + ExprAttrBuilder eav = new ExprAttrBuilder(); + ExprAttrNameBuilder ean = new ExprAttrNameBuilder(); + String kce = buildKce(partition, reads.get(read), accessPath.partitionKeyName(), + accessPath.sortKeyName(), eav, ean); + DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath); + Integer remaining = limit == null ? null : limit - scannedItems.size(); + DynamoDbService.QueryResult result = service.query(stmt.table(), null, eav.toNode(mapper), kce, null, + remaining, !descending, accessPath.indexName(), exclusiveStartKey, ean.toNode(mapper), region); + exclusiveStartKey = null; + readBytes.add(result.scannedBytes()); + scannedItems.addAll(result.items()); + rows.addAll(matchingIndexView(result.items(), stmt.where(), accessPath, table)); + if (result.lastEvaluatedKey() != null) { + return new Page(rows, readCursor(read, result.lastEvaluatedKey()), readBytes, scannedItems); + } + if (limit != null && scannedItems.size() >= limit) { + JsonNode next = read + 1 < reads.size() ? readCursor(read + 1, null) : null; + return new Page(rows, next, readBytes, scannedItems); + } + } + return new Page(rows, null, readBytes, scannedItems); + } + + private static int readIndex(JsonNode cursor, int reads) { + JsonNode read = cursor.get("r"); + if (read == null || !read.isInt() || read.intValue() < 0 || reads <= read.intValue()) { + throw new AwsException("ValidationException", "Invalid NextToken", 400); + } + return read.intValue(); + } + + private ObjectNode readCursor(int read, JsonNode exclusiveStartKey) { + ObjectNode cursor = mapper.createObjectNode().put("r", read); + if (exclusiveStartKey != null) { + cursor.set("k", exclusiveStartKey); + } + return cursor; } // The WHERE clause of an index read sees only what the index stores, so an @@ -299,7 +370,7 @@ class DynamoDbPartiQLHandler { JsonNode from = lastKey; Page page = readPage(stmt, table, accessPath, routing, () -> from, null, region); rows.addAll(page.items()); - scannedBytes += page.scannedBytes(); + scannedBytes += page.readBytes().stream().mapToLong(Long::longValue).sum(); scannedItems.addAll(page.scannedItems()); lastKey = page.lastEvaluatedKey(); } while (lastKey != null); @@ -314,7 +385,7 @@ class DynamoDbPartiQLHandler { } int end = limit == null ? rows.size() : Math.min(rows.size(), start + limit); JsonNode resumeAfter = start < end && end < rows.size() ? orderingKey(rows.get(end - 1), accessPath, table) : null; - return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, scannedBytes, scannedItems); + return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, List.of(scannedBytes), scannedItems); } private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath) { @@ -449,12 +520,12 @@ class DynamoDbPartiQLHandler { return payload.get("k"); } - private String buildKce(Cond.Eq pkEq, Cond skCond, String pkName, String skName, + private String buildKce(PVal partition, Cond skCond, String pkName, String skName, ExprAttrBuilder eav, ExprAttrNameBuilder ean) { // Query branch: callers only reach this with a partition-key equality // in the WHERE clause; every other shape routes to the scan branch. String pkAlias = ean.alias(pkName); - String pkPlaceholder = eav.add(toTypedNode(pkEq.val())); + String pkPlaceholder = eav.add(toTypedNode(partition)); StringBuilder kce = new StringBuilder(pkAlias).append(" = ").append(pkPlaceholder); if (skCond != null) { kce.append(" AND ").append(buildCondExpr(skCond, eav, ean)); diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLKeyPlan.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLKeyPlan.java index 328dfb9237..3971a5b3f3 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLKeyPlan.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLKeyPlan.java @@ -44,7 +44,8 @@ final class DynamoDbPartiQLKeyPlan { } } - private record Branch(Key partition, PVal partitionValue, Range sortRange, List filters) { + private record Branch(Key partition, PVal partitionValue, Range sortRange, List sortConditions, + List filters) { static final Comparator IN_KEY_ORDER = Comparator.comparing(Branch::partition) .thenComparing(Branch::sortRange, Range.BY_LOWER); @@ -58,7 +59,7 @@ final class DynamoDbPartiQLKeyPlan { this.everyBranchPinsPartition = everyBranchPinsPartition(conditions); List spread = spread(conditions); this.branches = tooManyBranches - ? List.of(new Branch(null, null, Range.ALL, where)) + ? List.of(new Branch(null, null, Range.ALL, List.of(), where)) : spread.stream().map(this::branchOf).toList(); } @@ -186,6 +187,21 @@ final class DynamoDbPartiQLKeyPlan { return Optional.of(branches.getFirst().partitionValue()); } + /** + * @return the sort-key condition of each read, in the order DynamoDB reads them, when every + * branch reads the same partition with one sort-key condition + */ + Optional> sortKeyReads(boolean descending) { + if (singlePartition().isEmpty() || branches.stream().anyMatch(this::testsAKeyOutsideARange) + || branches.stream().anyMatch(branch -> branch.sortConditions().size() != 1)) { + return Optional.empty(); + } + return Optional.of(branches.stream() + .sorted(descending ? Branch.IN_KEY_ORDER.reversed() : Branch.IN_KEY_ORDER) + .map(branch -> branch.sortConditions().getFirst()) + .toList()); + } + static Stream attributePaths(Cond cond) { return DynamoDbPartiQLParser.leaves(cond).map(Cond.Leaf::path); } @@ -207,6 +223,7 @@ final class DynamoDbPartiQLKeyPlan { PVal partitionValue = null; boolean conflicting = false; Range sortRange = Range.ALL; + List sortConditions = new ArrayList<>(); for (Cond.Leaf condition : spread.keyConditions()) { if (condition.path().root().equals(partitionKey)) { PVal value = ((Cond.Eq) condition).val(); @@ -218,9 +235,13 @@ final class DynamoDbPartiQLKeyPlan { } } else { sortRange = sortRange.intersect(rangeOf(condition)); + if (!sortConditions.contains(condition)) { + sortConditions.add(condition); + } } } - return new Branch(conflicting ? null : partition, partitionValue, sortRange, spread.filters()); + return new Branch(conflicting ? null : partition, partitionValue, sortRange, sortConditions, + spread.filters()); } private List spread(Cond cond) { diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLSortKeyReadsIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLSortKeyReadsIntegrationTest.java new file mode 100644 index 0000000000..a532c9bc29 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLSortKeyReadsIntegrationTest.java @@ -0,0 +1,184 @@ +package io.floci.aws.services.dynamodb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import static io.floci.aws.testing.DynamoDbRequests.CONTENT_TYPE; +import static io.floci.aws.testing.DynamoDbRequests.ddb; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class DynamoDbPartiQLSortKeyReadsIntegrationTest { + + private static final String TABLE = "PartiQLSortKeyReads"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static int testPort; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void createTable() throws Exception { + testPort = RestAssured.port; + call("CreateTable", """ + { + "TableName": "%s", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "l", "AttributeType": "S"} + ], + "LocalSecondaryIndexes": [{ + "IndexName": "lsi", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "l", "KeyType": "RANGE"} + ], + "Projection": {"ProjectionType": "ALL"} + }], + "BillingMode": "PAY_PER_REQUEST" + } + """.formatted(TABLE)); + for (int i = 1; i <= 3; i++) { + put("{\"pk\": {\"S\": \"p\"}, \"sk\": {\"S\": \"row-%1$d\"}, \"x\": {\"N\": \"%1$d\"}}".formatted(i)); + } + put("{\"pk\": {\"S\": \"lk\"}, \"sk\": {\"S\": \"r1\"}, \"l\": {\"S\": \"a\"}}"); + put("{\"pk\": {\"S\": \"lk\"}, \"sk\": {\"S\": \"r2\"}, \"l\": {\"S\": \"b\"}}"); + put("{\"pk\": {\"S\": \"lk\"}, \"sk\": {\"S\": \"r3\"}, \"l\": {\"S\": \"b\"}}"); + put("{\"pk\": {\"S\": \"big\"}, \"sk\": {\"S\": \"big\"}, \"pad\": {\"S\": \"%s\"}}".formatted("x".repeat(5000))); + put("{\"pk\": {\"S\": \"big\"}, \"sk\": {\"S\": \"row-1\"}}"); + } + + @ParameterizedTest(name = "{0} under Limit {1}") + @Order(2) + @CsvSource(delimiter = '|', quoteCharacter = '"', textBlock = """ + pk='p' AND (sk='row-1' OR sk='row-2') | 1 | [row-1] + 0.5;[row-2] 0.5 + pk='p' AND (sk='row-0' OR sk='row-2') | 1 | [row-2] 1.0 + pk='p' AND (sk='row-1' OR sk='row-9') | 1 | [row-1] + 0.5;[] 0.5 + pk='p' AND (sk='row-1' OR sk='row-2' OR sk='row-3') | 2 | [row-1,row-2] + 1.0;[row-3] 0.5 + pk='p' AND sk IN ['row-1','row-3'] ORDER BY sk DESC | 1 | [row-3] + 0.5;[row-1] 0.5 + pk='p' AND (sk='row-1' OR sk='row-3') ORDER BY pk DESC | 1 | [row-1] + 0.5;[row-3] 0.5 + pk='p' AND (sk BETWEEN 'row-0' AND 'row-1' OR sk BETWEEN 'x' AND 'y') | 1 | [row-1] + 0.5;[] 0.5 + pk='p' AND (sk='row-1' OR sk BETWEEN 'row-3' AND 'row-5') | 2 | [row-1,row-3] + 1.0;[] 0.5 + pk='p' AND (sk='row-1' OR sk='row-2' OR sk='row-3') AND x = 2 | 1 | [] + 0.5;[row-2] + 0.5;[] 0.5 + """) + void readsEachSortKeyBranchInKeyOrder(String where, int limit, String pages) throws Exception { + assertEquals(List.of(pages.split(";")), walk("SELECT * FROM \"" + TABLE + "\" WHERE " + where, limit)); + } + + @Test + @Order(3) + void chargesEachBranchOnItsOwn() throws Exception { + String keys = "SELECT * FROM \"" + TABLE + "\" WHERE pk='p' AND (sk='row-1' OR sk='row-3')"; + assertEquals(2.0, read(keys, true).path("ConsumedCapacity").path("CapacityUnits").asDouble()); + assertEquals(1.0, read(keys, false).path("ConsumedCapacity").path("CapacityUnits").asDouble()); + String big = "SELECT * FROM \"" + TABLE + "\" WHERE pk='big' AND (sk='big' OR sk='row-1')"; + assertEquals(3.0, read(big, true).path("ConsumedCapacity").path("CapacityUnits").asDouble()); + assertEquals(1.5, read(big, false).path("ConsumedCapacity").path("CapacityUnits").asDouble()); + } + + @Test + @Order(4) + void readsEachLsiKeyOnItsOwn() throws Exception { + String keys = "SELECT * FROM \"" + TABLE + "\".\"lsi\" WHERE pk='lk' AND "; + assertEquals(List.of("[r1] + 0.5", "[] 0.5"), walk(keys + "(l='a' OR l='z')", 1)); + JsonNode capacity = read(keys + "(l='a' OR l='b')", true).path("ConsumedCapacity"); + assertEquals(2.0, capacity.path("CapacityUnits").asDouble()); + assertEquals(2.0, capacity.path("LocalSecondaryIndexes").path("lsi").path("CapacityUnits").asDouble()); + } + + @ParameterizedTest + @Order(5) + @ValueSource(strings = {"-1", "2", "\"0\"", "null"}) + void refusesATokenThatNamesNoRead(String read) throws Exception { + String statement = "SELECT * FROM \"" + TABLE + "\" WHERE pk='p' AND (sk='row-1' OR sk='row-2')"; + String first = MAPPER.createObjectNode().put("Statement", statement).put("Limit", 1).toString(); + String token = call("ExecuteStatement", first).path("NextToken").asText(); + ObjectNode payload = (ObjectNode) MAPPER.readTree(Base64.getDecoder().decode(token)); + ((ObjectNode) payload.get("k")).set("r", MAPPER.readTree(read)); + String next = MAPPER.createObjectNode() + .put("Statement", statement) + .put("NextToken", Base64.getEncoder().encodeToString(MAPPER.writeValueAsBytes(payload))) + .toString(); + ddb("ExecuteStatement", next) + .statusCode(400) + .body("message", equalTo("Invalid NextToken")); + } + + private List walk(String statement, int limit) throws Exception { + List pages = new ArrayList<>(); + String token = null; + do { + ObjectNode request = MAPPER.createObjectNode() + .put("Statement", statement) + .put("Limit", limit) + .put("ReturnConsumedCapacity", "TOTAL"); + if (token != null) { + request.put("NextToken", token); + } + JsonNode page = call("ExecuteStatement", request.toString()); + List keys = new ArrayList<>(); + page.path("Items").forEach(item -> keys.add(item.path("sk").path("S").asText())); + token = page.hasNonNull("NextToken") ? page.get("NextToken").asText() : null; + pages.add("[" + String.join(",", keys) + "]" + (token == null ? "" : " +") + " " + + page.path("ConsumedCapacity").path("CapacityUnits").asDouble()); + } while (token != null && pages.size() < 8); + return pages; + } + + private JsonNode read(String statement, boolean consistentRead) throws Exception { + return call("ExecuteStatement", MAPPER.createObjectNode() + .put("Statement", statement) + .put("ConsistentRead", consistentRead) + .put("ReturnConsumedCapacity", "INDEXES") + .toString()); + } + + private void put(String item) throws Exception { + call("PutItem", "{\"TableName\": \"" + TABLE + "\", \"Item\": " + item + "}"); + } + + private JsonNode call(String action, String body) throws Exception { + return MAPPER.readTree(ddb(action, body).statusCode(200).extract().body().asString()); + } + + @AfterAll + static void cleanup() { + given() + .port(testPort) + .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable") + .contentType(CONTENT_TYPE) + .body("{\"TableName\": \"" + TABLE + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + } +}