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

@@ -651,6 +651,124 @@ class DynamoDbConformanceChangesTest {
assertThat(resp.item().get("count").n()).isEqualTo("99");
}
// -----------------------------------------------------------------------
// Phase 10 — Legacy API: Expected with Exists
// -----------------------------------------------------------------------
@Test @Order(88)
@SuppressWarnings("deprecation")
void legacyExpectedExistsTrueComparesValue() {
// Version-guarded write pattern: Exists:true is paired with the version the caller
// last read. Both must be honoured — the attribute must exist AND still equal that value.
ddb.putItem(r -> r.tableName(TABLE).item(Map.of(
"pk", av("legacy-exp-version"), "sk", av("s"),
"version", AttributeValue.builder().n("5").build(),
"session", av("original"))));
Map<String, ExpectedAttributeValue> expectVersion5 = Map.of("version",
ExpectedAttributeValue.builder()
.exists(true)
.value(AttributeValue.builder().n("5").build())
.build());
// The expectation is current → the write lands and bumps the version to 6.
ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-version"), "sk", av("s")))
.attributeUpdates(Map.of("version", AttributeValueUpdate.builder()
.value(AttributeValue.builder().n("6").build())
.action(AttributeAction.PUT)
.build()))
.expected(expectVersion5)
.build());
// The same expectation is now stale (stored version is 6) → must be rejected.
assertThatThrownBy(() -> ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-version"), "sk", av("s")))
.attributeUpdates(Map.of("session", AttributeValueUpdate.builder()
.action(AttributeAction.DELETE)
.build()))
.expected(expectVersion5)
.build()))
.isInstanceOf(ConditionalCheckFailedException.class);
// PutItem and DeleteItem route through the same evaluation and must agree.
assertThatThrownBy(() -> ddb.putItem(r -> r
.tableName(TABLE)
.item(Map.of("pk", av("legacy-exp-version"), "sk", av("s"),
"version", AttributeValue.builder().n("7").build()))
.expected(expectVersion5)))
.isInstanceOf(ConditionalCheckFailedException.class);
assertThatThrownBy(() -> ddb.deleteItem(r -> r
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-version"), "sk", av("s")))
.expected(expectVersion5)))
.isInstanceOf(ConditionalCheckFailedException.class);
// None of the stale writes took effect.
GetItemResponse resp = ddb.getItem(r -> r
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-version"), "sk", av("s"))));
assertThat(resp.item().get("version").n()).isEqualTo("6");
assertThat(resp.item().get("session").s()).isEqualTo("original");
// Exists:false still means "attribute must be absent".
assertThatThrownBy(() -> ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-version"), "sk", av("s")))
.attributeUpdates(Map.of("note", AttributeValueUpdate.builder()
.value(av("x")).action(AttributeAction.PUT).build()))
.expected(Map.of("version", ExpectedAttributeValue.builder().exists(false).build()))
.build()))
.isInstanceOf(ConditionalCheckFailedException.class);
}
@Test @Order(89)
@SuppressWarnings("deprecation")
void legacyExpectedRejectsInvalidExistsCombinations() {
// Exists:true with no Value — nothing to compare against.
DynamoDbException noValue = (DynamoDbException) catchThrowable(() -> ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-invalid"), "sk", av("s")))
.attributeUpdates(Map.of("note", AttributeValueUpdate.builder()
.value(av("x")).action(AttributeAction.PUT).build()))
.expected(Map.of("version", ExpectedAttributeValue.builder().exists(true).build()))
.build()));
assertThat(noValue).isNotNull();
assertThat(noValue.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
// Exists:false alongside a Value — contradictory.
DynamoDbException falseWithValue = (DynamoDbException) catchThrowable(() -> ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-invalid"), "sk", av("s")))
.attributeUpdates(Map.of("note", AttributeValueUpdate.builder()
.value(av("x")).action(AttributeAction.PUT).build()))
.expected(Map.of("version", ExpectedAttributeValue.builder()
.exists(false)
.value(AttributeValue.builder().n("5").build())
.build()))
.build()));
assertThat(falseWithValue).isNotNull();
assertThat(falseWithValue.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
// Exists mixed with the ComparisonOperator form.
DynamoDbException mixedForms = (DynamoDbException) catchThrowable(() -> ddb.updateItem(UpdateItemRequest.builder()
.tableName(TABLE)
.key(Map.of("pk", av("legacy-exp-invalid"), "sk", av("s")))
.attributeUpdates(Map.of("note", AttributeValueUpdate.builder()
.value(av("x")).action(AttributeAction.PUT).build()))
.expected(Map.of("version", ExpectedAttributeValue.builder()
.exists(true)
.comparisonOperator(ComparisonOperator.EQ)
.attributeValueList(AttributeValue.builder().n("5").build())
.build()))
.build()));
assertThat(mixedForms).isNotNull();
assertThat(mixedForms.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
}
// -----------------------------------------------------------------------
// Phase 11 — Enum validation fires before table lookup
// -----------------------------------------------------------------------