plan rev 2: region HA P1a, Astra plan round 1
HA state is sticky per host: every release of an HA-on host (sleep, failed wake, lease loss, shutdown) goes through one marker release with the persisted obligation, never a delete, and every box applies the HA rules to HA-on hosts whatever CARLOS_REGION_HA says; rollback only stops new migrations. Fresh shortcut removed: empty baselines only through the gate. Migration acquires first and updates the inventory before any release. Secrets gated on an absent manifest and published before every launch. Relocations named for the P0 deletions and surviving tests listed; adapters and the shared leasetest fixture named; identifiers compile-checked. Publisher owned by the entry; owner identity set on every box; simulation and drill strengthened. Disposition table at top.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+391
−247
docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md+391 −247
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| index 964f070e2..0b8a2bab4 100644 |
| --- 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 |
| @@ -2,64 +2,90 @@ |
| > **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. |
| +**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, and otherwise restores from S3 into a clean tree. Migration admits hosts one at a time under their own lease, 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. |
| +**Architecture:** A new pure package, `internal/hafresh`, holds the 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 acquire, the one marker release 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. |
| + |
| +A host's HA state is **sticky**: once its lock carries a marker or a `;ha=1` owner, every box running this release applies the HA rules to it, whatever `CARLOS_REGION_HA` says. The switch gates only new migrations and the move refusals. |
| **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. |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6 (approved, 0e53c932). In scope: §4.2, §5, §7.3, §8.2, §8.4, the P1a rows of §9.4, §9.6, §14's refusals, §16.3 items 1, 2, 3 and 5, and §19's first slice. |
| + |
| +**Rev 2** answers Astra plan round 1 (`docs/superpowers/notes/reviews/ASTRA-FINDINGS-region-ha-p1a-plan-r1.md`, 1a54f1db, round 1 of 3). Paul has also ruled since rev 1: Task 14 is in P1a, app files stay on the snapshot cadence in P1a, and execution is subagent-driven. |
| + |
| +| Finding | Fix | Task | |
| +|---|---|---| |
| +| F1 failed wakes delete the lock | HA state is sticky: no path deletes an HA-on lock. Every release (sleep, failed wake, lease loss, shutdown) goes through one marker release with the persisted obligation; `clean: false` unless the clean conditions hold. Witness: failed restore, then a stale copy elsewhere restores. | 7, 10 | |
| +| F2 `Fresh` skips the gate | `Fresh` removed. An empty baseline is admitted only by the gate, which needs every inventory to show no copy. Witness: an existing host with a copy on B and nothing in S3; A is refused. | 6, 12, 13 | |
| +| F3 validate before acquire | Migration takes the lease first, then reads head and inventories, gates, and publishes, all under the lease. It writes a clean marker only if `Final` is complete. A box updates its inventory before it releases any unmigrated host. Interleaving witness added. | 13 | |
| +| F4 secrets gate | Both producers are gated on the manifest being absent. Before every launch of an HA-on host, retries included, `<host>.env` must match the manifest's `host.env` item or be published and acknowledged. Two witnesses. | 11 | |
| +| F5 deletions leave shared code | Relocations named: the edges scheduler wrapper and `agentEntry` and its group-reference wait. Every surviving test listed. | 1, 2, 4 | |
| +| F6 interfaces don't connect | `Migrate` and `Decide` agree. Adapters named (`execLease`, `haLease`, `haRep`). The shared lease fixture moves to `leasetest`. Referenced identifiers compile-checked against this branch. | 6 to 13 | |
| +| F7 owed-marker oracle | Asserts request order and the new holder. | 10 | |
| +| F8 rollback re-enables stale reuse | Sticky HA. Rollback only stops new migrations. A full un-migrate is a follow-up. | 6, 9, 18 | |
| +| F9 publisher lifetime | The publisher is owned by the entry; stop-and-join before `Final`; cleanup on failed wake and lease loss. Witness: no write after the marker. | 10 | |
| +| F10 owner identity conditional | The box reference is set before any acquire, whatever the switch. IID read with a 2 s bound, then retried each minute. Witness through the agent wiring. | 5 | |
| +| F11 simulation too weak | I1 covers manifest writes and running exclusivity; I2 reuse needs a clean marker. Witnesses added. | 17 | |
| +| F12 drill steps | Sleep the holder and check the marker before each cross-box wake; a starting state for each reason. | 18 | |
| ## 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). |
| +- **Owner:** `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>`. `iid=` is omitted when unknown. A lock of an HA-on host carries `;ha=1` (spec 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` (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. |
| + - the DB file's inode, size, `mtime_ns` and `ctime_ns`, and whether `-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. Metadata only. |
| +- **`clean`:** the final sync succeeded, and the final files publish was complete (`hostfiles.SyncStats` with no `TooLarge`, `NotRegular` or `Unreadable`). Every other release writes `clean: false`. |
| +- **Sticky HA state:** no code path deletes the lock of an HA-on host. Expiry never lets another box acquire it. A failed marker PUT ends only on success or a 412. |
| +- **Cadences:** the H6 trio and the wake state publish at about 1 s. App files publish every `files_snapshot_interval`, 15 minutes (H8; Paul confirmed snapshot only in P1a). The stream class captures the WAL every 1 s while its host is HA-on. |
| +- **Switch:** `CARLOS_REGION_HA` (`strconv.ParseBool`) gates only migration, the inventory, the `region-ha-1` capability and the move and import refusals. |
| + - The owner format, the box reference and every HA-on host's rules run on every box. |
| + - 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; |
| + - failed marker: 1 PUT per retry; |
| + - migration: 1 LIST (L0) per host once + the baseline publish + 1 inventory PUT when a box's copy set changes; |
| - 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. |
| + On a box with no HA-on host, an acquire costs what it does today: the create PUT, then a GET only when a lock exists. No new periodic S3 poll. |
| +- **Cross-compile:** darwin and windows. 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. |
| +- **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`. Go commands may need the sandbox off ("read-only file system" from the build cache). Leave `GOCACHE` at its default. |
| ## 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`. |
| +1. **A host awake at activation** holds a lease without `;ha=1`. Its sleep migrates it only when the gate passes, under its lease, after the inventory lists it. Task 13: `TestSleepMigratesAwakeHostOnlyWhenGatePasses`. |
| +2. **An agent restart with a marker owed.** The marker is retried before the acquire, and expiry never drops it. Task 10: `TestOwedMarkerRetriedBeforeAcquire`. |
| +3. **The nested layout.** Set-aside and clean restore use `pathsFor`, and a failed rename fails the wake. Task 9: `TestRestoreHANestedRenameFailureFailsWake`. |
| +4. **A host with no files directory and no manifest.** The digest of an absent directory is stable. Task 8: `TestTreeDigestAbsentDirStable`. |
| +5. **A box with the switch off and an HA-on host.** It still refuses another box's expired lease and keeps only on proof. Task 9: `TestHAOnHostRulesHoldWithSwitchOff`. |
| --- |
| -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. |
| +Tasks 1 to 4 are P0; 5 to 16 are the slice; 17 is the simulation; 18 is the dev rollout. |
| +- **[own review]** marks stopping rule 3; the whole-branch review covers the rest. |
| +- **Run steps** are `nice -n 19 go test <pkg> -run '<names>' -count=1`. Each FAILs before the implementing step and PASSes after. |
| +- **Execution** is subagent-driven: each task's implementer sees only that task plus the Global Constraints. |
| ### 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`. |
| +- Modify: `internal/host/edgesfile.go:455` (signature), `:526` (drop `applyEdgesClaims`), `:734-757`, `:983-988`, `:1001` |
| +- Create: `internal/host/edgesschedule.go`. It receives `edgesLoopState`, moved from `internal/host/edgesclaims.go:241-300` without its `claims`, `claimsNext` and `claimDue` fields and with the asset-cache scheduling (`assetDue`, `dueWith`) unchanged. |
| +- Delete: `internal/host/edgesclaims.go` |
| +- Tests to update: |
| + - `internal/host/edgesclaims_test.go`: move the scheduler and asset tests to `edgesschedule_test.go`, and delete the claim tests; |
| + - `edgesfile_test.go`, `boxaddress_test.go`, `assetpublish_test.go` and `movesoffline_e2e_test.go`: replace each `newEdgesClaims(...)` or `claims` argument with an `AddressSource` or `nil`. |
| **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. |
| +- 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`, and `edgesLoopState{sched *edgesFileSchedule; schedDue, assetDue bool}` with `due`, `dueWith`, `timed`, `done` as today. `addrs` is `boxAddressSource(os.Getenv)` when `CARLOS_REGION_HA` is on. |
| - [ ] **Step 1: Test** |
| @@ -76,19 +102,23 @@ func TestEdgesFileRegionHAPublishesAddressWithoutClaimRead(t *testing.T) { |
| ``` |
| - [ ] **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" |
| +- [ ] **Step 3: Implement** the move, the parameter change and the deletion. |
| +- [ ] **Step 4: Run** `-run 'TestEdgesFile|TestBoxAddress|TestEdgesSchedule|TestAsset|TestMovesOffline'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "P0: edges file reads box addresses directly; scheduler moved; claim read 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/agententry.go`. It receives `agentEntry`, `awaitGroupReference` and `groupReferenceBackoff` from `internal/host/joining.go:247-296`. `agentEntry` loses its `gate` parameter: `func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any), run func())`. |
| - Create: `internal/host/retiredunits.go` |
| +- Delete: `internal/host/joining.go` (including `hostingGate`, `decideAgentMode` and `agentHosting`), `joinmode.go`, `joinroot.go`; `internal/host/units/carlos-system-join.service`, `.path` |
| +- Modify: `internal/host/agent.go:229-231` (the call loses the gate); `internal/host/claimwiring.go:102-106` (drop the `SetHosting` calls; gap 6); `internal/host/bootstrap.go:166-176`; `system.go:54`, `:104-106`, `:188` |
| +- Tests: |
| + - `internal/host/joining_test.go`: move `TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts` and `TestAwaitGroupReferenceStopsWithItsContext` to `agententry_test.go`, adjusted for the new signature, and delete the rest; |
| + - `internal/host/claimwiring_hosting_test.go`: delete. |
| **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. |
| +- Produces: `var retiredUnits = []string{"carlos-system-join.path", "carlos-system-join.service"}` and `func retireUnits(root string, units []string) error`. It 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** |
| @@ -99,26 +129,26 @@ func TestBootstrapRetiresJoinUnits(t *testing.T) { // internal/host |
| 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 |
| +func TestSystemJoinVerbGone(t *testing.T) { // root package |
| 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" |
| +- [ ] **Step 3: Implement** the move, the deletions and `retireUnits`. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestBootstrap|TestSystemUnits|TestAGroupBox|TestAwaitGroupReference'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "P0: joining mode, carlos system join and its units removed; group-reference wait kept" |
| ### 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) |
| +- Modify: `internal/console/hostclaimops.go:44-61` (drop the `s.cfg.RegionHA` branch; the capacity metric's start moves with P2) |
| **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 1: Delete,** then run `go build ./... && go vet ./internal/console/ ./internal/hostactors/...`. Expected: clean. First move any claims-off witness out of a deleted test file. |
| +- [ ] **Step 2: Run** `./internal/console/ -run 'TestClaimRecovery|TestHostClaimOps|TestNoCapacity'`. Expected: PASS. |
| - [ ] **Step 3: Commit** "P0: console enrolment pass and AWS membership read removed" |
| ### Task 4: P0. `beginExecutableChange` drops its region-HA arm [own review] |
| @@ -126,31 +156,39 @@ func TestSystemJoinVerbGone(t *testing.T) { // root package, system_test.go |
| Root runs this. |
| **Files:** |
| -- Modify: `internal/host/systemparticipation.go:47-110`; `internal/host/systemapply.go:134` and `:259-262` (the `regionHA` field goes) |
| +- Modify: `internal/host/systemparticipation.go:47-110`; `internal/host/systemapply.go:134` and `:259-262` (the field goes) |
| +- Tests to update, each listed by its `regionHA = true` line: |
| + - `systemparticipation_test.go:50`, `:83`, `:98`, `:112`; |
| + - `guardparticipation_test.go:22`, `:110`; |
| + - `participation_flagoff_test.go:16`; |
| + - `plan9_a_guard_test.go:99`; |
| + - `rootexecution_update_test.go:26`. |
| -**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. |
| + A test whose subject is the region-HA-only behaviour (the legacy update-begun marker, or a deferral with no participation required) is deleted. A test that set the field only to reach the guard path makes participation required through its fixture's disk instead. Record each decision in the commit message. |
| + |
| +**Interfaces:** none. With no participation required it returns nil and writes no marker. `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 |
| + mkdirAll(t, filepath.Join(a.dataDir, ".hostexec")) |
| 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 2: Run** `./internal/host/ -run TestBeginExecutableChangeIgnoresRegionHA`. It FAILs (`errSystemDeferred`). |
| +- [ ] **Step 3: Implement.** Return nil when `!required`, take the `WithParticipation` arm otherwise, and delete the field. Then update the listed tests. |
| +- [ ] **Step 4: Run** `-run 'TestBeginExecutableChange|TestSystemApply|TestGuardParticipation|TestParticipation|TestPlan9A|TestRootExecution'`. Expected: PASS. |
| - [ ] **Step 5: Commit** "P0: system apply no longer reads CARLOS_REGION_HA for claim participation" |
| -### Task 5: The owner format, unconditional |
| +### Task 5: The owner and the box reference, on every box |
| **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) |
| +- Create: `internal/hafresh/owner.go` and its test; `internal/lease/self.go`; `internal/host/haself.go` and its test |
| +- Modify: `internal/lease/lease.go:186-190`, `internal/lease/createlease.go:32`; `internal/host/agent.go:229-240` (inside `run`, before the activator is built and whatever the switch: `lease.SetSelf(haSelfNow(...))`, then `go haSelfRetry(...)`) |
| **Interfaces:** |
| - Produces: |
| @@ -160,24 +198,25 @@ 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 |
| +func ParseOwner(s string) (Owner, bool) // strict: 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) |
| +func SetSelf(s hafresh.Self) // atomic; safe to call again when the IID arrives |
| +func currentOwner(ha bool) string |
| ``` |
| ```go |
| package host |
| -func haSelf(ctx context.Context) (hafresh.Self, error) // Ref: metricsBoxLabel(os.Getenv, readMachineID()); IID: recordInstanceID(readIdentityRecord(...)), retried each minute |
| +func haSelfNow(getenv func(string) string, client *http.Client) hafresh.Self // Ref = metricsBoxLabel(getenv, readMachineID()); IID from one identity-document read, 2 s client timeout; "" on failure |
| +func haSelfRetry(ctx context.Context, getenv func(string) string, client *http.Client, every time.Duration) // while IID == "", every minute; SetSelf on success |
| ``` |
| - [ ] **Step 1: Test** |
| ```go |
| -func TestOwnerRoundTrip(t *testing.T) { |
| +func TestOwnerRoundTrip(t *testing.T) { // hafresh |
| 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) } |
| @@ -186,29 +225,43 @@ func TestOwnerRoundTrip(t *testing.T) { |
| } |
| 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) } |
| +func TestAgentWiringSetsOwnerWithSwitchOff(t *testing.T) { // internal/host: F10 |
| + fx := leasetest.NewLockFixture(t); imds := fakeIMDS(t, "i-0abc") // answers the identity document |
| + getenv := envOf(map[string]string{"CARLOS_REGION_HA": "", "CARLOS_STATUS_LABEL": "ie-box"}) |
| + lease.SetSelf(haSelfNow(getenv, imds.Client())) |
| + h, err := lease.Acquire(ctx, fx.Bucket, "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) } |
| + if o, ok := hafresh.ParseOwner(fx.Lock("instances/h").Owner); !ok || o.Ref != "ie-box" || o.IID != "i-0abc" || o.HA { t.Fatalf("%+v %v", o, ok) } |
| } |
| ``` |
| -- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestOwnerRoundTrip|TestAcquireWritesBoxOwner'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/host/ -run 'TestOwnerRoundTrip|TestAgentWiringSetsOwnerWithSwitchOff'`. It FAILs. `leasetest.NewLockFixture` comes from Task 6, so land Task 6's fixture commit first, or write this test after it. |
| - [ ] **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" |
| +- [ ] **Step 4: Run** the same, plus `./internal/lease/ -run TestTombstone`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "lease owner names the box on every box: box/v1;ref;iid;pid" |
| -### Task 6: The acquire table and `AcquireHA` [own review] |
| +### Task 6: The acquire table, sticky HA in `lease.Acquire`, and the shared fixture [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 |
| +- Create: `internal/lease/leasetest/lockfixture.go` (a public fixture both `package lease` and `package lease_test` tests use); `internal/hafresh/lock.go`, `internal/hafresh/acquire.go` and its test; `internal/lease/ha.go` and its test (`package lease`) |
| +- Modify: `internal/lease/lease.go:172-219` (`AcquireTTL`: create first; on a present lock, read the view; an HA-on view goes through the table, any other through litestream's `AcquireLease` as today) |
| **Interfaces:** |
| - Produces: |
| +```go |
| +package leasetest |
| +type LockFixture struct{ Bucket string /* server, hooks */ } |
| +func NewLockFixture(t *testing.T) *LockFixture // sets AWS_* and CARLOS_S3_ENDPOINT like tombFixture |
| +func (f *LockFixture) PutLock(prefix string, body []byte) |
| +func (f *LockFixture) Lock(prefix string) litestream.Lease |
| +func (f *LockFixture) LockBody(prefix string) []byte |
| +func (f *LockFixture) Writes() []string // "PUT <key>" / "DELETE <key>", in order |
| +func (f *LockFixture) FailNext(method string, status int) |
| +``` |
| + |
| ```go |
| package hafresh |
| type Marker struct { |
| @@ -222,47 +275,41 @@ type Lock struct { |
| 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 |
| +func (v View) HAOn() bool // Release != nil, or an owner that parses with HA |
| type Action int |
| -const ( ActCreate Action = iota + 1; ActTake; ActHeld; ActRefuse ) |
| +const ( ActTake Action = iota + 1; 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 |
| +func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision // HA-on views only |
| ``` |
| ```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 |
| +func SetSameBoxProof(prefix string, proof func() (bool, error)) // consulted once by the next Acquire of prefix (Task 14) |
| +func (h *Held) HA() bool // the lock this handle wrote carries ;ha=1 |
| +func (h *Held) View() hafresh.View // what the acquire read: Absent for a create |
| ``` |
| -**`DecideAcquire`** (spec §9.4, P1a rows): |
| +**`DecideAcquire`, for an HA-on view:** |
| | Lock | Action, reason | |
| |---|---| |
| -| absent | `ActCreate`, `absent` | |
| -| `Release != nil` | `ActTake`, `release marker` | |
| -| owner `moved:*`, expired | `ActTake`, `lifted tombstone` | |
| +| `Release != nil` (clean or not) | `ActTake`, `release marker` | |
| | 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) | |
| +| expired, own non-empty IID | `ActTake` if `SameBoxEmpty` says true, else `ActRefuse`, `same box without emptiness proof` | |
| +| expired, other box | `ActRefuse`, `another box's expired lease` | |
| -**`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. |
| +**`AcquireTTL`:** |
| +1. Create, with `If-None-Match: *` and a non-HA owner, as today. |
| +2. On a present lock, GET it with its ETag. |
| +3. A view that is not HA-on takes the legacy path: litestream's `AcquireLease`, which includes the lifted-tombstone case and the unmigrated hosts. |
| +4. An HA-on view: decide; a take uses `If-Match`, generation + 1 and `currentOwner(true)`. |
| +5. On 412, re-read, at most 3 rounds. |
| +6. Start the renewer with the returned ETag. |
| -`ActHeld` returns `*HeldError`; `ActRefuse` returns `*RefusedError`. |
| +`ActHeld` returns `*HeldError`; `ActRefuse` returns `*RefusedError`. On an absent lock the cost is unchanged: one PUT. |
| - [ ] **Step 1: Test** |
| @@ -272,18 +319,16 @@ func TestDecideAcquireTable(t *testing.T) { // hafresh |
| 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{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b", Clean: false}}}, 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) } |
| } |
| + if (View{Lock: Lock{Owner: OwnerFor(self, 1, false)}}).HAOn() || !(View{Lock: Lock{Owner: mine}}).HAOn() { t.Fatal("HAOn") } |
| } |
| func TestMarkerReadAsFreeByOldReaders(t *testing.T) { // lease |
| body, _ := hafresh.MarkerBody(7, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: 12, Clean: true}) |
| @@ -291,80 +336,94 @@ func TestMarkerReadAsFreeByOldReaders(t *testing.T) { // 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) } |
| +func TestAcquireTakesMarkerAsHAThenRenews(t *testing.T) { // lease, Review Focus 5 of rev 1 |
| + fx := leasetest.NewLockFixture(t); SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + body, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}); fx.PutLock("instances/h", body) |
| + h, err := AcquireTTL(ctx, fx.Bucket, "instances/h", "", 3*time.Second) |
| + if err != nil || !h.HA() || h.View().Lock.Release == nil { t.Fatal(err) } |
| 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{}) |
| +func TestAcquireRefusesOtherBoxExpiredHALease(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t); SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| + fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), time.Now().Add(-time.Hour))) |
| + _, err := Acquire(ctx, fx.Bucket, "instances/h", "") |
| var r *RefusedError |
| - if !errors.As(err, &r) || slices.Contains(s.methods(), http.MethodPut) { t.Fatalf("%v %v", err, s.methods()) } |
| + if !errors.As(err, &r) || len(fx.Writes()) != 1 { t.Fatalf("%v %v", err, fx.Writes()) } // only the failed create |
| +} |
| +func TestAcquireLegacyExpiredStillTakes(t *testing.T) { // an unmigrated host behaves as today |
| + fx := leasetest.NewLockFixture(t) |
| + fx.PutLock("instances/h", leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour))) |
| + if h, err := Acquire(ctx, fx.Bucket, "instances/h", ""); err != nil || h.HA() { t.Fatal(err) } |
| } |
| ``` |
| -- [ ] **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" |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestDecideAcquireTable|TestMarkerReadAsFree|TestAcquireTakes|TestAcquireRefuses|TestAcquireLegacy'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `leaseBody` is a test helper in `ha_test.go`. |
| +- [ ] **Step 4: Run** the same, plus `./internal/lease/` with `-run 'TestAcquire|TestTombstone|TestLockState|TestFastAcquire'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "acquire: HA-on locks go through the one table; expiry never authorizes another box" |
| -### Task 7: The release marker, its obligation, and stream capture [own review] |
| +### Task 7: The one marker release, 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) |
| +- Create: `internal/lease/release.go` and its test (`package lease`) |
| +- Modify: `internal/lease/lease.go:401-429` (`newStore` uses the Held's monitor interval), `:435-445` (`Replicator` keeps the generation and the HA flag) |
| **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 (h *Held) SetMonitorInterval(d time.Duration) // 0 keeps dbMonitorInterval (10 s) |
| +func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) (*Obligation, error) // before replication |
| +func (r *Replicator) Finish(ctx context.Context) (txid uint64, err error) // SyncAndWait + store close; renewer still running |
| func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) (*Obligation, error) |
| +func (r *Replicator) HA() bool |
| 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: |
| +Both `ReleaseMarker` methods call one private `releaseWithMarker(ctx, leaser, cur *litestream.Lease, m)`. It stops the renewer and PUTs `MarkerBody(cur.Generation, m)` with `If-Match: cur.ETag`: |
| - success: `(nil, nil)`; |
| - 412: `(nil, ErrObligationVoid)`; |
| - otherwise: `(&Obligation{exact body and ETag}, err)`. |
| -**`RetryObligation`** sends the same conditional PUT. It never reads expiry. |
| +This also holds after the renewer has latched a loss: the ETag is still the last one written. `RetryObligation` sends the same PUT and never reads expiry. Calling `Release` on a handle whose `HA()` is true is a programming error: it returns `ErrHAReleaseNeedsMarker` and deletes nothing. |
| - [ ] **Step 1: Test** |
| ```go |
| func TestReleaseMarkerOverwritesLock(t *testing.T) { |
| - s := tombFixture(t); r := replicatorFixture(t, s) |
| + fx := leasetest.NewLockFixture(t); r := haReplicator(t, fx, "instances/h") |
| 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) } |
| + if v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), ""); v.Lock.Release == nil || v.Lock.Release.TXID != txid { t.Fatalf("%+v", v) } |
| +} |
| +func TestHeldReleaseOfHALeaseNeverDeletes(t *testing.T) { // F1 |
| + fx := leasetest.NewLockFixture(t); h := haHeld(t, fx, "instances/h") |
| + if err := h.Release(ctx); !errors.Is(err, ErrHAReleaseNeedsMarker) { t.Fatal(err) } |
| + if slices.ContainsFunc(fx.Writes(), func(w string) bool { return strings.HasPrefix(w, "DELETE") }) { t.Fatal("HA lock deleted") } |
| + if _, err := h.ReleaseMarker(ctx, hafresh.Marker{V: 1, Box: "a", IID: "i-a"}); err != nil { t.Fatal(err) } |
| } |
| 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) }) |
| + fx := leasetest.NewLockFixture(t); r := haReplicatorTTL(t, fx, "instances/h", 2*time.Second); r.Finish(ctx) |
| + fx.FailNext(http.MethodPut, 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) } |
| + if err := RetryObligation(ctx, *ob); err != nil { t.Fatalf("retry after expiry: %v", err) } |
| } |
| func TestStreamCaptureOneSecond(t *testing.T) { |
| - h := heldFixture(t); h.SetMonitorInterval(time.Second) |
| + h := haHeld(t, leasetest.NewLockFixture(t), "instances/h"); 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 2: Run** `./internal/lease/ -run 'TestReleaseMarker|TestHeldReleaseOfHA|TestFailedMarkerPut|TestStreamCapture'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `haHeld` and `haReplicator` are test helpers: an acquire over a marker, then `Replicate` over a temp DB. |
| - [ ] **Step 4: Run** the same. Expected: PASS. |
| -- [ ] **Step 5: Commit** "release marker with a durable obligation; 1 s WAL capture for the stream class" |
| +- [ ] **Step 5: Commit** "one marker release for held and replicating handles, with a durable obligation; HA locks are never deleted" |
| ### Task 8: The keep decision and the local record [own review] |
| @@ -391,10 +450,10 @@ Reasons, in check order: |
| ```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 writeReleaseRecord(p instancePaths, host string, rec hafresh.LocalRecord) error |
| 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 |
| +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** |
| @@ -410,7 +469,7 @@ func TestDecideKeep(t *testing.T) { // hafresh |
| 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("unclean", func(m *Marker, n *LocalNow, _ *string) { m.Clean = false; n.Record.Marker.Clean = false }) // a matching but unclean pair |
| 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 }) |
| @@ -436,20 +495,20 @@ func TestTreeDigestSeesChmod(t *testing.T) { |
| - [ ] **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] |
| +### Task 9: Wake: keep or restore into a clean tree, on every box [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)`); |
| + - `internal/activator/activator.go:95-107` (`Config` gains `HA bool`, `Self hafresh.Self`, `Lifetime func(host string) (provision.LifetimeEntry, bool)`, `Migrate func(ctx context.Context, host 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). |
| + - `internal/activator/backend_exec.go:716-738` (`Acquire` maps `*lease.RefusedError`, and keeps the held handle's view), `:754-787` (`execLease` adapters), `:805-860` (`restorePlain` sends HA-on hosts to `restoreHA`); |
| + - the `ExecBackend` fields (`Registry *registry.Registry`, `FilesStore release.Store`); |
| + - `internal/provision/reconcile.go:36` (`ReconcileConfig.Lifetimes`) 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. |
| +- Consumes: `lease.Acquire`, `(*Held).HA`, `(*Held).View`, `hafresh.DecideKeep`, `readLocalNow`. |
| - Produces: |
| ```go |
| @@ -463,25 +522,35 @@ func (x *LifetimeIndex) Lookup(host string) (LifetimeEntry, bool) |
| ```go |
| package activator |
| +// haLease is the optional half of Lease an execLease over an HA-on handle answers. |
| +type haLease interface { |
| + HA() bool; View() hafresh.View |
| + SetMonitorInterval(d time.Duration) |
| + ReleaseMarker(ctx context.Context, m hafresh.Marker) (*lease.Obligation, error) |
| +} |
| +// haRep is the optional half of Rep a *lease.Replicator answers. |
| +type haRep interface { |
| + HA() bool; Finish(ctx context.Context) (uint64, error) |
| + ReleaseMarker(ctx context.Context, m hafresh.Marker) (*lease.Obligation, error) |
| +} |
| 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 |
| +func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error // Restore into <host>.restore/ and 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()`: |
| +**Behaviour, whatever `Config.HA` says:** |
| +- `Acquire` stores the handle's view per host. `restorePlain` sends the host to `restoreHA` when the handle's `HA()` is true: |
| - 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. |
| +- The staging fallback never runs for an HA-on host. |
| +- Hosts that are not HA-on 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 |
| + b, rt := haBackend(t, "shop.example.com") // 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)) |
| @@ -490,17 +559,24 @@ func TestRestoreHAKeepsOnlyOnProof(t *testing.T) { |
| 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}) |
| + b.restoreHA(ctx, rt, hafresh.View{}) |
| 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") } |
| + if _, err := b.restoreHA(ctx, rt, hafresh.View{}); err == nil { t.Fatal("wake proceeded over an old tree") } |
| +} |
| +func TestHAOnHostRulesHoldWithSwitchOff(t *testing.T) { // Review Focus 5, F8 |
| + b, rt := haBackend(t, "shop.example.com"); b.Cfg.HA = false |
| + writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 5, Clean: true}) |
| + putLockFor(t, b, rt, markerBody("b", "i-b", "L1", 6, true)) // B released newer state |
| + if _, err := b.Acquire(ctx, rt); err != nil { t.Fatal(err) } |
| + if fresh, err := b.Restore(ctx, rt); err != nil || fresh || restoreCalls != 1 { t.Fatalf("stale copy reused with the switch off: %v", err) } |
| } |
| 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") } |
| + b.restoreHA(ctx, rt, hafresh.View{}) |
| + if fm.promoted { t.Fatal("staging promoted for an HA-on host") } |
| } |
| func TestLifetimeIndexReplace(t *testing.T) { // provision |
| var x LifetimeIndex; created := time.Unix(1_700_000_000, 0) |
| @@ -510,21 +586,28 @@ func TestLifetimeIndexReplace(t *testing.T) { // provision |
| } |
| ``` |
| -- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAWake|TestLifetimeIndex'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAOnHostRules|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" |
| +- [ ] **Step 5: Commit** "HA-on hosts: keep on proof, otherwise restore DB and files into a clean tree, on every box" |
| -### Task 10: Files and wake-state publication; release writes the marker [own review] |
| +### Task 10: Files on the entry; every release writes a 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`). |
| + - `internal/activator/activator.go`: |
| + - `actEntry` gains `files *hostFiles`, `filesStop context.CancelFunc`, `filesDone chan struct{}`; |
| + - `:279-285` (`giveBack`: an HA-on lease goes to `releaseHA` with `Clean: false`, never `Release`); |
| + - `:4378-4410` (`finishStop` calls `releaseHA` for HA-on entries; lease loss and shutdown reach it the same way); |
| + - `:2621` (an HA-on host of the stream class: `lease.(haLease).SetMonitorInterval(time.Second)` before `Replicate`); |
| + - the wake after `Replicate` (`startFiles(e)`, on the service's lifetime context, never the wake's); |
| + - `Start` (`loadOwed`), and the sweep (`retryOwed`). |
| + - `internal/activator/maintenance.go:360` (`cleanupFailedWake`: `stopFiles(e)` before the release). |
| **Interfaces:** |
| -- Consumes: `hostfiles.Open`, `SyncDir`, `StagePlatform`, `Commit`, `ExportWake`, `StageWake`; `lease.Finish`, `ReleaseMarker`, `RetryObligation`; `writeReleaseRecord`, `statFileID`, `treeDigest`. |
| +- Consumes: `hostfiles.Open`, `SyncDir`, `StagePlatform`, `Commit`, `ExportWake`, `StageWake`; `haLease`, `haRep`, `lease.RetryObligation`; `writeReleaseRecord`, `statFileID`, `treeDigest`. |
| - Produces: |
| ```go |
| @@ -540,18 +623,24 @@ func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*ho |
| 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) startFiles(e *actEntry) |
| +func (a *Service) stopFiles(e *actEntry) // cancel, then wait on filesDone |
| +// releaseHA is the one HA release: sleep, shutdown, lease loss and failed wakes all reach it. |
| +func (a *Service) releaseHA(ctx context.Context, host string, rel interface { |
| + ReleaseMarker(context.Context, hafresh.Marker) (*lease.Obligation, error) |
| +}, e *actEntry, cleanAllowed bool) 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`. |
| +1. `stopFiles`; |
| +2. if `e` has files, `Final`; |
| +3. if `rel` is an `haRep`, `Finish`; |
| +4. `writeReleaseRecord`; |
| +5. `ReleaseMarker` with `Clean = cleanAllowed && 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"}`. |
| +`giveBack` passes `cleanAllowed = false`. An obligation is written to `<db>.release-owed.json` (fsynced) and queued. Before acquiring 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. |
| @@ -559,20 +648,34 @@ An obligation is written to `<db>.release-owed.json` (fsynced) and queued. Befor |
| ```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) } |
| + a, e := haServiceEntry(t, "shop.example.com"); makeUnreadable(t, e, "secret.bin") |
| + if err := a.releaseHA(ctx, e.host, e.rep.(haRep), e, true); err != nil { t.Fatal(err) } |
| + if lockView(t, e).Lock.Release.Clean { t.Fatal("incomplete publish marked clean") } |
| } |
| -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 TestFailedRestoreLeavesUncleanMarkerAndStaleCopyRestores(t *testing.T) { // F1 witness |
| + a, e := haServiceEntry(t, "shop.example.com"); failRestoreOnce(t, a) |
| + if _, err := a.wakeForTest(ctx, e.route); err == nil { t.Fatal("wake should fail") } |
| + v := lockView(t, e) |
| + if v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean { t.Fatalf("lock after failed wake: %+v", v) } |
| + b2 := otherBoxWithStaleCopy(t, a, e.route) // B holds an older local DB and a record naming B |
| + if _, err := b2.Acquire(ctx, e.route); err != nil { t.Fatal(err) } |
| + if fresh, err := b2.Restore(ctx, e.route); err != nil || fresh || b2RestoreCalls(b2) != 1 { t.Fatal("stale copy kept after a failed wake elsewhere") } |
| } |
| -func TestOwedMarkerRetriedBeforeAcquire(t *testing.T) { // Review Focus 2 |
| - a, e := haServiceEntry(t, "shop.example.com"); failMarkerPuts(t, e, 1); a.releaseHA(ctx, e) |
| +func TestNoWriteAfterMarker(t *testing.T) { // F9 |
| + a, e := haServiceEntry(t, "shop.example.com"); keepWriting(t, e) // the app keeps touching files |
| + a.releaseHA(ctx, e.host, e.rep.(haRep), e, true) |
| + w := storeWrites(t, e) |
| + if i := indexOfMarkerPut(w); i < 0 || i != len(w)-1 { t.Fatalf("write after the marker: %v", w) } |
| +} |
| +func TestOwedMarkerRetriedBeforeAcquire(t *testing.T) { // Review Focus 2, F7 |
| + a, e := haServiceEntry(t, "shop.example.com"); failMarkerPuts(t, e, 1) |
| + a.releaseHA(ctx, e.host, e.rep.(haRep), e, true) |
| 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") } |
| + if _, err := a2.backend.Acquire(ctx, e.route); err != nil { t.Fatal(err) } |
| + w := lockWrites(t, e) // PUTs to lock.json, in order |
| + if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], a2.Cfg.Self) { t.Fatalf("order: %v", w) } |
| + if exists(owedPath(e)) { t.Fatal("owed file not removed") } |
| } |
| func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| f := hostFilesFixture(t, nil); go f.Run(ctx); writeEnv(t, f, "CARLOS_INSTANCE_KEY=k1\n") |
| @@ -580,51 +683,61 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| } |
| ``` |
| -- [ ] **Step 2: Run** `./internal/activator/ -run 'TestFinalPublish|TestReleaseHA|TestOwedMarker|TestTrioPublished'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/activator/ -run 'TestFinalPublishIncomplete|TestFailedRestoreLeaves|TestNoWriteAfterMarker|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" |
| +- [ ] **Step 4: Run** the same, plus `./internal/hostfiles/`, and `-run 'TestStop|TestCleanupFailedWake|TestShutdown'` in `./internal/activator/`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA release: one marker path for sleep, failed wake, lease loss and shutdown; files publisher owned by the entry" |
| -### Task 11: Key and token producers on the holder only |
| +### Task 11: Secrets on the holder only, published before every launch |
| **Files:** |
| +- Create: `internal/activator/hasecrets.go` and its test |
| - 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). |
| + - `internal/activator/admintoken.go:73-78` (`ensureAdminTokenAt`) and `internal/activator/instancekey.go:254-290` (`ensureInstanceKeyAt`): on an HA-on host, a missing token or key is minted only when `mintAllowed` says true; otherwise `ErrInstanceKeyDeferred`; |
| + - the launch paths `internal/activator/prepare.go:83-87`, `internal/activator/backend_exec.go:1034-1039` and `:2130-2137`: call `haSecretsReady` before the launch on every attempt; |
| + - `internal/host/instancekeys.go:75-85`, `:138` (skip the backfill for HA-on hosts); |
| + - `internal/host/schedule_wiring.go:186-205` (for HA-on hosts `prepare` only reads, and answers `""` when absent); |
| + - `internal/activator/activator.go:5394-5404` (`ServeScheduled`: 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`. |
| +- Consumes: `hostfiles.Load`, `hostFiles.PublishPlatformNow`. |
| +- Produces: |
| + |
| +```go |
| +package activator |
| +func (b *ExecBackend) mintAllowed(ctx context.Context, rt registry.Route) (bool, error) // true only when the host's files manifest is absent |
| +func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) error // sha256(<host>.env) == manifest's host.env item, else publish and wait for the commit; an error fails the launch |
| +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 TestHATokenNotMintedBesideAManifest(t *testing.T) { // F4: an env with a key but no token |
| + b, rt := haBackend(t, "shop.example.com"); publishManifestEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n"); writeEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n") |
| + if err := b.launchForTest(ctx, rt); !errors.Is(err, ErrInstanceKeyDeferred) { t.Fatalf("minted a token beside a manifest: %v", 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 TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) { // F4: a mint whose publish failed |
| + b, rt := haBackend(t, "fresh.example.com"); failFilesCommitOnce(t, b) |
| + if err := b.launchForTest(ctx, rt); err == nil { t.Fatal("launched without an acknowledged publish") } |
| + if err := b.launchForTest(ctx, rt); err != nil { t.Fatal(err) } |
| + if !strings.Contains(platformEnv(t, b, rt), "CARLOS_INSTANCE_KEY=") || !strings.Contains(platformEnv(t, b, rt), "CARLOS_ADMIN_TOKEN=") { t.Fatal("retry launched before publishing") } |
| } |
| 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) } |
| + dd := t.TempDir(); reg := testRegistryHAOn(t, "shop.example.com") |
| + if tok, err := scheduleToken(dd, nil, reg)("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" |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/host/ -run 'TestHAToken|TestHALaunchRetry|TestHAScheduleToken'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `launchForTest` is a test helper that drives the backend's start path. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestInstanceKey|TestAdminToken|TestSchedule'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA secrets: minted only with no manifest, published and acknowledged before every launch" |
| ### 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 |
| +- Create: `internal/hafresh/migrate.go` and its test, `internal/lease/txid.go` and its test (`package lease`) |
| **Interfaces:** |
| - Produces: |
| @@ -656,7 +769,7 @@ func LocalTXID(dbPath string) (txid uint64, walEmpty bool, err error) // max ove |
| | `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 && !RemoteExists` | `Migrate`, `empty` (no inventory lists the host, by the row above) | |
| | `!HasLocal` | `Refuse`, `no-copy` | |
| | `RowCreated.Before(RecordCreated)` | `Refuse`, `lifetime` | |
| | `!LocalWALEmpty` or `LocalTXID != RemoteHead` | `Refuse`, `no-match` | |
| @@ -679,6 +792,8 @@ func TestMigrationGate(t *testing.T) { |
| 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{}} }) |
| + // F2 witness: an existing host with a copy on B and nothing in S3. A has no copy. |
| + check(Refuse, "two-copies", func(in *MigrationInput) { in.HasLocal, in.RemoteExists = false, false; in.Inventories[0] = Inventory{Box: "a", Hosts: map[string]uint64{}}; in.Inventories[1] = Inventory{Box: "b", Hosts: map[string]uint64{"h": 3}} }) |
| check(Refuse, "move", func(in *MigrationInput) { in.Staging = true }) |
| } |
| func TestLocalTXIDFromLTXNames(t *testing.T) { // lease |
| @@ -686,43 +801,52 @@ func TestLocalTXIDFromLTXNames(t *testing.T) { // lease |
| 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) } |
| + fx := leasetest.NewLockFixture(t); putL0Files(t, fx, "instances/h", 1100) |
| + if txid, ok, err := RemoteHeadTXID(ctx, fx.Bucket, "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" |
| +- [ ] **Step 5: Commit** "migration gate: one copy, matching TXID, unchanged lifetime; empty only when no inventory lists the host" |
| -### Task 13: Migration pass, sleep-time migration, activation [own review] |
| +### Task 13: Migration under the lease, with the inventory first [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`. |
| + - `internal/host/agent.go`. With `CARLOS_REGION_HA` on: `haActivationBlocked`, the activator's `HA`, `Lifetime` and `Migrate = migrator.Decide`, `ReconcileConfig.Lifetimes`, and the pass every 10 minutes while any host is unmigrated. `Lifetime` and `ReconcileConfig.Lifetimes` are set whatever the switch, because HA-on hosts need them. |
| + - `internal/activator/harelease.go`: `finishStop` for a non-HA-on host. If `Config.Migrate` is set, it first calls `Config.Inventory(ctx, host, txid)`, then `Config.Migrate`. On `Migrate` it runs `releaseHA` with the clean conditions; otherwise it takes today's release. |
| + - `internal/activator/activator.go:95-107` (`Config.Inventory func(ctx context.Context, host string, txid uint64) error`). |
| **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`. |
| +- Consumes: `MigrationGate`, `InventoryKey`, `RemoteHeadTXID`, `LocalTXID`, `ReadLock`, `edgesfile.ReadLiveSnapshot` (`internal/edgesfile/snapshot.go:123`; the view is the fresh files in this box's placement), `LifetimeIndex.Lookup`, `lease.Acquire`, `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 |
| +// noteCopy updates this box's inventory to list host at txid and waits for the PUT; called before ANY release of an unmigrated host with a local copy. |
| +func (m *haMigrator) noteCopy(ctx context.Context, host string, txid uint64) error |
| +// Decide is the one gate call. Precondition: the caller holds host's lease. It reads the replica head and every inventory now. |
| +func (m *haMigrator) Decide(ctx context.Context, host string) (hafresh.Verdict, string) |
| 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"`. |
| +**`Pass`, for each sleeping, unmigrated host with a local copy:** |
| +1. `lease.Acquire` (the legacy row). A held lease means the host is skipped this pass. |
| +2. `Decide`. |
| +3. On `Migrate`: `hostFiles.Final` from the local tree, with the wake state. Then `ReleaseMarker` with `Clean: complete`. An incomplete publish also records the refusal reason `incomplete`. |
| +4. On `Wait` or `Refuse`: today's legacy release. |
| + |
| +An awake host is decided at its sleep in `finishStop`, which already holds the lease. |
| + |
| +**Logs and blocking:** |
| +- `ha: <host>: migrated` and `ha: <host>: refused (<reason>)`. |
| +- A blocked activation logs `ha: activation refused: <reason>`, migrates nothing in this agent's life, and reports `State: "refused"`. |
| - [ ] **Step 1: Test** |
| @@ -735,33 +859,43 @@ func TestMigrationPassMigratesOnlyUniqueMatchingCopies(t *testing.T) { |
| 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 TestMigrationInterleavingNeverPublishesStale(t *testing.T) { // F3 witness |
| + w := haWorld(t, "a", "b"); w.localCopy("a", "h.example.com", 7); w.replicaHead("h.example.com", 7); w.inventories() |
| + w.beforeAcquire("a", func() { w.wakeWriteSleep("b", "h.example.com") }) // B writes TXID 8 and releases, legacy, after noting its copy |
| + w.migrator("a").Pass(ctx) |
| + if l := w.lock("h.example.com"); l.Lock.Release != nil && l.Lock.Release.TXID == 7 { t.Fatal("A published TXID 7") } |
| +} |
| 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 TestInventoryUpdatedBeforeRelease(t *testing.T) { // F3 ordering |
| + w := haWorld(t, "a", "b"); w.awake("b", "new.example.com"); w.sleep("b", "new.example.com") |
| + if seq := w.deployWrites(); indexOf(seq, "inventory b") > indexOf(seq, "release new.example.com") { t.Fatalf("release before inventory: %v", seq) } |
| +} |
| 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 2: Run** `./internal/host/ -run 'TestMigrationPass|TestMigrationInterleaving|TestSleepMigrates|TestInventoryUpdated|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" |
| +- [ ] **Step 5: Commit** "HA migration: acquire first, inventory before release, clean marker only on a complete baseline" |
| ### Task 14: Same-box recovery after expiry, with an emptiness proof [own review] |
| -This is pulled forward from P1b (gap 3). |
| +In P1a by Paul's approval. |
| **Files:** |
| - Create: `internal/activator/hasamebox.go` and its test |
| -- Modify: `internal/activator/backend_exec.go` (`Acquire` passes `SameBoxEmpty`) |
| +- Modify: `internal/activator/backend_exec.go:716-738` (`Acquire` registers `lease.SetSameBoxProof(prefix, b.sameBoxEmpty(ctx, rt))` before calling `lease.Acquire`) |
| **Interfaces:** |
| -- Consumes: `hostEmptier.EmptyHost` (`internal/activator/opset.go:437-453`), `Classify`. |
| +- Consumes: `hostEmptier.EmptyHost` (`internal/activator/opset.go:437-453`), `Classify`, `lease.SetSameBoxProof`. |
| - 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`. |
| @@ -784,15 +918,15 @@ func TestSameBoxEmptyRefusesUnprovenLayouts(t *testing.T) { |
| - [ ] **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 |
| +### Task 15: Move and import refusals |
| **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/host/movesoffline.go:59-64` (`offlineCapable` is false when `regionHAEnabled`, or when the box has any HA-on host, so it stays false after a rollback); |
| + - `internal/console/apiinstancemove_offline.go:384-433` (`offlineSelect` refuses when any box of either region publishes `boxchoice.Capability`, `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)`. |
| +**Interfaces:** none. Copy: C1 and C2, where `%s` is `s.offlineName(code)`. |
| - [ ] **Step 1: Test** |
| @@ -821,7 +955,7 @@ func TestImportRefusedForHARegion(t *testing.T) { |
| **Files:** |
| - Modify: |
| - - `internal/status/snapshot.go`: `:41` (`Probes.HA`), `:475` (`BoxMetrics.HA`, private, never copied into `FleetBox`), `:1060-1075`; |
| + - `internal/status/snapshot.go`: `:41` (`Probes.HA`), `:475` (`BoxMetrics.HA`, private, never in `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`). |
| @@ -867,22 +1001,27 @@ func TestPrintSystemStatusHA(t *testing.T) { // root package |
| - 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. |
| +- Consumes: `hafresh.DecideAcquire`, `DecideKeep`, `MigrationGate`, `OwnerFor`, `MarkerBody`, `DecodeLock`. These are the production decisions; the model supplies the I/O and the release ordering of Tasks 10 and 13. |
| -**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. |
| +**The model.** 2 to 5 boxes. Per box: a DB position, a files tree, a release record, an inventory, a pid, an agent state (running, crashed, hung), and a files publisher that may outlive its lease if a mutation allows it. One S3 with per-host TXID chains, a files manifest generation, `lock.json` with ETags and conditional writes, and the inventories. |
| -**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. |
| +**Actions:** request at a random box; graceful sleep; failed restore; 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, including B waking between A's inventory read and A's acquire; a recreated hostname; a tenant write while asleep; the switch turned off on a box. |
| **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. |
| +- **I1, single writer.** At every step at most one box runs a host. Every replica write and every manifest write for a host came from the box holding its current lease, and no two replica writes share a TXID. |
| +- **I2, no stale serving.** A box starts serving only from the S3 head, or from a copy whose clean 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`. |
| +- `expiry-authorizes`, `keep-without-marker`, `keep-unclean`, `migrate-two-copies`, `marker-before-final`, `same-box-no-proof`; |
| +- `failed-wake-deletes-lock` (F1), `fresh-shortcut` (F2), `validate-before-acquire` (F3), `publisher-outlives-release` (F9), `switch-off-legacy` (F8). |
| **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. |
| +- a failed marker PUT, then a retry after expiry, then another box acquires; |
| +- a stale publisher's manifest write after the release violates I1 under `publisher-outlives-release`, and never without it; |
| +- a matching but unclean marker restores (I2); |
| +- a failed restore, then a stale copy on another box, restores (F1); |
| +- the interleaving of Task 13. |
| - [ ] **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. |
| @@ -902,30 +1041,34 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D" |
| - 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. |
| + - the cost: §18's lines, plus one restore per migrated instance; |
| + - **rollback:** set `CARLOS_REGION_HA` empty and restart the agent. That stops new migrations only. Migrated hosts keep their HA rules on every box, and stay unmovable until the un-migrate follow-up. |
| 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 2: Release and roll** by the platform roll recipe (README): dev boxes, dev console, check. Verify the version by `X-Carlos-Version`. Note each box's `CARLOS_HIBERNATE_IDLE`: it is how long a host takes to sleep once traffic stops. |
| +- [ ] **Step 3: Pre-check.** `carlos system status` shows both 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 5: Paul's view.** `carlos system status` shows, per IE box, "high availability: N hosts migrated, …" with refused hosts named. Each refusal is fixed or accepted, and recorded. |
| +- [ ] **Step 6: Per-host checks** on a test app migrated by A and on `wakecheck`. Before each cross-box wake: stop traffic, wait the idle window, and read the lock (`aws s3 cp s3://<data-bucket>/<prefix>/lock.json -`, profile `kass`) until it shows `released/v1;ref=<the box just used>`. |
| + |
| + | Starting state | Wake through | Expected line | |
| + |---|---|---| |
| + | marker names A (fresh from migration) | A | `kept local` | |
| + | marker names A | B | `restored (other-box)` | |
| + | marker names B | A | `restored (other-box)` | |
| + | marker names A, then a file in A's files dir `touch`ed by root while asleep | A | `restored (tree-changed)` | |
| + | a file in A's files dir made unreadable (mode 000) before the sleep, so the marker is `clean: false` | A | `restored (unclean)` | |
| + |
| + Data written through each box must be present after the next wake 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. |
| +- [ ] **Step 8: Kill drill.** `kill -9` A's agent while a flat-layout test host is awake on A. |
| - 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)`. |
| + - After expiry, A's restarted agent re-takes the host by the proof, with `restored (no-marker)`, since the lock is A's own expired lease. |
| - 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. |
| +- [ ] **Step 9: Hang drill.** `SIGSTOP` A's agent for 20 minutes while a host is awake on A. |
| - 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. |
| + - After `SIGCONT`, A stands the instance down on its lost lease and writes a marker through `releaseHA`. The marker is clean only if the final sync and publish succeed, and it is never deleted. The next wake follows the marker. |
| + - Record the timeline, and that the replica has no write from B. |
| - [ ] **Step 10: Report** on the branch's discussion: the counts, the drill timelines, and 24 hours of observed cost. |
| ## Census |
| @@ -939,7 +1082,7 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D" |
| | `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. |
| +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) |
| @@ -956,13 +1099,14 @@ The other changed units with I/O are agent-run. They come out as `body`, `sites` |
| | 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. |
| +## Spec gaps and follow-ups |
| + |
| +1. **A held lease can't say whether its host is migrated.** The plan appends `;ha=1` for HA-on hosts. Only the owner survives litestream's renewals. |
| +2. **The marker's field list omits `clean`.** The plan puts it inside `carlos_release`. |
| +3. **Same-box recovery (§9.6) is in P1a** by Paul's approval (Task 14). |
| +4. **The marker lifetime needs the record's `CreatedAt`.** The plan feeds it from the reconcile pass. "Never re-pointed" is `row.CreatedAt >= record.CreatedAt`. |
| +5. **App files stay on the snapshot cadence in P1a,** by Paul's approval. |
| +6. **P0 item 4 is deferred** to P1b and P2: the claim halves of nocapacity, regioncapacity, the roles door, `termfence.Box`, and the latch. Those halves run only with claims on. |
| +7. **Readiness belongs to P2's console door.** P1a shows migration through the box status snapshot and `carlos system status`. |
| +8. **Sticky HA state (F8) goes further than the spec.** §19 says the switch gates P1a; the plan makes HA-on hosts' rules run on every box, so a rollback cannot re-enable stale reuse. **Follow-up:** an un-migrate procedure (settle holders and obligations, then clear markers) before any HA-on host can move again. |
| +9. **Every release of an HA-on host writes a marker (F1).** That includes failed wakes and lease loss, with `clean: false`. §5.2 described only the graceful release. |