fix(cloudformation): delete dependents first on update rollback (#5943)

The update rollback deleted what a failed update added in map order, so a
resource could go before the resources that depend on it. It now walks
the template's dependency order in reverse, as stack delete and the
cleanup of committed replacements do. Those walks ignore resource
conditions and count every Fn::If branch, since a failed rollback
restores the parameters while a resource can stay on the branch the
failed update chose; where counting every branch would close a cycle,
the branches chosen now decide just those edges. A resource the template
no longer names is deleted before the held resources its attributes
name, leftovers included, and a NAT gateway records its subnet and
Elastic IP under hidden attributes for this, restored with the public
ones when a replacement is reverted.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-18 21:06:53 -04:00
1 parent a6e2a5921e
commit d273d4f4e0
8 files changed
+681 -16

No files matched your search

@@ -0,0 +1,138 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.reset;
/**
* A NAT gateway the template no longer names, left by a rollback that skipped it, still holds its
* Elastic IP and its subnet, so DeleteStack has to delete it before either of them, though only
* its hidden attributes say what it uses.
*/
@QuarkusTest
class CloudFormationNatGatewayLeftoverIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/cloudformation/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/ec2/aws4_request";
@InjectSpy
Ec2Service ec2Service;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void deleteStackDeletesASkippedNatGatewayBeforeItsElasticIpSubnetAndVpc() {
String stack = "nat-leftover-" + Long.toString(System.nanoTime(), 36);
AtomicBoolean failNatDeletes = new AtomicBoolean(true);
doAnswer(invocation -> {
if (failNatDeletes.get()) {
throw new AwsException("InternalError", "simulated NAT gateway delete failure", 500);
}
return invocation.callRealMethod();
}).when(ec2Service).deleteNatGateway(anyString(), anyString());
try {
Map<String, String> created = createStack(stack, template(stack, ""));
String nat = """
,
"Nat": {"Type": "AWS::EC2::NatGateway",
"Properties": {"SubnetId": {"Ref": "Subnet"},
"AllocationId": {"Fn::GetAtt": ["Eip", "AllocationId"]}}},
"BadSecret": {"Type": "AWS::SecretsManager::Secret", "DependsOn": "Nat",
"Properties": {"Name": "%1$s-secret", "SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}}}""".formatted(stack);
request("UpdateStack", "StackName", stack, "TemplateBody", template(stack, nat)).statusCode(200);
String reason = CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_FAILED").reason();
assertTrue(reason.contains("Nat"), reason);
failNatDeletes.set(false);
request("ContinueUpdateRollback", "StackName", stack, "ResourcesToSkip.member.1", "Nat").statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(1, XmlParser.extractAll(ec2("DescribeNatGateways", "Filter.1.Name", "subnet-id",
"Filter.1.Value.1", created.get("Subnet")).statusCode(200).extract().asString(), "natGatewayId")
.size(), "the skipped gateway is left in place");
request("DeleteStack", "StackName", stack).statusCode(200);
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
ec2("DescribeVpcs", "VpcId.1", created.get("Vpc")).statusCode(400)
.body(containsString("InvalidVpcID.NotFound"));
assertEquals(List.of(), XmlParser.extractAll(ec2("DescribeAddresses", "PublicIp.1", created.get("Eip"))
.extract().asString(), "allocationId"));
} finally {
failNatDeletes.set(false);
reset(ec2Service);
// Best effort: a failed run may leave the stack DELETE_FAILED or mid-rollback.
if (request("DescribeStacks", "StackName", stack).extract().statusCode() == 200) {
request("DeleteStack", "StackName", stack);
}
}
}
/** A VPC with one subnet and an Elastic IP, plus whatever an update adds. */
private static String template(String stack, String extraResources) {
return """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.96.0.0/16",
"Tags": [{"Key": "floci-it", "Value": "%1$s"}]}},
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.96.1.0/24",
"AvailabilityZone": "us-east-1a"}},
"Eip": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}}%2$s
},
"Outputs": {
"Vpc": {"Value": {"Ref": "Vpc"}},
"Subnet": {"Value": {"Ref": "Subnet"}},
"Eip": {"Value": {"Ref": "Eip"}}
}
}""".formatted(stack, extraResources);
}
private static Map<String, String> createStack(String stack, String templateBody) {
request("CreateStack", "StackName", stack, "TemplateBody", templateBody).statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
String xml = request("DescribeStacks", "StackName", stack).statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "member", "OutputKey", "OutputValue");
}
private static ValidatableResponse ec2(String action, String... values) {
return send(EC2_AUTH, action, values);
}
private static ValidatableResponse request(String action, String... values) {
return send(CFN_AUTH, action, values);
}
private static ValidatableResponse send(String auth, String action, String... values) {
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("Action", action);
for (int i = 0; i < values.length; i += 2) {
parameters.put(values[i], values[i + 1]);
}
return given().contentType("application/x-www-form-urlencoded").header("Authorization", auth)
.formParams(parameters).when().post("/").then().log().ifValidationFails();
}
}
@@ -783,6 +783,275 @@ class CloudFormationServiceRollbackTest {
verify(provisioner, times(2)).rollbackUpdate(eq(dashboard), any());
}
/**
* A retry walks the failed update's template with the parameters the first pass already
* restored, so a condition the update turned on can read false again. A resource the stack
* holds is still ordered by its dependencies, so the load balancer the update created on the
* subnet it added is deleted before that subnet, not after it. The load balancer is inserted
* first, so falling back to the map's order would delete the subnet first too.
*/
@Test
void resumeUpdateRollback_ordersAHeldResourceByItsDependenciesWhateverItsConditionReadsNow() {
Stack stack = new Stack();
stack.setStackName("retry-flipped-condition");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setTemplateBody("""
{
"Parameters": {"Env": {"Type": "String"}},
"Conditions": {"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}},
"Resources": {
"SubnetC": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "vpc-1", "CidrBlock": "10.0.3.0/24"}},
"ProdAlb": {
"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
"Condition": "IsProd",
"Properties": {"Subnets": [{"Ref": "SubnetC"}]}
}
}
}
""");
stack.replaceParameters(Map.of("Env", "dev"));
stack.replaceResolvedParameters(Map.of("Env", "dev"));
StackResource subnet = resource("SubnetC", "subnet-c", "AWS::EC2::Subnet", "CREATE_COMPLETE");
StackResource loadBalancer = resource("ProdAlb", "arn:aws:elasticloadbalancing:us-east-1:000000000000:"
+ "loadbalancer/app/prod/1", "AWS::ElasticLoadBalancingV2::LoadBalancer", "CREATE_COMPLETE");
stack.getResources().put(loadBalancer.getLogicalId(), loadBalancer);
stack.getResources().put(subnet.getLogicalId(), subnet);
stack.setUpdateRollbackSnapshot(new StackUpdateSnapshot("previous-template", "previous-original",
Map.of("Env", "dev"), Map.of("Env", "dev"), Map.of(), Map.of(), Map.of(), Map.of()));
stack.setUpdateRollbackResourceIds(List.of("SubnetC", "ProdAlb"));
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
service.resumeUpdateRollback(stack, List.of(), false, REGION);
assertEquals("UPDATE_ROLLBACK_COMPLETE", stack.getStatus());
InOrder deletes = inOrder(provisioner);
deletes.verify(provisioner).delete(eq(loadBalancer), anyString());
deletes.verify(provisioner).delete(eq(subnet), anyString());
}
/**
* A held resource can depend on a condition-false one the stack no longer holds, such as a role
* an earlier cleanup deleted while the load balancer on it failed to delete. Ordering must not
* then give up on the whole template: the load balancer still goes before the subnet it uses.
*/
@Test
void deleteStack_withAHeldResourceOnAGoneConditionFalseOne_stillDeletesDependentsFirst() {
Stack stack = new Stack();
stack.setStackName("delete-held-on-gone-conditional");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_COMPLETE");
stack.setTemplateBody("""
{
"Parameters": {"Env": {"Type": "String"}},
"Conditions": {"IsProd": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}},
"Resources": {
"ProdRole": {"Type": "AWS::IAM::Role", "Condition": "IsProd"},
"SubnetC": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "vpc-1", "CidrBlock": "10.0.3.0/24"}},
"ProdAlb": {
"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
"Condition": "IsProd",
"DependsOn": "ProdRole",
"Properties": {"Subnets": [{"Ref": "SubnetC"}]}
}
}
}
""");
stack.replaceParameters(Map.of("Env", "dev"));
stack.replaceResolvedParameters(Map.of("Env", "dev"));
StackResource loadBalancer = resource("ProdAlb", "arn:aws:elasticloadbalancing:us-east-1:000000000000:"
+ "loadbalancer/app/prod/1", "AWS::ElasticLoadBalancingV2::LoadBalancer", "DELETE_FAILED");
StackResource subnet = resource("SubnetC", "subnet-c", "AWS::EC2::Subnet", "CREATE_COMPLETE");
stack.getResources().put(loadBalancer.getLogicalId(), loadBalancer);
stack.getResources().put(subnet.getLogicalId(), subnet);
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
service.deleteStackResources(stack, REGION, ACCOUNT);
InOrder deletes = inOrder(provisioner);
deletes.verify(provisioner).delete(loadBalancer, REGION);
deletes.verify(provisioner).delete(subnet, REGION);
}
/**
* Counting every Fn::If branch can close a cycle no choice of branches has: here A uses B when
* Flip is true, and B uses A when it is false. The walk then orders by the branches the
* conditions choose now, so A, which uses B, still goes first.
*/
@Test
void deleteStack_whenEveryBranchWouldCloseACycle_ordersByTheBranchesChosenNow() {
Stack stack = new Stack();
stack.setStackName("delete-branch-cycle");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("CREATE_COMPLETE");
stack.setTemplateBody("""
{
"Parameters": {"Flip": {"Type": "String"}},
"Conditions": {
"Flipped": {"Fn::Equals": [{"Ref": "Flip"}, "yes"]},
"NotFlipped": {"Fn::Not": [{"Condition": "Flipped"}]}
},
"Resources": {
"B": {"Type": "AWS::SQS::Queue",
"Properties": {"Tags": {"Fn::If": ["NotFlipped", [{"Key": "a", "Value": {"Ref": "A"}}],
{"Ref": "AWS::NoValue"}]}}},
"A": {"Type": "AWS::SQS::Queue",
"Properties": {"Tags": {"Fn::If": ["Flipped", [{"Key": "b", "Value": {"Ref": "B"}}],
{"Ref": "AWS::NoValue"}]}}}
}
}
""");
stack.replaceParameters(Map.of("Flip", "yes"));
StackResource b = resource("B", "queue-b", "AWS::SQS::Queue", "CREATE_COMPLETE");
StackResource a = resource("A", "queue-a", "AWS::SQS::Queue", "CREATE_COMPLETE");
stack.getResources().put(b.getLogicalId(), b);
stack.getResources().put(a.getLogicalId(), a);
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
service.deleteStackResources(stack, REGION, ACCOUNT);
InOrder deletes = inOrder(provisioner);
deletes.verify(provisioner).delete(a, REGION);
deletes.verify(provisioner).delete(b, REGION);
}
/**
* A cycle that only counting every branch closes, between X and Y, must not cost the rest of
* the stack its other-branch dependencies: the load balancer still on the subnet the failed
* update chose goes before that subnet, though the restored parameter now picks the other.
* SubnetC is created two steps after SubnetA, so only that dependency puts the load balancer
* after it.
*/
@Test
void deleteStack_withAnUnrelatedBranchCycle_stillDeletesAResourceBeforeItsOtherBranchDependency() {
Stack stack = new Stack();
stack.setStackName("delete-branch-cycle-and-held-branch");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_ROLLBACK_FAILED");
stack.setTemplateBody("""
{
"Parameters": {"Placement": {"Type": "String"}},
"Conditions": {
"Second": {"Fn::Equals": [{"Ref": "Placement"}, "second"]},
"First": {"Fn::Not": [{"Condition": "Second"}]}
},
"Resources": {
"Alb": {"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
"Properties": {"Subnets": {"Fn::If": ["Second", [{"Ref": "SubnetC"}], [{"Ref": "SubnetA"}]]}}},
"SubnetA": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "vpc-1", "CidrBlock": "10.0.1.0/24"}},
"SubnetB": {"Type": "AWS::EC2::Subnet", "DependsOn": "SubnetA",
"Properties": {"VpcId": "vpc-1", "CidrBlock": "10.0.2.0/24"}},
"SubnetC": {"Type": "AWS::EC2::Subnet", "DependsOn": "SubnetB",
"Properties": {"VpcId": "vpc-1", "CidrBlock": "10.0.3.0/24"}},
"Y": {"Type": "AWS::SQS::Queue",
"Properties": {"Tags": {"Fn::If": ["First", [{"Key": "x", "Value": {"Ref": "X"}}],
{"Ref": "AWS::NoValue"}]}}},
"X": {"Type": "AWS::SQS::Queue",
"Properties": {"Tags": {"Fn::If": ["Second", [{"Key": "y", "Value": {"Ref": "Y"}}],
{"Ref": "AWS::NoValue"}]}}}
}
}
""");
stack.replaceParameters(Map.of("Placement", "first"));
StackResource loadBalancer = resource("Alb", "arn:aws:elasticloadbalancing:us-east-1:000000000000:"
+ "loadbalancer/app/web/1", "AWS::ElasticLoadBalancingV2::LoadBalancer", "UPDATE_FAILED");
StackResource subnetA = resource("SubnetA", "subnet-a", "AWS::EC2::Subnet", "CREATE_COMPLETE");
StackResource subnetB = resource("SubnetB", "subnet-b", "AWS::EC2::Subnet", "CREATE_COMPLETE");
StackResource subnetC = resource("SubnetC", "subnet-c", "AWS::EC2::Subnet", "CREATE_COMPLETE");
StackResource y = resource("Y", "queue-y", "AWS::SQS::Queue", "CREATE_COMPLETE");
StackResource x = resource("X", "queue-x", "AWS::SQS::Queue", "CREATE_COMPLETE");
for (StackResource resource : new StackResource[] {loadBalancer, subnetA, subnetB, subnetC, y, x}) {
stack.getResources().put(resource.getLogicalId(), resource);
}
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
service.deleteStackResources(stack, REGION, ACCOUNT);
InOrder subnets = inOrder(provisioner);
subnets.verify(provisioner).delete(loadBalancer, REGION);
subnets.verify(provisioner).delete(subnetC, REGION);
InOrder queues = inOrder(provisioner);
queues.verify(provisioner).delete(y, REGION);
queues.verify(provisioner).delete(x, REGION);
}
/**
* A resource the template no longer names, such as a subnet ContinueUpdateRollback skipped, has
* no template entry left to order it by. It still goes as late as possible, after the load
* balancer that may still use it, but before the VPC its attributes name, or that VPC delete
* fails while the subnet exists.
*/
@Test
void deleteStack_deletesALeftoverResourceBeforeTheResourceItsAttributesName() {
Stack stack = new Stack();
stack.setStackName("delete-leftover-subnet");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
stack.setTemplateBody("""
{"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}},
"SubnetA": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.0.1.0/24"}},
"Alb": {"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
"Properties": {"Subnets": [{"Ref": "SubnetA"}]}}
}}""");
StackResource leftover = resource("SubnetC", "subnet-c", "AWS::EC2::Subnet", "UPDATE_COMPLETE");
leftover.getAttributes().put("VpcId", "vpc-1");
StackResource vpc = resource("Vpc", "vpc-1", "AWS::EC2::VPC", "CREATE_COMPLETE");
StackResource subnet = resource("SubnetA", "subnet-a", "AWS::EC2::Subnet", "CREATE_COMPLETE");
subnet.getAttributes().put("VpcId", "vpc-1");
StackResource loadBalancer = resource("Alb", "arn:aws:elasticloadbalancing:us-east-1:000000000000:"
+ "loadbalancer/app/web/1", "AWS::ElasticLoadBalancingV2::LoadBalancer", "UPDATE_COMPLETE");
for (StackResource resource : new StackResource[] {vpc, subnet, loadBalancer, leftover}) {
stack.getResources().put(resource.getLogicalId(), resource);
}
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
service.deleteStackResources(stack, REGION, ACCOUNT);
InOrder deletes = inOrder(provisioner);
deletes.verify(provisioner).delete(loadBalancer, REGION);
deletes.verify(provisioner).delete(leftover, REGION);
deletes.verify(provisioner).delete(vpc, REGION);
}
/**
* A leftover may name another leftover: a VPC an update added and a subnet in it, both left by
* a failed rollback. The subnet goes before its VPC, which names only itself.
*/
@Test
void deleteStack_deletesALeftoverBeforeTheLeftoverItsAttributesName() {
Stack stack = new Stack();
stack.setStackName("delete-leftover-chain");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_ROLLBACK_FAILED");
stack.setTemplateBody("""
{"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}}
}}""");
StackResource vpc = resource("Vpc", "vpc-1", "AWS::EC2::VPC", "CREATE_COMPLETE");
vpc.getAttributes().put("VpcId", "vpc-1");
StackResource leftoverSubnet = resource("SubnetX", "subnet-x", "AWS::EC2::Subnet", "UPDATE_COMPLETE");
leftoverSubnet.getAttributes().put("SubnetId", "subnet-x");
leftoverSubnet.getAttributes().put("VpcId", "vpc-2");
StackResource leftoverVpc = resource("Vpc2", "vpc-2", "AWS::EC2::VPC", "UPDATE_COMPLETE");
leftoverVpc.getAttributes().put("VpcId", "vpc-2");
for (StackResource resource : new StackResource[] {vpc, leftoverSubnet, leftoverVpc}) {
stack.getResources().put(resource.getLogicalId(), resource);
}
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
service.deleteStackResources(stack, REGION, ACCOUNT);
InOrder deletes = inOrder(provisioner);
deletes.verify(provisioner).delete(leftoverSubnet, REGION);
deletes.verify(provisioner).delete(leftoverVpc, REGION);
}
/**
* The resume runs on the operation executor, whose future nobody reads. An unexpected failure
* must still settle the stack in UPDATE_ROLLBACK_FAILED, keeping what a retry needs, instead
@@ -23,6 +23,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -192,7 +193,30 @@ class Ec2NetworkCfnProvisionerTest {
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx());
assertEquals(NAT_ID, r.getPhysicalId());
assertEquals(Set.of("NatGatewayId"), r.getAttributes().keySet());
assertEquals(Set.of("NatGatewayId"), r.getAttributes().keySet().stream()
.filter(key -> !key.startsWith("__Floci")).collect(Collectors.toSet()));
}
/**
* A gateway records the subnet and the Elastic IP it holds under hidden keys, by their physical
* ids, so a stack that no longer names it still deletes it before them.
*/
@Test
void natGatewayRecordsTheSubnetAndElasticIpItUsesUnderHiddenKeys() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
nat.setSubnetId(SUBNET_ID);
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", List.of())).thenReturn(nat);
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
when(ec2.describeAddresses(REGION, List.of(ALLOC_ID), Map.of())).thenReturn(List.of(addr));
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx());
assertEquals(SUBNET_ID, r.getAttributes().get(CfnRollback.USES_ATTR_PREFIX + "SubnetId"));
assertEquals(PUBLIC_IP, r.getAttributes().get(CfnRollback.USES_ATTR_PREFIX + "PublicIp"));
}
@Test
@@ -285,6 +285,29 @@ class ReplacementCleanupTest {
assertEquals(List.of("subnet-2"), deleted);
}
/**
* A revert puts back what the prior entity uses, as it does its public attributes, while other
* hidden keys, rollback bookkeeping, stay as they are.
*/
@Test
void rollback_restoresThePriorUsesAttributesAndKeepsOtherHiddenKeys() {
StackResource r = resource("subnet-1");
r.getAttributes().put("VpcId", "vpc-new");
r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "PublicIp", "203.0.113.2");
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
Map<String, String> before = Map.of("VpcId", "vpc-old",
CfnRollback.USES_ATTR_PREFIX + "PublicIp", "203.0.113.1", CfnRollback.ROLLBACK_OWNED_ATTR, "false");
r.setPhysicalId("subnet-2");
ReplacementCleanup.record(r, update("subnet-1"), before);
assertTrue(ReplacementCleanup.rollback(r, (type, id, region) -> { }));
assertEquals("subnet-1", r.getPhysicalId());
assertEquals("vpc-old", r.getAttributes().get("VpcId"));
assertEquals("203.0.113.1", r.getAttributes().get(CfnRollback.USES_ATTR_PREFIX + "PublicIp"));
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
/** A new provision supersedes the failed rollback; the replacement stays owed to the next cleanup instead. */
@Test
void record_afterAFailedRollbackDelete_doesNotRetryThatDeleteOnTheNextRollback() {