fix(dynamodb): measure item size and UpdateItem statements like DynamoDB (#5934)

* fix(dynamodb): measure item size and UpdateItem statements like DynamoDB

DynamoDB sizes a list or map at 3 bytes plus 1 per element, and a string
or binary set by its members alone.

An UpdateExpression is also measured as a statement. Each SET or ADD costs
19 bytes and each REMOVE or DELETE 1, on top of 3 for the update. Target
paths count once per shared prefix, 4 bytes per parent plus each key or
index digit. A SET also pays for every operand it reads: a value by its
size, a path at 1 plus 14 per element, list_append 37, if_not_exists 39,
plus 34 and minus 37. An ADD pays for its value. AttributeUpdates is
measured by the finished item only.

Closes #4339

* fix(dynamodb): refuse an unclosed call in an UpdateExpression

An UpdateExpression that ends inside a function call or a group, such as
"SET a = list_append(l, :v", reached the statement size check and failed
with a 500. DynamoDB refuses it before the table lookup with a syntax error
at <EOF>, near the raw text from the last token on. UpdateItem wraps the
message in the validation envelope and TransactWriteItems does not.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-18 20:56:48 -04:00
1 parent 5306e0e470
commit 3b7782e583
5 files changed
+425 -88

No files matched your search

@@ -7,9 +7,11 @@ import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* Calculates DynamoDB item size and enforces the 400KB limit.
@@ -20,12 +22,20 @@ final class DynamoDbItemSize {
static final String UPDATE_EXCEEDED = "Item size to update has exceeded the maximum allowed size";
// UpdateItem measures what the statement writes, name and value, not the item it stores,
// and charges these on top. Every other surface measures the finished item.
// An UpdateExpression is also measured as a statement: these per action, the target paths
// with a shared prefix counted once, and every operand a SET reads or an ADD writes.
// Every other surface, AttributeUpdates included, measures only the finished item.
private static final int UPDATE_COST = 3;
private static final int SET_OR_ADD_COST = 19;
private static final int REMOVE_OR_DELETE_COST = 2;
private static final int LIST_INDEX_COST = 1;
private static final int REMOVE_OR_DELETE_COST = 1;
private static final int TARGET_CONTAINER_COST = 4;
private static final int OPERAND_PATH_COST = 1;
private static final int OPERAND_PATH_ELEMENT_COST = 14;
private static final int PLUS_COST = 34;
private static final int MINUS_COST = 37;
private static final int LIST_APPEND_COST = 37;
private static final int IF_NOT_EXISTS_COST = 39;
private static final int CONTAINER_COST = 3;
private static final int MAX_NUMBER_PAIRS = 20;
private DynamoDbItemSize() {}
@@ -45,23 +55,13 @@ final class DynamoDbItemSize {
return calculateItemSize(item) <= MAX_ITEM_SIZE;
}
static boolean updateItemWithinLimit(JsonNode item, Set<String> writtenAttributes, int actionCost) {
int total = 0;
int written = 0;
Iterator<Map.Entry<String, JsonNode>> fields = item.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
int size = utf8Length(entry.getKey()) + attributeValueSize(entry.getValue());
total += size;
if (writtenAttributes.contains(entry.getKey())) {
written += size;
}
}
return total <= MAX_ITEM_SIZE && written + actionCost <= MAX_ITEM_SIZE;
static boolean updateItemWithinLimit(JsonNode item, int statementSize) {
return calculateItemSize(item) <= MAX_ITEM_SIZE && statementSize <= MAX_ITEM_SIZE;
}
static int updateExpressionCost(String expression) {
int cost = UPDATE_COST;
static int updateStatementSize(String expression, Function<String, List<Object>> paths, JsonNode values) {
int size = UPDATE_COST;
PathTree targets = new PathTree();
String remaining = expression.trim().replaceAll("\\s+", " ");
while (!remaining.isEmpty()) {
String keyword = remaining.substring(0, Math.max(remaining.indexOf(' '), 0)).toUpperCase(Locale.ROOT);
@@ -71,37 +71,95 @@ final class DynamoDbItemSize {
remaining = nextClause < 0 ? "" : body.substring(nextClause);
while (!actions.isBlank()) {
int comma = DynamoDbService.findNextComma(actions);
cost += actionCost(keyword, comma < 0 ? actions : actions.substring(0, comma));
String action = (comma < 0 ? actions : actions.substring(0, comma)).trim();
size += actionSize(keyword, action, targets, paths, values);
actions = comma < 0 ? "" : actions.substring(comma + 1);
}
}
return cost;
return size + targets.size();
}
static int attributeUpdatesCost(JsonNode attributeUpdates) {
int cost = UPDATE_COST;
if (attributeUpdates == null || !attributeUpdates.isObject()) {
return cost;
}
for (JsonNode update : attributeUpdates) {
cost += "DELETE".equals(update.path("Action").asText("PUT"))
? REMOVE_OR_DELETE_COST : SET_OR_ADD_COST;
}
return cost;
}
private static int actionCost(String clause, String action) {
private static int actionSize(String clause, String action, PathTree targets,
Function<String, List<Object>> paths, JsonNode values) {
return switch (clause) {
case "SET" -> SET_OR_ADD_COST + (writesListElement(action) ? LIST_INDEX_COST : 0);
case "ADD" -> SET_OR_ADD_COST;
default -> REMOVE_OR_DELETE_COST;
case "SET" -> {
int assignment = action.indexOf('=');
targets.add(paths.apply(action.substring(0, assignment)));
yield SET_OR_ADD_COST + operandSize(action.substring(assignment + 1), paths, values);
}
case "ADD" -> {
String[] parts = action.split(" ", 2);
targets.add(paths.apply(parts[0]));
yield SET_OR_ADD_COST + operandSize(parts[1], paths, values);
}
default -> {
targets.add(paths.apply(action.split(" ", 2)[0]));
yield REMOVE_OR_DELETE_COST;
}
};
}
private static boolean writesListElement(String action) {
int bracket = action.indexOf('[');
int assignment = action.indexOf('=');
return bracket >= 0 && (assignment < 0 || bracket < assignment);
private static int operandSize(String operand, Function<String, List<Object>> paths, JsonNode values) {
String expr = DynamoDbService.stripOuterParens(operand);
int operator = DynamoDbService.findArithmeticOperator(expr);
if (operator >= 0) {
return (expr.charAt(operator) == '+' ? PLUS_COST : MINUS_COST)
+ operandSize(expr.substring(0, operator), paths, values)
+ operandSize(expr.substring(operator + 1), paths, values);
}
String lower = expr.toLowerCase(Locale.ROOT);
if (DynamoDbService.startsWithFunctionCall(lower, "list_append")) {
return LIST_APPEND_COST + argumentsSize(expr, paths, values);
}
if (DynamoDbService.startsWithFunctionCall(lower, "if_not_exists")) {
return IF_NOT_EXISTS_COST + argumentsSize(expr, paths, values);
}
if (expr.startsWith(":")) {
return values == null ? 0 : attributeValueSize(values.get(expr));
}
int size = OPERAND_PATH_COST;
for (Object element : paths.apply(expr)) {
size += OPERAND_PATH_ELEMENT_COST + pathElementSize(element);
}
return size;
}
private static int argumentsSize(String call, Function<String, List<Object>> paths, JsonNode values) {
String arguments = call.substring(call.indexOf('(') + 1, call.lastIndexOf(')'));
int size = 0;
while (!arguments.isBlank()) {
int comma = DynamoDbService.findNextComma(arguments);
size += operandSize(comma < 0 ? arguments : arguments.substring(0, comma), paths, values);
arguments = comma < 0 ? "" : arguments.substring(comma + 1);
}
return size;
}
// A list index counts its decimal digits.
private static int pathElementSize(Object element) {
return element instanceof Long index ? Long.toString(index).length() : utf8Length((String) element);
}
private static final class PathTree {
private final Map<Object, PathTree> children = new LinkedHashMap<>();
void add(List<Object> path) {
PathTree node = this;
for (Object element : path) {
node = node.children.computeIfAbsent(element, ignored -> new PathTree());
}
}
int size() {
int size = 0;
for (Map.Entry<Object, PathTree> child : children.entrySet()) {
PathTree nested = child.getValue();
size += pathElementSize(child.getKey())
+ (nested.children.isEmpty() ? 0 : TARGET_CONTAINER_COST + nested.size());
}
return size;
}
}
static int calculateItemSize(JsonNode item) {
@@ -127,7 +185,7 @@ final class DynamoDbItemSize {
if (attr.has("NULL")) return 1;
if (attr.has("SS")) {
int size = 0;
for (JsonNode e : attr.get("SS")) size += utf8Length(e.asText()) + 1;
for (JsonNode e : attr.get("SS")) size += utf8Length(e.asText());
return size;
}
if (attr.has("NS")) {
@@ -139,20 +197,20 @@ final class DynamoDbItemSize {
}
if (attr.has("BS")) {
int size = 0;
for (JsonNode e : attr.get("BS")) size += binarySize(e.asText()) + 1;
for (JsonNode e : attr.get("BS")) size += binarySize(e.asText());
return size;
}
if (attr.has("L")) {
int size = 0;
for (JsonNode e : attr.get("L")) size += attributeValueSize(e) + 3;
int size = CONTAINER_COST;
for (JsonNode e : attr.get("L")) size += 1 + attributeValueSize(e);
return size;
}
if (attr.has("M")) {
int size = 0;
int size = CONTAINER_COST;
Iterator<Map.Entry<String, JsonNode>> fields = attr.get("M").fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
size += utf8Length(entry.getKey()) + 1 + attributeValueSize(entry.getValue()) + 3;
size += utf8Length(entry.getKey()) + 1 + attributeValueSize(entry.getValue());
}
return size;
}
@@ -1259,12 +1259,9 @@ public class DynamoDbService {
// AWS validates index key values against the item the update produces.
validateIndexKeyTypes(table, item, true);
if (sizeRule == UpdateSizeRule.UPDATE_ITEM) {
requireUpdateItemWithinSizeLimit(item,
writtenAttributes(touchedPaths, updateExpression, expressionAttrNames),
updateExpression != null
? DynamoDbItemSize.updateExpressionCost(updateExpression)
: DynamoDbItemSize.attributeUpdatesCost(attributeUpdates));
if (sizeRule == UpdateSizeRule.UPDATE_ITEM && updateExpression != null) {
requireUpdateItemWithinSizeLimit(item, DynamoDbItemSize.updateStatementSize(updateExpression,
path -> parsePath(path, expressionAttrNames), expressionAttrValues));
} else {
requireUpdatedItemWithinSizeLimit(item);
}
@@ -1308,18 +1305,6 @@ public class DynamoDbService {
return updateExpression != null ? parsePath(path, expressionAttrNames) : List.<Object>of(path);
}
private Set<String> writtenAttributes(List<String> touchedPaths, String updateExpression,
JsonNode expressionAttrNames) {
Set<String> names = new LinkedHashSet<>();
for (String path : touchedPaths) {
List<Object> tokens = pathTokens(path, updateExpression, expressionAttrNames);
if (!tokens.isEmpty() && tokens.get(0) instanceof String name) {
names.add(name);
}
}
return names;
}
public QueryResult query(String tableName, JsonNode keyConditions,
JsonNode expressionAttrValues, String keyConditionExpression,
String filterExpression, Integer limit, String region) {
@@ -2169,9 +2154,8 @@ public class DynamoDbService {
}
}
private static void requireUpdateItemWithinSizeLimit(JsonNode item, Set<String> writtenAttributes,
int actionCost) {
if (!DynamoDbItemSize.updateItemWithinLimit(item, writtenAttributes, actionCost)) {
private static void requireUpdateItemWithinSizeLimit(JsonNode item, int statementSize) {
if (!DynamoDbItemSize.updateItemWithinLimit(item, statementSize)) {
throw new UpdatedItemTooLargeException();
}
}
@@ -2929,6 +2913,7 @@ public class DynamoDbService {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: The expression can not be empty;", 400);
}
requireClosedParentheses(expression, "");
// AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs of
// whitespace (newlines, tabs, multiple spaces) so clause-keyword dispatch and the
// comma-separated action parsing below work regardless of formatting. Normalize
@@ -3132,7 +3117,7 @@ public class DynamoDbService {
* unwrapped form. Rejects forms like "(a) - (b)" where the outer parens do
* not actually enclose the whole expression.
*/
private static String stripOuterParens(String expr) {
static String stripOuterParens(String expr) {
String s = expr.trim();
while (s.length() >= 2 && s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')') {
int depth = 0;
@@ -3792,6 +3777,41 @@ public class DynamoDbService {
}
}
// DynamoDB reads an unclosed call or group to the end of the expression and reports the
// raw text from its last token on, trailing whitespace included. UpdateItem wraps the
// error in the validation envelope, TransactWriteItems does not.
static void requireClosedParentheses(String expression, String envelope) {
int depth = 0;
int lastToken = 0;
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isWhitespace(c)) {
continue;
}
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth < 0) {
return;
}
}
if (i == 0 || isUpdatePunctuation(c) || isUpdatePunctuation(expression.charAt(i - 1))
|| Character.isWhitespace(expression.charAt(i - 1))) {
lastToken = i;
}
}
if (depth > 0) {
throw new AwsException("ValidationException",
envelope + "Invalid UpdateExpression: Syntax error; token: \"<EOF>\", near: \""
+ expression.substring(lastToken) + "\"", 400);
}
}
private static boolean isUpdatePunctuation(char c) {
return "()[],.=+-".indexOf(c) >= 0;
}
static int findNextComma(String s) {
// Find next comma that is not inside a function call
int depth = 0;
@@ -3874,7 +3894,7 @@ public class DynamoDbService {
* Finds the index of an arithmetic operator (+ or -) that is outside
* function parentheses. Returns -1 if none found.
*/
private int findArithmeticOperator(String expr) {
static int findArithmeticOperator(String expr) {
int depth = 0;
for (int i = 0; i < expr.length(); i++) {
char c = expr.charAt(i);
@@ -3899,7 +3919,7 @@ public class DynamoDbService {
* spaced form (e.g. PynamoDB always generates {@code "list_append (x, y)"}), which a plain
* {@code startsWith(functionName + "(")} rejects.
*/
private static boolean startsWithFunctionCall(String value, String functionName) {
static boolean startsWithFunctionCall(String value, String functionName) {
return value.startsWith(functionName)
&& value.substring(functionName.length()).stripLeading().startsWith("(");
}
@@ -819,6 +819,7 @@ public class NativeDynamoDbJsonHandler {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
}
DynamoDbService.requireClosedParentheses(updateExpression, "1 validation error detected: ");
}
// Undefined tokens, then ConditionExpression's semantic errors, must both be caught
// before the unused-EAN/EAV checks below.