| index 0b8a2bab4..c4a4f9856 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,102 +2,98 @@ |
| |
| > **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, 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. |
| +**Goal:** Hosts created in a region after the console turns it HA ("born HA") run under the release-marker rules from their first wake. A box reuses such a host's local database and files only on positive proof, and otherwise restores from S3 into a clean tree. Existing hosts behave exactly as today. P0's removals ride in the same merge. |
| |
| -**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. |
| +**Architecture:** |
| +- **The pure decisions.** A new package, `internal/hafresh`, holds the acquire table (I1) and the keep decision (I2). The seeded simulation drives exactly these. |
| +- **The I/O.** `internal/lease` holds the one HA acquire and the one HA release; it refuses to delete an HA lock. |
| +- **The wiring.** `internal/activator` and `internal/host` wire wake, sleep, files publication and secrets. |
| +- **The switch.** A host is HA when its record carries `ha: true`, which the console stamps at create for regions listed in `CONSOLE_HA_REGIONS`. Every box honours the flag, whatever its own `CARLOS_REGION_HA`, and the flag is never cleared. |
| |
| -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`. |
| |
| -**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.1 (rev 6 approved, plus Paul's N-HA7). In scope: §4.2, §5, §7.3, §8.2, the P1a rows of §9.4, §9.6, §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. |
| +**Rev 3.** Plan round 2 (e384a8d2) found 9 P1s; stopping rule 2 triggered on the migration and HA/legacy boundary families. Paul's ruling **N-HA7**: P1a admits only born-HA hosts and migrates nothing; existing-host migration becomes a later, operator-run, held, offline slice. |
| +- **Deleted from the plan:** inventories, the migration gate, the migration pass, sleep-time migration, the activation hold, the status task, and the findings that existed only for them: r2.2, r2.7, r2.11, r1 F2 and r1 F3. Copy C3 to C10 go with them. |
| +- Rounds so far: 2 of 3. |
| |
| | 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 | |
| +| r2.1 cleanup paths delete HA locks | `lease` itself refuses to delete an HA lock. `Held.Release`, `Replicator.Close` and the acquire's own cleanup all write an unclean marker through the one release; failures surface as `*ObligationError`, persisted by one activator function. Witnesses: a late acquire acknowledgement; cleanup after replication starts. | 6, 7, 10 | |
| +| r2.3 admin-token gate on the wrong path | One mint gate, `haMintGate`, runs before every token and key producer (`prepare.go:83`, `backend_exec.go:1034`, `:2130`) on an HA host. | 11 | |
| +| r2.4 surviving tests | `joinmode_test.go`, `joinroot_test.go`, `systemparticipation_test.go:169`/`:191` and `system_test.go:39` disposed. | 2, 4 | |
| +| r2.5 fixture cycle | HA lease tests are external (`package lease_test`) on `leasetest.LockFixture`; private checks via `export_test.go`. | 6 | |
| +| r2.6 legacy fallback reclassifies | HA hosts never go through litestream's `AcquireLease`: one conditional PUT on the exact ETag classified; any 412 re-reads and reclassifies. Interleaving witness. | 6 | |
| +| r2.8 "complete" | `hostfiles.SyncStats.Complete()`: no `TooLarge`, `NotRegular`, `Unreadable`, `Retry` or `Torn`. Witnesses through `betweenLookAndOpen` and `readAll`. | 10 | |
| +| r2.9 refusals keyed on a box capability | Keyed on the host: the move door refuses a record with `HA`; the import door refuses when the record would be born HA. Tested in a one-box region. | 13 | |
| +| r2.10 owner test bypasses wiring | `agentEntry` takes an `identity` func and calls `lease.SetSelf` itself; the test acquires inside `run`. | 5 | |
| +| r2.12 budget | HA wake: 1 GET + 1 conditional PUT, asserted by request counts; first wake: 1 GET, 1 LIST, 1 PUT. | 6 | |
| +| r2.2, r2.7, r2.11, r1 F2, r1 F3 | Cut by N-HA7: no migration in P1a. | none | |
| |
| ## Global Constraints |
| |
| -- **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). |
| +- **Born HA:** `provision.Record.HA bool` (`json:"ha,omitempty"`), stamped by the console's create door when the record's region is in `CONSOLE_HA_REGIONS` (comma-separated region codes). Seeds, imports and sidecars are never stamped in P1a. A box treats a host as HA if its record is `HA`, or if its lock is HA-format. Neither is ever cleared. |
| +- **Owner:** `box/v1;ref=<ref>;iid=<instance id>;pid=<pid>`. `iid=` is omitted when unknown. HA locks carry `;ha=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, clean}}`. |
| - **Local record:** `<db>.release.json`. It holds: |
| - - the marker fields; |
| - - 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; |
| + - the marker; |
| + - the DB's inode, size, `mtime_ns` and `ctime_ns`, and whether `-wal` is absent or empty; |
| + - the files tree digest: SHA-256 over (path, type, mode, size, inode, `mtime_ns`, `ctime_ns`), metadata only. |
| +- **`clean`:** the final sync succeeded, and `SyncStats.Complete()` holds. Every other release (failed wake, acquire cleanup, `Close`, `Release`) writes `clean: false`. |
| +- **No HA lock is ever deleted.** Expiry never lets another box take one. A failed marker PUT ends only on success or a 412. |
| +- **First wake** of an HA host, with an absent lock, is refused unless the hibernate prefix is empty: no LTX, no `files/0/`, nothing. |
| +- **Cadences:** the H6 trio and the wake state publish at about 1 s. App files publish every `files_snapshot_interval`, 15 minutes (snapshot only in P1a, Paul). The stream class captures the WAL every 1 s for HA hosts. |
| +- **Budget:** |
| + - HA wake: 1 GET + 1 conditional PUT; |
| + - first HA wake: 1 GET (404) + 1 LIST (`max-keys=1`) + 1 PUT, plus the empty manifest; |
| - sleep: + 1 PUT (marker) in place of a free DELETE, + a files publish if changed; |
| - 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. |
| - |
| - 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`. Go commands may need the sandbox off ("read-only file system" from the build cache). Leave `GOCACHE` at its default. |
| + - an index miss after a restart: 1 GET of the record; |
| + - non-HA hosts: unchanged. |
| +- **Cross-compile:** darwin and windows. `ctime` reads 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`). |
| +- **Copy:** RHA-P1a-C1 and C2 only (approved). No em dashes. Log lines are diagnostics. |
| +- **Census:** `make census-card`, then CLAIMS, then `make census-propose`. A cross-model reviewer approves; Paul rules on decisions only. |
| +- **Tests:** locally, touched packages only, with `-run` and `nice -n 19`. The sandbox may need to be off for the Go build cache; leave `GOCACHE` at its default. |
| |
| ## Review Focus |
| |
| -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`. |
| +1. **A box restarted before its first reconcile pass.** The record index is empty, so an HA host must not be treated as legacy. An index miss reads the record. Task 9: `TestIndexMissReadsRecordBeforeAcquire`. |
| 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`. |
| +4. **A crash between the first-wake mint and its publish.** The next wake, on any box, finds no manifest and mints afresh. The unpublished key was never used by the app. Task 11: `TestFirstWakeCrashBeforePublishRemints`. |
| +5. **A one-box region with an HA host and a box whose switch is off.** The HA rules still apply. Task 9: `TestHAHostRulesHoldWithSwitchOff`. |
| |
| --- |
| |
| -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. |
| +Tasks 1 to 4 are P0. Tasks 5 to 13 are the slice. Task 14 is the simulation; Task 15 is the dev rollout. |
| +- **[own review]** marks stopping rule 3. |
| - **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`, `: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. |
| +- Modify: `internal/host/edgesfile.go:455`, `:526` (drop `applyEdgesClaims`), `:734-757`, `:983-988`, `:1001` |
| +- Create: `internal/host/edgesschedule.go`. It receives `edgesLoopState` from `internal/host/edgesclaims.go:241-300`, minus `claims`, `claimsNext` and `claimDue`; `assetDue` and `dueWith` are 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`. |
| + - `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`, `movesoffline_e2e_test.go`: replace each `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`, 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. |
| +**Interfaces:** `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)` with `CARLOS_REGION_HA` on. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| func TestEdgesFileRegionHAPublishesAddressWithoutClaimRead(t *testing.T) { |
| s := release.NewDirStore(t.TempDir()); reg := testRegistryWithInstance(t, "shop.example.com") |
| - addrs := fixedAddresses{Private: "10.0.1.5", PrivateCIDR: "10.0.0.0/16", Public: "203.0.113.9"} |
| var last []byte |
| + addrs := fixedAddresses{Private: "10.0.1.5", PrivateCIDR: "10.0.0.0/16", Public: "203.0.113.9"} |
| if err := edgesFileWriteClaims(ctx, s, reg, testIdent("box-a"), "", &last, true, addrs, false, nil); err != nil { t.Fatal(err) } |
| f := readEdgesFile(t, s, "box-a") |
| if f.PrivateIP != "10.0.1.5" { t.Fatalf("private_ip = %q", f.PrivateIP) } |
| - if _, ok := f.Hosts["shop.example.com"]; !ok { t.Fatal("relocatable host withheld: claim filtering still applied") } |
| + if _, ok := f.Hosts["shop.example.com"]; !ok { t.Fatal("host withheld by claim filtering") } |
| } |
| ``` |
| |
| @@ -109,21 +105,20 @@ func TestEdgesFileRegionHAPublishesAddressWithoutClaimRead(t *testing.T) { |
| ### Task 2: P0. Delete joining mode, `carlos system join` and its units |
| |
| **Files:** |
| -- 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` |
| +- Create: `internal/host/agententry.go` (`agentEntry`, `awaitGroupReference` and `groupReferenceBackoff`, moved from `internal/host/joining.go:247-296`); `internal/host/retiredunits.go` |
| +- Delete: `internal/host/joining.go` (with `hostingGate`, `decideAgentMode`, `agentHosting`), `joinmode.go`, `joinroot.go`; `internal/host/units/carlos-system-join.service`, `.path` |
| +- Modify: `internal/host/agent.go:229-231`; `internal/host/claimwiring.go:102-106` (drop the `SetHosting` calls); `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. |
| + - `joining_test.go`: move `TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts` and `TestAwaitGroupReferenceStopsWithItsContext` to `agententry_test.go`, and delete the rest; |
| + - `joinmode_test.go`, `joinroot_test.go`, `claimwiring_hosting_test.go`: delete. They test the deleted types and the claim agent only; |
| + - `system_test.go:39`: drop `join` from the expected verb list. |
| |
| -**Interfaces:** |
| -- 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. |
| +**Interfaces:** `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`, treating an absent unit as no error, and it is called by bootstrap's plan path. `agentEntry`'s final signature is Task 5's. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| -func TestBootstrapRetiresJoinUnits(t *testing.T) { // internal/host |
| +func TestBootstrapRetiresJoinUnits(t *testing.T) { |
| root := t.TempDir(); writeUnit(t, root, "carlos-system-join.path") |
| if err := retireUnits(root, retiredUnits); err != nil { t.Fatal(err) } |
| if _, err := os.Stat(filepath.Join(root, "etc/systemd/system/carlos-system-join.path")); !os.IsNotExist(err) { t.Fatal("still installed") } |
| @@ -134,8 +129,8 @@ func TestSystemJoinVerbGone(t *testing.T) { // root package |
| } |
| ``` |
| |
| -- [ ] **Step 2: Run** `./internal/host/ -run TestBootstrapRetiresJoinUnits` and `. -run TestSystemJoinVerbGone`. They FAIL. |
| -- [ ] **Step 3: Implement** the move, the deletions and `retireUnits`. |
| +- [ ] **Step 2: Run** `./internal/host/ -run TestBootstrapRetiresJoinUnits` and `. -run 'TestSystemJoinVerbGone|TestSystemVerb'`. They FAIL. |
| +- [ ] **Step 3: Implement** the moves and deletions. |
| - [ ] **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" |
| |
| @@ -143,9 +138,7 @@ func TestSystemJoinVerbGone(t *testing.T) { // root package |
| |
| **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) |
| - |
| -**Interfaces:** none. |
| +- Modify: `internal/console/hostclaimops.go:44-61` (drop the `s.cfg.RegionHA` branch) |
| |
| - [ ] **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. |
| @@ -156,42 +149,40 @@ func TestSystemJoinVerbGone(t *testing.T) { // root package |
| Root runs this. |
| |
| **Files:** |
| -- Modify: `internal/host/systemparticipation.go:47-110`; `internal/host/systemapply.go:134` and `:259-262` (the field goes) |
| +- Modify: `internal/host/systemparticipation.go:47-110`; `internal/host/systemapply.go:134`, `:259-262` |
| - Tests to update, each listed by its `regionHA = true` line: |
| - - `systemparticipation_test.go:50`, `:83`, `:98`, `:112`; |
| + - `systemparticipation_test.go:50`, `:83`, `:98`, `:112`, `:169`, `:191`; |
| - `guardparticipation_test.go:22`, `:110`; |
| - `participation_flagoff_test.go:16`; |
| - `plan9_a_guard_test.go:99`; |
| - `rootexecution_update_test.go:26`. |
| |
| - 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. |
| + A test whose subject is the region-HA-only behaviour (the legacy marker, or a deferral without participation) 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 choice in the commit message. |
| |
| -**Interfaces:** none. With no participation required it returns nil and writes no marker. `ParticipationRequired` and `WithParticipation` are unchanged. |
| +**Interfaces:** none. With no participation required, it returns nil and writes no marker. |
| |
| - [ ] **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")) |
| + a := testApplier(t); t.Setenv("CARLOS_REGION_HA", "1"); 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 (`errSystemDeferred`). |
| -- [ ] **Step 3: Implement.** Return nil when `!required`, take the `WithParticipation` arm otherwise, and delete the field. Then update the listed tests. |
| +- [ ] **Step 3: Implement.** Return nil when `!required`, and take `WithParticipation` otherwise. Delete the field, and 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 and the box reference, on every box |
| +### Task 5: The owner and box identity, set by `agentEntry` on every box |
| |
| **Files:** |
| -- 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(...)`) |
| +- 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/agententry.go` (Task 2's file); `internal/host/agent.go:229` |
| |
| **Interfaces:** |
| -- Produces: |
| |
| ```go |
| package hafresh |
| @@ -203,14 +194,16 @@ func ParseOwner(s string) (Owner, bool) // strict: ref, iid (optional), pid, ha |
| |
| ```go |
| package lease |
| -func SetSelf(s hafresh.Self) // atomic; safe to call again when the IID arrives |
| +func SetSelf(s hafresh.Self) // atomic; called again when the IID arrives |
| func currentOwner(ha bool) string |
| ``` |
| |
| ```go |
| package host |
| -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 |
| +func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration, |
| + logf func(string, ...any), identity func() hafresh.Self, run func()) // after the group-reference wait: lease.SetSelf(identity()), then run() |
| +func haSelfNow(getenv func(string) string, client *http.Client) hafresh.Self // Ref: metricsBoxLabel(getenv, readMachineID()); IID: one identity-document read, 2 s timeout, "" on failure |
| +func haSelfRetry(ctx context.Context, getenv func(string) string, client *http.Client, every time.Duration, set func(hafresh.Self)) // while IID is "", every minute |
| ``` |
| |
| - [ ] **Step 1: Test** |
| @@ -220,47 +213,36 @@ 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) } |
| - for _, bad := range []string{"ip-10-0-0-1:77", "moved:mv_1", "box/v1;ref=a;pid=1;extra=2", "box/v1;iid=i-1;ref=a;pid=1", "box/v2;ref=a;pid=1"} { |
| + for _, bad := range []string{"ip-10-0-0-1:77", "moved:mv_1", "box/v1;ref=a;pid=1;extra=2", "box/v1;iid=i-1;ref=a;pid=1"} { |
| if _, ok := hafresh.ParseOwner(bad); ok { t.Errorf("parsed %q", bad) } |
| } |
| if hafresh.OwnerFor(hafresh.Self{Ref: "ie-box"}, 1, false) != "box/v1;ref=ie-box;pid=1" { t.Fatal("empty iid kept") } |
| } |
| -func 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(fx.Lock("instances/h").Owner); !ok || o.Ref != "ie-box" || o.IID != "i-0abc" || o.HA { t.Fatalf("%+v %v", o, ok) } |
| +func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) { // internal/host, r2.10: deleting the SetSelf call in agentEntry fails this |
| + fx := leasetest.NewLockFixture(t) |
| + var owner string |
| + agentEntry(envOf(nil), nil, groupReferenceBackoff, t.Logf, func() hafresh.Self { return hafresh.Self{Ref: "ie-box", IID: "i-0abc"} }, func() { |
| + h, err := lease.Acquire(ctx, fx.Bucket, "instances/h", ""); if err != nil { t.Fatal(err) } |
| + owner = fx.LockOwner("instances/h"); h.Release(ctx) |
| + }) |
| + if o, ok := hafresh.ParseOwner(owner); !ok || o.Ref != "ie-box" || o.IID != "i-0abc" { t.Fatalf("%q", owner) } |
| } |
| ``` |
| |
| -- [ ] **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 2: Run** `./internal/hafresh/ ./internal/host/ -run 'TestOwnerRoundTrip|TestAgentEntrySetsOwnerBeforeRun'`. It FAILs. Land Task 6's fixture first, or write this test after it. |
| +- [ ] **Step 3: Implement** as specified. Production passes `identity = func() hafresh.Self { return haSelfNow(os.Getenv, imdsClient) }`, and `run` starts `haSelfRetry`. |
| - [ ] **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" |
| +- [ ] **Step 5: Commit** "lease owner names the box on every box, set by agentEntry" |
| |
| -### Task 6: The acquire table, sticky HA in `lease.Acquire`, and the shared fixture [own review] |
| +### Task 6: The HA acquire: one table, the exact ETag, an empty-prefix first wake [own review] |
| |
| This is I1's one place. |
| |
| **Files:** |
| -- 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: |
| +- Create: `internal/hafresh/lock.go`, `internal/hafresh/acquire.go` and its test; `internal/lease/ha.go`; `internal/lease/ha_test.go` (`package lease_test`); `internal/lease/leasetest/lockfixture.go` |
| +- Modify: `internal/lease/export_test.go` (narrow access: `LockHeldForTest = lockHeld`, `LeaseFreeForTest = leaseFree`, `AcquireHATTL = acquireHATTL`) |
| |
| -```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) |
| -``` |
| +**Interfaces** (compile-checked against this branch with stubs; see "Dry run"): |
| |
| ```go |
| package hafresh |
| @@ -273,43 +255,60 @@ type Lock struct { |
| Release *Marker `json:"carlos_release,omitempty"` |
| } |
| type View struct{ Absent bool; Lock Lock; ETag string } |
| -func DecodeLock(body []byte, etag string) (View, error) // no expiry is an error, never free |
| +func DecodeLock(body []byte, etag string) (View, error) // a lock with no expiry is an error |
| func MarkerBody(generation int64, m Marker) ([]byte, error) |
| -func (v View) HAOn() bool // Release != nil, or an owner that parses with HA |
| +func (v View) HAOn() bool // a release marker, or an owner that parses with HA |
| type Action int |
| -const ( ActTake Action = iota + 1; ActHeld; ActRefuse ) |
| +const ( ActCreate Action = iota + 1; ActTake; ActHeld; ActRefuse ) |
| type Decision struct{ Action Action; Reason string } |
| type Proofs struct{ SameBoxEmpty func() (bool, error) } |
| -func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision // HA-on views only |
| +func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision // for HA hosts only |
| ``` |
| |
| ```go |
| package lease |
| type RefusedError struct{ Reason string } |
| func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) |
| -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 |
| +func PrefixEmpty(ctx context.Context, bucket, prefix, region string) (bool, error) // one ListObjectsV2, max-keys 1 |
| +func AcquireHA(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*Held, error) |
| +func (h *Held) HA() bool |
| +func (h *Held) View() hafresh.View |
| +``` |
| + |
| +```go |
| +package leasetest |
| +type LockFixture struct{ Bucket string /* server, hooks */ } |
| +func NewLockFixture(t *testing.T) *LockFixture // sets AWS_* and CARLOS_S3_ENDPOINT |
| +func (f *LockFixture) PutLock(prefix string, body []byte) |
| +func (f *LockFixture) PutObject(key string, body []byte) |
| +func (f *LockFixture) LockBody(prefix string) []byte |
| +func (f *LockFixture) LockOwner(prefix string) string |
| +func (f *LockFixture) Requests() []string // "GET key", "PUT key", "LIST prefix", "DELETE key", in order |
| +func (f *LockFixture) FailNext(method string, status int) |
| +func (f *LockFixture) BeforeWrite(hook func(method, key string)) |
| ``` |
| |
| -**`DecideAcquire`, for an HA-on view:** |
| +**`DecideAcquire`:** |
| |
| | Lock | Action, reason | |
| |---|---| |
| -| `Release != nil` (clean or not) | `ActTake`, `release marker` | |
| -| unexpired | `ActHeld`, the owner | |
| +| absent | `ActCreate`, `absent` | |
| +| present, not HA-format | `ActRefuse`, `leftover lock` | |
| +| release marker (clean or not) | `ActTake`, `release marker` | |
| +| unexpired HA owner | `ActHeld`, the owner | |
| | 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` | |
| |
| -**`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. |
| +**`AcquireHA`,** used only for HA hosts and never falling back to litestream's `AcquireLease`: |
| +1. GET the lock with its ETag. |
| +2. Decide. |
| +3. For `ActCreate`: `PrefixEmpty` must be true, else `*RefusedError{"leftover data"}`. Then PUT with `If-None-Match: *`. |
| +4. For `ActTake`: PUT with `If-Match: <the ETag classified>`, generation + 1, owner `currentOwner(true)`. |
| +5. Any 412: back to step 1, at most 3 rounds. |
| 6. Start the renewer with the returned ETag. |
| +7. If the renewer's health fails before returning (a late acknowledgement), release through Task 7's unclean marker, never a DELETE. |
| |
| -`ActHeld` returns `*HeldError`; `ActRefuse` returns `*RefusedError`. On an absent lock the cost is unchanged: one PUT. |
| +`base` (box, IID, lifetime) is kept on the `Held` for Task 7's unclean releases. |
| |
| - [ ] **Step 1: Test** |
| |
| @@ -319,8 +318,9 @@ 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{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ActRefuse}, |
| {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}, |
| @@ -328,112 +328,124 @@ func TestDecideAcquireTable(t *testing.T) { // hafresh |
| } { |
| 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 |
| +func TestMarkerReadAsFreeByOldReaders(t *testing.T) { // lease_test |
| body, _ := hafresh.MarkerBody(7, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: 12, Clean: true}) |
| var l litestream.Lease |
| if err := json.NewDecoder(bytes.NewReader(body)).Decode(&l); err != nil || !l.IsExpired() { t.Fatal(err) } |
| - if lockHeld(l.ExpiresAt, time.Now()) || !leaseFree(l.ExpiresAt, time.Now()) { t.Fatal("marker read as held") } |
| + if lease.LockHeldForTest(l.ExpiresAt, time.Now()) || !lease.LeaseFreeForTest(l.ExpiresAt, time.Now()) { t.Fatal("read as held") } |
| } |
| -func TestAcquireTakesMarkerAsHAThenRenews(t *testing.T) { // lease, Review Focus 5 of rev 1 |
| - fx := leasetest.NewLockFixture(t); SetSelf(hafresh.Self{Ref: "a", IID: "i-a"}) |
| +func TestAcquireHAMarkerCostsOneGetOnePut(t *testing.T) { // r2.12 |
| + fx := leasetest.NewLockFixture(t); lease.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) } |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}) |
| + if err != nil || !h.HA() { t.Fatal(err) } |
| + if r := fx.Requests(); !slices.Equal(r, []string{"GET instances/h/lock.json", "PUT instances/h/lock.json"}) { t.Fatalf("%v", r) } |
| } |
| -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) || len(fx.Writes()) != 1 { t.Fatalf("%v %v", err, fx.Writes()) } // only the failed create |
| +func TestAcquireHAReclassifiesOnConflict(t *testing.T) { // r2.6 interleaving |
| + fx := leasetest.NewLockFixture(t); lease.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) |
| + fx.BeforeWrite(func(m, k string) { fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "c", IID: "i-c"}, 1, true), time.Now().Add(time.Hour))) }) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + var held *lease.HeldError |
| + if !errors.As(err, &held) || !strings.Contains(held.Owner, "ref=c") { t.Fatalf("did not reclassify: %v", err) } |
| } |
| -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) } |
| +func TestAcquireHAFirstWakeRefusesLeftovers(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t); fx.PutObject("instances/h/files/0/manifest.json", []byte(`{}`)) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + var r *lease.RefusedError |
| + if !errors.As(err, &r) || slices.ContainsFunc(fx.Requests(), func(s string) bool { return strings.HasPrefix(s, "PUT") }) { t.Fatal(err) } |
| +} |
| +func TestAcquireHALateAckWritesUncleanMarker(t *testing.T) { // r2.1 |
| + fx := leasetest.NewLockFixture(t); delayPutAck(t, fx, 4*time.Second) // the PUT lands, its answer arrives past the safe deadline |
| + if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second); err == nil { t.Fatal("late ack accepted") } |
| + v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| + if v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean { t.Fatalf("HA lock not left as an unclean marker: %+v", v) } |
| } |
| ``` |
| |
| -- [ ] **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" |
| +- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestDecideAcquireTable|TestMarkerReadAsFree|TestAcquireHA'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `leaseBody` and `delayPutAck` are test helpers in `ha_test.go`. |
| +- [ ] **Step 4: Run** the same, plus `./internal/lease/ -run 'TestAcquire|TestTombstone|TestLockState|TestFastAcquire'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA acquire: one table, conditional on the exact ETag classified, empty-prefix first wake" |
| |
| -### Task 7: The one marker release, its obligation, and stream capture [own review] |
| +### Task 7: The one HA release; `lease` never deletes an HA lock [own review] |
| |
| **Files:** |
| -- 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) |
| +- Create: `internal/lease/release.go`, `internal/lease/release_test.go` (`package lease_test`) |
| +- Modify: |
| + - `internal/lease/lease.go:285-303` (`Held.Release`) and `:497-524` (`Replicator.Close`): an HA handle routes to `releaseWithMarker` with `base` and `Clean: false`, plus the TXID for `Close`; |
| + - `:401-429` (`newStore` uses the Held's monitor interval); |
| + - `:435-445` (`Replicator` keeps the HA flag, base and generation). |
| |
| **Interfaces:** |
| -- Produces: |
| |
| ```go |
| package lease |
| -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 (h *Held) SetMonitorInterval(d time.Duration) // 0 keeps dbMonitorInterval (10 s) |
| +func (h *Held) ReleaseMarker(ctx context.Context, m hafresh.Marker) error // before replication |
| +func (r *Replicator) Finish(ctx context.Context) (txid uint64, err error) // SyncAndWait + store close; renewer running |
| +func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error |
| func (r *Replicator) HA() bool |
| type Obligation struct{ Bucket, Region, Key, ETag string; Body []byte } |
| +type ObligationError struct{ Obligation Obligation; Err error } // Error, Unwrap |
| func RetryObligation(ctx context.Context, o Obligation) error |
| var ErrObligationVoid = errors.New("lease: the marker's lease is no longer ours") |
| ``` |
| |
| -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)`. |
| +All HA releases call the 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; |
| +- 412: nil (someone else holds it now); |
| +- otherwise: `*ObligationError` with the exact body and ETag. |
| |
| -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. |
| +`RetryObligation` returns nil, `ErrObligationVoid` on a 412, or the error. It never reads expiry. Non-HA handles keep today's DELETE. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| -func TestReleaseMarkerOverwritesLock(t *testing.T) { |
| +func TestHAReleaseAndCloseNeverDelete(t *testing.T) { // r2.1 |
| + fx := leasetest.NewLockFixture(t) |
| + if err := haHeld(t, fx, "instances/a").Release(ctx); err != nil { t.Fatal(err) } |
| + if err := haReplicator(t, fx, "instances/b").Close(ctx); err != nil { t.Fatal(err) } // cleanup after replication started |
| + for _, p := range []string{"instances/a", "instances/b"} { |
| + v, _ := hafresh.DecodeLock(fx.LockBody(p), "") |
| + if v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean { t.Fatalf("%s: %+v", p, v) } |
| + } |
| + if slices.ContainsFunc(fx.Requests(), func(s string) bool { return strings.HasPrefix(s, "DELETE") }) { t.Fatal("HA lock deleted") } |
| +} |
| +func TestCleanReleaseMarker(t *testing.T) { |
| 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) } |
| - 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) } |
| + if err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Box: "a", IID: "i-a", TXID: txid, Clean: true}); err != nil { t.Fatal(err) } |
| + if v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), ""); !v.Lock.Release.Clean || v.Lock.Release.TXID != txid { t.Fatalf("%+v", v) } |
| } |
| -func TestFailedMarkerPutIsAnObligationExpiryNeverDischarges(t *testing.T) { |
| +func TestFailedMarkerIsAnObligationExpiryNeverDischarges(t *testing.T) { |
| 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) } |
| + err := r.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}) |
| + var oe *lease.ObligationError |
| + if !errors.As(err, &oe) || oe.Obligation.ETag == "" { t.Fatal(err) } |
| time.Sleep(3 * time.Second) |
| - if err := RetryObligation(ctx, *ob); err != nil { t.Fatalf("retry after expiry: %v", err) } |
| + if err := lease.RetryObligation(ctx, oe.Obligation); err != nil { t.Fatalf("retry after expiry: %v", err) } |
| } |
| func TestStreamCaptureOneSecond(t *testing.T) { |
| 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) } |
| + if lease.MonitorIntervalForTest(h, tempDB(t)) != time.Second { t.Fatal("interval not applied") } // export_test.go |
| } |
| ``` |
| |
| -- [ ] **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** "one marker release for held and replicating handles, with a durable obligation; HA locks are never deleted" |
| +- [ ] **Step 2: Run** `./internal/lease/ -run 'TestHARelease|TestCleanReleaseMarker|TestFailedMarker|TestStreamCapture'`. It FAILs. |
| +- [ ] **Step 3: Implement** as specified. `haHeld`, `haReplicator` and `haReplicatorTTL` are test helpers over `AcquireHA` and `Replicate`. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestRelease|TestReplicate'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "lease: one HA release; Release, Close and acquire cleanup write a marker, never a delete" |
| |
| ### Task 8: The keep decision and the local record [own review] |
| |
| This is I2's one place. |
| |
| -**Files:** |
| -- Create: `internal/hafresh/keep.go` and its test; `internal/activator/harecord.go`, `harecord_linux.go`, `harecord_other.go` and its test |
| +**Files:** create `internal/hafresh/keep.go` and its test; `internal/activator/harecord.go`, `harecord_linux.go`, `harecord_other.go` and its test. |
| |
| **Interfaces:** |
| -- Produces: |
| |
| ```go |
| package hafresh |
| @@ -443,9 +455,7 @@ type LocalNow struct { HaveRecord bool; Record LocalRecord; DBExists bool; DB Fi |
| func DecideKeep(v View, self Self, lifetime string, now LocalNow) (keep bool, reason string) |
| ``` |
| |
| -Reasons, in check order: |
| -- `no-marker`, `unclean`, `other-box`, `lifetime` (an empty `lifetime` counts), `no-record`, `txid`, `files-gen`, `no-db`, `db-changed`, `wal`, `tree-changed`; |
| -- `kept` when it keeps. |
| +Reasons, in order: `no-marker`, `unclean`, `other-box`, `lifetime` (an empty one counts), `no-record`, `txid`, `files-gen`, `no-db`, `db-changed`, `wal`, `tree-changed`; `kept` when it keeps. |
| |
| ```go |
| package activator |
| @@ -469,21 +479,17 @@ 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, n *LocalNow, _ *string) { m.Clean = false; n.Record.Marker.Clean = false }) // a matching but unclean pair |
| + try("unclean", func(m *Marker, n *LocalNow, _ *string) { m.Clean = false; n.Record.Marker.Clean = false }) |
| try("other-box", func(m *Marker, _ *LocalNow, _ *string) { m.IID = "i-b" }) |
| try("lifetime", func(_ *Marker, _ *LocalNow, l *string) { *l = "" }) |
| try("txid", func(_ *Marker, n *LocalNow, _ *string) { n.Record.Marker.TXID = 8 }) |
| try("db-changed", func(_ *Marker, n *LocalNow, _ *string) { n.DB.CtimeNs++ }) |
| try("wal", func(_ *Marker, n *LocalNow, _ *string) { n.WALEmpty = false }) |
| try("tree-changed", func(_ *Marker, n *LocalNow, _ *string) { n.TreeDigest = "e" }) |
| - if k, r := DecideKeep(View{}, self, "L1", ok); k || r != "no-marker" { t.Fatal(r) } |
| } |
| -func TestTreeDigestAbsentDirStable(t *testing.T) { // Review Focus 4 |
| - dir := filepath.Join(t.TempDir(), "absent"); env := filepath.Join(t.TempDir(), "h.env"); os.WriteFile(env, []byte("A=1\n"), 0o600) |
| - a, err1 := treeDigest(dir, env); b, err2 := treeDigest(dir, env) |
| - if err1 != nil || err2 != nil || a != b { t.Fatalf("%v %v", err1, err2) } |
| -} |
| -func TestTreeDigestSeesChmod(t *testing.T) { |
| +func TestTreeDigestStableAndSeesChmod(t *testing.T) { // activator, linux |
| + absent := filepath.Join(t.TempDir(), "absent"); a, _ := treeDigest(absent, ""); b, _ := treeDigest(absent, "") |
| + if a != b { t.Fatal("absent dir unstable") } |
| dir := filesTree(t, map[string]string{"report.token": "x"}); before, _ := treeDigest(dir, "") |
| os.Chmod(filepath.Join(dir, "report.token"), 0o640) |
| if after, _ := treeDigest(dir, ""); after == before { t.Fatal("chmod not seen") } |
| @@ -495,25 +501,26 @@ 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: keep or restore into a clean tree, on every box [own review] |
| +### Task 9: Born-HA classification and the HA wake [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(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` 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). |
| + - `internal/provision/provision.go:41` (`Record.HA bool` with `json:"ha,omitempty"`, additive); |
| + - `internal/provision/reconcile.go:36` (`ReconcileConfig.Lifetimes`), `:940-1100` (the scan calls `Replace` after a complete scan, `Merge` after a partial one); |
| + - `internal/activator/activator.go:95-107` (`Config.Record`, `Config.Self`), `:1080-1090` (`errLeaseRefused`), `:5495-5511` (503 with `Retry-After: 10`); |
| + - `internal/activator/backend_exec.go`: |
| + - `:716-738` (`Acquire`: an HA host uses `lease.AcquireHA`; anything else, today's `lease.Acquire`); |
| + - `:754-787` (the `execLease` adapters); |
| + - `:805-860` (`restorePlain` sends HA hosts to `restoreHA`); |
| + - the `ExecBackend` fields `Registry *registry.Registry` and `FilesStore release.Store`; |
| + - `internal/host/agent.go` (wires `Record` from the index, with `provision.GetRecord` on a miss). |
| |
| -**Interfaces:** |
| -- Consumes: `lease.Acquire`, `(*Held).HA`, `(*Held).View`, `hafresh.DecideKeep`, `readLocalNow`. |
| -- Produces: |
| +**Interfaces** (compile-checked): |
| |
| ```go |
| package provision |
| -type LifetimeEntry struct{ ID string; Created time.Time } // ID = Incarnation(acct, app, host, rec.CreatedAt) |
| +type LifetimeEntry struct{ ID string; Created time.Time; HA bool } // ID = Incarnation(acct, app, host, rec.CreatedAt) |
| type LifetimeIndex struct{ /* mu, m */ } |
| func (x *LifetimeIndex) Replace(recs map[string]Record) |
| func (x *LifetimeIndex) Merge(recs map[string]Record) |
| @@ -522,97 +529,93 @@ 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) |
| +// Config.Record: the host's record facts; host wiring = index, then provision.GetRecord on a miss. |
| +// Record func(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, error) |
| +type haLease interface{ HA() bool; View() hafresh.View; SetMonitorInterval(d time.Duration) } // *execLease |
| +type haRep interface { // *lease.Replicator |
| + HA() bool; Finish(ctx context.Context) (uint64, error); ReleaseMarker(ctx context.Context, m hafresh.Marker) 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/ and rename over; EnvItem to <host>.env; WakeItem via ImportWake; no manifest leaves an empty tree |
| +func (b *ExecBackend) isHA(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, bool, error) // record HA, or an HA-format lock (ReadLock only when the record is not HA and the index missed) |
| +func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafresh.View, first bool) (fresh bool, err error) |
| +func (b *ExecBackend) setAside(p instancePaths, host string) error |
| +func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error // into <host>.restore/, then rename over; EnvItem to <host>.env; WakeItem via ImportWake |
| ``` |
| |
| -**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: |
| +**Behaviour, whatever `CARLOS_REGION_HA` says:** |
| +- **An HA host:** |
| + - first wake (absent lock): `fresh = true`, with an empty tree; |
| - keep: log `activator: <host>: kept local`; |
| - otherwise: `setAside`, `restoreReplica`, `restoreFilesClean`, then log `activator: <host>: restored (<reason>)`. |
| -- The staging fallback never runs for an HA-on host. |
| -- Hosts that are not HA-on take today's path unchanged. |
| +- The staging fallback never runs for an HA host. |
| +- A record index miss reads the record; if that read fails, the wake fails, never falling back to legacy. |
| +- Non-HA hosts take today's path unchanged. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| func TestRestoreHAKeepsOnlyOnProof(t *testing.T) { |
| - b, rt := haBackend(t, "shop.example.com") // Self{a,i-a}, Lifetime L1, restoreReplica seam counting calls |
| + b, rt := haBackend(t, "shop.example.com") // Self{a,i-a}, record L1 HA, restoreReplica seam counting calls |
| writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: 5, Clean: true}) |
| - if fresh, err := b.restoreHA(ctx, rt, markerView("a", "i-a", "L1", 5, true)); err != nil || fresh || restoreCalls != 0 { t.Fatal(err) } |
| - b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true)) |
| + if fresh, err := b.restoreHA(ctx, rt, markerView("a", "i-a", "L1", 5, true), false); err != nil || fresh || restoreCalls != 0 { t.Fatal(err) } |
| + b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true), false) |
| if restoreCalls != 1 || !exists(dbPath(b, rt)+".stale") { t.Fatal("not set aside and restored") } |
| } |
| func TestRestoreHAFilesIntoCleanTree(t *testing.T) { |
| b, rt := haBackend(t, "shop.example.com"); publishManifest(t, b, rt, map[string]string{"a.txt": "s3"}) |
| writeFiles(t, b, rt, map[string]string{"a.txt": "local", "stray.txt": "x"}) |
| - b.restoreHA(ctx, rt, hafresh.View{}) |
| + b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true), false) |
| 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{}); err == nil { t.Fatal("wake proceeded over an old tree") } |
| + if _, err := b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true), false); 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 |
| +func TestHAHostRulesHoldWithSwitchOff(t *testing.T) { // Review Focus 5 |
| + b, rt := haBackend(t, "shop.example.com"); t.Setenv("CARLOS_REGION_HA", "") |
| 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 |
| + putLockFor(t, b, rt, markerBody("b", "i-b", "L1", 6, true)) |
| + if _, err := b.Acquire(ctx, rt); err != nil { t.Fatal(err) } |
| + if fresh, err := b.Restore(ctx, rt); err != nil || fresh || restoreCalls != 1 { t.Fatal("stale copy reused with the switch off") } |
| +} |
| +func TestIndexMissReadsRecordBeforeAcquire(t *testing.T) { // Review Focus 1 |
| + b, rt := haBackendEmptyIndex(t, "shop.example.com") // the record in the deployment store says HA |
| 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) } |
| + if !lockIsHA(t, b, rt) || recordGets(b) != 1 { t.Fatal("an HA host was treated as legacy after a restart") } |
| } |
| func TestHAWakeSkipsStagingFallback(t *testing.T) { |
| b, rt := haBackend(t, "shop.example.com"); fm := stagingMirrorWithObjects(t); b.Mirror = fm |
| - 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) |
| - x.Replace(map[string]Record{"h": {Account: "acct", App: "app", Host: "h", CreatedAt: created}}) |
| - e, ok := x.Lookup("h"); want, _ := Incarnation("acct", "app", "h", created) |
| - if !ok || e.ID != want || !e.Created.Equal(created) { t.Fatalf("%+v", e) } |
| + b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true), false) |
| + if fm.promoted { t.Fatal("staging promoted for an HA host") } |
| } |
| ``` |
| |
| -- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAOnHostRules|TestHAWake|TestLifetimeIndex'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAHostRules|TestIndexMiss|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-on hosts: keep on proof, otherwise restore DB and files into a clean tree, on every box" |
| +- [ ] **Step 5: Commit** "born-HA hosts: keep on proof, otherwise restore DB and files into a clean tree, on every box" |
| |
| -### Task 10: Files on the entry; every release writes a marker [own review] |
| +### Task 10: Files on the entry; every HA release persists its obligation [own review] |
| |
| **Files:** |
| - Create: `internal/activator/hafiles.go`, `internal/activator/harelease.go` and their tests |
| - Modify: |
| - - `internal/hostfiles/publisher.go` (`Gen`); |
| + - `internal/hostfiles/sync.go` (`SyncStats.Complete`), `internal/hostfiles/publisher.go` (`Gen`); |
| - `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); |
| + - `actEntry` gains `files`, `filesStop` and `filesDone`; |
| + - `:279-303` (`giveBack` and `oweRelease` call `noteReleaseErr`); |
| + - `:4378-4410` (`finishStop`: an HA entry calls `releaseHAClean`; a `Close` error goes to `noteReleaseErr`); |
| + - `:2621` (for an HA stream-class host: `lease.(haLease).SetMonitorInterval(time.Second)` before `Replicate`); |
| + - the wake after `Replicate` (`startFiles(e)` on the service's lifetime context); |
| - `Start` (`loadOwed`), and the sweep (`retryOwed`). |
| - - `internal/activator/maintenance.go:360` (`cleanupFailedWake`: `stopFiles(e)` before the release). |
| + - `internal/activator/maintenance.go:360-440` (`cleanupFailedWake`: `stopFiles(e)` first; its `w.rep.Close` error goes to `noteReleaseErr`). |
| |
| **Interfaces:** |
| -- Consumes: `hostfiles.Open`, `SyncDir`, `StagePlatform`, `Commit`, `ExportWake`, `StageWake`; `haLease`, `haRep`, `lease.RetryObligation`; `writeReleaseRecord`, `statFileID`, `treeDigest`. |
| -- Produces: |
| |
| ```go |
| package hostfiles |
| -func (p *Publisher) Gen() string // "<seq>:<sha256 hex of the committed manifest body>" |
| +func (s SyncStats) Complete() bool // no TooLarge, NotRegular, Unreadable, Retry or Torn |
| +func (p *Publisher) Gen() string // "<seq>:<sha256 hex of the committed manifest body>" |
| ``` |
| |
| ```go |
| @@ -620,62 +623,47 @@ package activator |
| func (b *ExecBackend) filesPrefix(host string) string // hibernatePrefix(host) + "/files/0/" |
| type hostFiles struct{ /* publisher, paths, host, reg */ } |
| func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) |
| -func (f *hostFiles) Run(ctx context.Context) // trio + wake state every 1 s when changed; app files every files_snapshot_interval when the local digest changed |
| +func (f *hostFiles) Run(ctx context.Context) // trio + wake state every 1 s when changed; app files every files_snapshot_interval |
| func (f *hostFiles) PublishPlatformNow(ctx context.Context) error |
| func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err 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 |
| +func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error // stopFiles, Final, Finish, writeReleaseRecord, ReleaseMarker(Clean = complete && Finish ok) |
| +func (a *Service) noteReleaseErr(host string, err error) // *lease.ObligationError: <db>.release-owed.json (fsynced) and the queue; otherwise today's oweRelease |
| +func (a *Service) loadOwed() |
| +func (a *Service) retryOwed(ctx context.Context) // backoff 1 min doubling to 10 min; the file goes on nil or ErrObligationVoid |
| ``` |
| |
| -**`releaseHA`, in order:** |
| -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`. |
| - |
| -`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. |
| +Before acquiring a host with an owed file, `retryOwed` runs for it. If the marker is still owed, the wake answers `errLeaseRefused{"marker owed"}`. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| -func TestFinalPublishIncompleteMarksUnclean(t *testing.T) { |
| - 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 TestCompleteRefusesRetryAndTorn(t *testing.T) { // hostfiles, r2.8, through the existing seams |
| + dir := tree(t, map[string]string{"a.txt": "1"}); p := openPublisher(t) |
| + betweenLookAndOpen = func() { replaceFile(t, dir, "a.txt") }; t.Cleanup(func() { betweenLookAndOpen = func() {} }) |
| + if st, _ := SyncDir(ctx, p, dir, nil); len(st.Retry) == 0 || st.Complete() { t.Fatalf("%+v", st) } |
| + betweenLookAndOpen = func() {} |
| + readAll = func(r io.Reader) ([]byte, error) { b, err := io.ReadAll(r); touchFile(t, dir, "a.txt"); return b, err }; t.Cleanup(func() { readAll = io.ReadAll }) |
| + if st, _ := SyncDir(ctx, p, dir, nil); len(st.Torn) == 0 || st.Complete() { t.Fatalf("%+v", st) } |
| } |
| -func TestFailedRestoreLeavesUncleanMarkerAndStaleCopyRestores(t *testing.T) { // F1 witness |
| - a, e := haServiceEntry(t, "shop.example.com"); failRestoreOnce(t, a) |
| +func TestFailedWakeAfterReplicationLeavesUncleanMarker(t *testing.T) { // r2.1 |
| + a, e := haServiceEntry(t, "shop.example.com"); failAfterReplicate(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") } |
| + if v := lockView(t, e); v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean { t.Fatalf("%+v", v) } |
| } |
| -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 TestNoWriteAfterMarker(t *testing.T) { |
| + a, e := haServiceEntry(t, "shop.example.com"); keepWriting(t, e) |
| + a.releaseHAClean(ctx, e) |
| + if w := storeWrites(t, e); w[len(w)-1] != "PUT "+lockKey(e) { 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) |
| +func TestOwedMarkerRetriedBeforeAcquire(t *testing.T) { // Review Focus 2 |
| + a, e := haServiceEntry(t, "shop.example.com"); failMarkerPuts(t, e, 1); a.releaseHAClean(ctx, e) |
| if !exists(owedPath(e)) { t.Fatal("obligation not persisted") } |
| a2 := restartService(t, a); expireLease(t, e) |
| if _, err := a2.backend.Acquire(ctx, e.route); err != nil { t.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") } |
| + w := lockWrites(t, e) |
| + if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], a2.Cfg.Self) || exists(owedPath(e)) { t.Fatalf("%v", w) } |
| } |
| func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| f := hostFilesFixture(t, nil); go f.Run(ctx); writeEnv(t, f, "CARLOS_INSTANCE_KEY=k1\n") |
| @@ -683,222 +671,69 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| } |
| ``` |
| |
| -- [ ] **Step 2: Run** `./internal/activator/ -run 'TestFinalPublishIncomplete|TestFailedRestoreLeaves|TestNoWriteAfterMarker|TestOwedMarker|TestTrioPublished'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/hostfiles/ -run TestCompleteRefusesRetryAndTorn` and `./internal/activator/ -run 'TestFailedWakeAfterReplication|TestNoWriteAfterMarker|TestOwedMarker|TestTrioPublished'`. They FAIL. |
| - [ ] **Step 3: Implement** as specified. |
| -- [ ] **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" |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestStop|TestCleanupFailedWake|TestShutdown|TestGiveBack'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA release: entry-owned publisher, clean marker only when complete, every obligation persisted" |
| |
| -### Task 11: Secrets on the holder only, published before every launch |
| +### Task 11: One mint gate; secrets published before every launch |
| |
| **Files:** |
| - Create: `internal/activator/hasecrets.go` and its test |
| - Modify: |
| - - `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). |
| + - the three launch paths, before any token or key call: `internal/activator/prepare.go:83`, `internal/activator/backend_exec.go:1034`, `:2130`. Each calls `haMintGate`, then the existing ensure calls, then `haSecretsReady`; |
| + - `internal/host/instancekeys.go:75-85` (skip HA hosts); |
| + - `internal/host/schedule_wiring.go:186-205` (for HA hosts `prepare` only reads, and answers `""` when absent); |
| + - `internal/activator/activator.go:5394-5404` (`ServeScheduled` fills the bearer token from the restored env after the wake). |
| |
| **Interfaces:** |
| -- 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 (b *ExecBackend) haMintGate(ctx context.Context, rt registry.Route) error // HA host: if the manifest exists and <host>.env lacks CARLOS_ADMIN_TOKEN or CARLOS_INSTANCE_KEY, ErrInstanceKeyDeferred; else nil |
| +func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) error // sha256(<host>.env) == the manifest's host.env item, else publish and wait; an error fails the launch |
| func (a *Service) fillScheduledToken(r *http.Request, rt registry.Route) error |
| ``` |
| |
| +On the first wake the order is: no manifest exists, so the existing calls mint both values. `haSecretsReady` then publishes the env, the empty files tree and the wake state. Only then does the app start. |
| + |
| - [ ] **Step 1: Test** |
| |
| ```go |
| -func TestHATokenNotMintedBesideAManifest(t *testing.T) { // F4: an env with a key but no token |
| +func TestHATokenNotMintedBesideAManifest(t *testing.T) { // r2.3 |
| 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) } |
| + if err := b.launchForTest(ctx, rt); !errors.Is(err, ErrInstanceKeyDeferred) || envHas(t, b, rt, "CARLOS_ADMIN_TOKEN") { t.Fatal(err) } |
| } |
| -func TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) { // F4: a mint whose publish failed |
| +func TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) { |
| 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") } |
| + if err := b.launchForTest(ctx, rt); err != nil || !strings.Contains(platformEnv(t, b, rt), "CARLOS_ADMIN_TOKEN=") { t.Fatal(err) } |
| +} |
| +func TestFirstWakeCrashBeforePublishRemints(t *testing.T) { // Review Focus 4 |
| + b, rt := haBackend(t, "fresh.example.com"); crashBeforePublish(t, b); b.launchForTest(ctx, rt) |
| + b2 := otherBox(t, b) |
| + if err := b2.launchForTest(ctx, rt); err != nil || platformEnv(t, b2, rt) == "" { t.Fatal(err) } |
| } |
| func TestHAScheduleTokenNeverMints(t *testing.T) { // internal/host |
| - dd := t.TempDir(); reg := testRegistryHAOn(t, "shop.example.com") |
| + dd := t.TempDir(); reg := testRegistryHA(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 '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 (`package lease`) |
| - |
| -**Interfaces:** |
| -- Produces: |
| - |
| -```go |
| -package hafresh |
| -type Inventory struct{ Box string `json:"box"`; At time.Time `json:"at"`; Hosts map[string]uint64 `json:"hosts"` } |
| -func InventoryKey(region, ref string) string // "control/ha-migration/<region>/<ref>.json" |
| -type MigrationInput struct { |
| - Host, Self string; HasLocal, LocalWALEmpty bool; LocalTXID uint64 |
| - RemoteExists bool; RemoteHead uint64; RowCreated, RecordCreated time.Time |
| - ViewBoxes []string; Inventories []Inventory; Tombstone, Staging bool |
| -} |
| -type Verdict int |
| -const ( Migrate Verdict = iota + 1; Wait; Refuse ) |
| -func MigrationGate(in MigrationInput) (Verdict, string) |
| -``` |
| - |
| -```go |
| -package lease |
| -func RemoteHeadTXID(ctx context.Context, bucket, prefix, region string) (txid uint64, exists bool, err error) // L0 first, deeper levels only if L0 is empty; paginates |
| -func LocalTXID(dbPath string) (txid uint64, walEmpty bool, err error) // max over <dir>/.activator-<db>-litestream/ltx/0/*.ltx (ltx.ParseFilename); walEmpty = no -wal, or size 0 |
| -``` |
| - |
| -**The gate, in order:** |
| - |
| -| Condition | Verdict, reason | |
| -|---|---| |
| -| `Tombstone` or `Staging` | `Refuse`, `move` | |
| -| a view box has no inventory | `Wait`, `inventories` | |
| -| another inventory lists the host | `Refuse`, `two-copies` | |
| -| `!HasLocal && !RemoteExists` | `Migrate`, `empty` (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` | |
| -| otherwise | `Migrate`, `ok` | |
| - |
| -- [ ] **Step 1: Test** |
| - |
| -```go |
| -func TestMigrationGate(t *testing.T) { |
| - base := MigrationInput{Host: "h", Self: "a", HasLocal: true, LocalWALEmpty: true, LocalTXID: 7, RemoteExists: true, RemoteHead: 7, |
| - RowCreated: time.Unix(200, 0), RecordCreated: time.Unix(100, 0), ViewBoxes: []string{"a", "b"}, |
| - Inventories: []Inventory{{Box: "a", Hosts: map[string]uint64{"h": 7}}, {Box: "b", Hosts: map[string]uint64{}}}} |
| - check := func(want Verdict, reason string, f func(*MigrationInput)) { |
| - in := base; in.Inventories = slices.Clone(base.Inventories); f(&in) |
| - if v, r := MigrationGate(in); v != want || r != reason { t.Errorf("got %v %s, want %v %s", v, r, want, reason) } |
| - } |
| - check(Migrate, "ok", func(*MigrationInput) {}) |
| - check(Wait, "inventories", func(in *MigrationInput) { in.Inventories = in.Inventories[:1] }) |
| - check(Refuse, "two-copies", func(in *MigrationInput) { in.Inventories[1] = Inventory{Box: "b", Hosts: map[string]uint64{"h": 7}} }) |
| - check(Refuse, "no-match", func(in *MigrationInput) { in.LocalTXID = 6 }) |
| - check(Refuse, "lifetime", func(in *MigrationInput) { in.RowCreated = time.Unix(50, 0) }) |
| - check(Migrate, "empty", func(in *MigrationInput) { in.HasLocal, in.RemoteExists = false, false; in.Inventories[0] = Inventory{Box: "a", Hosts: map[string]uint64{}} }) |
| - // 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 |
| - db := filepath.Join(t.TempDir(), "h.db"); writeLTX(t, db, 1, 5); writeLTX(t, db, 6, 9) |
| - if txid, walEmpty, err := LocalTXID(db); err != nil || txid != 9 || !walEmpty { t.Fatal(txid, walEmpty, err) } |
| -} |
| -func TestRemoteHeadTXIDPaginates(t *testing.T) { |
| - 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; empty only when no inventory lists the host" |
| - |
| -### 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`, 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`, `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 */ } |
| -// 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 |
| -``` |
| - |
| -**`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** |
| - |
| -```go |
| -func TestMigrationPassMigratesOnlyUniqueMatchingCopies(t *testing.T) { |
| - w := haWorld(t, "a", "b") |
| - w.localCopy("a", "solo.example.com", 7); w.replicaHead("solo.example.com", 7) |
| - w.localCopy("a", "both.example.com", 3); w.localCopy("b", "both.example.com", 3); w.replicaHead("both.example.com", 3) |
| - w.inventories() |
| - if st, err := w.migrator("a").Pass(ctx); err != nil || st.Migrated != 1 || st.Refused != 1 { t.Fatalf("%+v %v", st, err) } |
| - if w.lock("solo.example.com").Lock.Release == nil || w.lock("both.example.com").Lock.Release != nil { t.Fatal("wrong host migrated") } |
| -} |
| -func 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|TestMigrationInterleaving|TestSleepMigrates|TestInventoryUpdated|TestActivationBlocked'`. It FAILs. |
| +- [ ] **Step 2: Run** `./internal/activator/ ./internal/host/ -run 'TestHAToken|TestHALaunchRetry|TestFirstWakeCrash|TestHAScheduleToken'`. It FAILs. |
| - [ ] **Step 3: Implement** as specified. |
| -- [ ] **Step 4: Run** the same. Expected: PASS. |
| -- [ ] **Step 5: Commit** "HA migration: acquire first, inventory before release, clean marker only on a complete baseline" |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestInstanceKey|TestAdminToken|TestSchedule|TestPrepare'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "HA secrets: one mint gate before every producer; published and acknowledged before every launch" |
| |
| -### Task 14: Same-box recovery after expiry, with an emptiness proof [own review] |
| +### Task 12: Same-box recovery after expiry, with an emptiness proof [own review] |
| |
| In P1a by Paul's approval. |
| |
| -**Files:** |
| -- Create: `internal/activator/hasamebox.go` and its test |
| -- Modify: `internal/activator/backend_exec.go:716-738` (`Acquire` registers `lease.SetSameBoxProof(prefix, b.sameBoxEmpty(ctx, rt))` before calling `lease.Acquire`) |
| +**Files:** create `internal/activator/hasamebox.go` and its test; modify `internal/activator/backend_exec.go:716-738` (passes `hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt)}` to `AcquireHA`). |
| |
| -**Interfaces:** |
| -- 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`. |
| +**Interfaces:** `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` (`internal/activator/opset.go:437-453`). |
| |
| - [ ] **Step 1: Test** |
| |
| @@ -918,158 +753,114 @@ 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 |
| +### Task 13: The console: born-HA stamping and per-host refusals |
| |
| **Files:** |
| - Modify: |
| - - `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). |
| + - `cmd/console/main.go` (`CONSOLE_HA_REGIONS` into `console.Config.HARegions []string`); |
| + - `internal/console/server.go:526-530` (the field); |
| + - `internal/console/apiinstances.go:1706` and `internal/console/domainattach.go:259` (`rec.HA = s.haRegion(rec.Region)` before `CreateRecord`); |
| + - `internal/console/apiinstancemove_offline.go:384-433` (`offlineSelect` refuses when `d.rec.HA`, before `OfflineStart`, `:610`); |
| + - `internal/console/apiinstanceimport.go:135`, `:401`, `:713` (refuse when `s.haRegion(rec.Region)`, before any write). |
| |
| -**Interfaces:** none. Copy: C1 and C2, where `%s` is `s.offlineName(code)`. |
| +**Interfaces:** `func (s *Server) haRegion(region string) bool`. The home region `""` matches the console's home code. Copy: C1 for moves and C2 for imports, where `%s` is the region's name: the host's region for C1, the target region for C2. |
| |
| - [ ] **Step 1: Test** |
| |
| ```go |
| -func TestOfflineNotCapableWithRegionHA(t *testing.T) { |
| - if offlineCapable(func(k string) string { return map[string]string{"CARLOS_REGION_HA": "1"}[k] }, true) { t.Fatal("HA box offers offline moves") } |
| -} |
| -func TestOfflineStartRefusedForHARegionBeforeAnyWrite(t *testing.T) { // console |
| - s, f := offlineServerFixture(t, withBoxCaps("ie", "region-ha-1")) |
| - if ref := s.offlineSelect(ctx, f, "shop.example.com", "ie", "uk"); ref == nil || !strings.Contains(ref.msg, "high availability") { t.Fatalf("%+v", ref) } |
| - if f.writes() != 0 { t.Fatal("refused after a write") } |
| -} |
| -func TestImportRefusedForHARegion(t *testing.T) { |
| - s := seedServerFixture(t, withBoxCaps("ie", "region-ha-1")) |
| - if ref := s.seedRegionReady(ctx, "ie", true); ref == nil || ref.status != http.StatusConflict { t.Fatalf("%+v", ref) } |
| - if ref := s.seedRegionReady(ctx, "ie", false); ref != nil && strings.Contains(ref.msg, "high availability") { t.Fatal("plain seed refused") } |
| -} |
| -``` |
| - |
| -- [ ] **Step 2: Run** `./internal/host/ ./internal/console/ -run 'TestOfflineNotCapable|TestOfflineStartRefused|TestImportRefused'`. It FAILs. |
| -- [ ] **Step 3: Implement** with the approved copy. |
| -- [ ] **Step 4: Run** the same. Expected: PASS. |
| -- [ ] **Step 5: Commit** "HA regions refuse offline moves and imports up front" |
| - |
| -### Task 16: What Paul sees: status and `carlos system status` |
| - |
| -**Files:** |
| -- Modify: |
| - - `internal/status/snapshot.go`: `:41` (`Probes.HA`), `:475` (`BoxMetrics.HA`, private, never 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`). |
| - |
| -**Interfaces:** |
| -- Produces: |
| - |
| -```go |
| -package status |
| -type HARefusal struct{ Host string `json:"host"`; Reason string `json:"reason"` } |
| -type HAStatus struct { |
| - State string `json:"state"` // "on", "refused" |
| - Migrated int `json:"migrated"`; Waiting int `json:"waiting"`; Refused int `json:"refused"` |
| - RefusedHosts []HARefusal `json:"refused_hosts,omitempty"` // at most 50 |
| +func TestCreateStampsBornHA(t *testing.T) { |
| + s := newTestServer(t, withHARegions("ie")) |
| + rec := createInstanceForTest(t, s, "shop.example.com", "ie") |
| + if !rec.HA { t.Fatal("not stamped") } |
| + if rec2 := createInstanceForTest(t, s, "other.example.com", "uk"); rec2.HA { t.Fatal("stamped outside an HA region") } |
| } |
| -``` |
| - |
| -- [ ] **Step 1: Test** |
| - |
| -```go |
| -func TestHAStatusPrivateOnly(t *testing.T) { // internal/status, the TestFleetBoxCarries* pattern |
| - s := teststore(t); now := time.Now() |
| - status.WriteBox(ctx, s, status.CollectBox(nil, status.Probes{MachineID: "m", HA: &status.HAStatus{State: "on", Migrated: 3}}, now)) |
| - f, _ := status.BuildFleet(ctx, s, nil, now, 5*time.Minute) |
| - if strings.Contains(mustJSON(t, f), "migrated") { t.Fatal("HA leaked into fleet.json") } |
| +func TestMoveRefusedForHAHostInOneBoxRegion(t *testing.T) { // r2.9: keyed on the host, one box, switch off everywhere |
| + s, f := offlineServerFixture(t, oneBox("ie"), oneBox("uk")); d := offlineDoorFor(t, s, "shop.example.com", withRecordHA(true)) |
| + if ref := s.offlineSelect(ctx, f, d.rec.Host, "ie", "uk"); ref == nil || !strings.Contains(ref.msg, "high availability") || f.writes() != 0 { t.Fatalf("%+v", ref) } |
| } |
| -func TestPrintSystemStatusHA(t *testing.T) { // root package |
| - var buf bytes.Buffer |
| - printSystemStatus(&buf, systemStatusResponse{Boxes: []systemBoxRow{{Label: "ie-1", HA: &status.HAStatus{State: "on", Migrated: 4, Refused: 1, |
| - RefusedHosts: []status.HARefusal{{Host: "dup.example.com", Reason: "two-copies"}}}}}}, "") |
| - if out := buf.String(); !strings.Contains(out, "4 hosts migrated") || !strings.Contains(out, "more than one box holds a copy") { t.Fatal(out) } |
| +func TestImportRefusedIntoHARegionInOneBoxRegion(t *testing.T) { |
| + s := seedServerFixture(t, oneBox("ie"), withHARegions("ie")) |
| + if code := importForTest(t, s, "shop.example.com", "ie"); code != http.StatusConflict || recordWrites(s) != 0 { t.Fatal(code) } |
| } |
| ``` |
| |
| -- [ ] **Step 2: Run** `./internal/status/ -run TestHAStatusPrivateOnly` and `. -run TestPrintSystemStatusHA`. They FAIL. |
| -- [ ] **Step 3: Implement** with copy C3 to C10. |
| -- [ ] **Step 4: Run** both. Expected: PASS. |
| -- [ ] **Step 5: Commit** "carlos system status shows each box's HA migration" |
| +- [ ] **Step 2: Run** `./internal/console/ -run 'TestCreateStampsBornHA|TestMoveRefusedForHAHost|TestImportRefusedIntoHARegion'`. It FAILs. |
| +- [ ] **Step 3: Implement** with C1 and C2. |
| +- [ ] **Step 4: Run** the same, plus `-run 'TestAPIInstanceCreate|TestOffline|TestImport|TestDomainAttach'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** "console: hosts created in HA regions are born HA; their moves, and imports into HA regions, refused up front" |
| |
| -### Task 17: The seeded N-box simulation [own review] |
| +### Task 14: The seeded N-box simulation [own review] |
| |
| -**Files:** |
| -- Create in `internal/sim/regionha/`: `world_test.go`, `actions_test.go`, `invariants_test.go`, `rules_test.go`, `witness_test.go`, `sim_test.go`, `mutate.sh`, `expected-outcomes.txt`. The shape is `internal/sim/engines`, with `RHASIM_SEEDS`, `RHASIM_SEED`, `RHASIM_MUTATE`, `RHASIM_LIST` and `RHASIM_PAR`. |
| +**Files:** create in `internal/sim/regionha/`: `world_test.go`, `actions_test.go`, `invariants_test.go`, `rules_test.go`, `witness_test.go`, `sim_test.go`, `mutate.sh`, `expected-outcomes.txt`. The shape is `internal/sim/engines`, with `RHASIM_SEEDS`, `RHASIM_SEED`, `RHASIM_MUTATE`, `RHASIM_LIST` and `RHASIM_PAR`. |
| |
| -**Interfaces:** |
| -- Consumes: `hafresh.DecideAcquire`, `DecideKeep`, `MigrationGate`, `OwnerFor`, `MarkerBody`, `DecodeLock`. These are the production decisions; the model supplies the I/O and the release ordering of Tasks 10 and 13. |
| +**Consumes:** `hafresh.DecideAcquire`, `DecideKeep`, `OwnerFor`, `MarkerBody`, `DecodeLock`. The model supplies the I/O and the release ordering of Tasks 6, 7 and 10. |
| |
| -**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. |
| +**The model.** 2 to 5 boxes; born-HA hosts. Per box: a DB position, a files tree, a release record, a pid, an agent state (running, crashed, hung), and a files publisher. One S3 with per-host TXID chains, a manifest generation, and `lock.json` with ETags and conditional writes. |
| |
| -**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. |
| +**Actions:** request at a random box; graceful sleep; failed restore; failure after replication starts; an acquire acknowledged late; agent crash; hang past the TTL, then resume; concurrent cold wakes; a lock changing between GET and PUT; a failed marker PUT, then a retry; a tenant write while asleep; a first wake over leftover objects. |
| |
| **Invariants:** |
| -- **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. |
| +- **I1, single writer.** At every step at most one box runs a host. Every replica write and every manifest write came from the current lease holder, and no two replica writes share a TXID. |
| +- **I2, no stale serving.** A box serves 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`; |
| -- `failed-wake-deletes-lock` (F1), `fresh-shortcut` (F2), `validate-before-acquire` (F3), `publisher-outlives-release` (F9), `switch-off-legacy` (F8). |
| +- `expiry-authorizes`, `keep-without-marker`, `keep-unclean`, `same-box-no-proof`, `marker-before-final`; |
| +- `cleanup-deletes-lock` (r2.1), `legacy-fallback-on-ha` (r2.6), `publisher-outlives-release`, `first-wake-ignores-leftovers`. |
| |
| **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 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. |
| +- a late acknowledgement leaves an unclean marker; |
| +- a lock rewritten between GET and PUT is reclassified; |
| +- a matching but unclean marker restores. |
| |
| - [ ] **Step 1: Write** the world, actions, invariants, rules and witnesses. |
| - [ ] **Step 2: Run** `RHASIM_SEEDS=200 nice -n 19 go test ./internal/sim/regionha/ -run 'TestRegionHA|TestWitnesses|TestEveryActionFires' -count=1`. Expected: PASS. |
| -- [ ] **Step 3: The one sweep for this revision:** |
| +- [ ] **Step 3: The one sweep:** |
| |
| ```bash |
| D=$(mktemp -d -p "$TMPDIR" rhasim.XXXXXX); go test -c -o "$D/regionha.test" ./internal/sim/regionha/ |
| RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D" |
| ``` |
| |
| - Expected: every rule `CAUGHT`; none `MISSED` or `ERROR`. |
| -- [ ] **Step 4: Commit** "region HA simulation: single writer and no stale serving over N boxes, with mutation checks" |
| + Expected: every rule `CAUGHT`. |
| +- [ ] **Step 4: Commit** "region HA simulation: single writer and no stale serving for born-HA hosts, with mutation checks" |
| |
| -### Task 18: Dev rollout on the two IE boxes. Needs Paul's go before anything touches dev. |
| +### Task 15: Dev rollout. Needs Paul's go before anything touches dev. |
| |
| - [ ] **Step 1: Ask Paul for the go.** Give him: |
| - the release tag; |
| + - the console setting: `CONSOLE_HA_REGIONS=<dev IE code>` on the dev console; |
| - the boxes (`platform-infrastructure/dev/region-ie.tf`, `region-ie-b.tf`); |
| - - the switch: `CARLOS_REGION_HA=1` in `/etc/carlos/host.env`; |
| - - 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. |
| + - the cost: §18's lines, unchanged for existing hosts; |
| + - **rollback:** remove the setting. New hosts are then born legacy. Born-HA hosts keep their HA rules on every box and stay unmovable. |
| |
| - 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`. 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 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>`. |
| + Nothing below runs without his yes. |
| +- [ ] **Step 2: Release and roll** by the platform roll recipe: dev boxes, dev console, check. Verify by `X-Carlos-Version`. Note `CARLOS_HIBERNATE_IDLE` on each box. |
| +- [ ] **Step 3: Switch on.** Set `CONSOLE_HA_REGIONS` on the dev console and restart it. Create a test app instance in dev IE. Its record shows `"ha": true`. |
| +- [ ] **Step 4: First wake.** Expected: `restored (no-marker)` with fresh, and the files manifest and env present under `files/0/` before the app answers. A host created with leftovers under its prefix is refused (`leftover data`). |
| +- [ ] **Step 5: Per-host checks.** 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 (after the first wake on A) | 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)` | |
| + | marker names A, then a file in A's files dir `touch`ed by root | A | `restored (tree-changed)` | |
| + | a file made mode 000 before A's 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 on A. |
| +- [ ] **Step 6: Unchanged hosts.** An existing dev IE host still wakes the legacy way (no `kept local` or `restored` lines), and its lock is deleted on sleep as today. |
| +- [ ] **Step 7: Refusals.** A move of the born-HA host is refused with C1, and an import into dev IE with C2. Neither stops anything. |
| +- [ ] **Step 8: Kill drill.** `kill -9` A's agent while the test host is awake on A. |
| - Wakes through B are refused (`another box's expired lease`). |
| - - 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 on A. |
| + - After expiry, A's restarted agent re-takes the host by the proof (`restored (no-marker)`). |
| + - Record the downtime. |
| +- [ ] **Step 9: Hang drill.** `SIGSTOP` A's agent for 20 minutes while the host is awake. |
| - B never takes the host. |
| - - 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. |
| + - After `SIGCONT`, A stands the instance down and writes a marker, never a delete. The next wake follows the marker. |
| + - Record the timeline. |
| +- [ ] **Step 10: Report** on the branch's discussion: the drill timelines and 24 hours of observed cost. |
| |
| ## Census |
| |
| @@ -1079,34 +870,41 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D" |
| | `internal/host/systemapply.go`: the `systemApplier` construction (`:134`) and its field (`:259-262`) | the field removed | body | |
| | `internal/host/joinroot.go`, the root `system join` verb | removed (Task 2) | removed | |
| | `internal/host/units/carlos-system-join.service`, `.path` | external units removed | removed | |
| -| `internal/host/bootstrap.go`: `enabledUnits` and `retireUnits` (`carlos bootstrap`, self-update apply) | unit removal under `/etc/systemd/system` | sites, or `new` for `retireUnits`: then a decision for Paul | |
| +| `internal/host/bootstrap.go`: `enabledUnits` and `retireUnits` | unit removal under `/etc/systemd/system` | sites, or `new` for `retireUnits`: a decision for Paul | |
| | `system.go` `runSystem` dispatch | the join verb removed | body | |
| |
| -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. |
| +Agent-run changes (`internal/lease`, `internal/activator`, `internal/host`, `internal/provision`, `internal/hostfiles`, `internal/console`) come out as `body`, `sites` or envelope re-pins, approved the same way. `internal/provision`'s `@fields` does not move, since `Record` is not a registry struct. `internal/hafresh` does no I/O. |
| + |
| +## Copy |
| |
| -## Copy (pending Paul's review) |
| +All ten strings were approved unedited by Paul. Two remain: |
| |
| | Id | String | |
| |---|---| |
| -| RHA-P1a-C1 | `%s has high availability turned on. offline moves into or out of it are not available yet` | |
| -| RHA-P1a-C2 | `%s has high availability turned on. imports into it are not available yet` | |
| -| RHA-P1a-C3 | `high availability: %d hosts migrated, %d waiting, %d refused` | |
| -| RHA-P1a-C4 | `high availability is off on this box: a move or import is in progress` | |
| -| RHA-P1a-C5 | ` %s refused: %s` | |
| -| RHA-P1a-C6 | `two-copies`: `more than one box holds a copy` | |
| -| RHA-P1a-C7 | `no-match`: `the local copy does not match the replica` | |
| -| RHA-P1a-C8 | `lifetime`: `the local copy belongs to an earlier instance with this hostname` | |
| -| RHA-P1a-C9 | `no-copy`: `no box holds a copy, but a replica exists` | |
| -| RHA-P1a-C10 | `move`: `a move is in progress for this host` | |
| +| RHA-P1a-C1 | `%s has high availability turned on. offline moves into or out of it are not available yet` (`%s` is the host's region name, as approved) | |
| +| RHA-P1a-C2 | `%s has high availability turned on. imports into it are not available yet` (`%s` is the region's name) | |
| + |
| +C3 to C10 (migration status and reasons) are dropped with migration. |
| + |
| +## Dry run (before this commit) |
| + |
| +Stubs for every new exported signature in Tasks 5 to 10 were written into the real packages and compiled against this branch with `go build ./...` and `go vet` (`hafresh`, `lease`, `hostfiles`, `provision`, `activator`, `host`), then deleted. The stubs covered: |
| +- `hafresh`; |
| +- the `lease` additions; |
| +- `SyncStats.Complete` and `Publisher.Gen`; |
| +- `LifetimeIndex`; |
| +- `haLease` asserted on `*execLease`, which still satisfies `Lease`; |
| +- `haRep` asserted on `*lease.Replicator`; |
| +- the activator's call sites: `AcquireHA` with `RefusedError` and `ObligationError`, `hostfiles.Load`, `DecideKeep`, and the `restoreReplica` seam; |
| +- the host's `Record` closure over `LifetimeIndex.Lookup` and `provision.GetRecord`, and `lease.SetSelf(haSelfNow(...))`. |
| + |
| +Result: build and vet clean. Not covered: `Record.HA` (a struct field edit), `agentEntry`'s new signature (it replaces a live function), and the test-only helpers. |
| |
| ## 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. |
| +1. **`;ha=1` and `clean`** are additions to §4.2 and §5.2's formats, carried from rev 2. |
| +2. **The marker lifetime** comes from the reconcile pass's record index. A miss reads the record. |
| +3. **P0 item 4 is deferred** to P1b and P2. |
| +4. **The migration of existing hosts** is the later operator slice (N-HA7). The spec's §8.4 and §13 now say so. |
| +5. **Sidecars, seeds and imports are never born HA in P1a.** Seeds and sidecars stay legacy; imports into an HA region are refused. |
| +6. **Follow-up:** an un-HA procedure for born-HA hosts (settle holders and obligations, then clear markers and the record flag) before any of them can move. |