fix(dynamodb): scan when a PartiQL branch names the sort key twice (#8728)

* fix(dynamodb): scan when a PartiQL branch names the sort key twice
* fix(dynamodb): stop at the first PartiQL branch that names the sort key twice
* chore(dynamodb): keep the PartiQL two sort-key rule in one place
* chore(dynamodb): test PartiQL index reads that name the index sort key twice
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-17 18:49:34 -04:00
1 parent a9cb14b2ea
commit 77a4a1ff65
3 files changed
+179 -20

No files matched your search

@@ -101,11 +101,11 @@ class DynamoDbPartiQLHandler {
Optional<List<Cond.Leaf>> sortKeyReads = routing.partition() == null
? Optional.empty()
: keys.sortKeyReads(descending);
if (!stmt.orderBy().isEmpty()) {
requireOrderByShape(stmt, accessPath, keys.readsWholeTable());
}
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()) {
@@ -361,7 +361,6 @@ class DynamoDbPartiQLHandler {
private Page readOrdered(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,
Routing routing, JsonNode after, Integer limit, String region) {
requireOrderByShape(stmt, accessPath);
List<JsonNode> rows = new ArrayList<>();
long scannedBytes = 0;
List<JsonNode> scannedItems = new ArrayList<>();
@@ -388,7 +387,8 @@ class DynamoDbPartiQLHandler {
return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, List.of(scannedBytes), scannedItems);
}
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath) {
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath,
boolean readsWholeTable) {
if (stmt.where().isEmpty()) {
throw new AwsException("ValidationException",
"Must have WHERE clause in the statement when using ORDER BY clause.", 400);
@@ -401,7 +401,9 @@ class DynamoDbPartiQLHandler {
}
}
String pkName = accessPath.partitionKeyName();
int hashKeyConditions = stmt.where().stream().mapToInt(c -> hashKeyConditionCount(c, pkName)).sum();
int hashKeyConditions = readsWholeTable
? 0
: stmt.where().stream().mapToInt(c -> hashKeyConditionCount(c, pkName)).sum();
if (hashKeyConditions == 0) {
throw new AwsException("ValidationException",
"Must have at least one non-optional hash key condition in WHERE clause when using ORDER BY clause.",
@@ -12,6 +12,7 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -32,6 +33,7 @@ final class DynamoDbPartiQLKeyPlan {
private final boolean everyBranchPinsPartition;
private final List<Cond.Leaf> keyConditions = new ArrayList<>();
private final List<Branch> branches;
private final boolean readsWholeTable;
private boolean tooManyBranches;
private record Spread(List<Cond.Leaf> keyConditions, List<Cond> filters) {
@@ -44,11 +46,16 @@ final class DynamoDbPartiQLKeyPlan {
}
}
private record Branch(Key partition, PVal partitionValue, Range sortRange, List<Cond.Leaf> sortConditions,
List<Cond> filters) {
private record Branch(Key partition, PVal partitionValue, Range sortRange, List<Cond.Leaf> keyConditions,
List<Cond.Leaf> sortConditions, List<Cond> filters) {
static final Comparator<Branch> IN_KEY_ORDER = Comparator.comparing(Branch::partition)
.thenComparing(Branch::sortRange, Range.BY_LOWER);
// A key condition holds one sort-key condition, so a branch that names two reads the whole table.
boolean readsWholeTable() {
return sortConditions.size() > 1;
}
}
DynamoDbPartiQLKeyPlan(List<Cond> where, DynamoDbAccessPath accessPath, TableDefinition table) {
@@ -59,14 +66,29 @@ final class DynamoDbPartiQLKeyPlan {
this.everyBranchPinsPartition = everyBranchPinsPartition(conditions);
List<Spread> spread = spread(conditions);
this.branches = tooManyBranches
? List.of(new Branch(null, null, Range.ALL, List.of(), where))
? List.of(new Branch(null, null, Range.ALL, List.of(), List.of(), where))
: spread.stream().map(this::branchOf).toList();
this.readsWholeTable = branches.stream().anyMatch(Branch::readsWholeTable);
}
/** A statement with a branch that DynamoDB cannot read by key is read as a scan of the whole table or index. */
boolean readsWholeTable() {
return readsWholeTable;
}
void requireKeyTypesMatchSchema() {
// Only the branches read by key check the types of their key values.
Set<Cond.Leaf> readByKey = branches.stream()
.filter(branch -> !branch.readsWholeTable())
.flatMap(branch -> branch.keyConditions().stream())
.collect(Collectors.toSet());
for (Cond.Leaf condition : keyConditions) {
String name = condition.path().root();
for (PVal value : values(condition)) {
Cond.Leaf held = condition instanceof Cond.In in ? new Cond.Eq(in.path(), value) : condition;
if (readsWholeTable && !readByKey.contains(held)) {
continue;
}
String type = DynamoDbPartiQLParser.typeCode(value);
if (!DynamoDbPartiQLParser.ORDERED_TYPES.contains(type)) {
throw DynamoDbPartiQLParser.validationEx(
@@ -85,7 +107,8 @@ final class DynamoDbPartiQLKeyPlan {
}
void requireReadsWithinLimit() {
if (everyBranchPinsPartition && (tooManyBranches || branches.size() > MAX_DECOMPOSED_READS)) {
if (everyBranchPinsPartition && !readsWholeTable
&& (tooManyBranches || branches.size() > MAX_DECOMPOSED_READS)) {
throw DynamoDbPartiQLParser.validationEx("Too many decomposed read operations for a given query.");
}
}
@@ -215,7 +238,7 @@ final class DynamoDbPartiQLKeyPlan {
}
private boolean keyed() {
return branches.stream().allMatch(branch -> branch.partition() != null);
return !readsWholeTable && branches.stream().allMatch(branch -> branch.partition() != null);
}
private Branch branchOf(Spread spread) {
@@ -240,8 +263,8 @@ final class DynamoDbPartiQLKeyPlan {
}
}
}
return new Branch(conflicting ? null : partition, partitionValue, sortRange, sortConditions,
spread.filters());
return new Branch(conflicting ? null : partition, partitionValue, sortRange, spread.keyConditions(),
sortConditions, spread.filters());
}
private List<Spread> spread(Cond cond) {
@@ -264,20 +287,33 @@ final class DynamoDbPartiQLKeyPlan {
yield spread;
}
case Cond.Or or when anyLeaf(or, this::isKeyCondition) -> {
List<Spread> spread = or.operands().stream().flatMap(operand -> spread(operand).stream()).toList();
tooManyBranches |= spread.size() > MAX_BRANCHES;
yield spread;
List<List<Spread>> operands = or.operands().stream().map(this::spread).toList();
yield upToTheFirstScan(operands.stream().flatMap(List::stream));
}
default -> List.of(new Spread(List.of(), List.of(cond)));
};
}
private List<Spread> and(List<Spread> left, List<Spread> right) {
if ((long) left.size() * right.size() > MAX_BRANCHES) {
tooManyBranches = true;
return left;
return upToTheFirstScan(left.stream().flatMap(l -> right.stream().map(l::and)));
}
// DynamoDB walks the branches in written order and scans from the first one that names the sort key
// twice, so it never reads the branches after that one by key.
private List<Spread> upToTheFirstScan(Stream<Spread> branches) {
List<Spread> kept = new ArrayList<>();
for (Iterator<Spread> each = branches.iterator(); each.hasNext(); ) {
Spread branch = each.next();
kept.add(branch);
if (branchOf(branch).readsWholeTable()) {
break;
}
if (kept.size() > MAX_BRANCHES) {
tooManyBranches = true;
break;
}
}
return left.stream().flatMap(l -> right.stream().map(l::and)).toList();
return kept;
}
private static boolean anyLeaf(Cond cond, Predicate<Cond.Leaf> test) {