fix(dynamodb): merge shared-prefix projection paths and compact list indices (#3072)

* fix(dynamodb): merge shared-prefix projection paths and compact list indices

ProjectionExpression paths that share a prefix now merge into one
reconstructed structure instead of the first or last path winning.
Projected list indices compact to ascending source order, so l[2], l[0]
returns both elements as a two element list.

Matches DynamoDB behavior verified by the paritysuite dynamodb-conformance
tier1 suite (8 tests).

* fix(dynamodb): reject malformed and out-of-range projection list indices as ValidationException

* refactor(dynamodb): simplify projection evaluator internals and tests

* chore(dynamodb): brace single-line conditionals in ProjectionEvaluator

* fix(dynamodb): reject leading-zero projection list indices like real DynamoDB

* fix(dynamodb): accept only ascii digits in projection list indices
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-05 12:52:49 -04:00
1 parent 0a57f0ac08
commit 5c8cff61b8
2 files changed
+321 -59

No files matched your search

@@ -7,8 +7,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Applies a DynamoDB ProjectionExpression to a result item, returning a new
@@ -18,24 +21,32 @@ final class ProjectionEvaluator {
private static final ObjectMapper MAPPER = new ObjectMapper();
// The highest list index real DynamoDB accepts in a document path.
private static final long MAX_LIST_INDEX = 4_294_967_294L;
private ProjectionEvaluator() {}
/**
* Returns a new ObjectNode containing only the paths named in the expression.
* Resolves #alias references via exprAttrNames. Handles dot-path and [n] list index segments.
* Paths sharing a prefix merge into one reconstructed structure; projected list indices
* compact to ascending source order, the way DynamoDB reconstructs projected items.
*/
static ObjectNode project(JsonNode item, String projectionExpression, JsonNode exprAttrNames) {
if (item == null || projectionExpression == null || projectionExpression.isBlank()) {
return (ObjectNode) item;
}
validateExpression(projectionExpression);
ObjectNode result = MAPPER.createObjectNode();
PathTrie root = new PathTrie();
for (String rawPath : splitProjectionPaths(projectionExpression)) {
List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);
if (segments.isEmpty()) continue;
copyPath(item, result, segments, 0);
if (segments.isEmpty()) {
continue;
}
root.insert(segments);
}
return result;
ObjectNode projected = projectMapEntries(item, root);
return projected != null ? projected : MAPPER.createObjectNode();
}
/**
@@ -67,13 +78,16 @@ final class ProjectionEvaluator {
if (expression == null || expression.isBlank()) return;
char first = expression.charAt(0);
if (!Character.isLetterOrDigit(first) && first != '#' && first != '_') {
String token = String.valueOf(first);
String near = expression.length() > 2 ? expression.substring(1, 3) : expression.substring(1);
throw new AwsException("ValidationException",
"Invalid " + expressionType + ": Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
throw syntaxError(expressionType, String.valueOf(first), near);
}
}
private static AwsException syntaxError(String expressionType, String token, String near) {
return new AwsException("ValidationException",
"Invalid " + expressionType + ": Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
}
static void validateExpression(String expression) {
validateSyntax(expression, "ProjectionExpression");
DynamoDbReservedWords.check(expression, "ProjectionExpression");
@@ -120,6 +134,7 @@ final class ProjectionEvaluator {
while (i < rest.length() && rest.charAt(i) == '[') {
int close = rest.indexOf(']', i);
if (close < 0) break;
validateListIndex(rest.substring(i + 1, close));
segments.add(rest.substring(i, close + 1)); // e.g. "[0]"
i = close + 1;
}
@@ -130,6 +145,33 @@ final class ProjectionEvaluator {
return segments;
}
// DynamoDB rejects a non-numeric bracket segment and a leading zero as syntax
// errors, and a numeric index above 4294967294 as out of the allowable range,
// all at expression level. Verified on real DynamoDB (us-east-1, 2026-09-05).
private static void validateListIndex(String content) {
if (content.isEmpty()) {
throw syntaxError("ProjectionExpression", "]", "[]");
}
final var contentLength = content.length();
for (var i = 0; i < contentLength; i++) {
var c = content.charAt(i);
if (c < '0' || '9' < c) {
var near = "[" + content + "]";
throw syntaxError("ProjectionExpression", String.valueOf(c),
near.substring(0, Math.min(3, near.length())));
}
}
if (contentLength > 1 && content.charAt(0) == '0') {
throw syntaxError("ProjectionExpression", "0",
content.substring(0, Math.min(3, contentLength)));
}
if (contentLength > 10 || Long.parseLong(content) > MAX_LIST_INDEX) {
throw new AwsException("ValidationException",
"Invalid ProjectionExpression: List index is not within the allowable range; "
+ "index: [" + content + "]", 400);
}
}
private static String resolveSegment(String seg, JsonNode exprAttrNames) {
if (seg.startsWith("#") && exprAttrNames != null) {
JsonNode resolved = exprAttrNames.get(seg);
@@ -140,61 +182,88 @@ final class ProjectionEvaluator {
// ── Tree walking ──
private static void copyPath(JsonNode src, ObjectNode dest, List<String> segments, int idx) {
if (idx >= segments.size()) return;
String seg = segments.get(idx);
/**
* Merged view of every projected path. Map-name children and list-index children are
* kept separately; index children stay sorted so a projected list compacts to
* ascending source order. A node marked terminal ends a path and copies the whole
* subtree it points at.
*/
private static final class PathTrie {
private boolean terminal;
private final Map<String, PathTrie> names = new LinkedHashMap<>();
// Long keys: the allowable index range (up to 4294967294) exceeds Integer.MAX_VALUE.
private final TreeMap<Long, PathTrie> indices = new TreeMap<>();
if (seg.matches("\\[\\d+\\]")) {
// List index at root level — handled by the caller
return;
}
JsonNode child = src.get(seg);
if (child == null) return;
if (idx == segments.size() - 1) {
// Leaf: deep-copy to avoid placing a live source reference into the
// destination, which could be mutated by a subsequent sibling path.
dest.set(seg, child.deepCopy());
} else {
String nextSeg = segments.get(idx + 1);
if (nextSeg.matches("\\[\\d+\\]")) {
// Next is a list index — extract just that element.
// Reuse existing wrapper if already projected (same fix as the M branch).
int listIdx = Integer.parseInt(nextSeg.substring(1, nextSeg.length() - 1));
JsonNode listNode = child.has("L") ? child.get("L") : child;
if (listNode.isArray() && listIdx < listNode.size() && !dest.has(seg)) {
JsonNode element = listNode.get(listIdx);
// Build {"L": [element]} wrapper
ObjectNode wrapper = MAPPER.createObjectNode();
ArrayNode newList = MAPPER.createArrayNode();
newList.add(element);
wrapper.set("L", newList);
dest.set(seg, wrapper);
void insert(List<String> segments) {
PathTrie node = this;
for (String seg : segments) {
if (seg.startsWith("[")) {
long idx = Long.parseLong(seg.substring(1, seg.length() - 1));
node = node.indices.computeIfAbsent(idx, k -> new PathTrie());
} else {
node = node.names.computeIfAbsent(seg, k -> new PathTrie());
}
} else if (child.has("M")) {
// Nested map — reuse existing projected map if present
ObjectNode existing = dest.has(seg) && dest.get(seg).has("M")
? (ObjectNode) dest.get(seg).get("M") : null;
ObjectNode nestedDest = existing != null ? existing : MAPPER.createObjectNode();
copyPath(child.get("M"), nestedDest, segments, idx + 1);
if (existing == null) {
ObjectNode wrapper = MAPPER.createObjectNode();
wrapper.set("M", nestedDest);
dest.set(seg, wrapper);
}
} else if (child.isObject()) {
// Reuse existing nested object if present
ObjectNode existing = dest.has(seg) && dest.get(seg).isObject()
? (ObjectNode) dest.get(seg) : null;
ObjectNode nestedDest = existing != null ? existing : MAPPER.createObjectNode();
copyPath(child, nestedDest, segments, idx + 1);
if (existing == null) {
dest.set(seg, nestedDest);
}
} else {
dest.set(seg, child);
}
node.terminal = true;
}
}
/**
* Projects a typed attribute value through a trie node. Returns null when nothing
* under this value matches, so the caller can drop the branch entirely.
*/
private static JsonNode projectValue(JsonNode src, PathTrie node) {
if (node.terminal) {
return src.deepCopy();
}
if (!node.indices.isEmpty() && src.has("L")) {
JsonNode list = src.get("L");
ArrayNode projectedList = MAPPER.createArrayNode();
for (Map.Entry<Long, PathTrie> entry : node.indices.entrySet()) {
long idx = entry.getKey();
if (idx >= list.size()) {
continue;
}
JsonNode projected = projectValue(list.get((int) idx), entry.getValue());
if (projected != null) {
projectedList.add(projected);
}
}
if (projectedList.isEmpty()) {
return null;
}
ObjectNode wrapper = MAPPER.createObjectNode();
wrapper.set("L", projectedList);
return wrapper;
}
if (!node.names.isEmpty()) {
if (src.has("M")) {
JsonNode projectedMap = projectMapEntries(src.get("M"), node);
if (projectedMap == null) {
return null;
}
ObjectNode wrapper = MAPPER.createObjectNode();
wrapper.set("M", projectedMap);
return wrapper;
}
// Defensive fallback for plain (non-DynamoDB-typed) nested objects.
return projectMapEntries(src, node);
}
return null;
}
private static ObjectNode projectMapEntries(JsonNode map, PathTrie node) {
ObjectNode projectedMap = MAPPER.createObjectNode();
for (Map.Entry<String, PathTrie> entry : node.names.entrySet()) {
JsonNode child = map.get(entry.getKey());
if (child == null) {
continue;
}
JsonNode projected = projectValue(child, entry.getValue());
if (projected != null) {
projectedMap.set(entry.getKey(), projected);
}
}
return projectedMap.isEmpty() ? null : projectedMap;
}
}