plan: region HA P1a first slice (with P0 removals)
Eighteen tasks against spec rev 6: P0 removals (edges address source, joining mode and units, console enrolment pass, beginExecutableChange's HA arm); the owner format; the one acquire table and AcquireHA; the release marker with a durable obligation; the keep decision and local record; HA wake with clean-tree restore; files and wake-state publication; key and token producers; the migration gate, pass and sleep-time migration; same-box recovery with an emptiness proof (pulled forward); move and import refusals; carlos system status; the seeded N-box simulation; the dev rollout on the two IE boxes (needs Paul's go). Census rows, copy strings RHA-P1a-C1..C10 and eight spec gaps listed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+968
−0
docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md+968 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md b/docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md| new file mode 100644 |
| index 000000000..964f070e2 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md |
| @@ -0,0 +1,968 @@ |
| +# Region HA P1a: first slice Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** On dev's two IE boxes, a box reuses a host's local database and files only on positive proof from a release marker, restores from S3 into a clean tree otherwise, and shows Paul which hosts it migrated and which it refused. P0's removals ride in the same merge. |
| + |
| +**Architecture:** A new pure package, `internal/hafresh`, holds the three decisions the invariants rest on: the acquire table (I1), the keep decision (I2) and the migration gate (I2). The seeded simulation drives exactly these functions. `internal/lease` does the S3 I/O around them: the HA acquire, the release marker and its retry obligation, and the head and local TXIDs. `internal/activator` and `internal/host` wire them into wake, sleep, files publication, migration and status, all behind `CARLOS_REGION_HA`, and per host only once that host is migrated. |
| + |
| +**Tech Stack:** Go 1.26, litestream v0.5.14, superfly/ltx v0.5.1, aws-sdk-go-v2 S3 conditional writes, `internal/lease/leasetest` for S3 in tests. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6 (approved by Paul, 0e53c932). In scope: §4.2, §5, §7.3, §8.2, §8.4, the P1a rows of §9.4, §9.6 (pulled forward, gap 3), §14's refusals, §16.3 items 1, 2, 3 and 5, and §19's first slice. |
| + |
| +## Global Constraints |
| + |
| +- **Owner:** `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>`. `iid=` is omitted when unknown. A lock written for an HA-on host appends `;ha=1` (gap 1). |
| +- **Marker:** `{generation, expires_at: 1970-01-01T00:00:00Z, owner: "released/v1;ref=<ref>;iid=<iid>", carlos_release: {v:1, box, iid, lifetime, txid, files_gen, at}}`, plus `clean` inside `carlos_release` (gap 2). |
| +- **Local record:** `<db>.release.json`. It holds: |
| + - the marker fields; |
| + - the DB file's inode, size, `mtime_ns` and `ctime_ns`, and whether its `-wal` is absent or empty; |
| + - a files tree digest: SHA-256 over (path, type, mode, size, inode, `mtime_ns`, `ctime_ns`) for every entry of the files directory and the platform files. It reads metadata only. |
| +- **`clean`:** the final sync succeeded, and the final files publish reported no `TooLarge`, `NotRegular` or `Unreadable` entries (`hostfiles.SyncStats`). |
| +- **Expiry never lets another box acquire.** A failed marker PUT ends only on success or a 412, never on expiry. |
| +- **Cadences:** the H6 trio (`instance.key`, `report.token`, `<host>.env`) and the wake state publish at about 1 s. App files publish every `files_snapshot_interval` (15 min, H8). On HA boxes the stream class captures the WAL every 1 s; batched (5 min) and daily (24 h) are unchanged. |
| +- **Switch:** `CARLOS_REGION_HA` (box, `strconv.ParseBool`) gates everything here except the owner format, which is unconditional. |
| + - A host is **HA-on** once its `lock.json` carries a release marker or a `;ha=1` owner. |
| + - Activation is refused while any `registry.Route.HoldOp` is set or `Registry.ImportJournalHosts()` is non-empty. |
| +- **Budget (spec §18):** |
| + - wake, copy kept: 1 GET + 1 PUT; |
| + - wake, restore: 1 GET + 1 PUT + the restore; |
| + - sleep: + 1 PUT (marker) in place of a free DELETE, + a files publish if changed; |
| + - failed marker: 1 PUT per retry, with backoff; |
| + - migration: 1 LIST (L0) per host once + the baseline publish + 1 PUT per box for its inventory; |
| + - snapshot plan: at most 4 publishes per awake hour, none when unchanged; |
| + - trio: up to 2 PUTs a second while written. |
| + |
| + No new periodic S3 poll. |
| +- **Cross-compile:** darwin and windows build. Linux-only syscalls (stat `ctime`) need `//go:build linux` and a `!linux` stub that errors, so those systems never keep. |
| +- **Binary ceiling:** linux/arm64 `carlos` at most 53000000 bytes (`.amadan/ci.d/20-cross@5`, `max_bytes`). |
| +- **Copy:** no em dashes in any user-facing string. RHA-P1a-C1 to C10 wait for Paul's review. Log lines are diagnostics and are not reviewed. |
| +- **Census:** `make census-card`, then CLAIMS, then `make census-propose`. A cross-model reviewer approves. Paul rules only on decisions. Rows are in "Census". |
| +- **Tests:** locally, only touched packages, with `-run` and `nice -n 19`. CI runs the full gate. |
| + |
| +## Review Focus |
| + |
| +1. **A host awake at activation** holds a lease without `;ha=1`. Its sleep must migrate it only if the gate passes; it must never write a marker while another box holds a copy. Task 13: `TestSleepMigratesAwakeHostOnlyWhenGatePasses`. |
| +2. **An agent restart with a marker owed.** The marker is retried before that host is acquired, and expiry never drops the file. Task 10: `TestOwedMarkerRetriedBeforeAcquire`. |
| +3. **The nested layout.** Set-aside and clean restore use `pathsFor`'s directories, and a failed rename fails the wake. Task 9: `TestRestoreHANestedRenameFailureFailsWake`. |
| +4. **A host with no files directory and no manifest.** The tree digest of an absent directory is stable, so the host can still be kept. Task 8: `TestTreeDigestAbsentDirStable`. |
| +5. **Renewal after a take over a marker** uses the ETag the PUT returned. Task 6: `TestAcquireHATakeMarkerThenRenews`. |
| + |
| +--- |
| + |
| +Tasks 1 to 4 are P0. Tasks 5 to 16 are the slice. Task 17 is the simulation; Task 18 is the dev rollout. **[own review]** marks stopping rule 3; the whole-branch review covers the rest. Each run step is `nice -n 19 go test <pkg> -run '<names>' -count=1`: it FAILs before the step that follows it and PASSes after. |
| + |
| +### Task 1: P0. Box address source out of the claim code |
| + |
| +**Files:** |
| +- Modify: `internal/host/edgesfile.go:455` (signature), `:526` (drop `applyEdgesClaims`), `:734-757`, `:983-988` |
| +- Delete: `internal/host/edgesclaims.go`. First move its claims-off witnesses into `edgesfile_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Registry, ident edgesFile, eip string, last *[]byte, refresh bool, addrs AddressSource, lifetimes bool, assets *assetPolicy) error`. `addrs` is `boxAddressSource(os.Getenv)` when `CARLOS_REGION_HA` is on, and nil otherwise. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestEdgesFileRegionHAPublishesAddressWithoutClaimRead(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()); reg := testRegistryWithInstance(t, "shop.example.com") |
| + addrs := fixedAddresses{Private: "10.0.1.5", PrivateCIDR: "10.0.0.0/16", Public: "203.0.113.9"} |
| + var last []byte |
| + if err := edgesFileWriteClaims(ctx, s, reg, testIdent("box-a"), "", &last, true, addrs, false, nil); err != nil { t.Fatal(err) } |
| + f := readEdgesFile(t, s, "box-a") |
| + if f.PrivateIP != "10.0.1.5" { t.Fatalf("private_ip = %q", f.PrivateIP) } |
| + if _, ok := f.Hosts["shop.example.com"]; !ok { t.Fatal("relocatable host withheld: claim filtering still applied") } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/host/ -run TestEdgesFileRegionHAPublishesAddressWithoutClaimRead`. It FAILs: it does not compile. |
| +- [ ] **Step 3: Implement** the parameter change and the deletion. `edgesLoopState.claims` goes. |
| +- [ ] **Step 4: Run** `-run 'TestEdgesFile|TestBoxAddress'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "P0: edges file reads box addresses directly; claim read under CARLOS_REGION_HA removed" |
| + |
| +### Task 2: P0. Delete joining mode, `carlos system join` and its units |
| + |
| +**Files:** |
| +- Delete: `internal/host/joining.go`, `joinmode.go`, `joinroot.go` and their tests; `internal/host/units/carlos-system-join.service`, `.path` |
| +- Modify: `system.go:54`, `:104-106`, `:188`; `internal/host/bootstrap.go:166-176` (`enabledUnits`); `internal/host/agent.go:220-240` (the joining branch); `internal/host/claimwiring.go:102-106` (drop `SetHosting`; gap 6) |
| +- Create: `internal/host/retiredunits.go` |
| + |
| +**Interfaces:** |
| +- Produces: `var retiredUnits = []string{"carlos-system-join.path", "carlos-system-join.service"}` and `func retireUnits(root string, units []string) error`. `retireUnits` disables, stops and removes each unit under `<root>/etc/systemd/system`. An absent unit is not an error. Bootstrap's plan path calls it, and a self-update apply runs that path. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestBootstrapRetiresJoinUnits(t *testing.T) { // internal/host |
| + root := t.TempDir(); writeUnit(t, root, "carlos-system-join.path") |
| + if err := retireUnits(root, retiredUnits); err != nil { t.Fatal(err) } |
| + if _, err := os.Stat(filepath.Join(root, "etc/systemd/system/carlos-system-join.path")); !os.IsNotExist(err) { t.Fatal("still installed") } |
| + if slices.Contains(enabledUnits, "carlos-system-join.path") { t.Fatal("still enabled") } |
| +} |
| +func TestSystemJoinVerbGone(t *testing.T) { // root package, system_test.go |
| + if v, _, _ := systemVerb([]string{"join"}); v != "" { t.Fatalf("join still a verb: %q", v) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/host/ -run TestBootstrapRetiresJoinUnits` and `. -run TestSystemJoinVerbGone`. They FAIL. |
| +- [ ] **Step 3: Implement** the deletions and `retireUnits`. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestBootstrap|TestSystemUnits'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "P0: joining mode, carlos system join and its units removed; bootstrap retires installed units" |
| + |
| +### Task 3: P0. Delete the console's enrolment pass |
| + |
| +**Files:** |
| +- Delete: `internal/console/enrollpass.go`, `internal/console/awsmembership.go`, `internal/hostactors/awsmembership/` and their tests |
| +- Modify: `internal/console/hostclaimops.go:44-61` (drop the `s.cfg.RegionHA` branch; the capacity metric's start moves with P2, gap 6) |
| + |
| +**Interfaces:** none. |
| + |
| +- [ ] **Step 1: Delete,** then run `go build ./... && go vet ./internal/console/ ./internal/hostactors/...`. Expected: clean. |
| +- [ ] **Step 2: Run** `./internal/console/ -run 'TestClaimRecovery|TestHostClaimOps|TestNoCapacity'`. Expected: PASS. Move any claims-off witness out of a deleted test file first. |
| +- [ ] **Step 3: Commit** "P0: console enrolment pass and AWS membership read removed" |
| + |
| +### Task 4: P0. `beginExecutableChange` drops its region-HA arm [own review] |
| + |
| +Root runs this. |
| + |
| +**Files:** |
| +- Modify: `internal/host/systemparticipation.go:47-110`; `internal/host/systemapply.go:134` and `:259-262` (the `regionHA` field goes) |
| + |
| +**Interfaces:** none. With no participation required it returns nil and writes no update-begun marker, whatever `CARLOS_REGION_HA` says. `ParticipationRequired` and `WithParticipation` are unchanged. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestBeginExecutableChangeIgnoresRegionHA(t *testing.T) { |
| + a := testApplier(t); t.Setenv("CARLOS_REGION_HA", "1") |
| + mkdirAll(t, filepath.Join(a.dataDir, ".hostexec")) // the leftover that used to defer updates |
| + if err := a.beginExecutableChange(ctx, "v1", time.Now()); err != nil { t.Fatalf("deferred: %v", err) } |
| + if exists(updateBegunPath(a.optDir)) { t.Fatal("legacy marker written") } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/host/ -run TestBeginExecutableChangeIgnoresRegionHA`. It FAILs with `errSystemDeferred`. |
| +- [ ] **Step 3: Implement.** Delete the `a.regionHA` checks at `:52` and `:81`: return nil when `!required`; otherwise take the `WithParticipation` arm. Delete the field. |
| +- [ ] **Step 4: Run** `-run 'TestBeginExecutableChange|TestSystemApply'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "P0: system apply no longer reads CARLOS_REGION_HA for claim participation" |
| + |
| +### Task 5: The owner format, unconditional |
| + |
| +**Files:** |
| +- Create: `internal/hafresh/owner.go` and its test, `internal/lease/self.go`, `internal/host/haself.go` |
| +- Modify: `internal/lease/lease.go:186-190`, `internal/lease/createlease.go:32`, `internal/host/agent.go` (calls `lease.SetSelf` once `haSelf` answers) |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package hafresh |
| +type Self struct{ Ref, IID string } |
| +type Owner struct{ Ref, IID string; PID int; HA bool } |
| +func OwnerFor(s Self, pid int, ha bool) string |
| +func ParseOwner(s string) (Owner, bool) // strict: fields ref, iid (optional), pid, ha (optional, "1") in that order |
| +``` |
| + |
| +```go |
| +package lease |
| +func SetSelf(s hafresh.Self) |
| +func currentOwner(ha bool) string // OwnerFor(self, os.Getpid(), ha) |
| +``` |
| + |
| +```go |
| +package host |
| +func haSelf(ctx context.Context) (hafresh.Self, error) // Ref: metricsBoxLabel(os.Getenv, readMachineID()); IID: recordInstanceID(readIdentityRecord(...)), retried each minute |
| +``` |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestOwnerRoundTrip(t *testing.T) { |
| + s := hafresh.OwnerFor(hafresh.Self{Ref: "g-0123456789abcdef0123", IID: "i-0abc"}, 4242, true) |
| + if s != "box/v1;ref=g-0123456789abcdef0123;iid=i-0abc;pid=4242;ha=1" { t.Fatal(s) } |
| + if o, ok := hafresh.ParseOwner(s); !ok || o.IID != "i-0abc" || o.PID != 4242 || !o.HA { t.Fatalf("%+v", o) } |
| + for _, bad := range []string{"ip-10-0-0-1:77", "moved:mv_1", "box/v1;ref=a;pid=1;extra=2", "box/v1;iid=i-1;ref=a;pid=1", "box/v2;ref=a;pid=1"} { |
| + if _, ok := hafresh.ParseOwner(bad); ok { t.Errorf("parsed %q", bad) } |
| + } |
| + if hafresh.OwnerFor(hafresh.Self{Ref: "ie-box"}, 1, false) != "box/v1;ref=ie-box;pid=1" { t.Fatal("empty iid kept") } |
| +} |
| +func TestAcquireWritesBoxOwner(t *testing.T) { // internal/lease |
| + tombFixture(t); SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + h, err := Acquire(ctx, "data", "instances/h", ""); if err != nil { t.Fatal(err) } |
| + defer h.Release(ctx) |
| + if o, ok := hafresh.ParseOwner(readView(t, "instances/h").Lock.Owner); !ok || o.HA { t.Fatalf("%+v", o) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestOwnerRoundTrip|TestAcquireWritesBoxOwner'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same, plus `-run TestTombstone` in `./internal/lease/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "lease owner names the box: box/v1;ref;iid;pid" |
| + |
| +### Task 6: The acquire table and `AcquireHA` [own review] |
| + |
| +This is I1's one place. |
| + |
| +**Files:** |
| +- Create: `internal/hafresh/lock.go`, `internal/hafresh/acquire.go` and its test, `internal/lease/ha.go` and its test |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package hafresh |
| +type Marker struct { |
| + V int `json:"v"`; Box string `json:"box"`; IID string `json:"iid"`; Lifetime string `json:"lifetime"` |
| + TXID uint64 `json:"txid"`; FilesGen string `json:"files_gen"`; At time.Time `json:"at"`; Clean bool `json:"clean"` |
| +} |
| +type Lock struct { |
| + Generation int64 `json:"generation"`; ExpiresAt time.Time `json:"expires_at"`; Owner string `json:"owner"` |
| + Release *Marker `json:"carlos_release,omitempty"` |
| +} |
| +type View struct{ Absent bool; Lock Lock; ETag string } |
| +func DecodeLock(body []byte, etag string) (View, error) // no expiry is an error, never free |
| +func MarkerBody(generation int64, m Marker) ([]byte, error) |
| +func (v View) HAOn() bool |
| +type Action int |
| +const ( ActCreate Action = iota + 1; ActTake; ActHeld; ActRefuse ) |
| +type Decision struct{ Action Action; Reason string } |
| +type Proofs struct{ SameBoxEmpty func() (bool, error) } |
| +func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision |
| +``` |
| + |
| +```go |
| +package lease |
| +type HAOptions struct { |
| + Fresh func(ctx context.Context) (bool, error) // on an absent lock: a never-written host, so write ha=1 |
| + SameBoxEmpty func() (bool, error) |
| +} |
| +type RefusedError struct{ Reason string } |
| +func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) |
| +func AcquireHA(ctx context.Context, bucket, prefix, region string, opt HAOptions) (*Held, hafresh.View, error) |
| +func AcquireHATTL(ctx context.Context, bucket, prefix, region string, opt HAOptions, ttl time.Duration) (*Held, hafresh.View, error) // tests |
| +func (h *Held) HA() bool |
| +``` |
| + |
| +**`DecideAcquire`** (spec §9.4, P1a rows): |
| + |
| +| Lock | Action, reason | |
| +|---|---| |
| +| absent | `ActCreate`, `absent` | |
| +| `Release != nil` | `ActTake`, `release marker` | |
| +| owner `moved:*`, expired | `ActTake`, `lifted tombstone` | |
| +| unexpired | `ActHeld`, the owner | |
| +| expired, HA owner, own non-empty IID | `ActTake` if `SameBoxEmpty` says true, else `ActRefuse`, `same box without emptiness proof` | |
| +| expired, HA owner, other box | `ActRefuse`, `another box's expired lease` | |
| +| expired, owner not HA | `ActTake`, `legacy` (an unmigrated host, today's rule) | |
| + |
| +**`AcquireHA`:** |
| +1. GET with its ETag (`readLock`, `tombstone.go:117-140`). |
| +2. Decide. |
| +3. Create with `If-None-Match: *`, or take with `If-Match` and generation + 1. The owner is `currentOwner(v.HAOn() || fresh)`. |
| +4. On 412, re-read, at most 3 rounds. |
| +5. Start the renewer (`lease.go:206`) with the returned ETag. |
| + |
| +`ActHeld` returns `*HeldError`; `ActRefuse` returns `*RefusedError`. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestDecideAcquireTable(t *testing.T) { // hafresh |
| + now := time.Unix(1_800_000_000, 0); self := Self{Ref: "a", IID: "i-a"}; exp := now.Add(-time.Minute) |
| + other, mine := OwnerFor(Self{"b", "i-b"}, 9, true), OwnerFor(self, 9, true) |
| + yes := Proofs{SameBoxEmpty: func() (bool, error) { return true, nil }} |
| + for i, c := range []struct{ v View; p Proofs; want Action }{ |
| + {View{Absent: true}, Proofs{}, ActCreate}, |
| + {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b"}}}, Proofs{}, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, ActHeld}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "moved:mv_1"}}, Proofs{}, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Hour), Owner: "moved:mv_1"}}, Proofs{}, ActHeld}, |
| + } { |
| + if got := DecideAcquire(c.v, self, now, c.p).Action; got != c.want { t.Errorf("case %d: %v, want %v", i, got, c.want) } |
| + } |
| +} |
| +func TestMarkerReadAsFreeByOldReaders(t *testing.T) { // lease |
| + body, _ := hafresh.MarkerBody(7, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: 12, Clean: true}) |
| + var l litestream.Lease |
| + if err := json.NewDecoder(bytes.NewReader(body)).Decode(&l); err != nil || !l.IsExpired() { t.Fatal(err) } |
| + if lockHeld(l.ExpiresAt, time.Now()) || !leaseFree(l.ExpiresAt, time.Now()) { t.Fatal("marker read as held") } |
| +} |
| +func TestAcquireHATakeMarkerThenRenews(t *testing.T) { // Review Focus 5 |
| + s := tombFixture(t); putMarker(t, s, "instances/h", hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| + h, v, err := AcquireHATTL(ctx, "data", "instances/h", "", HAOptions{}, 3*time.Second) |
| + if err != nil || v.Lock.Release == nil || !h.HA() { t.Fatalf("%v %+v", err, v) } |
| + time.Sleep(2 * time.Second) |
| + if err := h.Err(); err != nil { t.Fatalf("renewal failed after take: %v", err) } |
| +} |
| +func TestAcquireHARefusesOtherBoxExpired(t *testing.T) { |
| + s := tombFixture(t); putLease(t, s, "instances/h", hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), time.Now().Add(-time.Hour)) |
| + _, _, err := AcquireHA(ctx, "data", "instances/h", "", HAOptions{}) |
| + var r *RefusedError |
| + if !errors.As(err, &r) || slices.Contains(s.methods(), http.MethodPut) { t.Fatalf("%v %v", err, s.methods()) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestDecideAcquireTable|TestMarkerReadAsFree|TestAcquireHA'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `putMarker`, `putLease` and `readView` are test helpers in `ha_test.go`, over `tombFixture`. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA acquire: the one acquire table; expiry never authorizes another box" |
| + |
| +### Task 7: The release marker, its obligation, and stream capture [own review] |
| + |
| +**Files:** |
| +- Create: `internal/lease/release.go` and its test |
| +- Modify: `internal/lease/lease.go:401-429` (`newStore` uses the Held's monitor interval), `:435-445` (`Replicator` keeps the generation) |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package lease |
| +func (h *Held) SetMonitorInterval(d time.Duration) // 0 keeps dbMonitorInterval (10 s) |
| +func (r *Replicator) Finish(ctx context.Context) (txid uint64, err error) // SyncAndWait + store close; lease held, renewer running |
| +func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) (*Obligation, error) |
| +type Obligation struct{ Bucket, Region, Key, ETag string; Body []byte } |
| +func RetryObligation(ctx context.Context, o Obligation) error |
| +var ErrObligationVoid = errors.New("lease: the marker's lease is no longer ours") |
| +``` |
| + |
| +**`ReleaseMarker`** stops the renewer and PUTs `MarkerBody(generation, m)` with `If-Match` on the renewer's last ETag: |
| +- success: `(nil, nil)`; |
| +- 412: `(nil, ErrObligationVoid)`; |
| +- otherwise: `(&Obligation{exact body and ETag}, err)`. |
| + |
| +**`RetryObligation`** sends the same conditional PUT. It never reads expiry. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestReleaseMarkerOverwritesLock(t *testing.T) { |
| + s := tombFixture(t); r := replicatorFixture(t, s) |
| + txid, err := r.Finish(ctx); if err != nil { t.Fatal(err) } |
| + if ob, err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: txid, Clean: true}); err != nil || ob != nil { t.Fatal(err) } |
| + v := readView(t, "instances/h") |
| + if v.Lock.Release == nil || v.Lock.Release.TXID != txid || v.Lock.Owner != "released/v1;ref=a;iid=i-a" { t.Fatalf("%+v", v) } |
| +} |
| +func TestFailedMarkerPutIsAnObligationExpiryNeverDischarges(t *testing.T) { |
| + s := tombFixture(t); r := replicatorFixtureTTL(t, s, 2*time.Second); r.Finish(ctx) |
| + s.beforeWrite(func(string) { s.failNext(http.StatusServiceUnavailable) }) |
| + ob, err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Clean: true}) |
| + if err == nil || ob == nil || ob.ETag == "" { t.Fatalf("%v %+v", err, ob) } |
| + time.Sleep(3 * time.Second) |
| + if err := RetryObligation(ctx, *ob); err != nil || readView(t, "instances/h").Lock.Release == nil { t.Fatalf("retry after expiry: %v", err) } |
| +} |
| +func TestStreamCaptureOneSecond(t *testing.T) { |
| + h := heldFixture(t); h.SetMonitorInterval(time.Second) |
| + if _, db, _ := h.newStore(tempDB(t), 0); db.MonitorInterval != time.Second { t.Fatal(db.MonitorInterval) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/lease/ -run 'TestReleaseMarker|TestFailedMarkerPut|TestStreamCapture'`. It FAILs. Add `failNext` to `tombStore`. |
| +- [ ] **Step 3: Implement.** `Finish` reads the TXID from `r.db.Pos()` after `SyncAndWait`, and leaves the renewer running. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "release marker with a durable obligation; 1 s WAL capture for the stream class" |
| + |
| +### Task 8: The keep decision and the local record [own review] |
| + |
| +This is I2's one place. |
| + |
| +**Files:** |
| +- Create: `internal/hafresh/keep.go` and its test; `internal/activator/harecord.go`, `harecord_linux.go`, `harecord_other.go` and its test |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package hafresh |
| +type FileID struct{ Inode, Size uint64; MtimeNs, CtimeNs int64 } |
| +type LocalRecord struct { Marker Marker `json:"marker"`; DB FileID `json:"db"`; WALEmpty bool `json:"wal_empty"`; TreeDigest string `json:"tree_digest"` } |
| +type LocalNow struct { HaveRecord bool; Record LocalRecord; DBExists bool; DB FileID; WALEmpty bool; TreeDigest string } |
| +func DecideKeep(v View, self Self, lifetime string, now LocalNow) (keep bool, reason string) |
| +``` |
| + |
| +Reasons, in check order: |
| +- `no-marker`, `unclean`, `other-box`, `lifetime` (an empty `lifetime` counts), `no-record`, `txid`, `files-gen`, `no-db`, `db-changed`, `wal`, `tree-changed`; |
| +- `kept` when it keeps. |
| + |
| +```go |
| +package activator |
| +func recordPath(p instancePaths, host string) string // <dbPath>.release.json |
| +func writeReleaseRecord(p instancePaths, host string, rec hafresh.LocalRecord) error // write, fsync file and directory |
| +func readLocalNow(p instancePaths, host string) (hafresh.LocalNow, error) |
| +func statFileID(path string) (hafresh.FileID, error) // linux: unix.Stat; !linux: error |
| +func treeDigest(filesDir, envFile string) (string, error) // linux: sorted metadata walk; an absent dir hashes as "absent"; !linux: error |
| +``` |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestDecideKeep(t *testing.T) { // hafresh |
| + self := Self{Ref: "a", IID: "i-a"} |
| + m := Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 9, FilesGen: "3:ab", Clean: true} |
| + rec := LocalRecord{Marker: m, DB: FileID{1, 2, 3, 4}, WALEmpty: true, TreeDigest: "d"} |
| + ok := LocalNow{HaveRecord: true, Record: rec, DBExists: true, DB: rec.DB, WALEmpty: true, TreeDigest: "d"} |
| + if k, r := DecideKeep(View{Lock: Lock{Release: &m}}, self, "L1", ok); !k || r != "kept" { t.Fatal(r) } |
| + try := func(want string, f func(*Marker, *LocalNow, *string)) { |
| + m2, n2, l := m, ok, "L1"; f(&m2, &n2, &l) |
| + if k, r := DecideKeep(View{Lock: Lock{Release: &m2}}, self, l, n2); k || r != want { t.Errorf("want %s, got %v %s", want, k, r) } |
| + } |
| + try("unclean", func(m *Marker, _ *LocalNow, _ *string) { m.Clean = false }) |
| + try("other-box", func(m *Marker, _ *LocalNow, _ *string) { m.IID = "i-b" }) |
| + try("lifetime", func(_ *Marker, _ *LocalNow, l *string) { *l = "" }) |
| + try("txid", func(_ *Marker, n *LocalNow, _ *string) { n.Record.Marker.TXID = 8 }) |
| + try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.CtimeNs++ }) |
| + try("wal", func(_ *Marker, n *LocalNow, _ *string) { n.WALEmpty = false }) |
| + try("tree-changed", func(_ *Marker, n *LocalNow, _ *string) { n.TreeDigest = "e" }) |
| + if k, r := DecideKeep(View{}, self, "L1", ok); k || r != "no-marker" { t.Fatal(r) } |
| +} |
| +func TestTreeDigestAbsentDirStable(t *testing.T) { // Review Focus 4 |
| + dir := filepath.Join(t.TempDir(), "absent"); env := filepath.Join(t.TempDir(), "h.env"); os.WriteFile(env, []byte("A=1\n"), 0o600) |
| + a, err1 := treeDigest(dir, env); b, err2 := treeDigest(dir, env) |
| + if err1 != nil || err2 != nil || a != b { t.Fatalf("%v %v", err1, err2) } |
| +} |
| +func TestTreeDigestSeesChmod(t *testing.T) { |
| + dir := filesTree(t, map[string]string{"report.token": "x"}); before, _ := treeDigest(dir, "") |
| + os.Chmod(filepath.Join(dir, "report.token"), 0o640) |
| + if after, _ := treeDigest(dir, ""); after == before { t.Fatal("chmod not seen") } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/activator/ -run 'TestDecideKeep|TestTreeDigest'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same, then `GOOS=darwin go build ./... && GOOS=windows go build ./...`. Expected: PASS, and both build. |
| +- [ ] **Step 5: Commit** "keep decision: a local copy only on a matching clean marker and unchanged state" |
| + |
| +### Task 9: Wake: HA acquire, then keep or restore into a clean tree [own review] |
| + |
| +**Files:** |
| +- Create: `internal/activator/hawake.go` and its test; `internal/provision/lifetimeindex.go` and its test |
| +- Modify: |
| + - `internal/activator/activator.go:95-107` (`Config` gains `HA bool`, `Self hafresh.Self`, `Lifetime func(string) (provision.LifetimeEntry, bool)`, `Migrate func(string) (hafresh.Verdict, string)`); |
| + - `:1080-1090` (`errLeaseRefused`); |
| + - `:5495-5511` (`errLeaseRefused` answers 503 with `Retry-After: 10`); |
| + - `internal/activator/backend_exec.go:716-738` (`Acquire`), `:805-860` (`restorePlain` sends HA-on hosts to `restoreHA`); |
| + - the `ExecBackend` fields (`Registry *registry.Registry`, `FilesStore release.Store`, and `views sync.Map` from host to the `hafresh.View` its acquire read); |
| + - `internal/provision/reconcile.go:36` (`ReconcileConfig.Lifetimes *LifetimeIndex`) and `:940-1100` (the scan calls `Replace` after a complete scan and `Merge` after a partial one). |
| + |
| +**Interfaces:** |
| +- Consumes: `lease.AcquireHA`, `hafresh.DecideKeep`, `readLocalNow`. `SameBoxEmpty` is nil until Task 14, so the table refuses. |
| +- Produces: |
| + |
| +```go |
| +package provision |
| +type LifetimeEntry struct{ ID string; Created time.Time } // ID = Incarnation(acct, app, host, rec.CreatedAt) |
| +type LifetimeIndex struct{ /* mu, m */ } |
| +func (x *LifetimeIndex) Replace(recs map[string]Record) |
| +func (x *LifetimeIndex) Merge(recs map[string]Record) |
| +func (x *LifetimeIndex) Lookup(host string) (LifetimeEntry, bool) |
| +``` |
| + |
| +```go |
| +package activator |
| +type errLeaseRefused struct{ reason string } |
| +func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafresh.View) (fresh bool, err error) |
| +func (b *ExecBackend) setAside(p instancePaths, host string) error // <db>.stale and <host>.stale/ (newest kept), then PurgeLocalDBArtifacts |
| +func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error // Restore into <host>.restore/, rename over; EnvItem to <host>.env; WakeItem via ImportWake; no manifest leaves an empty tree |
| +``` |
| + |
| +**Behaviour:** |
| +- **The acquire.** On an HA box, `Acquire` uses `AcquireHA`. `Fresh` answers true when the local DB is absent and `lease.HasReplica` is false. |
| +- **`restorePlain`** sends a host to `restoreHA` when `v.HAOn() || held.HA()`: |
| + - keep: log `activator: <host>: kept local`; |
| + - otherwise: `setAside`, `restoreReplica`, `restoreFilesClean`, then log `activator: <host>: restored (<reason>)`. |
| +- **The staging fallback** never runs on these hosts. |
| +- **Unmigrated hosts** take today's path unchanged. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestRestoreHAKeepsOnlyOnProof(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") // HA, Self{a,i-a}, Lifetime L1, restoreReplica seam counting calls |
| + writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 5, Clean: true}) |
| + if fresh, err := b.restoreHA(ctx, rt, markerView("a", "i-a", "L1", 5, true)); err != nil || fresh || restoreCalls != 0 { t.Fatal(err) } |
| + b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true)) |
| + if restoreCalls != 1 || !exists(dbPath(b, rt)+".stale") { t.Fatal("not set aside and restored") } |
| +} |
| +func TestRestoreHAFilesIntoCleanTree(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com"); publishManifest(t, b, rt, map[string]string{"a.txt": "s3"}) |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "local", "stray.txt": "x"}) |
| + b.restoreHA(ctx, rt, hafresh.View{Absent: true}) |
| + if readFile(t, b, rt, "a.txt") != "s3" || fileExists(b, rt, "stray.txt") { t.Fatal("tree not clean") } |
| +} |
| +func TestRestoreHANestedRenameFailureFailsWake(t *testing.T) { // Review Focus 3 |
| + b, rt := haBackendNested(t, "shop.example.com"); makeStaleUnrenamable(t, b, rt) |
| + if _, err := b.restoreHA(ctx, rt, hafresh.View{Absent: true}); err == nil { t.Fatal("wake proceeded over an old tree") } |
| +} |
| +func TestHAWakeSkipsStagingFallback(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com"); fm := stagingMirrorWithObjects(t); b.Mirror = fm |
| + b.restoreHA(ctx, rt, hafresh.View{Absent: true}) |
| + if fm.promoted { t.Fatal("staging promoted on an HA box") } |
| +} |
| +func TestLifetimeIndexReplace(t *testing.T) { // provision |
| + var x LifetimeIndex; created := time.Unix(1_700_000_000, 0) |
| + x.Replace(map[string]Record{"h": {Account: "acct", App: "app", Host: "h", CreatedAt: created}}) |
| + e, ok := x.Lookup("h"); want, _ := Incarnation("acct", "app", "h", created) |
| + if !ok || e.ID != want || !e.Created.Equal(created) { t.Fatalf("%+v", e) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAWake|TestLifetimeIndex'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestRestore|TestAcquire|TestWake'` in `./internal/activator/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA wake: one acquire table, keep on proof, otherwise restore DB and files into a clean tree" |
| + |
| +### Task 10: Files and wake-state publication; release writes the marker [own review] |
| + |
| +**Files:** |
| +- Create: `internal/activator/hafiles.go`, `internal/activator/harelease.go` and their tests |
| +- Modify: |
| + - `internal/hostfiles/publisher.go` (`Gen`); |
| + - `internal/activator/activator.go`: `:4378-4410` (`finishStop` calls `releaseHA` for HA-on entries), `:2621` (stream class on an HA box: `SetMonitorInterval(time.Second)` before `Replicate`), the wake path after `Replicate` (starts `hostFiles.Run`), `Start` (`loadOwed`), and the sweep (`retryOwed`). |
| + |
| +**Interfaces:** |
| +- Consumes: `hostfiles.Open`, `SyncDir`, `StagePlatform`, `Commit`, `ExportWake`, `StageWake`; `lease.Finish`, `ReleaseMarker`, `RetryObligation`; `writeReleaseRecord`, `statFileID`, `treeDigest`. |
| +- Produces: |
| + |
| +```go |
| +package hostfiles |
| +func (p *Publisher) Gen() string // "<seq>:<sha256 hex of the committed manifest body>" |
| +``` |
| + |
| +```go |
| +package activator |
| +func (b *ExecBackend) filesPrefix(host string) string // hibernatePrefix(host) + "/files/0/" |
| +type hostFiles struct{ /* publisher, paths, host, reg */ } |
| +func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) |
| +func (f *hostFiles) Run(ctx context.Context) // trio + wake state every 1 s when changed; app files every files_snapshot_interval when the local digest changed |
| +func (f *hostFiles) PublishPlatformNow(ctx context.Context) error |
| +func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err error) |
| +func (a *Service) releaseHA(ctx context.Context, e *actEntry) error |
| +func (a *Service) loadOwed() // <db>.release-owed.json for every registry route |
| +func (a *Service) retryOwed(ctx context.Context) // backoff 1 min doubling to 10 min; the file is deleted on nil or ErrObligationVoid |
| +``` |
| + |
| +**`releaseHA`, in order:** |
| +1. `Final`; |
| +2. `Finish`; |
| +3. `writeReleaseRecord`; |
| +4. `ReleaseMarker` with `Clean = complete && finishErr == nil`. |
| + |
| +An obligation is written to `<db>.release-owed.json` (fsynced) and queued. Before an HA acquire of a host with an owed file, `retryOwed` runs for it. If it is still owed, the wake answers `errLeaseRefused{"marker owed"}`. |
| + |
| +`FilesStore` is `release.NewS3StoreIn(ctx, cfg.Bucket, cfg.Region)` in production and `release.NewDirStore` in tests. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestFinalPublishIncompleteMarksUnclean(t *testing.T) { |
| + f := hostFilesFixture(t, map[string]string{"ok.txt": "1"}); makeUnreadable(t, f, "secret.bin") |
| + if _, complete, err := f.Final(ctx); err != nil || complete { t.Fatalf("%v %v", err, complete) } |
| +} |
| +func TestReleaseHAWritesRecordThenMarker(t *testing.T) { |
| + a, e := haServiceEntry(t, "shop.example.com") |
| + if err := a.releaseHA(ctx, e); err != nil { t.Fatal(err) } |
| + if v, rec := lockView(t, e), readRecord(t, e); v.Lock.Release == nil || v.Lock.Release.TXID != rec.Marker.TXID || !v.Lock.Release.Clean { t.Fatalf("%+v", v) } |
| +} |
| +func TestOwedMarkerRetriedBeforeAcquire(t *testing.T) { // Review Focus 2 |
| + a, e := haServiceEntry(t, "shop.example.com"); failMarkerPuts(t, e, 1); a.releaseHA(ctx, e) |
| + if !exists(owedPath(e)) { t.Fatal("obligation not persisted") } |
| + a2 := restartService(t, a); expireLease(t, e) |
| + if _, err := a2.backend.Acquire(ctx, e.route); err != nil { t.Fatalf("acquire after owed retry: %v", err) } |
| + if exists(owedPath(e)) || lockView(t, e).Lock.Release == nil { t.Fatal("owed marker not written first") } |
| +} |
| +func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| + f := hostFilesFixture(t, nil); go f.Run(ctx); writeEnv(t, f, "CARLOS_INSTANCE_KEY=k1\n") |
| + waitFor(t, 2*time.Second, func() bool { return platformEnvIn(t, f) == "CARLOS_INSTANCE_KEY=k1\n" }) |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/activator/ -run 'TestFinalPublish|TestReleaseHA|TestOwedMarker|TestTrioPublished'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same, plus `./internal/hostfiles/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA files: trio and wake state at 1 s, snapshot app files; release writes record then marker, with a durable obligation" |
| + |
| +### Task 11: Key and token producers on the holder only |
| + |
| +**Files:** |
| +- Modify: |
| + - `internal/activator/instancekey.go:254-290` (on an HA-on host, mint only when `hostfiles.Load` finds no manifest, otherwise `ErrInstanceKeyDeferred`; after a mint, `PublishPlatformNow` must succeed before the launch continues); |
| + - `internal/host/instancekeys.go:75-85`, `:138` (skip the backfill when `regionHAEnabled`); |
| + - `internal/host/schedule_wiring.go:186-205` (on an HA box, `prepare` only reads, and answers `""` if the token is absent); |
| + - `internal/activator/activator.go:5394-5404` (`ServeScheduled`, on an HA box: after the wake, fill `Authorization` from the restored env when it is `Bearer ` with no token). |
| + |
| +**Interfaces:** |
| +- Consumes: `hostFiles.PublishPlatformNow`. |
| +- Produces: `func (a *Service) fillScheduledToken(r *http.Request, rt registry.Route) error`. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestHAMintRefusedWhenManifestExists(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com"); publishManifest(t, b, rt, nil); removeEnv(t, b, rt) |
| + if _, err := b.ensureInstanceKeyFor(ctx, rt, b.pathsFor(rt)); !errors.Is(err, ErrInstanceKeyDeferred) { t.Fatal(err) } |
| +} |
| +func TestHAMintPublishedBeforeStart(t *testing.T) { |
| + b, rt := haBackend(t, "fresh.example.com") |
| + if _, err := b.ensureInstanceKeyFor(ctx, rt, b.pathsFor(rt)); err != nil { t.Fatal(err) } |
| + if !strings.Contains(platformEnv(t, b, rt), "CARLOS_INSTANCE_KEY=") { t.Fatal("key not durable before start") } |
| +} |
| +func TestHAScheduleTokenNeverMints(t *testing.T) { // internal/host |
| + t.Setenv("CARLOS_REGION_HA", "1"); dd := t.TempDir() |
| + if tok, err := scheduleToken(dd, nil, testRegistry(t))("shop.example.com"); err != nil || tok != "" || exists(filepath.Join(dd, "shop.example.com.env")) { t.Fatal(tok, err) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/host/ -run 'TestHAMint|TestHAScheduleToken'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestInstanceKey|TestSchedule'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA: instance key and admin token minted only on the holder after restore, published before start" |
| + |
| +### Task 12: The migration gate, head and local TXIDs [own review] |
| + |
| +**Files:** |
| +- Create: `internal/hafresh/migrate.go` and its test, `internal/lease/txid.go` and its test |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package hafresh |
| +type Inventory struct{ Box string `json:"box"`; At time.Time `json:"at"`; Hosts map[string]uint64 `json:"hosts"` } |
| +func InventoryKey(region, ref string) string // "control/ha-migration/<region>/<ref>.json" |
| +type MigrationInput struct { |
| + Host, Self string; HasLocal, LocalWALEmpty bool; LocalTXID uint64 |
| + RemoteExists bool; RemoteHead uint64; RowCreated, RecordCreated time.Time |
| + ViewBoxes []string; Inventories []Inventory; Tombstone, Staging bool |
| +} |
| +type Verdict int |
| +const ( Migrate Verdict = iota + 1; Wait; Refuse ) |
| +func MigrationGate(in MigrationInput) (Verdict, string) |
| +``` |
| + |
| +```go |
| +package lease |
| +func RemoteHeadTXID(ctx context.Context, bucket, prefix, region string) (txid uint64, exists bool, err error) // L0 first, deeper levels only if L0 is empty; paginates |
| +func LocalTXID(dbPath string) (txid uint64, walEmpty bool, err error) // max over <dir>/.activator-<db>-litestream/ltx/0/*.ltx (ltx.ParseFilename); walEmpty = no -wal, or size 0 |
| +``` |
| + |
| +**The gate, in order:** |
| + |
| +| Condition | Verdict, reason | |
| +|---|---| |
| +| `Tombstone` or `Staging` | `Refuse`, `move` | |
| +| a view box has no inventory | `Wait`, `inventories` | |
| +| another inventory lists the host | `Refuse`, `two-copies` | |
| +| `!HasLocal && !RemoteExists` | `Migrate`, `empty` | |
| +| `!HasLocal` | `Refuse`, `no-copy` | |
| +| `RowCreated.Before(RecordCreated)` | `Refuse`, `lifetime` | |
| +| `!LocalWALEmpty` or `LocalTXID != RemoteHead` | `Refuse`, `no-match` | |
| +| otherwise | `Migrate`, `ok` | |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestMigrationGate(t *testing.T) { |
| + base := MigrationInput{Host: "h", Self: "a", HasLocal: true, LocalWALEmpty: true, LocalTXID: 7, RemoteExists: true, RemoteHead: 7, |
| + RowCreated: time.Unix(200, 0), RecordCreated: time.Unix(100, 0), ViewBoxes: []string{"a", "b"}, |
| + Inventories: []Inventory{{Box: "a", Hosts: map[string]uint64{"h": 7}}, {Box: "b", Hosts: map[string]uint64{}}}} |
| + check := func(want Verdict, reason string, f func(*MigrationInput)) { |
| + in := base; in.Inventories = slices.Clone(base.Inventories); f(&in) |
| + if v, r := MigrationGate(in); v != want || r != reason { t.Errorf("got %v %s, want %v %s", v, r, want, reason) } |
| + } |
| + check(Migrate, "ok", func(*MigrationInput) {}) |
| + check(Wait, "inventories", func(in *MigrationInput) { in.Inventories = in.Inventories[:1] }) |
| + check(Refuse, "two-copies", func(in *MigrationInput) { in.Inventories[1] = Inventory{Box: "b", Hosts: map[string]uint64{"h": 7}} }) |
| + check(Refuse, "no-match", func(in *MigrationInput) { in.LocalTXID = 6 }) |
| + check(Refuse, "lifetime", func(in *MigrationInput) { in.RowCreated = time.Unix(50, 0) }) |
| + check(Migrate, "empty", func(in *MigrationInput) { in.HasLocal, in.RemoteExists = false, false; in.Inventories[0] = Inventory{Box: "a", Hosts: map[string]uint64{}} }) |
| + check(Refuse, "move", func(in *MigrationInput) { in.Staging = true }) |
| +} |
| +func TestLocalTXIDFromLTXNames(t *testing.T) { // lease |
| + db := filepath.Join(t.TempDir(), "h.db"); writeLTX(t, db, 1, 5); writeLTX(t, db, 6, 9) |
| + if txid, walEmpty, err := LocalTXID(db); err != nil || txid != 9 || !walEmpty { t.Fatal(txid, walEmpty, err) } |
| +} |
| +func TestRemoteHeadTXIDPaginates(t *testing.T) { |
| + s := tombFixture(t); putL0Files(t, s, "instances/h", 1100) |
| + if txid, ok, err := RemoteHeadTXID(ctx, "data", "instances/h", ""); err != nil || !ok || txid != 1100 { t.Fatal(txid, ok, err) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestMigrationGate|TestLocalTXID|TestRemoteHeadTXID'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "migration gate: one copy, matching TXID, unchanged lifetime" |
| + |
| +### Task 13: Migration pass, sleep-time migration, activation [own review] |
| + |
| +**Files:** |
| +- Create: `internal/host/hamigrate.go` and its test |
| +- Modify: |
| + - `internal/host/agent.go`. With `CARLOS_REGION_HA` on: `haActivationBlocked`, then `lease.SetSelf`, the activator HA config (`HA`, `Self`, `Lifetime`, `Migrate = migrator.Decide`), `ReconcileConfig.Lifetimes`, and the pass every 10 minutes while any host is unmigrated. |
| + - `internal/activator/harelease.go`: `finishStop` also calls `releaseHA` for an unmigrated host when `Config.Migrate` answers `Migrate`. |
| + |
| +**Interfaces:** |
| +- Consumes: `MigrationGate`, `InventoryKey`, `RemoteHeadTXID`, `LocalTXID`, `ReadLock` (for tombstones), `edgesfile.ReadLiveSnapshot` (`internal/edgesfile/snapshot.go:123`; the view is the fresh files in this box's placement), `LifetimeIndex.Lookup`, `releaseHA`. |
| +- Produces: |
| + |
| +```go |
| +package host |
| +func haActivationBlocked(reg *registry.Registry) (bool, string) |
| +type haMigrator struct{ /* deploy store, data bucket, reg, self, region, lifetimes, act */ } |
| +func (m *haMigrator) publishInventory(ctx context.Context) error // create, or replace its own key when the set changed |
| +func (m *haMigrator) Decide(ctx context.Context, host string) (hafresh.Verdict, string) // the one gate call |
| +func (m *haMigrator) Pass(ctx context.Context) (status.HAStatus, error) |
| +func (m *haMigrator) Last() *status.HAStatus |
| +``` |
| + |
| +**Behaviour:** |
| +- **A sleeping host the gate passes:** `Pass` takes the lease (the legacy row of the table), publishes the baseline (`hostFiles.Final` with the wake state), and calls `ReleaseMarker` (clean, naming itself). |
| +- **An awake host** migrates at its sleep, through `Decide`. |
| +- **Logs:** `ha: <host>: migrated` and `ha: <host>: refused (<reason>)`. |
| +- **A blocked activation** logs `ha: activation refused: <reason>`, runs this agent's life with HA off, and reports `State: "refused"`. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestMigrationPassMigratesOnlyUniqueMatchingCopies(t *testing.T) { |
| + w := haWorld(t, "a", "b") |
| + w.localCopy("a", "solo.example.com", 7); w.replicaHead("solo.example.com", 7) |
| + w.localCopy("a", "both.example.com", 3); w.localCopy("b", "both.example.com", 3); w.replicaHead("both.example.com", 3) |
| + w.inventories() |
| + if st, err := w.migrator("a").Pass(ctx); err != nil || st.Migrated != 1 || st.Refused != 1 { t.Fatalf("%+v %v", st, err) } |
| + if w.lock("solo.example.com").Lock.Release == nil || w.lock("both.example.com").Lock.Release != nil { t.Fatal("wrong host migrated") } |
| +} |
| +func TestSleepMigratesAwakeHostOnlyWhenGatePasses(t *testing.T) { // Review Focus 1 |
| + w := haWorld(t, "a", "b"); w.awake("a", "solo.example.com"); w.inventories(); w.sleep("a", "solo.example.com") |
| + if w.lock("solo.example.com").Lock.Release == nil { t.Fatal("sleep did not migrate") } |
| + w.localCopy("b", "dup.example.com", 2); w.awake("a", "dup.example.com"); w.inventories(); w.sleep("a", "dup.example.com") |
| + if w.lock("dup.example.com").Lock.Release != nil { t.Fatal("marker written while another box holds a copy") } |
| +} |
| +func TestActivationBlockedByMoveHold(t *testing.T) { |
| + reg := testRegistry(t); setHold(t, reg, "shop.example.com", "moving") |
| + if blocked, _ := haActivationBlocked(reg); !blocked { t.Fatal("activation allowed during a move") } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/host/ -run 'TestMigrationPass|TestSleepMigrates|TestActivationBlocked'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA migration: inventories, one gate, pass and sleep-time migration; activation refused during a move or import" |
| + |
| +### Task 14: Same-box recovery after expiry, with an emptiness proof [own review] |
| + |
| +This is pulled forward from P1b (gap 3). |
| + |
| +**Files:** |
| +- Create: `internal/activator/hasamebox.go` and its test |
| +- Modify: `internal/activator/backend_exec.go` (`Acquire` passes `SameBoxEmpty`) |
| + |
| +**Interfaces:** |
| +- Consumes: `hostEmptier.EmptyHost` (`internal/activator/opset.go:437-453`), `Classify`. |
| +- Produces: `func (b *ExecBackend) sameBoxEmpty(ctx context.Context, rt registry.Route) func() (bool, error)`. |
| + - It answers false for the nested layout, `Backing=unit`, a backend with no `hostEmptier`, and `cgroup.ErrNoDelegation`. |
| + - Otherwise it answers `EmptyHost(...) == nil`. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestSameBoxEmptyRefusesUnprovenLayouts(t *testing.T) { |
| + for _, tc := range []struct{ name string; rt registry.Route; emptier error; want bool }{ |
| + {"flat proven", flatRoute(), nil, true}, {"nested", nestedRoute(), nil, false}, {"unit", unitRoute(), nil, false}, |
| + {"no delegation", flatRoute(), cgroup.ErrNoDelegation, false}, {"busy", flatRoute(), errors.New("pids remain"), false}, |
| + } { |
| + if ok, _ := backendWithEmptier(t, tc.emptier).sameBoxEmpty(ctx, tc.rt)(); ok != tc.want { t.Errorf("%s: %v", tc.name, ok) } |
| + } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/activator/ -run TestSameBoxEmptyRefusesUnprovenLayouts`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA: same-box recovery after expiry only with a cgroup-empty proof" |
| + |
| +### Task 15: Move and import refusals for HA boxes |
| + |
| +**Files:** |
| +- Modify: |
| + - `internal/host/movesoffline.go:59-64` (`offlineCapable` is false when `regionHAEnabled`); |
| + - `internal/console/apiinstancemove_offline.go:384-433` (`offlineSelect` refuses when any box of either region publishes `boxchoice.Capability`, which is `region-ha-1`; this runs before `OfflineStart`, `:610`); |
| + - `internal/console/seedfloor.go:35-90` (`seedRegionReady` with `oneBox` refuses the same way). |
| + |
| +**Interfaces:** none. Copy: RHA-P1a-C1 and C2, where `%s` is `s.offlineName(code)`. |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestOfflineNotCapableWithRegionHA(t *testing.T) { |
| + if offlineCapable(func(k string) string { return map[string]string{"CARLOS_REGION_HA": "1"}[k] }, true) { t.Fatal("HA box offers offline moves") } |
| +} |
| +func TestOfflineStartRefusedForHARegionBeforeAnyWrite(t *testing.T) { // console |
| + s, f := offlineServerFixture(t, withBoxCaps("ie", "region-ha-1")) |
| + if ref := s.offlineSelect(ctx, f, "shop.example.com", "ie", "uk"); ref == nil || !strings.Contains(ref.msg, "high availability") { t.Fatalf("%+v", ref) } |
| + if f.writes() != 0 { t.Fatal("refused after a write") } |
| +} |
| +func TestImportRefusedForHARegion(t *testing.T) { |
| + s := seedServerFixture(t, withBoxCaps("ie", "region-ha-1")) |
| + if ref := s.seedRegionReady(ctx, "ie", true); ref == nil || ref.status != http.StatusConflict { t.Fatalf("%+v", ref) } |
| + if ref := s.seedRegionReady(ctx, "ie", false); ref != nil && strings.Contains(ref.msg, "high availability") { t.Fatal("plain seed refused") } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/host/ ./internal/console/ -run 'TestOfflineNotCapable|TestOfflineStartRefused|TestImportRefused'`. It FAILs. |
| +- [ ] **Step 3: Implement** with the approved copy. |
| +- [ ] **Step 4: Run** the same. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA regions refuse offline moves and imports up front" |
| + |
| +### Task 16: What Paul sees: status and `carlos system status` |
| + |
| +**Files:** |
| +- Modify: |
| + - `internal/status/snapshot.go`: `:41` (`Probes.HA`), `:475` (`BoxMetrics.HA`, private, never copied into `FleetBox`), `:1060-1075`; |
| + - `internal/host/agent.go:4155` (`p.HA = migrator.Last()`); |
| + - `internal/console/apisystemupdate.go:897-912` (`row["ha"] = b.Metrics.HA`); |
| + - `system.go:250-256` (`systemBoxRow.HA`), `:493-560` (`printSystemStatus`). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + |
| +```go |
| +package status |
| +type HARefusal struct{ Host string `json:"host"`; Reason string `json:"reason"` } |
| +type HAStatus struct { |
| + State string `json:"state"` // "on", "refused" |
| + Migrated int `json:"migrated"`; Waiting int `json:"waiting"`; Refused int `json:"refused"` |
| + RefusedHosts []HARefusal `json:"refused_hosts,omitempty"` // at most 50 |
| +} |
| +``` |
| + |
| +- [ ] **Step 1: Test** |
| + |
| +```go |
| +func TestHAStatusPrivateOnly(t *testing.T) { // internal/status, the TestFleetBoxCarries* pattern |
| + s := teststore(t); now := time.Now() |
| + status.WriteBox(ctx, s, status.CollectBox(nil, status.Probes{MachineID: "m", HA: &status.HAStatus{State: "on", Migrated: 3}}, now)) |
| + f, _ := status.BuildFleet(ctx, s, nil, now, 5*time.Minute) |
| + if strings.Contains(mustJSON(t, f), "migrated") { t.Fatal("HA leaked into fleet.json") } |
| +} |
| +func TestPrintSystemStatusHA(t *testing.T) { // root package |
| + var buf bytes.Buffer |
| + printSystemStatus(&buf, systemStatusResponse{Boxes: []systemBoxRow{{Label: "ie-1", HA: &status.HAStatus{State: "on", Migrated: 4, Refused: 1, |
| + RefusedHosts: []status.HARefusal{{Host: "dup.example.com", Reason: "two-copies"}}}}}}, "") |
| + if out := buf.String(); !strings.Contains(out, "4 hosts migrated") || !strings.Contains(out, "more than one box holds a copy") { t.Fatal(out) } |
| +} |
| +``` |
| + |
| +- [ ] **Step 2: Run** `./internal/status/ -run TestHAStatusPrivateOnly` and `. -run TestPrintSystemStatusHA`. They FAIL. |
| +- [ ] **Step 3: Implement** with copy C3 to C10. |
| +- [ ] **Step 4: Run** both. Expected: PASS. |
| +- [ ] **Step 5: Commit** "carlos system status shows each box's HA migration" |
| + |
| +### Task 17: The seeded N-box simulation [own review] |
| + |
| +**Files:** |
| +- Create in `internal/sim/regionha/`: `world_test.go`, `actions_test.go`, `invariants_test.go`, `rules_test.go`, `witness_test.go`, `sim_test.go`, `mutate.sh`, `expected-outcomes.txt`. The shape is `internal/sim/engines`, with `RHASIM_SEEDS`, `RHASIM_SEED`, `RHASIM_MUTATE`, `RHASIM_LIST` and `RHASIM_PAR`. |
| + |
| +**Interfaces:** |
| +- Consumes: `hafresh.DecideAcquire`, `DecideKeep`, `MigrationGate`, `OwnerFor`, `MarkerBody`, `DecodeLock`, the production decisions. The model supplies only I/O. |
| + |
| +**The model.** 2 to 5 boxes. Per box: a local DB position, a files tree, a release record, a pid, and an agent state (running, crashed, hung). One S3 with per-host TXID chains, and `lock.json` with ETags and conditional writes. |
| + |
| +**Actions:** request at a random box; graceful sleep; agent crash; hang past the TTL, then resume; concurrent cold wakes; a failed marker PUT, then a retry; migration with one, two or no copies; a recreated hostname; a tenant write while asleep. |
| + |
| +**Invariants:** |
| +- **I1, single writer.** Every replica write for a host came from the box whose lease was current at that step, and no two writes share a TXID. |
| +- **I2, no stale serving.** A box serves only from the S3 head, or from a copy whose marker named it with the same TXID, files generation and lifetime, unchanged since. |
| + |
| +**Mutation rules,** each to be CAUGHT: |
| +- `expiry-authorizes`, `keep-without-marker`, `keep-unclean`, `migrate-two-copies`, `marker-before-final`, `same-box-no-proof`. |
| + |
| +**Witnesses:** |
| +- a hang past the TTL, then another box's wake, is refused; |
| +- a failed marker PUT, then a retry after expiry, then another box acquires. |
| + |
| +- [ ] **Step 1: Write** the world, actions, invariants, rules and witnesses. |
| +- [ ] **Step 2: Run** `RHASIM_SEEDS=200 nice -n 19 go test ./internal/sim/regionha/ -run 'TestRegionHA|TestWitnesses|TestEveryActionFires' -count=1`. Expected: PASS. |
| +- [ ] **Step 3: The one sweep for this revision:** |
| + |
| +```bash |
| +D=$(mktemp -d -p "$TMPDIR" rhasim.XXXXXX); go test -c -o "$D/regionha.test" ./internal/sim/regionha/ |
| +RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D" |
| +``` |
| + |
| + Expected: every rule `CAUGHT`; none `MISSED` or `ERROR`. |
| +- [ ] **Step 4: Commit** "region HA simulation: single writer and no stale serving over N boxes, with mutation checks" |
| + |
| +### Task 18: Dev rollout on the two IE boxes. Needs Paul's go before anything touches dev. |
| + |
| +- [ ] **Step 1: Ask Paul for the go.** Give him: |
| + - the release tag; |
| + - the boxes (`platform-infrastructure/dev/region-ie.tf`, `region-ie-b.tf`); |
| + - the switch: `CARLOS_REGION_HA=1` in `/etc/carlos/host.env`; |
| + - the rollback: unset it and restart the agent; |
| + - the cost: §18's lines, plus one restore per instance. |
| + |
| + Nothing below runs without his explicit yes. |
| +- [ ] **Step 2: Release and roll** by the platform roll recipe (README): dev boxes, dev console, check. Verify the version by `X-Carlos-Version`. |
| +- [ ] **Step 3: Pre-check.** `carlos system status` shows both IE boxes on the release, and no move or import is in flight. |
| +- [ ] **Step 4: Switch on** both boxes, then restart the agents one after the other. Expected in the journal: `ha: <host>: migrated` or `ha: <host>: refused (<reason>)` for every local host. |
| +- [ ] **Step 5: Paul's view.** `carlos system status` shows, per IE box, "high availability: N hosts migrated, …" with the refused hosts named. Each refusal is fixed or accepted, and recorded. |
| +- [ ] **Step 6: Per-host checks** on a test app and on `wakecheck`. Expected lines, in order: |
| + 1. through A: `restored (no-marker)`; |
| + 2. sleep, then through A: `kept local`; |
| + 3. through B: `restored (other-box)`; |
| + 4. through A: `restored (other-box)`. |
| + |
| + Data written on each box survives on the other. |
| +- [ ] **Step 7: Refusals.** A move of an IE host to UK is refused with C1, and an import into IE with C2. Neither stops anything. |
| +- [ ] **Step 8: Kill drill.** `kill -9` A's agent while a flat-layout test host is awake. |
| + - Wakes through B are refused (`another box's expired lease`). |
| + - When A's agent restarts after expiry, the host comes back on A by the proof, with `restored (no-marker)`. |
| + - Record the downtime: at most the 15-minute TTL plus the restore. |
| +- [ ] **Step 9: Hang drill.** `SIGSTOP` A's agent for 20 minutes while a host is awake. |
| + - B never takes the host. |
| + - After `SIGCONT`, A stands the instance down on its lost lease, and re-takes it with the proof. |
| + - Record the timeline, and that no write from B reached the replica. |
| +- [ ] **Step 10: Report** on the branch's discussion: the counts, the drill timelines, and 24 hours of observed cost. |
| + |
| +## Census |
| + |
| +| Row (root-run) | Change | Class expected | |
| +|---|---|---| |
| +| `internal/host/systemparticipation.go` `(*systemApplier).beginExecutableChange` | the `regionHA` arms removed (Task 4) | body | |
| +| `internal/host/systemapply.go`: the `systemApplier` construction (`:134`) and its field (`:259-262`) | the field removed | body | |
| +| `internal/host/joinroot.go`, the root `system join` verb | removed (Task 2) | removed | |
| +| `internal/host/units/carlos-system-join.service`, `.path` | external units removed | removed | |
| +| `internal/host/bootstrap.go`: `enabledUnits` and `retireUnits` (`carlos bootstrap`, self-update apply) | unit removal under `/etc/systemd/system` | sites, or `new` for `retireUnits`: then a decision for Paul | |
| +| `system.go` `runSystem` dispatch | the join verb removed | body | |
| + |
| +The other changed units with I/O are agent-run. They come out as `body`, `sites` or envelope re-pins (`internal/lease`, `internal/activator`, `internal/host`, `internal/provision`, `internal/hostfiles`), approved the same way. `internal/hafresh` does no I/O. |
| + |
| +## Copy (pending Paul's review) |
| + |
| +| Id | String | |
| +|---|---| |
| +| RHA-P1a-C1 | `%s has high availability turned on. offline moves into or out of it are not available yet` | |
| +| RHA-P1a-C2 | `%s has high availability turned on. imports into it are not available yet` | |
| +| RHA-P1a-C3 | `high availability: %d hosts migrated, %d waiting, %d refused` | |
| +| RHA-P1a-C4 | `high availability is off on this box: a move or import is in progress` | |
| +| RHA-P1a-C5 | ` %s refused: %s` | |
| +| RHA-P1a-C6 | `two-copies`: `more than one box holds a copy` | |
| +| RHA-P1a-C7 | `no-match`: `the local copy does not match the replica` | |
| +| RHA-P1a-C8 | `lifetime`: `the local copy belongs to an earlier instance with this hostname` | |
| +| RHA-P1a-C9 | `no-copy`: `no box holds a copy, but a replica exists` | |
| +| RHA-P1a-C10 | `move`: `a move is in progress for this host` | |
| + |
| +## Spec gaps found while planning |
| + |
| +1. **A held lease cannot say whether its host is migrated.** The owner format `box/v1;ref;iid;pid` ships on every box. The plan appends `;ha=1` for HA-on hosts. Only the owner survives litestream's renewals. |
| +2. **The marker's field list omits `clean`,** which §5.2 relies on. The plan puts it inside `carlos_release`. |
| +3. **P1a has no termination check, and same-box recovery is in P1b.** So any agent crash on a dev IE box would strand its HA-on hosts. The plan pulls §9.6's proof forward (Task 14), which Task 18's kill drill needs. |
| +4. **The marker lifetime is `provision.Incarnation`,** which needs the record's `CreatedAt`. Registry rows lack it. The plan feeds it from the reconcile pass (`LifetimeIndex`), and a host not yet indexed restores. "Never re-pointed" is `row.CreatedAt >= record.CreatedAt`; clock skew errs toward refusal. |
| +5. **§8.3's per-app files setting has no door in any plan.** P1a publishes app files on the snapshot cadence only (H8). The 10 s continuous class lands with the door, so nothing sits dormant. |
| +6. **P0 item 4 is deferred** to the plans that build each replacement: P1b for the latch and roles, P2 for capacity and the metric start. That item rewrites the claim halves of `nocapacity.go`, `regioncapacity.go`, `apiboxroles.go` and `system_roles.go`, cuts `termfence.Box`, and turns `SetHosting` into the latch. Those halves run only with `CARLOS_HOST_CLAIM` on. |
| +7. **Readiness belongs to P2's console door.** P1a shows migration through the box status snapshot and `carlos system status` instead. |
| +8. **"A one-time inventory" would go stale.** The plan replaces the box's own inventory key whenever its set of copies changes. |