Merge remote-tracking branch 'origin/main' into plans-6b-checkout-flow
# Conflicts: # internal/provision/plan9_b8_census_test.go # internal/provision/testdata/plan14-root-reads-chain.tsv
20 files changed,
+1,551
−6
README.md+3 −2cmd/console/hostsused_scan_test.go+697 −0cmd/console/main_test.go+5 −0docs/superpowers/notes/census-nearest-region-scan-claims.md+8 −0docs/superpowers/notes/census-proposal-nearest-region-scan.md+11 −0docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-confirm.md+14 −0docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md+9 −0docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r2.md+12 −0docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r3.md+15 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R2.md+121 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R3.md+131 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-confirm.md+57 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan.md+106 −0internal/layout/hostsused.go+10 −1internal/layout/hostsused_test.go+23 −0internal/provision/nearest_region_scan_census_test.go+29 −0internal/provision/plans6b_census_test.go+3 −3internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv+3 −0scripts/hosts-used-scan-aws.sh+293 −0
CI failed — run details
diff --git a/README.md b/README.md| index 2e2128fc4..5c3899b89 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -363,8 +363,9 @@ while it is stopped. |
| 1. Stop the console. |
| 2. Run `console hosts-used roster -o roster.json`. It lists every box and |
| bucket the regions and fleets use. |
| -3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh` |
| - (in infra). |
| +3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh`. |
| + Pass it a `--targets` coords file naming each box's instance and region |
| + and each bucket's prefix. The script's header shows the format. |
| 4. Run `console hosts-used activate -roster roster.json -listings |
| scan.jsonl`. A fleet that cannot be scanned can be closed instead, with |
| `-close-fleet <fleet>`. A closed fleet takes no new instances. Regions |
diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go| new file mode 100644 |
| index 000000000..d2b596162 |
| --- /dev/null |
| +++ b/cmd/console/hostsused_scan_test.go |
| @@ -0,0 +1,697 @@ |
| +package main_test |
| + |
| +// scripts/hosts-used-scan-aws.sh, the hostname history's AWS adapter |
| +// (nearest-region never-reuse plan Task 11), run against a fake `aws`: this |
| +// test binary, re-executed under the name aws (TestMain). The fake pages S3 |
| +// listings two keys at a time and runs an SSM command's script with sh |
| +// against a local directory, keeping at most SSM's 24,000 characters of its |
| +// output. The happy path goes through the real verbs: `console hosts-used |
| +// roster`, the scan, then `console hosts-used activate`. |
| + |
| +import ( |
| + "bufio" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + boxlayout "github.com/carlosframework/platform/internal/layout" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +const scanScript = "../../scripts/hosts-used-scan-aws.sh" |
| + |
| +// fakeAWSConfig is the fake's world, in config.json under FAKE_AWS_DIR. |
| +type fakeAWSConfig struct { |
| + Buckets map[string]fakeBucket `json:"buckets"` |
| + Instances map[string]fakeInstance `json:"instances"` |
| +} |
| + |
| +type fakeBucket struct { |
| + Keys []string `json:"keys"` |
| + Fail string `json:"fail"` // every call fails with this |
| + FailPage int `json:"fail_page"` // the call for this page (1-based) fails |
| + // Malformed answers a page that is no listing: one of the keys of |
| + // malformedPages. |
| + Malformed string `json:"malformed"` |
| +} |
| + |
| +type fakeInstance struct { |
| + SendFail string `json:"send_fail"` // send-command fails with this |
| + Truncate int `json:"truncate"` // keep only this many characters of output |
| + GrowDir string `json:"grow_dir"` // send-commands add a file here: every one... |
| + GrowAt int `json:"grow_at"` // ...or only this instance's nth |
| + // Break replaces one tool the box's script runs with one that fails |
| + // after writing part of its output. |
| + Break string `json:"break"` |
| +} |
| + |
| +// fakeAWS is the fake aws CLI. It logs every call's arguments, one JSON |
| +// array per line, to calls.jsonl, and refuses any operation the scan has no |
| +// business making. |
| +func fakeAWS(args []string) int { |
| + dir := os.Getenv("FAKE_AWS_DIR") |
| + if f, err := os.OpenFile(filepath.Join(dir, "calls.jsonl"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600); err == nil { |
| + b, _ := json.Marshal(args) |
| + f.Write(append(b, '\n')) |
| + f.Close() |
| + } |
| + var cfg fakeAWSConfig |
| + if b, err := os.ReadFile(filepath.Join(dir, "config.json")); err != nil || json.Unmarshal(b, &cfg) != nil { |
| + fmt.Fprintln(os.Stderr, "fake aws: no config") |
| + return 99 |
| + } |
| + opts, words := map[string]string{}, []string{} |
| + for i := 0; i < len(args); i++ { |
| + switch { |
| + case args[i] == "--no-paginate": |
| + case strings.HasPrefix(args[i], "--") && i+1 < len(args): |
| + opts[args[i]] = args[i+1] |
| + i++ |
| + default: |
| + words = append(words, args[i]) |
| + } |
| + } |
| + op := strings.Join(words, " ") |
| + switch op { |
| + case "s3api list-objects-v2": |
| + return fakeListObjects(cfg, opts) |
| + case "ssm send-command": |
| + return fakeSendCommand(dir, cfg, opts) |
| + case "ssm get-command-invocation": |
| + return fakeGetInvocation(dir, opts) |
| + } |
| + fmt.Fprintf(os.Stderr, "fake aws: unexpected call %q\n", op) |
| + return 99 |
| +} |
| + |
| +func fakeListObjects(cfg fakeAWSConfig, opts map[string]string) int { |
| + b, ok := cfg.Buckets[opts["--bucket"]] |
| + if !ok { |
| + fmt.Fprintln(os.Stderr, "An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist") |
| + return 254 |
| + } |
| + start := 0 |
| + if tok := opts["--continuation-token"]; tok != "" { |
| + start, _ = strconv.Atoi(strings.TrimPrefix(tok, "tok-")) |
| + } |
| + if b.Fail != "" || (b.FailPage > 0 && start/2+1 == b.FailPage) { |
| + fmt.Fprintf(os.Stderr, "An error occurred (AccessDenied) when calling the ListObjectsV2 operation: %s\n", b.Fail) |
| + return 254 |
| + } |
| + if page, ok := malformedPages[b.Malformed]; ok { |
| + fmt.Println(page) |
| + return 0 |
| + } |
| + var keys []string |
| + for _, k := range b.Keys { |
| + if strings.HasPrefix(k, opts["--prefix"]) { |
| + keys = append(keys, k) |
| + } |
| + } |
| + sort.Strings(keys) |
| + end := min(start+2, len(keys)) |
| + resp := map[string]any{"IsTruncated": end < len(keys), "KeyCount": end - start} |
| + if end > start { |
| + var contents []map[string]string |
| + for _, k := range keys[start:end] { |
| + contents = append(contents, map[string]string{"Key": k}) |
| + } |
| + resp["Contents"] = contents |
| + } |
| + if end < len(keys) { |
| + resp["NextContinuationToken"] = "tok-" + strconv.Itoa(end) |
| + } |
| + json.NewEncoder(os.Stdout).Encode(resp) |
| + return 0 |
| +} |
| + |
| +// malformedPages are list-objects-v2 replies that are no listing. |
| +var malformedPages = map[string]string{ |
| + "nokey": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Size":1}]}`, |
| + "key-number": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Key":5}]}`, |
| + "empty": `{}`, |
| + "outside": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Key":"elsewhere/a.example.com/x"}]}`, |
| + "contents-false": `{"IsTruncated":false,"KeyCount":0,"Contents":false}`, |
| + "contents-null": `{"IsTruncated":false,"KeyCount":0,"Contents":null}`, |
| + "two-objects": "{\"IsTruncated\":true,\"KeyCount\":0,\"NextContinuationToken\":\"t\"}\n{\"IsTruncated\":false,\"KeyCount\":0}", |
| + "truncated-no-token": `{"IsTruncated":true,"KeyCount":0}`, |
| + "token-not-truncated": `{"IsTruncated":false,"KeyCount":0,"NextContinuationToken":"t"}`, |
| + "array": `[{"IsTruncated":false,"KeyCount":0}]`, |
| +} |
| + |
| +func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int { |
| + inst, ok := cfg.Instances[opts["--instance-ids"]] |
| + if !ok || inst.SendFail != "" { |
| + fmt.Fprintf(os.Stderr, "An error occurred (InvalidInstanceId) when calling the SendCommand operation: %s\n", inst.SendFail) |
| + return 254 |
| + } |
| + var params struct { |
| + Commands []string `json:"commands"` |
| + } |
| + if err := json.Unmarshal([]byte(opts["--parameters"]), ¶ms); err != nil || len(params.Commands) != 1 { |
| + fmt.Fprintln(os.Stderr, "fake aws: bad --parameters") |
| + return 99 |
| + } |
| + n := fakeCounter(dir, "commands") |
| + if mine := fakeCounter(dir, "commands-"+opts["--instance-ids"]); 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 |
| + cmd := exec.Command("sh", "-c", params.Commands[0]) |
| + if inst.Break != "" { |
| + shims := filepath.Join(dir, "shims-"+inst.Break) |
| + os.MkdirAll(shims, 0o755) |
| + os.WriteFile(filepath.Join(shims, inst.Break), []byte("#!/bin/sh\nhead -c 7\nexit 1\n"), 0o755) |
| + cmd.Env = append(os.Environ(), "PATH="+shims+string(os.PathListSeparator)+os.Getenv("PATH")) |
| + } |
| + cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| + code, status := 0, "Success" |
| + if err := cmd.Run(); err != nil { |
| + code, status = 1, "Failed" |
| + var ee *exec.ExitError |
| + if errors.As(err, &ee) { |
| + code = ee.ExitCode() |
| + } |
| + } |
| + out := stdout.String() |
| + limit := 24000 |
| + if inst.Truncate > 0 { |
| + limit = inst.Truncate |
| + } |
| + if len(out) > limit { |
| + out = out[:limit] |
| + } |
| + id := fmt.Sprintf("cmd-%d", n) |
| + b, _ := json.Marshal(map[string]any{"Status": status, "ResponseCode": code, "StandardOutputContent": out, "StandardErrorContent": stderr.String()}) |
| + os.WriteFile(filepath.Join(dir, id+".json"), b, 0o600) |
| + fmt.Println(id) |
| + return 0 |
| +} |
| + |
| +// fakeGetInvocation answers InvocationDoesNotExist on its first call for a |
| +// command, as SSM does straight after send-command, then the result. |
| +func fakeGetInvocation(dir string, opts map[string]string) int { |
| + id := opts["--command-id"] |
| + seen := filepath.Join(dir, id+".seen") |
| + if _, err := os.Stat(seen); err != nil { |
| + os.WriteFile(seen, nil, 0o600) |
| + fmt.Fprintln(os.Stderr, "An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation: ") |
| + return 254 |
| + } |
| + b, err := os.ReadFile(filepath.Join(dir, id+".json")) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "An error occurred (InvalidCommandId) when calling the GetCommandInvocation operation: ") |
| + return 254 |
| + } |
| + os.Stdout.Write(b) |
| + return 0 |
| +} |
| + |
| +func fakeCounter(dir, name string) int { |
| + p := filepath.Join(dir, name) |
| + b, _ := os.ReadFile(p) |
| + n, _ := strconv.Atoi(strings.TrimSpace(string(b))) |
| + n++ |
| + os.WriteFile(p, []byte(strconv.Itoa(n)), 0o600) |
| + return n |
| +} |
| + |
| +// scanWorld is one test's fake AWS, its PATH and its scratch. |
| +type scanWorld struct { |
| + t *testing.T |
| + dir, fake string |
| + env []string |
| + coordsPath string |
| + cfg fakeAWSConfig |
| + coordinates map[string]map[string]string |
| +} |
| + |
| +func newScanWorld(t *testing.T) *scanWorld { |
| + t.Helper() |
| + for _, tool := range []string{"jq", "sh", "find", "gzip", "base64", "sha256sum"} { |
| + if _, err := exec.LookPath(tool); err != nil { |
| + t.Skipf("%s not installed", tool) |
| + } |
| + } |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := t.TempDir() |
| + w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"), |
| + 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} { |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := os.Symlink(exe, filepath.Join(bin, "aws")); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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} |
| + return w |
| +} |
| + |
| +// box makes a data directory holding paths (a trailing "/" is a directory) |
| +// behind instance inst, with the box's coordinates. |
| +func (w *scanWorld) box(target, inst string, paths ...string) string { |
| + w.t.Helper() |
| + d := filepath.Join(w.dir, "data-"+inst) |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + w.t.Fatal(err) |
| + } |
| + for _, p := range paths { |
| + full := filepath.Join(d, p) |
| + if strings.HasSuffix(p, "/") { |
| + os.MkdirAll(full, 0o755) |
| + continue |
| + } |
| + os.MkdirAll(filepath.Dir(full), 0o755) |
| + if err := os.WriteFile(full, []byte("x"), 0o600); err != nil { |
| + w.t.Fatal(err) |
| + } |
| + } |
| + w.cfg.Instances[inst] = fakeInstance{} |
| + w.coordinates[target] = map[string]string{"instance": inst, "region": "eu-west-1", "data_dir": d} |
| + return d |
| +} |
| + |
| +func (w *scanWorld) bucket(target, prefix string, keys ...string) { |
| + name := strings.TrimPrefix(target, "bucket:") |
| + w.cfg.Buckets[name] = fakeBucket{Keys: keys} |
| + w.coordinates[target] = map[string]string{"prefix": prefix, "region": "eu-west-1"} |
| +} |
| + |
| +// scan writes the fake's config and the coords, runs the script and |
| +// returns its output lines, its stderr and its exit code. |
| +func (w *scanWorld) scan(rosterPath string, extraEnv ...string) ([]provision.TargetListing, string, int) { |
| + w.t.Helper() |
| + writeJSON(w.t, filepath.Join(w.fake, "config.json"), w.cfg) |
| + writeJSON(w.t, w.coordsPath, w.coordinates) |
| + out := filepath.Join(w.dir, "scan.jsonl") |
| + os.Remove(out) |
| + cmd := exec.Command(scanScript, "--profile", "scan-test", "--targets", w.coordsPath, rosterPath, out) |
| + cmd.Env = append(append(os.Environ(), w.env...), extraEnv...) |
| + var stderr strings.Builder |
| + cmd.Stderr = &stderr |
| + err := cmd.Run() |
| + code := 0 |
| + var ee *exec.ExitError |
| + if errors.As(err, &ee) { |
| + code = ee.ExitCode() |
| + } else if err != nil { |
| + w.t.Fatalf("run the scan: %v", err) |
| + } |
| + f, err := os.Open(out) |
| + if err != nil { |
| + w.t.Fatalf("no scan output (exit %d): %v\n%s", code, err, stderr.String()) |
| + } |
| + defer f.Close() |
| + // Every line is one JSON object, as activate's reader (readListings) |
| + // decodes them: strictly, with no unknown fields. |
| + var got []provision.TargetListing |
| + sc := bufio.NewScanner(f) |
| + sc.Buffer(nil, 1<<24) |
| + for sc.Scan() { |
| + dec := json.NewDecoder(strings.NewReader(sc.Text())) |
| + dec.DisallowUnknownFields() |
| + var l provision.TargetListing |
| + if err := dec.Decode(&l); err != nil { |
| + w.t.Fatalf("line %q: %v", sc.Text(), err) |
| + } |
| + got = append(got, l) |
| + } |
| + return got, stderr.String(), code |
| +} |
| + |
| +// calls is every aws invocation the fake saw. |
| +func (w *scanWorld) calls() [][]string { |
| + w.t.Helper() |
| + b, _ := os.ReadFile(filepath.Join(w.fake, "calls.jsonl")) |
| + var out [][]string |
| + for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") { |
| + if line == "" { |
| + continue |
| + } |
| + var args []string |
| + if err := json.Unmarshal([]byte(line), &args); err != nil { |
| + w.t.Fatal(err) |
| + } |
| + out = append(out, args) |
| + } |
| + return out |
| +} |
| + |
| +func writeJSON(t *testing.T, path string, v any) { |
| + t.Helper() |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, b, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func byTarget(ls []provision.TargetListing) map[string]provision.TargetListing { |
| + out := map[string]provision.TargetListing{} |
| + for _, l := range ls { |
| + out[l.Kind+":"+l.Target] = l |
| + } |
| + return out |
| +} |
| + |
| +// TestHostsUsedScanAWSActivates: a roster taken by the real console, scanned |
| +// through paged S3 listings and paged SSM output, is accepted by the real |
| +// activate, which marks every hostname the listings name. Every aws call |
| +// names the profile, and is a listing, a send-command or a read of its |
| +// result. Before that, a scan with a failed target is refused by activate. |
| +func TestHostsUsedScanAWSActivates(t *testing.T) { |
| + bin := buildConsole(t) |
| + w := newScanWorld(t) |
| + deploy := filepath.Join(w.dir, "deploy") |
| + for box, edges := range map[string]string{ |
| + "b1": `{"v":1,"box":"b1","eip":"192.0.2.1","region":"eu-west-1","placement":"","data_bucket":"data-ie","hosts":{}}`, |
| + "b2": `{"v":1,"box":"b2","eip":"192.0.2.2","region":"eu-west-2","placement":"uk","data_bucket":"data-uk","hosts":{}}`, |
| + } { |
| + p := filepath.Join(deploy, "control", "edges", box+".json") |
| + os.MkdirAll(filepath.Dir(p), 0o755) |
| + if err := os.WriteFile(p, []byte(edges), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + os.MkdirAll(filepath.Join(w.dir, "console"), 0o755) |
| + run := runner(t, bin, "CARLOS_DEPLOYMENT_DIR="+deploy, "CONSOLE_DB="+filepath.Join(w.dir, "console", "console.db"), |
| + "CARLOS_REGISTRY="+filepath.Join(w.dir, "registry.db")) |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + if out, err := run("hosts-used", "roster", "-o", rosterPath); err != nil { |
| + t.Fatalf("roster: %v\n%s", err, out) |
| + } |
| + |
| + // Seven keys under the three roots, two keys a page: several pages per |
| + // prefix. other/ is outside them and never listed. |
| + ieKeys := []string{ |
| + "instances/shop.example.com/db/000001", "instances/shop.example.com/generation", "instances/blog.example.org/db/1", |
| + "moves/moved.example.net/stage", "moves/@lanes/lane-1", "moves/@offline/off.example.com/x", |
| + "seeds/seed.example.com/snap", |
| + } |
| + w.bucket("bucket:data-ie", "instances", append(slices.Clone(ieKeys), "other/not-a-root")...) |
| + // An empty prefix: replicas at the top level, the whole bucket listed. |
| + ukKeys := []string{"uk.example.com/db/1", "moves/uk-moved.example.com/x", "seeds/uk-seed.example.com/y"} |
| + w.bucket("bucket:data-uk", "", ukKeys...) |
| + var filler []string |
| + for i := range 40 { |
| + filler = append(filler, fmt.Sprintf("static/asset-%02d.css", i)) |
| + } |
| + w.box("box:b1", "i-0b1", append([]string{ |
| + "shop.example.com.db", "shop.example.com.db-wal", "registry.db", |
| + "instances/blog.example.org/app.db", ".offline-moves/moved.example.net/x", "deep/a/b/c/too-deep.example.com.db", |
| + }, filler...)...) |
| + w.box("box:b2", "i-0b2", "uk.example.com.db") |
| + |
| + // A failed target: the scan says so, and activate refuses the listing. |
| + w.cfg.Buckets["data-ie"] = fakeBucket{Keys: w.cfg.Buckets["data-ie"].Keys, Fail: "Access Denied"} |
| + if _, stderr, code := w.scan(rosterPath); code != 1 || !strings.Contains(stderr, "FAIL bucket:data-ie") { |
| + t.Fatalf("scan with a denied bucket: exit %d\n%s", code, stderr) |
| + } |
| + listings := filepath.Join(w.dir, "scan.jsonl") |
| + if out, err := run("hosts-used", "activate", "-roster", rosterPath, "-listings", listings); err == nil || |
| + !strings.Contains(out, "The listing of bucket:data-ie failed.") { |
| + t.Fatalf("activate took a failed listing: %v\n%s", err, out) |
| + } |
| + w.cfg.Buckets["data-ie"] = fakeBucket{Keys: w.cfg.Buckets["data-ie"].Keys} |
| + os.Remove(filepath.Join(w.fake, "calls.jsonl")) |
| + |
| + // 64 characters a page: the box listings take several SSM pages. |
| + got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=64") |
| + if code != 0 { |
| + t.Fatalf("scan exit %d\n%s", code, stderr) |
| + } |
| + ls := byTarget(got) |
| + if len(got) != 4 || len(ls) != 4 { |
| + t.Fatalf("want one line for each of 4 targets, got %+v", got) |
| + } |
| + for k, l := range ls { |
| + if !l.OK || l.Error != "" { |
| + t.Fatalf("%s: %+v", k, l) |
| + } |
| + } |
| + sort.Strings(ieKeys) |
| + if ie := ls["bucket:data-ie"]; !slices.Equal(ie.Entries, ieKeys) || ie.Prefix != "instances" { |
| + t.Errorf("data-ie = %q prefix %q, want %q", ie.Entries, ie.Prefix, ieKeys) |
| + } |
| + sort.Strings(ukKeys) |
| + if uk := ls["bucket:data-uk"]; !slices.Equal(uk.Entries, ukKeys) || uk.Prefix != "" { |
| + t.Errorf("data-uk = %q prefix %q, want %q", uk.Entries, uk.Prefix, ukKeys) |
| + } |
| + b1 := ls["box:b1"].Entries |
| + for _, want := range []string{"shop.example.com.db", "instances", "instances/blog.example.org", "instances/blog.example.org/app.db", |
| + ".offline-moves/moved.example.net/x", "deep/a/b", "static/asset-39.css"} { |
| + if !slices.Contains(b1, want) { |
| + t.Errorf("box b1 is missing %q: %q", want, b1) |
| + } |
| + } |
| + for _, e := range b1 { |
| + if strings.HasPrefix(e, "/") || strings.HasPrefix(e, "./") || e == "." || strings.Count(e, "/") > 2 { |
| + t.Errorf("box b1 entry %q is not relative to depth 3", e) |
| + } |
| + } |
| + hosts, unmapped := boxlayout.HostsFromBoxListing(b1) |
| + if len(unmapped) != 0 || !slices.Contains(hosts, "shop.example.com") || !slices.Contains(hosts, "blog.example.org") { |
| + t.Errorf("box b1 maps to %q, unmapped %q", hosts, unmapped) |
| + } |
| + |
| + // Pagination happened on both sides. |
| + lists, sends := 0, 0 |
| + for _, c := range w.calls() { |
| + if len(c) < 2 || c[0] != "--profile" || c[1] != "scan-test" { |
| + t.Errorf("a call without the profile first: %q", c) |
| + } |
| + switch op := strings.Join(c[2:min(4, len(c))], " "); op { |
| + case "s3api list-objects-v2": |
| + lists++ |
| + case "ssm send-command": |
| + sends++ |
| + case "ssm get-command-invocation": |
| + default: |
| + t.Errorf("an unexpected aws call: %q", c) |
| + } |
| + } |
| + if lists < 7 || sends < 4 { |
| + t.Errorf("%d listings and %d commands: the scan did not page", lists, sends) |
| + } |
| + |
| + // The real activate accepts the scan and marks what it names. |
| + out, err := run("hosts-used", "activate", "-roster", rosterPath, "-listings", listings) |
| + if err != nil || !strings.Contains(out, "the hostname history is complete") { |
| + t.Fatalf("activate: %v\n%s", err, out) |
| + } |
| + for _, h := range []string{"shop.example.com", "blog.example.org", "moved.example.net", "off.example.com", "seed.example.com", |
| + "uk.example.com", "uk-moved.example.com", "uk-seed.example.com"} { |
| + if _, err := os.Stat(filepath.Join(deploy, "control", "hosts-used", h+".json")); err != nil { |
| + t.Errorf("%s is not marked: %v", h, err) |
| + } |
| + } |
| +} |
| + |
| +// 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. |
| +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") |
| + w.bucket("bucket:denied", "instances", "instances/a.example.com/x") |
| + w.cfg.Buckets["denied"] = fakeBucket{Fail: "Access Denied"} |
| + w.bucket("bucket:page2", "instances", "instances/a.example.com/1", "instances/a.example.com/2", "instances/a.example.com/3") |
| + w.cfg.Buckets["page2"] = fakeBucket{Keys: w.cfg.Buckets["page2"].Keys, FailPage: 2} |
| + w.cfg.Buckets["noprefix"] = fakeBucket{} |
| + w.coordinates["bucket:noprefix"] = map[string]string{"region": "eu-west-1"} |
| + w.box("box:okbox", "i-0a0", "shop.example.com.db") |
| + w.box("box:unsent", "i-0a1", "shop.example.com.db") |
| + w.cfg.Instances["i-0a1"] = fakeInstance{SendFail: "Instances not in a valid state for account"} |
| + w.box("box:nodir", "i-0a2") |
| + w.coordinates["box:nodir"]["data_dir"] = filepath.Join(w.dir, "no-such-dir") |
| + w.box("box:cut", "i-0a3", "shop.example.com.db") |
| + w.cfg.Instances["i-0a3"] = fakeInstance{Truncate: 110} |
| + d := w.box("box:grows", "i-0a4", "shop.example.com.db") |
| + w.cfg.Instances["i-0a4"] = fakeInstance{GrowDir: d} |
| + d = w.box("box:grows-once", "i-0a5", "shop.example.com.db") |
| + w.cfg.Instances["i-0a5"] = fakeInstance{GrowDir: d, GrowAt: 2} |
| + w.coordinates["box:badinst"] = map[string]string{"instance": "i-0a6; rm -rf /", "region": "eu-west-1"} |
| + var malformed []string |
| + for m := range malformedPages { |
| + w.bucket("bucket:malformed-"+m, "instances") |
| + w.cfg.Buckets["malformed-"+m] = fakeBucket{Malformed: m} |
| + malformed = append(malformed, "bucket:malformed-"+m) |
| + } |
| + for i, tool := range []string{"gzip", "sha256sum", "wc"} { |
| + inst := fmt.Sprintf("i-0b%d", i) |
| + w.box("box:broken-"+tool, inst, "shop.example.com.db") |
| + w.cfg.Instances[inst] = fakeInstance{Break: tool} |
| + } |
| + |
| + 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"}} |
| + roster["targets"] = append(roster["targets"].([]string), malformed...) |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + writeJSON(t, rosterPath, roster) |
| + got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=40") |
| + if code != 1 { |
| + 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 { |
| + t.Fatalf("want one line for each of %d targets, got %d: %+v", want, len(got), got) |
| + } |
| + expect := func(target, want string) { |
| + t.Helper() |
| + l, ok := ls[target] |
| + switch { |
| + case !ok: |
| + t.Errorf("%s: no line", target) |
| + case want == "" && (!l.OK || l.Error != "" || len(l.Entries) == 0): |
| + t.Errorf("%s: want ok with entries, got %+v", target, l) |
| + case want != "" && (l.OK || !strings.Contains(l.Error, want) || len(l.Entries) != 0): |
| + t.Errorf("%s: want ok:false with %q and no entries, got %+v", target, want, l) |
| + } |
| + } |
| + for target, want := range map[string]string{ |
| + "bucket:ok": "", |
| + "box:okbox": "", |
| + "box:grows-once": "", |
| + "bucket:denied": "AccessDenied", |
| + "bucket:page2": "AccessDenied", |
| + "bucket:noprefix": "no prefix for bucket:noprefix", |
| + "bucket:nocoords": "no prefix for bucket:nocoords", |
| + "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)", |
| + } { |
| + expect(target, want) |
| + } |
| + for m := range malformedPages { |
| + expect("bucket:malformed-"+m, "not a well-formed listing") |
| + } |
| + for _, c := range w.calls() { |
| + if slices.Contains(c, "i-0a6; rm -rf /") { |
| + t.Errorf("a bad instance id reached aws: %q", c) |
| + } |
| + } |
| +} |
| + |
| +// 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 |
| +// "" (replicas at the top level). A prefix whose first segment is moves or |
| +// seeds is refused too: the bucket mapper reads those roots first, so a |
| +// replica under them would be taken for move or seed data of another host |
| +// (Astra round 3). Any such prefix stops the whole run before any AWS call, |
| +// with exit 2 and no output. A plain prefix is listed as written. |
| +func TestHostsUsedScanAWSPrefixInPlainFormOnly(t *testing.T) { |
| + keys := []string{"top.example.com/db/1", "moves/m.example.com/x", "a/b.c-d_e/i.example.com/y", "instances/j.example.com/z"} |
| + refusals := map[string]string{"moves": "moves or seeds", "moves/x": "moves or seeds", "seeds/x": "moves or seeds"} |
| + for _, bad := range []string{"/instances", "instances/", "///", " //instances// ", "a//b", "a/./b", "./a", "a/..", "..", ".", |
| + "snapshots/../instances", " instances", "inst ances", "instances\t", "\u00edinstances", "a\nb", "a/b/"} { |
| + refusals[bad] = "plain form" |
| + } |
| + for bad, why := range refusals { |
| + w := newScanWorld(t) |
| + w.bucket("bucket:good", "instances", keys...) |
| + w.bucket("bucket:bad", bad, keys...) |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + writeJSON(t, rosterPath, map[string]any{"targets": []string{"bucket:good", "bucket:bad"}}) |
| + writeJSON(t, filepath.Join(w.fake, "config.json"), w.cfg) |
| + writeJSON(t, w.coordsPath, w.coordinates) |
| + out := filepath.Join(w.dir, "scan.jsonl") |
| + cmd := exec.Command(scanScript, "--profile", "scan-test", "--targets", w.coordsPath, rosterPath, out) |
| + cmd.Env = append(os.Environ(), w.env...) |
| + b, err := cmd.CombinedOutput() |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 2 || !strings.Contains(string(b), "bucket:bad") || !strings.Contains(string(b), why) { |
| + t.Errorf("prefix %q: %v, want exit 2 naming bucket:bad and %q\n%s", bad, err, why, b) |
| + } |
| + if _, err := os.Stat(out); err == nil { |
| + t.Errorf("prefix %q: an output file was written", bad) |
| + } |
| + if calls := w.calls(); len(calls) != 0 { |
| + t.Errorf("prefix %q: %d aws calls before the refusal", bad, len(calls)) |
| + } |
| + } |
| + w := newScanWorld(t) |
| + w.bucket("bucket:top", "", keys...) |
| + w.bucket("bucket:one", "instances", keys...) |
| + w.bucket("bucket:two", "a/b.c-d_e", keys...) |
| + w.bucket("bucket:movesish", "moves-archive", keys...) |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + writeJSON(t, rosterPath, map[string]any{"targets": []string{"bucket:top", "bucket:one", "bucket:two", "bucket:movesish"}}) |
| + got, stderr, code := w.scan(rosterPath) |
| + if code != 0 { |
| + t.Fatalf("plain prefixes: exit %d\n%s", code, stderr) |
| + } |
| + ls := byTarget(got) |
| + if l := ls["bucket:top"]; l.Prefix != "" || !slices.Equal(l.Entries, slices.Sorted(slices.Values(keys))) { |
| + t.Errorf("prefix \"\" = %+v, want the whole bucket", l) |
| + } |
| + if l := ls["bucket:one"]; l.Prefix != "instances" || !slices.Equal(l.Entries, []string{"instances/j.example.com/z", "moves/m.example.com/x"}) { |
| + t.Errorf("prefix instances = %+v", l) |
| + } |
| + if l := ls["bucket:movesish"]; !l.OK || l.Prefix != "moves-archive" { |
| + t.Errorf("prefix moves-archive = %+v, want it listed", l) |
| + } |
| + if l := ls["bucket:two"]; l.Prefix != "a/b.c-d_e" || !slices.Equal(l.Entries, []string{"a/b.c-d_e/i.example.com/y", "moves/m.example.com/x"}) { |
| + t.Errorf("prefix a/b.c-d_e = %+v", l) |
| + } |
| +} |
| + |
| +// TestHostsUsedScanAWSNeverPublishesAShortFile: when the output cannot be |
| +// written in full, the scan exits 2 and the earlier output file is left as |
| +// it was. Many targets with no coordinates fill the output past a |
| +// one-block file size limit with no other file written. |
| +func TestHostsUsedScanAWSNeverPublishesAShortFile(t *testing.T) { |
| + w := newScanWorld(t) |
| + var targets []string |
| + for i := range 30 { |
| + targets = append(targets, fmt.Sprintf("box:a-box-with-a-long-name-and-no-coordinates-%02d", i)) |
| + } |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + writeJSON(t, rosterPath, map[string]any{"targets": targets}) |
| + writeJSON(t, filepath.Join(w.fake, "config.json"), w.cfg) |
| + writeJSON(t, w.coordsPath, w.coordinates) |
| + out := filepath.Join(w.dir, "scan.jsonl") |
| + if err := os.WriteFile(out, []byte("earlier\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // SIGXFSZ ignored, so a write past the limit fails with EFBIG instead. |
| + cmd := exec.Command("bash", "-c", `trap '' XFSZ; ulimit -f 1; exec "$0" "$@"`, scanScript, |
| + "--profile", "scan-test", "--targets", w.coordsPath, rosterPath, out) |
| + cmd.Env = append(os.Environ(), w.env...) |
| + b, err := cmd.CombinedOutput() |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 2 || !strings.Contains(string(b), "could not write") { |
| + t.Fatalf("scan = %v, want exit 2 on a failed write\n%s", err, b) |
| + } |
| + if body, _ := os.ReadFile(out); string(body) != "earlier\n" { |
| + t.Errorf("the output file changed: %q", body) |
| + } |
| +} |
diff --git a/cmd/console/main_test.go b/cmd/console/main_test.go| index 0c889abc5..2e93612e3 100644 |
| --- a/cmd/console/main_test.go |
| +++ b/cmd/console/main_test.go |
| @@ -64,6 +64,11 @@ func runner(t *testing.T, bin string, env ...string) func(args ...string) (strin |
| } |
| func TestMain(m *testing.M) { |
| + // The fake aws CLI for the hosts-used scan script (hostsused_scan_test.go): |
| + // this binary, run under the name aws. |
| + if filepath.Base(os.Args[0]) == "aws" { |
| + os.Exit(fakeAWS(os.Args[1:])) |
| + } |
| // The GeoIP verifier verb: openGeoIP re-runs its own binary to verify |
| // the override in a child process, and under `go test` that binary is |
| // this one. |
diff --git a/docs/superpowers/notes/census-nearest-region-scan-claims.md b/docs/superpowers/notes/census-nearest-region-scan-claims.md| new file mode 100644 |
| index 000000000..0e389bd81 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-nearest-region-scan-claims.md |
| @@ -0,0 +1,8 @@ |
| +# CLAIMS for the root-read census, branch nearest-region-scan (amadan #437, #438; nearest-region never-reuse Task 11). |
| +# Format (AGENTS.md "The census"): <file>:<unit><TAB><what changed>. Lines starting with # are ignored. |
| +# Base: 0a32ce38 (origin/main). No root-read unit changed, so there are no unit claims. |
| +# The internal/layout envelope is re-pinned for one change: HostsFromBoxListing (internal/layout/hostsused.go), |
| +# a pure mapping with no I/O, now skips instances/_probe and .instances/_probe (instancectl.ProbeDirName, the |
| +# readiness probe's own directory, made at bootstrap) with anything below them, by exact name, instead of |
| +# reporting them unmapped. Its only caller is console hosts-used activate (cmd/console, out of scope); root |
| +# never calls it. No read added. |
diff --git a/docs/superpowers/notes/census-proposal-nearest-region-scan.md b/docs/superpowers/notes/census-proposal-nearest-region-scan.md| new file mode 100644 |
| index 000000000..2e183e0d2 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-nearest-region-scan.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: nearest-region-scan |
| + |
| +Ruling `census-ruling-nearest-region-scan`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/layout`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Seal: `f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7` → `f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-confirm.md b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-confirm.md| new file mode 100644 |
| index 000000000..2387a93d9 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-confirm.md |
| @@ -0,0 +1,14 @@ |
| +## Part A |
| + |
| +- **P1-1: fixed.** The [prefix gate](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:76) rejects first segments `moves` and `seeds` and exits before AWS calls. Direct execution of its jq predicate confirmed both roots and nested forms are refused; `moves-archive` remains accepted. [Witnesses](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/cmd/console/hostsused_scan_test.go:611) assert exit 2, no output, and zero AWS calls. |
| +- **P1-2: partly.** Independently recomputed fingerprints match the [record-write replacement](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/nearest_region_scan_census_test.go:15) and [layout envelope](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv:3). The [inventory selection](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/plan9_b8_census_test.go:369) and [chain entry](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/testdata/plan14-root-reads-chain.tsv:16) are connected. Required test passes remain unverified: both permitted commands stopped before running tests because Go’s work-directory creation failed with `read-only file system`. |
| + |
| +No new in-scope P1 found. |
| + |
| +**NOT CONFIRMED** — P1-2’s required test execution remains unverified; this is an environment limitation, not an observed census assertion failure. |
| + |
| +## Part B |
| + |
| +**APPROVE — `internal/layout`.** The change skips only the exact reserved `_probe` directory. It adds no I/O or root authority and weakens no check root relies on. Valid hostnames cannot equal `_probe`; hashed instance identifiers cannot equal it either. |
| + |
| +Read the changed mapper and its helpers at [hostsused.go:37–167](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/layout/hostsused.go:37), the changed [test:153–168](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/layout/hostsused_test.go:153), and their dependencies: [probe constant:590–593](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/instancectl/names.go:590), [hostname validation:9–28](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/launchctx/controlname/names.go:9), [InstanceID:3154–3173](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/provision.go:3154), and [SortedKeys:73–80](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/hostsused_map.go:73). The sole production caller is [console activation:390–400](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/console/hostsused_activate.go:390). |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md| new file mode 100644 |
| index 000000000..762d76526 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md |
| @@ -0,0 +1,9 @@ |
| +1. **P1 — Task 11, §§1–2: remote sorting can silently discard the inventory.** At [scripts/hosts-used-scan-aws.sh:137](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:137), the `sort` exit status is ignored. If it fails from memory or temporary-space exhaustion, the script hashes and encodes its empty or partial output, then exits successfully. Verified with the generated script under `sh`: a failing sort produced exit 0, matching checksum/length/count, and ultimately `ok:true, entries:[""]`. The box mapper ignores that empty entry, so activation can complete without marking orphaned data. Unrestricted `sort` can also spill temporary files onto the box, violating the read-only requirement. **Fix:** check transformation failures and use bounded, memory-only processing that refuses excess input; add a failing-sort witness. **Fault family:** completeness of the remote inventory before checksumming; remote read-only boundary. |
| + |
| +2. **P1 — Task 11, §§2–3: prefix normalization can scan the wrong namespace successfully.** [scripts/hosts-used-scan-aws.sh:109](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:109) removes only one leading and trailing slash. The box configuration removes all surrounding slashes at [internal/activator/activator.go:134](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/activator/activator.go:134), as does the bucket mapper. Verified: `///` becomes an empty prefix on the box, but `/` in the scanner, which lists `//`, `moves/`, and `seeds/` instead of the whole bucket. Top-level replicas are omitted while the target remains `ok:true`. **Fix:** match configuration normalization exactly, or reject noncanonical coordinates before scanning. Test repeated slashes, including an all-slash prefix. **Fault family:** agreement between the configured storage namespace and the inventoried namespace. |
| + |
| +3. **P2 — Task 11, §4: failed output writes can publish a partial file with exit 0.** The appends at [scripts/hosts-used-scan-aws.sh:121](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:121) and [scripts/hosts-used-scan-aws.sh:219](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:219) are unchecked; `emit_fail` also ignores its write result. If an append fails, such as from disk exhaustion, execution continues to the final rename and can report success with missing or truncated output. **Fix:** abort on any output-write failure, leave the previous destination intact, and publish only after every append succeeds. Add a write-failure witness. **Fault family:** atomic publication and truthful exit status. |
| + |
| +4. **P2 — Task 11, §§2,4,6: malformed S3 pages are accepted as complete listings.** At [scripts/hosts-used-scan-aws.sh:96](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:96), `strings` silently drops missing or non-string keys; missing `IsTruncated` defaults to false. Verified that `{}` succeeds as an empty terminal page and an entry without `Key` disappears without error. **Fix:** validate the response shape, pagination fields, and every key before accepting a page; emit `ok:false` on malformed responses. Extend the fake with those cases. **Fault family:** rejecting malformed provider responses rather than interpreting them as absence. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r2.md| new file mode 100644 |
| index 000000000..f667d0585 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r2.md |
| @@ -0,0 +1,12 @@ |
| +- R1 P1-1: **Resolved** — checked `find` output is hashed directly; the unchecked sort is gone. |
| +- R1 P1-2: **Partly resolved** — surrounding whitespace and slashes are handled, but internal path normalization still differs. |
| +- R1 P2-3: **Resolved** — failed output appends abort before publication. |
| +- R1 P2-4: **Partly resolved** — malformed response shapes can still pass validation. |
| + |
| +1. **P1 — Task 11, §§2–3: accepted prefixes can still miss replicas.** The scanner accepts `snapshots/../instances` and lists that literal prefix at [hosts-used-scan-aws.sh:126](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:126). The box constructs replica paths with `path.Join` at [activator.go:160](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/activator/activator.go:160), placing those replicas under `instances/`. Verified with the actual scanner functions against a mock containing `instances/old.example.com/db/1`: the scan returned `ok:true, entries:[]`. Activation can therefore complete without marking that hostname. Internal doubled slashes and `.` produce similar mismatches. **Fix:** refuse noncanonical prefixes before scanning, with witnesses for dot segments and doubled internal slashes. **Fault family:** agreement between the configured and inventoried namespace — the same family as R1 P1-2. Stopping rule 2 applies; the recommended cut is an upfront refusal gate. |
| + |
| +2. **P2 — Task 11, §§2,4,6: malformed S3 responses still become successful listings.** At [hosts-used-scan-aws.sh:106](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:106), `.Contents // []` treats `false` as an absent collection. The validator also accepts multiple JSON objects; at line 112, combined `IsTruncated` values differ from literal `true`, ending pagination. Verified that `{"IsTruncated":false,"KeyCount":0,"Contents":false}` succeeds with empty entries, and that a truncated response followed by an empty terminal object succeeds without following its continuation token. **Fix:** require exactly one response object, explicitly validate the collection type, and add both malformed-response witnesses. **Fault family:** rejecting malformed provider responses rather than interpreting them as absence — carried forward from R1 P2-4. |
| + |
| +3. **P3 — Task 11, header contract: the listing is described as sorted.** [hosts-used-scan-aws.sh:30](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:30) still promises sorted output, while lines 161–164 encode `find` traversal order directly. **Fix:** remove “sorted” from the header. **Fault family:** documentation matching the implemented output contract. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r3.md b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r3.md| new file mode 100644 |
| index 000000000..329a746d0 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r3.md |
| @@ -0,0 +1,15 @@ |
| +- R1 P1-1: **Resolved** — unchecked sorting is gone; failed `find` output is refused. |
| +- R1 P1-2: **Resolved** — the reported slash-normalization cases are rejected before AWS calls. |
| +- R1 P2-3: **Resolved** — failed output appends abort before publication. |
| +- R1 P2-4: **Resolved** — malformed S3 pages and keys are rejected. |
| +- R2 P1-1: **Resolved** — dot segments and doubled slashes are rejected. |
| +- R2 P2-2: **Resolved** — false/null collections and multiple JSON objects are rejected. |
| +- R2 P3-3: **Resolved** — the header no longer promises sorted output. |
| + |
| +1. **P1 — Task 11, §§2–3: plain prefixes can still cause activation to mark the wrong hostname.** The gate at [hosts-used-scan-aws.sh:74](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/scripts/hosts-used-scan-aws.sh:74) accepts `moves/archive.example.net`, verified against its actual jq predicate. A replica for `old.example.com` then lives under `moves/archive.example.net/old.example.com/…`. The scanner includes it, but [hostsused_map.go:56](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/hostsused_map.go:56) interprets `moves/` before the configured replica prefix, returning `archive.example.net` with no unmapped entry. Activation can complete without marking the orphaned replica’s actual hostname. `seeds/archive.example.net` has the same failure. **Recommended cut:** refuse replica prefixes nested beneath `moves/` or `seeds/` before any AWS call, with regression witnesses for both. **Fault family:** agreement between the configured storage namespace and the inventoried hostname; the namespace family from rounds 1–2 recurs, so stopping rule 2 applies. |
| + |
| +2. **P1 — Probe-directory change: both census fingerprints remain stale.** The change at [hostsused.go:55](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/layout/hostsused.go:55) changes `HostsFromBoxListing`’s digest from `b3c85cf9…` to `3f114122…`, but [nearest_region_b_census_test.go:54](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/nearest_region_b_census_test.go:54) still pins the former. The Linux source envelope likewise changes from `6061e8c4…` to `2b40e510…`, while [plan14-root-reads-nearest-region-b.tsv:6](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-scan/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv:6) retains the old value. Both mismatches were independently recomputed from source; they trigger the record-write and root-read census checks. The sandbox prevented executing Go tests. **Fix:** update the reviewed record-write fingerprint and add the required reviewed root-envelope proposal and chain entry. **Fault family:** census approval matching the source being merged. |
| + |
| +The P1s have separate causes. Upfront refusal removes the namespace-overlap case. The census failure requires updated review records; cutting the probe-directory change would also remove that mismatch. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R2.md| new file mode 100644 |
| index 000000000..9c15ce273 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R2.md |
| @@ -0,0 +1,121 @@ |
| +# Review brief: nearest-region never-reuse Task 11 (AWS adapter scan), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `nearest-region-scan`, commit c912aa0e (the |
| +round 1 fixes; this brief is the commit after it). |
| +Under review: the diff `origin/main..nearest-region-scan` (base 0a32ce38): |
| +`scripts/hosts-used-scan-aws.sh`, `cmd/console/hostsused_scan_test.go`, |
| +the TestMain hook in `cmd/console/main_test.go`, and one README line. |
| +Authorities (merged on main): `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md` |
| +(Task 11, the "Rework" section: offline `console hosts-used roster/activate` |
| +replaced the live `import`; Task 11's text still says import, ignore that; |
| +Global Constraints), `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md` |
| +§3b, README "The hostname history" and "Completing the history". |
| +Code the script feeds: `internal/provision/hostsused_map.go` (`TargetListing`, |
| +`HostsFromBucketListing`), `internal/layout/hostsused.go` |
| +(`HostsFromBoxListing`), `cmd/console/hostsused.go` (`readListings`, the |
| +roster file) and `internal/console/hostsused_activate.go` (`HostsRoster`, |
| +`Activate`: how it joins `kind:target`, what `ok:false` and unmapped |
| +entries do). |
| + |
| +You are an independent reviewer. Read the script, then the code it feeds, |
| +and check every claim in its header and the commit message against that |
| +code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The script lives in this repo's `scripts/` (the plan's file map), not in |
| + infra. README copy beyond removing "(in infra)" is out of scope. |
| +- Provider-neutral core (plan Global Constraints): S3 and SSM appear only |
| + in the adapter. The roster stays provider-neutral; the AWS coordinates |
| + (instance, region, data dir per box; replica prefix, region per bucket) |
| + come from a separate operator-written `--targets` file. The replica |
| + prefix is required, never defaulted. |
| +- No S3 output location for SSM: the roster never supplies one, so long |
| + output is paged through `get-command-invocation`, or the target fails. |
| +- `instances/_probe` and `.instances/_probe` on every box are reported |
| + unmapped by the Task 6 mapper, so activate would refuse on a real box. |
| + That is the mapper's fault, filed as amadan discussion 437, and out of |
| + scope here. |
| +- Local tests: only the touched package with `-run`. CI runs the rest. |
| + |
| +## What to check |
| + |
| +1. Read-only. The only AWS calls are `s3api list-objects-v2`, |
| + `ssm send-command` (AWS-RunShellScript) and `ssm get-command-invocation`. |
| + The remote script writes nothing on the box. Nothing an operator or a |
| + roster supplies (target names, instance id, region, data_dir, prefix) |
| + can inject shell into the local script or the remote command. |
| +2. No silent miss. Every roster target gets exactly one line. S3: every |
| + page is followed (IsTruncated, NextContinuationToken), keys are never |
| + split or altered (newlines, spaces, unicode), an error on any page |
| + fails the target with no partial entries. SSM: the 24,000-character |
| + output limit cannot truncate a listing without failing the target; |
| + the page reassembly, sha256, length and line-count checks hold; a |
| + listing that changes between pages is retried or failed, never merged; |
| + `find` errors fail the target; paths are relative to the data dir as |
| + `HostsFromBoxListing` expects. |
| +3. Output contract. Each line decodes as `provision.TargetListing`; `kind` |
| + and `target` join to the roster's `bucket:<name>` / `box:<name>` |
| + (including fleet boxes `box:fleet/<f>/<label>`); `prefix` means what |
| + `HostsFromBucketListing` takes it to mean, including the empty prefix |
| + (whole bucket listed). An `ok:false` line is refused by activate. |
| +4. Failure handling. Every failure path (missing coordinates, AWS error, |
| + SSM status other than Success, poll timeout, decode failure) emits |
| + `ok:false` with a usable error; exit codes are as documented; the |
| + output file is never left half-written. |
| +5. Portability for an operator laptop: bash 3.2 (macOS), BSD tools |
| + (`base64 -d`, `shasum`), and the remote side as POSIX sh under SSM. |
| +6. The tests: do they witness pagination on both sides, the S3 and SSM |
| + failures, and that the real `activate` accepts the output? Would they |
| + catch a regression in each of 1-4? Does the fake behave like the real |
| + CLI where it matters (InvocationDoesNotExist, 24,000-character cap)? |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: round 1, `docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md` |
| +(NOT READY: two P1, two P2). The round number counts every earlier |
| +review of this change, under any file name or reviewer. The fixes are |
| +commit c912aa0e; its message maps each finding to its fix and witness. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or |
| +not. Carry every unresolved or partly resolved finding forward at its |
| +current severity, then add new findings. The verdict covers everything |
| +outstanding, earlier rounds included. Name the fault family of every |
| +finding: if a round 2 finding falls in the same family as a round 1 P1 |
| +(completeness of the remote inventory before checksumming; agreement |
| +between the configured and the inventoried namespace), say so. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. You may run |
| +`go test ./cmd/console -run TestHostsUsedScanAWS -count=1` and bash |
| +experiments on the script; never call real AWS. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R3.md| new file mode 100644 |
| index 000000000..048372f3b |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-R3.md |
| @@ -0,0 +1,131 @@ |
| +# Review brief: nearest-region never-reuse Task 11 (AWS adapter scan), round 3 of 3 |
| + |
| +Repo carlos/platform, branch `nearest-region-scan`, commit 2060188d (Paul's |
| +cut after round 2; this brief is the commit after it). |
| +Under review: the diff `origin/main..nearest-region-scan` (base 0a32ce38): |
| +`scripts/hosts-used-scan-aws.sh`, `cmd/console/hostsused_scan_test.go`, |
| +the TestMain hook in `cmd/console/main_test.go`, one README line, and the |
| +probe-directory skip in `internal/layout/hostsused.go` with its test. |
| +Authorities (merged on main): `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md` |
| +(Task 11, the "Rework" section: offline `console hosts-used roster/activate` |
| +replaced the live `import`; Task 11's text still says import, ignore that; |
| +Global Constraints), `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md` |
| +§3b, README "The hostname history" and "Completing the history". |
| +Code the script feeds: `internal/provision/hostsused_map.go` (`TargetListing`, |
| +`HostsFromBucketListing`), `internal/layout/hostsused.go` |
| +(`HostsFromBoxListing`), `cmd/console/hostsused.go` (`readListings`, the |
| +roster file) and `internal/console/hostsused_activate.go` (`HostsRoster`, |
| +`Activate`: how it joins `kind:target`, what `ok:false` and unmapped |
| +entries do). |
| + |
| +You are an independent reviewer. Read the script, then the code it feeds, |
| +and check every claim in its header and the commit message against that |
| +code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The script lives in this repo's `scripts/` (the plan's file map), not in |
| + infra. README copy beyond removing "(in infra)" is out of scope. |
| +- Provider-neutral core (plan Global Constraints): S3 and SSM appear only |
| + in the adapter. The roster stays provider-neutral; the AWS coordinates |
| + (instance, region, data dir per box; replica prefix, region per bucket) |
| + come from a separate operator-written `--targets` file. The replica |
| + prefix is required, never defaulted. |
| +- No S3 output location for SSM: the roster never supplies one, so long |
| + output is paged through `get-command-invocation`, or the target fails. |
| +- Paul's cut after round 2 (amadan discussion 438, option 1): a bucket's |
| + prefix is accepted only in plain form (segments of `[A-Za-z0-9._-]+` |
| + joined by single slashes, no `.` or `..` segment, no empty segment, no |
| + slash at either end, or ""), and anything else stops the whole run |
| + before any AWS call; each S3 reply is checked strictly. Do not propose |
| + normalising prefixes or listing the whole bucket instead. |
| +- Discussion 437 (Paul): the mapper skips the readiness probe's own |
| + directory, `instancectl.ProbeDirName` under `instances/` and |
| + `.instances/`, by exact name only, with anything inside it. |
| +- Local tests: only the touched package with `-run`. CI runs the rest. |
| + |
| +## What to check |
| + |
| +1. Read-only. The only AWS calls are `s3api list-objects-v2`, |
| + `ssm send-command` (AWS-RunShellScript) and `ssm get-command-invocation`. |
| + The remote script writes nothing on the box. Nothing an operator or a |
| + roster supplies (target names, instance id, region, data_dir, prefix) |
| + can inject shell into the local script or the remote command. |
| +2. No silent miss. Every roster target gets exactly one line. S3: every |
| + page is followed (IsTruncated, NextContinuationToken), keys are never |
| + split or altered (newlines, spaces, unicode), an error on any page |
| + fails the target with no partial entries. SSM: the 24,000-character |
| + output limit cannot truncate a listing without failing the target; |
| + the page reassembly, sha256, length and line-count checks hold; a |
| + listing that changes between pages is retried or failed, never merged; |
| + `find` errors fail the target; paths are relative to the data dir as |
| + `HostsFromBoxListing` expects. |
| +3. Output contract. Each line decodes as `provision.TargetListing`; `kind` |
| + and `target` join to the roster's `bucket:<name>` / `box:<name>` |
| + (including fleet boxes `box:fleet/<f>/<label>`); `prefix` means what |
| + `HostsFromBucketListing` takes it to mean, including the empty prefix |
| + (whole bucket listed). An `ok:false` line is refused by activate. |
| +4. Failure handling. Every failure path (missing coordinates, AWS error, |
| + SSM status other than Success, poll timeout, decode failure) emits |
| + `ok:false` with a usable error; exit codes are as documented; the |
| + output file is never left half-written. |
| +5. Portability for an operator laptop: bash 3.2 (macOS), BSD tools |
| + (`base64 -d`, `shasum`), and the remote side as POSIX sh under SSM. |
| +6. The tests: do they witness pagination on both sides, the S3 and SSM |
| + failures, and that the real `activate` accepts the output? Would they |
| + catch a regression in each of 1-4? Does the fake behave like the real |
| + CLI where it matters (InvocationDoesNotExist, 24,000-character cap)? |
| + |
| +## Round 3 (the last allowed) |
| + |
| +Earlier rounds: round 1 `docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r1.md` |
| +(NOT READY: two P1, two P2; fixed in c912aa0e) and round 2 |
| +`docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r2.md` |
| +(NOT READY: one P1, one P2, one P3). Round 2 hit stopping rule 2 in two |
| +families (the configured vs inventoried namespace; malformed provider |
| +responses read as absence), and Paul chose the cut above. Commit 2060188d |
| +applies it; its message maps each change to its witness. |
| + |
| +First give one line per P1 and P2 from rounds 1 and 2: resolved, partly, |
| +or not. Carry every unresolved or partly resolved finding forward at its |
| +current severity, then add new findings. The verdict covers everything |
| +outstanding. Also check the probe-directory skip: that it skips exactly |
| +what the probe creates (internal/host/bootstrap.go, internal/instanceexec/probe.go) |
| +and nothing a host's data could be in. This is round 3: a NOT READY must |
| +also say whether its P1s share one cause, and whether refusing the case |
| +up front or cutting the feature would remove them. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. You may run |
| +`go test ./cmd/console -run TestHostsUsedScanAWS -count=1` and bash |
| +experiments on the script; never call real AWS. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-confirm.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-confirm.md| new file mode 100644 |
| index 000000000..ac739424e |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan-confirm.md |
| @@ -0,0 +1,57 @@ |
| +# Review brief: nearest-region-scan, narrow confirmation after round 3 (not a fourth round) |
| + |
| +Repo carlos/platform, branch `nearest-region-scan`, commit 0b634d7b (the |
| +fixes; this brief is the commit after it). Round 3's findings: |
| +`docs/superpowers/reviews/CODEX-FINDINGS-nearest-region-scan-r3.md` (two |
| +P1s). Paul approved fixing exactly those two and asked for this narrow |
| +confirmation instead of a fourth round. |
| + |
| +You are an independent reviewer (Astra, the other model family from the |
| +Claude author). Two questions, nothing else. |
| + |
| +## Part A: confirmation |
| + |
| +Verify these two round-3 P1s are fixed and the fix introduces no new P1; |
| +findings outside that scope are out of scope. |
| + |
| +1. Round 3 P1-1: a plain prefix whose first segment is `moves` or `seeds` |
| + must be refused before any AWS call (`scripts/hosts-used-scan-aws.sh`, |
| + the up-front prefix check; witnesses in |
| + `cmd/console/hostsused_scan_test.go`, |
| + `TestHostsUsedScanAWSPrefixInPlainFormOnly`). |
| +2. Round 3 P1-2: the census must match the source. |
| + `TestPlan9B8RecordWriteCensus` (new layer |
| + `internal/provision/nearest_region_scan_census_test.go`) and |
| + `TestPlan14RootReadCensus` (overlay |
| + `internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv` |
| + and its chain line) must pass at this commit. |
| + |
| +Answer each: fixed, partly, or not, with the evidence (file:line). Report |
| +a P1 only if it is in that scope: the fix does not work, a test fails, or |
| +the fix itself opens a new way to miss a hostname. Anything else is out |
| +of scope; do not report it. |
| + |
| +## Part B: census approval |
| + |
| +The census card is `docs/superpowers/notes/census-proposal-nearest-region-scan.md` |
| +(CLAIMS beside it: `census-nearest-region-scan-claims.md`). One envelope |
| +is re-pinned, `internal/layout`; no root-read unit changed. Read every |
| +changed function in that package in `git diff origin/main...HEAD -- internal/layout` |
| +and what it reaches, then give one verdict for the envelope, citing the |
| +lines you read: **approve**, or **reject** if the change lets root open, |
| +run, query or follow anything it did not before from a path or input a |
| +tenant, an app or a box agent can create, write or name; if it weakens a |
| +check, refusal, validation, argument or environment root relies on; or if |
| +the diff cannot settle either. You decide; nothing goes to Paul (#280). |
| + |
| +## Output |
| + |
| +Part A: one line per P1 (fixed, partly, not), then any in-scope P1, then |
| +exactly one of **CONFIRMED** (both fixed, no new in-scope P1) or **NOT |
| +CONFIRMED** (list the P1s). Part B: **APPROVE** or **REJECT** for |
| +`internal/layout`, with the lines read. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. You may run `go test ./internal/provision -run 'TestPlan9B8RecordWriteCensus|TestPlan14RootReadCensus$' -count=1` |
| +and `go test ./cmd/console -run TestHostsUsedScanAWS -count=1`; never call |
| +real AWS. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan.md| new file mode 100644 |
| index 000000000..88ee242e1 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-nearest-region-scan.md |
| @@ -0,0 +1,106 @@ |
| +# Review brief: nearest-region never-reuse Task 11 (AWS adapter scan), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `nearest-region-scan`, commit e45b71d7 (the |
| +brief itself is the commit after it). |
| +Under review: the diff `origin/main..nearest-region-scan` (base 0a32ce38): |
| +`scripts/hosts-used-scan-aws.sh`, `cmd/console/hostsused_scan_test.go`, |
| +the TestMain hook in `cmd/console/main_test.go`, and one README line. |
| +Authorities (merged on main): `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md` |
| +(Task 11, the "Rework" section: offline `console hosts-used roster/activate` |
| +replaced the live `import`; Task 11's text still says import, ignore that; |
| +Global Constraints), `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md` |
| +§3b, README "The hostname history" and "Completing the history". |
| +Code the script feeds: `internal/provision/hostsused_map.go` (`TargetListing`, |
| +`HostsFromBucketListing`), `internal/layout/hostsused.go` |
| +(`HostsFromBoxListing`), `cmd/console/hostsused.go` (`readListings`, the |
| +roster file) and `internal/console/hostsused_activate.go` (`HostsRoster`, |
| +`Activate`: how it joins `kind:target`, what `ok:false` and unmapped |
| +entries do). |
| + |
| +You are an independent reviewer. Read the script, then the code it feeds, |
| +and check every claim in its header and the commit message against that |
| +code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The script lives in this repo's `scripts/` (the plan's file map), not in |
| + infra. README copy beyond removing "(in infra)" is out of scope. |
| +- Provider-neutral core (plan Global Constraints): S3 and SSM appear only |
| + in the adapter. The roster stays provider-neutral; the AWS coordinates |
| + (instance, region, data dir per box; replica prefix, region per bucket) |
| + come from a separate operator-written `--targets` file. The replica |
| + prefix is required, never defaulted. |
| +- No S3 output location for SSM: the roster never supplies one, so long |
| + output is paged through `get-command-invocation`, or the target fails. |
| +- `instances/_probe` and `.instances/_probe` on every box are reported |
| + unmapped by the Task 6 mapper, so activate would refuse on a real box. |
| + That is the mapper's fault, filed as amadan discussion 437, and out of |
| + scope here. |
| +- Local tests: only the touched package with `-run`. CI runs the rest. |
| + |
| +## What to check |
| + |
| +1. Read-only. The only AWS calls are `s3api list-objects-v2`, |
| + `ssm send-command` (AWS-RunShellScript) and `ssm get-command-invocation`. |
| + The remote script writes nothing on the box. Nothing an operator or a |
| + roster supplies (target names, instance id, region, data_dir, prefix) |
| + can inject shell into the local script or the remote command. |
| +2. No silent miss. Every roster target gets exactly one line. S3: every |
| + page is followed (IsTruncated, NextContinuationToken), keys are never |
| + split or altered (newlines, spaces, unicode), an error on any page |
| + fails the target with no partial entries. SSM: the 24,000-character |
| + output limit cannot truncate a listing without failing the target; |
| + the page reassembly, sha256, length and line-count checks hold; a |
| + listing that changes between pages is retried or failed, never merged; |
| + `find` errors fail the target; paths are relative to the data dir as |
| + `HostsFromBoxListing` expects. |
| +3. Output contract. Each line decodes as `provision.TargetListing`; `kind` |
| + and `target` join to the roster's `bucket:<name>` / `box:<name>` |
| + (including fleet boxes `box:fleet/<f>/<label>`); `prefix` means what |
| + `HostsFromBucketListing` takes it to mean, including the empty prefix |
| + (whole bucket listed). An `ok:false` line is refused by activate. |
| +4. Failure handling. Every failure path (missing coordinates, AWS error, |
| + SSM status other than Success, poll timeout, decode failure) emits |
| + `ok:false` with a usable error; exit codes are as documented; the |
| + output file is never left half-written. |
| +5. Portability for an operator laptop: bash 3.2 (macOS), BSD tools |
| + (`base64 -d`, `shasum`), and the remote side as POSIX sh under SSM. |
| +6. The tests: do they witness pagination on both sides, the S3 and SSM |
| + failures, and that the real `activate` accepts the output? Would they |
| + catch a regression in each of 1-4? Does the fake behave like the real |
| + CLI where it matters (InvocationDoesNotExist, 24,000-character cap)? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. You may run |
| +`go test ./cmd/console -run TestHostsUsedScanAWS -count=1` and bash |
| +experiments on the script; never call real AWS. |
diff --git a/internal/layout/hostsused.go b/internal/layout/hostsused.go| index 538654666..034635933 100644 |
| --- a/internal/layout/hostsused.go |
| +++ b/internal/layout/hostsused.go |
| @@ -5,6 +5,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| @@ -22,7 +23,9 @@ import ( |
| // is unmapped: nothing is normalised. |
| // - instances/<id>/ and .instances/<id>/ map to <id>, or for a hashed id |
| // ("_" + prefix + hash, provision.InstanceID) to the full host a file |
| -// inside names; a hashed id with none is unmapped. |
| +// inside names; a hashed id with none is unmapped. The readiness |
| +// probe's own directory (instancectl.ProbeDirName) is the box's and |
| +// skipped, by that exact name only. |
| // - .offline-moves/<host>/ maps to <host>, or is unmapped. |
| // - Any other hidden entry (.parked/<hash>/<host>/, .moves/, .hostexec/ |
| // and the like) marks every host-like segment of its path, after the |
| @@ -46,6 +49,12 @@ func HostsFromBoxListing(paths []string) (hosts, unmapped []string) { |
| continue |
| } |
| id := segs[1] |
| + // The readiness probe's own directory (made at bootstrap, |
| + // internal/host/bootstrap.go), and whatever the probe leaves in |
| + // it, is the box's. Only that exact name: no host can have it. |
| + if id == instancectl.ProbeDirName { |
| + continue |
| + } |
| if strings.HasPrefix(id, "_") { |
| dir := segs[0] + "/" + id |
| if _, seen := hashed[dir]; !seen { |
diff --git a/internal/layout/hostsused_test.go b/internal/layout/hostsused_test.go| index 0023ef935..73d95e96a 100644 |
| --- a/internal/layout/hostsused_test.go |
| +++ b/internal/layout/hostsused_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "strings" |
| "testing" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| @@ -143,3 +144,25 @@ func TestHashedInstanceDirWithoutHostIsUnmapped(t *testing.T) { |
| t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| } |
| } |
| + |
| +// The readiness probe's own instance directory (instancectl.ProbeDirName, |
| +// made at bootstrap under .instances/ and seen as instances/ on a box) is |
| +// the box's, not a host's: skipped with whatever the probe left in it. Only |
| +// that exact name is skipped; any other "_" id is still a hashed id, and |
| +// unmapped without a host-named file inside (discussion 437). |
| +func TestBoxListingSkipsTheProbeDir(t *testing.T) { |
| + hosts, unmapped := HostsFromBoxListing([]string{ |
| + "instances/_probe", ".instances/_probe", "instances/_probe/link", ".instances/_probe/probe.example.com.db", |
| + "./instances/_probe/", |
| + }) |
| + if len(hosts) != 0 || len(unmapped) != 0 { |
| + t.Fatalf("the probe dir maps to %q, unmapped %q; want nothing", hosts, unmapped) |
| + } |
| + _, unmapped = HostsFromBoxListing([]string{"instances/_probex", ".instances/_Probe", "instances/_probe.example.com"}) |
| + if want := []string{".instances/_Probe", "instances/_probe.example.com", "instances/_probex"}; !reflect.DeepEqual(unmapped, want) { |
| + t.Fatalf("near-probe names: unmapped %q, want %q", unmapped, want) |
| + } |
| + if instancectl.ProbeDirName != "_probe" { |
| + t.Fatalf("ProbeDirName = %q: the dev listings and this test assume _probe", instancectl.ProbeDirName) |
| + } |
| +} |
diff --git a/internal/provision/nearest_region_scan_census_test.go b/internal/provision/nearest_region_scan_census_test.go| new file mode 100644 |
| index 000000000..c0df0e9cc |
| --- /dev/null |
| +++ b/internal/provision/nearest_region_scan_census_test.go |
| @@ -0,0 +1,29 @@ |
| +package provision |
| + |
| +// Record-write census entry for nearest-region-scan (amadan #437: the box |
| +// listing mapper skips the readiness probe's own directory), layered on |
| +// operatorPagesWriteCensusInventory (main's newest at 81db4870). |
| +// Reviewed by the branch author and the cross-model reviewer (Astra) with |
| +// the branch. No record write is added, moved or reclassified: |
| +// - layout.HostsFromBoxListing keeps its one key site, the "instances" |
| +// directory literal. Its body now skips instances/<id> and |
| +// .instances/<id> when id is exactly instancectl.ProbeDirName, with |
| +// anything below them. It is a pure mapping and writes nothing. |
| +func nearestRegionScanWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), operatorPagesWriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/layout/hostsused.go", "HostsFromBoxListing", "key-site", "lit:instances", "3f1141229de70236eaa9fd97198edfd139ff7f5ffa6d6c6236bdfe7cbc2daa73"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("nearest-region-scan replacement of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plans6b_census_test.go b/internal/provision/plans6b_census_test.go| index 3a60ed4e2..22eab7a42 100644 |
| --- a/internal/provision/plans6b_census_test.go |
| +++ b/internal/provision/plans6b_census_test.go |
| @@ -2,8 +2,8 @@ package provision |
| // Record-write census entries for branch plans-6b-checkout-flow (checkout, |
| // team plans and the billing page), layered on |
| -// operatorPagesWriteCensusInventory (main's newest at the merge |
| -// of 81db4870). No record write is added, moved or reclassified: 6b's billing |
| +// nearestRegionScanWriteCensusInventory (main's newest at the merge |
| +// of 3800b8bb). No record write is added, moved or reclassified: 6b's billing |
| // state lives in the console's own SQLite tables, never in a record. |
| // - Server.registerCLIRoutes: registers POST /api/cli/billing/house |
| // (apibillinghouse.go). Same "instances" and "sidecars" literals: still |
| @@ -12,7 +12,7 @@ package provision |
| // confirm, checkout, continue, done, change, renewal, seats and portal |
| // routes. Same "instances" literal: still key-site. |
| func plans6bWriteCensusInventory() []censusEntry { |
| - entries := append([]censusEntry(nil), operatorPagesWriteCensusInventory()...) |
| + entries := append([]censusEntry(nil), nearestRegionScanWriteCensusInventory()...) |
| replacements := []censusEntry{ |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "c5994862b070edba9bdf909aa2b4e4249112939d99c1caacea8c8831cd50959a"}, |
| {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "05185bea2dd3952d16cbb6041b8c16d1ddd41b5752e10f923e40c5f168e2a341"}, |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 5d2c07682..cbde46058 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -13,4 +13,5 @@ plan14-root-reads-ha-p1a-433.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d9 |
| plan14-root-reads-rollup-tenant-tags.tsv f8acbc0dd8828636e3f73d9afd0e539d3dfd1346e0232d91903c33d6eb27d820 |
| plan14-root-reads-alias-wake-338.tsv deeddee1bf22a18562acda97cc34c6d73ee0dff1825100c73fa0be4c6a3f3e7b |
| plan14-root-reads-analytics-onramp.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7 |
| +plan14-root-reads-nearest-region-scan.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7 |
| plan14-root-reads-plans-6b-checkout-flow.tsv f5afdacd495705841fcc8441eaefe0efb9db7056de281bb06d1714960a5575b7 |
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv| new file mode 100644 |
| index 000000000..2412fa7e4 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-nearest-region-scan.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay nearest-region-scan, written by census-propose (#369). census-ruling-nearest-region-scan, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-scan.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/layout 2b40e510234739bf231719b18c73ddc6b2112d96b203ad1191d62dd62612c1c1 |
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh| new file mode 100755 |
| index 000000000..602a08f19 |
| --- /dev/null |
| +++ b/scripts/hosts-used-scan-aws.sh |
| @@ -0,0 +1,293 @@ |
| +#!/usr/bin/env bash |
| +# scripts/hosts-used-scan-aws.sh --profile <aws-profile> --targets <coords.json> <roster.json> <scan.jsonl> |
| +# |
| +# The hostname history's AWS adapter (nearest-region never-reuse plan Task |
| +# 11, spec §3b): scans every target on a `console hosts-used roster` file, |
| +# read-only, and writes one TargetListing JSON line per target |
| +# (internal/provision/hostsused_map.go) for `console hosts-used activate |
| +# -roster <roster.json> -listings <scan.jsonl>`. |
| +# |
| +# bucket:<name> every current object key under the replica prefix, |
| +# 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. |
| +# |
| +# The roster is provider-neutral and names targets only, so their AWS |
| +# coordinates come from the operator's coords file, keyed by roster target: |
| +# |
| +# {"box:<name>": {"instance": "i-...", "region": "eu-west-1", "data_dir": "/data"}, |
| +# "bucket:<name>": {"prefix": "instances", "region": "eu-west-1"}} |
| +# |
| +# data_dir defaults to /data. prefix is required: it is the boxes' |
| +# CARLOS_HIBERNATE_PREFIX as the box resolves it ("" puts replicas at the |
| +# bucket's top level, and then the whole bucket is listed). A wrong prefix |
| +# misses that bucket's replicas, so it is never defaulted, and it is taken |
| +# only in plain form: segments of [A-Za-z0-9._-]+ joined by single slashes, |
| +# none of them "." or "..", or "". Its first segment may not be moves or |
| +# seeds: the mapper reads those roots before the replica prefix, so a |
| +# replica under them would be taken for another host's move or seed data. |
| +# Any other prefix stops the whole run before any AWS call. region is |
| +# 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 |
| +# reassembled listing must match all three. Nothing is truncated silently. |
| +# |
| +# 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. |
| +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; } |
| +profile="" coords="" |
| +while [ $# -gt 0 ]; do |
| + case "$1" in |
| + --profile) [ $# -ge 2 ] || usage; profile="$2"; shift 2 ;; |
| + --targets) [ $# -ge 2 ] || usage; coords="$2"; shift 2 ;; |
| + --) shift; break ;; |
| + -*) usage ;; |
| + *) break ;; |
| + esac |
| +done |
| +[ $# -eq 2 ] && [ -n "$profile" ] && [ -n "$coords" ] || usage |
| +roster="$1" out="$2" |
| +poll="${HOSTS_SCAN_POLL:-2}" |
| +wait_s="${HOSTS_SCAN_WAIT:-300}" |
| +page="${HOSTS_SCAN_PAGE:-20000}" |
| +case "$page" in ''|*[!0-9]*) echo "HOSTS_SCAN_PAGE must be a number" >&2; exit 2 ;; esac |
| +# 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; } |
| +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")" || { |
| + echo "hosts-used-scan: $roster is not a roster: it needs a targets array of strings" >&2; exit 2; } |
| +jq -e 'type == "object"' "$coords" >/dev/null 2>&1 || { echo "hosts-used-scan: $coords is not a JSON object" >&2; exit 2; } |
| +# Every bucket's prefix in plain form, checked on the JSON value itself (a |
| +# shell capture would drop a trailing newline), before anything is listed. |
| +notplain="$(jq -rn --slurpfile r "$roster" --slurpfile c "$coords" ' |
| + def plain: . == "" or (split("/") | all(. != "" and . != "." and . != ".." |
| + and (explode | all(. as $x | ($x >= 48 and $x <= 57) or ($x >= 65 and $x <= 90) or ($x >= 97 and $x <= 122) |
| + or $x == 45 or $x == 46 or $x == 95)))); |
| + $r[0].targets[] | select(startswith("bucket:")) as $t | $c[0][$t] |
| + | select(type == "object" and has("prefix")) | .prefix |
| + | if type != "string" or (plain|not) then "plain\t" + $t |
| + elif (split("/")[0]) == "moves" or (split("/")[0]) == "seeds" then "root\t" + $t |
| + else empty end')" || { |
| + echo "hosts-used-scan: could not check the prefixes in $coords" >&2; exit 2; } |
| +if [ -n "$notplain" ]; then |
| + while IFS=$'\t' read -r why t; do |
| + if [ "$why" = root ]; then |
| + echo "hosts-used-scan: the prefix for $t in $coords starts with moves or seeds, where the platform keeps move and seed data, so its replicas cannot be told apart. a box with such a CARLOS_HIBERNATE_PREFIX cannot be scanned" >&2 |
| + continue |
| + fi |
| + echo "hosts-used-scan: the prefix for $t in $coords is not in plain form. write it as the box resolves CARLOS_HIBERNATE_PREFIX: segments of letters, digits, '.', '_' and '-' joined by single slashes, with no '.' or '..' segment and no slash at either end, or \"\" for the top level" >&2 |
| + done <<<"$notplain" |
| + exit 2 |
| +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 |
| + |
| +awsp() { aws --profile "$profile" "$@" </dev/null; } |
| +sha256() { if command -v sha256sum >/dev/null; then sha256sum; else shasum -a 256; fi | cut -d' ' -f1; } |
| +# oneline: an AWS error's text, on one line, short enough for a report. |
| +oneline() { tr '\n' ' ' | sed 's/ */ /g; s/^ //; s/ $//' | cut -c1-400; } |
| + |
| +# put <line>: append one line to the output, or stop: a scan whose output |
| +# could not be written in full is never published. |
| +put() { printf '%s\n' "$1" >>"$part" || { echo "hosts-used-scan: could not write $part" >&2; exit 2; }; } |
| +fail=0 |
| +emit_fail() { # <target name> <kind> <error> |
| + local line |
| + line="$(jq -nc --arg t "$1" --arg k "$2" --arg e "$3" '{target:$t,kind:$k,ok:false,error:$e,entries:[]}')" || { |
| + echo "hosts-used-scan: could not report $2:$1" >&2; exit 2; } |
| + put "$line" |
| + echo "FAIL $2:$1: $3" >&2 |
| + fail=1 |
| +} |
| +coord() { # <roster target> <field>: the field, or exit 1 when absent |
| + jq -er --arg t "$1" --arg f "$2" '.[$t] | if type == "object" and has($f) and (.[$f]|type) == "string" then .[$f] else error("missing") end' "$coords" 2>/dev/null |
| +} |
| + |
| +# list_prefix <bucket> <region> <prefix>: append every page's keys, one JSON |
| +# array per line, to $work/keys; on failure set $err and return 1. |
| +list_prefix() { |
| + local b="$1" r="$2" p="$3" token="" resp pg trunc n=0 |
| + while :; do |
| + set -- s3api list-objects-v2 --bucket "$b" --prefix "$p" --max-keys 1000 --no-paginate --output json |
| + [ -n "$r" ] && set -- "$@" --region "$r" |
| + [ -n "$token" ] && set -- "$@" --continuation-token "$token" |
| + resp="$(awsp "$@" 2>"$work/err")" || { err="list s3://$b/$p: $(oneline <"$work/err")"; return 1; } |
| + n=$((n + 1)) |
| + # A reply is a page only when it is exactly one JSON object whose |
| + # Contents is absent or an array of objects, each with a non-empty |
| + # string Key under the prefix asked for; whose KeyCount counts them; |
| + # and whose IsTruncated is a boolean, true with a non-empty |
| + # NextContinuationToken and false with none. Anything else fails the |
| + # bucket, and never reads as no keys or as the last page. |
| + pg="$(jq -cse --arg p "$p" ' |
| + if length == 1 and (.[0]|type) == "object" then .[0] else error("not one object") end |
| + | if has("Contents") and ((.Contents|type) != "array" |
| + or (all(.Contents[]; type == "object" and (.Key|type) == "string" and .Key != "" and (.Key|startswith($p))) | not)) |
| + then error("contents") else . end |
| + | (if has("Contents") then .Contents else [] end) as $c |
| + | if (.IsTruncated|type) != "boolean" then error("truncated") else . end |
| + | if (.KeyCount|type) != "number" or .KeyCount != ($c|length) then error("count") else . end |
| + | if .IsTruncated then (if (.NextContinuationToken|type) == "string" and .NextContinuationToken != "" then . else error("token") end) |
| + elif has("NextContinuationToken") and .NextContinuationToken != null then error("token") else . end |
| + | [[$c[].Key], .IsTruncated, (.NextContinuationToken // "")]' <<<"$resp" 2>/dev/null)" || { |
| + err="list s3://$b/$p: page $n is not a well-formed listing"; return 1; } |
| + jq -c '.[0]' <<<"$pg" >>"$work/keys" || { err="list s3://$b/$p: could not keep page $n"; return 1; } |
| + trunc="$(jq -r '.[1]' <<<"$pg")" |
| + [ "$trunc" = true ] || return 0 |
| + token="$(jq -r '.[2]' <<<"$pg")" |
| + done |
| +} |
| + |
| +scan_bucket() { # <roster target> <bucket> |
| + local t="$1" b="$2" prefix region p line |
| + prefix="$(coord "$t" prefix)" || { emit_fail "$b" bucket "no prefix for $t in $coords"; return; } |
| + region="$(coord "$t" region)" || region="" |
| + # The prefix is in plain form: checked for every bucket before the scan. |
| + : >"$work/keys" |
| + err="" |
| + if [ -z "$prefix" ]; then |
| + list_prefix "$b" "$region" "" || { emit_fail "$b" bucket "$err"; return; } |
| + else |
| + for p in "$prefix/" moves/ seeds/; do |
| + list_prefix "$b" "$region" "$p" || { emit_fail "$b" bucket "$err"; return; } |
| + done |
| + fi |
| + line="$(jq -cs --arg t "$b" --arg p "$prefix" '{target:$t,kind:"bucket",prefix:$p,ok:true,entries:(add // [] | unique)}' "$work/keys")" || { |
| + emit_fail "$b" bucket "could not assemble the listing"; return; } |
| + put "$line" |
| + 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() { |
| + cat <<EOF |
| +export LC_ALL=C |
| +cd '$1' || { echo "cannot enter $1" >&2; exit 3; } |
| +nl=' |
| +' |
| +bad=\$(find . -maxdepth 3 -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; } |
| +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 |
| +EOF |
| +} |
| + |
| +# ssm_run <region> <instance> <script>: run it and leave its stdout in |
| +# $work/stdout; on failure set $err and return 1. |
| +ssm_run() { |
| + local r="$1" i="$2" id deadline resp status |
| + id="$(awsp ssm send-command --region "$r" --instance-ids "$i" --document-name AWS-RunShellScript \ |
| + --comment "hosts-used scan: read-only find" --timeout-seconds 60 \ |
| + --parameters "$(jq -nc --arg c "$3" '{commands:[$c],executionTimeout:["120"]}')" \ |
| + --query Command.CommandId --output text 2>"$work/err")" || { err="ssm send-command to $i: $(oneline <"$work/err")"; return 1; } |
| + [ -n "$id" ] && [ "$id" != None ] || { err="ssm send-command to $i returned no command id"; return 1; } |
| + deadline=$((SECONDS + wait_s)) |
| + while :; do |
| + sleep "$poll" |
| + if resp="$(awsp ssm get-command-invocation --region "$r" --command-id "$id" --instance-id "$i" --output json 2>"$work/err")"; then |
| + status="$(jq -r '.Status // empty' <<<"$resp")" |
| + case "$status" in |
| + Success) |
| + jq -r '.StandardOutputContent // empty' <<<"$resp" >"$work/stdout"; return 0 ;; |
| + Pending|InProgress|Delayed|"") ;; |
| + *) |
| + err="command $id on $i: $status (exit $(jq -r '.ResponseCode // "?"' <<<"$resp")): $(jq -r '.StandardErrorContent // empty' <<<"$resp" | oneline)" |
| + return 1 ;; |
| + esac |
| + elif ! grep -q InvocationDoesNotExist "$work/err"; then |
| + err="ssm get-command-invocation $id on $i: $(oneline <"$work/err")"; return 1 |
| + fi |
| + [ "$SECONDS" -lt "$deadline" ] || { err="command $id on $i: no result after ${wait_s}s"; return 1; } |
| + 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() { |
| + 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 |
| + 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 |
| + if [ -z "$header" ]; then |
| + 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 |
| + fi |
| + got="$(sed -n '2p' "$work/stdout" | tr -d '\r\n')" |
| + want=$((total - first + 1)); [ "$want" -gt "$page" ] && want="$page" |
| + [ "${#got}" -eq "$want" ] || { err="$i: page at $first has ${#got} characters, want $want: the output was cut short"; return 1; } |
| + printf '%s' "$got" >>"$work/blob" |
| + first=$((first + page)) |
| + done |
| + base64 -d <"$work/blob" 2>/dev/null | gunzip -c >"$work/listing" 2>/dev/null || { err="$i: the listing does not decode"; return 1; } |
| + [ "$(sha256 <"$work/listing")" = "$(cut -d' ' -f3 <<<"$header")" ] || { err="$i: the listing's checksum does not match"; return 1; } |
| + [ "$(wc -l <"$work/listing" | tr -d ' ')" = "$(cut -d' ' -f5 <<<"$header")" ] || { err="$i: the listing's line count does not match"; return 1; } |
| +} |
| + |
| +scan_box() { # <roster target> <box> |
| + local t="$1" x="$2" inst region dir try rc line |
| + inst="$(coord "$t" instance)" || { emit_fail "$x" box "no instance for $t in $coords"; return; } |
| + region="$(coord "$t" region)" || { emit_fail "$x" box "no region for $t in $coords"; return; } |
| + dir="$(coord "$t" data_dir)" || dir=/data |
| + [[ "$inst" =~ ^m?i-[0-9a-f]+$ ]] || { emit_fail "$x" box "instance $inst is not an instance id"; return; } |
| + [[ "$region" =~ ^[a-z0-9-]+$ ]] || { emit_fail "$x" box "region $region is not a region"; return; } |
| + [[ "$dir" =~ ^/[A-Za-z0-9._/-]*$ ]] || { emit_fail "$x" box "data_dir $dir is not a plain absolute path"; return; } |
| + err="" |
| + for try in 1 2 3; do |
| + box_listing "$region" "$inst" "$dir"; rc=$? |
| + [ "$rc" -eq 2 ] || break |
| + done |
| + [ "$rc" -eq 0 ] || { emit_fail "$x" box "$err"; return; } |
| + # find's output names the directory itself and never an empty path; |
| + # anything else is not a listing of it. |
| + grep -qx '\.' "$work/listing" && ! grep -q '^$' "$work/listing" || { emit_fail "$x" box "$inst: the listing under $dir is not find's output"; return; } |
| + line="$(jq -Rnc --arg t "$x" '{target:$t,kind:"box",ok:true,entries:[inputs | select(. != ".") | sub("^\\./"; "")]}' <"$work/listing")" || { |
| + emit_fail "$x" box "could not assemble the listing"; return; } |
| + put "$line" |
| + echo "ok box:$x: $(jq '.entries|length' <<<"$line") paths" >&2 |
| +} |
| + |
| +while IFS= read -r t; do |
| + [ -n "$t" ] || continue |
| + case "$t" in |
| + bucket:*) scan_bucket "$t" "${t#bucket:}" ;; |
| + box:*) scan_box "$t" "${t#box:}" ;; |
| + *) emit_fail "${t#*:}" "${t%%:*}" "the scan does not know this kind of target" ;; |
| + esac |
| +done <<<"$targets" |
| +mv "$part" "$out" || exit 2 |
| +exit "$fail" |