carlos / platform Public

Tasks 8, 9, 10: tripwire and invalidation; apps place cut; accounts migrate floor and resurrection cut

Task 8: at a start with the history active, a record with no mark that
may hold data (or does not decode) invalidates it (D2 page); a store
error retries in the background, never invalidating by itself. POST
/api/cli/system/hosts-used/invalidate (operators; C12 when not active;
D4). carlos system hosts-used invalidate (B9); the usage block (E1-E9).
Task 9: placeAppTarget answers S3 first once the history is active or
invalidated, before the registry or any write; placement at app creation
stays.
Task 10: carlos accounts migrate reads the floor and refuses below it
(B10) before any write; before the window it marks a data-kind record's
hostname before copying it; from the window on it never creates a
data-kind record at an absent destination (S6).

Astra findings committed unedited: Task 5 r3 (NOT READY; budget spent),
Task 6 r2 (NOT READY; stopping rule 2), Task 7 r1 (NOT READY).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e457d865d304082a6d1a56eaf02c6e580c6460af parent 7e50272
18 files changed, +780 −5
  • accounts.go +9 −0
  • accounts_hostsused.go +132 −0
  • accounts_record_sequence_test.go +154 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r3.md +35 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r2.md +27 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task7-r1.md +17 −0
  • internal/console/authcli.go +2 −0
  • internal/console/claim_invariant_fixtures_test.go +6 −0
  • internal/console/fleets.go +8 −0
  • internal/console/fleets_place_cut_test.go +70 −0
  • internal/console/hostsused.go +10 −0
  • internal/console/hostsused_tripwire.go +151 −0
  • internal/console/hostsused_tripwire_test.go +137 −0
  • internal/console/svcroutes_test.go +3 −2
  • internal/console/testdata/claim-routes.txt +1 −0
  • system.go +8 −2
  • system_hostsused.go +3 −1
  • system_hostsused_test.go +7 −0

CI cancelled — superseded by a newer push — run details

diff --git a/accounts.go b/accounts.go
index acc557932..02e1a2feb 100644
--- a/accounts.go
+++ b/accounts.go
@@ -363,6 +363,12 @@ func runAccountsMigrate(args []string) {
if err := validateMigrationRecords(ctx, store, plan); err != nil {
log.Fatal(err)
}
+ // The hostname history (accounts_hostsused.go): the floor before any
+ // write, and the mode every record copy is checked against.
+ history, err := readMigrationHistoryNow(ctx, store)
+ if err != nil {
+ log.Fatal(err)
+ }
if len(plan) == 0 {
mutedf(os.Stdout, "nothing under %s — nothing to copy\n", release.AppPrefix(srcAcct, *app))
}
@@ -427,6 +433,9 @@ func runAccountsMigrate(args []string) {
}
continue
}
+ if err := history.beforeRecord(ctx, store, c.to, body); err != nil {
+ log.Fatal(err)
+ }
if _, err := putMigrationObject(ctx, store, c.to, body); err != nil {
cur, _, gerr := store.Get(ctx, c.to)
if gerr != nil {
diff --git a/accounts_hostsused.go b/accounts_hostsused.go
new file mode 100644
index 000000000..b9ccdc7a4
--- /dev/null
+++ b/accounts_hostsused.go
@@ -0,0 +1,132 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "runtime/debug"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// The hostname history at carlos accounts migrate (nearest-region
+// never-reuse spec §2 and §4, plan Task 10). The verb copies an app's
+// records under another account, so it is a record writer: before the
+// history is active a data-kind record's copy marks its hostname first;
+// once the window has opened it never creates a data-kind record at a
+// destination that has none, because a re-run after the destination was
+// deleted would bring a deleted hostname back over its old data (S6). And
+// a carlos below the history's floor refuses before writing anything.
+
+// migrationHistory is what the verb read before its first write.
+type migrationHistory struct {
+ mode string
+}
+
+// readMigrationHistory reads the history's mode and floor once, and refuses
+// a build below the floor (B10). A build is at or above it when both are
+// release tags and this one is not older, or when it is the floor's own
+// commit; anything else (a dev build, a bare commit) cannot show it is, and
+// refuses.
+func readMigrationHistory(ctx context.Context, store release.Store, build, commit string) (*migrationHistory, error) {
+ floor, _, err := provision.ReadHostsFloor(ctx, store)
+ if err != nil {
+ return nil, fmt.Errorf("accounts migrate: read the hostname history's floor: %w", err)
+ }
+ if floor != nil && !buildMeetsFloor(*floor, build, commit) {
+ return nil, errors.New("this carlos is older than the hostname history's floor, " + floor.Version + ". update carlos, then run it again.")
+ }
+ mode, _, err := provision.ReadHostsMode(ctx, store)
+ if err != nil {
+ return nil, fmt.Errorf("accounts migrate: read the hostname history's mode: %w", err)
+ }
+ return &migrationHistory{mode: mode}, nil
+}
+
+func buildMeetsFloor(floor provision.HostsFloor, build, commit string) bool {
+ if floor.Commit != "" && commit == floor.Commit {
+ return true
+ }
+ return releaseBuild(build) && releaseBuild(floor.Version) && !newerVersion(floor.Version, build)
+}
+
+// thisBuildCommit is the commit this binary was built from, when it says.
+func thisBuildCommit() string {
+ if bi, ok := debug.ReadBuildInfo(); ok {
+ for _, kv := range bi.Settings {
+ if kv.Key == "vcs.revision" {
+ return kv.Value
+ }
+ }
+ }
+ return ""
+}
+
+// readMigrationHistoryNow is readMigrationHistory for this build.
+func readMigrationHistoryNow(ctx context.Context, store release.Store) (*migrationHistory, error) {
+ return readMigrationHistory(ctx, store, version.Build, thisBuildCommit())
+}
+
+// migrationRecordHost is a record key's hostname and whether the record is a
+// data kind: an instance record unless its body decodes to static or
+// service, and every sidecar (its host is in the body). ok is false for a
+// sidecar body with no readable host.
+func migrationRecordHost(key string, body []byte) (host string, data, ok bool) {
+ segs := strings.Split(key, "/")
+ var b struct {
+ Kind string `json:"kind"`
+ Host string `json:"host"`
+ }
+ derr := json.Unmarshal(body, &b)
+ if segs[3] == "sidecars" {
+ if derr != nil || !provision.ValidHostShape(b.Host) {
+ return "", true, false
+ }
+ return b.Host, true, true
+ }
+ host = strings.TrimSuffix(segs[4], ".json")
+ if derr == nil && (b.Kind == "static" || b.Kind == "service") {
+ return host, false, true
+ }
+ return host, true, true
+}
+
+// beforeRecord is the check before a record key is copied to key. Exempt
+// kinds and other objects pass. Before the window opens, a data kind's
+// hostname is marked create-only (a mark already there passes). From the
+// window on, a data-kind record is never created at an absent destination
+// (S6); a present one is left to the create-only copy, which reports an
+// identical one as already copied and refuses a different one.
+func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store, key string, body []byte) error {
+ if !provision.IsRecordKey(key) {
+ return nil
+ }
+ host, data, ok := migrationRecordHost(key, body)
+ if !data {
+ return nil
+ }
+ if h.mode != provision.HostsModeIncomplete {
+ // A present destination is the copy's own business: identical is
+ // "already copied", different is the verb's own refusal.
+ _, _, err := store.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ name := host
+ if !ok {
+ name = key
+ }
+ return errors.New(name + ": not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data.")
+ }
+ return err
+ }
+ if !ok {
+ return fmt.Errorf("accounts migrate: %s names no hostname, so its copy cannot be recorded", key)
+ }
+ _, err := provision.MarkHostUsed(ctx, store, provision.HostUse{Host: host, Kind: "instance", Source: "accounts migrate", At: time.Now().UTC()})
+ return err
+}
diff --git a/accounts_record_sequence_test.go b/accounts_record_sequence_test.go
index bcb3926da..aa1a83e62 100644
--- a/accounts_record_sequence_test.go
+++ b/accounts_record_sequence_test.go
@@ -106,3 +106,157 @@ func TestPlan9M1MigrationToleratesBodiesMainCopied(t *testing.T) {
})
}
}
+
+// The hostname history at carlos accounts migrate (nearest-region
+// never-reuse plan, Task 10; spec §2): before the history is active a
+// data-kind record's copy marks its hostname first; after, the verb never
+// creates a data-kind record at an absent destination (S6), and a carlos
+// below the history's floor refuses before any write.
+
+func migrateRecordBody(host, kind string, incarnation bool) []byte {
+ b := `{"schema":1,"host":"` + host + `","slug":"x","app":"app","account":"cac","channel":"stable","created_at":"2026-10-26T09:00:00Z"`
+ if kind != "" {
+ b += `,"kind":"` + kind + `"`
+ }
+ if incarnation {
+ b += `,"incarnation":1`
+ }
+ return []byte(b + "}")
+}
+
+func setHistory(t *testing.T, store release.Store, mode string) {
+ t.Helper()
+ _, etag, err := provision.ReadHostsState(context.Background(), store)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.WriteHostsState(context.Background(), store, provision.HostsState{Mode: mode}, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// migrateOne is the verb's record step: the history's check, then the copy.
+func migrateOne(t *testing.T, store release.Store, key string, body []byte) error {
+ t.Helper()
+ ctx := context.Background()
+ h, err := readMigrationHistory(ctx, store, "v9.9.9", "")
+ if err != nil {
+ return err
+ }
+ if err := h.beforeRecord(ctx, store, key, body); err != nil {
+ return err
+ }
+ _, err = putMigrationObject(ctx, store, key, body)
+ return err
+}
+
+func TestMigrateRefusesResurrection(t *testing.T) {
+ for _, incarnation := range []bool{false, true} {
+ store := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := provision.RecordKey("cac", "app", "shop.example.com")
+ body := migrateRecordBody("shop.example.com", "", incarnation)
+ if err := migrateOne(t, store, key, body); err != nil {
+ t.Fatal(err)
+ }
+ setHistory(t, store, provision.HostsModeActive)
+ if err := store.Delete(ctx, key); err != nil {
+ t.Fatal(err)
+ }
+ err := migrateOne(t, store, key, body)
+ if err == nil || err.Error() != "shop.example.com: not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data." {
+ t.Fatalf("migrate again over a deleted record = %v, want S6", err)
+ }
+ if _, _, err := store.Get(ctx, key); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the refused migrate wrote: %v", err)
+ }
+ // Sidecars too, by the host in the body.
+ sk := provision.SidecarRecordKey("cac", "app", "bot")
+ if err := migrateOne(t, store, sk, []byte(`{"schema":1,"name":"bot","host":"bot.app.cac.sidecar.internal","app":"app","account":"cac","channel":"stable"}`)); err == nil {
+ t.Fatal("a sidecar record was created at an absent destination once active")
+ }
+ }
+}
+
+func TestMigrateIdenticalDestinationPasses(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ key := provision.RecordKey("cac", "app", "shop.example.com")
+ body := migrateRecordBody("shop.example.com", "", false)
+ if err := migrateOne(t, store, key, body); err != nil {
+ t.Fatal(err)
+ }
+ setHistory(t, store, provision.HostsModeActive)
+ h, err := readMigrationHistory(context.Background(), store, "v9.9.9", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := h.beforeRecord(context.Background(), store, key, body); err != nil {
+ t.Fatalf("an identical present destination = %v, want it to pass", err)
+ }
+}
+
+func TestMigrateUnrelatedObjectsPass(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ setHistory(t, store, provision.HostsModeActive)
+ for key, body := range map[string][]byte{
+ "apps/cac/app/channel.json": []byte(`{"v":1}`),
+ provision.RecordKey("cac", "app", "site.example.com"): migrateRecordBody("site.example.com", "static", false),
+ provision.RecordKey("cac", "app", "svc.example.com"): migrateRecordBody("svc.example.com", "service", false),
+ } {
+ if err := migrateOne(t, store, key, body); err != nil {
+ t.Fatalf("%s once active = %v, want it copied", key, err)
+ }
+ }
+}
+
+func TestMigrateMarksBeforeCopy(t *testing.T) {
+ store := &orderStore{Store: release.NewDirStore(t.TempDir())}
+ key := provision.RecordKey("cac", "app", "shop.example.com")
+ if err := migrateOne(t, store, key, migrateRecordBody("shop.example.com", "", false)); err != nil {
+ t.Fatal(err)
+ }
+ mark := provision.HostsUsedKey("shop.example.com")
+ if len(store.puts) < 2 || store.puts[0] != mark || store.puts[1] != key {
+ t.Fatalf("puts = %v, want the mark before the record", store.puts)
+ }
+ // Static records do not mark.
+ store.puts = nil
+ if err := migrateOne(t, store, provision.RecordKey("cac", "app", "site.example.com"), migrateRecordBody("site.example.com", "static", false)); err != nil {
+ t.Fatal(err)
+ }
+ if len(store.puts) != 1 {
+ t.Fatalf("a static record's copy put %v, want the record alone", store.puts)
+ }
+}
+
+type orderStore struct {
+ release.Store
+ puts []string
+}
+
+func (s *orderStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ s.puts = append(s.puts, key)
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func TestCLIRefusesBelowFloor(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ if _, err := readMigrationHistory(ctx, store, "v0.29.0", ""); err != nil {
+ t.Fatalf("no floor = %v, want allowed", err)
+ }
+ if _, err := provision.WriteHostsFloor(ctx, store, provision.HostsFloor{Version: "v0.30.0", Commit: "abc123"}, ""); err != nil {
+ t.Fatal(err)
+ }
+ want := "this carlos is older than the hostname history's floor, v0.30.0. update carlos, then run it again."
+ for _, build := range []struct{ version, commit string }{{"v0.29.0", ""}, {"dev", ""}, {"0123abc", "def456"}} {
+ if _, err := readMigrationHistory(ctx, store, build.version, build.commit); err == nil || err.Error() != want {
+ t.Errorf("%+v below the floor = %v, want B10", build, err)
+ }
+ }
+ for _, build := range []struct{ version, commit string }{{"v0.30.0", ""}, {"v0.31.2", ""}, {"dev", "abc123"}} {
+ if _, err := readMigrationHistory(ctx, store, build.version, build.commit); err != nil {
+ t.Errorf("%+v at or above the floor = %v, want allowed", build, err)
+ }
+ }
+}
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r3.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r3.md
new file mode 100644
index 000000000..ab92a1009
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r3.md
@@ -0,0 +1,35 @@
+- **R1 P1 — Detached work escapes the drain: partly resolved.** Workers are counted, but status can miss a worker that starts during its scan.
+- **R1 P1 — Ambiguous mode write: resolved.** Every failed write clears the cached state and ETag.
+- **R1 P2 — Begin performs the status scan: resolved.** Begin and cancel return transition results directly.
+- **R2 P1 — Abort hides a running upload: partly resolved.** The counter survives abort, but the sampling race below remains.
+
+1. **P1 — Drain can report zero while an upload is writing (§3a.2).**
+
+ `hostsStatus` samples the worker count at [hostsused_window.go:83](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window.go:83), before scanning records. An existing import can subsequently start its counted worker at [apiinstanceimport.go:461](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceimport.go:461).
+
+ **Failure scenario:** open the window with an import awaiting upload. Pause status before its record scan, after it sampled zero workers. Start the upload, let it pass its record recheck, and block its snapshot PUT at [apiinstanceimport.go:616](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceimport.go:616). Abort the import, then resume status. The scan excludes the aborted seed, producing zero drain counts while the PUT remains outstanding. Complete uses the same sampling at [hostsused_inventory.go:417](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:417).
+
+ **Fix:** detect worker starts across the scan—for example, validate a worker-start generation and current count under the counter’s mutex, retrying or refusing when the generation changes. Add a real-door witness with the ordering above. The existing witness starts the worker before status, so misses this race.
+
+ **Fault family:** drain completeness—zero must mean no admitted creation or movement remains.
+
+2. **P1 — Census fingerprints still describe the original Task 5 commit (census bookkeeping).**
+
+ The console and provision fingerprints at [plan14-root-reads-nearest-region-b.tsv:11](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv:11) still match `58873885`. Recomputing the census’s hashing algorithm against the reviewed commit gives:
+
+ | Package | Recorded prefix | Actual prefix |
+ |---|---|---|
+ | `internal/console` | `cfe2313b` | `9e7b9452` |
+ | `internal/provision` | `5d5186ec` | `c48a7af3` |
+
+ **Failure scenario:** `TestPlan14RootReadCensus` rejects these mismatches through [plan14_root_reads_test.go:658](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/provision/plan14_root_reads_test.go:658), blocking the required gate.
+
+ **Fix:** regenerate the proposal against the final code and obtain the required independent approval for the changed envelopes.
+
+ **Fault family:** census approval must cover the code being merged.
+
+These P1s have different causes. Refusing activation while seed/import work can still start, or cutting that feature, would remove the drain case if enforced atomically with admissions. Neither addresses the stale census. Round 3 exhausts this review’s budget; another round requires Paul’s approval.
+
+The four targeted regression tests could not start because the read-only sandbox blocked Go’s work-directory creation. The reviewed Go files passed formatting checks. No files changed, no subagents spawned, no full suites ran, and `GOCACHE` remained unset.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r2.md
new file mode 100644
index 000000000..2ece406fc
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task6-r2.md
@@ -0,0 +1,27 @@
+- Round 1 P1 1 — **Partly resolved:** shared consumers at `begin` are protected; consumer changes can still exempt an open region’s bucket.
+- Round 1 P1 2 — **Resolved:** completion checks the window identity, and listings carry that identity.
+- Round 1 P1 3 — **Resolved:** the mapper is layout-owned; read-only reproduction of the guard found no violations.
+- Round 1 P2 4 — **Resolved:** the reported malformed flat filenames now become unmapped, with mapper and completion witnesses.
+- Round 1 P2 5 — **Resolved:** pools are excluded under the brief’s accepted ruling; examined regions and fleets come from the frozen roster.
+
+**P1 — Consumer changes can preserve the roster while invalidating a fleet’s inventory exemption.** Spec §3; Task 6. Carries forward round 1 P1 1.
+
+At [hostsused_inventory.go:428](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_inventory.go:428), `complete` discards the current `FleetTargets` and `RegionTargets`, comparing only the combined target names. It then computes exemptions using the old mappings at line 437. Those exemptions skip both required listings and their hostnames at lines 445 and 487.
+
+**Failure scenario:**
+
+1. At `begin`, boxes `b1` and `b2` serve regions `ie` and `uk`, both using bucket A. Fleet `fx` uses bucket B.
+2. Close `fx`; inventory both boxes and bucket A.
+3. Change `b2` to use bucket B before completion. Its edges file publishes the actual configured bucket ([snapshot.go:34](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/edgesfile/snapshot.go:34)).
+4. Every combined roster name remains unchanged: bucket A remains through `b1`, and bucket B was already present through `fx`.
+5. `complete` accepts the roster, excuses bucket B using the frozen consumers, and activates region `uk`. A hostname whose only old data is in B remains unmarked and reusable there.
+
+**Concrete fix:** Compare the consumer mappings as well as target names, refusing changed ownership with C10 before applying exemptions. Add an HTTP-door witness for this unchanged-target-set scenario.
+
+**Fault family:** Fleet closure must not waive inventory for an open placement target—the same invariant as round 1 P1 1.
+
+This recurrence triggers stopping rule 2, so the review stops here. Paul’s choices are to refuse consumer changes, cut fleet inventory exemptions, or centralize the consumer invariant with a guard test. I recommend refusing consumer changes with C10.
+
+Reviewed commit `7e50272ab99abf09588ae82eb1a85e590dbe21a1`. No files changed; `GOCACHE` remained unset. Targeted Go tests could not start because the read-only sandbox blocked work-directory creation. No full suites ran.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task7-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task7-r1.md
new file mode 100644
index 000000000..437f0d84a
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task7-r1.md
@@ -0,0 +1,17 @@
+1. **P1 — Failed invalidation permits creates to resume.** Task 7, spec §4, brief check 5.
+ In [hostsused.go:190](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused.go:190), a failed invalidation write returns before paging. The transition clears cached state at [hostsused.go:260](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused.go:260). If that PUT did not land, the next admission reloads `active` and permits creates.
+
+ **Failure scenario:** recovery detects an unmarked allocation; writing `invalidated` fails; subsequent reads and mark writes succeed. The allocation stays pending, but new creates proceed despite the known breach, without an incident page.
+ **Fix:** latch invalidation in process despite persistence failures, retry persistence, and page independently of write success. Add a failure-injection test through recovery followed by a real create request.
+ **Fault family:** a detected history breach must keep data-kind creates refused until re-inventory.
+
+2. **P2 — Required door-level witnesses are incomplete.** Task 7, brief check 6.
+ [hostsused_active_test.go:197](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_active_test.go:197) uses an already stored region rather than testing automatic assignment. The fleet instance assertions at [hostsused_active_test.go:253](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_active_test.go:253) call `hostsTargetRefusal` directly. The region and fleet witnesses do not run with lifetimes both off and on; there are no S4 door witnesses for sidecars, seeds or imports.
+
+ **Failure scenario:** removing the sidecar S4 call would escape these witnesses; the helper assertions cannot detect a missing fleet instance call.
+ **Fix:** exercise the actual create doors with unexamined and closed targets, both lifetime settings, and assert refusal without publication. Add new-app requests proving automatic assignment stays home before activation and selects an examined region afterward.
+ **Fault family:** enforcement must be witnessed at the publishing doors.
+
+No files changed. Targeted tests were attempted with `GOCACHE` unset, but the read-only sandbox prevented Go from creating its build directory; no tests ran.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 3ed46f59d..d83eecc27 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1081,6 +1081,8 @@ func (s *Server) registerCLIRoutes() {
s.cliRoute("POST /api/cli/system/hosts-used/import", svcrole.Set{}, s.handleAPIHostsUsedImport)
s.cliRoute("POST /api/cli/system/hosts-used/close-fleet", svcrole.Set{}, s.handleAPIHostsUsedCloseFleet)
s.cliRoute("POST /api/cli/system/hosts-used/complete", svcrole.Set{}, s.handleAPIHostsUsedComplete)
+ // Invalidation (hostsused_tripwire.go): apiSystemRoller.
+ s.cliRoute("POST /api/cli/system/hosts-used/invalidate", svcrole.Set{}, s.handleAPIHostsUsedInvalidate)
s.cliRoute("GET /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
s.cliRoute("POST /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index cc4abeab6..a0218fbe2 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1597,6 +1597,12 @@ var claimFixtures = map[string]claimFixture{
status: http.StatusConflict,
msg: msgHostsClaimsOn,
}},
+ "route POST /api/cli/system/hosts-used/invalidate": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/invalidate", ""),
+ status: http.StatusConflict,
+ msg: msgHostsClaimsOn,
+ }},
"route POST /api/cli/system/lifetimes/cutover": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo"),
do: claimRefusedAPI(http.MethodPost, "/api/cli/system/lifetimes/cutover", ""),
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index c912a1e98..b0da2f0eb 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -568,6 +568,14 @@ const placeInstancesFailed = "could not update this app's instances — try agai
// refuses the whole request rather than silently doing the routes-only
// half.
func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target string) (status int, errMsg string) {
+ // apps place is cut once the hostname history is active or invalidated
+ // (nearest-region never-reuse spec §5): S3, before the temporary-app
+ // check, the registry or any write. A placement change on an existing
+ // app would move data under hostnames the history cannot follow.
+ // Placement at app creation (carlos apps create --place) stays.
+ if mode, err := s.hostsMode(ctx); err == nil && (mode == provision.HostsModeActive || mode == provision.HostsModeInvalidated) {
+ return http.StatusConflict, msgPlacementFixed
+ }
// The hostname history's admission (hostsused.go): no placement while
// the activation window is open (S7); an admitted one is counted until
// it returns.
diff --git a/internal/console/fleets_place_cut_test.go b/internal/console/fleets_place_cut_test.go
new file mode 100644
index 000000000..14fa6a135
--- /dev/null
+++ b/internal/console/fleets_place_cut_test.go
@@ -0,0 +1,70 @@
+package console
+
+// apps place is cut once the hostname history is active or invalidated
+// (nearest-region never-reuse plan, Task 9; spec §5): every entry point
+// answers S3 before the registry is opened or anything is written. Before
+// activation it works as today, and placement at app creation stays.
+
+import (
+ "html"
+ "net/http"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestPlaceRefusedAfterActivation(t *testing.T) {
+ for _, mode := range []string{provision.HostsModeActive, provision.HostsModeInvalidated} {
+ t.Run(mode, func(t *testing.T) {
+ fx, token := placeFixture(t, "code-place-cut-"+mode)
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: mode, Examined: []string{"fleet:pi"}})
+ // A registry nobody can open: a door that opened it would answer
+ // that, not S3.
+ good := fx.srv.cfg.Registry
+ fx.srv.cfg.Registry = filepath.Join(t.TempDir(), "missing", "registry.db")
+
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/titogo/place", map[string]string{"target": "fleet/pi"}, token)
+ if status != http.StatusConflict || out["error"] != msgPlacementFixed {
+ t.Fatalf("API place = %d %v, want 409 S3", status, out)
+ }
+
+ fx.srv.cfg.Registry = good
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-place-cut-browser-"+mode)
+ csrf := sessionToken(t, fx, c)
+ fx.srv.cfg.Registry = filepath.Join(t.TempDir(), "missing", "registry.db")
+ if status, _, _ := postForm(t, c, fx.u("/apps/titogo/place"), url.Values{"csrf": {csrf}, "target": {"fleet/pi"}}); status != http.StatusSeeOther {
+ t.Fatalf("app place page = %d, want 303", status)
+ }
+ fx.srv.cfg.Registry = good
+ if _, _, body := get(t, c, fx.u("/apps/titogo/settings/placement")); !strings.Contains(body, html.EscapeString(msgPlacementFixed)) {
+ t.Fatalf("no S3 flash on the app page:\n%s", body)
+ }
+ if status, _, _ := postForm(t, c, fx.u("/fleets/pi/place"), url.Values{"csrf": {csrf}, "app": {"titogo"}}); status != http.StatusSeeOther {
+ t.Fatalf("fleet place page = %d, want 303", status)
+ }
+ if _, _, body := get(t, c, fx.u("/fleets/pi")); !strings.Contains(body, html.EscapeString(msgPlacementFixed)) {
+ t.Fatalf("no S3 flash on the fleet page:\n%s", body)
+ }
+ fx.srv.cfg.Registry = good
+ assertPlacement(t, fx, "")
+ })
+ }
+ t.Run("incomplete", func(t *testing.T) {
+ fx, token := placeFixture(t, "code-place-cut-incomplete")
+ if status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/titogo/place", map[string]string{"target": "fleet/pi"}, token); status != http.StatusOK {
+ t.Fatalf("API place before activation = %d %v, want 200", status, out)
+ }
+ assertPlacement(t, fx, "fleet/pi")
+ })
+ t.Run("placement at create stays", func(t *testing.T) {
+ fx, token := placeFixture(t, "code-place-cut-create")
+ forceHostsState(t, fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"fleet:pi"}})
+ if status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]string{"name": "placed", "place": "fleet/pi"}, token); status != http.StatusOK {
+ t.Fatalf("app create with --place once active = %d %v, want 200", status, out)
+ }
+ })
+}
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index a1f9e40b1..171cdd727 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -42,6 +42,7 @@ const (
msgHostsInvalidated = "New instances can't be created right now. Try again later." // S5
msgHostsActivating = "New instances can't be created during maintenance. Try again in a few minutes." // S8
msgHostsMovesPaused = "Moves and placement are paused for maintenance. Try again later." // S7
+ msgPlacementFixed = "An app's placement can't be changed once it exists." // S3
)
// msgHostsTargetUnexamined is S4: target is a region's place name, or
@@ -131,6 +132,15 @@ func (s *Server) LoadHostsMode(ctx context.Context) {
if err != nil {
log.Printf("console: hosts used: read the mode at start: %v (the first door that needs it reads it again)", err)
}
+ if mode == provision.HostsModeActive {
+ // The start's tripwire (hostsused_tripwire.go): once here, and
+ // again in the background until it finishes (RunHostsTripwire).
+ if err := s.hostsTripwire(ctx); err != nil {
+ log.Printf("console: hosts used: the start's tripwire could not finish: %v (it runs again in the background)", err)
+ go s.RunHostsTripwire(context.WithoutCancel(ctx))
+ }
+ mode, _ = s.hostsMode(ctx)
+ }
if s.cfg.AppRegions && s.cfg.HomeRegion != "" && mode != provision.HostsModeActive {
log.Printf("console: %s", msgAppRegionsWaitForHistory)
}
diff --git a/internal/console/hostsused_tripwire.go b/internal/console/hostsused_tripwire.go
new file mode 100644
index 000000000..512644391
--- /dev/null
+++ b/internal/console/hostsused_tripwire.go
@@ -0,0 +1,151 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// The tripwire and invalidation (nearest-region never-reuse spec §4, plan
+// Task 8). At a start with the history active, every record that may hold
+// data must be covered by a mark; one that is not (a restore that dropped
+// marks, a console below the floor) invalidates the history. Cost per
+// start: a listing of apps/ and one of control/hosts-used/ (a page per
+// 1,000 keys), and a GET per record key with no mark, which is every
+// static and service record. Nothing per request.
+
+// msgHostsPageOperator is D4 (approved, nearest-region-never-reuse-b.md).
+const msgHostsPageOperator = "the hostname history is invalidated by an operator"
+
+// hostsTripwireRetry is how long the tripwire waits before trying a start's
+// check again after a store error.
+var hostsTripwireRetry = time.Minute
+
+// hostsTripwire is the start-time check. It returns nil when the history is
+// not active, when every record is covered, or once it has invalidated the
+// history; an error means the check could not finish.
+func (s *Server) hostsTripwire(ctx context.Context) error {
+ if s.cfg.Releases == nil {
+ return nil
+ }
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ return err
+ }
+ if mode != provision.HostsModeActive {
+ return nil
+ }
+ marks, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix)
+ if err != nil {
+ return err
+ }
+ marked := map[string]bool{}
+ for _, k := range marks {
+ marked[k] = true
+ }
+ keys, err := s.cfg.Releases.List(ctx, "apps/")
+ if err != nil {
+ return err
+ }
+ for _, k := range keys {
+ if !provision.IsRecordKey(k) {
+ continue
+ }
+ segs := strings.Split(k, "/")
+ if segs[3] == "instances" && marked[provision.HostsUsedKey(strings.TrimSuffix(segs[4], ".json"))] {
+ continue
+ }
+ raw, _, err := s.cfg.Releases.Get(ctx, k)
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ var body struct {
+ Kind string `json:"kind"`
+ Host string `json:"host"`
+ }
+ derr := json.Unmarshal(raw, &body)
+ if segs[3] == "sidecars" {
+ if derr == nil && marked[provision.HostsUsedKey(body.Host)] {
+ continue
+ }
+ } else if derr == nil && (body.Kind == "static" || body.Kind == "service") {
+ continue
+ }
+ if err := s.invalidateHosts(ctx, msgHostsPageUncovered(k)); err != nil {
+ return err
+ }
+ return nil
+ }
+ return nil
+}
+
+// RunHostsTripwire runs the start's check, and again every
+// hostsTripwireRetry until it finishes: a store error is not a breach, and
+// must not invalidate the history by itself. LoadHostsMode starts it when
+// the start's own run could not finish.
+func (s *Server) RunHostsTripwire(ctx context.Context) {
+ for {
+ err := s.hostsTripwire(ctx)
+ if err == nil {
+ return
+ }
+ log.Printf("console: hosts used: the start's tripwire could not finish: %v (trying again in %s)", err, hostsTripwireRetry)
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(hostsTripwireRetry):
+ }
+ }
+}
+
+// handleAPIHostsUsedInvalidate is POST /api/cli/system/hosts-used/invalidate:
+// an operator invalidates an active history (after a restore that may have
+// dropped marks, spec §4). C12 when it is not active.
+func (s *Server) handleAPIHostsUsedInvalidate(w http.ResponseWriter, r *http.Request) {
+ addr, _, ok := s.apiSystemRoller(w, r)
+ if !ok {
+ return
+ }
+ if !s.systemBucket(w) {
+ return
+ }
+ if s.cfg.HostClaim || s.cfg.MovesEnabled {
+ jsonError(w, http.StatusConflict, msgHostsClaimsOn)
+ return
+ }
+ ctx := r.Context()
+ st, err := s.hostsState(ctx)
+ if err != nil {
+ hostsWriteFailed(w, "invalidate", err)
+ return
+ }
+ if st.Mode != provision.HostsModeActive {
+ jsonError(w, http.StatusConflict, msgHostsNotActive)
+ return
+ }
+ if err := s.invalidateHosts(ctx, msgHostsPageOperator); err != nil {
+ if err.Error() == msgHostsNotActive {
+ jsonError(w, http.StatusConflict, msgHostsNotActive)
+ return
+ }
+ hostsWriteFailed(w, "invalidate", err)
+ return
+ }
+ log.Printf("console: hosts used: %s invalidated the hostname history", addr)
+ st, err = s.hostsState(ctx)
+ if err != nil {
+ hostsWriteFailed(w, "invalidate", err)
+ return
+ }
+ writeJSON(w, http.StatusOK, hostsStateAnswer(st))
+}
diff --git a/internal/console/hostsused_tripwire_test.go b/internal/console/hostsused_tripwire_test.go
new file mode 100644
index 000000000..180910c70
--- /dev/null
+++ b/internal/console/hostsused_tripwire_test.go
@@ -0,0 +1,137 @@
+package console
+
+// The tripwire and invalidation (nearest-region never-reuse plan, Task 8;
+// spec §4): at a start with the history active, a record with no mark that
+// may hold data invalidates it; an operator may invalidate it; a fresh
+// inventory makes it active again.
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+const hostsUsedInvalidateURL = "/api/cli/system/hosts-used/invalidate"
+
+// startHostsAgain is a console start as far as the history goes.
+func startHostsAgain(t *testing.T, srv *Server) {
+ t.Helper()
+ srv.hosts.reset()
+ srv.LoadHostsMode(context.Background())
+}
+
+func putHistoryRecord(t *testing.T, l lifetimesFx, host, kind string) {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Host: host, Slug: "x", App: ltApp, Account: "bab", Channel: "stable", Kind: kind, CreatedAt: time.Now().UTC()}
+ b, _ := json.Marshal(rec)
+ if _, err := l.fx.rel.Put(context.Background(), provision.RecordKey("bab", ltApp, host), b, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func modeOf(t *testing.T, l lifetimesFx) provision.HostsState {
+ t.Helper()
+ st, _, err := provision.ReadHostsState(context.Background(), l.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return st
+}
+
+func TestTripwireInvalidatesOnUnmarkedRecord(t *testing.T) {
+ for name, write := range map[string]func(l lifetimesFx){
+ "instance": func(l lifetimesFx) { putHistoryRecord(t, l, "nomark.shop.example.com", "") },
+ "undecodable": func(l lifetimesFx) {
+ l.fx.rel.Put(context.Background(), provision.RecordKey("bab", ltApp, "bad.shop.example.com"), []byte("{no"), "")
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ l := newLifetimesFx(t)
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive})
+ write(l)
+ startHostsAgain(t, l.fx.srv)
+ if st := modeOf(t, l); st.Mode != provision.HostsModeInvalidated || st.Reason == "" {
+ t.Fatalf("state after the tripwire = %+v, want invalidated with a reason", st)
+ }
+ if code, out := createAs(t, l, `{"host":"after.shop.example.com"}`); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated {
+ t.Fatalf("create once invalidated = %d %s, want 503 S5", code, out)
+ }
+ })
+ }
+}
+
+func TestTripwireIgnoresExemptUnmarked(t *testing.T) {
+ l := newLifetimesFx(t)
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive})
+ putHistoryRecord(t, l, "site.shop.example.com", "static")
+ putHistoryRecord(t, l, "svc.shop.example.com", "service")
+ putHistoryRecord(t, l, "marked.shop.example.com", "")
+ if _, err := provision.MarkHostUsed(context.Background(), l.fx.rel, provision.HostUse{Host: "marked.shop.example.com", Source: "test"}); err != nil {
+ t.Fatal(err)
+ }
+ startHostsAgain(t, l.fx.srv)
+ if st := modeOf(t, l); st.Mode != provision.HostsModeActive {
+ t.Fatalf("state = %+v, want active", st)
+ }
+}
+
+// TestRestoreDroppingMarksInvalidates: a control-bucket restore that lost a
+// mark is found at the next start; data-kind creates are refused and the
+// nearest-region switch goes off.
+func TestRestoreDroppingMarksInvalidates(t *testing.T) {
+ l := newLifetimesFx(t)
+ if code, out := createAs(t, l, `{"host":"kept.shop.example.com"}`); code != http.StatusCreated {
+ t.Fatalf("create = %d %s", code, out)
+ }
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:ie"}})
+ l.fx.srv.cfg.AppRegions, l.fx.srv.cfg.HomeRegion = true, "ie"
+ if !l.fx.srv.appRegionsOn() {
+ t.Fatal("the switch is not on while active")
+ }
+ dropMark(t, l.fx.rel, "kept.shop.example.com")
+ startHostsAgain(t, l.fx.srv)
+ if st := modeOf(t, l); st.Mode != provision.HostsModeInvalidated {
+ t.Fatalf("state = %+v, want invalidated", st)
+ }
+ if l.fx.srv.appRegionsOn() {
+ t.Fatal("the switch stayed on once invalidated")
+ }
+ if code, out := createAs(t, l, `{"host":"new.shop.example.com"}`); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated {
+ t.Fatalf("create = %d %s, want 503 S5", code, out)
+ }
+}
+
+// TestReinventoryLeavesInvalidated: begin from invalidated, clean scans,
+// complete: active again.
+func TestReinventoryLeavesInvalidated(t *testing.T) {
+ l := invFx(t)
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: "test"})
+ begin(t, l)
+ cleanImport(t, l, nil, nil)
+ mustComplete(t, l)
+ if code, out := createAs(t, l, `{"host":"fresh.shop.example.com"}`); code != http.StatusCreated {
+ t.Fatalf("create once active again = %d %s", code, out)
+ }
+}
+
+func TestInvalidateDoor(t *testing.T) {
+ l := newLifetimesFx(t)
+ if code, _ := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.member, `{}`); code != http.StatusNotFound {
+ t.Fatalf("a member's invalidate = %d, want 404", code)
+ }
+ if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.operator, `{}`); code != http.StatusConflict || out["error"] != msgHostsNotActive {
+ t.Fatalf("invalidate when incomplete = %d %v, want 409 C12", code, out)
+ }
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive})
+ code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.operator, `{}`)
+ if code != http.StatusOK || out["mode"] != provision.HostsModeInvalidated {
+ t.Fatalf("invalidate = %d %v", code, out)
+ }
+ if st := modeOf(t, l); st.Reason != msgHostsPageOperator {
+ t.Fatalf("reason = %q, want D4", st.Reason)
+ }
+}
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 1395b442a..4f0ccb611 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -299,6 +299,7 @@ var closedDoors = []string{
"POST /api/cli/system/hosts-used/import",
"POST /api/cli/system/hosts-used/close-fleet",
"POST /api/cli/system/hosts-used/complete",
+ "POST /api/cli/system/hosts-used/invalidate",
// `carlos channels resign`: the console signs digests a person has
// confirmed. A credential never confirms on a person's behalf.
"POST /api/cli/apps/{account}/{app}/channels/resign",
@@ -1108,8 +1109,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 72 {
- t.Errorf("walked %d closed doors, want all %d (and 72 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status and its five window doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
+ if seen != len(closedDoors) || seen != 73 {
+ t.Errorf("walked %d closed doors, want all %d (and 73 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status and its six window doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 40151fcd6..26fab8d70 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -272,6 +272,7 @@ route POST /api/cli/system/hosts-used/cancel
route POST /api/cli/system/hosts-used/close-fleet
route POST /api/cli/system/hosts-used/complete
route POST /api/cli/system/hosts-used/import
+route POST /api/cli/system/hosts-used/invalidate
route POST /api/cli/system/layout
route POST /api/cli/system/legacy-routes
route POST /api/cli/system/lifetimes/cutover
diff --git a/system.go b/system.go
index c00ce01a6..8cda61883 100644
--- a/system.go
+++ b/system.go
@@ -148,7 +148,7 @@ func systemUsage() {
carlos system seeds-floor publish --min-release <release>
carlos system legacy-routes assign --name <name> --to <account>/<app>
carlos system lifetimes cutover [--no-wait]
- carlos system hosts-used status
+ carlos system hosts-used <status|begin|cancel|import|close-fleet|complete|invalidate>
carlos system box role <box> <default|legacy|platform>
carlos system box publish-record
carlos system group role <region> <default|legacy>
@@ -174,7 +174,13 @@ The platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):
once, after the old console has stopped. Waits until they are on
hosts-used status
the hostname history: its mode, how many hostnames it has
- recorded, and the instance creates and deletes still settling
+ recorded, and how much work is still settling
+ hosts-used begin | cancel
+ open or close the maintenance window used to complete the history
+ hosts-used import <file> | close-fleet <fleet> | complete
+ inside the window: load the scan, close a fleet, finish
+ hosts-used invalidate
+ stop new instances until a fresh inventory completes
box role <box> <default|legacy|platform>
whether new instances may be placed on a box. A legacy or
platform box keeps the instances it has and takes no new ones
diff --git a/system_hostsused.go b/system_hostsused.go
index 0675788ab..a3c5660c7 100644
--- a/system_hostsused.go
+++ b/system_hostsused.go
@@ -217,7 +217,7 @@ func runSystemHostsUsedVerb(rest []string) {
verb := rest[0]
args := 0
switch verb {
- case "status", "begin", "cancel", "complete":
+ case "status", "begin", "cancel", "complete", "invalidate":
case "import", "close-fleet":
args = 1
default:
@@ -271,5 +271,7 @@ func runSystemHostsUsedVerb(rest []string) {
fmt.Fprintf(stdout, "fleet %s is closed. new instances can't be placed on it\n", fs.Arg(0))
case "complete":
fmt.Fprintf(stdout, "the hostname history is complete. %d hostnames recorded\n", st.Marks)
+ case "invalidate":
+ fmt.Fprintln(stdout, "the hostname history is invalidated. new instances are refused until a fresh inventory completes")
}
}
diff --git a/system_hostsused_test.go b/system_hostsused_test.go
index 827f4b8ae..c8cf7baee 100644
--- a/system_hostsused_test.go
+++ b/system_hostsused_test.go
@@ -251,6 +251,10 @@ func TestSystemHostsUsedInventoryVerbsThroughTheBinary(t *testing.T) {
record("complete")(w, r)
w.Write([]byte(`{"mode":"active","marks":12}`))
})
+ mux.HandleFunc("POST /api/cli/system/hosts-used/invalidate", func(w http.ResponseWriter, r *http.Request) {
+ record("invalidate")(w, r)
+ w.Write([]byte(`{"mode":"invalidated"}`))
+ })
ts := httptest.NewServer(mux)
t.Cleanup(ts.Close)
dir := t.TempDir()
@@ -281,6 +285,9 @@ func TestSystemHostsUsedInventoryVerbsThroughTheBinary(t *testing.T) {
if out := run("complete"); !strings.Contains(out, "the hostname history is complete. 12 hostnames recorded\n") {
t.Fatalf("complete printed:\n%s", out)
}
+ if out := run("invalidate"); !strings.Contains(out, "the hostname history is invalidated. new instances are refused until a fresh inventory completes\n") {
+ t.Fatalf("invalidate printed:\n%s", out)
+ }
mu.Lock()
defer mu.Unlock()
if !strings.Contains(bodies["import"], `"entries":["a.example.com.db"]`) || bodies["close-fleet"] != `{"fleet":"fx"}` {