fix(dynamodb): compare Value when legacy Expected supplies Exists (#2125)

* fix(dynamodb): compare Value when legacy Expected supplies Exists

A legacy Expected entry that supplies both Exists:true and a Value was
evaluated as an existence check only — the supplied Value was silently
discarded, so any stale value passed the condition.

This is the wire form emitted by version-guarded writes, where the caller
pairs Exists:true with the version it last read:

    "Expected": {"version": {"Exists": true, "Value": {"N": "5"}}}

Because the guard was present on every request and ignored on every
request, conflicting writes were accepted with no visible symptom.

Per the documented ExpectedAttributeValue semantics, Exists:true always
carries a Value and means the attribute must exist AND equal it, which is
the same check as a bare Value. Only Exists:false is a pure absence check.
The three combinations DynamoDB documents as invalid now raise
ValidationException instead of being silently accepted:

  - Exists:true with no Value
  - Exists:false alongside a Value
  - Exists combined with ComparisonOperator / AttributeValueList

Validation runs over the whole Expected map before any condition is
evaluated. PutItem, DeleteItem and UpdateItem all route through
evaluateLegacyExpected, so the change applies to all three.

* fix(dynamodb): compare collection values in legacy EQ conditions

The EQ comparison used by legacy Expected, QueryFilter and ScanFilter
reduced a non-scalar attribute value to an empty string, so any two
values of the same collection type compared as equal. A stale
expectation on an SS, NS, BS, L or M value was therefore always
satisfied and the guarded write was applied.

EQ now delegates to the existing attributeValuesEqual helper — the same
one the ConditionExpression path uses. It is type-strict, compares
numbers via BigDecimal, recurses into M and L, and treats set types as
unordered.

* fix(dynamodb): compare number set members numerically in equality

Number set equality put the members in a HashSet<BigDecimal>, so
membership went through BigDecimal.equals, which is scale-sensitive: 1
and 1.0 were treated as different members. Because NS elements are
normalized on write while a supplied condition value is not, an
otherwise valid condition on a numerically equivalent set was rejected
and the guarded write blocked.

Membership now goes through a TreeSet, whose contains uses compareTo, so
members compare numerically. Applies to both the legacy Expected /
QueryFilter / ScanFilter EQ path and ConditionExpression, which share
this helper.

* fix(dynamodb): compare collection values in legacy NE conditions

NE had the inverse of the collapse the previous commit fixed for EQ: it
compared the scalar projections of both values, which are empty strings
for non-scalar types, so any two collections of the same type looked
equal and NE was always false. A condition asserting an attribute
differs from a set it genuinely differs from blocked the write.

NE now negates attributeValuesEqual, mirroring EQ. Null handling is
unchanged: a missing attribute or a missing comparison value still
satisfies NE.

* test(dynamodb): pin type-strict equality in legacy conditions

EQ and NE compare attribute types as well as values, so a string "5"
does not match a stored number 5. Nothing pinned that, which left room
for a refactor to reintroduce equality via scalar string projections
without any test failing.

* fix(dynamodb): match DynamoDB validation for legacy Expected entries

Verified the legacy Expected rules against DynamoDB itself and aligned
the validation with what the service actually returns.

Error messages now carry the "1 validation error detected: " prefix and
the exact wording, including "Exists and ComparisonOperator cannot be
used together", which differed from the message used before.

Two rules were missing:

  - AttributeValueList without a ComparisonOperator is rejected, and
    that check takes precedence over the Exists rules. It applies
    whether or not Exists is present.
  - An entry with neither Exists nor Value is rejected as well,
    reported as "Value must be provided when Exists is null".

DynamoDB reports only the first offending entry even when several are
invalid, so validation still stops at the first error.
This commit is contained in:
Dmitriy Polomoshnov authored and GitHub committed 2026-08-09 19:03:42 -04:00
1 parent 91b6a40bc7
commit a2b20cc085
5 files changed
+963 -10

No files matched your search

@@ -570,6 +570,7 @@ public class DynamoDbJsonHandler {
private void evaluateLegacyExpected(JsonNode existing, JsonNode expected, String conditionalOperator,
String returnValuesOnConditionCheckFailure) {
if (expected == null) return;
validateLegacyExpected(expected);
boolean useOr = "OR".equals(conditionalOperator);
boolean overall = !useOr;
var fields = expected.fields();
@@ -579,10 +580,11 @@ public class DynamoDbJsonHandler {
JsonNode condition = entry.getValue();
JsonNode attrValue = existing != null ? existing.get(attrName) : null;
boolean condResult;
if (condition.has("Exists")) {
boolean exists = condition.get("Exists").asBoolean();
condResult = exists ? attrValue != null : attrValue == null;
if (condition.has("Exists") && !condition.get("Exists").asBoolean()) {
condResult = attrValue == null;
} else {
// Exists:true always carries a Value, so it evaluates as an attribute
// comparison exactly like a bare Value: must exist AND match.
condResult = dynamoDbService.matchesKeyConditionPublic(attrValue, normalizeLegacyCondition(condition));
}
if (useOr) overall = overall || condResult;
@@ -597,6 +599,55 @@ public class DynamoDbJsonHandler {
}
}
/**
* Validates every entry of a legacy Expected map before any condition is evaluated.
* The rules and their precedence mirror ExpectedAttributeValue:
* <ul>
* <li>{@code AttributeValueList} is only meaningful alongside a {@code ComparisonOperator}.</li>
* <li>{@code Exists} cannot be combined with a {@code ComparisonOperator} — they are
* alternative forms.</li>
* <li>Without a {@code ComparisonOperator}, a {@code Value} is required unless
* {@code Exists: false} asks for plain absence.</li>
* <li>{@code Exists: false} forbids a {@code Value} — an attribute cannot be expected to
* hold a value while also being expected to be absent.</li>
* </ul>
* DynamoDB reports only the first offending entry, so validation stops at the first error.
*/
private void validateLegacyExpected(JsonNode expected) {
var fields = expected.fields();
while (fields.hasNext()) {
var entry = fields.next();
String attrName = entry.getKey();
JsonNode condition = entry.getValue();
boolean hasComparisonOperator = condition.has("ComparisonOperator");
boolean hasExists = condition.has("Exists");
boolean hasValue = condition.has("Value");
if (condition.has("AttributeValueList") && !hasComparisonOperator) {
throw legacyExpectedValidationError(
"AttributeValueList can only be used with a ComparisonOperator for Attribute: " + attrName);
}
if (hasExists && hasComparisonOperator) {
throw legacyExpectedValidationError(
"Exists and ComparisonOperator cannot be used together for Attribute: " + attrName);
}
boolean expectsValue = !hasExists || condition.get("Exists").asBoolean();
if (!hasComparisonOperator && expectsValue && !hasValue) {
throw legacyExpectedValidationError("Value must be provided when Exists is "
+ (hasExists ? "true" : "null") + " for Attribute: " + attrName);
}
if (!expectsValue && hasValue) {
throw legacyExpectedValidationError(
"Value cannot be used when Exists is false for Attribute: " + attrName);
}
}
}
private AwsException legacyExpectedValidationError(String detail) {
return new AwsException("ValidationException",
"1 validation error detected: One or more parameter values were invalid: " + detail, 400);
}
/**
* Converts a legacy Expected condition from the {"Value": {...}} form to the
* {"AttributeValueList": [{...}]} form expected by matchesKeyCondition.
@@ -2461,14 +2461,18 @@ public class DynamoDbService {
return switch (op) {
case "EQ" -> {
if (attrValue == null) yield false;
yield ExpressionEvaluator.compareAttributeValues(attrValue, compareAttr != null ? compareAttr : attrValue) == 0
&& actual != null && actual.equals(compareValue);
if (attrValue == null || compareAttr == null) {
yield false;
}
// Deep equality, so set/list/map values compare by content rather than
// collapsing to an empty scalar and matching everything.
yield attributeValuesEqual(attrValue, compareAttr);
}
case "NE" -> {
if (attrValue == null) yield true;
if (actual == null || compareValue == null) yield true;
yield !actual.equals(compareValue);
if (attrValue == null || compareAttr == null) {
yield true;
}
yield !attributeValuesEqual(attrValue, compareAttr);
}
case "NULL" -> attrValue == null;
case "NOT_NULL" -> attrValue != null;
@@ -1001,7 +1001,9 @@ final class ExpressionEvaluator {
if (a.has("NS") && b.has("NS")) {
JsonNode aArr = a.get("NS"), bArr = b.get("NS");
if (aArr.size() != bArr.size()) return false;
var aSet = new java.util.HashSet<BigDecimal>();
// TreeSet membership goes through compareTo, so 1 and 1.0 are the same member.
// BigDecimal.equals() is scale-sensitive and would treat them as different.
var aSet = new java.util.TreeSet<BigDecimal>();
try {
aArr.forEach(e -> aSet.add(new BigDecimal(e.asText())));
for (JsonNode e : bArr) { if (!aSet.contains(new BigDecimal(e.asText()))) return false; }