fix(dynamodb): correct UpdateExpression semantics and TransactWriteItems idempotency (#804)

Three related DynamoDB correctness fixes, all in the same DynamoDbService surface:

1. Cross-attribute SET reads pre-update values (#798)
   "SET a = :v, b = a" now writes the *original* value of `a` into `b`, matching
   real DynamoDB. Snapshot the item once at the start of applySetClause and
   resolve every RHS reference against the snapshot; defer writes to `item`.
   Previously, in-place mutation between comma-separated clauses caused later
   clauses to read post-update values, silently corrupting audit/history fields.

2. ClientRequestToken idempotency for TransactWriteItems (#799)
   Same token + same body → no-op success. Same token + different body →
   IdempotentParameterMismatchException. Implemented via a per-region in-memory
   cache with a 10-minute TTL (matching the AWS window) keyed by
   "region::token" with a SHA-256 of the raw request body for comparison.
   handleTransactWriteItems now extracts ClientRequestToken from the request
   and forwards it plus the raw body through a new 4-arg
   transactWriteItems(items, region, token, rawRequest) overload. The original
   2-arg signature is preserved as a no-token convenience that delegates.

3. Parenthesized arithmetic in SET silently dropped (#802)
   "SET c = (c - :v)" now applies identically to "SET c = c - :v". Added
   stripOuterParens() and call it on each SET-action RHS before
   findArithmeticOperator() — which still correctly only finds operators at
   depth 0, but now sees an unwrapped expression to scan. Combined forms like
   "SET c = (if_not_exists(c, :d) - :v), other = :s" now apply both clauses
   instead of dropping the parenthesized one while applying the other.

Tests
- DynamoDbServiceTest gains 8 regression tests:
  cross-attribute SET (plain + #name), parenthesized arithmetic (simple,
  with if_not_exists, doubled parens, alongside a plain assignment), and
  TransactWriteItems idempotency (no-op replay, parameter-mismatch error,
  null-token bypass).

Refs: #798, #799, #802
This commit is contained in:
Benson authored and GitHub committed 2026-05-13 00:38:56 -05:00
1 parent 558983078c
commit 6b2c081f0b
3 files changed
+397 -9

No files matched your search

@@ -1968,4 +1968,268 @@ class DynamoDbServiceTest {
assertTrue(returnedItem.has("customerId"), "returned item should have customerId");
assertEquals("1", returnedItem.get("customerId").get("S").asText());
}
// ── Regression tests: cross-attribute SET, parenthesized arithmetic,
// and TransactWriteItems ClientRequestToken idempotency ──
@Test
void updateItemSetCrossAttributeReferenceUsesPreUpdateValue() {
// "SET a = :new, b = a" must write the ORIGINAL value of a into b.
// AWS DynamoDB applies SET actions atomically; attribute references on the RHS
// resolve to pre-update values.
createUsersTable();
ObjectNode existing = mapper.createObjectNode();
existing.set("userId", attributeValue("S", "u1"));
existing.set("a", attributeValue("S", "original_a"));
existing.set("b", attributeValue("S", "original_b"));
service.putItem("Users", existing);
ObjectNode key = item("userId", "u1");
ObjectNode exprValues = mapper.createObjectNode();
exprValues.set(":new_a", attributeValue("S", "new_a_value"));
service.updateItem("Users", key, null,
"SET a = :new_a, b = a",
null, exprValues, null);
JsonNode stored = service.getItem("Users", key);
assertNotNull(stored);
assertEquals("new_a_value", stored.get("a").get("S").asText(),
"a should be updated to the new value");
assertEquals("original_a", stored.get("b").get("S").asText(),
"b should receive a's pre-update value (atomic application)");
}
@Test
void updateItemSetCrossAttributeReferenceWithExpressionAttributeNames() {
// Same as above but using #placeholder names — the form most client libraries emit.
createUsersTable();
ObjectNode existing = mapper.createObjectNode();
existing.set("userId", attributeValue("S", "u1"));
existing.set("status", attributeValue("S", "ISSUED"));
existing.set("previousStatus", attributeValue("S", "NONE"));
service.putItem("Users", existing);
ObjectNode key = item("userId", "u1");
ObjectNode exprAttrNames = mapper.createObjectNode();
exprAttrNames.put("#s", "status");
exprAttrNames.put("#p", "previousStatus");
ObjectNode exprValues = mapper.createObjectNode();
exprValues.set(":v", attributeValue("S", "VOID"));
service.updateItem("Users", key, null,
"SET #s = :v, #p = #s",
exprAttrNames, exprValues, null);
JsonNode stored = service.getItem("Users", key);
assertEquals("VOID", stored.get("status").get("S").asText());
assertEquals("ISSUED", stored.get("previousStatus").get("S").asText(),
"previousStatus should receive the pre-update value of status");
}
@Test
void updateItemSetParenthesizedArithmeticAppliesSubtraction() {
// "SET c = (c - :v)" must subtract identically to the unwrapped form.
// Previously, findArithmeticOperator only returned operators at paren-depth 0,
// so wrapped arithmetic silently no-oped.
createUsersTable();
ObjectNode existing = mapper.createObjectNode();
existing.set("userId", attributeValue("S", "u1"));
ObjectNode counterVal = mapper.createObjectNode();
counterVal.put("N", "5");
existing.set("counter", counterVal);
service.putItem("Users", existing);
ObjectNode key = item("userId", "u1");
ObjectNode exprAttrNames = mapper.createObjectNode();
exprAttrNames.put("#c", "counter");
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode vNode = mapper.createObjectNode();
vNode.put("N", "1");
exprValues.set(":v", vNode);
service.updateItem("Users", key, null,
"SET #c = (#c - :v)",
exprAttrNames, exprValues, null);
JsonNode stored = service.getItem("Users", key);
assertEquals("4", stored.get("counter").get("N").asText(),
"parenthesized arithmetic should subtract identically to the unwrapped form");
}
@Test
void updateItemSetParenthesizedIfNotExistsArithmeticAlongsidePlainAssignment() {
// ElectroDB-style emission: "SET c = (if_not_exists(c, :d) - :v), other = :s".
// Previously the parenthesized arithmetic was silently dropped while the simple
// SET clause applied — a confusing partial-success outcome.
createUsersTable();
ObjectNode existing = mapper.createObjectNode();
existing.set("userId", attributeValue("S", "u1"));
ObjectNode counterVal = mapper.createObjectNode();
counterVal.put("N", "5");
existing.set("counter", counterVal);
existing.set("other", attributeValue("S", "old"));
service.putItem("Users", existing);
ObjectNode key = item("userId", "u1");
ObjectNode exprAttrNames = mapper.createObjectNode();
exprAttrNames.put("#c", "counter");
exprAttrNames.put("#o", "other");
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode vNode = mapper.createObjectNode(); vNode.put("N", "1");
ObjectNode dNode = mapper.createObjectNode(); dNode.put("N", "0");
exprValues.set(":v", vNode);
exprValues.set(":d", dNode);
exprValues.set(":s", attributeValue("S", "new"));
service.updateItem("Users", key, null,
"SET #c = (if_not_exists(#c, :d) - :v), #o = :s",
exprAttrNames, exprValues, null);
JsonNode stored = service.getItem("Users", key);
assertEquals("4", stored.get("counter").get("N").asText(),
"parenthesized arithmetic should apply alongside a simple SET clause");
assertEquals("new", stored.get("other").get("S").asText(),
"the non-parenthesized clause should still apply");
}
@Test
void updateItemSetDoubledOuterParensStillApplies() {
// Defence-in-depth: even multiply-wrapped expressions should parse the same as bare.
createUsersTable();
ObjectNode existing = mapper.createObjectNode();
existing.set("userId", attributeValue("S", "u1"));
ObjectNode counterVal = mapper.createObjectNode(); counterVal.put("N", "10");
existing.set("counter", counterVal);
service.putItem("Users", existing);
ObjectNode key = item("userId", "u1");
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode vNode = mapper.createObjectNode(); vNode.put("N", "3");
exprValues.set(":v", vNode);
service.updateItem("Users", key, null,
"SET counter = ((counter - :v))",
null, exprValues, null);
JsonNode stored = service.getItem("Users", key);
assertEquals("7", stored.get("counter").get("N").asText());
}
@Test
void transactWriteItemsReplayWithSameTokenAndBodyIsNoOp() {
// ClientRequestToken contract: same token + same body → no re-application of writes.
createUsersTable();
service.putItem("Users", item("userId", "u1"));
ObjectNode update = mapper.createObjectNode();
update.put("TableName", "Users");
update.set("Key", item("userId", "u1"));
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
exprValues.set(":one", oneVal);
ObjectNode exprNames = mapper.createObjectNode();
exprNames.put("#c", "counter");
update.put("UpdateExpression", "ADD #c :one");
update.set("ExpressionAttributeNames", exprNames);
update.set("ExpressionAttributeValues", exprValues);
ObjectNode transactItem = mapper.createObjectNode();
transactItem.set("Update", update);
ObjectNode rawRequest = mapper.createObjectNode();
rawRequest.putArray("TransactItems").add(transactItem);
rawRequest.put("ClientRequestToken", "tok-replay");
// First call applies the ADD: counter becomes 1.
service.transactWriteItems(List.of(transactItem), "us-east-1", "tok-replay", rawRequest);
// Replay must be a no-op.
service.transactWriteItems(List.of(transactItem), "us-east-1", "tok-replay", rawRequest);
JsonNode stored = service.getItem("Users", item("userId", "u1"));
assertEquals("1", stored.get("counter").get("N").asText(),
"replay with the same ClientRequestToken must not re-apply the write");
}
@Test
void transactWriteItemsReplayWithSameTokenButDifferentBodyThrowsIdempotentMismatch() {
// ClientRequestToken contract: same token + different body → IdempotentParameterMismatchException.
createUsersTable();
service.putItem("Users", item("userId", "u1"));
ObjectNode exprNames = mapper.createObjectNode();
exprNames.put("#c", "counter");
// First request: ADD #c :x with :x = 1
ObjectNode update1 = mapper.createObjectNode();
update1.put("TableName", "Users");
update1.set("Key", item("userId", "u1"));
ObjectNode exprValues1 = mapper.createObjectNode();
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
exprValues1.set(":x", oneVal);
update1.put("UpdateExpression", "ADD #c :x");
update1.set("ExpressionAttributeNames", exprNames);
update1.set("ExpressionAttributeValues", exprValues1);
ObjectNode tx1 = mapper.createObjectNode(); tx1.set("Update", update1);
ObjectNode raw1 = mapper.createObjectNode();
raw1.putArray("TransactItems").add(tx1);
raw1.put("ClientRequestToken", "tok-mismatch");
service.transactWriteItems(List.of(tx1), "us-east-1", "tok-mismatch", raw1);
// Second request reuses the token but changes :x to 2.
ObjectNode update2 = mapper.createObjectNode();
update2.put("TableName", "Users");
update2.set("Key", item("userId", "u1"));
ObjectNode exprValues2 = mapper.createObjectNode();
ObjectNode twoVal = mapper.createObjectNode(); twoVal.put("N", "2");
exprValues2.set(":x", twoVal);
update2.put("UpdateExpression", "ADD #c :x");
update2.set("ExpressionAttributeNames", exprNames);
update2.set("ExpressionAttributeValues", exprValues2);
ObjectNode tx2 = mapper.createObjectNode(); tx2.set("Update", update2);
ObjectNode raw2 = mapper.createObjectNode();
raw2.putArray("TransactItems").add(tx2);
raw2.put("ClientRequestToken", "tok-mismatch");
AwsException ex = assertThrows(AwsException.class, () ->
service.transactWriteItems(List.of(tx2), "us-east-1", "tok-mismatch", raw2));
assertEquals("IdempotentParameterMismatchException", ex.getErrorCode());
// First call applied; second was rejected — counter remains 1.
JsonNode stored = service.getItem("Users", item("userId", "u1"));
assertEquals("1", stored.get("counter").get("N").asText());
}
@Test
void transactWriteItemsNullClientRequestTokenSkipsIdempotencyCheck() {
// When no token is supplied, two calls with identical bodies should both apply
// (i.e. counter ends at 2). This is the pre-existing behaviour and must remain.
createUsersTable();
service.putItem("Users", item("userId", "u1"));
ObjectNode update = mapper.createObjectNode();
update.put("TableName", "Users");
update.set("Key", item("userId", "u1"));
ObjectNode exprNames = mapper.createObjectNode();
exprNames.put("#c", "counter");
ObjectNode exprValues = mapper.createObjectNode();
ObjectNode oneVal = mapper.createObjectNode(); oneVal.put("N", "1");
exprValues.set(":one", oneVal);
update.put("UpdateExpression", "ADD #c :one");
update.set("ExpressionAttributeNames", exprNames);
update.set("ExpressionAttributeValues", exprValues);
ObjectNode tx = mapper.createObjectNode(); tx.set("Update", update);
service.transactWriteItems(List.of(tx), "us-east-1", null, null);
service.transactWriteItems(List.of(tx), "us-east-1", null, null);
JsonNode stored = service.getItem("Users", item("userId", "u1"));
assertEquals("2", stored.get("counter").get("N").asText());
}
}