carlos / platform Public

P1a plan rev 4, final: approved for build by Paul (no 4th round)

Answers Astra plan round 3 (592fb92f), each fix in one place: lease
classifies every lock on every acquire, legacy included (r3.1); lease
persists every failed HA release (r3.3); born-HA hosts run nested only,
with the marker and same-box recovery on root's existing proofs (startup
sweep, KillGen, the observer, the host slice) (r3.2, r3.5); legacy route
classes before any record lookup (r3.4); the surviving regionHA test
keeps its witness via a pending participation record (r3.6);
refuseHAMove in offlineBeginChecks, both request doors and place (r3.7);
the same-box crash witness (r3.8); census rows systemVerb and
bootstrapWith (r3.9).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 80defca1e88ad0ec29419a74333e217e9e96f3e1 parent 592fb92
1 file changed, +346 −91
  • docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md +346 −91

CI failed — run details

diff --git a/docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md b/docs/superpowers/plans/2026-10-26-region-ha-p1a-first-slice.md
index c4a4f9856..490700286 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
@@ -6,7 +6,10 @@
**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 I/O.** `internal/lease` holds the one HA acquire and the one HA release.
+ - It classifies the lock on every acquire, the legacy one included.
+ - It never deletes an HA lock.
+ - It persists every failed HA release itself.
- **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.
@@ -14,26 +17,45 @@
**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.
-**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.
+**Status: rev 4, final, approved for build by Paul (2026-10-26). No fourth review round.**
-| Finding | Fix | Task |
+**Rev 4** answers plan round 3 (592fb92f, NOT READY, 7 P1s and 2 P2s). Each fix is enforced in one place:
+
+| Round 3 finding | Fix, and its one place | Task |
+|---|---|---|
+| r3.1 a cached non-HA entry bypasses an HA lock | `lease` classifies every lock on every acquire, the legacy `AcquireTTL` included. An HA-format lock (a marker, or an owner with `;ha=1`) on the legacy path answers `*HALockError` and is never written. The activator then takes the HA acquire and marks the host HA, sticky. Every legacy write is conditional on the ETag it classified: litestream's `AcquireLease` is no longer called. Witness: a stale negative index entry while the host is re-created. The accepted nearest-region #199 never-reuse rule would remove the re-creation scenario, but that design is not merged and P1a does not depend on it. | 6, 9 |
+| r3.2, r3.5 containment, and nested recovery | **Refused up front.** A born-HA host runs only in the nested layout, under root's control service; the flat layout, a unit row, or a box failing `nestedGate` refuses the wake before the acquire, with no uncontained fallback. Nested placement is systemd's, done before exec: root writes the unit's slice and checks systemd took it before it starts anything (`instancectl/gen.go:314` `startGen`, `genView`). Both proofs use root's existing stop-and-prove for nested units (see "The nested proofs" under Task 12):<br>- **the pre-marker stop:** the unit stop proven by the observer, then the host slice read empty;<br>- **same-box recovery:** this agent's startup `/sweep` succeeded, this process never acquired the host, and the host slice reads empty.<br>Task 15 drills a real nested host. | 9, 10, 12, 15 |
+| r3.3 obligations forgotten | `lease` persists every failed HA release itself (fsynced under `SetObligationDir`), whether from `Held.Release`, `Replicator.Close` or acquisition cleanup, before it returns `*ObligationError`. `AcquireHA` retries a key's pending obligation before reading, and refuses without an obligation store. `reapUnprovenWake` (`opset.go:875-906`) and the acquisition at `activator.go:2269` cannot drop one. Restart witnesses for both, with the marker PUT failing. | 7, 10 |
+| r3.4 sidecars and hand-added routes | `haLegacyRoute(rt)`: a sidecar, an unprovisioned route, or any kind but `instance` is legacy before any record lookup, and keeps today's acquire. A provisioned instance still fails closed on a failed read. Sidecar and unprovisioned-route witnesses. | 9 |
+| r3.6 surviving `regionHA` test | `TestDecidePrevWritesTheSidecarAndVerdictBeforeTheJournal` keeps its ordering witness through a pending participation record. That record defers at the update-begun step (`systemapply.go:536-543`) with `regionHA` false; this was checked on this branch. | 4 |
+| r3.7 `offlineSelect` has no record | One helper, `refuseHAMove(w, rec)` beside `refuseSeedMove`, runs in `offlineBeginChecks` (start and stage), in both live move request doors, and in `carlos apps place` through `placeMoveBlock`. Each refuses before any write. | 13 |
+| r3.8 crash witness | Crash and restart the same box through the service wake path, with the startup-sweep proof. Assert both unpublished secrets are replaced, and acknowledged before execution, and that another box stays refused. | 11 |
+| r3.9 census rows | `systemVerb` and `bootstrapWith` added. The table is reconciled against the generated card in Tasks 2 and 4. | Census |
+
+**Rev 3** (N-HA7). Plan round 2 (e384a8d2) found 9 P1s, and 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; migrating existing hosts 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 and the status task.
+- **Findings that went with them:** r2.2, r2.7, r2.11, r1 F2 and r1 F3. Copy C3 to C10 went too.
+
+| Round 2 finding | Fix | Task |
|---|---|---|
-| 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.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 `lease` (rev 4). Witnesses: a late acquire acknowledgement; cleanup after replication starts. | 6, 7 |
| 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.9 refusals keyed on a box capability | Keyed on the host: the move doors refuse a record with `HA` (rev 4: `refuseHAMove`); 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
-- **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.
+- **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.
+ - `lease` refuses an HA-format lock on the legacy path, whatever the caller believes (r3.1).
+ - Sidecars, unprovisioned routes and non-instance kinds are legacy before any record lookup (r3.4).
+- **Containment:** a born-HA host runs only in the nested layout, under root's control service (r3.2). Anything else refuses its wake before the acquire.
- **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:
@@ -41,16 +63,16 @@
- 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.
+- **No HA lock is ever deleted.** Expiry never lets another box take one. A failed marker PUT is persisted by `lease` and 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;
+ - failed marker: 1 PUT per retry, one of them before the next acquire of that key;
- an index miss after a restart: 1 GET of the record;
- - non-HA hosts: unchanged.
+ - non-HA hosts: unchanged. The legacy path's GET and conditional PUT replace litestream's own GET and PUT one for one.
- **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.
@@ -62,8 +84,10 @@
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 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`.
+4. **A crash between the first-wake mint and its publish.** The same box, restarted, takes the host by the startup-sweep proof, finds no manifest and mints afresh. Another box stays refused. 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`.
+6. **A stale negative index entry.** The lock's own format refuses the legacy path. Task 6: `TestLegacyAcquireRefusesHALock`; Task 9: `TestStaleNegativeIndexTakesHAPath`.
+7. **A descendant outliving the stop.** No marker is written while the host slice holds anything. Task 10: `TestNoMarkerWhileHostSlicePopulated`.
---
@@ -132,7 +156,8 @@ func TestSystemJoinVerbGone(t *testing.T) { // root package
- [ ] **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"
+- [ ] **Step 5: Census card (r3.9).** Run `make census-card`. Every root-run unit it reports must be a row of the Census table below, at least `systemVerb`, `runSystem`, `bootstrapWith`, `enabledUnits` and `retireUnits`. Add any other row it reports to the table in this commit.
+- [ ] **Step 6: Commit** "P0: joining mode, carlos system join and its units removed; group-reference wait kept"
### Task 3: P0. Delete the console's enrolment pass
@@ -155,7 +180,12 @@ Root runs this.
- `guardparticipation_test.go:22`, `:110`;
- `participation_flagoff_test.go:16`;
- `plan9_a_guard_test.go:99`;
- - `rootexecution_update_test.go:26`.
+ - `rootexecution_update_test.go:26`;
+ - `systemapply_test.go:1863` (r3.6), `TestDecidePrevWritesTheSidecarAndVerdictBeforeTheJournal`. It keeps its ordering witness.
+ - Replace `f.a.regionHA = true` with `f.a.participation = updateParticipationFixture(t)` plus a pending record: `f.a.participation.State.Write("shop.example.json", []byte("{\"Schema\":1,\"Status\":\"pending\"}"))`.
+ - That defers at the update-begun step (`systemapply.go:536-543` wraps the ledger's `ErrUnavailable` as `errSystemDeferred`). The sidecar and verdict are already written, and the journal is not.
+ - Every assertion is unchanged.
+ - This was run on this branch with `regionHA` false: outcome `deferred`, no journal, sidecar `v0.31.0`.
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.
@@ -173,8 +203,9 @@ func TestBeginExecutableChangeIgnoresRegionHA(t *testing.T) {
- [ ] **Step 2: Run** `./internal/host/ -run TestBeginExecutableChangeIgnoresRegionHA`. It FAILs (`errSystemDeferred`).
- [ ] **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"
+- [ ] **Step 4: Run** `-run 'TestBeginExecutableChange|TestSystemApply|TestGuardParticipation|TestParticipation|TestPlan9A|TestRootExecution|TestDecidePrevWritesTheSidecarAndVerdictBeforeTheJournal'`, then `go vet ./internal/host/`. That is a compile check of every test file in the package. Expected: PASS.
+- [ ] **Step 5: Census card.** `make census-card`, reconciled against the Census table as in Task 2.
+- [ ] **Step 6: Commit** "P0: system apply no longer reads CARLOS_REGION_HA for claim participation"
### Task 5: The owner and box identity, set by `agentEntry` on every box
@@ -234,13 +265,15 @@ func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) { // internal/host, r2.10: d
- [ ] **Step 4: Run** the same, plus `./internal/lease/ -run TestTombstone`. Expected: PASS.
- [ ] **Step 5: Commit** "lease owner names the box on every box, set by agentEntry"
-### Task 6: The HA acquire: one table, the exact ETag, an empty-prefix first wake [own review]
+### Task 6: Every acquire classifies the lock; the HA acquire: one table, the exact ETag, an empty-prefix first wake [own review]
-This is I1's one place.
+This is I1's one place. Both acquire paths, HA and legacy, classify the lock in `lease` (r3.1).
**Files:**
-- 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`)
+- Create: `internal/hafresh/lock.go`, `internal/hafresh/acquire.go` and its test; `internal/lease/ha.go`; `internal/lease/legacytake.go`; `internal/lease/ha_test.go` (`package lease_test`); `internal/lease/leasetest/lockfixture.go`
+- Modify:
+ - `internal/lease/lease.go:193-195`: on `errLockPresent`, call `takeLegacy` in place of `leaser.AcquireLease`;
+ - `internal/lease/export_test.go` (narrow access: `LockHeldForTest = lockHeld`, `LeaseFreeForTest = leaseFree`, `AcquireHATTL = acquireHATTL`).
**Interfaces** (compile-checked against this branch with stubs; see "Dry run"):
@@ -268,6 +301,8 @@ func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision // for H
```go
package lease
type RefusedError struct{ Reason string }
+type HALockError struct{ View hafresh.View } // the legacy path met an HA-format lock; nothing was written
+func takeLegacy(ctx context.Context, client *awss3.Client, l *lss3.Leaser) (*litestream.Lease, error)
func ReadLock(ctx context.Context, bucket, prefix, region string) (hafresh.View, error)
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)
@@ -308,7 +343,16 @@ func (f *LockFixture) BeforeWrite(hook func(method, key string))
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.
-`base` (box, IID, lifetime) is kept on the `Held` for Task 7's unclean releases.
+`base` (box, IID, lifetime) is kept on the `Held` for Task 7's unclean releases. Before step 1, `AcquireHA` settles the key's pending obligation (Task 7).
+
+**The legacy acquire (`AcquireTTL`),** for every caller, moves staging included. `createLease` (`If-None-Match: *`) runs first, as today. On a 412, `takeLegacy` runs:
+1. GET the lock with its ETag, and `hafresh.DecodeLock`.
+2. If `HAOn()`, return `*HALockError` and write nothing.
+3. If it is unexpired, return `*HeldError`.
+4. If it is expired, PUT with `If-Match: <the ETag classified>`, generation + 1, owner `currentOwner(false)`.
+5. Any 412: back to step 1, at most 3 rounds.
+
+litestream's `AcquireLease` is no longer called, since it decodes an HA lock leniently and would take an expired one. An absent lock created by a legacy caller is today's #199 hazard. Nearest-region's accepted never-reuse rule removes it, but that rule is not merged and P1a does not depend on it.
- [ ] **Step 1: Test**
@@ -362,17 +406,41 @@ func TestAcquireHALateAckWritesUncleanMarker(t *testing.T) { // r2.1
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) }
}
+func TestLegacyAcquireRefusesHALock(t *testing.T) { // r3.1: a marker, and another box's expired HA owner
+ expired := leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Hour))
+ marker, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true})
+ for _, body := range [][]byte{expired, marker} {
+ fx := leasetest.NewLockFixture(t); fx.PutLock("instances/h", body)
+ _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ var ha *lease.HALockError
+ if !errors.As(err, &ha) || !bytes.Equal(fx.LockBody("instances/h"), body) { t.Fatalf("legacy path took an HA lock: %v", err) }
+ }
+}
+func TestLegacyTakeIsConditionalOnTheClassifiedETag(t *testing.T) { // r3.1 interleaving
+ fx := leasetest.NewLockFixture(t); fx.PutLock("instances/h", leaseBody("ip-10-0-0-1:77", time.Now().Add(-time.Hour)))
+ var once sync.Once // the create's PUT 412s; before the take's PUT, a born-HA box takes the key
+ fx.BeforeWrite(func(m, k string) {
+ if m == http.MethodPut && slices.Contains(fx.Requests(), "GET instances/h/lock.json") {
+ once.Do(func() { fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Second))) })
+ }
+ })
+ _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ var ha *lease.HALockError
+ if !errors.As(err, &ha) { t.Fatalf("the 412 was not reclassified: %v", err) }
+}
```
-- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestDecideAcquireTable|TestMarkerReadAsFree|TestAcquireHA'`. It FAILs.
+- [ ] **Step 2: Run** `./internal/hafresh/ ./internal/lease/ -run 'TestDecideAcquireTable|TestMarkerReadAsFree|TestAcquireHA|TestLegacyAcquireRefusesHALock|TestLegacyTake'`. 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"
+- [ ] **Step 4: Run** the same, plus `./internal/lease/ -run 'TestAcquire|TestTombstone|TestLockState|TestFastAcquire|TestRelease'` and `./internal/moves/ -run 'TestStaging'`. Expected: PASS.
+- [ ] **Step 5: Commit** "lease: every acquire classifies the lock; HA acquire conditional on the exact ETag classified, empty-prefix first wake"
+
+### Task 7: The one HA release; `lease` never deletes an HA lock, and persists every failed release [own review]
-### Task 7: The one HA release; `lease` never deletes an HA lock [own review]
+Obligations are `lease`'s own (r3.3). No caller can drop one, since each is on disk before the error returns.
**Files:**
-- Create: `internal/lease/release.go`, `internal/lease/release_test.go` (`package lease_test`)
+- Create: `internal/lease/release.go`, `internal/lease/owed.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);
@@ -391,14 +459,20 @@ 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")
+var ErrNoObligationStore = errors.New("lease: no obligation store; HA acquire refused")
+func SetObligationDir(dir string) error // once at agent start: creates dir, loads its files as pending
+func PendingObligations() []Obligation
+func RetryPending(ctx context.Context) error // every pending one; a file goes on nil or ErrObligationVoid
```
-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`:
+All HA releases call the private `releaseWithMarker(ctx, leaser, cur *litestream.Lease, m)`. That covers `Held.Release`, `Replicator.Close`, `ReleaseMarker` and the acquire's own cleanup. 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.
+- otherwise: write `<dir>/<sha256(bucket/key)>.json` holding the exact body and ETag, fsync the file and the dir, add it to the pending set, and only then return `*ObligationError`. If the write fails, the entry stays pending in memory, the error says so, and `RetryPending` writes the file again.
`RetryObligation` returns nil, `ErrObligationVoid` on a 412, or the error. It never reads expiry. Non-HA handles keep today's DELETE.
+- `AcquireHA` refuses with `ErrNoObligationStore` until `SetObligationDir` has run.
+- With an obligation pending for its key, `AcquireHA` retries it first. If the retry fails, it returns that `*ObligationError` and reads nothing.
- [ ] **Step 1: Test**
@@ -428,16 +502,32 @@ func TestFailedMarkerIsAnObligationExpiryNeverDischarges(t *testing.T) {
time.Sleep(3 * time.Second)
if err := lease.RetryObligation(ctx, oe.Obligation); err != nil { t.Fatalf("retry after expiry: %v", err) }
}
+func TestAcquireCleanupObligationSurvivesRestart(t *testing.T) { // r3.3, path 1: a late ack, then its marker PUT fails
+ dir := t.TempDir(); lease.SetObligationDir(dir); fx := leasetest.NewLockFixture(t)
+ delayPutAck(t, fx, 4*time.Second); fx.FailNext(http.MethodPut, http.StatusServiceUnavailable) // after the delayed acquire PUT
+ _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second)
+ var oe *lease.ObligationError
+ if !errors.As(err, &oe) || len(dirFiles(t, dir)) != 1 { t.Fatalf("not persisted: %v", err) }
+ lease.ResetForTest(); lease.SetObligationDir(dir) // a new process
+ if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}); err != nil { t.Fatal(err) }
+ if w := fx.Requests(); !slices.Equal(w[len(w)-3:], []string{"PUT instances/h/lock.json", "GET instances/h/lock.json", "PUT instances/h/lock.json"}) || len(dirFiles(t, dir)) != 0 {
+ t.Fatalf("the marker was not settled before the read: %v", w)
+ }
+}
+func TestHAAcquireRefusedWithoutObligationStore(t *testing.T) {
+ lease.ResetForTest(); fx := leasetest.NewLockFixture(t)
+ if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoObligationStore) || len(fx.Requests()) != 0 { t.Fatal(err) }
+}
func TestStreamCaptureOneSecond(t *testing.T) {
h := haHeld(t, leasetest.NewLockFixture(t), "instances/h"); h.SetMonitorInterval(time.Second)
if lease.MonitorIntervalForTest(h, tempDB(t)) != time.Second { t.Fatal("interval not applied") } // export_test.go
}
```
-- [ ] **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 2: Run** `./internal/lease/ -run 'TestHARelease|TestCleanReleaseMarker|TestFailedMarker|TestStreamCapture|TestAcquireCleanupObligation|TestHAAcquireRefusedWithout'`. It FAILs.
+- [ ] **Step 3: Implement** as specified. `haHeld`, `haReplicator` and `haReplicatorTTL` are test helpers over `AcquireHA` and `Replicate`, with `SetObligationDir(t.TempDir())`. `ResetForTest` (`export_test.go`) clears the self, the store and the pending set.
- [ ] **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"
+- [ ] **Step 5: Commit** "lease: one HA release, never a delete; every failed release persisted before it returns"
### Task 8: The keep decision and the local record [own review]
@@ -501,7 +591,7 @@ func TestTreeDigestStableAndSeesChmod(t *testing.T) { // activator, linux
- [ ] **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: Born-HA classification and the HA wake [own review]
+### Task 9: Born-HA classification, containment admission, and the HA wake [own review]
**Files:**
- Create: `internal/activator/hawake.go` and its test; `internal/provision/lifetimeindex.go` and its test
@@ -510,11 +600,11 @@ func TestTreeDigestStableAndSeesChmod(t *testing.T) { // activator, linux
- `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`);
+ - `:716-738` (`Acquire`: the classification order below);
- `: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).
+ - the `ExecBackend` fields `Registry *registry.Registry`, `FilesStore release.Store`, `Lifetimes *provision.LifetimeIndex` and `StartupSwept func() bool` (Task 12);
+ - `internal/host/agent.go` (wires `Record` from the index, with `provision.GetRecord` on a miss; `eb.StartupSwept = seedSweptAtStart.Load`; `lease.SetObligationDir(filepath.Join(dd, ".ha-owed"))` before `svc.Start`).
**Interfaces** (compile-checked):
@@ -525,6 +615,7 @@ type LifetimeIndex struct{ /* mu, m */ }
func (x *LifetimeIndex) Replace(recs map[string]Record)
func (x *LifetimeIndex) Merge(recs map[string]Record)
func (x *LifetimeIndex) Lookup(host string) (LifetimeEntry, bool)
+func (x *LifetimeIndex) MarkHA(host string) // sticky: a later Replace or Merge never clears it
```
```go
@@ -536,12 +627,30 @@ type haRep interface {
HA() bool; Finish(ctx context.Context) (uint64, error); ReleaseMarker(ctx context.Context, m hafresh.Marker) error
}
type errLeaseRefused struct{ reason string }
-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 haLegacyRoute(rt registry.Route) bool // rt.IsSidecar() || !rt.Provisioned || rt.Kind != "instance"
+func (b *ExecBackend) isHA(ctx context.Context, rt registry.Route) (provision.LifetimeEntry, bool, error) // record facts only; never reads the lock
+func (b *ExecBackend) haContained(rt registry.Route) error // nil only for LayoutNested (pathsFor), not BackingUnit, and nestedGate(rt) nil
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
```
+**`Acquire`'s classification order** (one function, `backend_exec.go:716`):
+1. **Legacy routes (r3.4).** `haLegacyRoute(rt)` routes take `lease.Acquire` before any record lookup, as today. A `*lease.HALockError` there refuses the wake (`errLeaseRefused{"ha lock on a route with no instance record"}`).
+2. **The record.** `isHA` reads the index, then `provision.GetRecord` on a miss. A failed read fails the wake, never falling back to legacy.
+3. **Not HA.** `lease.Acquire`. On `*lease.HALockError` (r3.1: a stale negative entry, or a host re-created born HA), `idx.MarkHA(host)`, then continue at step 4 in the same call.
+4. **HA.**
+ - `haContained(rt)` must be nil, else `errLeaseRefused{"high availability needs the nested layout: <reason>"}`, before any lock request.
+ - Then `lease.AcquireHA` with Task 12's proof.
+ - On success, the host goes into the backend's `acquiredHere` set (Task 12).
+
+**Containment (r3.2), refused up front.** An HA host never spawns outside the nested layout, so a flat, fenced or conflicting layout, a unit row, or a box whose `nestedGate` fails (no control channel, or `NestedOK` false) refuses the wake. The paths that already refuse without a fallback:
+- `nestedGate` (`backend_exec.go:2740`) refuses before a nested spawn;
+- root's `startGen` (`instancectl/gen.go:314`) checks that systemd took the unit's slice before it starts anything;
+- placement into the host slice happens before exec.
+
+So there is no uncontained fallback for an HA host. `haContained` is asked again before every spawn of an HA host (wake, generation start, sidecar co-spawn), so a layout pass that converts the row mid-life refuses the next spawn.
+
**Behaviour, whatever `CARLOS_REGION_HA` says:**
- **An HA host:**
- first wake (absent lock): `fresh = true`, with an empty tree;
@@ -588,14 +697,46 @@ func TestHAWakeSkipsStagingFallback(t *testing.T) {
b.restoreHA(ctx, rt, markerView("b", "i-b", "L1", 5, true), false)
if fm.promoted { t.Fatal("staging promoted for an HA host") }
}
+func TestStaleNegativeIndexTakesHAPath(t *testing.T) { // r3.1: A's index says legacy; the host was re-created born HA and B holds it
+ b, rt := haBackendIndexed(t, "shop.example.com", provision.LifetimeEntry{ID: "L0", HA: false})
+ putLockFor(t, b, rt, leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true), time.Now().Add(-time.Hour))) // B hung past expiry
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.Contains(refused.reason, "another box") || lockWrites(t, b, rt) != 0 { t.Fatalf("legacy took B's lock: %v", err) }
+ if e, _ := b.Lifetimes.Lookup(rt.Host); !e.HA { t.Fatal("not marked HA") }
+}
+func TestSidecarKeepsLegacyAcquireWithoutRecordRead(t *testing.T) { // r3.4
+ b, rt := haBackendEmptyIndex(t, "worker.shop.example.com"); rt.Kind = "sidecar"; failRecordReads(b)
+ if _, err := b.Acquire(ctx, rt); err != nil || recordGets(b) != 0 { t.Fatalf("sidecar wake: %v, %d record reads", err, recordGets(b)) }
+}
+func TestUnprovisionedRouteKeepsLegacyAcquire(t *testing.T) { // r3.4: a hand-added hibernating route
+ b, rt := haBackendEmptyIndex(t, "hand.example.com"); rt.Provisioned = false; failRecordReads(b)
+ if _, err := b.Acquire(ctx, rt); err != nil || recordGets(b) != 0 { t.Fatal(err) }
+}
+func TestProvisionedInstanceFailsClosedOnRecordRead(t *testing.T) {
+ b, rt := haBackendEmptyIndex(t, "shop.example.com"); failRecordReads(b)
+ if _, err := b.Acquire(ctx, rt); err == nil || lockRequests(t, b, rt) != 0 { t.Fatal("wake went on without its record") }
+}
+func TestHAWakeRefusedOutsideNested(t *testing.T) { // r3.2, through the production Acquire
+ for name, mod := range map[string]func(*ExecBackend, *registry.Route){
+ "flat": func(b *ExecBackend, rt *registry.Route) { flattenRoute(t, b, rt) },
+ "unit": func(_ *ExecBackend, rt *registry.Route) { rt.Backing = registry.BackingUnit },
+ "no nested gate": func(b *ExecBackend, _ *registry.Route) { b.NestedOK = func() error { return errors.New("mounts") } },
+ } {
+ b, rt := haBackend(t, "shop.example.com"); mod(b, &rt)
+ _, err := b.Acquire(ctx, rt)
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || lockRequests(t, b, rt) != 0 || spawns(b) != 0 { t.Errorf("%s: %v", name, err) }
+ }
+}
```
-- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAHostRules|TestIndexMiss|TestHAWake|TestLifetimeIndex'`. It FAILs.
-- [ ] **Step 3: Implement** as specified.
+- [ ] **Step 2: Run** `./internal/activator/ ./internal/provision/ -run 'TestRestoreHA|TestHAHostRules|TestIndexMiss|TestHAWake|TestLifetimeIndex|TestStaleNegativeIndex|TestSidecarKeepsLegacy|TestUnprovisionedRoute|TestProvisionedInstanceFailsClosed'`. It FAILs.
+- [ ] **Step 3: Implement** as specified. `haBackend` builds a provisioned instance route on the nested layout, with `NestedOK` nil, `StartupSwept` true and `lease.SetObligationDir(t.TempDir())`.
- [ ] **Step 4: Run** the same, plus `-run 'TestRestore|TestAcquire|TestWake'` in `./internal/activator/`. Expected: PASS.
- [ ] **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 HA release persists its obligation [own review]
+### Task 10: Files on the entry; the marker only after a proven stop [own review]
**Files:**
- Create: `internal/activator/hafiles.go`, `internal/activator/harelease.go` and their tests
@@ -603,12 +744,13 @@ func TestHAWakeSkipsStagingFallback(t *testing.T) {
- `internal/hostfiles/sync.go` (`SyncStats.Complete`), `internal/hostfiles/publisher.go` (`Gen`);
- `internal/activator/activator.go`:
- `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`);
+ - `:4378-4410` (`finishStop`: an HA entry calls `releaseHAClean`);
- `: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-440` (`cleanupFailedWake`: `stopFiles(e)` first; its `w.rep.Close` error goes to `noteReleaseErr`).
+ - the sweep (`lease.RetryPending`, backoff 1 min doubling to 10 min).
+ - `internal/activator/maintenance.go:360-440` (`cleanupFailedWake`: `stopFiles(e)` first).
+
+The obligation paths need no activator change (r3.3). `giveBack`, `oweRelease`, `cleanupFailedWake`, `reapUnprovenWake` (`opset.go:875-906`) and the acquisition at `activator.go:2269` keep their error handling. Every HA release error they see is already on disk in `lease` (Task 7).
**Interfaces:**
@@ -628,13 +770,21 @@ 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
-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
+func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error // the order below
+func (b *ExecBackend) hostSliceEmpty(rt registry.Route) (bool, error) // CgroupEvents(instancectl.SliceName(host), ""): the host slice, every unit of the host
```
-Before acquiring a host with an owed file, `retryOwed` runs for it. If the marker is still owed, the wake answers `errLeaseRefused{"marker owed"}`.
+**`releaseHAClean`'s order (r3.2).** The marker is the last write, and only after a proven stop:
+1. The entry's stop has returned nil. `finishStop` runs only then, and today's nested proofs give that nil (see "The nested proofs" under Task 12):
+ - `unitProc.Stop` returns nil only after the observer saw the unit inactive or failed with its cgroup empty, else `ErrStillRunning`;
+ - a generation uses `KillGen`;
+ - a co-spawned sidecar is stopped through `KillSidecar` and `sidecarsExited`.
+2. `hostSliceEmpty` is true: nothing of the host runs in any of its units. If not, or on a read error, no marker is written. The lease stays held and renewing, and the stop stays pending, as an unproven stop does today.
+3. `stopFiles`, then `Final`.
+4. `Finish`, then `writeReleaseRecord`.
+5. `ReleaseMarker`, with `Clean = complete && Finish ok`.
+
+A `*lease.ObligationError` from step 5 is already persisted.
- [ ] **Step 1: Test**
@@ -659,11 +809,30 @@ func TestNoWriteAfterMarker(t *testing.T) {
}
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 len(lease.PendingObligations()) != 1 { t.Fatal("obligation not persisted") }
+ a2 := restartService(t, a); expireLease(t, e) // a new lease state loaded from the same obligation dir
if _, err := a2.backend.Acquire(ctx, e.route); err != nil { t.Fatal(err) }
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) }
+ if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], a2.Cfg.Self) || len(lease.PendingObligations()) != 0 { t.Fatalf("%v", w) }
+}
+func TestReapedWakeObligationSurvivesRestart(t *testing.T) { // r3.3, path 2: reapUnprovenWake's rep.Close, its marker PUT failing
+ a, e := haServiceEntry(t, "shop.example.com"); retainUnprovenWake(t, a, e) // a failed wake whose stop was unproven, replication started
+ failMarkerPuts(t, e, 1); proveStopped(t, e); a.reapUnprovenWakesForTest()
+ a2 := restartService(t, a)
+ if len(lease.PendingObligations()) != 1 { t.Fatal("the reaper's obligation was dropped") }
+ if _, err := a2.backend.Acquire(ctx, e.route); err != nil || !isMarker(lockWrites(t, e)[len(lockWrites(t, e))-2]) { t.Fatal(err) }
+}
+func TestNoMarkerWhileHostSlicePopulated(t *testing.T) { // r3.2: a descendant outlives the unit's stop
+ a, e := haServiceEntry(t, "shop.example.com"); hostSlicePopulated(t, a, true) // CgroupEvents seam: the slice still holds a process
+ a.stopForTest(e)
+ if lockWrites(t, e) != nil || !leaseHeld(t, e) { t.Fatal("a marker went out while the host's slice was populated") }
+ hostSlicePopulated(t, a, false); a.stopForTest(e)
+ if v := lockView(t, e); v.Lock.Release == nil { t.Fatal("no marker after the proof") }
+}
+func TestNoMarkerWhileUnitStopUnproven(t *testing.T) {
+ a, e := haServiceEntry(t, "shop.example.com"); unitStaysActive(t, a) // UnitState seam: the observer never sees inactive, Stop answers ErrStillRunning
+ a.stopForTest(e)
+ if lockWrites(t, e) != nil { t.Fatal("marker before the observer's proof") }
}
func TestTrioPublishedWithinOneSecond(t *testing.T) {
f := hostFilesFixture(t, nil); go f.Run(ctx); writeEnv(t, f, "CARLOS_INSTANCE_KEY=k1\n")
@@ -671,10 +840,10 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) {
}
```
-- [ ] **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 `-run 'TestStop|TestCleanupFailedWake|TestShutdown|TestGiveBack'`. Expected: PASS.
-- [ ] **Step 5: Commit** "HA release: entry-owned publisher, clean marker only when complete, every obligation persisted"
+- [ ] **Step 2: Run** `./internal/hostfiles/ -run TestCompleteRefusesRetryAndTorn` and `./internal/activator/ -run 'TestFailedWakeAfterReplication|TestNoWriteAfterMarker|TestOwedMarker|TestReapedWakeObligation|TestNoMarkerWhile|TestTrioPublished'`. They FAIL.
+- [ ] **Step 3: Implement** as specified. The service test fixture uses the real `unitProc` and observer with the `UnitState` and `CgroupEvents` seams (`backend_exec.go:191-199`), not a fake `Proc`.
+- [ ] **Step 4: Run** the same, plus `-run 'TestStop|TestCleanupFailedWake|TestShutdown|TestGiveBack|TestReapUnproven'`. Expected: PASS.
+- [ ] **Step 5: Commit** "HA release: entry-owned publisher, marker only after a proven stop and an empty host slice"
### Task 11: One mint gate; secrets published before every launch
@@ -709,10 +878,20 @@ func TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) {
if err := b.launchForTest(ctx, rt); err == nil { t.Fatal("launched without an acknowledged publish") }
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 TestFirstWakeCrashBeforePublishRemints(t *testing.T) { // Review Focus 4, r3.8: same box, through the service wake path
+ a, rt := haService(t, "fresh.example.com", withLeaseTTL(2*time.Second)) // real Acquire, Restore, launch; nested seams
+ crashBeforePublish(t, a) // mint runs, the files commit never does, the agent dies
+ if _, err := a.wakeForTest(ctx, rt); err == nil { t.Fatal("crash not simulated") }
+ lost := envValues(t, a, rt, "CARLOS_ADMIN_TOKEN", "CARLOS_INSTANCE_KEY") // the unpublished pair, on disk
+ b := otherBoxService(t, a); waitExpiry(t, rt)
+ if _, err := b.wakeForTest(ctx, rt); !isRefused(err, "another box's expired lease") { t.Fatalf("another box took it: %v", err) }
+ a2 := restartService(t, a, withStartupSweep(true)) // the startup sweep succeeded: the proof
+ if _, err := a2.wakeForTest(ctx, rt); err != nil { t.Fatal(err) }
+ got := envValues(t, a2, rt, "CARLOS_ADMIN_TOKEN", "CARLOS_INSTANCE_KEY")
+ if got[0] == "" || got[1] == "" || got[0] == lost[0] || got[1] == lost[1] { t.Fatalf("secrets not reminted: %v after %v", got, lost) }
+ if pub := platformEnvAtSpawn(t, a2, rt); !strings.Contains(pub, "CARLOS_ADMIN_TOKEN="+got[0]) || !strings.Contains(pub, "CARLOS_INSTANCE_KEY="+got[1]) {
+ t.Fatal("the app started before its secrets were acknowledged") // read from the manifest at the spawn seam
+ }
}
func TestHAScheduleTokenNeverMints(t *testing.T) { // internal/host
dd := t.TempDir(); reg := testRegistryHA(t, "shop.example.com")
@@ -725,33 +904,55 @@ func TestHAScheduleTokenNeverMints(t *testing.T) { // internal/host
- [ ] **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 12: Same-box recovery after expiry, with an emptiness proof [own review]
+### Task 12: Same-box recovery after expiry, by root's nested proof [own review]
+
+In P1a by Paul's approval. Nested hosts only (r3.2, r3.5). `EmptyHost` is not used: it reads the flat host cgroup, treats an absent one as empty, and accepts `ErrNoDelegation`.
-In P1a by Paul's approval.
+**The nested proofs.** These exist today; P1a adds none:
+- **The startup sweep.** Root's `/sweep` (`internal/instancectl/server.go:934-1033`) stops every instance unit on the box, of every template (run, seed, sidecar, cmd, generation and rootfs). For each unit it waits until systemd reports it inactive or failed, then until its cgroup under the host slice is empty (`WaitCgroupEmpty`, `server.go:1123`). It answers 502, and `Client.Sweep` an error, if any unit is not proven.
+ - The agent runs it at every start, before the startup latch, so no wake runs before it (`internal/host/agent.go:660-667`).
+ - The agent records success in `seedSweptAtStart` (`agent.go:670`, `seedwiring.go:185-189`).
+- **`KillGen`.** `internal/activator/containment.go:395` calls root's `StopGen` with kill (`instancectl/gen.go:445-459`): SIGKILL, stop, then wait for the generation's cgroup to empty.
+- **The observer.** `unitProc.Stop` (`unitproc.go:189-221`, `observe` at `:269`) returns nil only once the unit reads inactive or failed with its cgroup empty, and otherwise `ErrStillRunning`. `LegacyRunGone` (`backend_exec.go:2664-2712`) does the same for the original run unit.
+- **The host slice.** Every nested unit of a host runs under `carlos-instances-<host>.slice`. Root checks that systemd placed the unit there before it starts anything, so one read of the slice's `cgroup.events` (`cgroupEventsUnder`, `control.go:125`) covers every unit of the host.
**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:** `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`).
+**Interfaces** (compile-checked): `func (b *ExecBackend) sameBoxEmpty(ctx context.Context, rt registry.Route) func() (bool, error)`. It answers true only when all four hold:
+1. `haContained(rt)` is nil.
+2. `b.StartupSwept()` is true: this agent's startup sweep proved every unit stopped.
+3. The host is not in `acquiredHere`. The lock is then a previous agent process's, and every unit that process started was swept. A lock this process wrote is settled by its own stop and marker, so it is refused here, whatever the pid says (pids repeat across boots).
+4. `hostSliceEmpty(rt)` is true.
+
+Anything else answers false, and the wake is refused (`same box without emptiness proof`). It costs no S3 request.
- [ ] **Step 1: Test**
```go
-func TestSameBoxEmptyRefusesUnprovenLayouts(t *testing.T) {
- for _, tc := range []struct{ name string; rt registry.Route; emptier error; want bool }{
- {"flat proven", flatRoute(), nil, true}, {"nested", nestedRoute(), nil, false}, {"unit", unitRoute(), nil, false},
- {"no delegation", flatRoute(), cgroup.ErrNoDelegation, false}, {"busy", flatRoute(), errors.New("pids remain"), false},
+func TestSameBoxEmptyNeedsTheNestedProof(t *testing.T) {
+ for _, tc := range []struct{ name string; mod func(*ExecBackend, *registry.Route); want bool }{
+ {"swept, slice empty", nil, true},
+ {"sweep failed", func(b *ExecBackend, _ *registry.Route) { b.StartupSwept = func() bool { return false } }, false},
+ {"acquired by this process", func(b *ExecBackend, rt *registry.Route) { markAcquiredHere(b, rt.Host) }, false},
+ {"slice populated", func(b *ExecBackend, _ *registry.Route) { b.CgroupEvents = sliceEvents(true) }, false},
+ {"flat", func(b *ExecBackend, rt *registry.Route) { flattenRoute(t, b, rt) }, false},
} {
- if ok, _ := backendWithEmptier(t, tc.emptier).sameBoxEmpty(ctx, tc.rt)(); ok != tc.want { t.Errorf("%s: %v", tc.name, ok) }
+ b, rt := haBackend(t, "shop.example.com"); b.StartupSwept = func() bool { return true }; b.CgroupEvents = sliceEvents(false)
+ if tc.mod != nil { tc.mod(b, &rt) }
+ if ok, _ := b.sameBoxEmpty(ctx, rt)(); ok != tc.want { t.Errorf("%s: %v", tc.name, ok) }
}
}
+func TestRestartedAgentRetakesNestedHostAfterExpiry(t *testing.T) { // r3.5, through the service wake path
+ a, rt := haService(t, "shop.example.com", withLeaseTTL(2*time.Second)); wakeAndCrash(t, a, rt) // the unit outlives the agent
+ a2 := restartService(t, a, withStartupSweep(true)); waitExpiry(t, rt)
+ if _, err := a2.wakeForTest(ctx, rt); err != nil { t.Fatalf("same box not recovered: %v", err) }
+}
```
-- [ ] **Step 2: Run** `./internal/activator/ -run TestSameBoxEmptyRefusesUnprovenLayouts`. It FAILs.
+- [ ] **Step 2: Run** `./internal/activator/ -run 'TestSameBoxEmptyNeedsTheNestedProof|TestRestartedAgentRetakes'`. It FAILs.
- [ ] **Step 3: Implement** as specified.
-- [ ] **Step 4: Run** the same. Expected: PASS.
-- [ ] **Step 5: Commit** "HA: same-box recovery after expiry only with a cgroup-empty proof"
+- [ ] **Step 4: Run** the same, plus `./internal/host/ -run 'TestStartup|TestSweep'`. Expected: PASS.
+- [ ] **Step 5: Commit** "HA: same-box recovery after expiry only by the startup sweep's proof and an empty host slice"
### Task 13: The console: born-HA stamping and per-host refusals
@@ -760,10 +961,22 @@ func TestSameBoxEmptyRefusesUnprovenLayouts(t *testing.T) {
- `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/seedmove.go` (`refuseHAMove` beside `refuseSeedMove`; `placeSeedBlock` becomes `placeMoveBlock`);
+ - the move doors, each straight after its `refuseSeedMove` (r3.7). All three run before any write:
+ - `internal/console/apiinstancemove_offline.go:490`, in `offlineBeginChecks`. The start door (`:610`) and the stage door (`:648`) both call it before `offlineBegin` or `offlineAdvance`;
+ - `internal/console/apiinstancemove.go:411` (`legacyHandleAPIInstanceMoveRequest`) and `:567` (`handleAPIInstanceMoveRequest`);
+ - `internal/console/fleets.go:622` (`carlos apps place` re-homes every record, so an HA record refuses it with C1, before any write);
- `internal/console/apiinstanceimport.go:135`, `:401`, `:713` (refuse when `s.haRegion(rec.Region)`, before any write).
-**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.
+**Interfaces** (compile-checked):
+
+```go
+func (s *Server) haRegion(region string) bool // the home region "" matches the console's home code
+func (s *Server) refuseHAMove(w http.ResponseWriter, rec *provision.Record) bool // rec.HA: 409, C1 with s.offlineName(rec.Region)
+func placeMoveBlock(ctx context.Context, st release.Store, judge *provision.LifetimeJudge, acct, app string) (seed string, ha *provision.Record, err error) // one strict read, as placeSeedBlock's
+```
+
+Copy: C1 for moves and place, C2 for imports. `%s` is the region's name: the host's region for C1, the target region for C2.
- [ ] **Step 1: Test**
@@ -774,9 +987,18 @@ func TestCreateStampsBornHA(t *testing.T) {
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") }
}
-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 TestMoveDoorsRefuseHAHostBeforeAnyWrite(t *testing.T) { // r2.9, r3.7: the real start and stage doors, one box per region
+ for _, door := range []string{"/offline/start", "/offline/stage", "/move"} {
+ s := offlineServerFixture(t, oneBox("ie"), oneBox("uk")); seedRecord(t, s, "shop.example.com", "ie", withRecordHA(true))
+ before := storeWrites(s)
+ code, body := moveRequest(t, s, door, "shop.example.com", "uk")
+ if code != http.StatusConflict || !strings.Contains(body, "has high availability turned on") || storeWrites(s) != before { t.Errorf("%s: %d %s", door, code, body) }
+ }
+}
+func TestPlaceRefusedForAppWithHAHost(t *testing.T) {
+ s := offlineServerFixture(t, oneBox("ie"), oneBox("uk")); seedRecord(t, s, "shop.example.com", "ie", withRecordHA(true))
+ before := storeWrites(s)
+ if code := placeForTest(t, s, "uk"); code != http.StatusConflict || storeWrites(s) != before { t.Fatal(code) }
}
func TestImportRefusedIntoHARegionInOneBoxRegion(t *testing.T) {
s := seedServerFixture(t, oneBox("ie"), withHARegions("ie"))
@@ -784,10 +1006,10 @@ func TestImportRefusedIntoHARegionInOneBoxRegion(t *testing.T) {
}
```
-- [ ] **Step 2: Run** `./internal/console/ -run 'TestCreateStampsBornHA|TestMoveRefusedForHAHost|TestImportRefusedIntoHARegion'`. It FAILs.
+- [ ] **Step 2: Run** `./internal/console/ -run 'TestCreateStampsBornHA|TestMoveDoorsRefuseHAHost|TestPlaceRefusedForAppWithHAHost|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"
+- [ ] **Step 4: Run** the same, plus `-run 'TestAPIInstanceCreate|TestOffline|TestImport|TestDomainAttach|TestPlace|TestMoveRequest'`. Expected: PASS.
+- [ ] **Step 5: Commit** "console: hosts created in HA regions are born HA; their moves and places, and imports into HA regions, refused up front"
### Task 14: The seeded N-box simulation [own review]
@@ -797,7 +1019,13 @@ func TestImportRefusedIntoHARegionInOneBoxRegion(t *testing.T) {
**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; 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.
+**Actions:**
+- request at a random box; graceful sleep; failed restore; failure after replication starts; an acquire acknowledged late;
+- agent crash, where the unit outlives it until the restarted agent's startup sweep; hang past the TTL, then resume;
+- concurrent cold wakes; a lock changing between GET and PUT;
+- a failed marker PUT, then an agent restart, then a retry;
+- a tenant write while asleep; a first wake over leftover objects;
+- a box with a stale negative index entry waking the host by the legacy path.
**Invariants:**
- **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.
@@ -805,7 +1033,8 @@ func TestImportRefusedIntoHARegionInOneBoxRegion(t *testing.T) {
**Mutation rules,** each to be CAUGHT:
- `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`.
+- `cleanup-deletes-lock` (r2.1), `legacy-fallback-on-ha` (r2.6), `publisher-outlives-release`, `first-wake-ignores-leftovers`;
+- `legacy-takes-ha-lock` (r3.1), `obligation-in-memory-only` (r3.3), `recover-without-sweep` and `marker-before-slice-empty` (r3.2).
**Witnesses:**
- a hang past the TTL, then another box's wake, is refused;
@@ -831,13 +1060,16 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D"
- [ ] **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 boxes (`platform-infrastructure/dev/region-ie.tf`, `region-ie-b.tf`), each confirmed nested-ready: root's `/ready` answers 204, and the agent's log shows the startup sweep succeeded;
- 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 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 3: Switch on.** Set `CONSOLE_HA_REGIONS` on the dev console and restart it. Create a test app instance in dev IE, with the layout it is minted with.
+ - Its record shows `"ha": true`.
+ - Its route on both boxes shows the nested layout (`carlos-instances-<host>.slice` exists while it runs).
+ - If either box mints it flat, stop and report: the wake is refused by design, and the drill needs a nested box.
- [ ] **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>`.
@@ -851,14 +1083,15 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D"
Data written through each box must be present after the next wake on the other.
- [ ] **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 (`restored (no-marker)`).
- - Record the downtime.
+- [ ] **Step 7: Refusals.** A move (offline start and stage) of the born-HA host, and a `carlos apps place` of its app, are refused with C1. An import into dev IE is refused with C2. None of them stops anything or writes a record.
+- [ ] **Step 8: Kill drill,** on the real nested host. `kill -9` A's agent while the test host is awake on A.
+ - The nested unit outlives the agent. A's restarted agent logs its startup sweep stopping it.
+ - Wakes through B are refused: held, and then `another box's expired lease`.
+ - After the 15-minute expiry, A's agent re-takes the host by the sweep proof (`restored (no-marker)`).
+ - Record the downtime, which is up to one lease TTL.
- [ ] **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 and writes a marker, never a delete. The next wake follows the marker.
+ - After `SIGCONT`, A stands the instance down. Its marker follows only the unit's proven stop and an empty host slice, and it is 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.
@@ -871,7 +1104,11 @@ RHASIM_PAR=2 nice -n 19 internal/sim/regionha/mutate.sh 3000; rm -r "$D"
| `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` | unit removal under `/etc/systemd/system` | sites, or `new` for `retireUnits`: a decision for Paul |
+| `internal/host/bootstrap.go` `bootstrapWith` (r3.9) | its plan path calls `retireUnits` | body |
| `system.go` `runSystem` dispatch | the join verb removed | body |
+| `system.go` `systemVerb` (r3.9) | `join` no longer a verb | body |
+
+Tasks 2 and 4 reconcile this table against `make census-card` and add any row the card reports.
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.
@@ -898,7 +1135,23 @@ Stubs for every new exported signature in Tasks 5 to 10 were written into the re
- 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.
+Result: build and vet clean. Not covered: `agentEntry`'s new signature (it replaces a live function), and the test-only helpers.
+
+**Rev 4 dry run.** This was run the same way, then deleted, with `git status` clean afterwards. It used one-line temporary additions of `provision.Record.HA` and `ExecBackend.StartupSwept`, removed by exact edit. Build and vet were clean on `hafresh`, `lease`, `activator`, `console`, `host` and `provision`. It covered:
+- `lease`:
+ - `HALockError`, unwrapped with `errors.As` beside an `AcquireTTL` call;
+ - `SetObligationDir`, `PendingObligations`, `RetryPending` and `ErrNoObligationStore`;
+- `activator`:
+ - `haLegacyRoute` over `rt.IsSidecar()`, `rt.Provisioned` and `rt.Kind`;
+ - `haContained` over `pathsFor(rt).layout`, `registry.BackingUnit` and `nestedGate`;
+ - `hostSliceEmpty` over `cgroupEventsUnder` and `instancectl.SliceName` with an empty unit;
+ - `sameBoxEmpty` with `StartupSwept` and an `acquiredHere` set;
+- `console`:
+ - `refuseHAMove` over `rec.HA` and `offlineName`, called beside `offlineBeginChecks`;
+ - `placeMoveBlock` over `ListRecordsStrictJudged` and `Seed.MoveBlock`;
+- `host`: `eb.StartupSwept = seedSweptAtStart.Load` and `lease.SetObligationDir`.
+
+r3.6's replacement deferral was run as a scratch test on this branch: outcome `deferred`, no journal, sidecar written. It is deleted.
## Spec gaps and follow-ups
@@ -908,3 +1161,5 @@ Result: build and vet clean. Not covered: `Record.HA` (a struct field edit), `ag
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.
+7. **Nested only (r3.2).** A born-HA host on a box that cannot run nested is refused, not served. §9.6's same-box recovery is the startup-sweep proof only. The spec needs no change: it already asks for a cgroup-empty proof and refuses without one.
+8. **Host re-creation (r3.1).** A legacy create on an absent lock for a re-created born-HA host is today's #199 hazard, not widened by P1a. The accepted nearest-region never-reuse rule removes it once merged.