carlos / platform Public

hosts-used scan: a snapshot expires on the box if its name never reaches the scan (Astra r1 P2)

Human

Prompt

Paul's go (2026-10-27) to fix #444: narrow Astra check, one round expected; fix findings within the stopping rules.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

Astra round 1: READY AFTER FIXES, one P2 (a snapshot whose first response is lost has no cleanup owner). Each snapshot command now starts a detached timer that removes that exact path after HOSTS_SCAN_EXPIRE seconds (900); explicit removal after paging is unchanged. TestHostsUsedScanAWSExpiresALostSnapshot loses the first response and waits for the expiry. Findings committed unedited.
claude agent, operated by paul@keymail.dev 80152787010a0d13783a20432d4e5d6ffb1929ac parent 5fa188f
3 files changed, +67 −5
  • cmd/console/hostsused_scan_test.go +36 −2
  • docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md +15 −0
  • scripts/hosts-used-scan-aws.sh +16 −3

CI passed — run details

diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go
index 42c41f0d4..16089b5ef 100644
--- a/cmd/console/hostsused_scan_test.go
+++ b/cmd/console/hostsused_scan_test.go
@@ -21,6 +21,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
boxlayout "github.com/carlosframework/platform/internal/layout"
"github.com/carlosframework/platform/internal/provision"
@@ -51,6 +52,9 @@ type fakeInstance struct {
// Break replaces one tool the box's script runs with one that fails
// after writing part of its output.
Break string `json:"break"`
+ // Lose runs this instance's nth command but loses its result, which
+ // reads as TimedOut with no output.
+ Lose int `json:"lose"`
}
// fakeAWS is the fake aws CLI. It logs every call's arguments, one JSON
@@ -161,7 +165,8 @@ func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int
return 99
}
n := fakeCounter(dir, "commands")
- if mine := fakeCounter(dir, "commands-"+opts["--instance-ids"]); inst.GrowDir != "" && (inst.GrowAt == 0 || mine == inst.GrowAt) {
+ mine := fakeCounter(dir, "commands-"+opts["--instance-ids"])
+ if inst.GrowDir != "" && (inst.GrowAt == 0 || mine == inst.GrowAt) {
os.WriteFile(filepath.Join(inst.GrowDir, fmt.Sprintf("grow-%d.example.com.db", n)), nil, 0o600)
}
var stdout, stderr strings.Builder
@@ -182,6 +187,9 @@ func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int
}
}
out := stdout.String()
+ if inst.Lose == mine {
+ code, status, out = 1, "TimedOut", ""
+ }
limit := 24000
if inst.Truncate > 0 {
limit = inst.Truncate
@@ -261,7 +269,7 @@ func newScanWorld(t *testing.T) *scanWorld {
}
w.coordsPath = filepath.Join(dir, "coords.json")
w.env = []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), "FAKE_AWS_DIR=" + w.fake,
- "HOSTS_SCAN_POLL=0", "HOSTS_SCAN_WAIT=30", "HOSTS_SCAN_RUNDIR=" + w.run, "TMPDIR=" + dir}
+ "HOSTS_SCAN_POLL=0", "HOSTS_SCAN_WAIT=30", "HOSTS_SCAN_RUNDIR=" + w.run, "HOSTS_SCAN_EXPIRE=60", "TMPDIR=" + dir}
return w
}
@@ -678,6 +686,32 @@ func TestHostsUsedScanAWSPagesOneSnapshot(t *testing.T) {
}
}
+// TestHostsUsedScanAWSExpiresALostSnapshot (#444, Astra round 1 P2): when
+// the first command's result is lost, the scan never learns the scratch
+// file's name and cannot remove it, so the box removes that exact path
+// itself once HOSTS_SCAN_EXPIRE runs out. The target fails.
+func TestHostsUsedScanAWSExpiresALostSnapshot(t *testing.T) {
+ w := newScanWorld(t)
+ w.box("box:lost", "i-0d1", "shop.example.com.db")
+ w.cfg.Instances["i-0d1"] = fakeInstance{Lose: 1}
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ writeJSON(t, rosterPath, map[string]any{"targets": []string{"box:lost"}})
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_EXPIRE=5")
+ if l := byTarget(got)["box:lost"]; code != 1 || l.OK || !strings.Contains(l.Error, "TimedOut") {
+ t.Fatalf("box:lost: exit %d, %+v\n%s", code, l, stderr)
+ }
+ if left := w.leftovers(); len(left) != 1 {
+ t.Fatalf("want the lost snapshot still on the box before it expires, got %q", left)
+ }
+ deadline := time.Now().Add(30 * time.Second)
+ for len(w.leftovers()) != 0 && time.Now().Before(deadline) {
+ time.Sleep(200 * time.Millisecond)
+ }
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("the lost snapshot did not expire: %q", left)
+ }
+}
+
// TestHostsUsedScanAWSPrefixInPlainFormOnly (Paul's cut on discussion 438):
// a bucket's prefix is taken only in plain form, segments of
// [A-Za-z0-9._-]+ joined by single slashes, none of them "." or "..", or
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md b/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md
new file mode 100644
index 000000000..e6cbcf9ce
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md
@@ -0,0 +1,15 @@
+No P1 findings.
+
+- **P2 — Brief §3, cleanup: a completed snapshot can lose its cleanup owner.** The remote command disables its removal trap before returning the first page ([scripts/hosts-used-scan-aws.sh:225](scripts/hosts-used-scan-aws.sh#L225)). The caller records `pending` only after receiving and validating the filename ([line 314](scripts/hosts-used-scan-aws.sh#L314)); an initial SSM failure returns before that ([line 304](scripts/hosts-used-scan-aws.sh#L304)).
+
+ **Failure scenario:** the snapshot completes, but polling fails, times out, or the operator interrupts before its header is processed. Neither side removes the file. A truncated or invalid first header also loses the filename. These paths leave roughly 500 KB of root-only tmpfs data per attempt; they do not compromise listing integrity, but repeated attempts accumulate files. Explicit cleanup failures also leave files, although those produce a warning.
+
+ **Fix:** give each snapshot bounded remote expiry that removes only its exact path independently of successful response delivery, while retaining immediate cleanup. Add coverage for lost initial responses and interruption before filename registration.
+
+ **Fault family:** every remote scratch file retains a cleanup owner throughout creation, transfer and termination.
+
+The remaining scoped checks look sound: pages retain header, length, checksum and line-count validation; the filename and scratch-directory constraints prevent shell injection; both `find` calls place `-ignore_readdir_race` correctly and check failure status. The new growing-directory test distinguishes snapshot paging from the old implementation, and the previous failure expectations remain except for the deliberately removed changing-directory refusal.
+
+The prescribed test command could not start: Go’s work-directory creation was denied by the read-only sandbox. Runtime verification, including the reported old-script failure, therefore remains unconfirmed. No files were changed.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh
index 2f60c84a2..937c75308 100755
--- a/scripts/hosts-used-scan-aws.sh
+++ b/scripts/hosts-used-scan-aws.sh
@@ -43,7 +43,11 @@
# reassembled listing must match all three. Nothing is truncated silently.
# The scratch file is removed by its exact name once the box is paged,
# whether paging worked or not; a box whose snapshot command fails removes
-# its own.
+# its own. Each snapshot also starts a detached timer that removes that
+# same path after HOSTS_SCAN_EXPIRE seconds (900), so a file whose name
+# never reached the scan (a lost or cut first response, an interrupted
+# run) does not outlive it for long. A box paged slower than that fails
+# cleanly: its next page finds the file gone.
#
# Read-only for platform data: the only AWS calls are s3api
# list-objects-v2, ssm send-command (running find, cut and rm of the
@@ -51,8 +55,8 @@
# every target is ok, 1 when any is not (the output file is still
# written), 2 on bad arguments, a prefix not in plain form, or an output
# file that could not be written. HOSTS_SCAN_POLL, HOSTS_SCAN_WAIT,
-# HOSTS_SCAN_PAGE and HOSTS_SCAN_RUNDIR (the boxes' scratch directory,
-# /run) exist for tests.
+# HOSTS_SCAN_PAGE, HOSTS_SCAN_RUNDIR (the boxes' scratch directory, /run)
+# and HOSTS_SCAN_EXPIRE exist for tests.
set -uo pipefail
export LC_ALL=C
usage() { echo "usage: hosts-used-scan-aws.sh --profile <aws-profile> --targets <coords.json> <roster.json> <scan.jsonl>" >&2; exit 2; }
@@ -78,6 +82,8 @@ case "$page" in ''|*[!0-9]*) echo "HOSTS_SCAN_PAGE must be a number" >&2; exit 2
rundir="${HOSTS_SCAN_RUNDIR:-/run}"
# It is written into the box's commands, so only a plain absolute path.
[[ "$rundir" =~ ^/[A-Za-z0-9._/-]*$ ]] || { echo "HOSTS_SCAN_RUNDIR must be a plain absolute path" >&2; exit 2; }
+expire="${HOSTS_SCAN_EXPIRE:-900}"
+[[ "$expire" =~ ^[1-9][0-9]{0,5}$ ]] || { echo "HOSTS_SCAN_EXPIRE must be a number of seconds" >&2; exit 2; }
command -v jq >/dev/null || { echo "hosts-used-scan: jq is required" >&2; exit 2; }
command -v aws >/dev/null || { echo "hosts-used-scan: the aws CLI is required" >&2; exit 2; }
targets="$(jq -r 'if (.targets|type) == "array" and all(.targets[]; type == "string") then .targets[] else error("no targets array") end' "$roster")" || {
@@ -210,6 +216,13 @@ umask 077
cd '$1' || { echo "cannot enter $1" >&2; exit 3; }
snap=\$(mktemp '$rundir/hosts-used-scan.XXXXXXXXXX') || { echo "cannot make a scratch file in $rundir" >&2; exit 7; }
trap 'rm -f "\$snap"' EXIT
+# The bounded expiry: this exact path, whatever happens to this command's
+# response. Detached and silent, so the command still returns at once.
+if command -v setsid >/dev/null 2>&1; then
+ setsid sh -c 'sleep $expire; rm -f -- "\$1"' sh "\$snap" </dev/null >/dev/null 2>&1 &
+else
+ sh -c 'sleep $expire; rm -f -- "\$1"' sh "\$snap" </dev/null >/dev/null 2>&1 &
+fi
nl='
'
bad=\$(find . -maxdepth 3 -ignore_readdir_race -name "*\${nl}*" -print) || { echo "find failed under $1" >&2; exit 4; }