Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
ci(cleanup): report a retained Amplify table on every later run
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.
  • Loading branch information
belaboe committed Nov 5, 2026
commit 5229debaaec6efee5009cbaed8a23faea1f5f12a
17 changes: 12 additions & 5 deletions .github/workflows/cleanup-stacks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -554,8 +554,9 @@ jobs:
# model stack retaining only that table resource, and the root is
# deleted on the next run. The real table survives the retain and no
# sweep deletes tables, so it is named in a warning and the step summary
# for deletion by hand. The script runs from the job's checkout, which
# includes scripts/ci on every leg.
# for deletion by hand, on this run and every later one (--leftovers
# below). The script runs from the job's checkout, which includes
# scripts/ci on every leg.
echo "🧹 Emptying nested buckets for $STACK"
_VISITED_STACKS=""
empty_stack_buckets "$STACK"
Expand Down Expand Up @@ -601,6 +602,11 @@ jobs:
fi
done

# Tables retained on earlier runs, reported again on every run until
# CloudFormation drops the deleted stack's record (90 days).
AMPLIFY_RETAINED_FILE="$RETAINED_FILE" bash scripts/ci/amplify-stuck-delete.sh --leftovers ||
echo "::warning::amplify-stuck-delete.sh --leftovers failed; tables retained on earlier runs are not reported this run"

# Early-warning tally (see the e2e step) — Amplify sandboxes still stuck in
# DELETE_FAILED (commonly the managed DynamoDB table) surfaced as a warning
# so the backlog can't grow silently and exhaust the AppSync API quota.
Expand All @@ -625,11 +631,12 @@ jobs:
echo "- Root delete deferred (nested stack delete started): $DEFERRED" | tee -a "$GITHUB_STEP_SUMMARY"
echo "- Nested retain script failed: $SCRIPT_FAILED" | tee -a "$GITHUB_STEP_SUMMARY"
echo "- Still DELETE_FAILED: $STILL_FAILED" | tee -a "$GITHUB_STEP_SUMMARY"
# What amplify-stuck-delete.sh retained (with the DynamoDB table to
# delete by hand) and the failed resources it left in place.
# What amplify-stuck-delete.sh retained, this run or earlier (with the
# DynamoDB table to delete by hand), and the failed resources it left
# in place.
if [ -s "$RETAINED_FILE" ]; then
echo "" | tee -a "$GITHUB_STEP_SUMMARY"
echo "Retained, left-in-place and bucket-blocked resources of stuck sandboxes:" | tee -a "$GITHUB_STEP_SUMMARY"
echo "Retained, leftover, left-in-place and bucket-blocked resources of stuck sandboxes:" | tee -a "$GITHUB_STEP_SUMMARY"
tee -a "$GITHUB_STEP_SUMMARY" < "$RETAINED_FILE"
fi
rm -f "$RETAINED_FILE"
Expand Down
56 changes: 53 additions & 3 deletions scripts/ci/amplify-stuck-delete.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# Amplify sweep in .github/workflows/cleanup-stacks.yml.
#
# Usage: amplify-stuck-delete.sh <root-stack>
# amplify-stuck-delete.sh --leftovers
#
# Amplify's managed DynamoDB table is a custom resource
# (Custom::AmplifyDynamoDBTable) in a nested model stack: root -> data ->
Expand Down Expand Up @@ -34,6 +35,12 @@
# resource is reported with the real table name, resolved from the nested
# stack's template and parameters, as a table to delete by hand.
#
# With --leftovers it reports those tables again, on every run: it reads the
# retained resources of the deleted model stacks. CloudFormation keeps a
# deleted stack's record, resources and template for 90 days, so a leftover
# table is reported for that long. The role can't read DynamoDB, so whether
# the table still exists is not checked.
#
# Why the nested stack and not the root: --retain-resources on the root can
# only name the data stack, which would orphan the AppSync API the sweep
# exists to free. FORCE_DELETE_STACK on the root also skips the nested stacks
Expand All @@ -50,13 +57,14 @@
# Exit status: 0 when nothing was deleted here (the caller retries the root
# plainly), 3 when a nested stack delete was started (the caller deletes the
# root on its next run, after the nested delete has finished), 1 on bad usage.
# With --leftovers it never deletes, and exits 0.
#
# Tests: node --test scripts/ci/amplify-stuck-delete.test.mjs

set -euo pipefail

if [ "$#" -ne 1 ] || [ -z "$1" ]; then
echo "usage: amplify-stuck-delete.sh <root-stack>" >&2
echo "usage: amplify-stuck-delete.sh <root-stack> | --leftovers" >&2
exit 1
fi

Expand Down Expand Up @@ -198,8 +206,8 @@ walk() {
echo " $(name "$stack") is ${status:-unreadable}, not DELETE_FAILED; left for the plain retry"
return 0
fi
# Resolved before the delete: afterwards the stack's template is still
# readable, but nothing reports the table again on a later run.
# Resolved before the delete, while the stack is still live. Later runs
# report the table again from the deleted stack (--leftovers).
names=$(table_names "$stack" "${keep[@]}")
echo " Deleting nested stack $(name "$stack"), retaining the stuck table resource(s): ${keep[*]}"
if ! aws cloudformation delete-stack --stack-name "$stack" --retain-resources "${keep[@]}" </dev/null 2>&1; then
Expand All @@ -215,6 +223,48 @@ walk() {
done
}

# The tables retained on earlier runs: a table resource in DELETE_SKIPPED in a
# deleted nested stack of a sandbox. Only stacks that lived at least 5 hours
# are read. The retain only runs on a sandbox created more than 6 hours
# earlier (the step's STUCK_CUTOFF), and an ordinary teardown deletes its
# nested stacks within the hour, so this skips almost every deleted stack.
leftovers() {
local listed candidates id stack when rows names logical table
local ids=()
if ! listed=$(aws cloudformation list-stacks --stack-status-filter DELETE_COMPLETE --output json </dev/null) ||
! candidates=$(jq -r '
def ts: .[0:19] + "Z" | fromdateiso8601;
.StackSummaries[]
| select(.ParentId != null and (.StackName | test("^amplify-amplify(gen2|interoptest)-")))
| select(.DeletionTime != null and ((.DeletionTime | ts) - (.CreationTime | ts)) >= 5 * 3600)
| [.StackId, .StackName, .DeletionTime[0:10]] | @tsv' <<<"$listed"); then
echo "::warning::could not list deleted stacks, so tables retained on earlier runs are not reported this run"
return 0
fi
while IFS=$'\t' read -r id stack when; do
[ -z "$id" ] && continue
if ! rows=$(aws cloudformation list-stack-resources --stack-name "$id" --output json </dev/null |
jq -r --arg type "$table_type" '.StackResourceSummaries[]
| select(.ResourceType == $type and .ResourceStatus == "DELETE_SKIPPED") | .LogicalResourceId'); then
echo "::warning::could not list the resources of deleted stack $stack; its retained tables are not reported this run"
continue
fi
[ -z "$rows" ] && continue
mapfile -t ids <<<"$rows"
Comment thread
belaboe marked this conversation as resolved.
Resolved
names=$(table_names "$id" "${ids[@]}")
for logical in "${ids[@]}"; do
table=$(awk -F'\t' -v id="$logical" '$1 == id { print $2; exit }' <<<"$names")
table=${table:-"(name unresolved, see the stack template)"}
echo "::warning::$stack retained $logical when it was deleted on $when; DynamoDB table $table may still exist, and no sweep deletes it"
echo "- leftover: $logical ($table_type) of $stack, deleted $when; delete DynamoDB table $table by hand if it still exists" >>"$report"
done
done <<<"$candidates"
}

if [ "$root" = '--leftovers' ]; then
leftovers
exit 0
fi
walk "$root"
[ "$started" -eq 1 ] && exit 3
exit 0
139 changes: 134 additions & 5 deletions scripts/ci/amplify-stuck-delete.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand All @@ -28,7 +28,9 @@ const STEP = 'Find and delete stale Amplify sandbox stacks';
// A stub `aws` that serves canned output from its fixture dir and logs every
// call. Files are keyed by the --stack-name value with every character outside
// [A-Za-z0-9-] replaced by `_` (see key() below).
// list-stacks -> stacks.txt; with a length() query, 0
// list-stacks -> stacks.txt; with a length() query, 0;
// for DELETE_COMPLETE, deleted.json (exit
// 254 if list-deleted-fails exists)
// describe-stacks, Tags query -> info-<key>.txt (the step's tag/status/date)
// describe-stacks, Parameters -> params-<key>.json, else exit 254
// describe-stacks, other query -> status-<key>.txt, else exit 254
Expand All @@ -49,6 +51,11 @@ k=$(printf '%s' "$stack" | tr -c 'A-Za-z0-9-' '_')
q=$(arg --query "$@")
case "$1 $2" in
'cloudformation list-stacks')
case " $* " in *' DELETE_COMPLETE '*)
if [ -f "$d/list-deleted-fails" ]; then echo "An error occurred (Throttling) for stack $(cat "$d/list-deleted-fails")" >&2; exit 254; fi
cat "$d/deleted.json" 2>/dev/null || echo '{"StackSummaries":[]}'
exit 0 ;;
esac
case "$q" in length*) echo 0 ;; *) cat "$d/stacks.txt" 2>/dev/null ;; esac ;;
'cloudformation describe-stacks')
case "$q" in
Expand Down Expand Up @@ -202,6 +209,7 @@ function run(dir, args, env = {}, cwd = ROOT_DIR) {
summary: read('summary.md'),
report: read('report.md'),
deletes: read('deletes.txt').split('\n').filter(Boolean),
calls: read('calls.txt'),
};
}

Expand Down Expand Up @@ -229,9 +237,9 @@ function stepScript() {
*/
function runStep(files, { status = 'DELETE_FAILED', created = '2026-10-19T14:48:22.894Z', cwd } = {}) {
const dir = fixture({
...files,
'stacks.txt': `${ROOT}\n`,
[`info-${key(ROOT)}.txt`]: `sandbox\t${status}\t${created}\n`,
...files,
});
const file = join(dir, 'step.sh');
writeFileSync(file, stepScript());
Expand Down Expand Up @@ -553,6 +561,95 @@ describe('amplify-stuck-delete.sh', () => {
});
});

// The model stack after the retain, as list-stacks reports it once deleted:
// CloudFormation keeps a deleted stack's record, resources and template for
// 90 days. It lived from the failed deploy to the retain, over 6 h later.
const deletedTodo = (over = {}) => ({
StackId: TODO,
StackName: TODO_NAME,
ParentId: DATA,
StackStatus: 'DELETE_COMPLETE',
CreationTime: '2026-10-19T14:50:01.123000+00:00',
DeletionTime: '2026-10-21T08:12:40.456000+00:00',
...over,
});
const deleted = (...items) => JSON.stringify({ StackSummaries: items });
/** Fixture files for a later run: the retain went through and the model stack is gone. */
const afterRetain = (over = {}) =>
sandbox({
'deleted.json': deleted(deletedTodo()),
[`status-${key(TODO)}.txt`]: 'DELETE_COMPLETE\n',
[`resources-${key(TODO)}.json`]: resources(
resource('TodoTable', TABLE, 'DELETE_SKIPPED', TABLE_ID),
resource('TodoIAMRole', 'AWS::IAM::Role', 'DELETE_COMPLETE', 'role'),
),
...over,
});
const runLeftovers = (dir) => run(dir, [SCRIPT, '--leftovers']);

describe('amplify-stuck-delete.sh --leftovers', () => {
it('reports a table retained on an earlier run, by its real name, and deletes nothing', () => {
const r = runLeftovers(fixture(afterRetain()));
assert.equal(r.status, 0, r.stdout + r.stderr);
assert.deepEqual(r.deletes, []);
assert.match(
r.stdout,
new RegExp(`^::warning::${TODO_NAME} retained TodoTable when it was deleted on 2026-10-21; DynamoDB table ${REAL_TABLE} may still exist`, 'm'),
);
assert.match(
r.report,
new RegExp(`^- leftover: TodoTable \\(${TABLE}\\) of ${TODO_NAME}, deleted 2026-10-21; delete DynamoDB table ${REAL_TABLE} by hand if it still exists$`, 'm'),
);
assert.doesNotMatch(r.stdout + r.stderr + r.report, NO_ACCOUNT);
});

it('does not read the resources of a nested stack that lived under 5 hours (an ordinary teardown)', () => {
const r = runLeftovers(
fixture(afterRetain({ 'deleted.json': deleted(deletedTodo({ DeletionTime: '2026-10-19T19:40:00.000000+00:00' })) })),
);
assert.equal(r.status, 0, r.stdout);
assert.equal(r.report, '');
assert.doesNotMatch(r.calls, /list-stack-resources/);
});

it('ignores a deleted root stack, and stacks of other apps', () => {
const r = runLeftovers(
fixture(
afterRetain({
'deleted.json': deleted(deletedTodo({ ParentId: undefined }), deletedTodo({ StackName: 'amplify-myapp-x-sandbox-1-y' })),
}),
),
);
assert.equal(r.status, 0, r.stdout);
assert.equal(r.report, '');
assert.doesNotMatch(r.calls, /list-stack-resources/);
});

it('reports nothing for a table resource the delete removed', () => {
const r = runLeftovers(
fixture(afterRetain({ [`resources-${key(TODO)}.json`]: resources(resource('TodoTable', TABLE, 'DELETE_COMPLETE', TABLE_ID)) })),
);
assert.equal(r.status, 0, r.stdout);
assert.equal(r.report, '');
assert.doesNotMatch(r.stdout, /::warning::/);
});

it('warns, without the account id, when the deleted stacks cannot be listed', () => {
const r = runLeftovers(fixture(afterRetain({ 'list-deleted-fails': TODO })));
assert.equal(r.status, 0, r.stdout);
assert.match(r.stdout, /::warning::could not list deleted stacks/);
assert.doesNotMatch(r.stdout + r.stderr, NO_ACCOUNT);
});

it('still names the table, unresolved, when its deleted template cannot be read', () => {
const files = afterRetain();
delete files[`template-${key(TODO)}.json`];
const r = runLeftovers(fixture(files));
assert.equal(r.status, 0, r.stdout);
assert.match(r.report, /^- leftover: TodoTable .*delete DynamoDB table \(name unresolved, see the stack template\) by hand/m);
});
});

describe(`cleanup-stacks.yml "${STEP}" step`, { skip: !GNU_DATE && 'needs GNU date' }, () => {
it('unblocks the stuck sandbox: nested retain, root deferred, real table in the summary', () => {
const r = runStep(sandbox());
Expand Down Expand Up @@ -585,7 +682,8 @@ describe(`cleanup-stacks.yml "${STEP}" step`, { skip: !GNU_DATE && 'needs GNU da
it('warns and retries plainly when the script fails', () => {
const cwd = mkdtempSync(join(tmpdir(), 'amplify-stuck-delete-cwd-'));
dirs.push(cwd);
mkdirSync(join(cwd, 'scripts', 'ci'), { recursive: true });
// Every script the step runs from scripts/ci, with this one failing.
cpSync(join(ROOT_DIR, 'scripts', 'ci'), join(cwd, 'scripts', 'ci'), { recursive: true });
writeFileSync(join(cwd, 'scripts', 'ci', 'amplify-stuck-delete.sh'), 'exit 1\n');
const r = runStep(sandbox(), { cwd });
assert.equal(r.status, 0, r.stdout);
Expand All @@ -595,15 +693,46 @@ describe(`cleanup-stacks.yml "${STEP}" step`, { skip: !GNU_DATE && 'needs GNU da
});

it('only retries plainly while a DELETE_FAILED sandbox is younger than 6 hours', () => {
const created = new Date(Date.now() - 3600_000).toISOString();
const created = new Date(Date.now() - 5 * 3600_000).toISOString();
const r = runStep(sandbox(), { created });
assert.equal(r.status, 0, r.stdout);
assert.deepEqual(r.deletes, [`cloudformation delete-stack --stack-name ${ROOT}`]);
});

it('only retries plainly a sandbox with no creation time, even after an old stuck one', () => {
const ROOT2 = 'amplify-amplifygen2-amp716639251-sandbox-0000000000';
const r = runStep({
...sandbox(),
'stacks.txt': `${ROOT}\n${ROOT2}\n`,
[`info-${key(ROOT2)}.txt`]: 'sandbox\tDELETE_FAILED\tNone\n',
});
assert.equal(r.status, 0, r.stdout);
assert.deepEqual(r.deletes, [RETAIN_TODO, `cloudformation delete-stack --stack-name ${ROOT2}`]);
assert.doesNotMatch(r.calls, new RegExp(`list-stack-resources --stack-name ${ROOT2} --output json`));
});

it('reports a table retained on an earlier run in the summary, on every later run', () => {
// The root is gone too: only the deleted model stack's record is left.
const r = runStep(afterRetain(), { created: 'None' });
assert.equal(r.status, 0, r.stdout);
assert.match(r.stdout, new RegExp(`^::warning::${TODO_NAME} retained TodoTable when it was deleted`, 'm'));
assert.match(r.summary, new RegExp(`^- leftover: TodoTable .* delete DynamoDB table ${REAL_TABLE} by hand`, 'm'));
assert.doesNotMatch(r.summary, NO_ACCOUNT);
});

it('only retries plainly a ROLLBACK_FAILED sandbox (the retain needs DELETE_FAILED)', () => {
const r = runStep(sandbox(), { status: 'ROLLBACK_FAILED' });
assert.equal(r.status, 0, r.stdout);
assert.deepEqual(r.deletes, [`cloudformation delete-stack --stack-name ${ROOT}`]);
});
});

describe('cleanup-stacks.yml checkout', () => {
// Every leg runs scripts from scripts/ci, so the comment names them.
it('names the scripts it checks out for', () => {
const lines = readFileSync(WORKFLOW, 'utf8').split('\n');
const at = lines.findIndex((l, i) => i > lines.indexOf(' cleanup:') && l.trim().startsWith('- uses: actions/checkout@'));
const comment = lines.slice(at - 3, at).join('\n');
assert.match(comment, /amplify-stuck-delete\.sh/);
});
});