diff --git a/CHANGELOG.md b/CHANGELOG.md index e83425c521..f34bea79bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ * include `ec2` and `ecs` in enabled-service reporting and enforce disabled gating for ACM and ECS targeted requests * return protocol-correct JSON disabled responses for auth-only REST GETs instead of falling back to XML * honor `floci.storage.services.acm.*` overrides in `StorageFactory` +* **dynamodb:** serialise concurrent mutations via per-item locks and total-ordered transaction lock acquisition so `UpdateItem` counters, conditional `PutItem`/`DeleteItem`, and `TransactWriteItems` are linearisable under load — callers whose prior races silently succeeded may now see the `ConditionalCheckFailedException` / `TransactionCanceledException` that real DynamoDB would raise ([#571](https://github.com/floci-io/floci/issues/571)) * **s3:** honor canned object ACLs on PutObject, CopyObject, and multipart uploads ## [1.5.2](https://github.com/floci-io/floci/compare/1.5.1...1.5.2) (2026-04-10) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbConcurrencyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbConcurrencyTest.java new file mode 100644 index 0000000000..416b5f490e --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbConcurrencyTest.java @@ -0,0 +1,288 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; +import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.Put; +import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; +import software.amazon.awssdk.services.dynamodb.model.ReturnValue; +import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; +import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; +import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; +import software.amazon.awssdk.services.dynamodb.model.Update; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * End-to-end concurrency tests against a running Floci instance. + * + *

Covers the four scenarios that must match real DynamoDB's per-item + * linearisability and transaction atomicity — see issue #571. + * + *

Each scenario uses a shared {@link CountDownLatch} starting gate so + * client threads dispatch simultaneously, maximising contention at the server. + */ +@DisplayName("DynamoDB - Concurrency") +class DynamoDbConcurrencyTest { + + private static final String TABLE_NAME = "sdk-test-concurrency-table"; + private static final int THREADS = 20; + + private static DynamoDbClient ddb; + + @BeforeAll + static void setup() { + ddb = TestFixtures.dynamoDbClient(); + ddb.createTable(CreateTableRequest.builder() + .tableName(TABLE_NAME) + .keySchema(KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build()) + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("pk").attributeType(ScalarAttributeType.S).build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(5L).writeCapacityUnits(5L).build()) + .build()); + } + + @AfterAll + static void cleanup() { + if (ddb != null) { + try { + ddb.deleteTable(DeleteTableRequest.builder().tableName(TABLE_NAME).build()); + } catch (Exception ignored) {} + ddb.close(); + } + } + + @Test + @DisplayName("UpdateItem arithmetic — 20 concurrent increments yield 20 distinct results") + void concurrentUpdateItemArithmetic() throws InterruptedException { + String pk = "arith-" + System.nanoTime(); + Set observed = Collections.synchronizedSet(new HashSet<>()); + + runConcurrently(THREADS, () -> { + UpdateItemResponse response = ddb.updateItem(UpdateItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pk).build())) + .updateExpression("SET cnt = if_not_exists(cnt, :start) + :inc") + .expressionAttributeValues(Map.of( + ":start", AttributeValue.builder().n("0").build(), + ":inc", AttributeValue.builder().n("1").build())) + .returnValues(ReturnValue.ALL_NEW) + .build()); + observed.add(Integer.parseInt(response.attributes().get("cnt").n())); + }); + + assertThat(observed) + .as("each UpdateItem should return a distinct cnt under contention") + .hasSize(THREADS); + + int finalCnt = Integer.parseInt(ddb.getItem(GetItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pk).build())) + .consistentRead(true) + .build()) + .item().get("cnt").n()); + assertThat(finalCnt).isEqualTo(THREADS); + } + + @Test + @DisplayName("PutItem attribute_not_exists — exactly one of N concurrent attempts succeeds") + void concurrentPutItemAttributeNotExists() throws InterruptedException { + String pk = "unique-" + System.nanoTime(); + AtomicInteger successes = new AtomicInteger(); + AtomicInteger conditionalFailures = new AtomicInteger(); + + runConcurrently(THREADS, () -> { + try { + ddb.putItem(PutItemRequest.builder() + .tableName(TABLE_NAME) + .item(Map.of("pk", AttributeValue.builder().s(pk).build())) + .conditionExpression("attribute_not_exists(pk)") + .build()); + successes.incrementAndGet(); + } catch (ConditionalCheckFailedException e) { + conditionalFailures.incrementAndGet(); + } + }); + + assertThat(successes.get()) + .as("exactly one concurrent PutItem(attribute_not_exists) must succeed") + .isEqualTo(1); + assertThat(conditionalFailures.get()).isEqualTo(THREADS - 1); + } + + @Test + @DisplayName("TransactWriteItems overlapping — winners see consistent state across items") + void concurrentTransactWriteItemsOverlapping() throws InterruptedException { + String pkA = "txA-" + System.nanoTime(); + String pkB = "txB-" + System.nanoTime(); + + // Seed both keys at version=0. + for (String pk : List.of(pkA, pkB)) { + ddb.putItem(PutItemRequest.builder() + .tableName(TABLE_NAME) + .item(Map.of( + "pk", AttributeValue.builder().s(pk).build(), + "version", AttributeValue.builder().n("0").build())) + .build()); + } + + AtomicInteger committed = new AtomicInteger(); + AtomicInteger cancelled = new AtomicInteger(); + + runConcurrently(THREADS, () -> { + int currentVersion = Integer.parseInt(ddb.getItem(GetItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pkA).build())) + .consistentRead(true) + .build()) + .item().get("version").n()); + int nextVersion = currentVersion + 1; + + Map exprValues = Map.of( + ":v0", AttributeValue.builder().n(String.valueOf(currentVersion)).build(), + ":v1", AttributeValue.builder().n(String.valueOf(nextVersion)).build()); + + try { + ddb.transactWriteItems(TransactWriteItemsRequest.builder() + .transactItems( + buildVersionUpdate(pkA, exprValues), + buildVersionUpdate(pkB, exprValues)) + .build()); + committed.incrementAndGet(); + } catch (TransactionCanceledException e) { + cancelled.incrementAndGet(); + } + }); + + int versionA = Integer.parseInt(ddb.getItem(GetItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pkA).build())) + .consistentRead(true) + .build()) + .item().get("version").n()); + int versionB = Integer.parseInt(ddb.getItem(GetItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pkB).build())) + .consistentRead(true) + .build()) + .item().get("version").n()); + + assertThat(versionA) + .as("pkA and pkB must end on the same version — transaction atomicity") + .isEqualTo(versionB); + assertThat(committed.get()) + .as("commit count must match observed version progress") + .isEqualTo(versionA); + assertThat(committed.get() + cancelled.get()).isEqualTo(THREADS); + } + + private static TransactWriteItem buildVersionUpdate(String pk, Map exprValues) { + return TransactWriteItem.builder() + .update(Update.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pk).build())) + .updateExpression("SET version = :v1") + .conditionExpression("version = :v0") + .expressionAttributeValues(exprValues) + .build()) + .build(); + } + + @Test + @DisplayName("UpdateItem + PutItem on same key — linearisable, no half-updated state") + void concurrentMixedUpdateAndPut() throws InterruptedException { + String pk = "mixed-" + System.nanoTime(); + AtomicInteger idSource = new AtomicInteger(); + + runConcurrently(THREADS, () -> { + int id = idSource.getAndIncrement(); + if (id % 2 == 0) { + ddb.updateItem(UpdateItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pk).build())) + .updateExpression("SET cnt = if_not_exists(cnt, :start) + :inc") + .expressionAttributeValues(Map.of( + ":start", AttributeValue.builder().n("0").build(), + ":inc", AttributeValue.builder().n("1").build())) + .build()); + } else { + ddb.putItem(PutItemRequest.builder() + .tableName(TABLE_NAME) + .item(Map.of( + "pk", AttributeValue.builder().s(pk).build(), + "writer", AttributeValue.builder().s("put-" + id).build())) + .build()); + } + }); + + Map finalItem = ddb.getItem(GetItemRequest.builder() + .tableName(TABLE_NAME) + .key(Map.of("pk", AttributeValue.builder().s(pk).build())) + .consistentRead(true) + .build()) + .item(); + assertThat(finalItem).isNotNull(); + assertThat(finalItem.get("pk").s()).isEqualTo(pk); + finalItem.forEach((name, value) -> assertThat(value) + .as("attribute %s must not be null in final item", name) + .isNotNull()); + } + + private static void runConcurrently(int threadCount, Runnable work) throws InterruptedException { + ExecutorService pool = Executors.newFixedThreadPool(threadCount); + CountDownLatch startGate = new CountDownLatch(1); + CountDownLatch doneGate = new CountDownLatch(threadCount); + List errors = Collections.synchronizedList(new ArrayList<>()); + try { + for (int i = 0; i < threadCount; i++) { + pool.submit(() -> { + try { + startGate.await(); + work.run(); + } catch (Throwable t) { + errors.add(t); + } finally { + doneGate.countDown(); + } + }); + } + startGate.countDown(); + assertThat(doneGate.await(60, TimeUnit.SECONDS)) + .as("concurrent work did not complete within 60s") + .isTrue(); + } finally { + pool.shutdownNow(); + pool.awaitTermination(5, TimeUnit.SECONDS); + } + assertThat(errors) + .as("no unexpected errors should be thrown") + .isEmpty(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index e27bdc734a..9a3c570897 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -20,12 +20,16 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; @ApplicationScoped public class DynamoDbService { @@ -37,6 +41,11 @@ public class DynamoDbService { // Items stored per table: storageKey -> Map // itemKey is "pk" or "pk#sk" depending on table schema private final ConcurrentHashMap> itemsByTable = new ConcurrentHashMap<>(); + // Per-item locks: storageKey -> itemKey -> ReentrantLock. Locks are created lazily + // on first access and cleared with the table (see deleteTable); transactWriteItems + // relies on ReentrantLock's re-entrancy so the inner put/update/delete calls do + // not deadlock after the outer transaction already took each participant's lock. + private final ConcurrentHashMap> itemLocks = new ConcurrentHashMap<>(); private final RegionResolver regionResolver; private DynamoDbStreamService streamService; private KinesisStreamingForwarder kinesisForwarder; @@ -209,6 +218,7 @@ public class DynamoDbService { } tableStore.delete(storageKey); itemsByTable.remove(storageKey); + itemLocks.remove(storageKey); if (itemStore != null) { itemStore.delete(storageKey); } @@ -247,25 +257,28 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); String itemKey = buildItemKey(table, item); - var tableItems = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); - JsonNode existing = tableItems.get(itemKey); + withItemLock(storageKey, itemKey, () -> { + var tableItems = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); - if (conditionExpression != null) { - evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure); - } + JsonNode existing = tableItems.get(itemKey); - tableItems.put(itemKey, item); - persistItems(storageKey); - LOG.debugv("Put item in {0}: key={1}", canonicalTableName, itemKey); + if (conditionExpression != null) { + evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure); + } - String eventName = existing == null ? "INSERT" : "MODIFY"; - if (streamService != null) { - streamService.captureEvent(canonicalTableName, eventName, existing, item, table, region); - } - if (kinesisForwarder != null) { - kinesisForwarder.forward(eventName, existing, item, table, region); - } + tableItems.put(itemKey, item); + persistItems(storageKey); + LOG.debugv("Put item in {0}: key={1}", canonicalTableName, itemKey); + + String eventName = existing == null ? "INSERT" : "MODIFY"; + if (streamService != null) { + streamService.captureEvent(canonicalTableName, eventName, existing, item, table, region); + } + if (kinesisForwarder != null) { + kinesisForwarder.forward(eventName, existing, item, table, region); + } + }); } public JsonNode getItem(String tableName, JsonNode key) { @@ -304,28 +317,31 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); String itemKey = buildItemKey(table, key); - var items = itemsByTable.get(storageKey); - if (items == null) return null; - if (conditionExpression != null) { - JsonNode existing = items.get(itemKey); - evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure); - } + return withItemLock(storageKey, itemKey, () -> { + var items = itemsByTable.get(storageKey); + if (items == null) return null; - JsonNode removed = items.remove(itemKey); - persistItems(storageKey); - LOG.debugv("Deleted item from {0}: key={1}", canonicalTableName, itemKey); - - if (removed != null) { - if (streamService != null) { - streamService.captureEvent(canonicalTableName, "REMOVE", removed, null, table, region); + if (conditionExpression != null) { + JsonNode existing = items.get(itemKey); + evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure); } - if (kinesisForwarder != null) { - kinesisForwarder.forward("REMOVE", removed, null, table, region); - } - } - return removed; + JsonNode removed = items.remove(itemKey); + persistItems(storageKey); + LOG.debugv("Deleted item from {0}: key={1}", canonicalTableName, itemKey); + + if (removed != null) { + if (streamService != null) { + streamService.captureEvent(canonicalTableName, "REMOVE", removed, null, table, region); + } + if (kinesisForwarder != null) { + kinesisForwarder.forward("REMOVE", removed, null, table, region); + } + } + + return removed; + }); } public UpdateResult updateItem(String tableName, JsonNode key, JsonNode attributeUpdates, @@ -347,7 +363,7 @@ public class DynamoDbService { public UpdateResult updateItem(String tableName, JsonNode key, JsonNode attributeUpdates, String updateExpression, JsonNode expressionAttrNames, JsonNode expressionAttrValues, - String returnValues, String conditionExpression, String region, + String returnValues, String conditionExpression, String region, String returnValuesOnConditionCheckFailure) { String canonicalTableName = canonicalTableName(region, tableName); String storageKey = regionKey(region, canonicalTableName); @@ -355,58 +371,61 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); String itemKey = buildItemKey(table, key); - var items = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); - // Get existing item or create new one from key - JsonNode existing = items.get(itemKey); + return withItemLock(storageKey, itemKey, () -> { + var items = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); - if (conditionExpression != null) { - evaluateCondition(existing, conditionExpression, expressionAttrNames, expressionAttrValues, returnValuesOnConditionCheckFailure); - } + // Get existing item or create new one from key + JsonNode existing = items.get(itemKey); - ObjectNode item; - if (existing != null) { - item = existing.deepCopy(); - } else { - item = key.deepCopy(); - } + if (conditionExpression != null) { + evaluateCondition(existing, conditionExpression, expressionAttrNames, expressionAttrValues, returnValuesOnConditionCheckFailure); + } - // Apply UpdateExpression (modern format: "SET #n = :val, age = :age REMOVE attr") - if (updateExpression != null) { - applyUpdateExpression(item, updateExpression, expressionAttrNames, expressionAttrValues); - } - // Apply attribute updates (legacy format: AttributeUpdates) - else if (attributeUpdates != null && attributeUpdates.isObject()) { - Iterator> fields = attributeUpdates.fields(); - while (fields.hasNext()) { - var entry = fields.next(); - String attrName = entry.getKey(); - JsonNode update = entry.getValue(); - String action = update.has("Action") ? update.get("Action").asText() : "PUT"; - JsonNode value = update.get("Value"); + ObjectNode item; + if (existing != null) { + item = existing.deepCopy(); + } else { + item = key.deepCopy(); + } - switch (action) { - case "PUT" -> { if (value != null) item.set(attrName, value); } - case "DELETE" -> item.remove(attrName); - case "ADD" -> { - // Simple ADD for numeric values - if (value != null) item.set(attrName, value); + // Apply UpdateExpression (modern format: "SET #n = :val, age = :age REMOVE attr") + if (updateExpression != null) { + applyUpdateExpression(item, updateExpression, expressionAttrNames, expressionAttrValues); + } + // Apply attribute updates (legacy format: AttributeUpdates) + else if (attributeUpdates != null && attributeUpdates.isObject()) { + Iterator> fields = attributeUpdates.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + String attrName = entry.getKey(); + JsonNode update = entry.getValue(); + String action = update.has("Action") ? update.get("Action").asText() : "PUT"; + JsonNode value = update.get("Value"); + + switch (action) { + case "PUT" -> { if (value != null) item.set(attrName, value); } + case "DELETE" -> item.remove(attrName); + case "ADD" -> { + // Simple ADD for numeric values + if (value != null) item.set(attrName, value); + } } } } - } - items.put(itemKey, item); - persistItems(storageKey); + items.put(itemKey, item); + persistItems(storageKey); - if (streamService != null) { - streamService.captureEvent(canonicalTableName, "MODIFY", existing, item, table, region); - } - if (kinesisForwarder != null) { - kinesisForwarder.forward("MODIFY", existing, item, table, region); - } + if (streamService != null) { + streamService.captureEvent(canonicalTableName, "MODIFY", existing, item, table, region); + } + if (kinesisForwarder != null) { + kinesisForwarder.forward("MODIFY", existing, item, table, region); + } - return new UpdateResult(item, existing); + return new UpdateResult(item, existing); + }); } public QueryResult query(String tableName, JsonNode keyConditions, @@ -664,49 +683,111 @@ public class DynamoDbService { // --- Transact Operations --- public void transactWriteItems(List transactItems, String region) { - // First pass: evaluate all conditions and collect failures - List cancellationReasons = new ArrayList<>(); - boolean hasFailed = false; - + // Acquire every participant's item lock in a deterministic (storageKey, itemKey) + // order before evaluating conditions or applying writes. Total-ordered acquisition + // prevents deadlock across concurrent transactions; ReentrantLock lets the inner + // putItem/updateItem/deleteItem calls re-enter the same lock for free. + // + // Ordering uses a tuple comparator — not a delimited string — so user-supplied + // bytes in an item's PK/SK value cannot collide two distinct participants + // into the same ordering key. + TreeMap toAcquire = new TreeMap<>(PARTICIPANT_ORDER); for (JsonNode transactItem : transactItems) { - String failReason = evaluateTransactCondition(transactItem, region); - if (failReason != null) { - hasFailed = true; - cancellationReasons.add(failReason); - } else { - cancellationReasons.add(""); + TransactParticipant p = resolveParticipant(transactItem, region); + if (p == null) continue; + toAcquire.putIfAbsent(p, lockFor(p.storageKey, p.itemKey)); + } + + List acquired = new ArrayList<>(toAcquire.size()); + try { + for (ReentrantLock lock : toAcquire.values()) { + lock.lock(); + acquired.add(lock); + } + + // First pass: evaluate all conditions and collect failures. + List cancellationReasons = new ArrayList<>(); + boolean hasFailed = false; + for (JsonNode transactItem : transactItems) { + String failReason = evaluateTransactCondition(transactItem, region); + if (failReason != null) { + hasFailed = true; + cancellationReasons.add(failReason); + } else { + cancellationReasons.add(""); + } + } + + if (hasFailed) { + throw new TransactionCanceledException(cancellationReasons); + } + + // Second pass: apply all writes. Inner methods re-acquire their own locks, + // which is a no-op thanks to ReentrantLock. + for (JsonNode transactItem : transactItems) { + if (transactItem.has("Put")) { + JsonNode put = transactItem.get("Put"); + String tableName = put.path("TableName").asText(); + JsonNode item = put.get("Item"); + putItem(tableName, item, region); + } else if (transactItem.has("Delete")) { + JsonNode del = transactItem.get("Delete"); + String tableName = del.path("TableName").asText(); + JsonNode key = del.get("Key"); + deleteItem(tableName, key, region); + } else if (transactItem.has("Update")) { + JsonNode upd = transactItem.get("Update"); + String tableName = upd.path("TableName").asText(); + JsonNode key = upd.get("Key"); + String updateExpression = upd.has("UpdateExpression") ? upd.get("UpdateExpression").asText() : null; + JsonNode exprAttrNames = upd.has("ExpressionAttributeNames") ? upd.get("ExpressionAttributeNames") : null; + JsonNode exprAttrValues = upd.has("ExpressionAttributeValues") ? upd.get("ExpressionAttributeValues") : null; + //there is no ConditionExpression, so setting returnValuesOnConditionCheckFailure = "NONE" + updateItem(tableName, key, null, updateExpression, exprAttrNames, exprAttrValues, + "NONE", null, region, "NONE"); + } + // ConditionCheck-only items are handled in the first pass only + } + } finally { + for (int i = acquired.size() - 1; i >= 0; i--) { + acquired.get(i).unlock(); } } + } - if (hasFailed) { - throw new TransactionCanceledException(cancellationReasons); + private record TransactParticipant(String storageKey, String itemKey) {} + + private static final Comparator PARTICIPANT_ORDER = + Comparator.comparing(TransactParticipant::storageKey) + .thenComparing(TransactParticipant::itemKey); + + private TransactParticipant resolveParticipant(JsonNode transactItem, String region) { + JsonNode target; + boolean isPut = false; + if (transactItem.has("Put")) { + target = transactItem.get("Put"); + isPut = true; + } else if (transactItem.has("Delete")) { + target = transactItem.get("Delete"); + } else if (transactItem.has("Update")) { + target = transactItem.get("Update"); + } else if (transactItem.has("ConditionCheck")) { + target = transactItem.get("ConditionCheck"); + } else { + return null; } - // Second pass: apply all writes - for (JsonNode transactItem : transactItems) { - if (transactItem.has("Put")) { - JsonNode put = transactItem.get("Put"); - String tableName = put.path("TableName").asText(); - JsonNode item = put.get("Item"); - putItem(tableName, item, region); - } else if (transactItem.has("Delete")) { - JsonNode del = transactItem.get("Delete"); - String tableName = del.path("TableName").asText(); - JsonNode key = del.get("Key"); - deleteItem(tableName, key, region); - } else if (transactItem.has("Update")) { - JsonNode upd = transactItem.get("Update"); - String tableName = upd.path("TableName").asText(); - JsonNode key = upd.get("Key"); - String updateExpression = upd.has("UpdateExpression") ? upd.get("UpdateExpression").asText() : null; - JsonNode exprAttrNames = upd.has("ExpressionAttributeNames") ? upd.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = upd.has("ExpressionAttributeValues") ? upd.get("ExpressionAttributeValues") : null; - //there is no ConditionExpression, so setting returnValuesOnConditionCheckFailure = "NONE" - updateItem(tableName, key, null, updateExpression, exprAttrNames, exprAttrValues, - "NONE", null, region, "NONE"); - } - // ConditionCheck-only items are handled in the first pass only + String tableName = canonicalTableName(region, target.path("TableName").asText()); + JsonNode keyOrItem = isPut ? target.get("Item") : target.get("Key"); + if (keyOrItem == null) { + return null; } + + String storageKey = regionKey(region, tableName); + TableDefinition table = tableStore.get(storageKey) + .orElseThrow(() -> resourceNotFoundException(tableName)); + String itemKey = buildItemKey(table, keyOrItem); + return new TransactParticipant(storageKey, itemKey); } private String evaluateTransactCondition(JsonNode transactItem, String region) { @@ -1633,6 +1714,32 @@ public class DynamoDbService { return region + "::" + tableName; } + private ReentrantLock lockFor(String storageKey, String itemKey) { + return itemLocks + .computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>()) + .computeIfAbsent(itemKey, k -> new ReentrantLock()); + } + + private void withItemLock(String storageKey, String itemKey, Runnable body) { + ReentrantLock lock = lockFor(storageKey, itemKey); + lock.lock(); + try { + body.run(); + } finally { + lock.unlock(); + } + } + + private T withItemLock(String storageKey, String itemKey, Supplier body) { + ReentrantLock lock = lockFor(storageKey, itemKey); + lock.lock(); + try { + return body.get(); + } finally { + lock.unlock(); + } + } + String buildItemKey(TableDefinition table, JsonNode item) { String pkName = table.getPartitionKeyName(); JsonNode pkAttr = item.get(pkName); diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConcurrencyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConcurrencyIntegrationTest.java new file mode 100644 index 0000000000..ae9aa5b567 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConcurrencyIntegrationTest.java @@ -0,0 +1,501 @@ +package io.github.hectorvent.floci.services.dynamodb; + +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition; +import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException; +import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; +import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription; +import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Concurrency compatibility suite for {@link DynamoDbService}. + * + *

All scenarios use a {@link CountDownLatch} starting gate so threads release + * simultaneously, maximising contention. Wrapped in {@code @RepeatedTest(5)} so a + * regression that surfaces intermittently has a real chance of being observed in a + * single CI run. + * + *

See issue #571. + */ +class DynamoDbConcurrencyIntegrationTest { + + private static final int REPEATS = 5; + private static final int THREADS = 32; + private static final int OPS_PER_SCENARIO = 50; + + private DynamoDbService service; + private DynamoDbStreamService streamService; + private ObjectMapper mapper; + + @BeforeEach + void setUp() { + mapper = new ObjectMapper(); + StorageBackend tableStore = new InMemoryStorage<>(); + streamService = new DynamoDbStreamService(mapper, tableStore); + service = new DynamoDbService( + tableStore, + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000"), + streamService, + null); + } + + private TableDefinition createCounterTable() { + return service.createTable("Counters", + List.of(new KeySchemaElement("pk", "HASH")), + List.of(new AttributeDefinition("pk", "S")), + 5L, 5L); + } + + private ObjectNode stringAttr(String value) { + ObjectNode node = mapper.createObjectNode(); + node.put("S", value); + return node; + } + + private ObjectNode numberAttr(String value) { + ObjectNode node = mapper.createObjectNode(); + node.put("N", value); + return node; + } + + private ObjectNode pkKey(String value) { + ObjectNode key = mapper.createObjectNode(); + key.set("pk", stringAttr(value)); + return key; + } + + private ObjectNode itemWithPk(String pkValue) { + return pkKey(pkValue); + } + + /** Run {@code work} in {@code threadCount} threads, released together. */ + private List runConcurrently(int threadCount, Runnable work) throws InterruptedException { + ExecutorService pool = Executors.newFixedThreadPool(threadCount); + CountDownLatch startGate = new CountDownLatch(1); + CountDownLatch doneGate = new CountDownLatch(threadCount); + List errors = Collections.synchronizedList(new ArrayList<>()); + try { + for (int i = 0; i < threadCount; i++) { + pool.submit(() -> { + try { + startGate.await(); + work.run(); + } catch (Throwable t) { + errors.add(t); + } finally { + doneGate.countDown(); + } + }); + } + startGate.countDown(); + assertTrue(doneGate.await(30, TimeUnit.SECONDS), + "concurrent tasks did not complete within 30s"); + return errors; + } finally { + pool.shutdownNow(); + assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS), + "thread pool did not terminate"); + } + } + + @RepeatedTest(REPEATS) + void concurrent_updateItem_arithmetic_is_atomic() throws InterruptedException { + createCounterTable(); + + String pk = "counter-1"; + ObjectNode key = pkKey(pk); + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":start", numberAttr("0")); + exprValues.set(":inc", numberAttr("1")); + + List observedValues = Collections.synchronizedList(new ArrayList<>()); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + DynamoDbService.UpdateResult result = service.updateItem( + "Counters", key, null, + "SET cnt = if_not_exists(cnt, :start) + :inc", + null, exprValues, "ALL_NEW"); + JsonNode newItem = result.newItem(); + int value = Integer.parseInt(newItem.get("cnt").get("N").asText()); + observedValues.add(value); + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + JsonNode stored = service.getItem("Counters", key); + assertNotNull(stored, "counter item must exist after updates"); + assertEquals(String.valueOf(OPS_PER_SCENARIO), stored.get("cnt").get("N").asText(), + "final counter must equal number of increments"); + + Set distinct = new HashSet<>(observedValues); + assertEquals(OPS_PER_SCENARIO, distinct.size(), + () -> "each returned cnt must be distinct, got: " + observedValues); + + List sorted = new ArrayList<>(distinct); + Collections.sort(sorted); + assertEquals(1, sorted.get(0)); + assertEquals(OPS_PER_SCENARIO, sorted.get(sorted.size() - 1)); + } + + @RepeatedTest(REPEATS) + void concurrent_updateItem_ADD_action_is_atomic() throws InterruptedException { + createCounterTable(); + + String pk = "counter-add"; + ObjectNode key = pkKey(pk); + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":inc", numberAttr("1")); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> service.updateItem( + "Counters", key, null, + "ADD cnt :inc", + null, exprValues, "NONE")); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + JsonNode stored = service.getItem("Counters", key); + assertNotNull(stored); + assertEquals(String.valueOf(OPS_PER_SCENARIO), stored.get("cnt").get("N").asText(), + "ADD :inc with N=1 run 50 times must yield 50"); + } + + @RepeatedTest(REPEATS) + void concurrent_putItem_with_attribute_not_exists_allows_exactly_one() throws InterruptedException { + createCounterTable(); + + String pk = "unique-row"; + AtomicInteger successes = new AtomicInteger(); + AtomicInteger conditionalFailures = new AtomicInteger(); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + ObjectNode item = itemWithPk(pk); + item.set("stamp", numberAttr(String.valueOf(System.nanoTime()))); + try { + service.putItem("Counters", item, "attribute_not_exists(pk)", + null, null, "us-east-1", "NONE"); + successes.incrementAndGet(); + } catch (ConditionalCheckFailedException e) { + conditionalFailures.incrementAndGet(); + } + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + assertEquals(1, successes.get(), + "exactly one putItem(attribute_not_exists) should succeed under contention"); + assertEquals(OPS_PER_SCENARIO - 1, conditionalFailures.get(), + "the remaining attempts should raise ConditionalCheckFailedException"); + } + + @RepeatedTest(REPEATS) + void concurrent_putItem_with_distinct_keys_all_succeed() throws InterruptedException { + createCounterTable(); + + AtomicInteger idSource = new AtomicInteger(); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + int id = idSource.getAndIncrement(); + ObjectNode item = itemWithPk("distinct-" + id); + item.set("val", numberAttr(String.valueOf(id))); + service.putItem("Counters", item, "us-east-1"); + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + for (int i = 0; i < OPS_PER_SCENARIO; i++) { + JsonNode stored = service.getItem("Counters", pkKey("distinct-" + i)); + assertNotNull(stored, "distinct-" + i + " should exist — proves per-item locking, not table-wide"); + } + } + + @RepeatedTest(REPEATS) + void concurrent_updateItem_and_putItem_on_same_key_is_linearisable() throws InterruptedException { + createCounterTable(); + + String pk = "mixed"; + ObjectNode key = pkKey(pk); + + ObjectNode updateExprValues = mapper.createObjectNode(); + updateExprValues.set(":start", numberAttr("0")); + updateExprValues.set(":inc", numberAttr("1")); + + AtomicInteger idSource = new AtomicInteger(); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + int id = idSource.getAndIncrement(); + if (id % 2 == 0) { + service.updateItem("Counters", key, null, + "SET cnt = if_not_exists(cnt, :start) + :inc", + null, updateExprValues, "NONE"); + } else { + ObjectNode item = itemWithPk(pk); + item.set("writer", stringAttr("put-" + id)); + service.putItem("Counters", item, "us-east-1"); + } + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + JsonNode stored = service.getItem("Counters", key); + assertNotNull(stored, "item must still exist"); + // Must be a well-formed single record; no half-updated state. + assertEquals("S", stored.get("pk").fieldNames().next()); + assertEquals(pk, stored.get("pk").get("S").asText()); + // Exactly one of writer/cnt must be the 'last write' — we can't assert which + // without a happens-before record; just require no null DynamoDB attribute values. + stored.fields().forEachRemaining(entry -> + assertNotNull(entry.getValue(), "attribute " + entry.getKey() + " must not be null")); + } + + @RepeatedTest(REPEATS) + void concurrent_deleteItem_with_condition_only_one_succeeds() throws InterruptedException { + createCounterTable(); + + String pk = "to-delete"; + ObjectNode seed = itemWithPk(pk); + seed.set("marker", stringAttr("present")); + service.putItem("Counters", seed, "us-east-1"); + + AtomicInteger successes = new AtomicInteger(); + AtomicInteger conditionalFailures = new AtomicInteger(); + + ObjectNode key = pkKey(pk); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + try { + service.deleteItem("Counters", key, + "attribute_exists(pk)", null, null, "us-east-1", "NONE"); + successes.incrementAndGet(); + } catch (ConditionalCheckFailedException e) { + conditionalFailures.incrementAndGet(); + } + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + assertEquals(1, successes.get(), + "exactly one conditional delete should succeed"); + assertEquals(OPS_PER_SCENARIO - 1, conditionalFailures.get(), + "the rest must raise ConditionalCheckFailedException"); + assertNull(service.getItem("Counters", key), "item must be gone"); + } + + @RepeatedTest(REPEATS) + void concurrent_transactWriteItems_all_or_nothing() throws InterruptedException { + createCounterTable(); + + String pkA = "txA"; + String pkB = "txB"; + + // Seed both keys with version=0 so we can write a conflicting conditional increment. + ObjectNode seedA = itemWithPk(pkA); + seedA.set("version", numberAttr("0")); + ObjectNode seedB = itemWithPk(pkB); + seedB.set("version", numberAttr("0")); + service.putItem("Counters", seedA, "us-east-1"); + service.putItem("Counters", seedB, "us-east-1"); + + AtomicInteger committed = new AtomicInteger(); + AtomicInteger cancelled = new AtomicInteger(); + + // Each transaction updates both keys with a condition "version = :v0" and + // sets version = :v1. Concurrent attempts must serialise: one wins, others cancel. + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + JsonNode versionBefore = service.getItem("Counters", pkKey(pkA)).get("version"); + int currentVersion = Integer.parseInt(versionBefore.get("N").asText()); + int nextVersion = currentVersion + 1; + + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":v0", numberAttr(String.valueOf(currentVersion))); + exprValues.set(":v1", numberAttr(String.valueOf(nextVersion))); + + ObjectNode tx1 = buildUpdateTx(pkA, exprValues); + ObjectNode tx2 = buildUpdateTx(pkB, exprValues); + + try { + service.transactWriteItems(List.of(tx1, tx2), "us-east-1"); + committed.incrementAndGet(); + } catch (TransactionCanceledException e) { + cancelled.incrementAndGet(); + } + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + JsonNode finalA = service.getItem("Counters", pkKey(pkA)); + JsonNode finalB = service.getItem("Counters", pkKey(pkB)); + int versionA = Integer.parseInt(finalA.get("version").get("N").asText()); + int versionB = Integer.parseInt(finalB.get("version").get("N").asText()); + assertEquals(versionA, versionB, + "both keys must end on the same version — proves transactional atomicity"); + assertEquals(committed.get(), versionA, + "commit count must match version progress"); + assertTrue(committed.get() + cancelled.get() >= OPS_PER_SCENARIO, + "every attempt must either commit or cancel"); + } + + private ObjectNode buildUpdateTx(String pk, ObjectNode exprValues) { + ObjectNode update = mapper.createObjectNode(); + update.put("TableName", "Counters"); + update.set("Key", pkKey(pk)); + update.put("UpdateExpression", "SET version = :v1"); + update.put("ConditionExpression", "version = :v0"); + update.set("ExpressionAttributeValues", exprValues); + ObjectNode wrapper = mapper.createObjectNode(); + wrapper.set("Update", update); + return wrapper; + } + + @RepeatedTest(REPEATS) + void concurrent_transactWriteItems_disjoint_commute() throws InterruptedException { + createCounterTable(); + + // Seed 2 * OPS_PER_SCENARIO keys. Each transaction touches two disjoint keys. + for (int i = 0; i < OPS_PER_SCENARIO * 2; i++) { + ObjectNode seed = itemWithPk("disjoint-" + i); + seed.set("version", numberAttr("0")); + service.putItem("Counters", seed, "us-east-1"); + } + + AtomicInteger txId = new AtomicInteger(); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + int id = txId.getAndIncrement(); + String keyA = "disjoint-" + (id * 2); + String keyB = "disjoint-" + (id * 2 + 1); + + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":v0", numberAttr("0")); + exprValues.set(":v1", numberAttr("1")); + + ObjectNode tx1 = buildUpdateTx(keyA, exprValues); + ObjectNode tx2 = buildUpdateTx(keyB, exprValues); + service.transactWriteItems(List.of(tx1, tx2), "us-east-1"); + }); + + assertTrue(errors.isEmpty(), + () -> "disjoint transactions must not deadlock or cancel: " + errors); + + for (int i = 0; i < OPS_PER_SCENARIO * 2; i++) { + JsonNode stored = service.getItem("Counters", pkKey("disjoint-" + i)); + assertEquals("1", stored.get("version").get("N").asText(), + "disjoint-" + i + " should be committed"); + } + } + + @RepeatedTest(REPEATS) + void concurrent_batchWriteItem_accumulates_without_lost_writes() throws InterruptedException { + createCounterTable(); + + AtomicInteger idSource = new AtomicInteger(); + ConcurrentHashMap submittedIds = new ConcurrentHashMap<>(); + + List errors = runConcurrently(OPS_PER_SCENARIO, () -> { + int id = idSource.getAndIncrement(); + List writeRequests = new ArrayList<>(); + for (int j = 0; j < 5; j++) { + String itemId = "batch-" + id + "-" + j; + submittedIds.put(itemId, true); + ObjectNode item = itemWithPk(itemId); + item.set("batch", numberAttr(String.valueOf(id))); + + ObjectNode putRequest = mapper.createObjectNode(); + putRequest.set("Item", item); + ObjectNode req = mapper.createObjectNode(); + req.set("PutRequest", putRequest); + writeRequests.add(req); + } + service.batchWriteItem(Map.of("Counters", writeRequests), "us-east-1"); + }); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + for (String itemId : submittedIds.keySet()) { + assertNotNull(service.getItem("Counters", pkKey(itemId)), + "every batch-submitted item must land: " + itemId); + } + } + + @RepeatedTest(REPEATS) + void concurrent_updateItem_preserves_stream_order() throws InterruptedException { + TableDefinition table = createCounterTable(); + StreamDescription sd = streamService.enableStream( + table.getTableName(), table.getTableArn(), "NEW_IMAGE", "us-east-1"); + + String pk = "streamed"; + ObjectNode key = pkKey(pk); + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":start", numberAttr("0")); + exprValues.set(":inc", numberAttr("1")); + + int ops = 20; + + List errors = runConcurrently(ops, () -> service.updateItem( + "Counters", key, null, + "SET cnt = if_not_exists(cnt, :start) + :inc", + null, exprValues, "NONE")); + + assertTrue(errors.isEmpty(), () -> "unexpected errors: " + errors); + + String iterator = streamService.getShardIterator(sd.getStreamArn(), + DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null); + DynamoDbStreamService.GetRecordsResult pulled = streamService.getRecords(iterator, 1000); + + assertEquals(ops, pulled.records().size(), + "stream must emit one record per mutation"); + + // The NEW_IMAGE.cnt values, read in stream order, must be strictly increasing. + int previous = 0; + for (var record : pulled.records()) { + JsonNode newImage = record.getNewImage(); + assertNotNull(newImage, "NEW_IMAGE view type must populate newImage"); + int current = Integer.parseInt(newImage.get("cnt").get("N").asText()); + assertEquals(previous + 1, current, + "stream events must be emitted in the order the mutations landed"); + previous = current; + } + assertEquals(ops, previous, "final event must reflect final counter value"); + } + + @Test + void baseline_single_threaded_still_works() { + createCounterTable(); + + ObjectNode key = pkKey("single"); + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":start", numberAttr("0")); + exprValues.set(":inc", numberAttr("1")); + + for (int i = 1; i <= 10; i++) { + service.updateItem("Counters", key, null, + "SET cnt = if_not_exists(cnt, :start) + :inc", + null, exprValues, "ALL_NEW"); + } + + JsonNode stored = service.getItem("Counters", key); + assertNotNull(stored); + assertEquals("10", stored.get("cnt").get("N").asText()); + } +}