mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): order Query by full composite sort key (#2114)
* fix(dynamodb): order Query by full composite sort key Query ordered results using only the first RANGE attribute returned by getSortKeyName(). For an index with a composite sort key (more than one RANGE attribute, e.g. "state RANGE, createdAt RANGE"), the remaining components were ignored: when the first component tied across rows, the stable sort left items in base-table storage order and ScanIndexForward =false merely reversed that order, so the secondary component (e.g. createdAt) never drove ordering. Sort by the full sort key instead, comparing each RANGE attribute in key-schema order and short-circuiting on the first non-equal component, then reverse for ScanIndexForward=false. Single-sort-key indexes are unaffected (one-element list preserves previous behavior). Adds getSortKeyNames() to GlobalSecondaryIndex, LocalSecondaryIndex and TableDefinition, and a regression test whose base-key order deliberately disagrees with the secondary sort component. Fixes #1675 * fix(dynamodb): paginate composite sort-key Query by full key The composite-sort-key ordering fix sorted by every RANGE attribute, but pagination still used only the first RANGE component (getSortKeyName()). LastEvaluatedKey construction and ExclusiveStartKey matching therefore dropped the later components, so a cursor no longer uniquely identified the row a page stopped on — rows sharing the first RANGE value could be skipped or duplicated across pages. Thread the full sort-key list (getSortKeyNames()) through buildKeyNode() and buildItemKeyFromNode(): the emitted cursor now carries every sort-key component, and cursor matching compares the full composite key. Single sort-key indexes and the scan/table-key paths keep the previous behavior via the retained single-key overloads. Addresses PR review comment r3710297799 ("Composite pagination loses key identity"). Adds paginated regression tests over the composite index that fail without this change. Refs #1675. --------- Co-authored-by: Nikola Gencic <nikola.gencic@centiglobe.com>
This commit is contained in:
1 parent
02288abc11
commit
cd3c6b54b2
6 files changed
+426
-18
No files matched your search
+283
@@ -0,0 +1,283 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
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 java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Wire-protocol regression for floci-io/floci#1675: a Query against an index whose sort key is
|
||||
* composite (more than one RANGE attribute, e.g. {@code state RANGE, createdAt RANGE}) must order
|
||||
* by ALL sort-key attributes in key-schema order, so {@code ScanIndexForward=false} yields the
|
||||
* reverse of the full composite order.
|
||||
*
|
||||
* <p>Previously only the first RANGE attribute (here {@code state}, identical across the rows) drove
|
||||
* ordering: {@code createdAt} was ignored, and the stable sort merely preserved (or, when
|
||||
* {@code ScanIndexForward=false}, reversed) base-table storage order. The items below are inserted
|
||||
* so their storage order (requestId a, b, c) deliberately disagrees with {@code createdAt} order,
|
||||
* so a correct result can only come from sorting on the second composite component.
|
||||
*
|
||||
* <p>DynamoDB natively supports multi-attribute composite keys on secondary indexes, so emulating
|
||||
* full-key ordering is required for parity.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class DynamoDbCompositeSortKeyQueryIntegrationTest {
|
||||
|
||||
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String TABLE = "CompositeSortKeyRequests";
|
||||
private static final String INDEX = "memberIndex";
|
||||
|
||||
// KeyCondition on the composite GSI: partition (memberName) + both sort components.
|
||||
private static final String KEY_CONDITION =
|
||||
"memberName = :pk AND #st = :st AND createdAt BETWEEN :from AND :to";
|
||||
private static final String EXPRESSION_ATTRIBUTE_VALUES = """
|
||||
{
|
||||
":pk": {"S": "alice"},
|
||||
":st": {"S": "ACTIVE"},
|
||||
":from": {"S": "1970-01-01T00:00:00Z"},
|
||||
":to": {"S": "2100-01-01T00:00:00Z"}
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTableWithCompositeSortKeyIndex() {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"KeySchema": [
|
||||
{"AttributeName": "requestId", "KeyType": "HASH"}
|
||||
],
|
||||
"AttributeDefinitions": [
|
||||
{"AttributeName": "requestId", "AttributeType": "S"},
|
||||
{"AttributeName": "memberName", "AttributeType": "S"},
|
||||
{"AttributeName": "state", "AttributeType": "S"},
|
||||
{"AttributeName": "createdAt", "AttributeType": "S"}
|
||||
],
|
||||
"GlobalSecondaryIndexes": [
|
||||
{
|
||||
"IndexName": "%s",
|
||||
"KeySchema": [
|
||||
{"AttributeName": "memberName", "KeyType": "HASH"},
|
||||
{"AttributeName": "state", "KeyType": "RANGE"},
|
||||
{"AttributeName": "createdAt", "KeyType": "RANGE"}
|
||||
],
|
||||
"Projection": {"ProjectionType": "ALL"}
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(TABLE, INDEX))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TableDescription.GlobalSecondaryIndexes[0].IndexName", equalTo(INDEX))
|
||||
.body("TableDescription.GlobalSecondaryIndexes[0].KeySchema.size()", equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void putItemsWhoseStorageOrderDisagreesWithCreatedAt() {
|
||||
// Same memberName + state across all three; requestId (storage) order a, b, c is chosen to
|
||||
// DISAGREE with createdAt order (a=:03, b=:01, c=:02).
|
||||
String[] items = {
|
||||
"{\"requestId\":{\"S\":\"a\"},\"memberName\":{\"S\":\"alice\"},"
|
||||
+ "\"state\":{\"S\":\"ACTIVE\"},\"createdAt\":{\"S\":\"2026-07-14T00:00:03Z\"}}",
|
||||
"{\"requestId\":{\"S\":\"b\"},\"memberName\":{\"S\":\"alice\"},"
|
||||
+ "\"state\":{\"S\":\"ACTIVE\"},\"createdAt\":{\"S\":\"2026-07-14T00:00:01Z\"}}",
|
||||
"{\"requestId\":{\"S\":\"c\"},\"memberName\":{\"S\":\"alice\"},"
|
||||
+ "\"state\":{\"S\":\"ACTIVE\"},\"createdAt\":{\"S\":\"2026-07-14T00:00:02Z\"}}"
|
||||
};
|
||||
for (String item : items) {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"TableName\":\"" + TABLE + "\",\"Item\":" + item + "}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void queryAscendingOrdersByFullCompositeSortKey() {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.Query")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"IndexName": "%s",
|
||||
"KeyConditionExpression": "%s",
|
||||
"ExpressionAttributeNames": {"#st": "state"},
|
||||
"ExpressionAttributeValues": %s,
|
||||
"ScanIndexForward": true
|
||||
}
|
||||
""".formatted(TABLE, INDEX, KEY_CONDITION, EXPRESSION_ATTRIBUTE_VALUES))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Count", equalTo(3))
|
||||
.body("Items[0].createdAt.S", equalTo("2026-07-14T00:00:01Z"))
|
||||
.body("Items[1].createdAt.S", equalTo("2026-07-14T00:00:02Z"))
|
||||
.body("Items[2].createdAt.S", equalTo("2026-07-14T00:00:03Z"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void queryDescendingReversesFullCompositeSortKey() {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.Query")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"IndexName": "%s",
|
||||
"KeyConditionExpression": "%s",
|
||||
"ExpressionAttributeNames": {"#st": "state"},
|
||||
"ExpressionAttributeValues": %s,
|
||||
"ScanIndexForward": false
|
||||
}
|
||||
""".formatted(TABLE, INDEX, KEY_CONDITION, EXPRESSION_ATTRIBUTE_VALUES))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Count", equalTo(3))
|
||||
.body("Items[0].createdAt.S", equalTo("2026-07-14T00:00:03Z"))
|
||||
.body("Items[1].createdAt.S", equalTo("2026-07-14T00:00:02Z"))
|
||||
.body("Items[2].createdAt.S", equalTo("2026-07-14T00:00:01Z"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A paginated Query over a composite-sort-key index must surface a LastEvaluatedKey that carries
|
||||
* EVERY sort-key component, not just the first RANGE attribute. Emitting only {@code state}
|
||||
* (identical across these rows) loses composite key identity: the cursor no longer pins the row
|
||||
* it stopped on. This is the regression from PR review comment r3710297799 — pre-fix the cursor
|
||||
* omitted {@code createdAt}.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void paginatedQueryEmitsFullCompositeCursor() {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.Query")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"IndexName": "%s",
|
||||
"KeyConditionExpression": "%s",
|
||||
"ExpressionAttributeNames": {"#st": "state"},
|
||||
"ExpressionAttributeValues": %s,
|
||||
"ScanIndexForward": true,
|
||||
"Limit": 1
|
||||
}
|
||||
""".formatted(TABLE, INDEX, KEY_CONDITION, EXPRESSION_ATTRIBUTE_VALUES))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Count", equalTo(1))
|
||||
// First ascending row by the full composite key is createdAt=:01 (requestId b).
|
||||
.body("Items[0].createdAt.S", equalTo("2026-07-14T00:00:01Z"))
|
||||
// Cursor pins that exact row: index keys (both components), plus the base-table key.
|
||||
.body("LastEvaluatedKey.memberName.S", equalTo("alice"))
|
||||
.body("LastEvaluatedKey.state.S", equalTo("ACTIVE"))
|
||||
.body("LastEvaluatedKey.createdAt.S", equalTo("2026-07-14T00:00:01Z"))
|
||||
.body("LastEvaluatedKey.requestId.S", notNullValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Walking every page with Limit=1 must return all three rows in full composite order, each
|
||||
* exactly once, with the cursor advancing on every page (no repeat, no skip).
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void paginatedQueryWalksAllRowsExactlyOnceInCompositeOrder() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<String> collected = new ArrayList<>();
|
||||
Set<String> seenCursors = new HashSet<>();
|
||||
JsonNode exclusiveStartKey = null;
|
||||
int pages = 0;
|
||||
|
||||
do {
|
||||
String startClause = exclusiveStartKey == null
|
||||
? ""
|
||||
: ",\n\"ExclusiveStartKey\": " + mapper.writeValueAsString(exclusiveStartKey);
|
||||
String body = """
|
||||
{
|
||||
"TableName": "%s",
|
||||
"IndexName": "%s",
|
||||
"KeyConditionExpression": "%s",
|
||||
"ExpressionAttributeNames": {"#st": "state"},
|
||||
"ExpressionAttributeValues": %s,
|
||||
"ScanIndexForward": true,
|
||||
"Limit": 1%s
|
||||
}
|
||||
""".formatted(TABLE, INDEX, KEY_CONDITION, EXPRESSION_ATTRIBUTE_VALUES, startClause);
|
||||
|
||||
String responseBody = given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.Query")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().body().asString();
|
||||
|
||||
JsonNode root = mapper.readTree(responseBody);
|
||||
pages++;
|
||||
for (JsonNode item : root.path("Items")) {
|
||||
collected.add(item.path("createdAt").path("S").asText());
|
||||
}
|
||||
|
||||
JsonNode lek = root.path("LastEvaluatedKey");
|
||||
if (lek.isMissingNode() || lek.isNull()) {
|
||||
exclusiveStartKey = null;
|
||||
} else {
|
||||
assertNotNull(lek.get("createdAt"),
|
||||
"LastEvaluatedKey missing composite component createdAt: " + lek);
|
||||
String cursor = lek.toString();
|
||||
assertTrue(seenCursors.add(cursor),
|
||||
"LastEvaluatedKey repeated — pagination did not advance: " + cursor);
|
||||
exclusiveStartKey = lek;
|
||||
}
|
||||
} while (exclusiveStartKey != null && pages < 10);
|
||||
|
||||
assertEquals(List.of(
|
||||
"2026-07-14T00:00:01Z",
|
||||
"2026-07-14T00:00:02Z",
|
||||
"2026-07-14T00:00:03Z"), collected,
|
||||
"Expected all rows once, in full composite order");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -359,6 +360,66 @@ class DynamoDbServiceTest {
|
||||
.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression for floci-io/floci#1675: a GSI whose sort key is composite (more than one RANGE
|
||||
* attribute) must order by ALL sort-key attributes in schema order, so ScanIndexForward=false
|
||||
* yields the reverse of the full composite order. Previously only the first RANGE attribute
|
||||
* (here {@code state}, identical across the rows) was used, so {@code createdAt} never
|
||||
* participated and ordering/reversal were effectively ignored.
|
||||
*/
|
||||
@Test
|
||||
void queryOnCompositeSortKeyGsiRespectsScanIndexForward() {
|
||||
String region = "us-east-1";
|
||||
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(
|
||||
"memberIndex",
|
||||
List.of(
|
||||
new KeySchemaElement("memberName", "HASH"),
|
||||
new KeySchemaElement("state", "RANGE"),
|
||||
new KeySchemaElement("createdAt", "RANGE")),
|
||||
null, "ALL", null);
|
||||
service.createTable("Requests",
|
||||
List.of(new KeySchemaElement("requestId", "HASH")),
|
||||
List.of(
|
||||
new AttributeDefinition("requestId", "S"),
|
||||
new AttributeDefinition("memberName", "S"),
|
||||
new AttributeDefinition("state", "S"),
|
||||
new AttributeDefinition("createdAt", "S")),
|
||||
5L, 5L, List.of(gsi), region);
|
||||
|
||||
// Same memberName + state. Deliberately make base-table key order (requestId: a, b, c)
|
||||
// DISAGREE with createdAt order, so a correct result can only come from sorting on the
|
||||
// second composite component (createdAt) — not from incidental storage order.
|
||||
service.putItem("Requests", item("requestId", "a", "memberName", "alice",
|
||||
"state", "ACTIVE", "createdAt", "2026-07-14T00:00:03Z"), region);
|
||||
service.putItem("Requests", item("requestId", "b", "memberName", "alice",
|
||||
"state", "ACTIVE", "createdAt", "2026-07-14T00:00:01Z"), region);
|
||||
service.putItem("Requests", item("requestId", "c", "memberName", "alice",
|
||||
"state", "ACTIVE", "createdAt", "2026-07-14T00:00:02Z"), region);
|
||||
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":pk", attributeValue("S", "alice"));
|
||||
exprValues.set(":st", attributeValue("S", "ACTIVE"));
|
||||
exprValues.set(":from", attributeValue("S", "1970-01-01T00:00:00Z"));
|
||||
exprValues.set(":to", attributeValue("S", "2100-01-01T00:00:00Z"));
|
||||
String kce = "memberName = :pk AND state = :st AND createdAt BETWEEN :from AND :to";
|
||||
|
||||
DynamoDbService.QueryResult ascending = service.query("Requests", null, exprValues,
|
||||
kce, null, null, true, "memberIndex", null, null, region);
|
||||
assertEquals(
|
||||
List.of("2026-07-14T00:00:01Z", "2026-07-14T00:00:02Z", "2026-07-14T00:00:03Z"),
|
||||
ascending.items().stream()
|
||||
.map(result -> result.get("createdAt").get("S").asText())
|
||||
.toList());
|
||||
|
||||
DynamoDbService.QueryResult descending = service.query("Requests", null, exprValues,
|
||||
kce, null, null, false, "memberIndex", null, null, region);
|
||||
assertEquals(
|
||||
List.of("2026-07-14T00:00:03Z", "2026-07-14T00:00:02Z", "2026-07-14T00:00:01Z"),
|
||||
descending.items().stream()
|
||||
.map(result -> result.get("createdAt").get("S").asText())
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryAppliesFilterExpressionAfterKeyCondition() {
|
||||
String region = "eu-west-1";
|
||||
|
||||
Reference in new issue
Block a user