rootfs apps plan 3: amendment round 2 (Astra plan review R1)
All 11 findings verified against main a912a342 and fixed: Task 5 widens only (ActivatorLeased keeps hibernating sidecars); N1's staged arm returns before health and every rootfs Gen carries its full identity; new backend interfaces go through SplitBackend with a production-composition test; one releaseRun record owns a release from admission to proof (INV-7); a final worker exec gate; no I/O under a.mu; pins published before exec; a release floor for system apply; INV coverage widened.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+211
−77
docs/superpowers/plans/2026-10-24-rootfs-apps-3-lifecycle.md+211 −77
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-3-lifecycle.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-3-lifecycle.md| index 8a96df6c8..d3fbb1156 100644 |
| --- a/docs/superpowers/plans/2026-10-24-rootfs-apps-3-lifecycle.md |
| +++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-3-lifecycle.md |
| @@ -20,18 +20,19 @@ They come from where Plan 2 spun. Plan 2's Task 11 rounds 1 to 5 and its final w |
| - **INV-1. Runtime first, rootfs proof.** Every agent start, stop, kill, poll and proof of a rootfs row (generation, worker, release, run) goes to the rootfs unit and is proven through `unitEvents` (`waitUnitCgroupEmpty`). Never the binary unit, `Control.Stop`/`StopGen`/`Cmd`/`CmdExe`/`CmdStatus`, `KillHost`, `EmptyHost` or a binary cgroup read. |
| - *Guard (Task 1):* `TestRootfsFilesNameNoBinaryVerb`, a go/ast check over the non-test `rootfs*.go` and `backend_rootfs.go` in `internal/activator` that refuses those identifiers and `childEnv`, resolved through selectors and method values. |
| - - *Behaviour (N1, then Tasks 10 and 12, then W1):* `TestEveryRootfsProofNamesTheRootfsUnit`, a table over each handle's Stop, Poll and Kill. Its fakes have no binary unit and a populated reported group, so each handle must stay unproven, and `KillHost`/`EmptyHost` refuse a rootfs row. |
| + - *Behaviour (Task 1, then N1, Tasks 10 and 12, and W1):* `TestEveryRootfsProofNamesTheRootfsUnit`, a table over each handle's Stop, Poll and Kill. Its fakes have no binary unit and a populated reported group, so each handle must stay unproven, and `KillHost`/`EmptyHost` refuse a rootfs row. Task 1 lands it with the handles main already has (a rootfs generation's `unitProc`, the rootfs `cmdUnit`), so the runtime dispatch in the shared files the guard does not scan (`cmdunit.go:260-293`, `unitproc.go:146-171`) is covered from the first commit: Task 1's mutation evidence flips each dispatch and shows this test fail [Astra R1 11]. |
| - **INV-2. No rootfs file goes before the proof.** Agent side: a worker's launch file, exit records and stray entry, and a release or run hold, go only after `RootfsWorkerGone`, or after the cmd unit's `StopAndSettle`, returned nil. Root side: Plan 3 adds no removal owner, and `TestRootfsRemovalGuard`'s allowlist is unchanged. |
| - *Guard (Task 1):* `TestRootfsRemovalOwnersUnchanged` pins `rawRemovalOwners` and `rootfsRemovalOwners` unchanged. |
| - - *Behaviour (Task 10, W1):* an unproven stop keeps the hold, the stray and `launch.worker.<name>.json`. |
| + - *Behaviour (Tasks 10 and 11, W1):* an unproven stop keeps the obligation that owns it: a release's `releaseRun` record outlives the wake or swap that started it, keeps its lease, its pin and the wake latch, and is retried by its one reaper until proven (`TestReleaseObligationOutlivesTheWake`, `TestReleaseObligationRetriedUntilProven`); a worker's stray keeps `launch.worker.<name>.json`, its exit records and its pin. Each test's mutation (drop the record or the stray on the failure path) makes it fail [Astra R1 11]. |
| - **INV-3. Refuse before the lease.** A rootfs row on a box that refuses rootfs is refused before `Acquire`, `Restore`, `LiveIdentity`, `recordBuild` or any entry state. That covers each of Plan 2's gate reasons, unarmed, and an unknown runtime. |
| - *Behaviour (Task 7, with Task 8's rows):* `TestRootfsRefusalPrecedesTheLease`, a table over every reason through `doWake`, `begin` and `rootfsTick`, asserting `acquires == restores == materialized == 0`. No guard passes on main here: the gap this invariant closes is the pre-flight's finding [pf 2.1]. |
| - **INV-4. A refusal is never a build failure.** Every pre-start refusal is classified gateNoOwnership or stale, and never reaches `OnGen`, `SwapFailed`, the failure book or the resident failure count. That covers `errRootfsRefused`, `ErrStagedImage` and `ErrStartRefused` on `/start` and `/cmd`, unarmed, the release's lease loss and `errSwapBusy`. |
| - *Guard (Task 1):* `TestRootfsRefusalsAreNotBuildFailures`, a `verdictOf`/`classifyStep` table pinning today's rootfs sentinels. |
| - - *Behaviour (N1, Tasks 10 and 11):* client through activator, root answers 503 on `/cmd` mid-swap. |
| + - *Behaviour (N1, Tasks 8, 10 and 11):* client through activator, root answers 503 on `/cmd` mid-swap. Resident accounting reads the same classification: `residentFailure(err)` (Task 8) is false for every INV-4 case (a refusal, the release's lease loss, `errSwapBusy`, `errReleaseUnproven`, `errWakeUnproven`), and the INV-4 table asserts it row by row [Astra R1 11]. |
| - **INV-5. Rootfs launch files carry only the composed environment.** Schema 2, no argv, and `env == rootfsLaunchEnv(vars)`: nothing from the agent's process, so no `PATH` or `HOME` unless the tenant's files set them. `CARLOS_SOCKET` and `CARLOS_DB` are agent-owned. |
| - *Behaviour (Task 1 for web, then Tasks 6, 10 and 12, then W1):* `TestRootfsLaunchFilesCarryOnlyComposedEnv`, with `t.Setenv("PATH", "/agent/bin")`, over web, release, run and worker. Task 1 lands it with the web row, which holds on main (Plan 2's `rootfsLaunchEnv`); each later task adds its row. |
| -- **INV-6. Binary rows unchanged.** Golden tests for the binary `StartCmd` launch, `StartStaged`, the `genHealthy` bound, `KillHost` and `HasSidecar` land in Task 1 and must stay byte-identical (the N1 lesson). |
| +- **INV-6. Binary rows unchanged.** Golden tests for the binary `StartCmd` launch, `StartStaged`, the `genHealthy` bound, `KillHost` and `HasSidecar` land in Task 1 and must stay byte-identical (the N1 lesson). Every Task 5 predicate change only widens a site by residents: binary instances and binary sidecars keep today's answer at every site, and each site's test has a binary-sidecar row [Astra R1 1]. |
| +- **INV-7. One owner for a running release.** From admission to proof a release is owned by exactly one record, `a.releaseRuns[host]` (Task 10), whatever happens to the entry, the wake or the swap that started it. Every consumer (run admission, idle and run ceilings, stop proofs, pins, wake admission, lease give-back) reads that record and nothing else, and one reaper retries its proof [Astra R1 5, 6]. *Behaviour (Tasks 10 and 11):* the INV-2 tests above, plus `TestReleaseRunConsumersReadTheRecord` (each consumer refuses or waits while the record exists, and stops doing so once it is proven and removed). |
| ## Task order and review |
| @@ -108,7 +109,10 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| - Worker restart pacing (Group W) is the co-spawn sidecar's: `sidecarRestartBase` 2 s doubling to `sidecarRestartMax` 60 s, reset after `sidecarHealthyRun` 60 s (`internal/activator/activator.go:779-781`). |
| - C5: every rootfs process (web, workers, release, run) is a unit in the instance's slice and tier. C7: one box runs an instance, under its lease. C8: a failed or timed-out `release` never lets the new `web` serve and never stops the old one under overlap. |
| - The runtime and a rootfs record's hibernation are fixed at mint; no ordinary writer changes either (spec §5.0, B1-2). A re-tenanted host is a new life and takes the incoming runtime and hibernation (Plan 2's rule) [pf 1.10]. |
| -- Every rootfs launch file carries `rootfsLaunchEnv(composed vars)` and nothing of the agent's environment (INV-5) [pf 1.6]. Every rootfs memory limit comes from `b.tier(rt)` or the generation's `g.Tier` (A6) [pf 1.8]. |
| +- Every rootfs launch file carries `rootfsLaunchEnv(composed vars)` and nothing of the agent's environment (INV-5) [pf 1.6]. |
| +- Every backend interface this plan adds (`rootfsStartable`, `rootfsDBPlacer`, `ReleaseBackend`, `RootfsWorkerBackend`) is implemented on `SplitBackend` too, forwarding to `Exec` for an exec-backed row and refusing a unit-backed one, because production builds the service over a `SplitBackend` (`internal/host/agent.go:524`) whose fields promote nothing. Each is covered by `TestProductionBackendImplementsRootfsSeams` and by at least one integration test run through `productionBackend` [Astra R1 4]. |
| +- Nothing slow runs under `a.mu`: no control-service request, store read or file hash. The shape is reserve under the lock, do the I/O off it, retake the lock and re-check ownership before publishing or launching [Astra R1 8]. |
| +- Every exec of a rootfs process names a full staged identity (`stagedIdentityOf`: version, path, digest, demand), and that identity is in the generations file on disk before the exec (`publishBeforeExec`); a failed write starts nothing [Astra R1 3, 9]. Every rootfs memory limit comes from `b.tier(rt)` or the generation's `g.Tier` (A6) [pf 1.8]. |
| - Copy: every user-facing string in this plan is a row of the string table below, written into code only after Paul has approved it in the series deck (`2026-10-24-rootfs-apps-copy.md`). A task that writes one adds its id to the gate's built list in the same commit. No em dashes; a full stop and a new sentence, lower case after it as the run deck does; neutral names (`shop`, `example.com`). |
| - Diagnostics (log lines, `ValidateShape` errors, test messages) are not copy and are not in the table. |
| - CI cross-compiles darwin and windows: linux-only code needs `//go:build linux` and a `!linux` stub. Nothing in this plan adds a syscall. |
| @@ -129,6 +133,7 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| 8. **An app that never opens `CARLOS_DB` restarts (D7).** Test: Task 7, `TestRootfsAppWithoutSQLiteRestarts`; the refusal it must not weaken, `TestServedRootfsNeverBootsEmpty`. |
| 9. **A rootfs row swaps, holds and takes a planned wake [pf 1.1].** On main every one of those starts is refused as gateNoOwnership, so under D2 every deploy would be abandoned while `fakeBackend` tests pass. Tests: N1, `TestOverlapSwapStartsTheRootfsGeneration`, `TestHoldSwapStartsTheRootfsGeneration`, `TestPlannedWakeStartsTheRootfsGeneration`, through `fakeControl`, not `fakeBackend`. |
| 10. **A refused rootfs row costs nothing per retry [pf 2.1].** A resident on a box that refuses rootfs must not take the lease, restore, or materialize the live link on every backoff step. Test: Task 7, `TestRootfsRefusalPrecedesTheLease` (INV-3). |
| +11. **An unproven release outlives its wake [Astra R1 5, 6].** The wake fails and its entry is deleted, but the release's unit may still write the database. The record must keep the lease, the pin and the wake latch, and its one reaper must prove the rootfs cmd unit before anything else runs on the host. Tests: Task 11, `TestReleaseObligationOutlivesTheWake`, `TestReleaseObligationRetriedUntilProven`; Task 10, `TestReleaseRunConsumersReadTheRecord`. |
| --- |
| @@ -151,8 +156,11 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| | `internal/instancectl/client.go` | `CmdRootfs` types root's pre-start refusals (the only `instancectl` file Plan 3 changes) | N1 | |
| | `internal/activator/rootfs_service.go` (new; Plan 2 owns `rootfs.go`) | `healthBoundFor` (N1); start gates, `ArmRootfs`, wake ceiling, first-wake budget (7); residency state and `rootfsTick` (8) | N1, 7, 8 | |
| | `internal/activator/rootfsdb.go` (new) | `ExecBackend.PlaceRootfsDB`, the empty SQLite database of D7 | 7 | |
| -| `internal/activator/backend_rootfs.go` (new) | `Processes`, `stagedImageOf`, `StartRelease`, `ReleaseEnv` (10); `StartWorker`, `RootfsWorkerGone` (W1) | 10, W1 | |
| -| `internal/activator/rootfsrelease.go` (new) | `releaseDue`, `releaseTimeout`, `ReleaseError`, `leaseWatch`, `Service.runRelease` and its lease supervisor | 10 | |
| +| `internal/activator/backend_rootfs.go` (new) | `Processes`, `stagedImageOf`, `StartRelease`, `ReleaseEnv` (10); `LaunchRootfsWorker`, `RootfsWorkerGone` (W1) | 10, W1 | |
| +| `internal/activator/rootfsrelease.go` (new) | `releaseDue`, `releaseTimeout`, `ReleaseError`, `leaseWatch`, `releaseRun` and `reapReleaseRunsLocked`, `Service.runRelease` and its lease supervisor | 10 | |
| +| `internal/activator/maintenance.go`, `opset.go` | the failed wake hands an unproven release's lease to its record; `releasable` waits on the record | 10, 11 | |
| +| `internal/activator/backend_unit.go`, `production_backend_test.go` (new) | `SplitBackend` forwarding of every new interface; the production composition and its test | 7, 10, W1 | |
| +| `internal/release/layoutintent.go` | `RootfsLifecycleFloor` | 15 | |
| | `internal/activator/rootfs_ctl_harness_test.go` (new) | `rootfsCtlHarness`: the real `instancectl.Server` handler and client behind an `ExecBackend` | 10, used by 12 | |
| | `internal/activator/cmd.go`, `cmdunit.go`, `swaphold.go`, `generations_file.go` | release and run integration, the stop proof, the generations pins | 10, 11, 12 | |
| | `internal/activator/rootfsworkers.go` (new), `prepare.go`, `unitproc.go`, `opset.go` | worker identity, lifecycle, supervision, handover, stop proof, `RootfsWorkers` | W1, W2 | |
| @@ -190,6 +198,7 @@ The guards (each passes on main and fails on a violation; fixtures prove each re |
| - **`TestRootfsRemovalOwnersUnchanged` (INV-2).** Parses `internal/instancectl/rootfs_removal_guard_test.go` with `go/parser` (no file there changes) and checks the keys of `rawRemovalOwners` and `rootfsRemovalOwners` are a subset of the sets pinned in this test at Task 1. The claims cleanup may shrink them (a merge of `origin/main` that removes an entry stays green); Plan 3 never adds one. |
| - **`TestRootfsRefusalsAreNotBuildFailures` (INV-4).** A table over today's rootfs sentinels, each wrapped as the code wraps it: `refuseRootfs(errors.New("x"))`, `errRootfsRefused`, `errRootfsBinaryLaunch`, `errNoRootfsControl`, `fmt.Errorf("%w: x", instancectl.ErrStagedImage)`, `refuseRootfs(fmt.Errorf("%w: x", instancectl.ErrStartRefused))` (the marking `rootfs.go:322` does), `errBuildStateUnwritten`. Each: `verdictOf(err) == gateNoOwnership` (`swap.go:228`) and `classifyStep(nil, err) == stepStale` (`swap.go:134`), never a failure outcome. Later tasks add their sentinels to this table (Task 7's, Task 10's lease loss and `errSwapBusy`). |
| - **`TestRootfsLaunchFilesCarryOnlyComposedEnv` (INV-5), web row.** `t.Setenv("PATH", "/agent/bin")` and `t.Setenv("HOME", "/agent")`; production-wired (`nestedBackend`, `unitproc_test.go:225`, with `fakeControl`), a rootfs row with a `.env` holding `SHOP_MODE=live`: `StartGenExe` for generation 7; the launch file `GenLaunchFileName(7)` decodes to schema 2, no argv, `Env == rootfsLaunchEnv(<the vars startRootfs composed>)`, and neither `PATH` nor `HOME` is in it. A table keyed by process, so Tasks 6, 10 and 12 and W1 add `release`, `run` and `worker` rows. |
| +- **`TestEveryRootfsProofNamesTheRootfsUnit` (INV-1 behaviour), main's rows.** Production-wired (`nestedBackend` with `fakeControl` and a cgroup fixture whose `cgroup.events` the test sets; no binary unit in any answer, every rootfs unit's group `populated 1`): a rootfs generation's `unitProc` (Stop asks `StopRootfs` for that generation, never `Stop`/`StopGen`, and stays unproven), and the rootfs `cmdUnit` (`Poll` asks `CmdStatusRootfs`; `StopAndSettle` asks `StopRootfs` with `RoleCmd` and fails while `RootfsUnitName(RoleCmd, host)`'s group is populated). A table keyed by handle, so N1, Tasks 10 and 12 and W1 add rows. |
| - **INV-6 goldens** (`binary_golden_test.go`, each byte-compared with a file under `testdata/binary_golden/`, written once from main at Task 1; a later change to a golden file needs its own reason in review): |
| - `TestBinaryStartCmdLaunchGolden`: a binary nested row's `StartCmd` (`cmdunit.go:172`): `launch.cmd.json`'s bytes, and the `Control.Cmd` or `CmdExe` call `fakeControl` records (host, `b.tier(rt).MemoryMax`, the staged exe). |
| - `TestBinaryStartStagedGolden`: `StartStaged` (`genbackend.go:230`) on a binary nested row and a binary flat row: the returned `Gen` and the start request `fakeControl` records. |
| @@ -198,8 +207,8 @@ The guards (each passes on main and fails on a violation; fixtures prove each re |
| - `TestHasSidecarBinaryGolden`: `HasSidecar` (`backend_exec.go:2985`) on a binary row: a planted `<host>-sidecar.env` answers true, none false. |
| - [ ] **Step 1:** `grep -c '^| RFS-3-' docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md` is 29: 28 `approved`, RFS-3-C13 `struck`; every RFS-3 file cell is a bare path with an optional note in parentheses; `rootfsCopyStruck` is `{"RFS-3-C13"}`. Run `go test . -run 'TestRootfsCopy|TestRootfsBuilt' -count=1` (PASS). If a row was added after 2026-10-24 and is `pending`, invoke the `copy-review` skill on those rows only, apply Paul's edits verbatim to the deck and to this plan's string table, and mark them `approved` (read `result.json` before any restart of the review server). |
| -- [ ] **Step 2:** Write the guards and goldens above. Run `go test ./internal/activator/ -run 'TestRootfsFilesNameNoBinaryVerb|TestRootfsRemovalOwnersUnchanged|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` under the short `TMPDIR`. Expected: PASS on main. |
| -- [ ] **Step 3:** Mutation evidence, in scratch edits reverted by hand before the commit (never `git checkout`): add `_ = b.Control.Stop` to `rootfs.go` (INV-1 FAILS); add `"x": true` to a copy of `rawRemovalOwners` in a fixture (INV-2 FAILS); swap `rootfsLaunchEnv` for `childEnv` in `startRootfs`'s launch (INV-1 and INV-5 FAIL); change `spawnHealthTimeout` to 31 s (INV-6 FAILS). Record each in the report. |
| +- [ ] **Step 2:** Write the guards and goldens above. Run `go test ./internal/activator/ -run 'TestRootfsFilesNameNoBinaryVerb|TestRootfsRemovalOwnersUnchanged|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv|TestEveryRootfsProofNamesTheRootfsUnit|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` under the short `TMPDIR`. Expected: PASS on main. |
| +- [ ] **Step 3:** Mutation evidence, in scratch edits reverted by hand before the commit (never `git checkout`): add `_ = b.Control.Stop` to `rootfs.go` (INV-1 guard FAILS); add `"x": true` to a copy of `rawRemovalOwners` in a fixture (INV-2 FAILS); swap `rootfsLaunchEnv` for `childEnv` in `startRootfs`'s launch (INV-1 and INV-5 FAIL); in the shared dispatch files the guard does not scan, make `cmdUnit.Poll`'s rootfs test (`cmdunit.go:261`) false, and make `stopRole` (`unitproc.go:165`) take its binary arm for a rootfs row (INV-1 behaviour FAILS for each); change `spawnHealthTimeout` to 31 s (INV-6 FAILS). Record each in the report. |
| - [ ] **Step 4:** Commit. |
| ```bash |
| @@ -227,6 +236,8 @@ git commit -m "rootfs apps plan 3: invariant guards INV-1, 2, 4, 5 and the binar |
| func (t Route) Rootfs() bool // t.Runtime == RuntimeRootfsV1 |
| func (t Route) ActivatorOwned() bool // t.Kind == "instance" && (t.Hibernate || t.Rootfs()) |
| func (t Route) Resident() bool // t.Kind == "instance" && t.Rootfs() && !t.Hibernate |
| + func (t Route) ActivatorLeased() bool // t.Hibernate || t.Resident(): every row whose lease and replication the |
| + // activator holds, binary sidecars included (they hibernate: sidecarRouteFor, provision/sidecar_reconcile.go:131) |
| var ErrRuntimeFixed = errors.New("registry: a rootfs row's hibernation is fixed when it is minted") |
| func (r *Registry) ResidentInstances() ([]Route, error) |
| ``` |
| @@ -244,9 +255,10 @@ Rules the code must keep: |
| - [ ] **Step 1: Write the failing tests** in `runtime_test.go` (each opens a temp registry with `Open(filepath.Join(t.TempDir(), "r.db"))`): |
| ```go |
| -func TestRoutePredicates(t *testing.T) // table: binary hibernating (owned, not resident); binary awake (neither); |
| - // rootfs hibernate=true (owned, Rootfs, not resident); rootfs hibernate=false (owned, Rootfs, Resident); |
| - // rootfs kind static (not owned); Runtime "rootfs-v2" (Rootfs false, owned only if Hibernate) |
| +func TestRoutePredicates(t *testing.T) // table: binary hibernating (owned, leased, not resident); binary awake (none); |
| + // binary hibernating sidecar (not owned, leased); binary awake sidecar (none); |
| + // rootfs hibernate=true (owned, leased, Rootfs, not resident); rootfs hibernate=false (owned, leased, Rootfs, Resident); |
| + // rootfs kind static (not owned, not leased); Runtime "rootfs-v2" (Rootfs false, owned and leased only if Hibernate) |
| func TestResidentKeepsItsReplicationRung(t *testing.T) |
| // rootfs hibernate=false Replication "daily" -> kept on insert; a re-Upsert with Replication "" keeps "daily"; |
| // a binary hibernate=false row with "daily" is still cleared (today's rule) |
| @@ -393,6 +405,8 @@ git commit -m "provision: reconcile mints rootfs rows nested and seedless; never |
| The always-awake design's rule: no consumer reconstructs "the activator owns this" with its own `Hibernate` test. Each change below is one expression; each family has its own test, and each test fails if its expression is put back to `Hibernate`. |
| +The rule for every row: a change only widens a site by residents (INV-6). A site that already tests `Kind == "instance" && Hibernate` takes `ActivatorOwned()`, which is that plus residents. A site that tests `Hibernate` with no kind check also covers hibernating binary sidecars today, so it takes `ActivatorLeased()` (`Hibernate || Resident()`), never `ActivatorOwned()`, which would drop the sidecars [Astra R1 1]. Each family's test has a binary hibernating sidecar row that answers as on main. |
| + |
| **Files and changes:** |
| | site | today | becomes | |
| @@ -401,9 +415,10 @@ The always-awake design's rule: no consumer reconstructs "the activator owns thi |
| | `internal/activator/wakeidentity.go:61-66` (`stillWoken`; `wakeRouteChanged` is `:36`) | runtime not compared | `began.Runtime != now.Runtime` is a changed route | |
| | `internal/activator/activator.go:5395` `ServeScheduled`, `:5407` and `:5440` `serve` | `rt.Hibernate` | `rt.ActivatorOwned()` | |
| | `internal/edge/edge.go:805` (generation proxy), `:926` (`hib`), `:959` (no-activator advice) | `t.Kind == "instance" && t.Hibernate` | `t.ActivatorOwned()` | |
| -| `internal/ops/litestream.go:356` (`FleetDBsWithSkipped`) and `internal/ops/hibernate_verify.go:58` (`HibernatingHosts`) | `r.Hibernate && r.DBPath != ""` | `r.ActivatorOwned() && r.DBPath != ""` | |
| +| `internal/ops/litestream.go:356` (`FleetDBsWithSkipped`) and `internal/ops/hibernate_verify.go:58` (`HibernatingHosts`) | `r.Hibernate && r.DBPath != ""` (no kind check: a hibernating binary sidecar, which `sidecarRouteFor` mints with a database path, `provision/sidecar_reconcile.go:131`, is the activator's to replicate) | `r.ActivatorLeased() && r.DBPath != ""`, never `ActivatorOwned`, which is instance-only and would put every hibernating sidecar's database into box-wide replication beside the activator's [Astra R1 1] | |
| | `internal/rollout/policy.go:168` `Managed` | `release.Adoptable(rt) && rt.Hibernate` | `release.Adoptable(rt) && rt.ActivatorOwned()` | |
| -| `internal/host/socket_advice.go:42`, `:83`, `:121`; `internal/host/probes.go:310`; `internal/host/schedule_wiring.go:342` | `rt.Hibernate` | `rt.ActivatorOwned()`. At `:121` it picks the diagnostic: a resident is activator-managed, so it gets the stray-supervisor line, never the "set hibernate=1" advice [pf 1.13] | |
| +| `internal/host/socket_advice.go:83`; `internal/host/probes.go:310`; `internal/host/schedule_wiring.go:342` | `r.Kind == "instance" && r.Hibernate` | `r.ActivatorOwned()` (the same answer for every binary row) | |
| +| `internal/host/socket_advice.go:42`, `:121` | `rt.Hibernate` (no kind check) | `rt.ActivatorLeased()`. At `:121` it picks the diagnostic: a resident is activator-managed, so it gets the stray-supervisor line, never the "set hibernate=1" advice [pf 1.13, Astra R1 1] | |
| | `internal/release/pins.go:236` `BuildStateKept` | `rt.Hibernate && rt.Socket != "" && ...` | `rt.ActivatorOwned() && rt.Socket != "" && ...` (a registry predicate, so the package can import it). It must agree with the host's `keepsBuildState` (`internal/host/buildstate.go:367-376`), which reads `ActivatorManaged` and so widens with the first row [pf 1.13] | |
| | `internal/layout/pass.go:264` | every `ActivatorManaged` row converges | a rootfs row is skipped with `Result{Host, "kept", "rootfs instances are always nested"}` in both modes; `restoreHold` (`:529`) and the recheck it runs (`recheck`, `:559`) refuse one the same way | |
| @@ -434,13 +449,16 @@ func TestPlatformApexOfRootfsIsAnAlias(t *testing.T) // mintedRoute(src rootf |
| // internal/ops/rootfs_litestream_test.go |
| func TestFleetDBsExcludesResidentRootfs(t *testing.T) // the resident's DB is skipped by FleetDBsWithSkipped and listed by |
| // HibernatingHosts; a binary hibernate=false row's DB is still replicated box-wide (as TestFleetDBsDiscoversNestedDatabases sets up) |
| +func TestFleetDBsStillExcludesHibernatingSidecars(t *testing.T) // [Astra R1 1] a hibernating binary sidecar with a DB path (as |
| + // sidecarRouteFor mints it): skipped by FleetDBsWithSkipped and listed by HibernatingHosts (the restore drill), as on main; |
| + // an always-on sidecar's DB is replicated box-wide as on main |
| // internal/rollout/rootfs_managed_test.go |
| func TestManagedIncludesResidentRootfs(t *testing.T) |
| // internal/release/rootfs_pins_test.go |
| func TestBuildStateKeptCoversResident(t *testing.T) // BuildStateKept(resident) true; a binary awake row false; a binary hibernating row true |
| // internal/host/rootfs_advice_test.go |
| func TestSocketAdvisoryLeavesOwnedResident(t *testing.T) // warnExternalSockets(owns true) returns nothing for it; not owned, the |
| - // activator-managed diagnostic is the one logged |
| + // activator-managed diagnostic is the one logged; a hibernating sidecar with a socket answers as on main |
| func TestCurrentSocketProbeFollowsResident(t *testing.T) |
| func TestResidentSettingsRefsWaitForBuildState(t *testing.T) // a resident's held settings refs refuse while its build state is unread: |
| // the sweep never reads them as complete before keepsBuildState's read, so a pinned build is not swept |
| @@ -450,7 +468,7 @@ func TestPassNeverMovesRootfsRows(t *testing.T) // flat mode, nested ro |
| - [ ] **Step 2:** Run each package's tests with `-run` on the names above. Expected: FAIL. |
| - [ ] **Step 3:** Make the changes in the table. Do not touch `keepsBuildState`'s `claims` parameter; the cleanup removes it [pf 3.3]. |
| -- [ ] **Step 4:** Run Step 2's commands, then each touched package's existing tests on the families touched (`-run 'Reload|FleetDBs|Hibernating|Managed|Advisory|SocketProbe|Pass|ActivatorManaged|WakeRoute|BuildState|Pins'`). Expected: PASS. |
| +- [ ] **Step 4:** Run Step 2's commands, then each touched package's existing tests on the families touched (`-run 'Reload|FleetDBs|Hibernating|Managed|Advisory|SocketProbe|Pass|ActivatorManaged|WakeRoute|BuildState|Pins|Sidecar|Drill'`). Expected: PASS. |
| - [ ] **Step 5: Commit** |
| ```bash |
| @@ -525,15 +543,20 @@ On main a rootfs row can never swap, hold or take a planned wake. The overlap su |
| - Modify: `internal/activator/genbackend.go`: `StartStaged` (`:230`, the rootfs arm); `KillHost` (`:583`) and `EmptyHost` (`:623`) refuse a rootfs row; the `SplitBackend` forms (below each) forward the refusal |
| - Modify: `internal/activator/swap.go`: `genHealthy` (`:358`) takes the row and waits `healthBoundFor(rt)`; `internal/activator/wakeplan.go`: `verdictFloorGate` (`:478`) takes the bound, and `spawnPlanned` (`:370`) passes `healthBoundFor(rt)` |
| - Modify: `internal/activator/backend_exec.go`: `HasSidecar` (`:2985`) answers false for a rootfs row; `StartSidecar` (`:2991`) keeps refusing rootfs |
| +- Modify: `internal/activator/rootfs.go`: `startRootfsFromLive` (`:168`) returns the identity it resolved and `startRootfsGen` (`:189`) puts it on the `Gen`; `internal/activator/identity.go` (`stagedIdentityOf`, beside `stagedExeOf` at `:98`) |
| - Modify: `internal/instancectl/client.go`: `CmdRootfs` (`:484-506`) types root's pre-start answers |
| - Create: `internal/activator/rootfs_service.go` (this task's part: `healthBoundFor`), `internal/activator/rootfs_staged_test.go` |
| - Modify: `internal/activator/rootfs_invariants_test.go` (INV-1's behaviour table, INV-4 rows) |
| **Interfaces:** |
| -- Consumes: Plan 2's `startRootfsGen(ctx, rt, n, perGen bool, id *release.StagedIdentity) (Proc, Gen, error)` (`rootfs.go:189`), `refuseRootfs` (`rootfs.go:65`), `rootfsHealthTimeout`, `spawnHealthTimeout` (`backend_exec.go:43`), `instancectl.startRefused` (`client.go:438`), `ErrStartRefused` (`client.go:434`). |
| +- Consumes: Plan 2's `rootfsGates` (`rootfs.go:128`), `spawnRootfs(ctx, rt, sock, n, id) (*unitProc, string, error)` (`rootfs.go:269`, which returns once the unit runs, before any health wait), `startRootfsGen` (`rootfs.go:189`), `startRootfsFromLive` (`rootfs.go:168`), `refuseRootfs` (`rootfs.go:65`), `rootfsHealthTimeout`, `spawnHealthTimeout` (`backend_exec.go:43`), `instancectl.startRefused` (`client.go:438`), `ErrStartRefused` (`client.go:434`). |
| - Produces: |
| ```go |
| func healthBoundFor(rt registry.Route) time.Duration // rootfsHealthTimeout (120 s) for a rootfs row; spawnHealthTimeout (30 s) otherwise |
| + // stagedIdentityOf is g's full staged identity [Astra R1 3]: genIdentity (generations_file.go:220) answers two values and |
| + // only Version and StagedPath, which the manifest digest check and /cmd cannot use. It refuses a Gen with no StagedPath |
| + // or no Digest, so nothing downstream runs on a partial identity. |
| + func stagedIdentityOf(g Gen) (release.StagedIdentity, error) // {g.Build, g.StagedPath, g.Digest, g.Demand} |
| func (a *Service) genHealthy(ctx context.Context, rt registry.Route, g Gen) error // waits healthBoundFor(rt) |
| func verdictFloorGate(gate func() error, healthBy time.Time, bound time.Duration, left *time.Duration) func() error |
| var errRootfsKillHost = errors.New("activator: a rootfs row has no host cgroup to kill or prove empty") |
| @@ -541,8 +564,9 @@ On main a rootfs row can never swap, hold or take a planned wake. The overlap su |
| ``` |
| Rules: |
| -- **`StartStaged`'s rootfs arm** checks the runtime first, before `genLayout`: for `rt.Runtime == registry.RuntimeRootfsV1`, refuse an empty `g.StagedPath` with `refuseRootfs` (a swap never starts the live link); else build `id := release.StagedIdentity{Version: g.Build, StagedPath: g.StagedPath, Digest: g.Digest, Demand: g.Demand}` and call `b.startRootfsGen(ctx, rt, g.N, true, &id)`, returning `(gen, proc, err)` in `StartStaged`'s order. Keep `g.Tier` from `GenTier`, as the binary arms do. The exec gate rides in on `ctx` (`withExecGate`) and `startRootfsGen`'s `rootfsGates` runs first, so a refused start asks root nothing. The binary arms are unchanged (INV-6). |
| -- **The health bound** [pf 1.2]: `genHealthy` and `verdictFloorGate` use `healthBoundFor(rt)` where they used `spawnHealthTimeout`. `startRootfs` already waits `rootfsHealthTimeout` itself (`rootfs.go:234`); the floor must size B's verdict window to the same bound, or a 40 to 120 s boot loses its window on every first wake. A binary row stays at 30 s (INV-6). |
| +- **`StartStaged`'s rootfs arm** keeps `StartStaged`'s contract, which every caller relies on: it returns the process as soon as it runs, and the caller does the one bounded health check (`startPinnedAt`, `swaphold.go:481`, under its `healthBy`; `swapOverlap`, `swap.go:582`) [Astra R1 2]. So it must not call `startRootfsGen`, whose `startRootfs` waits for health itself (`rootfs.go:234`) and, after stopping an unhealthy unit, answers a nil process and an ordinary error (`rootfs.go:252`): `spawnPlanned` reads that as nothing ran (`wakeplan.go:419-424`), records no failure of B and does not fall back, and a hold loses its execution evidence. The arm checks the runtime first, before `genLayout`: for `rt.Runtime == registry.RuntimeRootfsV1`, `id, err := stagedIdentityOf(g)` (an empty `StagedPath` or `Digest` is refused with `refuseRootfs`: a swap never starts the live link); `b.rootfsGates(rt)`; `release.VerifyStaged(id)`; then `up, ver, err := b.spawnRootfs(ctx, rt, sock, g.N, id)` with `sock = nestedGenSocketIn(runDir, g.N)`. It returns `(g', up, err)` with `g'` carrying `N`, `Socket`, `Control`, `Build = ver` and the full identity, and `g.Tier` kept from `GenTier`, as the binary arms do. Errors follow `spawnRootfs`'s contract (spawnUnitFrom's): a handle comes back whenever the unit may have run, so `startMayHaveRun` and `genStartUnproven` see it. The exec gate rides in on `ctx` (`withExecGate`) and `rootfsGates` runs first, so a refused start asks root nothing. The binary arms are unchanged (INV-6). |
| +- **Every rootfs `Gen` carries its full identity** [Astra R1 3]: `startRootfsGen`'s live-link branch (`id == nil`, `rootfs.go:202-203`; the fill at `:219-221` runs only when `id != nil`) today leaves `g.StagedPath` and `g.Digest` empty, because `startRootfsFromLive` drops the identity it resolved. It returns that identity, and `startRootfsGen` fills `g.StagedPath`, `g.Digest`, `g.Demand` and `g.Tier` from it in both branches, so `stagedIdentityOf(e.gen)` never refuses a rootfs generation that is running. |
| +- **The health bound** [pf 1.2]: `genHealthy` and `verdictFloorGate` use `healthBoundFor(rt)` where they used `spawnHealthTimeout`. With the staged arm above, the caller's check is the only health wait a staged rootfs generation gets, so it must be the rootfs bound, or a 40 to 120 s boot fails health on every swap and loses its verdict window on every first wake. A binary row stays at 30 s (INV-6). |
| - **`CmdRootfs`'s typed refusal** [pf 1.7]: as `startRootfsQuery` does for `/start` (`client.go:446-458`, final review I1): `status == 403` is `ErrStagedImage`; `startRefused(status)` (400, 409, 501, 503, 507) is `ErrStartRefused`; anything else, 502 and transport included, stays plain. Root's pre-start `/cmd` answers are 501 (`instancectl/rootfs.go:1017`), 409 (`:1022`, `:1045`), 503 (the probe, through `rootfsPreflight`) and 400. The callers mark both with `refuseRootfs` (Tasks 10 and 12), which `verdictOf` already reads as a refusal (`swap.go:247`). |
| - **`KillHost` and `EmptyHost`** [pf 2.2] return `errRootfsKillHost` for a rootfs row, never nil, before any cgroup is opened: they read `carlos-exec@<host>`, where an absent cgroup counts as proven, and a rootfs process never lives there. Today only binary sidecar-worker generations (`opset.go:295`) and flat rows (`opset.go:363`, `:406`, `:451`) reach them; this makes a later path that reaches them with a rootfs row fail closed. INV-1's guard already keeps `hostKiller` and `hostEmptier` out of rootfs files. |
| - **`HasSidecar`** [pf 1.14] answers false for a rootfs row: it stats `<host>-sidecar.env` in the tenant-writable instance directory, and for a rootfs row the co-spawn would be refused by `nestedGate` and retried by `sidecarWanted` every sweep. This closes Plan 2's "seed/sidecar/cmd refuse until Plan 3" carry (ledger 76): seeds by D5 and `RouteFor`, cmd by Task 12's rootfs arm, sidecar here. |
| @@ -556,10 +580,18 @@ func TestHoldSwapStartsTheRootfsGeneration(t *testing.T) // ModeHold: the pin |
| func TestPlannedWakeStartsTheRootfsGeneration(t *testing.T) // spawnPlanned booting B: StartRootfs for the planned generation with B's image |
| func TestStartStagedRefusesARootfsLiveLink(t *testing.T) // g.StagedPath "": errors.Is(err, errRootfsRefused); fakeControl asked nothing |
| func TestStartStagedKeepsTheGenerationsTier(t *testing.T) // the returned Gen's Tier is GenTier(rt, B); the StartRootfs memory_max is its MemoryMax |
| -func TestRootfsFirstWakeGetsTheRootfsHealthBound(t *testing.T) // a planned first wake of a rootfs build with healthBy 100 s ahead is not |
| - // refused with errNoTimeForVerdict; a binary row with the same healthBy gets a 30 s window (INV-6's golden unchanged) |
| -func TestGenHealthyUsesTheRowsBound(t *testing.T) // rootfsHealthTimeout and spawnHealthTimeout shrunk to distinct values: |
| - // a rootfs successor answering between them is healthy; a binary one is not |
| +func TestStagedRootfsStartReturnsBeforeHealth(t *testing.T) // [Astra R1 2] StartStaged on a rootfs row whose web never answers returns |
| + // a non-nil handle at once, with the full identity on the Gen; it waits no health itself |
| +func TestUnhealthyRootfsPlannedWakeFailsB(t *testing.T) // real spawnPlanned wiring, fakeControl, web never answers: B's failure is |
| + // recorded (w.failed), the planned fallback to the good build runs, the unhealthy unit is stopped and proven |
| +func TestUnhealthyRootfsHoldReportsDown(t *testing.T) // ModeHold, web never answers: SwapDown with execution evidence (pinExec), |
| + // never a cancelled no-run |
| +func TestEveryRootfsGenCarriesItsIdentity(t *testing.T) // StartGen (live link) and StartGenExe on a rootfs row: the Gen has |
| + // StagedPath, Digest and Demand of the image root was asked for; stagedIdentityOf(g) succeeds; a Gen without Digest refuses |
| +func TestRootfsHealthWindowIsTheRootfsBound(t *testing.T) // [Astra R1 11] spawnHealthTimeout 300 ms, rootfsHealthTimeout 2 s, a web that |
| + // first answers at 900 ms; through the real planned-wake and overlap wiring: the rootfs generation is healthy and serves; the |
| + // same timing on a binary row fails health. healthBy is set far enough out that verdictFloorGate's floor is not what decides |
| + // (today's 30 s window and 20 s floor would pass a 100 s-ahead healthBy without proving the change) |
| func TestCmdRootfsRefusalsAreTyped(t *testing.T) // a unix-socket HTTP stub behind instancectl.NewClient answering /cmd with |
| // 400, 409, 501, 503: errors.Is(err, ErrStartRefused); 403: ErrStagedImage; 502: neither |
| func TestKillHostAndEmptyHostRefuseRootfs(t *testing.T) // ExecBackend and SplitBackend, rootfs row, cgroup absent: both return |
| @@ -569,7 +601,7 @@ func TestHasSidecarFalseForRootfs(t *testing.T) // a planted <host>- |
| INV-1's behaviour test lands here: `TestEveryRootfsProofNamesTheRootfsUnit`, a table over each rootfs handle's Stop, Poll and Kill (this task: a rootfs generation's `unitProc` and `KillHost`/`EmptyHost`), whose fakes have no binary unit and a populated reported group (`unitEvents` answers populated), so every handle stays unproven and both host verbs refuse. Tasks 10 and 12 and W1 add their handles. INV-4's table gains `fmt.Errorf("%w: x", instancectl.ErrStartRefused)` from `/cmd`, marked by `refuseRootfs`. |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapSwapStartsTheRootfs|TestHoldSwapStartsTheRootfs|TestPlannedWakeStartsTheRootfs|TestStartStaged|TestRootfsFirstWakeGets|TestGenHealthyUses|TestCmdRootfsRefusalsAreTyped|TestKillHostAndEmptyHost|TestHasSidecarFalse|TestEveryRootfsProofNamesTheRootfsUnit' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapSwapStartsTheRootfs|TestHoldSwapStartsTheRootfs|TestPlannedWakeStartsTheRootfs|TestStartStaged|TestStagedRootfsStartReturnsBeforeHealth|TestUnhealthyRootfs|TestEveryRootfsGenCarriesItsIdentity|TestRootfsHealthWindow|TestCmdRootfsRefusalsAreTyped|TestKillHostAndEmptyHost|TestHasSidecarFalse|TestEveryRootfsProofNamesTheRootfsUnit' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| - [ ] **Step 3:** Implement to the rules. |
| - [ ] **Step 4:** Run Step 2's command, Task 1's guards and goldens, and the families the edits touch: `-run 'Swap|Hold|Planned|FirstWake|Overlap|KillHost|EmptyHost|Sidecar|StartStaged|Verdict'`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -589,7 +621,8 @@ git commit -m "activator: StartStaged starts rootfs generations; the rootfs heal |
| - Modify: `internal/activator/rootfs_service.go` (this task's half), create `internal/activator/rootfs_gate_test.go` |
| - Create: `internal/activator/rootfsdb.go`, `internal/activator/rootfsdb_test.go` (D7, Astra R1 finding 8) |
| - Modify: `internal/activator/activator.go`: `wake` (`:1760`, the ceiling), `doWake` (`:2114`: the gate after step 0's refresh and before step 0.5 at `:2161`; after step 2 at `:2302` the served-never-empty check and the placeholder; after step 5 at `:2616` the placeholder's first sync, in step 5b's shape at `:2628`), `begin` (`:1484`, the gate before an entry is made), `serveWakeError` (`:5494`) |
| -- Modify: `internal/activator/backend_unit.go:316` (beside `SplitBackend.SeedPlaced`): `SplitBackend.PlaceRootfsDB` dispatches on `Backing` like it; a side without `rootfsDBPlacer` answers `errNoRootfsDB`. `SplitBackend` forwards `rootfsStartable` the same way. |
| +- Modify: `internal/activator/backend_unit.go` (beside `SplitBackend.SeedPlaced`, `:316`): `SplitBackend.PlaceRootfsDB` and `SplitBackend.rootfsStartable`, each forwarding to `b.Exec` for an exec-backed row whose `Exec` implements the interface and refusing otherwise (`errNoRootfsDB`; `refuseRootfs(errNoRootfsControl)`). Production builds the service over a `SplitBackend` (`internal/host/agent.go:524`), whose fields promote nothing, so an interface only `ExecBackend` implements is invisible in production [Astra R1 4] |
| +- Create: `internal/activator/production_backend_test.go`: `productionBackend(t, eb *ExecBackend) *SplitBackend`, the composition `agent.go:524` builds (`&SplitBackend{Exec: eb, Unit: &UnitBackend{OptDir: ...}}`), and `TestProductionBackendImplementsRootfsSeams`, which asserts the production composition satisfies every interface Plan 3 adds (this task: `rootfsStartable`, `rootfsDBPlacer`; Task 10: `ReleaseBackend`; W1: `RootfsWorkerBackend`) and that a unit-backed row is refused by each |
| - Modify: `internal/activator/wakeplan.go:381` and `awaitWake` (`activator.go:1606`, its deadline at `:1621`): `firstWakeBudgetFor(rt)` |
| - Modify: `internal/host/rollout.go:406`: `svc.ArmRootfs()` once the manager has armed (not in `refuseManaged`, `:210`) |
| @@ -599,11 +632,16 @@ git commit -m "activator: StartStaged starts rootfs generations; the rootfs heal |
| ```go |
| func (a *Service) ArmRootfs() // a.rootfsArmed.Store(true); only internal/host calls it |
| // rootfsStartable is the backend's own rootfs gates, asked before the lease. ExecBackend answers rootfsGates(rt); |
| - // SplitBackend forwards to its exec side. A backend without it answers nothing here and Start still gates. |
| + // SplitBackend forwards to its exec side and refuses a unit-backed row. A backend without it refuses a rootfs row |
| + // (refuseRootfs(errNoRootfsControl)): there is no unchecked path. It may do I/O (the control service's readiness, |
| + // a cached owner read), so it is never called with a.mu held [Astra R1 8]. |
| type rootfsStartable interface{ rootfsStartable(rt registry.Route) error } |
| - func (a *Service) rootfsStartRefusal(rt registry.Route) error // nil for a binary row with a valid runtime; else, in order: |
| - // !registry.ValidRuntime(rt.Runtime) -> errRuntimeUnknown; !a.gens || !a.rootfsArmed.Load() -> errRootfsUnarmed; |
| - // the backend's rootfsStartable(rt). Every non-nil answer is marked with refuseRootfs (errRootfsRefused). |
| + // Two halves, so nothing slow runs under a.mu [Astra R1 8]: |
| + func (a *Service) rootfsRefusalLocked(rt registry.Route) error // cheap, under a.mu: nil for a binary row with a valid |
| + // runtime; !registry.ValidRuntime(rt.Runtime) -> errRuntimeUnknown; !a.gens || !a.rootfsArmed.Load() -> errRootfsUnarmed |
| + func (a *Service) rootfsStartRefusal(ctx context.Context, rt registry.Route) error // never with a.mu held: the locked half |
| + // (taking a.mu briefly), then the backend's rootfsStartable(rt), shared per host (a singleflight, so a request storm on a |
| + // cold host asks the gates once). Every non-nil answer of either half is marked with refuseRootfs (errRootfsRefused). |
| var errRootfsUnarmed, errRuntimeUnknown, errRootfsReplicaMissing error |
| func wakeCeilingFor(rt registry.Route) time.Duration // 5 min; rootfs: 5 min + runs.MaxTimeout |
| func firstWakeBudgetFor(rt registry.Route) time.Duration // firstWakeBudget; rootfs: healthBoundFor(rt) + firstWakeKillReserve |
| @@ -620,7 +658,7 @@ git commit -m "activator: StartStaged starts rootfs generations; the rootfs heal |
| The method is `rootfsStartRefusal`, not `rootfsRefusal`, because Plan 2's `rootfsRefusal` is the wrapper type `refuseRootfs` builds (`rootfs.go:58`). The first draft's `errRootfsClaim` and its claim reason are struck: Plan 3 reads no claim switch, and Plan 2's gates still refuse under it (`rootfs.go:155`), which this gate inherits [pf 3.1]. |
| Rules: |
| -- **Refuse before the lease (INV-3)** [pf 2.1]: `doWake` and `begin` refuse a rootfs row on `rootfsStartRefusal` before `Acquire`, `Restore`, `LiveIdentity`, `recordBuild` or any entry state: `acquires == restores == materialized == 0`. Plan 2's `rootfsGates` still runs inside `Backend.Start`, after `Acquire`, `Restore` and `LiveIdentity` (which materializes the live link); asking it here first means a refused row pays none of that. The wake's member event is `RFS-3-C12` with the fragment `RFS-3-C14` for unarmed. An unknown runtime and a backend gate refusal log only (no member can cause the first; the second carries Plan 2's reason in the log). `serveWakeError` answers these 503 "instance failed to wake" (today's text). Task 8 asks the same gate in `rootfsTick`. |
| +- **Refuse before the lease (INV-3)** [pf 2.1]: `doWake` and `begin` refuse a rootfs row before `Acquire`, `Restore`, `LiveIdentity`, `recordBuild` or any entry state: `acquires == restores == materialized == 0`. Where each half runs [Astra R1 8]: `begin` asks `rootfsRefusalLocked` under its lock; on the path that would make a new entry (no live entry for the host) it drops `a.mu`, asks `rootfsStartRefusal`, retakes `a.mu` and re-checks from the top of its loop (an entry made meanwhile is coalesced on, as today), so an awake instance's requests never pay the gates and a cold one's pay them once per wake attempt; `doWake` asks `rootfsStartRefusal` off `a.mu` before step 0.5, for wakes that did not come through `begin` (due wakes, planned wakes, the tick); Task 8's tick asks it off `a.mu` for each candidate before it takes the lock to start one. Plan 2's `rootfsGates` still runs inside `Backend.Start`, after `Acquire`, `Restore` and `LiveIdentity` (which materializes the live link); asking it here first means a refused row pays none of that. The wake's member event is `RFS-3-C12` with the fragment `RFS-3-C14` for unarmed. An unknown runtime and a backend gate refusal log only (no member can cause the first; the second carries Plan 2's reason in the log). `serveWakeError` answers these 503 "instance failed to wake" (today's text). Task 8 asks the same gate in `rootfsTick`. |
| - `errRuntimeUnknown` is also returned for a binary-looking row whose `Runtime` is not valid, so no future value degrades to a binary launch. |
| - **Request budget** [pf 2.1]: the early gate's placement read is Plan 2's coalesced owner cache (at most 12 GET an hour per account with a record, 120 without). Residency adds no S3 read beyond a cache miss, and D7 adds one sync per first boot. A refused resident costs no lease cycle. |
| - The wake ceiling: a rootfs wake may run its `release` (Task 11), which has its own timeout up to 6 h. The other steps keep their own bounds; the ceiling exists for wedged steps and must not cut a declared migration short. |
| @@ -637,6 +675,11 @@ func TestRootfsRefusalPrecedesTheLease(t *testing.T) // INV-3. table over eve |
| // called; and each of Plan 2's gate reasons through rootfsStartable (not nested-ready, layout flat, layout fenced, probe not |
| // passed, no probe, placement refused, no placement check, claim switch on, no rootfs control half). Through doWake and |
| // begin: acquires == restores == materialized == 0, no recordBuild, no entry left; ServeHTTP 503. Task 8 adds rootfsTick rows. |
| +func TestRootfsGatesRunOffTheLock(t *testing.T) // [Astra R1 8] rootfsStartable blocks on a channel for host A: a request to |
| + // binary host B and to awake host C completes meanwhile, and Shutdown is not held up by A beyond its ctx; awake host C's |
| + // requests never call rootfsStartable; 20 concurrent cold requests to A call it once |
| +func TestRootfsGatesThroughTheProductionBackend(t *testing.T) // productionBackend over a nestedBackend with RootfsOK failing: a wake |
| + // is refused before Acquire; a unit-backed rootfs row is refused by SplitBackend.rootfsStartable |
| func TestRootfsWakeRefusedUnarmed(t *testing.T) // gens on, ArmRootfs not called: refused, event C12 with C14; after ArmRootfs it wakes |
| func TestBinaryWakeNotGated(t *testing.T) // a binary hibernating row wakes with neither armed |
| func TestUnknownRuntimeNeverWakes(t *testing.T) // Runtime "rootfs-v2", Hibernate true: refused, acquires 0 |
| @@ -666,7 +709,7 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) // Review Focus 8. A web |
| INV-4's table gains `errRootfsUnarmed` and `errRuntimeUnknown`, each marked by `refuseRootfs`. |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsRefusalPrecedesTheLease|TestRootfsWakeRefused|TestBinaryWakeNotGated|TestUnknownRuntimeNeverWakes|TestRootfsWakeCeiling|TestServedRootfsNeverBootsEmpty|TestFirstRootfsWakeMayBootFresh|TestServedRootfsPlacesNoPlaceholder|TestBinaryFreshWakePlacesNothing|TestRootfsPlaceholderFailureStartsNothing|TestPlaceRootfsDB|TestRootfsAppWithoutSQLiteRestarts' -count=1` (the production-wired ones need the short `TMPDIR` of the Global Constraints). Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsRefusalPrecedesTheLease|TestRootfsGatesRunOffTheLock|TestRootfsGatesThroughTheProductionBackend|TestProductionBackendImplementsRootfsSeams|TestRootfsWakeRefused|TestBinaryWakeNotGated|TestUnknownRuntimeNeverWakes|TestRootfsWakeCeiling|TestServedRootfsNeverBootsEmpty|TestFirstRootfsWakeMayBootFresh|TestServedRootfsPlacesNoPlaceholder|TestBinaryFreshWakePlacesNothing|TestRootfsPlaceholderFailureStartsNothing|TestPlaceRootfsDB|TestRootfsAppWithoutSQLiteRestarts' -count=1` (the production-wired ones need the short `TMPDIR` of the Global Constraints). Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C12`, `C14` and `C15` from the deck and add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's command, Task 1's guards, the restore and seed families the new step sits beside (`go test ./internal/activator/ -run 'Restore|Seed|Fresh' -count=1`), and `go test ./internal/host/ -run 'TestRollout' -count=1`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -716,10 +759,11 @@ git commit -m "activator: rootfs rows refused before the lease unless overlap sw |
| 1. Off `a.mu`: `routes, err := lister.ResidentInstances()`. An error logs and ends the tick. It is never read as "no residents": nothing is stopped and nothing forgotten (incomplete discovery is not retirement). |
| 2. Under `a.mu`, return if `a.shuttingDown`. For every awake rootfs entry (resident or not) whose `e.proc.Exited()`: `e.unexpectedExit = true; a.beginStopLocked(e, StopExited)`, the sweep's own crash arm (`:4614`), so a crash is seen within 2 s rather than the sweep's 30. Then `a.superviseRootfsLocked(e)` for every awake rootfs entry: one hook, a no-op until W1 [pf 6.1]. |
| -3. Forget `a.residents[host]` for hosts no longer listed. For each listed route, in host order, skip when: `a.fences[host] != 0`; any live entry; `a.unprovenWakes[host]` or `a.straySidecars[host]` (the uncertainty latches); `st.starting`; `a.now().Before(st.retryAt)`; `a.residentStarting >= residentStartCeiling` (stop the loop). `rootfsStartRefusal(rt) != nil` sets `st.refused` and skips, counting no failure, with one log line per change of `st.refused` and, for unarmed, one `RFS-3-C12` event (fragment `RFS-3-C14`) per change [pf 2.1]. Otherwise make `e := &actEntry{host, route: rt, state: actWaking, ready: make(chan struct{}), resident: true}`, publish it, set `st.starting`, `a.residentStarting++`, and `go a.wake(e)`. |
| +3. Forget `a.residents[host]` for hosts no longer listed. For each listed route, in host order, skip when: `a.fences[host] != 0`; any live entry; `a.unprovenWakes[host]`, `a.straySidecars[host]` or `a.releaseRuns[host]` (the uncertainty latches; the last is Task 10's, and until then absent); `st.starting`; `a.now().Before(st.retryAt)`; `a.residentStarting >= residentStartCeiling` (stop the loop). A route that passes every skip is a candidate. Candidates are collected under `a.mu`, and the lock is dropped to ask `rootfsStartRefusal(ctx, rt)` for each (off `a.mu`, Astra R1 8); then, under `a.mu` again, every skip is re-checked before anything starts. A refusal sets `st.refused` and skips, counting no failure, with one log line per change of `st.refused` and, for unarmed, one `RFS-3-C12` event (fragment `RFS-3-C14`) per change [pf 2.1]. Otherwise make `e := &actEntry{host, route: rt, state: actWaking, ready: make(chan struct{}), resident: true}`, publish it, set `st.starting`, `a.residentStarting++`, and `go a.wake(e)`. |
| Outcome and stop accounting, both under `a.mu`: |
| -- `noteResidentWakeLocked` (in `wake`'s final critical section, for any wake of a resident row, proactive or by request): a proactive wake clears `starting` and decrements `residentStarting`. A failed wake counts a failure unless the error is `ErrFenced`, `errShuttingDown` or marked `errRootfsRefused` (INV-4): `failures++`, `retryAt = now + residentBackoff(failures, jitter())`. |
| +- `noteResidentWakeLocked` (in `wake`'s final critical section, for any wake of a resident row, proactive or by request): a proactive wake clears `starting` and decrements `residentStarting`. A failed wake counts a failure only when `residentFailure(err)`: `failures++`, `retryAt = now + residentBackoff(failures, jitter())`. Otherwise `retryAt = now` and nothing is counted [Astra R1 11]. |
| +- `residentFailure(err error) bool` is false for every ownership end and refusal, the INV-4 set: `ErrFenced`, `errShuttingDown`, `context.Canceled`, anything `verdictOf` answers gateNoOwnership or superseded for (so `errRootfsRefused`, `errSwapLeaseLost` and with it the release's lease loss), `errSwapBusy`, `errReleaseUnproven` and `errWakeUnproven` (both latch the host until their record is proven, Task 10, so a backoff would only add to it). It is true for the build's own failures (`*ReleaseError`, a health failure, a crash at start) and for anything unclassified, such as an `Acquire` that fails on a store outage, which must back off rather than retry every 2 s. Tasks 10 and 11 define the sentinels it names; until then it names those that exist. |
| - `noteResidentStopLocked` (in `finishStop`, as the entry is forgotten): when `e.stopWhy` is `StopExited` or `StopLeaseLost` it is a failure: if `now.Sub(e.spawnedAt) >= residentHealthyRun` reset `failures` to 0 first; then `failures++`, `restarts++`, `retryAt` as above, and the member event `RFS-3-C11` with the delay. Any other reason (a release cycle, a bounce, retirement, a fence, shutdown) sets `retryAt = now` and counts nothing: a resident is back on the next tick after an adoption or a `carlos restart`. |
| Requests: `begin`, before it makes an entry for a resident row, answers `&errResidentBackoff{retryAfter}` while `now < st.retryAt`. `serveWakeError` answers it 503 with `Retry-After` (whole seconds, rounded up) and the body `RFS-3-C16`. A request that finds a waking entry coalesces on it as today, so a request and the tick never make two wakes. |
| @@ -748,6 +792,10 @@ func TestResidentListingFailureStopsNothing(t *testing.T) // lister errors for 2 |
| func TestResidentReplicationIsTheActivators(t *testing.T) // the awake resident's rep is the fakeLease's Replicate result |
| func TestResidentRefusalCountsNoFailure(t *testing.T) // rootfsStartable refusing for 20 ticks: failures == 0, acquires == 0, |
| // one log line; after it clears, the next tick starts the resident with no backoff |
| +func TestResidentFailureClassification(t *testing.T) // [Astra R1 11] table over residentFailure: each INV-4 case false (a refusal, |
| + // errSwapLeaseLost wrapping errReleaseLeaseLost, errSwapBusy, errReleaseUnproven, errWakeUnproven, ErrFenced, shutdown); |
| + // *ReleaseError, a health failure and an Acquire store error true; and through the tick: a wake failing with each false case |
| + // leaves failures == 0 |
| func TestResidentRequestAndTickRaceOneWake(t *testing.T) // RACE: 50 goroutines ServeHTTP a cold resident while the tick runs every |
| // 1 ms; fb.acquires == 1 and fb.starts == 1. Run with -race. |
| func TestResidentCrashDuringStopIsOneStop(t *testing.T) // RACE: proc exits while a Bounce stops the entry: one stop, one restart |
| @@ -773,7 +821,9 @@ git commit -m "activator: always-on rootfs instances: boot start, crash restart |
| **Files:** |
| - Create: `internal/activator/rootfsrelease.go`, `internal/activator/rootfsrelease_test.go`, `internal/activator/rootfs_ctl_harness_test.go`, `internal/activator/backend_rootfs.go` (this task's half: `Processes`, `stagedImageOf`, `StartRelease`, `ReleaseEnv`) |
| -- Modify: `internal/activator/cmdunit.go` (`StartCmd`'s body, `:172`, becomes `startCmdUnit`, shared; it builds Plan 2's runtime-aware `cmdUnit` for both runtimes, A8), `internal/activator/cmd.go:301` (`cmdHoldsLocked` includes `e.releaseHold`), `internal/activator/activator.go` (`actEntry.releaseHold *cmdHold`) |
| +- Modify: `internal/activator/cmdunit.go` (`StartCmd`'s body, `:172`, becomes `startCmdUnit`, shared; it builds Plan 2's runtime-aware `cmdUnit` for both runtimes, A8) |
| +- Modify: the consumers of the one release record (INV-7, the table below): `internal/activator/cmd.go` (`RunCmd`'s admission beside `cmdBusyLocked`, `:284`), `internal/activator/activator.go` (the idle arm, `:4709`; the max-run arm, `:4743`; `beginStopLocked`, `:2687`; doWake's wake latch, `:2183`; the sweep calls `reapReleaseRunsLocked`), `internal/activator/opset.go` (`releasable`, `:681`), `internal/activator/maintenance.go` (`cleanupFailedWake`, `:360`), `internal/activator/generations_file.go` (the snapshot lists every record's build), `internal/activator/rootfs_service.go` (the tick skips a host with a record) |
| +- Modify: `internal/activator/backend_unit.go`: `SplitBackend.Processes`, `ReleaseEnv`, `StartRelease`, forwarding to `b.Exec` for an exec-backed row and refusing a unit-backed one (`refuseRootfs(errNoRootfsControl)`) [Astra R1 4]; `production_backend_test.go` gains the `ReleaseBackend` row |
| - Modify: `internal/activator/backend_exec.go:787` (`execLease.SafeUntil`, `execLease.Lost`, beside `Err`) |
| - Modify: `internal/rolloutwords/words.go` (events), `internal/status/snapshot.go:410` (reason words, beside `ReasonHealth`) |
| - Modify: `internal/activator/rootfs_invariants_test.go` (INV-1, INV-4 and INV-5 rows) |
| @@ -783,8 +833,11 @@ git commit -m "activator: always-on rootfs instances: boot start, crash restart |
| - Produces: |
| ```go |
| type ReleaseBackend interface { |
| - // Processes reads the root-written staged manifest of id for rt's account and app [pf 1.9]. It refuses unless |
| - // m.IsRootfs() and m.BoxArtifact(platform).SHA256 == id.Digest: a manifest read must belong to the image it names. |
| + // Processes reads the root-written staged manifest of id for rt's account and app [pf 1.9], with root's own check |
| + // (instancectl/rootfs.go:226-231): ReadStagedManifest(optDir, RouteAccount(rt), id.Version, rt.App); its documented |
| + // (nil, nil) for an absent sibling (versions.go:236-240, :267-269) is a refusal, never "no processes"; !m.IsRootfs() |
| + // refuses; art, ok := m.BoxArtifact(platform) with !ok refuses; !strings.EqualFold(art.SHA256, id.Digest) refuses. |
| + // An id with no Digest refuses before any read [Astra R1 3]. |
| Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error) |
| ReleaseEnv(rt registry.Route) (map[string]string, error) // the delivered files a successor would launch with, composed by rootfsCmdVars |
| // StartRelease runs runPendingRecord(ctx) and runExecGate(ctx) immediately before CmdRootfs; a refusal there is |
| @@ -820,6 +873,21 @@ git commit -m "activator: always-on rootfs instances: boot start, crash restart |
| var errReleaseNoLease = errors.New("activator: the lease a release would run under cannot report its safety deadline") |
| var errReleaseLeaseLost = errors.New("activator: the instance's lease ended while its release command ran") |
| // returned as fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost): an ownership end (gateNoOwnership), never the build's failure |
| + // releaseRun is the one owner of a running release (INV-7), from admission until its unit is proven gone, whatever |
| + // happens to the entry, wake or swap that started it [Astra R1 5, 6]. Service.releaseRuns map[string]*releaseRun, by host. |
| + type releaseRun struct { |
| + build release.StagedIdentity // full identity (stagedIdentityOf); pinned in the generations file while the record lives |
| + hold *cmdHold // the cmd unit's stop and settle; one attempt at a time (busy) |
| + cancel context.CancelCauseFunc |
| + owner *actEntry // the entry whose wake or swap started it; nil once that entry is gone |
| + owed Lease // a failed wake's lease, kept here while the unit is unproven; given back after the proof |
| + retryAt time.Time |
| + busy bool // runRelease is settling it, or the reaper is |
| + } |
| + var errReleaseRunOpen = errors.New("activator: a release command of this instance is still running or not proven stopped") |
| + func (a *Service) reapReleaseRunsLocked() // the sweep's one retry path: each record with no owner, or an owner whose stop |
| + // waits on it, not busy and past retryAt, gets one settle off a.mu (actStopTimeout); proven: the record goes, its owed |
| + // lease is given back (or a.oweRelease), the generations file is rewritten |
| func (a *Service) runRelease(ctx context.Context, e *actEntry, rt registry.Route, id release.StagedIdentity, held leaseWatch, gate func() error) error |
| // nil when not due; *ReleaseError; errReleaseUnproven; errReleaseNoLease; the gate's own refusal; a Processes refusal; |
| // root's pre-start refusal; the lease-loss error above; ctx's own error when ctx ended; errSwapBusy when a run holds the cmd unit |
| @@ -846,16 +914,32 @@ own := func() error { |
| `runRelease`, in order: |
| 1. `procs, err := Processes(rt, id)`. Any error is a refusal to start, marked with `refuseRootfs`, never "no release process, not due": nothing starts, `web` included [pf 1.9]. Not due: return nil. `held == nil`: `errReleaseNoLease`, nothing started (a caller whose `Lease` or `Rep` is not a `leaseWatch` passes nil). |
| -2. `own()`; a refusal returns it and starts nothing. Under `a.mu`: refuse with `errSwapBusy` when `cmdBusyLocked(e)` (a member's run holds the host's one cmd unit); else attach `e.releaseHold = newCmdHold("release", cancel, a.now)` with `starting` set, so every stop path settles it before replication closes (`settleCmds`, `cmd.go:415`, through `cmdHoldsLocked`) and `RunCmd` starts nothing beside it. |
| +2. `own()`; a refusal returns it and starts nothing. Under `a.mu`: refuse with `errSwapBusy` when `cmdBusyLocked(e)` (a member's run holds the host's one cmd unit), and with `errReleaseRunOpen` when `a.releaseRuns[rt.Host]` exists in any state (so no release ever overwrites another's record); else create the record (`build: id`, `hold: newCmdHold("release", cancel, a.now)` with `starting` set, `owner: e`, `busy: true`). Then, off `a.mu`, `a.publishBeforeExec()`: the record's build is now in the generations file before anything runs, and a failed write removes the record and returns `errStagedBuildNotPublished` (abandonment, never the build's failure) [Astra R1 9]. |
| 3. `recordBuild(ctx, rt.Host, id.Version)`: the build state names the release's build before it touches the data (settings §4.2). `StartRelease` then runs `runPendingRecord(ctx)` and `runExecGate(ctx)` immediately before `CmdRootfs`, as the exec seam does, so a cold wake's pending record is written before `release` runs, not at `web`'s exec, and ownership is checked at the last moment before root is asked. (No egress step: #328 checks on root's side, in `startRootfsCmd` [pf 2.5].) |
| 4. Event `RFS-3-C03`. `rctx, trip := context.WithCancelCause(ctx)` with `releaseTimeout(procs[release.ProcessRelease])` over it. |
| -5. `StartRelease(withExecGate(rctx, own), rt, id, ReleaseEnv(rt), out)`: `startCmdUnit` with Plan 2's `writeRootfsLaunchFor(p, RoleCmd, 0, rt.Host, release.ProcessRelease, rootfsLaunchEnv(env))` (A3: schema 2, no argv, nothing of the agent's environment [pf 1.6]) and `RootfsControl.CmdRootfs(ctx, host, b.tier(rt).MemoryMax, stagedImageOf(id, release.ProcessRelease, nil))` (A5, the sized tier [pf 1.8]). An `ErrStagedImage` or `ErrStartRefused` answer is marked with `refuseRootfs`: root refused before anything ran, so it is a refusal, never the build's failure (INV-4) [pf 1.7]. The unit it returns, with or without an error, is Plan 2's runtime-aware `cmdUnit` (A8): it polls `RootfsUnitName(RoleCmd, host)` and stops and proves that unit, never the binary `carlos-instance-cmd@`. `out` is a line writer into the app log sink (`b.logEmitter(rt)`, `prepare.go:259`), both streams, at most `runs.MaxOutputBytes`, after which lines are dropped and one diagnostic logged. A `launchRefused` start returns the gate's error with the hold detached: nothing ran. |
| +5. `StartRelease(withExecGate(rctx, own), rt, id, ReleaseEnv(rt), out)`: `startCmdUnit` with Plan 2's `writeRootfsLaunchFor(p, RoleCmd, 0, rt.Host, release.ProcessRelease, rootfsLaunchEnv(env))` (A3: schema 2, no argv, nothing of the agent's environment [pf 1.6]) and `RootfsControl.CmdRootfs(ctx, host, b.tier(rt).MemoryMax, stagedImageOf(id, release.ProcessRelease, nil))` (A5, the sized tier [pf 1.8]). An `ErrStagedImage` or `ErrStartRefused` answer is marked with `refuseRootfs`: root refused before anything ran, so it is a refusal, never the build's failure (INV-4) [pf 1.7]. The unit it returns, with or without an error, is Plan 2's runtime-aware `cmdUnit` (A8): it polls `RootfsUnitName(RoleCmd, host)` and stops and proves that unit, never the binary `carlos-instance-cmd@`. `out` is a line writer into the app log sink (`b.logEmitter(rt)`, `prepare.go:259`), both streams, at most `runs.MaxOutputBytes`, after which lines are dropped and one diagnostic logged. A `launchRefused` start returns the gate's error with the record removed: nothing ran. |
| 6. **Lease supervision**, from the moment the unit may run until it is proven gone: a goroutine re-reads `held.SafeUntil()` every `releaseLeaseRecheck` and wakes at once on `held.Lost()`. It trips (`trip(errReleaseLeaseLost)`) when `Lost()` closes, when `SafeUntil` errors, or when `time.Until(until) <= releaseStopLead`, keeping the last `until` it read as the deadline. It uses the real clock, as the lease does (`SafeUntil` is monotonic), not `a.now`. |
| -7. Poll (`unit.Poll`, the 30 s long-poll) until done or `rctx` ends. Then stop and settle whatever happened, through `e.releaseHold.stop` (so a stop path settling the same hold joins one attempt), with the reason `StopLeaseLost` after a trip. After a trip the settle is retried until it is proven or the deadline from step 6 passes; otherwise it is bounded by `cmdStopBound`. A failed settle is `errReleaseUnproven` (wrapped with `errSwapLeaseLost` after a trip), and the hold stays attached so the entry's next stop retries it (INV-2). |
| +7. Poll (`unit.Poll`, the 30 s long-poll) until done or `rctx` ends. Then stop and settle whatever happened, through the record's `hold.stop`, with the reason `StopLeaseLost` after a trip. After a trip the settle is retried until it is proven or the deadline from step 6 passes; otherwise it is bounded by `cmdStopBound`. A failed settle is `errReleaseUnproven` (wrapped with `errSwapLeaseLost` after a trip); the record stays, `busy` is cleared and `retryAt` set, and from then on the sweep's `reapReleaseRunsLocked` is its only retrier (INV-2, INV-7). |
| 8. Results, in this order: a trip is the lease-loss error, whatever the unit's exit (a release that exited 0 on a box that no longer holds the lease is not success), with event `RFS-3-C29` once the unit is proven gone, and never a `ReleaseError`; `ctx` itself ended (a fence, a stop, shutdown): `ctx.Err()`, no event, never a build failure; exit 0: event `RFS-3-C04`, nil; non-zero, a signal, or the timeout: `*ReleaseError` and its event. |
| -9. Detach the hold once settled; stop the supervisor. |
| +9. Once proven: remove the record under `a.mu`, rewrite the generations file off it, stop the supervisor. |
| + |
| +The callers (Task 11) treat the lease-loss error as they treat `errSwapLeaseLost` today: an overlap abandons (`classifyStep`, `swap.go:134`, through `verdictOf`, `:234`); a wake fails and gives the lease back only when the record is gone (the unit proven), and otherwise hands its lease to the record (`owed`) before its entry is deleted (Task 11). |
| -The callers (Task 11) treat the lease-loss error as they treat `errSwapLeaseLost` today: an overlap abandons (`classifyStep`, `swap.go:134`, through `verdictOf`, `:234`); a wake fails and gives the lease back only when the unit was proven gone, and otherwise leaves it to its TTL (`w.stopOutcome.uncertain`, as `ErrSeedUnproven` does, `activator.go:2313`). |
| +**Who reads the record (INV-7).** Every consumer of "is a release running or unproven for this host" reads `a.releaseRuns[host]`, never an entry field, so an entry's deletion cannot drop the obligation [Astra R1 5, 6]: |
| + |
| +| consumer | main's code | with a record for the host | |
| +|---|---|---| |
| +| a member's run | `RunCmd`'s admission, beside `cmdBusyLocked` (`cmd.go:284`) | refused as busy (the run's existing busy answer); no run beside a release | |
| +| another release | `runRelease` step 2 | `errReleaseRunOpen` | |
| +| idle sleep | the sweep's idle arm, `e.cmd == nil` (`activator.go:4709`) | the owner entry is never idle-stopped, so a hibernating incumbent keeps serving through an overlap migration (C8) | |
| +| max-run recycle | `e.workerMaxRun` arm (`activator.go:4743`) | applies only to sidecar entries (`e.worker`), never a rootfs owner; unchanged, and `TestReleaseRunConsumersReadTheRecord` pins that it never fires for one | |
| +| a stop of the owner | `beginStopLocked` (`:2687`) | cancels the record (`cancel(cause)`), so `runRelease` settles it at once; `releasable(e)` (`opset.go:681`) is false until the record is gone, so replication and the lease are held | |
| +| a wake of the host | doWake's latch (`activator.go:2183`), the tick's skip | refused with `errWakeUnproven` while the record exists and its owner is not this wake | |
| +| the failed wake's cleanup | `cleanupFailedWake` (`maintenance.go:360`), then the entry's deletion (`activator.go:1860`) | the wake's lease moves to `owed` (never released, never left to TTL alone), `owner = nil`; the record outlives the entry | |
| +| pins | `entryGenerationsLocked` and the snapshot | every record's `build` is listed, whatever its owner; published before the release execs (step 2) | |
| +| retries | `retryCmdSettlesLocked` (`cmd.go:399`) is a run's | untouched; a release's one retry path is `reapReleaseRunsLocked` | |
| + |
| +`settleCmds` and `cmdHoldsLocked` (a member's runs) are unchanged: a release is not a run and does not sit in `e.cmd` or `e.cmdLeft`. |
| - [ ] **Step 1: Write the failing tests.** The backend half goes through the real control handler, not a scripted fake (Astra R1 finding 1): `rootfsCtlHarness` in `rootfs_ctl_harness_test.go` serves a real `instancectl.Server` (`Handler()`, `internal/instancectl/server.go:380`) on a unix socket under the short `TMPDIR`, with `PeerOK` returning nil; `Systemctl` a fake keyed by unit name (each unit's `show` answer, and `start`/`stop` recorded in order and changing that unit's state); `CgroupRoot` a fixture tree whose `cgroup.events` per unit the test sets; `OptDir` with build B staged at `release.VersionPath` and its root-written staged manifest (Plan 2's rootfs server fixture shape); `HostApp` answering the row's account and app; `ExeRoot` and `DropInDir` under `t.TempDir()`; a switch that makes the handler answer `/cmd` with a chosen pre-start status. The `ExecBackend` is `nestedBackend` with `Control: instancectl.NewClient(sock)` and `CgroupEvents` reading the same fixture tree. The binary `carlos-instance-cmd@<host>.service` exists in no answer: `show` reports it with no invocation and inactive, and its cgroup is absent, so a test passes only if every poll, stop and proof names the rootfs unit. The Service half uses `fakeBackend` implementing `ReleaseBackend`, with `fakeLease` and `fakeRep` implementing `leaseWatch` (a `lost` channel the test closes, an `until` the test sets or advances). |
| @@ -877,24 +961,37 @@ func TestReleaseStopProvesTheRootfsCmdUnitGone(t *testing.T) // StopAndSettle: t |
| // and no "stop carlos-instance-cmd@"; with the rootfs unit's cgroup.events "populated 1" the settle fails although the binary |
| // unit's cgroup is absent; after "populated 0" the next attempt proves it |
| func TestReleaseRefusedByRootIsNotABuildFailure(t *testing.T) // [pf 1.7] the handler answers /cmd 503, then 403: each is marked |
| - // errRootfsRefused, no ReleaseError, no C05..C07 event, the hold detached, nothing started |
| + // errRootfsRefused, no ReleaseError, no C05..C07 event, the record removed, nothing started |
| func TestReleaseExitNonZero(t *testing.T) // the rootfs unit exits with status 3: *ReleaseError{Exit: 3}; event C05; |
| // one stop of the rootfs unit |
| func TestReleaseTimesOut(t *testing.T) // the rootfs unit stays running past a shrunk timeout: TimedOut, stop sent to |
| // the rootfs unit and its cgroup proven empty, event C07 |
| -func TestReleaseUnprovenKeepsTheHold(t *testing.T) // the rootfs unit's cgroup stays populated: errReleaseUnproven; e.releaseHold still set |
| +func TestReleaseUnprovenKeepsTheRecord(t *testing.T) // the rootfs unit's cgroup stays populated: errReleaseUnproven; a.releaseRuns[host] |
| + // still set, its build in the persisted generations file; the next sweep's reaper proves it once the group empties, then |
| + // the record and the pin go |
| func TestReleaseExecGateRefusesAtTheLastMoment(t *testing.T) // the gate flips to refusing after step 2: launchRefused, no /cmd request |
| - // in the log, the hold detached, the gate's error returned |
| + // in the log, the record removed, the gate's error returned |
| func TestReleaseOutputReachesTheAppLog(t *testing.T) // lines the unit writes to both streams reach the fake EventSink's App lines; |
| // past the cap they stop |
| // Service half, fakeBackend |
| +func TestProcessesRefusesAPartialOrAbsentManifest(t *testing.T) // [Astra R1 3] no sibling (ReadStagedManifest nil, nil), no box artifact, |
| + // an id with no Digest: each refused, nothing started |
| +func TestReleaseRunConsumersReadTheRecord(t *testing.T) // INV-7. with a record for the host: RunCmd refused; a second runRelease |
| + // errReleaseRunOpen; sweepOnce past the idle window does not stop the owner (a hibernating incumbent); a Bounce stop stays |
| + // pending (releasable false) with rep open; a ServeHTTP to the cold host and a resident tick both refused errWakeUnproven |
| + // once the owner is gone; the persisted generations file lists the build. Remove the record (proven): each consumer |
| + // proceeds |
| +func TestReleaseBuildPublishedBeforeExec(t *testing.T) // [Astra R1 9] the generations file on disk names the release's build before |
| + // the /cmd request; a failed write: errStagedBuildNotPublished, no /cmd request, no record left |
| +func TestReleaseThroughTheProductionBackend(t *testing.T) // [Astra R1 4] productionBackend over the rootfsCtlHarness ExecBackend: the |
| + // service's type assertion finds ReleaseBackend and the release runs in the rootfs cmd unit; a unit-backed row is refused |
| func TestReleaseRefusedWhenTheManifestIsNotTheImage(t *testing.T) // [pf 1.9] Processes errors: errRootfsRefused, StartRelease never |
| // called; through doWake, web is not started either |
| func TestReleaseRefusedWhileARunHoldsTheUnit(t *testing.T) // e.cmd set: errSwapBusy, StartRelease never called |
| func TestReleaseGatedOnOwnership(t *testing.T) // table, StartRelease never called in each: the site gate refuses (entry |
| // superseded, fence raised, shutdown); held.Err set; SafeUntil less than releaseStopLead ahead: errors.Is(err, errSwapLeaseLost); no event |
| func TestReleaseNeedsAWatchableLease(t *testing.T) // held nil: errReleaseNoLease, nothing started |
| -func TestReleaseStopsOnLostLease(t *testing.T) // close fakeLease.lost while the release polls: the hold's stop runs with |
| +func TestReleaseStopsOnLostLease(t *testing.T) // close fakeLease.lost while the release polls: the record's stop runs with |
| // StopLeaseLost and is proven before until; errors.Is(err, errSwapLeaseLost) and errors.Is(err, errReleaseLeaseLost); no |
| // ReleaseError; event C29 after the proof |
| func TestReleaseStopsBeforeTheSafetyDeadline(t *testing.T) // renewals stall: lost never closes, until frozen at now+lead+300ms, with |
| @@ -902,7 +999,7 @@ func TestReleaseStopsBeforeTheSafetyDeadline(t *testing.T) // renewals stall: lo |
| func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) // until advanced by 1 s every 20 ms (lead 200 ms): the release runs to |
| // exit 0 unstopped, event C04, nil |
| func TestReleaseLeaseLossUnprovenLeavesTheHold(t *testing.T) // lost closes, every settle fails until past until: errReleaseUnproven and |
| - // errSwapLeaseLost both match; the hold stays attached; no C29 |
| + // errSwapLeaseLost both match; the record stays (owned by the reaper); no C29 |
| func TestReleaseLeaseLossRacesExit(t *testing.T) // RACE: lost closes as the unit reports done with status 0: one settle, |
| // the result is the lease-loss error, never nil. Run with -race. |
| func TestStopSettlesARunningRelease(t *testing.T) // RACE: Bounce while the release polls: the release unit is stopped and settled |
| @@ -911,7 +1008,7 @@ func TestStopSettlesARunningRelease(t *testing.T) // RACE: Bounce while t |
| The invariant tables gain this task's rows: INV-1, the release `cmdUnit` (Stop and Poll through the harness, no binary unit, populated reported group: unproven); INV-4, `errSwapBusy` and the lease-loss error; INV-5, the release launch file under `t.Setenv("PATH", "/agent/bin")`. |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestReleaseDue|TestReleaseTimeout|TestProcessesBelong|TestRelease|TestStopSettlesARunningRelease|TestEveryRootfsProof|TestRootfsRefusalsAreNot|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestReleaseDue|TestReleaseTimeout|TestProcessesBelong|TestProcessesRefuses|TestRelease|TestStopSettlesARunningRelease|TestProductionBackend|TestEveryRootfsProof|TestRootfsRefusalsAreNot|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C03` to `C07` and `RFS-3-C29`, add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's command, `go test -race ./internal/activator/ -run 'TestStopSettlesARunningRelease|TestReleaseLeaseLossRacesExit|TestReleaseStopsOnLostLease' -count=3`, the cmd families (`-run 'Cmd|RunCmd'`), which the `startCmdUnit` refactor touches, and Task 1's guards and goldens (`TestBinaryStartCmdLaunchGolden` must stay byte-identical). Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -943,7 +1040,7 @@ The worker handover of the first draft's step 8, `TestOverlapHandsOverWorkersNev |
| ```go |
| // SwapResult.Reason for a release failure: "release: " + err.Error(), or "release timed out: " + err.Error() |
| func (a *Service) rootfsWorkersHook(ctx context.Context, e *actEntry, rt registry.Route, g Gen) |
| - // group A: when Processes(rt, genIdentity of g) declares workers, log once per wake or swap |
| + // group A: when Processes(rt, stagedIdentityOf(g)) declares workers, log once per wake or swap |
| // "activator: %s: build %s declares workers (%s); this box does not run workers yet" (a diagnostic, D8). W1 and W2 fill it. |
| ``` |
| @@ -951,14 +1048,14 @@ Where `release` runs, under which lease and gate, and what its failure means: |
| | path | where | lease (`held`) and `gate` | failure | |
| |---|---|---|---| |
| -| overlap swap (awake row, a new build) | `swapOverlap`, after the member is registered, the build published and step 3a's checks passed, before step 3's spawn: `a.runRelease(mctx, e, rt, a.genIdentity(m.gen), watchOf(e.rep), gate)` | the incumbent's replica `e.rep` (a `*lease.Replicator`); the attempt gate the successor's spawn passes | `dropMember`; a cancelled or stale error, a refusal (`errRootfsRefused`), and the lease-loss error, abandon through `classifyStep` (`errSwapLeaseLost` is already in `verdictOf`, `swap.go:234`); otherwise `failSwap` (`swap.go:114`) with the reason above and `Executed` true. The incumbent was never touched (C8). `errSwapBusy` abandons, and the scheduler retries after its deferral | |
| -| hold swap | `startPinnedChecked`, after its gate, before `startPinnedAt` | the wake's `lease`; its `gate` | the old build is already stopped; `markPinExec(e)` (`swaphold.go:378`) when the release ran, so the hold reports down, as a hold build that ran and failed does today. The lease-loss error and a refusal are the gate's NoOwnership refusal, as `leaseLost(lease)` there already is | |
| -| planned wake (asleep row, or a resident's restart, scheduler choosing B) | `spawnPlanned`, after `checkPlan` and before `healthBy` is computed, on `plan.Boot`; `healthBy` is then measured from the release's end, and the verdict floor uses `healthBoundFor(rt)` (N1) | the wake's `lease`; `planGate(ctx, e, lease, plan, plan.Boot.Version)` | treated as B failing at its start: `executed` and `crashed` include `*ReleaseError`, so a first wake with a fallback boots the good build and records B's failure (`w.failed`, `w.fellBack`). The lease-loss error and a refusal are not B's failure: they are gateNoOwnership like every `planGate` refusal, nothing more is started, and no fallback runs | |
| +| overlap swap (awake row, a new build) | `swapOverlap`, after the member is registered, the build published and step 3a's checks passed, before step 3's spawn: `id, err := stagedIdentityOf(m.gen)` (N1; a refusal abandons) then `a.runRelease(mctx, e, rt, id, watchOf(e.rep), gate)`. Never `genIdentity`, which answers two values and no digest (`generations_file.go:220`) [Astra R1 3] | the incumbent's replica `e.rep` (a `*lease.Replicator`); the attempt gate the successor's spawn passes | `dropMember`; a cancelled or stale error, a refusal (`errRootfsRefused`), and the lease-loss error, abandon through `classifyStep` (`errSwapLeaseLost` is already in `verdictOf`, `swap.go:234`); otherwise `failSwap` (`swap.go:114`) with the reason above and `Executed` true. The incumbent was never touched (C8). `errSwapBusy` abandons, and the scheduler retries after its deferral | |
| +| hold swap | `startPinnedChecked`, after its gate, before `startPinnedAt`, on `stagedIdentityOf(pin)` | the wake's `lease`; its `gate` | the old build is already stopped; `markPinExec(e)` (`swaphold.go:378`) when the release ran, so the hold reports down, as a hold build that ran and failed does today. The lease-loss error and a refusal are the gate's NoOwnership refusal, as `leaseLost(lease)` there already is | |
| +| planned wake (asleep row, or a resident's restart, scheduler choosing B) | `spawnPlanned`, after `checkPlan` and before `healthBy` is computed, on `plan.Boot`, already a full `StagedIdentity` with its digest (`wakeplan.go:25`); `healthBy` is then measured from the release's end, and the verdict floor uses `healthBoundFor(rt)` (N1) | the wake's `lease`; `planGate(ctx, e, lease, plan, plan.Boot.Version)` | treated as B failing at its start: `executed` and `crashed` include `*ReleaseError`, so a first wake with a fallback boots the good build and records B's failure (`w.failed`, `w.fellBack`). The lease-loss error and a refusal are not B's failure: they are gateNoOwnership like every `planGate` refusal, nothing more is started, and no fallback runs | |
| | other wakes with a pinned identity | `doWake`, right before the `ib != nil` branch, on `id` | the wake's `lease`; `leaseLost(lease)` then `a.wakeOwned(ctx, e)` | the wake fails with the error | |
| -`watchOf(x any) leaseWatch` is `x.(leaseWatch)` or nil (and `runRelease` then refuses with `errReleaseNoLease`); the cold-wake sites pass `watchOf(lease)`. On a cold wake the entry is `actWaking`, which the sweep's lease check never visits (it runs for awake entries, `activator.go:4606`), so Task 10's supervisor is the only thing watching the lease while the migration runs; in a swap the sweep also sees a lost `e.rep` and begins a `StopLeaseLost` stop, whose `settleCmds` joins the same hold's settle. |
| +`watchOf(x any) leaseWatch` is `x.(leaseWatch)` or nil (and `runRelease` then refuses with `errReleaseNoLease`); the cold-wake sites pass `watchOf(lease)`. On a cold wake the entry is `actWaking`, which the sweep's lease check never visits (it runs for awake entries, `activator.go:4606`), so Task 10's supervisor is the only thing watching the lease while the migration runs; in a swap the sweep also sees a lost `e.rep` and begins a `StopLeaseLost` stop, which cancels the record (`beginStopLocked`) and waits for it (`releasable`); the settle stays `runRelease`'s, then the reaper's, never a second attempt beside it (INV-7). |
| -In `doWake`'s start-error switch, `errReleaseUnproven` (with or without the lease-loss error) leaves the lease to its TTL (as `ErrSeedUnproven` does, `activator.go:2313`): the unit may still write the database. The lease-loss error with the unit proven gone gives the lease back (`giveBack`, which a lost lease answers harmlessly) and starts nothing after it: no `web`, no fallback. Restart and config attempts re-run the serving build, which is the good build, so `releaseDue` is false (D3). A rootfs row is never seeded (D5), so on a first boot `release` runs after the restore and the placeholder (Task 7) and before `web`. A release stopped by lease loss leaves `GoodVersion` unchanged, so the next attempt, on whichever box then holds the lease, runs it again. |
| +In `doWake`'s start-error switch, `errReleaseUnproven` (with or without the lease-loss error) means the unit may still write the database. Leaving the lease to its TTL is not enough [Astra R1 5]: `wake()` deletes the failed entry (`activator.go:1860`), `unprovenWake` (`opset.go:741`) carries generation and legacy-run evidence but no command hold, and nothing would block the next wake or retry the proof. So the obligation is already the record's (Task 10): `cleanupFailedWake` (`maintenance.go:360`) finds `a.releaseRuns[host]` owned by this wake, moves the wake's lease into its `owed` field instead of giving it back or closing it, and clears `owner`; the entry then goes as today, and the record keeps the pin, the wake latch and the lease until the reaper proves the unit and gives the lease back. The lease-loss error with the unit proven gone gives the lease back (`giveBack`, which a lost lease answers harmlessly) and starts nothing after it: no `web`, no fallback. Restart and config attempts re-run the serving build, which is the good build, so `releaseDue` is false (D3). A rootfs row is never seeded (D5), so on a first boot `release` runs after the restore and the placeholder (Task 7) and before `web`. A release stopped by lease loss leaves `GoodVersion` unchanged, so the next attempt, on whichever box then holds the lease, runs it again. |
| `reasonWord` answers `status.ReasonReleaseTimeout` for a reason starting `release timed out` and `status.ReasonRelease` for one starting `release`, before its other arms (`exited` would otherwise match `ReasonExit`). `rolloutwords.Reason` renders them as `RFS-3-C01` and `C02`, so the existing `swap.failed` event and the REASON column say why without new code. |
| @@ -990,14 +1087,24 @@ func TestColdWakeReleaseStopsOnLeaseLoss(t *testing.T) // Review Focus 6. |
| func TestColdWakeReleaseStallsBeforeTheDeadline(t *testing.T) // same row, renewals stall (until frozen, lost never closes, shrunk lead): |
| // stopped and proven before until; same outcome |
| func TestColdWakeReleaseLeaseLossUnprovenKeepsTheLease(t *testing.T) // the settle never proves: the wake fails, the lease is not |
| - // released (w.stopOutcome.uncertain), the hold stays on the entry for the next stop |
| + // released: it is the record's owed lease; the entry is deleted and the record is not |
| func TestSwapReleaseStopsOnLeaseLoss(t *testing.T) // Review Focus 6. Incumbent gen 1 on A, attempt B; fakeRep.lost closed while |
| // release(B) polls: release unit proven before until; SwapAbandoned (not SwapFailed), StartStaged never called, no C05..C07 |
| - // event, C29 once; the next sweep stops the incumbent with StopLeaseLost (today's arm) and its settleCmds finds the hold proven |
| + // event, C29 once; the next sweep stops the incumbent with StopLeaseLost (today's arm) and its releasable waits on the record, which runRelease has proven |
| func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) // RACE: fakeRep.lost closed and sweepOnce run at once: one settle attempt |
| - // for the release hold (cmdHold.stop joins it), the incumbent stopped once, rep.Close after the proof. Run with -race. |
| + // at a time on the record (busy), the incumbent stopped once, rep.Close after the record is gone. Run with -race. |
| func TestReleaseRefusedWhenOwnershipEndsBeforeItStarts(t *testing.T) // each site: a fence raised (overlap: the attempt superseded) |
| // between admission and runRelease: no StartRelease, the site's NoOwnership outcome |
| +func TestReleaseObligationOutlivesTheWake(t *testing.T) // INV-2, INV-7 [Astra R1 5]. cold wake, release(B) unproven (its cgroup stays |
| + // populated): the complete wake() fails and its entry is deleted; a.releaseRuns[host] keeps B's pin (the persisted |
| + // generations file names it), the lease is the record's owed lease and is not released; a second ServeHTTP and a resident |
| + // tick are both refused errWakeUnproven with acquires unchanged; RunCmd is refused |
| +func TestReleaseObligationRetriedUntilProven(t *testing.T) // the same, then the group empties: the next sweep's reaper proves the rootfs |
| + // cmd unit (never the binary one), gives the owed lease back, drops the pin from the file on disk, and the next request wakes |
| +func TestIncumbentNeverIdlesThroughAMigration(t *testing.T) // [Astra R1 6] hibernating rootfs incumbent, overlap release(B) running past |
| + // cfg.Idle of fake time: sweepOnce does not stop the incumbent (C8); after the release ends it may idle as before |
| +func TestRunAfterAnUnprovenReleaseIsRefused(t *testing.T) // [Astra R1 6] overlap release unproven, swap abandoned, entry still awake: |
| + // RunCmd refused and a new attempt's release refused errReleaseRunOpen until the reaper proves the record |
| func TestDeclaredWorkersAreLoggedNotStarted(t *testing.T) // D8. a build declaring jobs: one log line per wake and per swap, no |
| // worker start asked of root, the wake and the swap succeed |
| // internal/rollout/rootfs_reason_test.go |
| @@ -1005,7 +1112,7 @@ func TestReasonWordRelease(t *testing.T) // "release: the re |
| // ReasonRelease; "release timed out: ..." -> ReasonReleaseTimeout; existing words unchanged |
| ``` |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapRelease|TestOverlapRunsRelease|TestOverlapAbandonsWhileARun|TestSwapReleaseRefusedByRoot|TestHoldReleaseFailure|TestAsleepRowRunsRelease|TestFirstWakeReleaseFailure|TestRestartDoesNotRerunRelease|TestReleaseRerunsAfterInterruptedWake|TestColdWakeRelease|TestSwapRelease|TestReleaseRefusedWhenOwnershipEnds|TestDeclaredWorkersAreLogged' -count=1` (under the short `TMPDIR`) and `go test ./internal/rollout/ -run TestReasonWordRelease -count=1`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapRelease|TestOverlapRunsRelease|TestOverlapAbandonsWhileARun|TestSwapReleaseRefusedByRoot|TestHoldReleaseFailure|TestAsleepRowRunsRelease|TestFirstWakeReleaseFailure|TestRestartDoesNotRerunRelease|TestReleaseRerunsAfterInterruptedWake|TestColdWakeRelease|TestSwapRelease|TestReleaseRefusedWhenOwnershipEnds|TestReleaseObligation|TestIncumbentNeverIdlesThroughAMigration|TestRunAfterAnUnprovenRelease|TestDeclaredWorkersAreLogged' -count=1` (under the short `TMPDIR`) and `go test ./internal/rollout/ -run TestReasonWordRelease -count=1`. Expected: FAIL. |
| - [ ] **Step 3:** Implement to the table; write `RFS-3-C01` and `C02`, add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's commands, `go test -race ./internal/activator/ -run 'TestSwapReleaseLeaseLossRacesTheSweep' -count=3`, the swap and wake-plan families (`-run 'Swap|Hold|Planned|FirstWake|Overlap'`, and `go test ./internal/rollout/ -run 'Reason|Scheduler' -count=1`), and Task 1's guards. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -1042,7 +1149,8 @@ git commit -m "rootfs: release gates every move onto a new build; a failure keep |
| Rules: |
| - `StartCmd` on a rootfs row: the tenant launch file is Plan 2's schema 2 with `Process: "cmd"` and no argv, its env `rootfsLaunchEnv(rootfsCmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir))` [pf 1.6]; the argv is `spec.Args` as given (no live-link prefix), sent to root as `StagedImage.Argv` through `RootfsControl.CmdRootfs(ctx, host, b.tier(rt).MemoryMax, stagedImageOf(id, "", spec.Args))` (A3, A5, the sized tier [pf 1.8]); the image identity is required (a rootfs command always names its image; none refuses with `errNoCmdExe`). An `ErrStagedImage` or `ErrStartRefused` answer is marked with `refuseRootfs` [pf 1.7]. The `CmdUnit` it returns, on success and on a failed start alike, is Plan 2's runtime-aware unit (A8, through Task 10's `startCmdUnit`): `RunCmd`'s `Poll`, its `Stop`, `interruptCmdsLocked` (`cmd.go:377`), `settleCmds` (`:415`) and the sweep's `retryCmdSettlesLocked` (`:399`) all reach `RootfsUnitName(RoleCmd, host)` and prove that unit's cgroup empty, never the binary cmd unit's (Astra R1 finding 1). A binary row is unchanged (INV-6). No egress step: #328 checks in root's `startRootfsCmd` [pf 2.5]. |
| -- `RunCmd` with `spec.Build != ""`, at the point it sets `spec.serving` (`cmd.go:600`): `id, err := b.BuildIdentity(rt, spec.Build)`; an error ends the run before anything starts with `ErrCmdVersion` (wrapped). Otherwise `spec.serving = stagedExeOf(id)` (a rootfs row's `StartCmd` turns that identity into `stagedImageOf`), `h.build = id`, and `recordBuild` names `spec.Build`, which is the build about to touch the data. The environment stays the serving generation's (merge ruling M3). `entryGenerationsLocked` adds `h.build` for every hold not proven settled, so the sweep keeps the image until the run ends. This works for binary rows too: `CmdExe` already mounts a staged binary. |
| +- `RunCmd` with `spec.Build != ""` resolves the build before it takes its admission lock, never under `a.mu` [Astra R1 8]: `BuildIdentity` (`backend_exec.go:1842`) hashes the whole image (`release.FileSHA256`, `:1857`), and `RunCmd` holds `a.mu` from its admission loop until `:615`, where it sets `spec.serving` (`cmd.go:600`). So `id, err := b.BuildIdentity(rt, spec.Build)` runs once, off the lock, after `Prepare` and before the loop; an error ends the run before anything starts with `ErrCmdVersion` (wrapped). Under the lock, at `:600`, `spec.serving = stagedExeOf(id)` (a rootfs row's `StartCmd` turns that identity into `stagedImageOf`) and `h.build = id`, the full identity, digest included. Root checks the digest again at the start, so a file replaced between the hash and the start is refused as `ErrStagedImage` (a refusal). `recordBuild` names `spec.Build`, which is the build about to touch the data. The environment stays the serving generation's (merge ruling M3). Pins [Astra R1 9]: `entryGenerationsLocked` adds `h.build` for every hold not proven settled, and `RunCmd` calls `a.publishBeforeExec()` off the lock after `recordBuild` and before `StartCmd`, so the generations file on disk names the run's build before it execs; a failed write abandons the run (`errStagedBuildNotPublished`), nothing started. This works for binary rows too: `CmdExe` already mounts a staged binary. |
| +- `RunCmd` is refused as busy while `a.releaseRuns[host]` exists (INV-7, Task 10's table): a run never starts beside a release, running or unproven. |
| - Console: `runClassRefusal` passes a rootfs record that does not hibernate (`rec.Runtime == provision.RuntimeRootfsV1`; today's `!rec.HibernateOrDefault()` arm, `apiruns.go:274`, refuses it), and keeps the fleet refusal for every record (D4, `:279-281`): a `carlos run` on a fleet box is refused with today's sentence until Plan 6 Task 16 carries it over the box-dials-the-console door (R7), and that task removes the fleet arm. The CLI page says so (RFS-3-C28). With `meta.Version != ""`: `release.ValidVersion` or 400 `RFS-3-C19`; `release.GetManifest(ctx, store, acct, app, version)` not found, 409 `RFS-3-C20`; written to `request.json`'s `Version` and the `run-start` audit row's version. |
| - Box: the runs worker sets `CmdSpec.Build = req.Version`. `runResultForLaunch` maps `ErrCmdVersion` to `Result{Refused: runs.RefusedVersion, Detail: req.Version}`; `runRefusedWords` says `RFS-3-C22`; the CLI's `runExit` prints `RFS-3-C21` with `r.Detail` and exits 3. |
| - CLI: `--version <build>` (help `RFS-3-C17`), sent as `meta.version`; the usage line becomes `RFS-3-C18`. |
| @@ -1065,6 +1173,10 @@ func TestRootfsRunRefusedByRootIsARefusal(t *testing.T) // the harness answers / |
| func TestRunVersionRunsTheNamedBuild(t *testing.T) // RunCmd with Build "v2" staged: CmdRootfs (CmdExe for a binary row) got v2's path and digest, env the |
| // serving generation's; generations snapshot lists v2 until settled |
| func TestRunVersionNotStagedIsRefused(t *testing.T) // Build "v9": errors.Is(err, ErrCmdVersion); no unit started |
| +func TestRunVersionHashesOffTheLock(t *testing.T) // [Astra R1 8] a BuildIdentity stub that blocks: a request to another host and a |
| + // sweepOnce complete meanwhile |
| +func TestRunVersionPinPublishedBeforeExec(t *testing.T) // [Astra R1 9] the persisted generations file names v2 before the /cmd |
| + // request, and still after the serving generation retires, until the run is proven settled; a failed write starts nothing |
| // internal/console/apiruns_rootfs_test.go |
| func TestRunDoorAdmitsRootfsResident(t *testing.T) // rootfs record, hibernate false, platform region: 202 |
| func TestRunDoorStillRefusesFleet(t *testing.T) // rootfs record on fleet/pi: 409, today's message |
| @@ -1145,7 +1257,7 @@ git commit -m "moves: refuse rootfs instances in every move transition and at ca |
| Spec §5.6's version floor has two halves: the console never places a rootfs row on a box that does not report `rootfs_ready` (Plans 2 and 4), and a box that has rootfs rows never installs a platform release that cannot run them. This is the second half, box side, in the shape of the layout floor (`internal/host/systemapply.go:525-526`). |
| **Files:** |
| -- Modify: `internal/host/systemapply.go` `install` (`:493`, after the layout guard at `:525`) |
| +- Modify: `internal/host/systemapply.go` `install` (`:493`, after the layout guard at `:525`); `internal/release/layoutintent.go` (`RootfsLifecycleFloor` beside `LayoutFloor`, `:211`) |
| - Create: `internal/host/systemapply_rootfs_test.go` |
| **Interfaces:** |
| @@ -1158,7 +1270,9 @@ Spec §5.6's version floor has two halves: the console never places a rootfs row |
| const systemApplyRootfsRefusal = "<RFS-3-C25>" |
| ``` |
| -When the candidate's units lack `rootfsInstanceUnit` and the registry has a rootfs row, the apply is refused before the journal (`errSystemRefused`, `:89`, the layout guard's wrapping), naming the hosts. A registry that will not open or list is itself the reason, as `layoutReversalReasons` treats it. The console's refusal to move the platform channel below the first rootfs release is Plan 4's, beside `layoutDowngradeBlocked` (`internal/console/layoutguard.go:24`). |
| +The unit set alone cannot tell this plan's lifecycle from Plan 2's [Astra R1 10]: main already ships `rootfsInstanceUnit`, and main's `ActivatorManaged` (`activator/layout.go:63`) excludes residents and has no release integration, which is exactly the distinction the layout floor draws between shipping units and supporting their lifecycle (`systemapply.go:517-524`). So the guard is the layout floor's shape with a release floor: `!slices.Contains(newUnits, rootfsInstanceUnit) || release.BelowFloor(target, release.RootfsLifecycleFloor)`, where `release.RootfsLifecycleFloor` (a `SemVer` beside `LayoutFloor`, `internal/release/layoutintent.go:211`) is the first release that carries group A. Task 15 sets it to the version the release recipe cuts next after group A merges (read from the changelog at the time), with a test pinning it as `LayoutFloor`'s test does (`layoutintent_test.go:112`). A candidate whose version does not parse (a local build named by a sha) is refused while rootfs rows exist: unlike the layout floor, its unit set says nothing here, so refusing up front is the only safe reading (C25's text covers it, `%s` the candidate). |
| + |
| +When the guard trips and the registry has a rootfs row, the apply is refused before the journal (`errSystemRefused`, `:89`, the layout guard's wrapping), naming the hosts. A registry that will not open or list is itself the reason, as `layoutReversalReasons` treats it. The console's refusal to move the platform channel below the first rootfs release is Plan 4's, beside `layoutDowngradeBlocked` (`internal/console/layoutguard.go:24`). |
| Root reads SQLite only through the service-user child [pf 4.2]: the census used to stand in for that rule, and now a test does. `systemapply.go` opens the registry only through `openSystemRegistry` (or the `openRegistry` seam that defaults to it), and never calls `registry.Open`. |
| @@ -1168,19 +1282,22 @@ Root reads SQLite only through the service-user child [pf 4.2]: the census used |
| func TestApplyRefusesACandidateWithoutRootfsUnits(t *testing.T) // a rootfs row present, candidate units lack it: refused, C25 names the host, |
| // no journal written |
| func TestApplyAllowsWithoutRootfsRows(t *testing.T) // same candidate, no rootfs rows: proceeds past the guard |
| -func TestApplyAllowsACandidateWithRootfsUnits(t *testing.T) |
| +func TestApplyAllowsACandidateWithRootfsUnits(t *testing.T) // units present, version at or above RootfsLifecycleFloor |
| +func TestApplyRefusesPlan2WithRootfsUnits(t *testing.T) // [Astra R1 10] a candidate with the rootfs units and a version below |
| + // RootfsLifecycleFloor (Plan 2's release): refused, C25 names the host; an unparseable version: refused |
| +func TestRootfsLifecycleFloorIsPinned(t *testing.T) // internal/release: the floor's value |
| func TestApplyRefusesWhenTheRegistryWillNotOpen(t *testing.T) // openRegistry errors: refused with that reason, no journal |
| func TestSystemApplyOpensNoRegistryItself(t *testing.T) // go/ast over systemapply.go: no call to registry.Open (or OpenReadOnly); |
| // rootfsRowsPresent's only caller passes the openRegistry seam's *Registry |
| ``` |
| -- [ ] **Step 2:** Run `go test ./internal/host/ -run 'TestApplyRefusesACandidateWithoutRootfs|TestApplyAllowsWithoutRootfs|TestApplyAllowsACandidateWithRootfs|TestApplyRefusesWhenTheRegistryWillNotOpen|TestSystemApplyOpensNoRegistryItself' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/release/ -run TestRootfsLifecycleFloorIsPinned -count=1` and `go test ./internal/host/ -run 'TestApplyRefusesPlan2WithRootfsUnits|TestApplyRefusesACandidateWithoutRootfs|TestApplyAllowsWithoutRootfs|TestApplyAllowsACandidateWithRootfs|TestApplyRefusesWhenTheRegistryWillNotOpen|TestSystemApplyOpensNoRegistryItself' -count=1`. Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C25`, add its id to the built list. |
| - [ ] **Step 4:** Run Step 2's command and `go test ./internal/host/ -run 'TestSystemApply|Layout' -count=1`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| ```bash |
| -git add internal/host/systemapply.go internal/host/systemapply_rootfs_test.go approved_rootfs_copy_test.go |
| +git add internal/host/systemapply.go internal/host/systemapply_rootfs_test.go internal/release/layoutintent.go internal/release/layoutintent_test.go approved_rootfs_copy_test.go |
| git commit -m "system apply: a box with rootfs instances refuses a platform release that cannot run them" |
| ``` |
| @@ -1194,7 +1311,7 @@ git commit -m "system apply: a box with rootfs instances refuses a platform rele |
| - [ ] **Step 2:** `GOOS=darwin go build ./... && GOOS=windows go build ./... && GOOS=linux GOARCH=arm64 go build ./...`. Expected: clean. |
| - [ ] **Step 3:** Every touched package once, without `-run`: `go test ./internal/registry/ ./internal/provision/ ./internal/rollout/ ./internal/ops/ ./internal/layout/ ./internal/runs/ ./internal/rolloutwords/ ./internal/release/ -count=1`, then `go test ./internal/activator/ ./internal/edge/ ./internal/host/ ./internal/console/ -count=1` under `nice`, one package at a time, then the root package's `TestRun|TestRootfsCopy|TestRootfsBuilt|TestDocsite|TestAddRefuses` group. Expected: PASS. |
| - [ ] **Step 4:** `go test -race ./internal/activator/ -run 'TestResidentRequestAndTickRaceOneWake|TestResidentCrashDuringStopIsOneStop|TestStopSettlesARunningRelease|TestReleaseLeaseLossRacesExit|TestSwapReleaseLeaseLossRacesTheSweep' -count=1`. Expected: PASS. |
| -- [ ] **Step 5:** The invariants hold: `go test ./internal/activator/ -run 'TestRootfsFilesNameNoBinaryVerb|TestRootfsRemovalOwnersUnchanged|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv|TestEveryRootfsProofNamesTheRootfsUnit|TestRootfsRefusalPrecedesTheLease|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` (PASS). Plan 3's diff touches no `internal/instancectl` file except `client.go` [pf 4.2]: `git diff --name-only origin/main...HEAD -- internal/instancectl` prints exactly `internal/instancectl/client.go`. |
| +- [ ] **Step 5:** The invariants hold: `go test ./internal/activator/ -run 'TestRootfsFilesNameNoBinaryVerb|TestRootfsRemovalOwnersUnchanged|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv|TestEveryRootfsProofNamesTheRootfsUnit|TestRootfsRefusalPrecedesTheLease|TestReleaseObligation|TestReleaseRunConsumersReadTheRecord|TestResidentFailureClassification|TestProductionBackendImplementsRootfsSeams|TestRootfsHealthWindowIsTheRootfsBound|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` and `go test ./internal/ops/ -run 'TestFleetDBsStillExcludesHibernatingSidecars' -count=1` (PASS). Plan 3's diff touches no `internal/instancectl` file except `client.go` [pf 4.2]: `git diff --name-only origin/main...HEAD -- internal/instancectl` prints exactly `internal/instancectl/client.go`. |
| - [ ] **Step 6:** Every live `RFS-3-C` id except W1's (`C08`, `C09`, `C10`) is in the gate's built list, and C13 is in none: `go test . -run 'TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. The controller pushes the branch to amadan; CI runs the full suite; main's census runs at merge [pf 4.1]. |
| --- |
| @@ -1213,7 +1330,7 @@ This is the first draft's Task 9, with the worker identity, Task 6's worker half |
| **Files:** |
| - Create: `internal/activator/rootfsworkers.go`, `internal/activator/rootfsworkers_test.go` |
| -- Modify: `internal/activator/backend_rootfs.go` (worker half: `StartWorker`, `RootfsWorkerGone`); `internal/activator/rootfsenv.go` (`rootfsWorkerVars`) |
| +- Modify: `internal/activator/backend_rootfs.go` (worker half: `LaunchRootfsWorker`, `RootfsWorkerGone`); `internal/activator/rootfsenv.go` (`rootfsWorkerVars`) |
| - Modify: `internal/activator/prepare.go` (`prepareWorker`, `writeRootfsWorkerLaunch`, the worker forms of `removeLaunch`), `internal/activator/unitproc.go` (`unitProc.worker`, `rootfsUnitFor`, `stopRole` with the worker name, the worker form of `recordName`) |
| - Modify: `internal/activator/activator.go`: `actEntry` (worker fields), Task 11's `rootfsWorkersHook` in `doWake` after step 6 (`:2638`), `stop` (`:3916`, workers stopped first), Task 8's `superviseRootfsLocked` (supervision) |
| - Modify: `internal/activator/opset.go:681` `releasable` (the worker proof), `internal/activator/generations_file.go:177` `entryGenerationsLocked` (worker builds) |
| @@ -1226,8 +1343,11 @@ This is the first draft's Task 9, with the worker identity, Task 6's worker half |
| ```go |
| // The control verbs are Plan 2's activator.RootfsControl (StartRootfsWorker, StopRootfs); no new control interface. |
| type RootfsWorkerBackend interface { |
| - // StartWorker, not StartRootfsWorker: that name is the client's (RootfsControl.StartRootfsWorker, control.go:55) [pf 8.2] |
| - StartWorker(ctx context.Context, rt registry.Route, name string, g Gen, genEnv map[string]string) (Proc, error) |
| + // LaunchRootfsWorker: not StartRootfsWorker, the client's name (RootfsControl.StartRootfsWorker, control.go:55) [pf 8.2], |
| + // and not the pre-flight's StartWorker either, which ExecBackend (backend_exec.go:3084) and SplitBackend |
| + // (backend_unit.go:407) already have for binary sidecar workers with another signature. Its first act is |
| + // runExecGate(ctx), immediately before root is asked (the worker exec gate below). |
| + LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, genEnv map[string]string) (Proc, error) |
| // RootfsControl.StopRootfs(ctx, host, RoleWorker, 0, name, false), then waitUnitCgroupEmpty(ctx, rt, WorkerUnitName(host, name)) |
| RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error |
| } |
| @@ -1243,7 +1363,9 @@ This is the first draft's Task 9, with the worker identity, Task 6's worker half |
| type rootfsWorker struct { |
| name string |
| proc Proc |
| - gen uint64 // the generation whose build and env it runs |
| + gen uint64 // the generation whose env it runs |
| + build release.StagedIdentity // that generation's full identity (stagedIdentityOf), kept through a stray, |
| + // pinned in the generations file until the worker is proven gone [Astra R1 9] |
| started, retryAt time.Time |
| backoff time.Duration |
| restarts int |
| @@ -1251,7 +1373,7 @@ This is the first draft's Task 9, with the worker identity, Task 6's worker half |
| startDone chan struct{} |
| } |
| type WorkerReport struct{ Name, State string; Restarts int } // State: running | restarting | crash-loop | stopped |
| - func (a *Service) startRootfsWorkers(ctx context.Context, e *actEntry, rt registry.Route, g Gen) // one StartWorker per name, off a.mu |
| + func (a *Service) startRootfsWorkers(ctx context.Context, e *actEntry, rt registry.Route, g Gen) // one LaunchRootfsWorker per name, off a.mu |
| func (a *Service) stopRootfsWorkers(e *actEntry) bool // stop and prove each; false leaves strays |
| func (a *Service) rootfsWorkersGone(e *actEntry) bool // re-stop and re-prove the strays; true when none is left |
| func (a *Service) RootfsWorkers(host string) []WorkerReport |
| @@ -1263,13 +1385,15 @@ Rules: |
| - **The launch environment** [pf 1.6, 8.1]: `env == rootfsLaunchEnv(rootfsWorkerVars(rt, g, dbPath, genEnv))`, where `genEnv` is the generation's launch file environment (`launchEnvProc`) before the agent-owned variables, and `g.Control` is the generation's control socket, which a worker keeps (D1). The test compares it with web's launch file, less `CARLOS_SOCKET`. Never `childEnv` (INV-1, INV-5). |
| - **The tier** [pf 1.8]: `memoryMax` is the worker's generation's `g.Tier.MemoryMax`, never `rootfsTier`. |
| - **The stop** [pf 1.3, 1.5]: `RootfsWorkerGone` is `StopRootfs(ctx, host, RoleWorker, 0, name, false)` then `waitUnitCgroupEmpty(ctx, rt, WorkerUnitName(host, name))` (`unitEvents`, the reported group, R-b). `kill` is always false: a worker whose stop cannot be proven stays a stray, with no kill escalation in v1; root has no tested worker kill (`killGen`, `internal/instancectl/rootfs.go:1144`, is a generation's). Any `StopRootfs` error is unproven: `ErrGenUnproven`, a 409 in-flight answer (`rootfs_unitlock.go:162`) or transport. |
| -- **Start after `web` is healthy** (spec §5.4): Task 11's hook in `doWake` after step 6 becomes `startRootfsWorkers` for a rootfs row, on the wake's generation `w.gen`: one `StartWorker` per name, from that generation's staged image and its launch env, off `a.mu`, under the wake's context and after `a.wakeAllowed(host)`. A worker that fails to start is not a wake failure (members before bots, the co-spawn rule); it is installed as exited so the tick restarts it. The declaration is read through `Processes(rt, genIdentity(w.gen))`, from the build the generation runs, never from the live link. A `Processes` refusal starts no worker and logs once; `web` serves. More than 4 names, or an invalid one, starts no worker and logs once; `web` serves. |
| +- **Start after `web` is healthy** (spec §5.4): Task 11's hook in `doWake` after step 6 becomes `startRootfsWorkers` for a rootfs row, on the wake's generation `w.gen`: one `LaunchRootfsWorker` per name, from that generation's staged image and its launch env, off `a.mu`, under the wake's context and after `a.wakeAllowed(host)`. A worker that fails to start is not a wake failure (members before bots, the co-spawn rule); it is installed as exited so the tick restarts it. The declaration is read through `Processes(rt, stagedIdentityOf(w.gen))`, from the build the generation runs, never from the live link. A `Processes` refusal starts no worker and logs once; `web` serves. More than 4 names, or an invalid one, starts no worker and logs once; `web` serves. |
| - **Supervision** in Task 8's `superviseRootfsLocked`, for each awake rootfs entry: a worker whose `proc.Exited()` and that is not `starting` is a crash whatever its exit status (Review Focus 3: a worker's record says it runs). Before a restart its unit is proven gone (`RootfsWorkerGone`); unproven, it moves to `strayRootfsWorkers` and no restart runs beside it. Backoff is the sidecar's (Global Constraints). A worker whose backoff has reached `sidecarRestartMax` is in crash loop: event `RFS-3-C10` once on entry, then `RFS-3-C09` at most once a minute. Every other exit emits `RFS-3-C09`. A start emits `RFS-3-C08`. The restart runs off `a.mu` and re-checks entry identity (`a.entries[host] == e0`) and `e0.state == actAwake` before it installs, the sidecar restart's shape (`activator.go:4873-4920`); a start that lost its entry stops what it started and proves it gone before `startDone` closes. |
| +- **The worker exec gate** [Astra R1 7]: every worker start, the first after the wake and every restart, passes `workerGate(e, w)` immediately before root is asked, riding in on the context (`withExecGate`) as a generation's gate does, and `LaunchRootfsWorker` asks `runExecGate(ctx)` after its preparation and before `StartRootfsWorker`. `workerGate` takes `a.mu` and refuses unless: `a.ownedLocked(e, waking)` holds (`swapadmit.go:88`: the entry is the host's, awake (or, for the wake's own first start, still the waking entry whose lease the wake holds), its replica's lease not lost, no fence, no shutdown); `e.gen.N == w.gen` (the generation the worker belongs to is still the serving one, so a swap that switched meanwhile starts none of the old set); no stray of that worker's name is unproven; and no release record is open for the host. The backend's own rootfs gates run in `LaunchRootfsWorker` before its preparation, as `rootfsGates` does for web. This is `startSidecar`'s shape (`activator.go:2828`), which checks ownership before and after its preparation. A refused start starts nothing and is not a crash; the post-start identity check (below) stays, for a start that raced a stop after the gate. |
| +- **Pins** [Astra R1 9]: a worker's `build` is set before its start, `entryGenerationsLocked` adds every worker's and every stray's `build`, and the start calls `a.publishBeforeExec()` off `a.mu` before `LaunchRootfsWorker`; a failed write starts nothing (`errStagedBuildNotPublished`) and retries on the next tick. The pin is the worker's own identity, not its generation's member entry, so it survives `dropMember` of the retiring generation (`swap.go:685`), which W2's handover runs after. |
| +- **Through the production backend** [Astra R1 4]: `SplitBackend.LaunchRootfsWorker` and `SplitBackend.RootfsWorkerGone` forward to `b.Exec` for an exec-backed row and refuse a unit-backed one; `production_backend_test.go` gains the `RootfsWorkerBackend` row, and the worker tests below run once through `productionBackend`. |
| - **Never takes `web` down:** no worker path calls `beginStopLocked`. |
| - **Stops first:** in `stop`, before the sidecar co-stop: `a.stopRootfsWorkers(e)` waits each `startDone`, then `proc.Stop` (bounded by `sidecarStopTimeout`, `activator.go:791`) and `RootfsWorkerGone`; unproven ones go to `strayRootfsWorkers`. Every non-nil `StopRootfs` answer is a stray, which the sweep retries [pf 2.4]: a failed non-kill worker stop answers 502, and a `/stop` during a start of the same unit answers `statusGenUnproven` at once (`errRootfsUnitInFlight`). `releasable` (gens are on for every rootfs row, D2) adds `&& a.rootfsWorkersGone(e)`, which re-stops and re-proves strays, so a stop with an unproven worker stays pending with its lease and replication held, and the sweep retries. |
| - **Files only after the proof (INV-2):** a worker's launch file, exit records and stray entry are removed only after `RootfsWorkerGone` returned nil. |
| - **Never `KillHost` or `EmptyHost`** [pf 2.2]: workers are built on `unitProc` and are not activator `e.worker` entries (`activator.go:673` is a sidecar row), so they never reach those verbs, which refuse a rootfs row anyway (N1). |
| -- **Pins:** `entryGenerationsLocked` adds the build of every worker and stray (`a.genIdentity` of its generation), so root never sweeps an image a worker still runs. |
| - `RootfsWorkers(host)` reports `running` (proc alive), `restarting` (exited, inside its backoff, below the cap), `crash-loop`, or `stopped` (no awake entry, or not started). |
| - [ ] **Step 1: Write the failing tests.** Service tests use `fakeBackend` extended with `RootfsWorkerBackend` (a `fakeWorkerBackend` in the test file that records `start <name> gen<N>` and `gone <name>` into the same ordered log `fakeBackend` keeps); backend tests use `nestedBackend` with Plan 2's `fakeControl`, which already implements `RootfsControl`, and the real file names. |
| @@ -1286,25 +1410,30 @@ func TestRootfsWorkerStopAnswers(t *testing.T) // [pf 2.4] fakeContro |
| // the first, proven after the second; a 502 is a stray too |
| func TestRootfsWorkerUnprovenKeepsItsFiles(t *testing.T) // INV-2. RootfsWorkerGone unproven: the stray entry, launch.worker.jobs.json |
| // and its exit records all stay; after the proof they go |
| -func TestRootfsWorkerStartRacesStop(t *testing.T) // RACE: a restart blocked inside StartWorker while Shutdown runs: the |
| +func TestRootfsWorkerStartRacesStop(t *testing.T) // RACE: a restart blocked inside LaunchRootfsWorker while Shutdown runs: the |
| // started worker is stopped and proven before the lease goes; no worker survives. Run with -race. |
| func TestTooManyWorkersStartNone(t *testing.T) // five names: no worker starts, web serves, one log line |
| func TestWorkerProcessesRefusalStartsNone(t *testing.T) // Processes refuses (digest mismatch): no worker starts, web serves, one log line |
| // backend half |
| -func TestRootfsWorkerLaunchIsTheGenerationsEnv(t *testing.T) // StartWorker: root got the generation's image (StagedImage path, digest, |
| +func TestRootfsWorkerLaunchIsTheGenerationsEnv(t *testing.T) // LaunchRootfsWorker: root got the generation's image (StagedImage path, digest, |
| // Process "jobs") and memory_max g.Tier.MemoryMax; launch.worker.jobs.json (WorkerLaunchFileName) has Process "jobs" and |
| // env == rootfsLaunchEnv(rootfsWorkerVars(...)): web's launch env less CARLOS_SOCKET, with CARLOS_SOCKET == rt.Socket and |
| // CARLOS_CONTROL_SOCKET == g.Control |
| func TestRootfsWorkerIdentity(t *testing.T) // prepareWorker reads no <host>-sidecar.env, binds no control listener, binds |
| // WorkerLogSocket(host, "jobs"), clears WorkerExitPrefix("jobs"); the unitProc's unit is WorkerUnitName; its Stop asks |
| // StopRootfs with worker "jobs" and kill false; unitNameFor(rt, RoleWorker, 0) is still "" |
| -func TestWorkerImagePinnedWhileItRuns(t *testing.T) // generationsSnapshotLocked lists the worker's build while it runs and while stray |
| +func TestWorkerImagePinnedWhileItRuns(t *testing.T) // the persisted generations file (read from disk) names the worker's build |
| + // before root is asked, while it runs, while it is stray after a failed proof, and after its generation is dropped |
| +func TestWorkerGateRefusesAtTheLastMoment(t *testing.T) // [Astra R1 7] during LaunchRootfsWorker's preparation: the lease is lost, a |
| + // fence is raised, or a swap switches to a new generation: each time root is asked nothing and no worker runs |
| +func TestWorkersThroughTheProductionBackend(t *testing.T) // productionBackend: the workers start and are proven gone through it; a |
| + // unit-backed row is refused |
| func TestRootfsWorkersReport(t *testing.T) // the four states |
| ``` |
| The invariant tables gain the worker rows: INV-1, the worker handle's Stop and Poll (no binary unit, populated reported group: unproven); INV-5, the worker launch file under `t.Setenv("PATH", "/agent/bin")`. |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWorker|TestCleanExitingWorker|TestTooManyWorkers|TestWorkerProcessesRefusal|TestWorkerImagePinned|TestEveryRootfsProof|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWorker|TestCleanExitingWorker|TestTooManyWorkers|TestWorkerProcessesRefusal|TestWorkerImagePinned|TestWorkerGate|TestWorkersThroughTheProductionBackend|TestProductionBackend|TestEveryRootfsProof|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C08` to `C10`, add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's command, `go test -race ./internal/activator/ -run 'TestRootfsWorkerStartRacesStop|TestRootfsWorkersStopFirst' -count=3`, `-run 'Stop|Sidecar|Releasable|Generations|Prepare|UnitProc'`, and Task 1's guards and goldens. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -1333,7 +1462,7 @@ This is the first draft's Task 11 step 8, its `TestOverlapHandsOverWorkersNeverT |
| func (a *Service) handOverRootfsWorkers(e *actEntry) // stop and prove the old set, then start the set of e.gen |
| ``` |
| -Worker handover (spec §5.2): at step 8, beside `replaceSidecar`, `a.handOverRootfsWorkers(e)`. By then the new `web` has passed its health check and is serving. It stops and proves every worker of the retiring generation, then starts the new generation's set. A worker it cannot prove stays stray and the new set waits; the tick starts it once every stray is proven. A config attempt with the same build hands over too, so workers pick up new config. Two worker sets never run at once. A cold wake whose release ends in lease loss, refusal or failure starts no worker. |
| +Worker handover (spec §5.2): at step 8, beside `replaceSidecar`, `a.handOverRootfsWorkers(e)`. By then the new `web` has passed its health check and is serving. It stops and proves every worker of the retiring generation, then starts the new generation's set. A worker it cannot prove stays stray and the new set waits; the tick starts it once every stray is proven. A config attempt with the same build hands over too, so workers pick up new config. Two worker sets never run at once. A cold wake whose release ends in lease loss, refusal or failure starts no worker. The retiring set's pins are the workers' own (`rootfsWorker.build`, W1), so `dropMember` of the retiring generation (`swap.go:685`) before the handover leaves them listed until each is proven gone [Astra R1 9]. |
| - [ ] **Step 1: Write the failing tests:** |
| @@ -1345,6 +1474,8 @@ func TestOverlapReleaseFailureLeavesWorkersAlone(t *testing.T) // release(B) exi |
| func TestColdWakeReleaseLeaseLossStartsNoWorker(t *testing.T) // as Task 11's TestColdWakeReleaseStopsOnLeaseLoss, with a declared |
| // worker: no worker start asked of root |
| func TestConfigAttemptHandsOverWorkers(t *testing.T) // same build, new config: the workers restart on the new generation's env |
| +func TestRetiringWorkersStayPinnedAfterDropMember(t *testing.T) // the persisted generations file names gen 1's build after dropMember, |
| + // while a gen-1 worker is stray, and drops it once the stray is proven |
| ``` |
| - [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapHandsOverWorkers|TestOverlapReleaseFailureLeavesWorkers|TestColdWakeReleaseLeaseLossStartsNoWorker|TestConfigAttemptHandsOverWorkers' -count=1`. Expected: FAIL. |
| @@ -1468,10 +1599,13 @@ None open. The one this plan raised, `carlos run` on fleet boxes (D4), Paul answ |
| - What a claim-armed box does: Plan 3 reads no claim switch; Plan 2's `rootfsGates` refuses every rootfs start under it, and Task 7 asks those gates before the lease, so residency, wake, release and run all refuse there with the reason in `carlos logs`. |
| - Names used across tasks: `ActivatorOwned`, `Resident`, `Rootfs` (Task 2) in Tasks 4, 5, 7, 8; `RuntimeRootfsV1` in `registry` and `provision`; Plan 2's `rootfsVars` with Task 6's `rootfsCmdVars` in Tasks 10, 12 and W1's `rootfsWorkerVars`; `healthBoundFor` (N1) in Tasks 7 and 11; `rootfsStartRefusal` and `rootfsStartable` (Task 7) in Task 8; Plan 2's `RootfsControl` verbs (A4, A5) and Task 10's `Processes(rt, id)` and `stagedImageOf` in Tasks 11, 12, W1; `runRelease`, `leaseWatch`, `ReleaseError`, `errReleaseUnproven`, `errReleaseLeaseLost`, `errReleaseNoLease` (Task 10) in Task 11; Task 10's `startCmdUnit` and `rootfsCtlHarness` in Task 12 and N1's swap tests in Task 11; `rootfsDBPlacer`, `PlaceRootfsDB` (Task 7) in Task 11's first-boot order; Task 8's `superviseRootfsLocked` and Task 11's `rootfsWorkersHook` filled by W1 and W2; `RootfsWorkers`, `WorkerReport` (W1) in W3; `stopRootfsWorkers`, `rootfsWorkersGone`, `handOverRootfsWorkers` in W1 and W2. |
| - Proportion: decisions, signatures and test assertions; bodies only where the order of steps is the decision (`rootfsTick`, `runRelease`). |
| +- **Who owns a running `release`, admission to proof (INV-7, round 2).** One owner: the Service, through one record per host, `a.releaseRuns[host]` (Task 10). One obligation record: it holds the build's full identity (the pin), the cmd unit's hold (the stop and settle), the cancel, the entry that started it while that entry lives, and the lease it must give back if that entry's wake failed. One retry path: `runRelease` settles while it runs; once it returns unproven, only the sweep's `reapReleaseRunsLocked` retries, one attempt at a time (`busy`). Admission creates the record before anything else and publishes the pin before root is asked; the proof is the only thing that removes it. Every consumer reads that record and nothing else: a member's run and another release are refused; the owner is never idle-stopped or max-run recycled; the owner's stop cancels it and `releasable` waits for it; a wake of the host is latched; the failed wake's cleanup hands the lease to it; the generations file lists its build. No entry field (`e.cmd`, `e.cmdLeft`, the first draft's `releaseHold`) says whether a release runs, so deleting an entry cannot drop the obligation, and the run paths (`settleCmds`, `cmdHoldsLocked`, `retryCmdSettlesLocked`) are untouched. |
| +- **Decoupling `release` from the wake and swap lifecycle (flagged, not done).** My view: it would be simpler for the overlap swap and not for the cold wake. In a swap, running `release` as its own owned step before the attempt (the scheduler admits a release for B under the incumbent's replica, waits for its record to be proven and its result, then admits the swap with no release in it) would take the release case out of `swapOverlap`'s step 3a and 3 entirely, and the swap would never have to classify a release error. The cost is a durable "release passed for B" marker, the column D3 rejected, so that a swap admitted later knows not to re-run it, and a second scheduler state. In a cold wake the release needs the wake's own lease and the restored database, and runs between restore and `web`; a separate step would have to acquire the lease, restore, run, then hand the lease to the wake, and that hand-off is the hard part this record already avoids. So the record above is the smaller change for both; if a round 3 finds this family again in the swap path, decoupling the swap side (a release step with its own record, before the attempt) is the change I would make first. |
| - **The 2026-10-26 amendment** (the pre-flight against as-built Plan 2 and main a912a342; every proposed ruling adopted; per-row map in `.superpowers/sdd/2026-10-24-rootfs-apps-3-lifecycle/amend-report.md`): |
| - An Invariants section (INV-1 to INV-6), each naming its enforcing test; Task 1 now lands the INV-1, INV-2 and INV-4 guards, INV-5's web row and the INV-6 goldens, green on main, with mutation evidence. |
| - New Task N1 before Task 7: `StartStaged`'s rootfs arm (on main a rootfs row could never swap, hold or take a planned wake), `healthBoundFor` in `genHealthy` and the verdict floor, `CmdRootfs`'s typed refusal, `KillHost`/`EmptyHost` refusing rootfs, `HasSidecar` false. |
| - - Group W at the end: W1 (the first draft's Task 9, plus the worker identity the agent lacks on main, Task 6's worker half, `StopRootfs` with `kill=false`, `waitUnitCgroupEmpty` on `WorkerUnitName`, the stop answers, `rootfsWorkerVars` over the generation's agent-owned vars, `StartWorker`'s rename), W2 (Task 11's handover), W3 (Task 14). No group A task needs them: `Processes(rt, id)` and `stagedImageOf` moved to Task 10, Task 8 leaves a no-op supervision hook, Task 11 a declared-workers log (D8). Plan 3 may merge without Group W; the index makes Plan 4 depend on it. |
| + - Group W at the end: W1 (the first draft's Task 9, plus the worker identity the agent lacks on main, Task 6's worker half, `StopRootfs` with `kill=false`, `waitUnitCgroupEmpty` on `WorkerUnitName`, the stop answers, `rootfsWorkerVars` over the generation's agent-owned vars, the worker start renamed `LaunchRootfsWorker`), W2 (Task 11's handover), W3 (Task 14). No group A task needs them: `Processes(rt, id)` and `stagedImageOf` moved to Task 10, Task 8 leaves a no-op supervision hook, Task 11 a declared-workers log (D8). Plan 3 may merge without Group W; the index makes Plan 4 depend on it. |
| - Refusal before the lease (Task 7, INV-3) through the backend's own gates, with a request budget; the claim reason, `errRootfsClaim`, RFS-3-C13 (struck in the deck and the gate's struck list) and its test removed; the census line and run removed, replaced by Task 15's no-`registry.Open` test and gate A's `instancectl` diff check; dead claim references (`claimAwareLegacy`, `ErrCmdClaim`, the #250 post and hand-off) struck. |
| - Task 2: `Upsert` keeps a rootfs row's hibernation unless re-tenanted, the replication arm keys on the effective runtime, `carlos add` refuses an existing rootfs host, `ErrRuntimeFixed` crosses the remote registry. Task 5: `BuildStateKept`, `socket_advice.go:121` and `restartscope.go:496` added, `movesphase1.go` dropped. Task 7: `RenameBetweenNoReplace`. Task 10: `Processes` checks the image's digest, root's refusals are refusals, launch env `rootfsLaunchEnv`, the sized tier. Task 12: the same, plus `runCopySuperseded` for RUN-C47. Task 13: the provision transitions are the control, a test enumerates the `seedMoveRefusal` sites, the Phase 1 citations dropped. Every agent-side egress slot struck (#328 checks on root's side). |
| + - **Round 2 (Astra plan review R1 of b3a40781, 7 P1 and 4 P2; map in amend-report.md "Round 2"):** Task 5 widens only (`ActivatorLeased` keeps hibernating binary sidecars where today's no-kind sites have them); N1's staged arm launches without a health wait and every rootfs `Gen` carries its full identity (`stagedIdentityOf`), with the manifest read's (nil, nil) and `BoxArtifact` cases refused; every new interface goes through `SplitBackend` with a production-composition test; one `releaseRun` record owns a release from admission to proof (INV-7), outliving a failed wake with its lease, pin and latch, read by every consumer; a final worker exec gate (`workerGate`) and `LaunchRootfsWorker` (the pre-flight's `StartWorker` collides with the binary worker start); gates, `BuildIdentity` and pins off `a.mu` and published before exec; the rollback floor is a release floor (`RootfsLifecycleFloor`), not the unit set; INV tests cover the shared dispatch files, the agent-held obligations, a real health response between the bounds and resident accounting (`residentFailure`). |
| - Every file:line refreshed against main a912a342, spec rev 5; the RFS-3 file cells set to bare paths in the deck and here (texts unchanged); each task's header says whether it gets a cross-model review. `Service.rootfsRefusal` is now `rootfsStartRefusal`, because Plan 2's `rootfsRefusal` is a type in the same package. |