carlos / platform Public

Plan: managed fleets 1c, a rebooted box takes back its own lease (#451, #457)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 17625470909d67ba5accee965fb4b39ce44621d5 parent 1488f6d
1 file changed, +221 −0
  • docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md +221 −0

CI failed — run details

diff --git a/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md b/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md
new file mode 100644
index 000000000..0b3e1a442
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md
@@ -0,0 +1,221 @@
+# Managed fleets 1c: a rebooted box takes back its own lease (#451) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** After a reboot, a box wakes its instances at once instead of waiting up to 15 minutes for the lock its own previous boot left behind.
+
+**Architecture:** The legacy (non-HA) lease owner string gains the kernel boot id. When a starting agent meets an unexpired non-HA lock written by this same EC2 instance under a different boot, it takes it, conditional on the ETag it read, exactly as it takes an expired lock today. Nothing from an earlier boot can still be running under a new kernel, so that lock is provably dead. Every other unexpired lock is still refused.
+
+**Tech Stack:** Go; `internal/hafresh` (owner vocabulary), `internal/lease` (acquire), `internal/host` (identity), `internal/activator` (diagnostic only).
+
+**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, item 1c. Bug: amadan #451. Investigation: §"Findings" below.
+
+## Findings (main d3908d93)
+
+- Owner string: `hafresh.OwnerFor` (`internal/hafresh/owner.go:34-45`) writes `box/v1;ref=<ref>;iid=<iid>;pid=<pid>[;ha=1]`. `ParseOwner` (`:52-97`) is strict.
+- `lease.currentOwner` (`internal/lease/self.go`) fills it with `os.Getpid()`; the agent names itself with `lease.SetSelf(haSelfNow(...))` (`internal/host/haself.go:25-28`, `agententry.go:47-48`). `iid` comes from IMDS, `ref` from `metricsBoxLabel`.
+- `LeaseTTL` is 15 min (`internal/lease/lease.go:40`).
+- The non-HA take is `takeLegacy` (`internal/lease/legacytake.go:55-66`): any unexpired lock is `*HeldError`; ownership is never compared. That is the 15 minutes.
+- #451 affects native instances too (leo on dev, 2026-10-26, ~13 min dark; `docs/superpowers/notes/dev-claim-trial-undo-log.md` on `design-live-moves-ha`, fdf30876).
+- Why shutdown can't prove the stop is unconfirmed. The leading guess: `systemctlUnitState` (`internal/activator/control.go:100-117`) runs as `carlos`, needs D-Bus, and D-Bus stops in parallel at shutdown; the error's stderr is discarded. Task 4 makes the next occurrence say so. The unit-ordering fix is a follow-up once confirmed; the takeover rule is needed regardless (power loss, kernel panic).
+
+## Global Constraints
+
+- Non-HA locks only. An HA owner (`;ha=1`) never carries `boot=`, and HA locks keep every current rule (`*HALockError` on the legacy path). Old binaries would misread an HA owner with an extra field as non-HA, so HA needs two releases and is out of scope.
+- Take only when ALL hold: the lock is not HA; `self.IID != ""` and equals the owner's `iid`; `self.Ref` equals the owner's `ref`; both boot ids are non-empty; they differ.
+- The take stays conditional on the classified ETag (`classifyAndTake`), at generation + 1. No new write path.
+- A box off EC2 (empty `iid`) or one that can't read its boot id behaves exactly as today.
+- Boot id source: `/proc/sys/kernel/random/boot_id`, trimmed. No build tags (on non-Linux the read fails and the field stays empty).
+- Local tests: only touched packages, with `-run` (AGENTS.md; CI runs the full suite). Cross-compile gate: darwin and windows must still build.
+- Copy: the one new log line is operator diagnostics, not copy-reviewed.
+
+## Review Focus
+
+1. **The agent restarts within one boot** (`systemctl restart carlos-edge`, a crash): the new process has a new pid but the same boot id, and its old instance units may still be running. Must stay `*HeldError`. Test in Task 3.
+2. **Two boxes cloned from one disk image** share `/etc/machine-id` (so maybe `ref`) but not `iid`. Must stay `*HeldError`. Test in Task 3.
+3. **A lock written by an older binary** (no `boot=` field) after an upgrade-and-reboot: no takeover (waits the TTL, as today). Test in Tasks 1 and 3.
+4. **An older binary on another box** reading a new owner string: it must still classify the lock as non-HA and held. Test in Task 1 (the string keeps `ha=` last and `HAOn()` false).
+5. **EC2 stop/hibernate-resume** keeps the boot id, so a hibernated box's lock is never taken. Covered by rule (same boot), asserted in Task 1's table.
+
+---
+
+### Task 1: The owner string carries the boot, and the previous-boot rule
+
+**Files:**
+- Modify: `internal/hafresh/owner.go`
+- Test: `internal/hafresh/owner_test.go`
+
+**Interfaces:**
+- Produces: `hafresh.Self` gains `Boot string` (NOT part of `Complete()`); `hafresh.Owner` gains `Boot string`; `func PreviousBoot(o Owner, self Self) bool`.
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestOwnerForWritesBootOnlyWhenLegacy`:
+- `OwnerFor(Self{Ref: "r", IID: "i-1", Boot: "b1"}, 7, false)` == `"box/v1;ref=r;iid=i-1;pid=7;boot=b1"`.
+- `OwnerFor(Self{Ref: "r", IID: "i-1", Boot: "b1"}, 7, true)` == `"box/v1;ref=r;iid=i-1;pid=7;ha=1"` (no boot on HA).
+- `OwnerFor(Self{Ref: "r", Boot: ""}, 7, false)` == `"box/v1;ref=r;pid=7"`.
+
+`TestParseOwnerBoot`: round trip of the first string gives `Owner{Ref:"r", IID:"i-1", PID:7, Boot:"b1"}`; `"box/v1;ref=r;pid=7;boot=b1;ha=1"` is rejected (`ok == false`); `"box/v1;ref=r;pid=7;boot="` is rejected; every string the existing owner tests accept still parses identically; `hafresh.View{Lock: ...Owner: "box/v1;ref=r;iid=i-1;pid=7;boot=b1"}.HAOn()` is false.
+
+`TestPreviousBoot` (table, `self = Self{Ref:"r", IID:"i-1", Boot:"b2"}` unless stated):
+| owner | want |
+|---|---|
+| `{Ref:"r", IID:"i-1", Boot:"b1"}` | true |
+| `{Ref:"r", IID:"i-1", Boot:"b2"}` (same boot, any pid) | false |
+| `{Ref:"r", IID:"i-2", Boot:"b1"}` | false |
+| `{Ref:"x", IID:"i-1", Boot:"b1"}` | false |
+| `{Ref:"r", IID:"", Boot:"b1"}` | false |
+| `{Ref:"r", IID:"i-1", Boot:""}` (old binary) | false |
+| `{Ref:"r", IID:"i-1", Boot:"b1", HA:true}` | false |
+| self with `IID:""` | false |
+| self with `Boot:""` | false |
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/hafresh/ -run 'TestOwnerForWritesBootOnlyWhenLegacy|TestParseOwnerBoot|TestPreviousBoot'`
+Expected: FAIL (unknown field `Boot`, undefined `PreviousBoot`).
+
+- [ ] **Step 3: Implement**
+
+`OwnerFor` appends `;boot=<s.Boot>` after `pid` when `!ha && s.Boot != ""`. `ParseOwner` accepts an optional `boot` field after `pid` and before `ha`, but rejects `boot` together with `ha`. Update both doc comments to show the new shape. `PreviousBoot` implements the Global Constraints rule, with a comment saying why it is safe (a new kernel means no process of the old boot survives) and why HA is excluded.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/hafresh/`
+Expected: PASS (whole package, including the existing owner and keep tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/hafresh/owner.go internal/hafresh/owner_test.go
+git commit -m "hafresh: legacy owners carry the boot id; PreviousBoot names a lock this box's earlier boot left (#451)"
+```
+
+### Task 2: The agent knows its boot
+
+**Files:**
+- Modify: `internal/host/haself.go`
+- Test: `internal/host/haself_test.go` (create if absent; else add)
+
+**Interfaces:**
+- Consumes: `hafresh.Self.Boot` (Task 1).
+- Produces: `haSelfNow` fills `Boot`; `var bootIDPath = "/proc/sys/kernel/random/boot_id"` (package var, for tests); `func readBootID(path string) string` returning the trimmed contents or `""` on any error.
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestReadBootID`: a temp file containing `"3f1c...\n"` gives `"3f1c..."`; a missing path gives `""`; an empty file gives `""`.
+`TestHASelfNowCarriesTheBoot`: with `bootIDPath` pointed at a temp file holding `b9` and IMDS unreachable (the existing tests' pattern for `haSelfNow` with a client that fails), the result has `Boot == "b9"` and `Complete()` unchanged by `Boot`. Do not call `t.Parallel()` (the test sets a package var).
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/host/ -run 'TestReadBootID|TestHASelfNowCarriesTheBoot'`
+Expected: FAIL (undefined).
+
+- [ ] **Step 3: Implement**
+
+`haSelfNow` sets `Boot: readBootID(bootIDPath)`. Check `haSelfRetry`/`startHASelfRetry`: any `Self` it rebuilds goes through `haSelfNow`, so `Boot` is carried; if anything builds a `Self` another way, carry `Boot` there too.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/host/ -run 'TestReadBootID|TestHASelfNowCarriesTheBoot|HASelf'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/host/haself.go internal/host/haself_test.go
+git commit -m "host: the lease identity carries the kernel boot id (#451)"
+```
+
+### Task 3: The legacy take accepts this box's previous boot
+
+**Files:**
+- Modify: `internal/lease/legacytake.go:55-66`
+- Test: `internal/lease/ha_test.go`
+
+**Interfaces:**
+- Consumes: `hafresh.ParseOwner`, `hafresh.PreviousBoot` (Task 1), `lease.CurrentSelf()`.
+- Produces: nothing new exported.
+
+- [ ] **Step 1: Write the failing tests**
+
+All with `leasetest.NewLockFixture(t)`, `lease.SetSelf(hafresh.Self{Ref:"r", IID:"i-1", Boot:"b2"})` and a `t.Cleanup` that restores the previous self (follow `self_test.go`). Each puts an UNEXPIRED lock (`time.Now().Add(10*time.Minute)`) at generation 9 via `leaseBody`.
+
+- `TestLegacyTakeTakesThePreviousBootsLock`: owner `OwnerFor(Self{Ref:"r",IID:"i-1",Boot:"b1"}, 41, false)`. `lease.Acquire` succeeds; the lock is generation 10, owned by `OwnerFor(CurrentSelf(), os.Getpid(), false)`; the take went through `classifyAndTake` (generation 10 on an unexpired lock can only come from there; no new write path).
+- `TestLegacyTakeRefusesTheSameBoot`: owner boot `b2`, pid 41. `*lease.HeldError`, lock unchanged.
+- `TestLegacyTakeRefusesAnotherInstance`: owner `IID:"i-2"`, boot `b1`. `*lease.HeldError`.
+- `TestLegacyTakeRefusesAnOldOwner`: owner `"box/v1;ref=r;iid=i-1;pid=41"` (no boot). `*lease.HeldError`.
+- `TestLegacyTakeStillRefusesHALocks`: owner `OwnerFor(Self{Ref:"r",IID:"i-1"}, 41, true)`. `*lease.HALockError`.
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/lease/ -run 'TestLegacyTake'`
+Expected: the first FAILs with `*HeldError`; the other four pass already (they pin today's behaviour).
+
+- [ ] **Step 3: Implement**
+
+In `takeLegacy`'s decide, before returning `*HeldError` for an unexpired lock: if `o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && hafresh.PreviousBoot(o, CurrentSelf())`, log once `lease: taking <key> from this box's previous boot (<old boot> -> <new boot>), lock would have expired at <time>` and return nil. Update `takeLegacy`'s doc comment list with the new bullet.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/lease/`
+Expected: PASS (whole package).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/lease/legacytake.go internal/lease/ha_test.go
+git commit -m "lease: a box takes the unexpired lock its own previous boot left, at once (#451)"
+```
+
+### Task 4: A failed unit-state check says why
+
+**Files:**
+- Modify: `internal/activator/control.go:100-117`
+- Test: `internal/activator/control_test.go` (add; create if absent)
+
+**Interfaces:**
+- Produces: `func unitStateError(err error) error`, wrapping an `*exec.ExitError` as `fmt.Errorf("%w: %s", err, <stderr trimmed, cut to 200 bytes>)`, other errors unchanged.
+
+- [ ] **Step 1: Write the failing test**
+
+`TestUnitStateErrorCarriesStderr`: an `*exec.ExitError` built by running `sh -c 'echo "Failed to connect to bus" >&2; exit 1'` with `.Output()` gives an error whose text contains `Failed to connect to bus` and which still `errors.As` to `*exec.ExitError`; a 1 KB stderr is cut to 200 bytes; a non-exit error is returned as is.
+
+- [ ] **Step 2: Run it to see it fail**
+
+Run: `go test ./internal/activator/ -run TestUnitStateErrorCarriesStderr`
+Expected: FAIL (undefined).
+
+- [ ] **Step 3: Implement**
+
+`systemctlUnitState` (and `UnitMainExit`'s systemctl call beside it, if it discards stderr the same way) returns `unitStateError(err)`. `exec.Cmd.Output` already fills `ExitError.Stderr` when `Stderr` is nil.
+
+- [ ] **Step 4: Run it to see it pass**
+
+Run: `go test ./internal/activator/ -run 'TestUnitStateErrorCarriesStderr|UnitState'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/activator/control.go internal/activator/control_test.go
+git commit -m "activator: a failed systemctl state read logs systemctl's own reason (#451 diagnosis)"
+```
+
+### Task 5: Census and branch review
+
+`internal/hafresh`, `internal/lease` and `internal/host` compile into the root binary, so `TestPlan14RootReadCensus` will fail.
+
+- [ ] **Step 1:** Run `go test . -run TestPlan14RootReadCensus`. Expected: FAIL naming the changed units.
+- [ ] **Step 2:** Follow AGENTS.md "The census": `make census-card`, write the CLAIMS (this code runs in the agent as `carlos`; root's behaviour is unchanged), `make census-propose`. The reviewer decides the ruling (never Paul) and it is recorded on #280.
+- [ ] **Step 3:** Whole-branch Astra review from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3. This branch touches lease takeover (termination and production storage), so it gets that review even though the tasks are small. Focus: the five Review Focus items; that no path takes an HA lock or a same-boot lock.
+- [ ] **Step 4:** CI green on the branch tip; merge with `amadan branch merge carlos/platform <branch> -squash` on Paul's go.
+
+### Task 6: Prove it on dev
+
+Live action: needs Paul's go with the scoped plan (AGENTS.md). Account dev, the dev fleet box (r10r box-1), one reboot, about 10 minutes, nothing created.
+
+- [ ] **Step 1:** After the release carrying this is rolled to dev (roll order: dev boxes, then dev console), reboot box-1 with a rootfs resident and a native instance on it, while probing each public URL every second.
+- [ ] **Step 2:** Pass: both serve again within 2 minutes of the box's tunnel reconnecting (was ~15 min), and the box's log shows the `taking ... from this box's previous boot` line for each.
+- [ ] **Step 3:** Read the previous boot's journal for the `unit state:` lines (Task 4 now carries systemctl's reason). If it is `Failed to connect to bus`, file the unit-ordering follow-up (`After=dbus.service` on the edge unit; a census unit) on #451; otherwise post what it says.
+- [ ] **Step 4:** Post the result on #451 and close it if the takeover held.