fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy (#2365)

* fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy

CreateStack had no name-conflict check at all: createChangeSet's
computeIfAbsent silently reused any existing stack regardless of
status, so a second CreateStack for a live name re-ran the template
against the same stack instead of failing. That left callers no
AWS-faithful way to redeploy over a ROLLBACK_COMPLETE stack except an
explicit DeleteStack first - which destroys the failed attempt's
DescribeStackEvents before an operator gets to read them.

Now a CREATE-type change set against an existing stack throws
AlreadyExistsException unless that stack is ROLLBACK_COMPLETE, in
which case it's replaced with a fresh stack (new StackId, empty
resources/events) at execute time - the moment a redeploy is actually
requested, not eagerly when the rollback itself completes. The failed
attempt stays fully describable for as long as nobody's asked to
retry.

Closes #2207.

* 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.

* fix(cloudformation): drop the unverified ROLLBACK_COMPLETE recreate exemption

The previous commit let a CREATE change set proceed directly over a
ROLLBACK_COMPLETE stack, deleting and recreating it at execute time,
on the claim that AWS added this in 2022. That claim was wrong and
went into the PR without a source - checked now against AWS's own
CreateStack API reference and troubleshooting guide, both of which
document AlreadyExists/AlreadyExistsException unconditionally for an
existing stack name, with no ROLLBACK_COMPLETE carve-out anywhere.

ROLLBACK_COMPLETE is a real conflict like any other status; only an
explicit DeleteStack clears the name for reuse. This is exactly the
simpler option #2207 itself proposed ("let DeleteStack remove it"),
which the diagnostic-preservation fix from the first commit already
supports on its own - the stack stays fully describable for as long
as nobody deletes it, whether that's a rejected retry or a real
DeleteStack call.

* fix(cloudformation): let a CREATE change set attach to a REVIEW_IN_PROGRESS stack

The unconditional AlreadyExistsException broke the deploy retry flow.
`aws cloudformation deploy` (and SAM, which shares the code) treats a
REVIEW_IN_PROGRESS stack as nonexistent - has_stack in the AWS CLI's
deployer.py ends with `return stack["StackStatus"] != "REVIEW_IN_PROGRESS"`
- and sends a second CREATE change set against it, which real
CloudFormation accepts: a CREATE change set leaves the stack in
REVIEW_IN_PROGRESS until somebody executes it, so it is a placeholder
rather than a deployment to conflict with. Retrying a failed deploy
before any execute now works again.

The exemption is scoped to the CreateChangeSet operation rather than to
the status alone, which is the part a one-line status check would have
got wrong. CreateStack funnels through this same method and newStack()
sets REVIEW_IN_PROGRESS immediately, so every brand-new stack carries
that status for the window between newStack() and the execute that
follows it. Keying only on the status therefore hands a racing
CreateStack the first request's stack and reopens the duplicate
provisioning race closed in baf406b5 - confirmed by running the
unscoped version against createStack_concurrentRequestsForUnusedName_
exactlyOneSucceeds, where all 16 concurrent requests then "succeed"
instead of 1.

LocalStack draws the same line: the REVIEW_IN_PROGRESS exemption lives
only in its create_change_set, while create_stack conflicts on any
status but DELETE_COMPLETE.

CreateStack, UpdateStack and StackSet deployment keep the existing
signatures and stay unexempted; only the CreateChangeSet handler moves
to the new entry point.

Tests: two CREATE change sets before execution land on the same stack
and the second executes normally; a CREATE change set after execution
still conflicts; CreateStack against a REVIEW_IN_PROGRESS stack still
conflicts, pinning the implicit path so this cannot later be collapsed
into a status-only check. Full cloudformation package: 603 tests, 0
failures.

* fix(cloudformation): record a change set inside the stack's per-key lock

Stack#changeSets is a plain LinkedHashMap, and the insert ran after
stacks.compute() had already released the per-key lock. Two requests
that legitimately share one stack - two UPDATE change sets on a live
stack, or two CREATE change sets attaching to the same
REVIEW_IN_PROGRESS placeholder - could therefore both write it
unsynchronized, losing an accepted change set or breaking the map's
links.

Build and insert the ChangeSet inside the same remapping function that
resolves the stack, so name reservation, the REVIEW_IN_PROGRESS event
and the change-set insert are one atomic unit per stack key. The
brand-new-stack branch records its event there too: a stack the
remapping function has not returned yet is not in the map, so no other
thread can reach it, and keeping the sequence in one place beats
splitting it either side of the lock. persistStack() stays outside -
it is storage I/O, and compute()'s contract is that the remapping
function does short, non-blocking work.

The unsynchronized write predates this PR - it is byte-identical on
main, where the UPDATE path reaches it the same way - so this is
hardening of an adjacent hazard rather than a fix for a regression.
The rest of Stack's collections (events, resources, outputs) are still
mutated outside any lock; that is filed as #2419 rather than widened
into here.

Adds createChangeSet_concurrentRequestsOnSamePlaceholder_keepEveryChangeSet,
which fires 16 concurrent CREATE change sets at one placeholder and
asserts every one is accepted and still listed afterwards. It is a
behavioural guard, not a reproducer: run against the previous ordering
it passes, because the window between the two puts is nanoseconds
against an HTTP round trip. The correctness here comes from the
structure, not from the test catching the race.

Full cloudformation package: 604 tests, 0 failures.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-19 21:46:07 -05:00
1 parent 7b83bd5283
commit c54f8ddf02
3 files changed
+506 -35

No files matched your search

@@ -210,7 +210,9 @@ public class CloudFormationQueryHandler {
List<String> capabilities = extractList(params, "Capabilities.member.");
Map<String, String> tags = extractTags(params);
ChangeSet cs = cfnService.createChangeSet(stackName, changeSetName, changeSetType,
// The CreateChangeSet operation, unlike the change sets CreateStack/UpdateStack build
// internally, may attach a CREATE change set to a stack still in REVIEW_IN_PROGRESS.
ChangeSet cs = cfnService.createChangeSetForRequest(stackName, changeSetName, changeSetType,
templateBody, templateUrl, parameters, capabilities, tags, region);
String xml = new XmlBuilder()
@@ -151,7 +151,31 @@ public class CloudFormationService {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId());
parameters, capabilities, tags, region, regionResolver.getAccountId(), false);
}
/**
* Entry point for the {@code CreateChangeSet} operation itself, as opposed to the change sets
* {@code CreateStack}/{@code UpdateStack}/StackSet deployment create internally and execute
* immediately.
*
* <p>The difference matters for exactly one case: a CREATE change set is allowed to attach to a
* stack already sitting in {@code REVIEW_IN_PROGRESS}, because that status means "a CREATE
* change set was created here and nobody has executed it yet" - the stack is a placeholder, not
* a deployment. {@code aws cloudformation deploy} and SAM rely on this: {@code has_stack} in the
* AWS CLI's deployer treats a {@code REVIEW_IN_PROGRESS} stack as nonexistent and sends a second
* CREATE change set against it, which real CloudFormation accepts. Routing that exemption
* through a separate entry point rather than the shared one keeps it off the implicit callers,
* where a stack is only ever momentarily {@code REVIEW_IN_PROGRESS} - between {@link #newStack}
* and the execute that immediately follows - and treating that window as reusable would let two
* racing {@code CreateStack} requests both provision the same template.
*/
public ChangeSet createChangeSetForRequest(String stackName, String changeSetName, String changeSetType,
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, regionResolver.getAccountId(), true);
}
/**
@@ -168,48 +192,93 @@ public class CloudFormationService {
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
parameters, capabilities, tags, region, accountId, false);
}
private ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId,
boolean attachToReviewInProgressStack) {
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
// Reject an unresolvable condition dependency graph up front, before any stack state is
// created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.
validateConditionDependencies(resolvedTemplate, parameters, region, accountId);
// 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;
// A CREATE change set against a name that already has a stack of any status - including
// ROLLBACK_COMPLETE - is a real conflict: AWS requires an explicit DeleteStack before a
// name can be reused, even when the existing stack already failed to create (see #2207).
//
// The one exception is a stack in REVIEW_IN_PROGRESS, and only for the CreateChangeSet
// operation itself (see createChangeSetForRequest): that status means a CREATE change set
// exists but has never been executed, so the stack is a placeholder the next CREATE change
// set attaches to rather than a deployment to conflict with. The AWS CLI's `deploy` and SAM
// both depend on it - their has_stack treats REVIEW_IN_PROGRESS as nonexistent and sends a
// second CREATE change set, which real CloudFormation accepts.
//
// 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 stack already there
// and throws, instead of both executing the template concurrently. That race is also why
// the exemption above is scoped to the explicit operation: on the CreateStack path every
// brand-new stack is REVIEW_IN_PROGRESS for the moment between newStack() and the execute
// that follows it, so exempting the status outright would hand the racing request the same
// stack and reopen exactly this hole.
//
// Recording the change set happens inside the same remapping function, for the same reason.
// Stack#changeSets is a plain LinkedHashMap, so two requests that legitimately share one
// stack - two UPDATE change sets on a live stack, or two CREATE change sets attaching to the
// same REVIEW_IN_PROGRESS placeholder - would otherwise both write it after the per-key lock
// was already released, losing an accepted change set or corrupting the map's links. Only
// persistStack() stays outside: it is storage I/O, and compute()'s contract is that the
// remapping function does short, non-blocking work.
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
ChangeSet[] created = new ChangeSet[1];
Stack stack = stacks.compute(key(stackName, region), (k, existing) -> {
Stack target;
if (existing == null) {
target = newStack(stackName, region);
if (tags != null) target.getTags().putAll(tags);
// A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the
// matching stack-level event (as AWS and LocalStack do) so DescribeStackEvents is
// non-empty straight after change-set creation — tooling such as the AWS SAM CLI
// reads StackEvents[0] there and otherwise fails with an IndexError.
// (CreateChangeSet defaults a null type to CREATE.)
if (isCreateType) {
addEvent(target, target.getStackName(), target.getStackId(),
"AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
}
} else {
boolean reusableReviewPlaceholder =
attachToReviewInProgressStack && "REVIEW_IN_PROGRESS".equals(existing.getStatus());
if (isCreateType && !reusableReviewPlaceholder) {
throw new AwsException("AlreadyExistsException",
"Stack [" + stackName + "] already exists", 400);
}
target = existing;
}
ChangeSet cs = new ChangeSet();
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
cs.setChangeSetName(changeSetName);
cs.setStackName(stackName);
cs.setStackId(target.getStackId());
cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
cs.setTemplateBody(resolvedTemplate);
cs.setParameters(parameters);
cs.setCapabilities(capabilities);
cs.setStatus("CREATE_COMPLETE");
cs.setExecutionStatus("AVAILABLE");
target.getChangeSets().put(changeSetName, cs);
created[0] = cs;
return target;
});
// A CREATE change set puts a brand-new stack into REVIEW_IN_PROGRESS. Record the matching
// stack-level event (as AWS and LocalStack do) so DescribeStackEvents is non-empty straight
// after change-set creation — tooling such as the AWS SAM CLI reads StackEvents[0] there and
// otherwise fails with an IndexError. (CreateChangeSet defaults a null type to CREATE.)
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
if (stackCreated[0] && isCreateType) {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
}
ChangeSet cs = new ChangeSet();
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
cs.setChangeSetName(changeSetName);
cs.setStackName(stackName);
cs.setStackId(stack.getStackId());
cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
cs.setTemplateBody(resolvedTemplate);
cs.setParameters(parameters);
cs.setCapabilities(capabilities);
cs.setStatus("CREATE_COMPLETE");
cs.setExecutionStatus("AVAILABLE");
stack.getChangeSets().put(changeSetName, cs);
persistStack(stack);
return cs;
return created[0];
}
// ── DescribeChangeSet ─────────────────────────────────────────────────────
@@ -20,6 +20,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;
@@ -9655,6 +9660,401 @@ class CloudFormationIntegrationTest {
.body(containsString("CREATE_FAILED"));
}
@Test
void createStack_onExistingActiveStack_throwsAlreadyExistsException() {
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-active-bus" } }
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "cfn-2207-active-stack")
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
// A second CreateStack for the same name, while the first is still ACTIVE, is a real
// conflict - it must not silently re-run the template against the live stack.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "cfn-2207-active-stack")
.formParam("TemplateBody", template)
.when().post("/")
.then()
.body(containsString("AlreadyExistsException"))
.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_onRollbackCompleteStack_alsoThrowsAlreadyExistsException() {
// #2207: a stack whose first CREATE fails ends in ROLLBACK_COMPLETE and stays fully
// describable - it is not deleted eagerly at rollback time. Matching real AWS,
// ROLLBACK_COMPLETE is still a real conflict for CreateStack: an explicit DeleteStack is
// required before the name can be reused (verified against AWS's own CreateStack API
// reference and troubleshooting docs, which list AlreadyExists unconditionally - there is
// no ROLLBACK_COMPLETE carve-out).
String failingTemplate = """
{
"Resources": {
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"Properties": {
"Name": "cfn-2207-redeploy-secret",
"SecretString": "explicit",
"GenerateSecretString": { "PasswordLength": 32 }
}
}
}
}
""";
String stackName = "cfn-2207-redeploy-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when().post("/").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"));
// A second CreateStack still conflicts - the diagnostic is preserved, not silently
// superseded.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when().post("/")
.then().body(containsString("AlreadyExistsException"));
// The failed attempt's diagnostic is still readable after that rejected retry.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("CREATE_FAILED"));
// An explicit DeleteStack, though, clears the way for a fresh CreateStack - matching the
// issue's suggested fix: "let DeleteStack remove it."
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
String workingTemplate = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-redeploy-bus" } }
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", workingTemplate)
.when().post("/").then().statusCode(200).body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
}
@Test
void createChangeSet_secondCreateTypeBeforeExecution_attachesToReviewInProgressStack() {
// `aws cloudformation deploy` (and SAM, which shares the code) treats a REVIEW_IN_PROGRESS
// stack as nonexistent - see has_stack in the AWS CLI's deployer.py - and sends another
// CREATE change set against it, which real CloudFormation accepts: a CREATE change set
// leaves the stack in REVIEW_IN_PROGRESS until somebody executes it, so it is a placeholder
// rather than a deployment to conflict with. Retrying a failed `deploy` before any execute
// must therefore not hit AlreadyExistsException.
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-review-bus" } }
}
}
""";
String stackName = "cfn-2365-review-stack";
String firstStackId = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-1")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/")
.then().statusCode(200).extract().path("CreateChangeSetResponse.CreateChangeSetResult.StackId");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("<StackStatus>REVIEW_IN_PROGRESS</StackStatus>"));
// The retry: same name, still nothing executed. It attaches to the placeholder rather than
// conflicting with it, and lands on the same stack rather than creating a second one.
String secondStackId = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-2")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString("AlreadyExistsException")))
.extract().path("CreateChangeSetResponse.CreateChangeSetResult.StackId");
assertEquals(firstStackId, secondStackId, "the retry should attach to the same placeholder stack");
// Executing the retry's change set still deploys normally.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-2")
.when().post("/").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
}
@Test
void createChangeSet_createTypeAfterExecution_stillThrowsAlreadyExistsException() {
// The exemption is narrow: it covers a stack that never left REVIEW_IN_PROGRESS. Once the
// change set has been executed the stack is a real deployment, and a further CREATE change
// set is the ordinary name conflict again.
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-executed-bus" } }
}
}
""";
String stackName = "cfn-2365-executed-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-1")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-1")
.when().post("/").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "deploy-attempt-2")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/")
.then().body(containsString("AlreadyExistsException"));
}
@Test
void createChangeSet_concurrentRequestsOnSamePlaceholder_keepEveryChangeSet() throws InterruptedException {
// Two requests are allowed to share one stack - two CREATE change sets attaching to the
// same REVIEW_IN_PROGRESS placeholder, or two UPDATE change sets on a live stack. Stack's
// changeSets is a plain LinkedHashMap, so recording the change set has to happen inside the
// same per-key lock that resolves the stack; done afterwards, concurrent writers lose an
// accepted change set or corrupt the map.
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-parallel-bus" } }
}
}
""";
String stackName = "cfn-2365-parallel-stack";
int attempts = 16;
// Establish the placeholder first, so every racing request takes the "attach" path.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "seed")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(attempts);
try {
for (int i = 0; i < attempts; i++) {
String changeSetName = "parallel-" + 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", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/").then().extract().asString();
if (body.contains("<StackId>")) {
accepted.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(attempts, accepted.get(), "every CREATE change set on the placeholder should be accepted");
// Every accepted change set must still be readable - an acknowledged write that vanished
// from the map is exactly the failure this guards.
String listed = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListChangeSets")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
for (int i = 0; i < attempts; i++) {
assertTrue(listed.contains("parallel-" + i), "change set parallel-" + i + " was lost");
}
assertTrue(listed.contains("seed"), "the seed change set was lost");
}
@Test
void createStack_onReviewInProgressStack_throwsAlreadyExistsException() {
// CreateStack does not get the REVIEW_IN_PROGRESS exemption, and must not: every stack it
// creates is REVIEW_IN_PROGRESS for the window between newStack() and the execute that
// immediately follows, so exempting the status on this path would let two racing
// CreateStack requests share one stack and both provision the template - the very race
// createStack_concurrentRequestsForUnusedName_exactlyOneSucceeds covers. LocalStack draws
// the same line: its create_stack conflicts on any status but DELETE_COMPLETE, while only
// its create_change_set exempts REVIEW_IN_PROGRESS.
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2365-implicit-bus" } }
}
}
""";
String stackName = "cfn-2365-implicit-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "pending")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when().post("/")
.then().body(containsString("AlreadyExistsException"));
}
@Test
void createStack_apiGatewayRestApi_withEndpointConfiguration() {
String template = """