From a115078c4814c4ef9f0083f2b5881d7e23d8fc25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Mon, 16 Nov 2026 22:07:34 +0900 Subject: [PATCH] fix(dynamodb): leave out LastEvaluatedKey when a Query stops at the end of its key condition (#8577) A Query that Limit stops on its last matching item now leaves out LastEvaluatedKey when the read has reached the end of its key condition: when the partition holds a later item the condition excludes, or, on a table, when the last item sits on the condition's inclusive bound. PartiQL reads of one key or one sort-key range end without a NextToken the same way. A read that stops on the last item of a partition short of an inclusive bound still returns the key. --- .../dynamodb/DynamoDbAccessPathValidator.java | 26 ++++++ .../services/dynamodb/DynamoDbService.java | 68 ++++++++++++++-- ...imitBoundaryPaginationIntegrationTest.java | 80 ++++++++++++++++++- 3 files changed, 162 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAccessPathValidator.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAccessPathValidator.java index 101087a101..65fc8f0460 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAccessPathValidator.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbAccessPathValidator.java @@ -164,6 +164,32 @@ final class DynamoDbAccessPathValidator { } } + /** + * @return the value a validated sort-key condition holds as its last key in read order, as in + * {@code sk = :v}, {@code sk <= :v} read forward or {@code sk BETWEEN :a AND :b}, or + * {@code null} when the condition has no such bound + */ + static JsonNode keyConditionInclusiveEnd(String expression, JsonNode names, JsonNode values, + String sortKey, boolean forward) { + TokenType closingBound = forward ? TokenType.LE : TokenType.GE; + for (Expr rawCondition : keyConditions(expression)) { + Expr condition = normalizeOperandOrder(rawCondition); + if (!sortKey.equals(conditionAttribute(condition, names))) { + continue; + } + Operand bound = switch (condition) { + case CompareExpr compare when compare.op() == TokenType.EQ || compare.op() == closingBound -> + compare.right(); + case BetweenExpr between -> forward ? between.high() : between.low(); + default -> null; + }; + return bound instanceof PlaceholderOperand placeholder && values != null + ? values.get(placeholder.name()) + : null; + } + return null; + } + private static List keyConditions(String expression) { return DynamoDbKeyConditionParser.conditions(parseExpression(expression, "KeyConditionExpression")); } 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 728d178214..08e8cfe8c8 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -1614,6 +1614,7 @@ public class DynamoDbService { if (items == null) return new QueryResult(List.of(), 0, 0, null, List.of()); List results = new ArrayList<>(); + List partition = new ArrayList<>(); if (keyConditions != null) { String partitionKeyValue = extractComparisonValue(keyConditions.get(pkName)); @@ -1621,6 +1622,7 @@ public class DynamoDbService { boolean partitionKeyMatches = pkNames.stream().allMatch(name -> item.has(name) && matchesAttributeValue(item.get(name), extractComparisonValue(keyConditions.get(name)))); if (!partitionKeyMatches) continue; + partition.add(item); if (skName != null && keyConditions.has(skName)) { JsonNode skCondition = keyConditions.get(skName); if (matchesKeyCondition(item.get(skName), skCondition)) { @@ -1632,7 +1634,7 @@ public class DynamoDbService { } } else if (keyConditionExpression != null) { results = queryWithExpression(items, accessPath, partitionKeyValuePlaceholder, - keyConditionExpression, expressionAttrValues, exprAttrNames); + keyConditionExpression, expressionAttrValues, exprAttrNames, partition); } // Filter out items without GSI key attributes (sparse index behavior). @@ -1677,15 +1679,12 @@ public class DynamoDbService { // The size check comes first for each item — per the Query API reference, // "if the processed dataset size exceeds 1 MB before DynamoDB reaches this // limit, it stops the operation", so an item that would cross the 1 MB cap - // is not read and does not count toward Limit. DynamoDB does not look ahead - // either way: a read that stops at a boundary always returns a - // LastEvaluatedKey, even when the boundary happens to be the last item of - // the result set ("the absence of LastEvaluatedKey is the only way to know - // that you have reached the end of the result set"). + // is not read and does not count toward Limit. final int MAX_RESPONSE_BYTES = 1024 * 1024; int accSize = 0; long billedBytes = 0; int included = -1; // index one past the last included item; -1 = no boundary hit + boolean stoppedByLimit = false; for (int i = 0; i < evaluatedItems.size(); i++) { int sz = readItemSize(evaluatedItems.get(i), accessPath, table); if (accSize > 0 && accSize + sz > MAX_RESPONSE_BYTES) { @@ -1696,11 +1695,19 @@ public class DynamoDbService { billedBytes += billedReadSize(evaluatedItems.get(i), accessPath, table, sz); if (limit != null && limit > 0 && i + 1 >= limit) { included = i + 1; // the Limit cap stops the read AFTER this item + stoppedByLimit = true; break; } } if (included > 0) { - lastEvaluatedKey = buildKeyNode(table, evaluatedItems.get(included - 1), pkName, sortKeyNames, indexName != null); + JsonNode last = evaluatedItems.get(included - 1); + boolean rangeEnded = stoppedByLimit && included == evaluatedItems.size() + && endsKeyRange(partition, accessPath, last, (a, b) -> direction * keyOrder.compare(a, b), + () -> keyRangeInclusiveEnd(accessPath, keyConditions, keyConditionExpression, + exprAttrNames, expressionAttrValues, direction > 0)); + if (!rangeEnded) { + lastEvaluatedKey = buildKeyNode(table, last, pkName, sortKeyNames, indexName != null); + } evaluatedItems = new ArrayList<>(evaluatedItems.subList(0, included)); } @@ -5045,12 +5052,56 @@ public class DynamoDbService { return items.subMap(encodedPk + "#", true, encodedPk + "$", false).values(); } + // A read that stops at Limit on its last match leaves out LastEvaluatedKey when the partition + // holds another item past it, which the key condition then excludes. A table read also leaves + // it out on the condition's inclusive bound, as no other item can share that key. + private static boolean endsKeyRange(List partition, DynamoDbAccessPath accessPath, JsonNode last, + Comparator readOrder, Supplier inclusiveEnd) { + List partitionKeys = accessPath.partitionKeyNames(); + Set keyAttributes = accessPath.keyAttributeNames(); + for (JsonNode item : partition) { + if (compareKeyAttributes(item, last, partitionKeys) == 0 + && keyAttributes.stream().allMatch(key -> hasNonNullAttribute(item, key)) + && readOrder.compare(item, last) > 0) { + return true; + } + } + JsonNode end = inclusiveEnd.get(); + return end != null && ExpressionEvaluator.compareAttributeValues(last.get(accessPath.sortKeyName()), end) == 0; + } + + private static JsonNode keyRangeInclusiveEnd(DynamoDbAccessPath accessPath, JsonNode keyConditions, + String keyConditionExpression, JsonNode exprAttrNames, + JsonNode exprAttrValues, boolean forward) { + String sortKey = accessPath.sortKeyName(); + if (accessPath.isIndex() || sortKey == null) { + return null; + } + if (keyConditions == null) { + return keyConditionExpression == null ? null : DynamoDbAccessPathValidator.keyConditionInclusiveEnd( + keyConditionExpression, exprAttrNames, exprAttrValues, sortKey, forward); + } + JsonNode condition = keyConditions.get(sortKey); + JsonNode values = condition == null ? null : condition.get("AttributeValueList"); + if (values == null || values.isEmpty()) { + return null; + } + return switch (condition.path("ComparisonOperator").asText("EQ")) { + case "EQ" -> values.get(0); + case "LE" -> forward ? values.get(0) : null; + case "GE" -> forward ? null : values.get(0); + case "BETWEEN" -> values.get(forward ? 1 : 0); + default -> null; + }; + } + private List queryWithExpression(ConcurrentSkipListMap items, DynamoDbAccessPath accessPath, String partitionKeyValuePlaceholder, String expression, JsonNode expressionAttrValues, - JsonNode exprAttrNames) { + JsonNode exprAttrNames, + List partition) { List results = new ArrayList<>(); String partitionKeyName = accessPath.partitionKeyName(); String partitionKeyValue = expressionAttrValues != null && partitionKeyValuePlaceholder != null @@ -5063,6 +5114,7 @@ public class DynamoDbService { && !matchesAttributeValue(item.get(partitionKeyName), partitionKeyValue)) { continue; } + partition.add(item); if (keyCondition == null) { keyCondition = ExpressionEvaluator.parse(expression); } diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbLimitBoundaryPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbLimitBoundaryPaginationIntegrationTest.java index 7da14600c4..5811697b81 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbLimitBoundaryPaginationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbLimitBoundaryPaginationIntegrationTest.java @@ -9,6 +9,11 @@ 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 java.util.ArrayList; +import java.util.List; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,10 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * Wire-protocol regression for floci-io/floci#2383: when a Query or Scan stops because it * reached {@code Limit}, DynamoDB returns a {@code LastEvaluatedKey} even if the stop position - * happens to be the last item of the result set. DynamoDB does not look ahead — per the - * developer guide, "the absence of LastEvaluatedKey is the only way to know that you have - * reached the end of the result set", so the client discovers the end on the follow-up request, - * which returns an empty page with no LastEvaluatedKey. + * happens to be the last item of the partition or table, so the client discovers the end on the + * follow-up request, which returns an empty page with no LastEvaluatedKey. A Query that stops + * where its key condition ends leaves the cursor out. * *

Covers the exact-Limit boundary for ascending Query, descending Query * ({@code ScanIndexForward=false}), GSI Query (cursor must carry index + table keys), and Scan, @@ -546,6 +550,74 @@ class DynamoDbLimitBoundaryPaginationIntegrationTest { "a Scan that exhausts the table below Limit must not carry a cursor: " + summary(result)); } + @ParameterizedTest(name = "{0} from {1} to {2}, forward {3}, Limit {4}") + @Order(13) + @CsvSource(delimiter = '|', textBlock = """ + pk = :p AND sk = :a | 1 | | true | 1 | 1 | false + pk = :p AND sk BETWEEN :a AND :b | 1 | 2 | true | 2 | 1;2 | false + pk = :p AND sk <= :a | 2 | | true | 2 | 1;2 | false + pk = :p AND sk < :a | 2 | | true | 1 | 1 | false + pk = :p AND sk >= :a | 2 | | false | 2 | 3;2 | false + pk = :p AND sk BETWEEN :a AND :b | 2 | 3 | true | 2 | 2;3 | false + pk = :p AND sk BETWEEN :a AND :b | 1 | 5 | true | 3 | 1;2;3 | true + pk = :p AND sk > :a | 1 | | true | 1 | 2 | true + """) + void queryLimitAtTheEndOfTheKeyRangeLeavesOutTheCursor(String condition, String a, String b, boolean forward, + int limit, String keys, boolean cursor) throws Exception { + String values = "\":p\": {\"N\": \"1\"}, \":a\": {\"N\": \"%s\"}".formatted(a) + + (b == null ? "" : ", \":b\": {\"N\": \"%s\"}".formatted(b)); + JsonNode page = query(""" + { + "TableName": "%s", + "KeyConditionExpression": "%s", + "ExpressionAttributeValues": {%s}, + "ScanIndexForward": %s, + "Limit": %d + } + """.formatted(TABLE, condition, values, forward, limit)); + assertEquals(List.of(keys.split(";")), sortKeys(page)); + assertEquals(cursor, page.path("LastEvaluatedKey").isObject(), summary(page)); + } + + @Test + @Order(14) + void gsiQueryLimitBeforeAnExcludedItemLeavesOutTheCursor() throws Exception { + JsonNode page = query(""" + { + "TableName": "%s", + "IndexName": "%s", + "KeyConditionExpression": "category = :c AND sk = :a", + "ExpressionAttributeValues": {":c": {"S": "a"}, ":a": {"N": "1"}}, + "Limit": 1 + } + """.formatted(TABLE, INDEX)); + assertEquals(List.of("1"), sortKeys(page)); + assertTrue(page.path("LastEvaluatedKey").isMissingNode(), summary(page)); + } + + @Test + @Order(15) + void keyConditionsLimitOnTheInclusiveBoundLeavesOutTheCursor() throws Exception { + JsonNode page = query(""" + { + "TableName": "%s", + "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"N": "1"}]}, + "sk": {"ComparisonOperator": "BETWEEN", "AttributeValueList": [{"N": "2"}, {"N": "3"}]} + }, + "Limit": 2 + } + """.formatted(TABLE)); + assertEquals(List.of("2", "3"), sortKeys(page)); + assertTrue(page.path("LastEvaluatedKey").isMissingNode(), summary(page)); + } + + private static List sortKeys(JsonNode page) { + List keys = new ArrayList<>(); + page.path("Items").forEach(item -> keys.add(item.path("sk").path("N").asText())); + return keys; + } + /** Response summary without the bulky Items array, for assertion messages. */ private static String summary(JsonNode response) { return "{Count=" + response.path("Count") + ", ScannedCount=" + response.path("ScannedCount")