feat(cloudformation): list a deleted stack and report its DeletionTime (#4246)

* feat(cloudformation): list a deleted stack and report its DeletionTime

A deleted stack is already retained so DescribeStacks and DescribeStackEvents
keep answering for it by stack id after the delete, but the record they answer
with was incomplete in two ways.

It carried no deletion time, so DescribeStacks reported DELETE_COMPLETE with
nothing saying when. Stack now has a deletionTime, set as the stack reaches
DELETE_COMPLETE from the same service clock the retention window uses, and the
query handler emits DeletionTime wherever AWS does.

ListStacks omitted deleted stacks entirely. AWS keeps one there as
DELETE_COMPLETE long after DescribeStacks has stopped answering for it by name,
which is how a client reconciles what it deployed against what is left, and a
StackStatusFilter of DELETE_COMPLETE selects exactly those. Retained stacks are
now merged into the listing, still scoped to the caller's account and region and
still dropped once the window passes. A name reused after a delete lists twice,
once per stack id, as it does on AWS. Resource Explorer reads the live map
directly and is unaffected.

Restores deleted-stack-retention-seconds to application.yml, which #849 dropped
in a merge: the knob kept working on its @WithDefault, but the repository YAML
is the source of truth for what a deployment actually runs. Pinned in the test
YAML too, since the retention tests advance the clock past that exact window.

Nothing here changes how a delete runs, and it does not make a multi-stack cdk
destroy work: that client polls a destroy entirely by stack name, so a record
retained by stack id, these two members included, never enters its path.
DeleteStack does already return before the delete finishes, and the stack does
pass through DELETE_IN_PROGRESS, but the whole delete completes in roughly 15ms,
well inside one poll interval, so a client that starts watching when it issues
the delete finds the stack gone by name on its first poll. Giving a deleting
stack an observable window is separate work.

* fix(cloudformation): set a stack's deletion time before publishing the status

Stack.status is volatile and is documented as the publishing write of a deploy:
a reader that observes a terminal status is guaranteed to observe every write
that preceded it. deletionTime was assigned after it, outside that guarantee, so
a DescribeStacks running concurrently with the last step of a delete could
observe DELETE_COMPLETE while deletionTime was still null and answer with no
DeletionTime element at all.

Assigning it first puts it inside the same happens-before edge as the rest of
the delete. The window is nanoseconds wide and no test can land in it reliably,
so this carries none; the ordering rule is the thing being fixed, and the
comment records it so the next edit here keeps it.

* fix(cloudformation): retain a deleted stack before it leaves the live map

The handover at the end of a delete removed the stack from the live map, wrote
its removal through to storage, and only then retained it as deleted. A
ListStacks landing between the removal and the retention found it in neither
map and dropped it from the listing, though the stack both existed a moment ago
and is retained a moment later.

Retaining before removing closes that window. The stack is then briefly in both
maps, which is harmless: they hold the same Stack, and listStacks now reduces by
stack id, so it is listed exactly once throughout. Nothing else reads both maps,
since resolveStackForDescribe consults the retained one only after the live
lookup has missed.

Greptile reported the listing could also show the stack twice. It could not:
the old order removed before it inserted, so the two maps never overlapped. The
duplicate only becomes possible with this ordering, which is why the reduction
comes with it.

The test drives 60 deletes with four concurrent listings each. It fails on every
run against the old ordering and passes on every run against this one. It pins
the retention window open through a profile: the window is measured on the test
MutableClock, which advances on every read, and the pollers would otherwise
expire the retained record themselves.

* style(cloudformation): order the Stream import with the rest of java.util

java.util.stream.Stream landed between java.util.regex and java.util.concurrent
when it was added. It now follows both, the order AGENTS.md asks for. Only the
line this branch introduced moves; the block's older irregularities are left
where they are.

* fix(cloudformation): read the live stacks before creating the deleted-stack view

Retaining a stack before removing it keeps it in at least one map at every
instant, but listStacks built both of its views up front, the retained one
first and the live one after. A ConcurrentHashMap view reflects the table at
some point at or since its own creation and is not guaranteed to reflect a
modification made after it, so the retained view, created before the retain,
need never show the stack, while the live view, created after the remove, can
already miss it. A listing landing there loses the stack in both, which is the
window the retain-before-remove ordering was meant to close. Traversing the
retained view second does not help: creation bounds the guarantee, not
traversal.

The maps are now read one after the other instead of through a concatenated
pipeline, the live one first and in full, so the retained view is created after
any remove the live pass could have missed, and therefore after the retain that
preceded it. The reduction by stack id stays: the overlap it covers is real.

No test. The fault is the absence of a JDK guarantee rather than a behaviour:
these views do in practice reflect a later put, so the old ordering passes every
time and nothing can force it not to. The existing listing-race test still
covers the retain-before-remove ordering this rests on.

The java.util.stream.Stream import goes with Stream.concat, which the change
removes.

* test(cloudformation): stop the listing-race pollers on every exit path

The pollers were stopped after awaitDeleted returned, so a throw from the delete
or the wait left four non-daemon threads spinning on listStacks for the rest of
the run. That holds the test JVM open and buries the failure that caused it
under a hang, which is a far worse thing to debug than the failure itself.

Shutdown moves into a finally, so a failing delete stops them on its way out.
Each join is bounded and a thread still alive afterwards is interrupted and
recorded, with the poller loop now checking its own interrupt flag so that
interrupt is not merely decorative. The check that they all stopped is asserted
after the try and never inside the finally, where it would replace whatever the
delete threw with its own failure. The threads are daemons as a backstop, so a
future edit that throws somewhere nothing throws today still cannot wedge the
suite.

Also replaces an assertTrue(false, ...) in the wait helper with fail(...), which
says the same thing and reads as what it is. Noted here rather than slipped in.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-23 18:01:55 -05:00
1 parent 97a2a08e1f
commit 67f06c3ac9
8 files changed
+430 -5

No files matched your search

@@ -0,0 +1,177 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* A stack being deleted moves from the live map to the retained-deleted one. Handing it over in
* the wrong order leaves a window in which it is in neither, and a ListStacks landing there loses
* a stack that both exists and is retained.
*/
@QuarkusTest
@TestProfile(CloudFormationDeletedStackListingRaceTest.LongRetentionProfile.class)
class CloudFormationDeletedStackListingRaceTest {
/**
* Retention long enough that it cannot end this test. The shipped 30 seconds are measured on
* the test {@code MutableClock}, which advances a millisecond on every read, and the pollers
* below read it thousands of times: left at the default they expire the retained record
* themselves and lose the stack for a reason that has nothing to do with the handoff.
*/
public static final class LongRetentionProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.cloudformation.deleted-stack-retention-seconds", "86400");
}
}
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
/**
* The window is one map removal plus a storage delete wide, so a single reader on a single
* delete rarely lands in it. Several readers across many deletes make it dependable: on the
* unfixed ordering this fails on every run, and it still takes only a few seconds.
*/
private static final int ATTEMPTS = 60;
private static final int POLLERS = 4;
/** Generous: a poller checks the stop flag every pass, so overrunning this means it is stuck. */
private static final long POLLER_SHUTDOWN_MILLIS = 10_000;
@Inject
CloudFormationService cloudFormationService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void listStacks_whileADeleteHandsTheStackOver_neverLosesIt() throws Exception {
for (int attempt = 0; attempt < ATTEMPTS; attempt++) {
String stackName = "list-race-stack-" + attempt;
String stackId = createStack(stackName, attempt);
AtomicBoolean stop = new AtomicBoolean();
AtomicReference<String> lost = new AtomicReference<>();
List<Thread> pollers = new ArrayList<>();
for (int p = 0; p < POLLERS; p++) {
Thread poller = new Thread(() -> {
while (!stop.get() && !Thread.currentThread().isInterrupted()) {
Stack listed = RequestScopes.callAs(ACCOUNT, () ->
cloudFormationService.listStacks(REGION).stream()
.filter(s -> stackId.equals(s.getStackId()))
.findFirst()
.orElse(null));
if (listed == null) {
lost.compareAndSet(null, "ListStacks lost " + stackId + " mid-delete");
return;
}
}
}, "list-race-poller-" + p);
// Daemon as a backstop: a poller left running by some future edit that throws
// where nothing throws today must not be able to hold the test JVM open.
poller.setDaemon(true);
pollers.add(poller);
poller.start();
}
List<String> stillRunning = new ArrayList<>();
try {
deleteStack(stackName);
awaitDeleted(stackId);
} finally {
// In a finally so a failing delete stops the pollers on its way out rather than
// leaving them spinning, which would bury the failure that caused it.
stop.set(true);
for (Thread poller : pollers) {
poller.join(POLLER_SHUTDOWN_MILLIS);
if (poller.isAlive()) {
poller.interrupt();
stillRunning.add(poller.getName());
}
}
}
// After the try, never inside the finally: an assertion there would replace whatever
// the delete threw with its own failure.
assertTrue(stillRunning.isEmpty(), "pollers did not stop: " + stillRunning);
assertNull(lost.get(), lost.get());
}
}
private String createStack(String stackName, int attempt) {
String template = """
{
"Resources": {
"Q1": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "list-race-q1-%1$d" } },
"Q2": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "list-race-q2-%1$d" } },
"T1": { "Type": "AWS::SNS::Topic", "Properties": { "TopicName": "list-race-t1-%1$d" } }
}
}
""".formatted(attempt);
String response = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"))
.extract().asString();
return response.substring(response.indexOf("<StackId>") + "<StackId>".length(),
response.indexOf("</StackId>"));
}
private void deleteStack(String stackName) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
}
private void awaitDeleted(String stackId) throws InterruptedException {
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackId)
.when()
.post("/")
.then()
.extract().asString();
if (body.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")) {
return;
}
Thread.sleep(2);
}
fail("stack " + stackId + " never reached DELETE_COMPLETE");
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -2213,6 +2214,179 @@ class CloudFormationIntegrationTest {
.body(containsString("does not exist"));
}
@Test
void describeDeletedStack_byArn_reportsItsDeletionTime() throws Exception {
String stackArn = createAndDeleteStack("deleted-deletion-time-stack",
"deleted-deletion-time-test-bucket");
String xml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackArn)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
assertThat(xml, containsString("<StackStatus>DELETE_COMPLETE</StackStatus>"));
// The service clock, not the wall clock: the test clock starts the run at 2026-01-01.
assertThat(xml, containsString("<DeletionTime>2026-01-01T"));
}
@Test
void describeLiveStack_reportsNoDeletionTime() {
String template = """
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": { "BucketName": "live-no-deletion-time-test-bucket" }
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "live-no-deletion-time-stack")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", "live-no-deletion-time-stack")
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("<DeletionTime>")));
}
@Test
void listStacks_includesADeletedStackAsDeleteComplete() throws Exception {
String stackArn = createAndDeleteStack("listed-deleted-stack",
"listed-deleted-test-bucket");
String member = listStacksMemberFor(listStacksXml(null), stackArn);
assertThat(member, containsString("<StackName>listed-deleted-stack</StackName>"));
assertThat(member, containsString("<StackStatus>DELETE_COMPLETE</StackStatus>"));
assertThat(member, containsString("<DeletionTime>2026-01-01T"));
}
@Test
void listStacks_filteredToDeleteComplete_returnsTheDeletedStackAndNoLiveOne() throws Exception {
String stackArn = createAndDeleteStack("listed-filtered-deleted-stack",
"listed-filtered-deleted-test-bucket");
String xml = listStacksXml("DELETE_COMPLETE");
assertThat(xml, containsString("<StackId>" + stackArn + "</StackId>"));
assertThat(xml, not(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>")));
}
@Test
void listStacks_afterTheRetentionWindow_dropsTheDeletedStack() throws Exception {
String stackArn = createAndDeleteStack("listed-expiring-deleted-stack",
"listed-expiring-deleted-test-bucket");
assertThat(listStacksXml(null), containsString("<StackId>" + stackArn + "</StackId>"));
clock.advance(Duration.ofSeconds(31));
assertThat(listStacksXml(null), not(containsString("<StackId>" + stackArn + "</StackId>")));
}
/**
* Creates a single-bucket stack, deletes it, and answers its stack ARN once the delete has
* reached DELETE_COMPLETE. DeleteStack hands the work to a background executor, so the
* DELETE_COMPLETE event is what says the retained record is in place.
*/
private String createAndDeleteStack(String stackName, String bucketName) throws Exception {
String template = """
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": { "BucketName": "%s" }
}
}
}
""".formatted(bucketName);
String createResponse = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"))
.extract().asString();
String stackArn = createResponse.substring(
createResponse.indexOf("<StackId>") + "<StackId>".length(),
createResponse.indexOf("</StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String events = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackArn)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
if (events.contains("<ResourceStatus>DELETE_COMPLETE</ResourceStatus>")) {
return stackArn;
}
Thread.sleep(200);
}
throw new AssertionError("stack " + stackName + " never reached DELETE_COMPLETE");
}
private String listStacksXml(String statusFilter) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListStacks");
if (statusFilter != null) {
request = request.formParam("StackStatusFilter.member.1", statusFilter);
}
return request
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
}
/** The one ListStacks summary carrying this stack id, so an assertion cannot match another. */
private static String listStacksMemberFor(String xml, String stackArn) {
int idAt = xml.indexOf("<StackId>" + stackArn + "</StackId>");
assertTrue(idAt >= 0, "stack " + stackArn + " is not listed:\n" + xml);
return xml.substring(xml.lastIndexOf("<member>", idAt), xml.indexOf("</member>", idAt));
}
@Test
void deleteChangeSet_nonExistentChangeSet_returnsError() {
String template = """