fix(cloudformation): make the CreateStack name-conflict check atomic

The existence check (stacks.get) and the stack-map insert
(computeIfAbsent) were two separate operations, so two CreateStack
requests racing for the same never-before-used name could both
observe "absent", pass the check, and then share whichever Stack
computeIfAbsent settled on - each independently executing the
template against it instead of one request getting
AlreadyExistsException.

Fold both into a single stacks.compute() call: it holds the map's
per-key lock for the whole call, so the second racing request now
finds the first's stack already there and throws.

Verified the race is real and the fix closes it: reverting just the
source change while keeping the new concurrency test, 15 of 16
concurrent requests against an unused name "succeeded" (duplicate
provisioning); with the fix, exactly 1 does.
This commit is contained in:
Priamo committed 2026-08-18 00:29:31 -04:00
1 parent d8e66b3ced
commit baf406b5af
2 files changed
+79 -14

No files matched your search

@@ -179,22 +179,26 @@ public class CloudFormationService {
// (deleting the failed attempt at execute time, not here - see the ROLLBACK_COMPLETE
// handling in executeChangeSet) rather than throwing. Every other existing status is a
// real conflict.
//
// The existence check and the insert must be one atomic operation: compute() holds the
// map's per-key lock for the whole call, so two CreateStack requests racing for the same
// unused name can no longer both see "absent" and then share whichever Stack
// computeIfAbsent settled on - the second one now finds the first's (non-ROLLBACK_COMPLETE)
// stack already there and throws, instead of both executing the template concurrently.
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
Stack existing = stacks.get(key(stackName, region));
if (isCreateType && existing != null && !"ROLLBACK_COMPLETE".equals(existing.getStatus())) {
throw new AwsException("AlreadyExistsException",
"Stack [" + stackName + "] already exists", 400);
}
// Detect first creation atomically: the mapping function runs at most once per key, so the
// flag is only set for the thread that actually creates the stack (no double-recording under
// concurrent CreateChangeSet calls).
boolean[] stackCreated = {false};
Stack stack = stacks.computeIfAbsent(key(stackName, region), k -> {
stackCreated[0] = true;
Stack s = newStack(stackName, region);
if (tags != null) s.getTags().putAll(tags);
return s;
Stack stack = stacks.compute(key(stackName, region), (k, existing) -> {
if (existing == null) {
stackCreated[0] = true;
Stack s = newStack(stackName, region);
if (tags != null) s.getTags().putAll(tags);
return s;
}
if (isCreateType && !"ROLLBACK_COMPLETE".equals(existing.getStatus())) {
throw new AwsException("AlreadyExistsException",
"Stack [" + stackName + "] already exists", 400);
}
return existing;
});
// A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the matching
@@ -19,6 +19,11 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
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 java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
@@ -9535,6 +9540,62 @@ class CloudFormationIntegrationTest {
.body(containsString("already exists"));
}
@Test
void createStack_concurrentRequestsForUnusedName_exactlyOneSucceeds() throws InterruptedException {
// The existence check and the stack-map insert used to be two separate operations, so two
// requests racing for the same never-before-used name could both observe "absent" and then
// share whichever Stack computeIfAbsent settled on, each independently executing the
// template - duplicate provisioning instead of one AlreadyExistsException. Verifies the
// check-and-insert is now atomic.
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-concurrent-bus" } }
}
}
""";
String stackName = "cfn-2207-concurrent-stack";
int attempts = 16;
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger succeeded = new AtomicInteger();
AtomicInteger conflicted = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(attempts);
try {
for (int i = 0; i < attempts; i++) {
pool.submit(() -> {
ready.countDown();
try {
go.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
String body = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when().post("/").then().extract().asString();
if (body.contains("AlreadyExistsException")) {
conflicted.incrementAndGet();
} else if (body.contains("<StackId>")) {
succeeded.incrementAndGet();
}
});
}
assertTrue(ready.await(10, TimeUnit.SECONDS), "workers failed to line up in time");
go.countDown();
} finally {
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "requests did not finish in time");
}
assertEquals(1, succeeded.get(), "exactly one CreateStack should have won the race");
assertEquals(attempts - 1, conflicted.get(), "every other request should see AlreadyExistsException");
}
@Test
void createStack_redeployOverRollbackComplete_succeedsWithFreshStack() {
// #2207: floci used to give callers no way to redeploy over ROLLBACK_COMPLETE except an