Repository navigation
ci(cleanup): unblock Amplify sandboxes stuck on a cancelled table create - #970
Conversation
|
osama-rizk
left a comment
There was a problem hiding this comment.
This adds a narrow, signature-gated unblock for Amplify Gen 2 sandboxes that can never be deleted after a cancelled table create: delete the nested model stack retaining only the stuck table resource, then let the next run delete the root plainly. I think it's safe to merge (after #959). Nothing blocking: the gates are tight, it only retains a resource CloudFormation could never delete anyway, and if the nested delete is refused it falls back to today's plain retry.
Speed / flakiness: No run-time change to PR Checks beyond about 2 s. The new test step took about 1.9 s in Build, Unit Tests, E2E Local on run 39871901324 (job 18.3 min, against 18.9 and 17.6 min on the baseline main runs 39812188339 and 39821845972, so within noise). On flakiness it's a real but rare gain: it closes one permanent leak (1 of 137 model stacks in 90 days, per the PR) that holds an AppSync API, Cognito pools and IAM roles against account quotas. It doesn't touch the 120 EDGE REST API quota behind most of the E2E reds, and the latest scheduled sweep (run 39937187759) reports 0 Amplify stacks still in DELETE_FAILED in every leg, so there's no immediate effect. It's a guard against a recurrence, not a speed-up.
E2E integrity: Not weakened. No test is removed, skipped, gated or loosened, the required-check layout doesn't change, and the head commit carries no E2E: trailer. The new step adds a unit test to the required Build job. On teardown safety, I checked whether this can act on an in-progress run's stack. It can't. The root must be tagged amplify:deployment-type=sandbox, be in DELETE_FAILED and have been created more than 6 h ago. Interop sandboxes use a per-run identifier (amp-/int- plus the run id and attempt), and those jobs have 30-minute timeouts. The nested stack must itself be DELETE_FAILED before the retain, and the cleanup-stale-stacks concurrency group stops two sweeps overlapping. The only thing retained is the custom-resource record, whose delete can never succeed. The real Todo-<apiId>-NONE table was already orphaned before this change, because the table manager only ever addresses the placeholder id. So this surfaces the leak rather than adding one.
What's good
- The signature is checked precisely: create failed and never completed, plus the DescribeTable denial for that resource's own physical id, with a boundary check so a longer table name doesn't match. Any read error counts as "no", so it fails closed.
- It retains only at the nested model stack. Retaining at the root or using FORCE_DELETE_STACK would orphan the AppSync API, and the reasoning for avoiding both is written down in the script.
- Every
awscall reads from/dev/nullinside thewhile readloops, the recursion has a visited set, and exit 3 makes the root wait for the next run so the two deletes can't race. - No new permissions. The reads come from the existing CloudFormation read-only policy, and DeleteStack on
amplify-*names is the same grant today's plain root delete already uses. - The tests are strong. Under bash 5 / GNU date, 32 of 32 pass at the head. I ran 19 mutants against the script and the workflow step (dropping each signature clause, the root guard, the nested-status check, the child-failed and blocker returns, the visited set, exit 3, masking, the age gate, the DELETE_FAILED gate and the defer
continue). Tests killed 16. The 3 that survived are in the inline comment. - Account ids are masked in the output, and that's tested too, including the case where the guard variable is inherited.
What needs work: 0 blocking · 2 minor · 1 nit. Details are inline.
Open questions
- The E2E role also attaches
AmplifyBackendDeployFullAccess. Have you confirmed it grants no DynamoDB delete on these tables? If it does, the "sweeper has no DynamoDB access" premise changes, and the sweep could delete the leftover table itself instead of asking for a manual delete. - A direct
delete-stack --retain-resourceson a nested stack hasn't been exercised against real CloudFormation. The fallback is safe, but could the call shape be checked once against a throwaway nested stack in a pool account, so the first real stuck sandbox doesn't become the test?
Cross-cutting
- #959: I checked the checkout hunk and it's byte-identical to #959's, so they merge cleanly in either order. Order only matters for the comment wording (see the nit). #955 and #957 touch the same spot in the pr-checks.yml Build step list, so keep all the steps when resolving.
- On filing upstream: I'd file it. The table manager should treat a placeholder physical id, or AccessDenied on an id outside its own
table/*-<apiId>-<env>scope, as already deleted. That fixes the root cause for every Amplify user, not just this sweep.
|
On open question 1: |
osama-rizk
left a comment
There was a problem hiding this comment.
Since the last review: 3 resolved · 1 new · 0 still open
Resolved:
- Leftover table reporting:
--leftoversnow re-reports every retainedTodo-<apiId>-NONEtable on each run from the deleted model stack's record, and stops once DescribeTable returns not-found. I checked that it only reads (list-stacks, list-stack-resources, get-template, describe-stacks, describe-table), exits 0 on every path, and that a denied DescribeTable still reports the table as "may still exist" and doesn't count it as gone. - 6 h gate tests: the 5 h 50 min / 6 h 10 min pair and the
None-after-old-stack case kill all three earlier survivors (the gate moved to 2 h, theCREATED_TS=0reset dropped, the-ne 0guard dropped). - Checkout comment: it names all three scripts, and a test pins it.
The PR adds IAM (Identity and Access Management) access with dynamodb:DescribeTable on arn:aws:dynamodb:<region>:<account>:table/*-NONE. That looks right to me: one read-only action, scoped to this account and region, and the test asserts it's the role's only DynamoDB statement. Until the OIDC (OpenID Connect) stack is redeployed, the sweep degrades the safe way: the denial is logged with the account masked, and the table is still reported. I also confirmed the answer about the managed policy: AmplifyBackendDeployFullAccess v9 has no DynamoDB action, so reporting by hand is the right call and nothing here can delete a table.
What I re-checked on e0d6c76:
- The safety gates still hold in the Amplify step: the sandbox tag,
DELETE_FAILED, created more than 6 h ago and a non-zero creation time. The retain still runs only on a nested stack, never at the root, and exit 3 still skips the root delete for that run. - Tests: 49/49 in a Linux container (bash 5, GNU date), matching PR Checks run 39982314601.
test-infrapasses 9/9 in that run. - A mutation pass over the script and the step: 29 of 29 mutants killed. That includes 10 new ones on
--leftovers: the DELETE_SKIPPED filter, the 5 h lifetime filter (removed, and raised to 7 h), the stack-name filter, treating any error as gone, treating success as gone, the missingexit 0, a non-zero exit on a listing failure, the dropped report line, and the step no longer calling it. - Cost: the test step takes 2.4 s and the Build job 15m51s, in line with the baseline.
What needs work: 1 nit, inline (bash 3.2 portability of the new mapfile).
Open questions (not blocking): the direct delete-stack --retain-resources on a nested stack still hasn't run against real CloudFormation. As before, the fallback is safe either way.
Cross-cutting: none new. --leftovers runs before the time-budget check and has no limit of its own. The 14-15 s you measured makes that fine today. If the 90-day DELETE_COMPLETE listing grows a lot, it's the first place to look.
This is a COMMENT rather than an approval only because the PR is still a draft. With the nit optional, I'd approve once it's marked ready.
e0d6c76 to
ec616f8
Compare
osama-rizk
left a comment
There was a problem hiding this comment.
Since the last review: 1 resolved · 0 new · 0 still open
Resolved:
- bash 3.2 portability:
--leftoversnow builds the id list with a read loop instead ofmapfile(ec616f8). On stock macOS bash 3.2 the suite passes 40/40 locally (it was 34/40).
Approving. All four earlier findings are fixed and I re-verified each on ec616f8, which is still the head. The branch was rebased onto main, so e0d6c76 isn't an ancestor of it. I compared the commits: the four earlier commits are patch-identical, and the only new change is the 3-line read loop.
What I verified on ec616f8:
--leftoversre-reports retained tables on every run and stops once DescribeTable returns not-found. The 6 h gate tests are in place, and the checkout comment names all three scripts.- The safety gates in the Amplify step are unchanged: the sandbox tag,
DELETE_FAILED, created more than 6 h ago, and a non-zero creation time. The retain still runs only on a nested stack, never at the root, and exit 3 still skips the root delete for that run. - IAM (Identity and Access Management): the role still gains only
dynamodb:DescribeTableontable/*-NONE, scoped to the account and region, and a test pins it. - Tests: 49/49 in a Linux container (bash 5, GNU date), matching PR Checks run 40346603752 at this head. Mutation pass: 31 of 31 mutants killed, including two on the read loop (dropping the
ids=()reset between stacks, and keeping only the first id).
Speed: neutral, and this PR doesn't claim a speed gain. Its gain is on flakiness: a sandbox stuck in DELETE_FAILED no longer pins an AppSync API slot for days. On the head run, the new step takes 3 s inside "Local Build and Checks" (6 m 31 s). That job and Local Unit Tests shard 2 both finish about 15:16:28, so the 3 s may sit on the critical path. The "Build, Unit Tests, E2E Local" aggregate was 6 m 45 s, inside the 6.8 to 7.4 min range of PR runs after #963. The wall-clock cost is inferred to be at most 3 s.
Regression: none found. git merge-tree against current main (db15b5e) is clean. The only workflow changes on main since the base a13143c are #948 and #1032, in other jobs of pr-checks.yml. In the merged job graph, the new test step sits in local-build (no if:, so it runs on every PR), and the always() aggregator still needs it. All required checks are green on the head. This changes CI only, with no customer-facing behaviour.
Coverage / blind spots: no test or assertion is removed or skipped, and nothing moves from required to advisory or nightly. The new suite is added to a required job. The removed lines are the if: matrix.environment == 'e2e' / sparse-checkout hunk shared with #959 (byte-identical), the old "don't retain" comment, the old warning text, and one README row widened to cover the new sweep. The one blind spot is disclosed in the PR: delete-stack --retain-resources on a nested stack hasn't run against real CloudFormation, because nothing is stuck today. If CloudFormation refuses it, the sweep is no worse than before.
Merge-order note: land this after #959, which carries the same checkout hunk. Expect a same-spot conflict in the pr-checks.yml Local Build steps with #955 and #957. Keep both sides.
Follow-ups (not blocking):
- Run the nested-stack retain once on a throwaway nested stack, or watch the first real sweep that hits it.
- File the Amplify table-manager defect upstream (you have a draft).
The PR is still marked draft. This approval covers the code as it stands at ec616f8.
ec616f8 to
f74b525
Compare
f74b525 to
dcd9c34
Compare
dcd9c34 to
b6879cd
Compare
An Amplify Gen 2 sandbox whose deploy fails while its model table is being created stays in DELETE_FAILED for good. CloudFormation cancels the table custom resource and gives it a placeholder physical id, but Amplify's table manager has already created the table under its real name. On delete, the table manager calls dynamodb:DescribeTable on the placeholder, its role is not allowed to, and every retry fails the same way. The Amplify sweep only retried plainly, so such a stack held its AppSync API for days until it was removed by hand. For a sandbox in DELETE_FAILED created more than 6 hours ago, the sweep now runs scripts/ci/amplify-stuck-delete.sh. It walks the nested stacks to the model stack holding the failed table, and deletes that nested stack with --retain-resources only when every failed resource there shows exactly that signature in the stack's events: a create that failed and never completed, and a delete that failed on the DescribeTable denial for its own physical id. Anything else is warned about and left for the plain retry. The root is deleted plainly on the next run, once the nested stack is gone. Retaining the resource leaves the real table behind, and no sweep deletes DynamoDB tables, so its name (resolved from the nested stack's template and parameters) is reported in a warning and the step summary for deletion by hand. The root itself is never retained or force-deleted: that would orphan the data stack's AppSync API, or skip the auth and table-manager stacks. Stacks are logged by name, not ARN, so no account id reaches the log. Every leg checks out scripts/ci; the checkout hunk matches the one in the REST API quota change so the two merge cleanly. Tested by scripts/ci/amplify-stuck-delete.test.mjs (new PR check step), which replays the stuck stack against a stub aws CLI.
A table retained by the nested-stack delete was reported once, in that run's annotation and step summary, and never again. The Amplify step now runs `amplify-stuck-delete.sh --leftovers` on every run. It reads the retained table resources (DELETE_SKIPPED) of deleted nested stacks of Amplify sandboxes, which CloudFormation keeps for 90 days, and names each real table in a warning and the step summary. Only nested stacks that lived at least 5 hours are read: the retain only runs on a sandbox created more than 6 hours earlier. It only reads; the sweeper role has no DynamoDB access, so whether the table still exists is not checked. Tests: the 6-hour age test now uses a 5-hour-old stack, so it pins the threshold; a new step test covers a sandbox with no creation time after an old stuck one. The "script fails" step test copies all of scripts/ci, so it keeps working when the step sources other scripts there. The checkout comment names every script the job runs from scripts/ci. 7 of the new tests fail on the previous head; 11 of 11 hand mutants are killed, including the three survivors from review.
Checked against the deleted records of the sandbox that was stuck in October, read-only: - A deleted nested stack carries no ParentId in list-stacks, so the ParentId filter dropped every real leftover. The filter now keys on the sandbox name prefix and the stack's lifetime only. DeletionTime is the time of the delete that succeeded, so the 5-hour lifetime holds for a stack that failed to delete for days. - That sandbox's table was deleted by hand, so the report would have warned about it for 90 days. The script now calls DescribeTable and drops a table it reports as not found. Any other error, such as a role without the grant, still reports the table. The E2E role gets dynamodb:DescribeTable on Amplify sandbox tables (table/*-NONE), which takes effect once the OIDC stack is redeployed. Also from review: one warning per run however many tables are left (each table is a line in the step summary), the leftover read runs before the delete loop so a table retained this run is not reported twice, the deleted-stack listing retries in adaptive mode, and the 6-hour and 5-hour thresholds are pinned from both sides. Tests: 48/48, test-infra 9/9; 19 of 19 hand mutants are killed.
… the gates closer From the second review: - A DescribeTable error other than not-found is printed with its reason, so a role without the grant shows in the log; a failed deleted-stack listing carries the CLI's reason in its warning. - The 6-hour retain gate is tested at 5 h 50 min and 6 h 10 min, the 5-hour lifetime filter at 4 h 50 min and 5 h 10 min. - A retained resource that is not a table is not reported (test). - test-infra/README.md lists the describe-only table check on the E2E role. Tests: 49/49; 26 of 26 hand mutants are killed.
mapfile needs bash 4, so on stock macOS bash 3.2 the --leftovers tests failed with "mapfile: command not found". With the mapfile builtin disabled the suite now passes 49/49, as it does under bash 5.
A test now pins what the Amplify step needs from that checkout: it runs on every leg and includes scripts/ci. Restoring the old checkout (e2e legs only, no scripts/ci) fails it.
…serial sweep's The Amplify step now deletes one sandbox at a time (#1255) and counts the sandboxes it defers to the next run in DEFERRED. This PR counted the roots it defers after starting a nested retain in a variable of the same name, so both summary lines printed the sum. It now has its own counter, NESTED_DEFERRED. The nested retain stays behind the one-at-a-time gate, so it never starts while an earlier sandbox's delete may still be running, and its nested delete is not awaited: the model stack holds no API Gateway resource, so it doesn't compete for the REST API delete quota the wait protects. A comment in the step says so. Tests: a stuck and a normal sandbox in one run (the stuck root is deferred on its own line, the normal one deleted and awaited), and no nested delete once the wait budget is spent or while an earlier delete is still running. The step tests use the step's poll override, so they take seconds, not minutes.
b6879cd to
b373158
Compare
Brings in 14 commits from main, among them "fix(core): return Invalid Request for a null JSON-RPC body" (#1143), "fix(core): reject non-JSON-RPC response bodies with ApiError" (#1171), "feat(bb-logger,core): backend Lambda log lines carry the invocation's requestId" (#1325), #1131, #1132, #1142, #1167, #1173, #1178, #1214, #494 and CI changes (#946, #970, #971). packages/core/src/client/index.test.ts and lambda-handler.test.ts: keep both sides' tests (this branch's httpErrorStatus, namespace identity and per-call fetch suites; main's non-JSON-RPC body and request id suites). packages/core/src/api.ts: the httpErrorStatus docs now say what the client does since #1171 when a Hosting error page replaces a 403 / 404: it rejects with a bare ApiError carrying the HTTP status, instead of response.json() throwing. # Conflicts: # packages/core/src/client/index.test.ts # packages/core/src/lambda-handler.test.ts
Problem
The scheduled stack cleanup could not reclaim one Amplify Gen 2 sandbox. It sat in
ROLLBACK_FAILED, thenDELETE_FAILED, for about 3 days, until it was removed by hand.Cause: Amplify's managed-table custom resource (a dependency, not AWS Blocks code).
Custom::AmplifyDynamoDBTablewas being created.Todo-<apiId>-NONE.dynamodb:DescribeTableon the placeholder. Its role only allowstable/*-<apiId>-<env>, so IAM returns AccessDenied. The handler only toleratesResourceNotFoundException, so every delete fails the same way.Trigger. The sibling failure was a one-off on the AWS side. The AWS-managed
aws/dynamodbKMS key was created on first use in that account, 270 ms before the table create returned "Key does not exist".Change
For an Amplify sandbox in
DELETE_FAILEDthat was created more than 6 h ago (the same gate as the e2e step's retain path), the sweep runs the newscripts/ci/amplify-stuck-delete.sh. The script:--retain-resources, but only when every failed resource in it shows exactly this signature in the stack's events:DescribeTabledenial for its own physical id;It never retains at the root or force-deletes the root:
FORCE_DELETE_STACKalso skips the auth and table-manager nested stacks and leaves them behind (that happened during the manual cleanup).The table that is left behind. Retaining the resource does not delete the real table, and no sweep deletes tables. The script resolves the table name from the nested stack's template and parameters and reports it in a warning and the step summary for deletion by hand. On every later run,
amplify-stuck-delete.sh --leftoversreports it again: it reads the retained table resources of deleted sandbox stacks, which CloudFormation keeps for 90 days, and callsdynamodb:DescribeTableso a table deleted by hand stops being reported. It is one warning per run, with a line per table in the summary. It only reads.The E2E role gets
dynamodb:DescribeTableontable/*-NONE(Amplify sandbox tables) for that check. Until the role is redeployed, the call is denied and the table is reported as "may still exist". The role'sAmplifyBackendDeployFullAccesspolicy (v9) has no DynamoDB action, so the sweep can't delete these tables.Stacks are logged by name, and all script output has 12-digit numbers masked, so no account id reaches the log. No OIDC trust, environment or prefix-list change.
With the one-at-a-time sweep (#1255). The Amplify step now deletes one sandbox at a time, waits for each, and defers the rest once its wait budget is spent or a delete outlasts its wait. The nested retain runs behind that gate, so it never starts while an earlier root delete may still be running. Its own nested delete is not awaited: the model stack holds AppSync resolvers, IAM roles and the table, but no API Gateway resource, so it doesn't compete for the REST API delete quota the wait protects. The root (whose
blocksnested stack holds the REST API) is deleted, and awaited, on the next run. Roots deferred after a nested retain are counted on their own summary line, apart from the sweep's own deferrals.The DescribeTable grant
test-infra,npm run deploy:oidc) has already been redeployed in each E2E account from a tree with this grant and ci(cleanup): delete orphaned Lambda and RDS log groups of test stacks #967's. Merge this PR before anyone redeploys that stack again from main, or the grant is dropped. Without it, a leftover table is reported as "may still exist", and the log says DescribeTable was denied.Testing
scripts/ci/amplify-stuck-delete.test.mjsreplays the stuck stack against a stubaws, for the script and the workflow step itself: 53/53, including a test that the cleanup job's checkout runs on every leg and includesscripts/ci, and three with a stuck and a normal sandbox in one run: the stuck root is deferred on its own line while the normal one is deleted and awaited, and no nested delete starts once the wait budget is spent or while an earlier delete is still running. ci(e2e-amplify-interop): retry throttled sandbox teardown; sweep sandboxes one at a time #1255'samplify-sweep.test.mjsandamplify-sandbox-teardown.test.mjspass against the merged step (10/10). 26 of 26 hand mutants of the review fixes are killed (the 6 h gate at 5 h 50 min and 6 h 10 min, theNonecreation-time reset, each--leftoversfilter, the existence check, the call order).test-infranpm test: 11/11 (with ci(cleanup): delete orphaned Lambda and RDS log groups of test stacks #967's log-group grants), including the new grant's exact shape.list-stacks,list-stack-resources,get-template,describe-stacksanddescribe-tableallowed through):--leftoversfinds its retainedTodoTableand resolves the real table name, then DescribeTable shows the table was already deleted, so nothing is reported. That check also showed that deleted nested stacks carry noParentIdinlist-stacks, which the first version relied on. The other two accounts report nothing (14-15 s per run).cleanup-stacks.yml,node scripts/check-actions-pinned.mjsand shellcheck are clean. (actionlint reports one SC2086 info inpr-checks.ymlthat is on main too and outside this diff.) No PR Checks E2E job is selected (nothing underpackages/ortest-apps/changes).delete-stack --retain-resourcesitself. If CloudFormation refuses it, the sweep is no worse than before.Merge order
Merge this PR first; #959 rebases on top of it afterwards. This PR stands alone on main: it checks out
scripts/cion every leg (the Amplify step runs on all of them) and names only its own script in the comment above the checkout. #959 changes the same checkout in the same way and names its two scripts in that comment, so on rebase it conflicts on that comment line only.History
NESTED_DEFERRED, instead of sharing ci(e2e-amplify-interop): retry throttled sandbox teardown; sweep sandboxes one at a time #1255'sDEFERRED, and a comment and three step tests cover how the two fit.