fix(dynamodb): recognize every HASH attribute of a composite GSI partition key (#2474)

Query only validated/matched the first HASH attribute of a GSI's
partition key, ignoring the rest.

Closes #2461

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-08-22 17:29:20 -05:00
1 parent 0397826b90
commit 768e96a33f
5 files changed
+167 -35

No files matched your search

@@ -43,11 +43,14 @@ record DynamoDbAccessPath(String indexName, Kind kind, List<KeySchemaElement> ke
}
String partitionKeyName() {
return partitionKeyNames().getFirst();
}
List<String> partitionKeyNames() {
return keySchema.stream()
.filter(key -> "HASH".equals(key.getKeyType()))
.map(KeySchemaElement::getAttributeName)
.findFirst()
.orElseThrow();
.toList();
}
List<String> sortKeyNames() {
@@ -89,9 +89,10 @@ final class DynamoDbAccessPathValidator {
List<Expr> conditions = root instanceof AndExpr and
? and.operands() : List.of(root);
String partitionKey = accessPath.partitionKeyName();
List<String> partitionKeys = accessPath.partitionKeyNames();
Set<String> partitionKeySet = Set.copyOf(partitionKeys);
Set<String> sortKeys = Set.copyOf(accessPath.sortKeyNames());
int partitionConditions = 0;
Set<String> conditionedPartitionKeys = new HashSet<>();
String partitionKeyValuePlaceholder = null;
Set<String> conditionedAttributes = new HashSet<>();
@@ -101,12 +102,14 @@ final class DynamoDbAccessPathValidator {
throw new AwsException("ValidationException",
"KeyConditionExpressions must only contain one condition per key", 400);
}
if (partitionKey.equals(attribute)) {
partitionConditions++;
if (attribute != null && partitionKeySet.contains(attribute)) {
if (!isPartitionKeyEquality(condition)) {
throw new AwsException("ValidationException", "Query key condition not supported", 400);
}
partitionKeyValuePlaceholder = ((PlaceholderOperand) ((CompareExpr) condition).right()).name();
conditionedPartitionKeys.add(attribute);
if (attribute.equals(partitionKeys.getFirst())) {
partitionKeyValuePlaceholder = ((PlaceholderOperand) ((CompareExpr) condition).right()).name();
}
} else if (attribute != null && sortKeys.contains(attribute)) {
if (!isSupportedSortKeyCondition(condition)) {
throw new AwsException("ValidationException", "Query key condition not supported", 400);
@@ -116,13 +119,12 @@ final class DynamoDbAccessPathValidator {
}
}
if (partitionConditions == 0) {
if (!conditionedPartitionKeys.containsAll(partitionKeySet)) {
String missing = partitionKeys.stream()
.filter(pk -> !conditionedPartitionKeys.contains(pk))
.findFirst().orElseThrow();
throw new AwsException("ValidationException",
"Query condition missed key schema element: " + partitionKey, 400);
}
if (partitionConditions > 1) {
throw new AwsException("ValidationException",
"KeyConditionExpressions must only contain one condition per key", 400);
"Query condition missed key schema element: " + missing, 400);
}
return partitionKeyValuePlaceholder;
}
@@ -165,18 +167,21 @@ final class DynamoDbAccessPathValidator {
}
private static void validateLegacyKeyConditions(DynamoDbAccessPath accessPath, JsonNode keyConditions) {
String partitionKey = accessPath.partitionKeyName();
if (keyConditions == null || !keyConditions.has(partitionKey)) {
throw new AwsException("ValidationException",
"Query condition missed key schema element: " + partitionKey, 400);
List<String> partitionKeys = accessPath.partitionKeyNames();
for (String partitionKey : partitionKeys) {
if (keyConditions == null || !keyConditions.has(partitionKey)) {
throw new AwsException("ValidationException",
"Query condition missed key schema element: " + partitionKey, 400);
}
}
Set<String> partitionKeySet = Set.copyOf(partitionKeys);
Set<String> sortKeys = Set.copyOf(accessPath.sortKeyNames());
keyConditions.fields().forEachRemaining(entry -> {
String attribute = entry.getKey();
String operator = entry.getValue().path("ComparisonOperator").asText();
int values = entry.getValue().path("AttributeValueList").size();
if (partitionKey.equals(attribute)) {
if (partitionKeySet.contains(attribute)) {
if (!"EQ".equals(operator) || values != 1) {
throw new AwsException("ValidationException", "Query key condition not supported", 400);
}
@@ -737,6 +737,7 @@ public class DynamoDbService {
String partitionKeyValuePlaceholder = DynamoDbAccessPathValidator.validateQuery(
accessPath, keyConditions, keyConditionExpression, filterExpression, null, exprAttrNames);
String pkName = accessPath.partitionKeyName();
List<String> pkNames = accessPath.partitionKeyNames();
String skName = accessPath.sortKeyName();
List<String> sortKeyNames = accessPath.sortKeyNames();
@@ -746,21 +747,17 @@ public class DynamoDbService {
List<JsonNode> results = new ArrayList<>();
if (keyConditions != null) {
// Legacy KeyConditions format
JsonNode pkCondition = keyConditions.get(pkName);
String pkValue = extractComparisonValue(pkCondition);
for (JsonNode item : items.values()) {
if (!item.has(pkName)) continue;
if (matchesAttributeValue(item.get(pkName), pkValue)) {
if (skName != null && keyConditions.has(skName)) {
JsonNode skCondition = keyConditions.get(skName);
if (matchesKeyCondition(item.get(skName), skCondition)) {
results.add(item);
}
} else {
boolean partitionKeyMatches = pkNames.stream().allMatch(name -> item.has(name)
&& matchesAttributeValue(item.get(name), extractComparisonValue(keyConditions.get(name))));
if (!partitionKeyMatches) continue;
if (skName != null && keyConditions.has(skName)) {
JsonNode skCondition = keyConditions.get(skName);
if (matchesKeyCondition(item.get(skName), skCondition)) {
results.add(item);
}
} else {
results.add(item);
}
}
} else if (keyConditionExpression != null) {
@@ -24,6 +24,7 @@ class DynamoDbAccessPathValidatorTest {
private DynamoDbAccessPath tablePath;
private DynamoDbAccessPath gsiPath;
private DynamoDbAccessPath lsiPath;
private DynamoDbAccessPath compositePkGsiPath;
@BeforeEach
void setUp() {
@@ -31,11 +32,18 @@ class DynamoDbAccessPathValidatorTest {
table.setKeySchema(List.of(
new KeySchemaElement("pk", "HASH"),
new KeySchemaElement("sk", "RANGE")));
table.setGlobalSecondaryIndexes(List.of(new GlobalSecondaryIndex(
"status-index",
List.of(new KeySchemaElement("status", "HASH"),
new KeySchemaElement("createdAt", "RANGE")),
null, "INCLUDE", List.of("summary"))));
table.setGlobalSecondaryIndexes(List.of(
new GlobalSecondaryIndex(
"status-index",
List.of(new KeySchemaElement("status", "HASH"),
new KeySchemaElement("createdAt", "RANGE")),
null, "INCLUDE", List.of("summary")),
new GlobalSecondaryIndex(
"tenant-region-index",
List.of(new KeySchemaElement("tenantId", "HASH"),
new KeySchemaElement("region", "HASH"),
new KeySchemaElement("createdAt", "RANGE")),
null, "ALL", null)));
table.setLocalSecondaryIndexes(List.of(new LocalSecondaryIndex(
"alternate-index",
List.of(new KeySchemaElement("pk", "HASH"),
@@ -45,6 +53,45 @@ class DynamoDbAccessPathValidatorTest {
tablePath = DynamoDbAccessPath.resolve(table, null);
gsiPath = DynamoDbAccessPath.resolve(table, "status-index");
lsiPath = DynamoDbAccessPath.resolve(table, "alternate-index");
compositePkGsiPath = DynamoDbAccessPath.resolve(table, "tenant-region-index");
}
@Test
void acceptsCompositePartitionKeyQueryWhenEveryHashAttributeHasEquality() {
assertDoesNotThrow(() -> validateExpression(compositePkGsiPath,
"tenantId = :t AND region = :r"));
assertDoesNotThrow(() -> validateExpression(compositePkGsiPath,
"region = :r AND tenantId = :t"));
}
@Test
void rejectsCompositePartitionKeyQueryMissingOneHashAttribute() {
AwsException error = assertThrows(AwsException.class,
() -> validateExpression(compositePkGsiPath, "tenantId = :t"));
assertEquals("Query condition missed key schema element: region", error.getMessage());
}
@Test
void rejectsCompositePartitionKeyQueryWithNonEqualityCondition() {
assertThrows(AwsException.class, () -> validateExpression(compositePkGsiPath,
"tenantId = :t AND region > :r"));
}
@Test
void validatesLegacyCompositePartitionKeyConditions() {
ObjectNode valid = mapper.createObjectNode();
valid.set("tenantId", legacyCondition("EQ", attributeValues("acme")));
valid.set("region", legacyCondition("EQ", attributeValues("us")));
assertDoesNotThrow(() -> DynamoDbAccessPathValidator.validateQuery(
compositePkGsiPath, valid, null, null, null, null));
ObjectNode missingRegion = mapper.createObjectNode();
missingRegion.set("tenantId", legacyCondition("EQ", attributeValues("acme")));
AwsException error = assertThrows(AwsException.class,
() -> DynamoDbAccessPathValidator.validateQuery(
compositePkGsiPath, missingRegion, null, null, null, null));
assertEquals("Query condition missed key schema element: region", error.getMessage());
}
@Test
@@ -532,6 +532,86 @@ class DynamoDbServiceTest {
5L, 5L, List.of(gsi), region);
}
private void createTableWithCompositePartitionKeyGsi(String region) {
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(
"tenantRegionIndex",
List.of(
new KeySchemaElement("tenantId", "HASH"),
new KeySchemaElement("region", "HASH"),
new KeySchemaElement("createdAt", "RANGE")),
null, "ALL", null);
service.createTable("Accounts",
List.of(new KeySchemaElement("id", "HASH")),
List.of(
new AttributeDefinition("id", "S"),
new AttributeDefinition("tenantId", "S"),
new AttributeDefinition("region", "S"),
new AttributeDefinition("createdAt", "S")),
5L, 5L, List.of(gsi), region);
service.putItem("Accounts",
item("id", "1", "tenantId", "acme", "region", "us", "createdAt", "2026-01-01"), region);
service.putItem("Accounts",
item("id", "2", "tenantId", "acme", "region", "eu", "createdAt", "2026-01-02"), region);
}
@Test
void queryOnCompositePartitionKeyGsiRequiresEveryHashAttribute() {
String region = "eu-west-1";
createTableWithCompositePartitionKeyGsi(region);
ObjectNode exprValues = mapper.createObjectNode();
exprValues.set(":t", attributeValue("S", "acme"));
AwsException error = assertThrows(AwsException.class, () -> service.query(
"Accounts", null, exprValues, "tenantId = :t",
null, null, null, "tenantRegionIndex", null, null, region));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void queryOnCompositePartitionKeyGsiFiltersByEveryHashAttribute() {
String region = "eu-west-1";
createTableWithCompositePartitionKeyGsi(region);
ObjectNode exprValues = mapper.createObjectNode();
exprValues.set(":t", attributeValue("S", "acme"));
exprValues.set(":r", attributeValue("S", "us"));
DynamoDbService.QueryResult results = service.query(
"Accounts", null, exprValues, "tenantId = :t AND region = :r",
null, null, null, "tenantRegionIndex", null, null, region);
assertEquals(List.of("1"), results.items().stream()
.map(item -> item.get("id").get("S").asText())
.toList());
}
@Test
void legacyQueryOnCompositePartitionKeyGsiFiltersByEveryHashAttribute() {
String region = "eu-west-1";
createTableWithCompositePartitionKeyGsi(region);
ObjectNode keyConditions = mapper.createObjectNode();
keyConditions.set("tenantId", legacyEqCondition("acme"));
keyConditions.set("region", legacyEqCondition("us"));
DynamoDbService.QueryResult results = service.query("Accounts", keyConditions, null, null,
null, null, null, "tenantRegionIndex", null, null, region);
assertEquals(List.of("1"), results.items().stream()
.map(item -> item.get("id").get("S").asText())
.toList());
}
private ObjectNode legacyEqCondition(String value) {
ObjectNode condition = mapper.createObjectNode();
condition.put("ComparisonOperator", "EQ");
var attrList = mapper.createArrayNode();
attrList.add(attributeValue("S", value));
condition.set("AttributeValueList", attrList);
return condition;
}
@Test
void queryAppliesFilterExpressionAfterKeyCondition() {
String region = "eu-west-1";