carlos / platform Public

hosts-used scan: page one find snapshot per box (#444)

Human

Prompt

Paul's go (2026-10-27) to fix #444 and then finish flagship: each box runs find once into a mktemp scratch file in /run or /dev/shm, removed by exact path when done including on failure; page from that file keeping the sha256/length/line-count check; use -ignore_readdir_race; a fake-aws test that fails first.

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

A box's listing is taken by one find (with -ignore_readdir_race) into a mktemp scratch file in /run, and every SSM page is cut from that file, so a busy box whose files come and go between commands (annie-welding) can be scanned. The sha256, length and line-count check now covers the snapshot. The scratch file is removed by exact name after paging, on failure too; a failed snapshot command removes its own. New test TestHostsUsedScanAWSPagesOneSnapshot failed first with the old 'changed while it was paged' refusal.
claude agent, operated by paul@keymail.dev cab9c9cf7d7d58e5130ccb98a18f09591b029b43 parent 5f4df95
2 files changed, +189 −40
  • cmd/console/hostsused_scan_test.go +87 −9
  • scripts/hosts-used-scan-aws.sh +102 −31

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go
index d2b596162..42c41f0d4 100644
--- a/cmd/console/hostsused_scan_test.go
+++ b/cmd/console/hostsused_scan_test.go
@@ -228,6 +228,7 @@ func fakeCounter(dir, name string) int {
type scanWorld struct {
t *testing.T
dir, fake string
+ run string // the boxes' scratch directory, standing in for /run
env []string
coordsPath string
cfg fakeAWSConfig
@@ -246,11 +247,11 @@ func newScanWorld(t *testing.T) *scanWorld {
t.Fatal(err)
}
dir := t.TempDir()
- w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"),
+ w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"), run: filepath.Join(dir, "run"),
cfg: fakeAWSConfig{Buckets: map[string]fakeBucket{}, Instances: map[string]fakeInstance{}},
coordinates: map[string]map[string]string{}}
bin := filepath.Join(dir, "bin")
- for _, d := range []string{bin, w.fake} {
+ for _, d := range []string{bin, w.fake, w.run} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
@@ -260,7 +261,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", "TMPDIR=" + dir}
+ "HOSTS_SCAN_POLL=0", "HOSTS_SCAN_WAIT=30", "HOSTS_SCAN_RUNDIR=" + w.run, "TMPDIR=" + dir}
return w
}
@@ -354,6 +355,20 @@ func (w *scanWorld) calls() [][]string {
return out
}
+// leftovers is every scratch listing still on the boxes' scratch directory.
+func (w *scanWorld) leftovers() []string {
+ w.t.Helper()
+ ents, err := os.ReadDir(w.run)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ var out []string
+ for _, e := range ents {
+ out = append(out, e.Name())
+ }
+ return out
+}
+
func writeJSON(t *testing.T, path string, v any) {
t.Helper()
b, err := json.Marshal(v)
@@ -508,8 +523,9 @@ func TestHostsUsedScanAWSActivates(t *testing.T) {
// TestHostsUsedScanAWSFailsATargetClosed: each failure gives its target one
// ok:false line with the reason and no entries, the other targets are still
-// scanned, and the scan exits 1. A listing that changed between pages is
-// scanned again, up to three times.
+// scanned, and the scan exits 1. A box that changes between SSM commands is
+// still listed in full, from the one snapshot its first command took
+// (#444). No snapshot is left on any box, whatever failed.
func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
w := newScanWorld(t)
w.bucket("bucket:ok", "instances", "instances/a.example.com/x", "moves/b.example.com/y", "seeds/c.example.com/z")
@@ -537,7 +553,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
w.cfg.Buckets["malformed-"+m] = fakeBucket{Malformed: m}
malformed = append(malformed, "bucket:malformed-"+m)
}
- for i, tool := range []string{"gzip", "sha256sum", "wc"} {
+ for i, tool := range []string{"gzip", "sha256sum", "wc", "find"} {
inst := fmt.Sprintf("i-0b%d", i)
w.box("box:broken-"+tool, inst, "shop.example.com.db")
w.cfg.Instances[inst] = fakeInstance{Break: tool}
@@ -545,7 +561,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
roster := map[string]any{"targets": []string{"bucket:ok", "bucket:denied", "bucket:page2", "bucket:noprefix", "bucket:nocoords",
"box:okbox", "box:unsent", "box:nodir", "box:cut", "box:grows", "box:grows-once", "box:badinst", "box:nocoords", "pool:p1",
- "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc"}}
+ "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc", "box:broken-find"}}
roster["targets"] = append(roster["targets"].([]string), malformed...)
rosterPath := filepath.Join(w.dir, "roster.json")
writeJSON(t, rosterPath, roster)
@@ -554,7 +570,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
t.Fatalf("scan exit %d, want 1\n%s", code, stderr)
}
ls := byTarget(got)
- if want := 17 + len(malformedPages); len(got) != want || len(ls) != want {
+ if want := 18 + len(malformedPages); len(got) != want || len(ls) != want {
t.Fatalf("want one line for each of %d targets, got %d: %+v", want, len(got), got)
}
expect := func(target, want string) {
@@ -573,6 +589,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
"bucket:ok": "",
"box:okbox": "",
"box:grows-once": "",
+ "box:grows": "",
"bucket:denied": "AccessDenied",
"bucket:page2": "AccessDenied",
"bucket:noprefix": "no prefix for bucket:noprefix",
@@ -580,13 +597,13 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
"box:unsent": "InvalidInstanceId",
"box:nodir": "Failed (exit 3)",
"box:cut": "cut short",
- "box:grows": "changed while it was paged",
"box:badinst": "is not an instance id",
"box:nocoords": "no instance for box:nocoords",
"pool:p1": "does not know this kind of target",
"box:broken-gzip": "does not decode",
"box:broken-sha256sum": "Failed (exit 6)",
"box:broken-wc": "Failed (exit 6)",
+ "box:broken-find": "Failed (exit 4)",
} {
expect(target, want)
}
@@ -598,6 +615,67 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
t.Errorf("a bad instance id reached aws: %q", c)
}
}
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("scratch listings left on the boxes: %q", left)
+ }
+}
+
+// TestHostsUsedScanAWSPagesOneSnapshot (#444): on a busy box, files come
+// and go between SSM commands (SQLite -wal and -shm files on annie-welding),
+// so a listing re-taken for every page never matched itself across about
+// 23 pages and the box could not be scanned. Now the box runs find once
+// into a scratch file, and every page is cut from that file: the listing
+// is ok, and it is the directory as that one find saw it. The scratch file
+// is removed afterwards, also when a page fails.
+func TestHostsUsedScanAWSPagesOneSnapshot(t *testing.T) {
+ w := newScanWorld(t)
+ var paths []string
+ for i := range 40 {
+ paths = append(paths, fmt.Sprintf("app-%02d.example.com.db", i))
+ }
+ d := w.box("box:busy", "i-0c1", paths...)
+ w.cfg.Instances["i-0c1"] = fakeInstance{GrowDir: d} // a new file before every command
+ w.box("box:cut", "i-0c2", paths...)
+ w.cfg.Instances["i-0c2"] = fakeInstance{Truncate: 110}
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ writeJSON(t, rosterPath, map[string]any{"targets": []string{"box:busy", "box:cut"}})
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=64")
+ if code != 1 {
+ t.Fatalf("scan exit %d, want 1 for box:cut alone\n%s", code, stderr)
+ }
+ ls := byTarget(got)
+ busy := ls["box:busy"]
+ if !busy.OK || busy.Error != "" {
+ t.Fatalf("box:busy: %+v\n%s", busy, stderr)
+ }
+ for _, p := range paths {
+ if !slices.Contains(busy.Entries, p) {
+ t.Errorf("box:busy is missing %q", p)
+ }
+ }
+ grown := 0
+ for _, e := range busy.Entries {
+ if strings.HasPrefix(e, "grow-") {
+ grown++
+ }
+ }
+ sends := 0
+ for _, c := range w.calls() {
+ if slices.Contains(c, "send-command") && slices.Contains(c, "i-0c1") {
+ sends++
+ }
+ }
+ // The first command's file is in the snapshot; the ones made before
+ // every later page are not.
+ if grown != 1 || sends < 4 {
+ t.Errorf("box:busy has %d grown files over %d commands, want exactly the 1 its snapshot saw over several pages", grown, sends)
+ }
+ if cut := ls["box:cut"]; cut.OK || !strings.Contains(cut.Error, "cut short") {
+ t.Errorf("box:cut: %+v, want ok:false, cut short", cut)
+ }
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("scratch listings left on the boxes: %q", left)
+ }
}
// TestHostsUsedScanAWSPrefixInPlainFormOnly (Paul's cut on discussion 438):
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh
index 602a08f19..2f60c84a2 100755
--- a/scripts/hosts-used-scan-aws.sh
+++ b/scripts/hosts-used-scan-aws.sh
@@ -11,7 +11,7 @@
# moves/ and seeds/ (s3api list-objects-v2, every page).
# box:<name> every path under the box's data directory to depth 3
# (find, run through `aws ssm send-command`), relative to
-# that directory.
+# that directory, as one find saw it.
#
# The roster is provider-neutral and names targets only, so their AWS
# coordinates come from the operator's coords file, keyed by roster target:
@@ -31,19 +31,28 @@
# optional for a bucket.
#
# Any failure for a target (no coordinates, an AWS error, a command that
-# failed or timed out, a listing that changed while it was paged) gives that
-# target ok:false and the error, which activate refuses. SSM returns at most
-# 24,000 characters of output, so a box's listing comes back in find's own
-# order, gzipped and base64-encoded, in pages of HOSTS_SCAN_PAGE characters; every page
-# carries the whole listing's sha256, length and line count, and the
+# failed or timed out, a find that failed) gives that target ok:false and
+# the error, which activate refuses. SSM returns at most 24,000 characters
+# of output, so a box's listing comes back in pages of HOSTS_SCAN_PAGE
+# characters. A busy box's files come and go between commands (SQLite -wal
+# and -shm files), so the box runs find ONCE (#444), with
+# -ignore_readdir_race so a file that vanishes mid-walk is not an error,
+# and keeps the result, gzipped and base64-encoded, in a scratch file made
+# by mktemp in /run (root-only, tmpfs). Every page is cut from that file
+# and carries the snapshot's sha256, length and line count, and the
# 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.
#
-# Read-only: the only AWS calls are s3api list-objects-v2, ssm send-command
-# (running find, which writes nothing on the box) and ssm
-# get-command-invocation. Exit 0 when 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 and HOSTS_SCAN_PAGE exist for tests.
+# Read-only for platform data: the only AWS calls are s3api
+# list-objects-v2, ssm send-command (running find, cut and rm of the
+# scan's own scratch file) and ssm get-command-invocation. Exit 0 when
+# 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.
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; }
@@ -66,6 +75,9 @@ case "$page" in ''|*[!0-9]*) echo "HOSTS_SCAN_PAGE must be a number" >&2; exit 2
# SSM keeps the first 24,000 characters of output; a page and its header
# line must fit.
[ "$page" -ge 1 ] && [ "$page" -le 23000 ] || { echo "HOSTS_SCAN_PAGE must be 1 to 23000" >&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; }
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")" || {
@@ -96,7 +108,11 @@ fi
export AWS_PAGER=""
work="$(mktemp -d "${TMPDIR:-/tmp}/hosts-used-scan.XXXXXX")" || exit 2
part="$(mktemp "$out.XXXXXX")" || { rm -rf "$work"; exit 2; }
-trap 'rm -rf "$work"; rm -f "$part"' EXIT
+# A box snapshot not yet removed ("<region> <instance> <path>"): removed on
+# the way out too, so an interrupted run leaves nothing on a box.
+pending=""
+trap 'drop_pending; rm -rf "$work"; rm -f "$part"' EXIT
+trap 'exit 130' INT TERM
awsp() { aws --profile "$profile" "$@" </dev/null; }
sha256() { if command -v sha256sum >/dev/null; then sha256sum; else shasum -a 256; fi | cut -d' ' -f1; }
@@ -174,33 +190,73 @@ scan_bucket() { # <roster target> <bucket>
echo "ok bucket:$b: $(jq '.entries|length' <<<"$line") keys" >&2
}
-# remote_script <data dir> <first char> <last char>: the command the box
-# runs. POSIX sh, as AWS-RunShellScript runs it. Read-only: find and
-# encoders over pipes, nothing written (no sort, which can spill to disk;
-# find's order is stable while the directory is unchanged, and a change
-# shows as a different sum). The sum and count are taken from find's own
-# checked output, so a failed or partial encoder can only make the
-# reassembled listing disagree with them, which fails the box.
-remote_script() {
+# The box's commands, POSIX sh, as AWS-RunShellScript runs them (as root).
+#
+# snapshot_script <data dir>: run find once and keep the listing in a
+# scratch file made by mktemp in $rundir, then print its first page. The
+# file's first line is the header, "hosts-used-scan v2 <sha256> <length>
+# <lines> <name>", where sha256 and the line count are of find's own
+# checked output, length is that of the gzipped, base64-encoded listing on
+# the second line, and name is the random part of the file's name. A
+# failed or partial encoder can only make the reassembled listing disagree
+# with them, which fails the box. Until the file is complete, an exit
+# removes it. -ignore_readdir_race: a file that vanishes while find walks
+# (a SQLite -wal or -shm file closing) is not an error; any other find
+# error is.
+snapshot_script() {
cat <<EOF
export LC_ALL=C
+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
nl='
'
-bad=\$(find . -maxdepth 3 -name "*\${nl}*" -print) || { echo "find failed under $1" >&2; exit 4; }
+bad=\$(find . -maxdepth 3 -ignore_readdir_race -name "*\${nl}*" -print) || { echo "find failed under $1" >&2; exit 4; }
[ -z "\$bad" ] || { echo "a path under $1 has a newline in its name" >&2; exit 5; }
-list=\$(find . -maxdepth 3 -print) || { echo "find failed under $1" >&2; exit 4; }
+list=\$(find . -maxdepth 3 -ignore_readdir_race -print) || { echo "find failed under $1" >&2; exit 4; }
sum=\$(printf '%s\n' "\$list" | sha256sum | cut -d' ' -f1)
n=\$(printf '%s\n' "\$list" | wc -l | tr -d ' ')
blob=\$(printf '%s\n' "\$list" | gzip -n -c | base64 | tr -d '\n')
case "\$sum" in *[!0-9a-f]*|'') sum=bad ;; esac
case "\$n" in *[!0-9]*|'') n=bad ;; esac
[ "\${#sum}" -eq 64 ] && [ "\$n" != bad ] && [ -n "\$blob" ] || { echo "could not encode the listing of $1" >&2; exit 6; }
-printf 'hosts-used-scan v1 %s %s %s\n' "\$sum" "\${#blob}" "\$n"
-printf '%s' "\$blob" | cut -c $2-$3
+printf 'hosts-used-scan v2 %s %s %s %s\n%s\n' "\$sum" "\${#blob}" "\$n" "\${snap##*.}" "\$blob" >"\$snap" || { echo "could not write the scratch file in $rundir" >&2; exit 7; }
+trap - EXIT
+head -n 1 "\$snap"
+sed -n '2p' "\$snap" | cut -c 1-$2
EOF
}
+# page_script <name> <first char> <last char>: one page of a snapshot.
+page_script() {
+ cat <<EOF
+export LC_ALL=C
+snap='$rundir/hosts-used-scan.$1'
+[ -f "\$snap" ] && [ ! -L "\$snap" ] || { echo "the scratch listing \$snap is gone" >&2; exit 8; }
+head -n 1 "\$snap"
+sed -n '2p' "\$snap" | cut -c $2-$3
+EOF
+}
+
+# drop_snapshot <region> <instance> <name>: remove the box's scratch file by
+# its exact name, and say so when that fails; the listing itself stands.
+drop_snapshot() {
+ local f="$rundir/hosts-used-scan.$3"
+ if ssm_run "$1" "$2" "rm -f -- '$f' && [ ! -e '$f' ]"; then
+ pending=""
+ else
+ echo "WARN box $2: could not remove the scratch listing $f ($err). remove it by hand" >&2
+ pending=""
+ fi
+}
+drop_pending() {
+ [ -n "$pending" ] || return 0
+ local r i n err=""
+ read -r r i n <<<"$pending"
+ drop_snapshot "$r" "$i" "$n"
+}
+
# ssm_run <region> <instance> <script>: run it and leave its stdout in
# $work/stdout; on failure set $err and return 1.
ssm_run() {
@@ -230,22 +286,37 @@ ssm_run() {
done
}
-# box_listing <region> <instance> <data dir>: one consistent listing,
-# reassembled from pages, in $work/listing; on failure set $err and return
-# 1 (2 when the listing changed between pages, which is worth a retry).
+# box_listing <region> <instance> <data dir>: one snapshot, reassembled
+# from pages, in $work/listing; on failure set $err and return 1 (2 when
+# the snapshot's header changed between pages, which is worth a retry with
+# a new snapshot). The box's scratch file is removed either way.
box_listing() {
+ local r="$1" i="$2" d="$3" name="" rc
+ box_pages "$r" "$i" "$d"; rc=$?
+ [ -z "$name" ] || { local keep="$err"; drop_snapshot "$r" "$i" "$name"; err="$keep"; }
+ return "$rc"
+}
+box_pages() {
local r="$1" i="$2" d="$3" first=1 header="" total=1 got want h
: >"$work/blob"
while [ "$first" -le "$total" ]; do
- ssm_run "$r" "$i" "$(remote_script "$d" "$first" $((first + page - 1)))" || return 1
+ if [ -z "$header" ]; then
+ ssm_run "$r" "$i" "$(snapshot_script "$d" "$page")" || return 1
+ else
+ ssm_run "$r" "$i" "$(page_script "$name" "$first" $((first + page - 1)))" || return 1
+ fi
h="$(head -n1 "$work/stdout")"
- case "$h" in "hosts-used-scan v1 "*) ;; *) err="$i: no listing header in the command's output"; return 1 ;; esac
+ case "$h" in "hosts-used-scan v2 "*) ;; *) err="$i: no listing header in the command's output"; return 1 ;; esac
if [ -z "$header" ]; then
+ # The name goes into the next commands, so only mktemp's own shape.
+ name="$(cut -d' ' -f6 <<<"$h")"
+ [[ "$name" =~ ^[A-Za-z0-9]{10}$ ]] || { name=""; err="$i: a bad listing header: $h"; return 1; }
+ pending="$r $i $name"
header="$h"
total="$(cut -d' ' -f4 <<<"$h")"
case "$total" in ''|*[!0-9]*) err="$i: a bad listing header: $h"; return 1 ;; esac
elif [ "$h" != "$header" ]; then
- err="$i: the listing under $d changed while it was paged"; return 2
+ err="$i: the scratch listing under $rundir changed while it was paged"; return 2
fi
got="$(sed -n '2p' "$work/stdout" | tr -d '\r\n')"
want=$((total - first + 1)); [ "$want" -gt "$page" ] && want="$page"