| index 479238c72..8a96df6c8 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 |
| @@ -2,19 +2,53 @@ |
| |
| > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| |
| -**Goal:** A rootfs instance record mints a rootfs row with its hibernation fixed; the box runs it always-on (started at boot, restarted after a crash or an adoption, never idle-slept) or hibernating, with every rootfs process given the web environment; declared workers run beside `web`; the `release` process runs from the new image at each deploy and gates the switch; `carlos run` works on rootfs rows and gains `--version`; moves refuse rootfs rows. |
| +**Goal:** A rootfs instance record mints a rootfs row with its hibernation fixed; the box runs it always-on (started at boot, restarted after a crash or an adoption, never idle-slept) or hibernating, with every rootfs process given the web environment; a rootfs row swaps, holds and takes a planned wake like any generation; the `release` process runs from the new image at each deploy and gates the switch; `carlos run` works on rootfs rows and gains `--version`; moves refuse rootfs rows. Declared workers run beside `web` once Group W lands; Plan 3 may merge without it. |
| |
| -**Architecture:** One immutable column, `routes.runtime` (Plan 2 Task 2), decides everything on the box. `registry.Route.ActivatorOwned()` replaces every `Kind == "instance" && Hibernate` test, so a non-hibernating rootfs row is the activator's, nested, lease-held and activator-replicated. A 2-second rootfs tick inside the activator's sweeper goroutine starts resident rows (four at a time, per-host backoff), notices crashes and supervises workers. Workers are `RoleWorker` units started after `web` is healthy and stopped first. The `release` process runs in the rootfs cmd unit from the new image, in three places: the overlap swap before the successor spawns, the pinned wake of a hold, and a wake onto a build the row has not served. A failure is the build's failure (`SwapFailed`), so the incumbent keeps serving. Every release runs gated on ownership and supervised by the lease it runs under; losing that lease stops it and proves it gone before the lease's safety deadline, and is never the build's failure. |
| +**Architecture:** One immutable column, `routes.runtime` (Plan 2 Task 2), decides everything on the box. `registry.Route.ActivatorOwned()` replaces every `Kind == "instance" && Hibernate` test, so a non-hibernating rootfs row is the activator's, nested, lease-held and activator-replicated. Every start of a rootfs row, the overlap successor, the hold pin and the planned wake included, goes through Plan 2's rootfs start (Task N1), and every refusal comes before the lease (Task 7). A 2-second rootfs tick inside the activator's sweeper goroutine starts resident rows (four at a time, per-host backoff) and notices crashes. The `release` process runs in the rootfs cmd unit from the new image, in three places: the overlap swap before the successor spawns, the pinned wake of a hold, and a wake onto a build the row has not served. A failure is the build's failure (`SwapFailed`), so the incumbent keeps serving. Every release runs gated on ownership and supervised by the lease it runs under; losing that lease stops it and proves it gone before the lease's safety deadline, and is never the build's failure. Workers (Group W, last) are `RoleWorker` units started after `web` is healthy and stopped first. |
| |
| -**Tech Stack:** Go 1.26; `internal/registry`, `internal/provision`, `internal/activator` (state machine, `ExecBackend`, cmd unit), `internal/rollout`, `internal/edge`, `internal/ops`, `internal/layout`, `internal/host`, `internal/console`, `internal/runs`, `internal/rolloutwords`, `internal/status`; systemd through `instancectl`. |
| +**Tech Stack:** Go 1.26; `internal/registry`, `internal/provision`, `internal/activator` (state machine, `ExecBackend`, cmd unit), `internal/rollout`, `internal/edge`, `internal/ops`, `internal/layout`, `internal/host`, `internal/console`, `internal/runs`, `internal/rolloutwords`, `internal/status`, `internal/release`; systemd through `instancectl` (Plan 3 changes only `internal/instancectl/client.go` there). |
| |
| -**Spec:** `docs/superpowers/specs/2026-10-24-rootfs-apps-design.md` rev 4: §5.0 (record half), §5.2 (environment and deploy half), §5.2.1, §5.4, §5.5, §5.6, §7 C5, C7, C8. Index and shared contract: `docs/superpowers/plans/2026-10-24-rootfs-apps-0-index.md`. Prior design used for residency semantics only: `implementation/always-awake-exec.md`. Run design for the cmd unit: `docs/superpowers/specs/2026-10-08-carlos-run-design.md`. |
| +**Spec:** `docs/superpowers/specs/2026-10-24-rootfs-apps-design.md` rev 5: §5.0 (record half), §5.2 (environment and deploy half), §5.2.1, §5.4, §5.5, §5.6, §7 C5, C7, C8. Index and shared contract: `docs/superpowers/plans/2026-10-24-rootfs-apps-0-index.md`. Prior design used for residency semantics only: `implementation/always-awake-exec.md`. Run design for the cmd unit: `docs/superpowers/specs/2026-10-08-carlos-run-design.md`. |
| |
| -**Build target:** `main` with Plans 1 and 2 merged (index). Every name below that is not from Plans 1 or 2 was read at 64a002c8. |
| +**Build target:** `main` with Plans 1 and 2 merged (Plan 2 is d34c0a72). Every file:line below was read on main at a912a342 (claims cleanup R1 and R2 landed), unless a section says otherwise. |
| + |
| +**Amended 2026-10-26** from the pre-flight against as-built Plan 2 (`.superpowers/sdd/2026-10-24-rootfs-apps-3-lifecycle/preflight.md`, every proposed ruling adopted). A bracketed `[pf 1.1]` names the pre-flight row behind a requirement. Where this text and a pre-flight ruling differ, the ruling wins; this amendment means them to agree. |
| + |
| +## Invariants |
| + |
| +They come from where Plan 2 spun. Plan 2's Task 11 rounds 1 to 5 and its final waves kept finding the same families: E1 (a staged identity not byte-equal to its manifest); E2, E6 and K2 (removal or a kill proof through the wrong unit, or without the proof); I1 (a refusal recorded as a build failure); I3 (a proof bypassing the reported group); N1 (binary behaviour changed by a rootfs fix). Each invariant is enforced from Task 1, like Plan 2's G1 guard: a guard that passes on main and fails on a violation, plus a behavioural test that turns green in the task named. Every task keeps every guard green; a task that cannot keep one green stops and reports. |
| + |
| +- **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. |
| +- **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`. |
| +- **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. |
| +- **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). |
| + |
| +## Task order and review |
| + |
| +| group | tasks, in order | merge | |
| +|---|---|---| |
| +| A | 1, 2, 3, 4, 5, 6, N1, 7, 8, 10, 11, 12, 13, 15, 16 (gate A) | Plan 3 merges after gate A | |
| +| W | W1, W2, W3, W gate | may follow in a later merge; Plan 4 depends on it (index) | |
| + |
| +The numbers of the first draft are kept so the pre-flight's row ids still read. Task 9 (workers) is now W1, Task 14 (worker states in the rollout report) is W3, and Task 11's worker handover is W2. No group A task consumes anything from Group W [pf 6.1]. |
| + |
| +Before each task: merge `origin/main` (claims cleanup R3 to R9 land in any order), and resolve any conflict by keeping the cleanup's deletion. Plan 3 depends on none of the code the cleanup deletes and edits only its own lines beside it [pf 3.3]. Code tasks check amadan #404 before Task 1. |
| + |
| +Each task's header says whether it gets a cross-model security or termination review (pre-flight §7). Reviewed: N1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 15, W1, W2. Not reviewed cross-model: 1 and 6 (pure composers, behind INV-5), 13 (console doors over provision checks), W3, 16. |
| |
| ## Review dispositions (Astra R1) |
| |
| -Findings in `CODEX-FINDINGS-ROOTFS-PLANS-R1.md` that this plan owns, each checked against the code at 3dff2214 before it was accepted. |
| +Findings in `CODEX-FINDINGS-ROOTFS-PLANS-R1.md` that this plan owns, each checked against the code at 3dff2214 before it was accepted. The citations in this section are as read then; the task text carries main's. |
| |
| - **1. Accepted (Plan 3 side).** Verified: `cmdUnit.Poll` asks `Control.CmdStatus`, whose handler reads `UnitName(RoleCmd, host)` (`internal/instancectl/cmd.go:129`); `StopAndSettle` stops `RoleCmd` through the binary `Stop` and waits on `UnitName(role, host)`'s cgroup (`cmdunit.go:256`, `backend_exec.go:1656`), while `CmdRootfs` starts `RootfsUnitName(RoleCmd, host)`. A running release read as `gone` and its stop proved the wrong unit. Changed: A8 consumes Plan 2's runtime-aware cmd unit; Tasks 10 and 12 return it for every rootfs command; the backend tests of both tasks now go through the real `instancectl.Server` handler and client (Task 10's `rootfsCtlHarness`) with a running rootfs cmd unit and no binary one, in place of the scripted `CmdStatus` fake. |
| - **2. Accepted.** Verified: the sweep's lease check runs only for `actAwake` entries (`activator.go:4563`), a cold wake's entry is `actWaking`, and a failed renewal closes `Held.Lost()` (`internal/lease/health.go:51`) without cancelling the wake's context; during a swap the sweep sees the loss only at the safety deadline and then stops on a 2 min bound, past the lease's 5 s margin. Changed: `runRelease` takes the held lease (`leaseWatch`: the wake's `Lease`, or `e.rep` in a swap) and the site's ownership gate; the gate runs before the start and again immediately before `CmdRootfs`; a supervisor stops the release and proves it gone when the lease reports loss or comes within `releaseStopLead` of `SafeUntil`; the end is an ownership end (`errReleaseLeaseLost`), never the build's failure. New tests for lease loss during a cold-wake migration, during a swap's migration, and for stalled renewals (Tasks 10 and 11). New event RFS-3-C29. |
| @@ -22,139 +56,169 @@ Findings in `CODEX-FINDINGS-ROOTFS-PLANS-R1.md` that this plan owns, each checke |
| |
| ### Cross-plan changes |
| |
| -Names this plan now needs from Plan 2 (the orchestrator checks Plan 2 provides them; where Plan 2 names one differently, this plan uses Plan 2's name): |
| +Plan 2 has merged, and provides every name below as built; this plan uses main's forms. |
| |
| -- **Runtime-aware cmd unit (finding 1).** For a rootfs row, the `cmdUnit` polls and stops the rootfs cmd unit and nothing else. Plan 2's fix round (its Tasks 5 and 9) names these, and this plan uses them as named there: |
| - - `RootfsControl.CmdStatusRootfs(ctx, host, invocation string) (instancectl.CmdStatus, error)`: the `runtime=rootfs` status read, whose handler reads `RootfsUnitName(RoleCmd, host)` and takes no `image`. Today's `handleCmdStatus` (`internal/instancectl/cmd.go:113`) reads only `UnitName(RoleCmd, host)`. |
| - - `cmdUnit.Poll` and `cmdUnit.StopAndSettle` dispatching on `rt.Runtime` themselves: `Poll` through `CmdStatusRootfs`; `StopAndSettle` through `RootfsControl.StopRootfs(ctx, host, instancectl.RoleCmd, 0, "")`, then `waitRoleCgroupEmpty(ctx, rt, RoleCmd)` made runtime-aware through `unitNameFor(rt, RoleCmd, 0)`. So this plan's `startCmdUnit` builds `&cmdUnit{b: b, rt: rt, inv: inv, out: out, errs: errs}` for a rootfs row exactly as for a binary one, including the invocation-less unit a failed start returns. |
| -- **Lease seams (finding 2).** None from Plan 2. This plan adds `SafeUntil` and `Lost` to `execLease` (forwarding `*lease.Held`); `*lease.Replicator` already has both (`internal/lease/lease.go:466`, `:470`). |
| -- **Placeholder database (finding 8).** None from Plan 2. Plan 2's `rootfsVars` already sets `CARLOS_DB` to the nested path this plan's placeholder sits at. |
| +- **Runtime-aware cmd unit (finding 1).** For a rootfs row, the `cmdUnit` polls and stops the rootfs cmd unit and nothing else: |
| + - `RootfsControl.CmdStatusRootfs(ctx, host, invocation string) (instancectl.CmdStatus, error)` (`internal/activator/control.go:62`): the `runtime=rootfs` status read, whose handler reads `RootfsUnitName(RoleCmd, host)` (`internal/instancectl/cmd.go:148-150`). |
| + - `cmdUnit.Poll` (`cmdunit.go:260`) and `cmdUnit.StopAndSettle` (`cmdunit.go:276`) dispatch on `rt.Runtime` themselves: `Poll` through `CmdStatusRootfs`; `StopAndSettle` through `stopRole` (`unitproc.go:165`, which asks `StopRootfs` for a rootfs row) and `waitRoleCgroupEmpty(ctx, rt, RoleCmd)` (`backend_exec.go:1670`, runtime-aware through `unitNameFor`, `unitproc.go:146`). So this plan's `startCmdUnit` builds `&cmdUnit{b: b, rt: rt, inv: inv, out: out, errs: errs}` for a rootfs row exactly as for a binary one, including the invocation-less unit a failed start returns. |
| +- **Lease seams (finding 2).** None from Plan 2. This plan adds `SafeUntil` and `Lost` to `execLease` (forwarding `*lease.Held`, `internal/lease/lease.go:237-241`); `*lease.Replicator` already has both (`lease.go:476`, `:480`). |
| +- **Placeholder database (finding 8).** None from Plan 2. Plan 2's `rootfsVars` (`rootfs.go:83`) already sets `CARLOS_DB` to the nested path this plan's placeholder sits at. |
| |
| ## Review dispositions (Astra R2) |
| |
| Findings from `CODEX-FINDINGS-ROOTFS-PLANS-R2.md` that touch this plan, checked against the plans and the code first. |
| |
| -- **Finding 4: accepted (Plan 3 half).** Checked: Task 11's table runs `release` before `web` at every site, through `StartRelease` and `CmdRootfs`, and Plan 5's hook sat only in the binary `spawnUnitFrom`, so a migration could run before a fresh grant reached the slice and fail the build. `StartRelease` (Task 10 step 3), `StartRootfsWorker` and the rootfs `StartCmd` now carry an egress readiness slot before the pending record, the exec gate and root's call; Plan 5 Task 7 fills it and owns the ordering tests (`TestEveryRootfsLaunchWaitsForEgressReady`). Nothing else here changes: the release's timeout and lease supervision already cover the bounded wait. |
| -- **Finding 5 (consumer): taken in.** RFS-3-C28 stays live (deck status `pending`) until Plan 6 Task 16 marks it struck under Plan 1 Task 1's rule. |
| +- **Finding 4: covered by #328's root-side Assert [pf 2.5].** The first disposition gave `StartRelease`, the worker start and the rootfs `StartCmd` an agent-side egress readiness slot for Plan 5 Task 7 to fill. Plan 5 is withdrawn (index, "Coordination with #328/#329"), and #328's check lives on root's side: in `startRootfs` (`internal/instancectl/rootfs.go:762`, covering `/start` for web and workers) and in `startRootfsCmd` (`:1093`, covering release and run). So every agent-side egress slot and `TestEveryRootfsLaunchWaitsForEgressReady` are struck; nothing here waits for egress. |
| +- **Finding 5 (consumer): taken in.** RFS-3-C28 stays live (deck status `approved`) until Plan 6 Task 16 marks it struck under Plan 1 Task 1's rule. |
| |
| -String IDs added: none. Changed: RFS-3-C28 (deck status `struck` back to `pending`; text unchanged). |
| +String IDs added: none. Changed: RFS-3-C28 (deck status `struck` back to live; text unchanged). |
| |
| ## Contract deviations |
| |
| Each is decided here and proposed for the index's "Where the code differs from the spec" list. |
| |
| - **D1. "The same environment as web" (index, Environment).** Every rootfs process gets the instance's file environment, `CARLOS_DB`, `CARLOS_HOST`, `CARLOS_REGION`, `CARLOS_ADMIN_TOKEN` and the instance key, exactly as `web` does. Two refinements, because a value cannot be the same for processes with different lives: |
| - - `CARLOS_SOCKET` is the generation's own socket for `web` (where it must bind; with generations on that is `g<n>/app.sock`, not the route's socket). Workers, `release` and `carlos run` get the route's canonical socket, `rt.Socket`, which the activator links to whichever generation is serving (`swapCanonicalLink`, `internal/activator/activator.go:1907`). A worker that calls `web` then reaches the serving one after a swap, and `release` never names a socket nothing will bind. |
| + - `CARLOS_SOCKET` is the generation's own socket for `web` (where it must bind; with generations on that is `g<n>/app.sock`, not the route's socket). Workers, `release` and `carlos run` get the route's canonical socket, `rt.Socket`, which the activator links to whichever generation is serving (`swapCanonicalLink`, `internal/activator/canonlink.go:35`, called at `activator.go:1929`). A worker that calls `web` then reaches the serving one after a swap, and `release` never names a socket nothing will bind. |
| - `release` and `carlos run` do not get `CARLOS_CONTROL_SOCKET` or `CARLOS_PURGE`, the rule the run design already set for the cmd unit (`cmdVars`, `internal/activator/cmdunit.go:124`): their life is not tied to a listener's. Workers keep both: they are handed over with the generation whose listener they name. |
| - **D2. Rootfs rows need the rollout scheduler.** C8 ("never stops the old one under overlap") only holds where the overlap scheduler runs (`internal/rollout/policy.go:23`). Without it the box "restarts instances the old way", which is stop-then-start, and a failing `release` would take the app down. So a rootfs row starts only where generations are on and the scheduler armed (`Service.ArmRootfs`, Task 7), and refuses elsewhere with a reason in `carlos logs`. Settled in the index (decision 4): Plan 2 carries the configured half (`RootfsBoxFacts.OverlapSwaps`, part of `host.RootfsBoxReady` and so of `rootfs_ready`), so the console never places a rootfs row where it would refuse; this plan's `ArmRootfs` is the runtime half (the scheduler has actually armed this boot). |
| -- **D3. No "release done" column.** `release` is due when the build about to start is not the row's good build (`GoodVersion`/`GoodDigest`, written only by the scheduler once a build has served, `internal/registry/registry.go:2427`). With D2 the scheduler always runs, so the good build is always maintained. A restart or config attempt re-runs the serving build and never re-runs `release`. A build whose `release` passed but whose `web` then failed runs `release` again at its next attempt, which spec §5.2.1 ("the next deploy tries again") allows. |
| -- **D4. `carlos run` on fleet boxes is refused until Plan 6 lands, then goes through Plan 6's door (Paul's ruling R7).** A fleet box reaches the bucket only through the fleet store door, which lets it write neither instance records nor `runs/` objects (`aclWrite`, `internal/edge/storedoor.go:530`). The run protocol needs both: the pickup is a CAS on the record, and output is chunks under `runs/<id>/out/`. Paul ruled (2026-10-24) that a run on a fleet box is carried over Plan 6's box-dials-the-console door: the box dials the console per run on a signed grant, and the console makes the record and `runs/` writes for it (Plan 6 Task 16). Until then this plan makes `carlos run` and `--version` work on rootfs rows on every box that is not a fleet box (a single-tenant deployment's boxes), and keeps today's fleet refusal message (`internal/console/apiruns.go:66`) for every record. Plan 6 Task 16 removes that refusal. |
| -- **D5. Seeds and imports are not offered for rootfs records in v1** (spec §5.5 leaves seeds to the builder). `ValidateShape` refuses `Seed` on a rootfs record, and a rootfs row never carries the manifest's seed argv, which is a binary's `<argv> --db` (`seedArgv`, `internal/activator/backend_exec.go:943`). |
| +- **D3. No "release done" column.** `release` is due when the build about to start is not the row's good build (`GoodVersion`/`GoodDigest`, written only by the scheduler once a build has served, `registry.SetGoodBuild`, `internal/registry/registry.go:2657`). With D2 the scheduler always runs, so the good build is always maintained. A restart or config attempt re-runs the serving build and never re-runs `release`. A build whose `release` passed but whose `web` then failed runs `release` again at its next attempt, which spec §5.2.1 ("the next deploy tries again") allows. |
| +- **D4. `carlos run` on fleet boxes is refused until Plan 6 lands, then goes through Plan 6's door (Paul's ruling R7).** A fleet box reaches the bucket only through the fleet store door, which lets it write neither instance records nor `runs/` objects (`aclWrite`, `internal/edge/storedoor.go:530`). The run protocol needs both: the pickup is a CAS on the record, and output is chunks under `runs/<id>/out/`. Paul ruled (2026-10-24) that a run on a fleet box is carried over Plan 6's box-dials-the-console door: the box dials the console per run on a signed grant, and the console makes the record and `runs/` writes for it (Plan 6 Task 16). Until then this plan makes `carlos run` and `--version` work on rootfs rows on every box that is not a fleet box (a single-tenant deployment's boxes), and keeps today's fleet refusal message (`internal/console/apiruns.go:280`) for every record. Plan 6 Task 16 removes that refusal. |
| +- **D5. Seeds and imports are not offered for rootfs records in v1** (spec §5.5 leaves seeds to the builder). `ValidateShape` refuses `Seed` on a rootfs record, and a rootfs row never carries the manifest's seed argv, which is a binary's `<argv> --db` (`seedArgv`, `internal/activator/backend_exec.go:967`). |
| - **D6. A rootfs record is never a replica, never pooled.** `ValidateShape` refuses `Role`, `Replicas` and `Pool` on it. Pools do not qualify in v1 (index, Box facts). A replica is a second copy of an account's data, which the stateless-replicas design owns (spec §12). |
| - **D7. The platform creates the empty SQLite file (spec §5.6, B1-4: "the platform replicates an empty file").** A binary app creates its database when it boots; a rootfs app whose data lives elsewhere never does, and litestream replicates nothing for a file that does not exist, so after its first serve the row would read as "served, no database, no replica" and Task 7's refusal would stop every restart (Astra R1 finding 8). So on a rootfs first boot (`Restore` fresh, `GoodVersion == ""`) the agent places an empty SQLite database at `CARLOS_DB` under the first-wake lease, before `release` and `web`, and the wake syncs it to the replica once replication starts. An app that does use SQLite opens an existing, empty database: WAL mode, default page size, no tables. To an ordinary SQLite client (Rails' adapter included) that is the same as a missing file, except for an app that sets a non-default `page_size` before its first table, which then keeps the default. |
| +- **D8. Workers may land after the rest [pf 6.1].** Group A runs every rootfs process but workers. Until Group W lands, a build that declares workers serves `web` and logs once per wake that this box does not run workers yet (a diagnostic, Task 11). Plan 4 depends on Group W (index), because its sample app may declare workers. |
| |
| ### What this plan assumes from Plans 1 and 2 beyond the contract |
| |
| -Each is a name this plan consumes. When Plan 1 or 2 merges, the implementer checks each against `main` and, where Plan 2 named it differently, uses Plan 2's name. Where a seam is missing, the task that needs it adds it with the signature given. |
| +Each is a name this plan consumes, checked against main at the amendment (a912a342). Where a seam is missing, the task that needs it adds it with the signature given. |
| |
| -- **A1 (Plan 1).** The copy gate is `approved_rootfs_copy_test.go`, with an inventory and a built list (named there `rootfsCopyIDs`, `rootfsCopyBuilt`) that accept `RFS-3-C` ids. |
| -- **A2 (this plan, on Plan 2's staging).** A staged rootfs version's process declaration is read from the root-written staged manifest beside its image (`release.ReadStagedManifest`, `internal/release/versions.go:261`; Plan 2 deviation 3 puts the image at `release.VersionPath`): `ExecBackend.Processes(id release.StagedIdentity) (map[string]release.Process, error)`, added by Task 9 in `backend_rootfs.go`. Plan 2 does not provide it. Plan 3 never reads a manifest from tenant-writable ground. |
| -- **A3 (Plan 2).** The rootfs launch file carries the process to run by name and never an argv: `instancectl.Launch{Schema: LaunchSchemaRootfs, Runtime: registry.RuntimeRootfsV1, Process: <name>, Env}` with `Argv` empty (the trampoline refuses a tenant argv, Plan 2 Task 6). The control service resolves the command from the staged manifest (spec C4) into root's `RootfsLaunch`. A member's `carlos run -- <args>` reaches root as `instancectl.StagedImage.Argv` in the `/cmd` request body, and the tenant launch file then names `Process: "cmd"`; root resolves `Argv[0]` against the image's `PATH`. |
| -- **A4 (Plan 2).** Worker units: `instancectl.WorkerUnitName(host, name)` (instance string `WorkerInstance(iid, name)`), a per-worker launch file `instancectl.WorkerLaunchFileName(name)`, a per-worker log socket `instancectl.WorkerLogSocket(host, name)`, exit records `WorkerExitRecordName(name, inv)`, and the control-client pair on Plan 2's `activator.RootfsControl`: `StartRootfsWorker(ctx, host, name string, memoryMax int64, img instancectl.StagedImage) (string, error)` and `StopRootfs(ctx, host, instancectl.RoleWorker, 0, name) error`. |
| -- **A5 (Plan 2).** For a rootfs row, `ExecBackend.BuildIdentity` and `LiveIdentity` name the staged image (it sits at `VersionPath`), `Start` and `StartGenExe` dispatch to Plan 2's `startRootfs`, and a one-off command from an image goes through `RootfsControl.CmdRootfs(ctx, host, memoryMax, img instancectl.StagedImage) (string, error)`, never `CmdExe`. This plan adds `stagedImageOf(id release.StagedIdentity, process string, argv []string) instancectl.StagedImage` (`Path: id.StagedPath, Version: id.Version, Digest: id.Digest`) beside `stagedExeOf`. |
| -- **A6 (Plan 2).** The rootfs `web` start is Plan 2's own function, `(*ExecBackend).startRootfs` in `internal/activator/rootfs.go`, not a branch of `spawnUnitFrom`; it composes the web environment with Plan 2's `rootfsVars(vars map[string]string, sock, dbPath string) map[string]string`. The 120 s health bound is Plan 2's `rootfsHealthTimeout` (from `release.RootfsHealthTimeout`); this plan adds `healthBoundFor(rt registry.Route) time.Duration` (Task 7: `rootfsHealthTimeout` for a rootfs row, `spawnHealthTimeout`, 30 s, otherwise). The tier is Plan 2's `rootfsTier`, `cgroup.TierChildren` (R9). |
| -- **A7 (Plan 2).** The box-side placement refusal (`host.RootfsPlacementAllowed`) runs on every rootfs start. Plan 3 adds no placement check of its own. |
| -- **A8 (Plan 2, Astra R1 finding 1).** The cmd unit of a rootfs row is polled, stopped and proven gone as `RootfsUnitName(RoleCmd, host)`, never as the binary `carlos-instance-cmd@`: Plan 2's runtime-aware `cmdUnit`: `Poll` through `RootfsControl.CmdStatusRootfs`, `StopAndSettle` through `StopRootfs(ctx, host, RoleCmd, 0, "")` and then that unit's cgroup proven empty (`waitRoleCgroupEmpty` through `unitNameFor`), both chosen from `rt.Runtime` (names under "Cross-plan changes"). Every `CmdUnit` this plan returns for a rootfs row (Task 10's release, Task 12's run) is that unit, and each task's backend tests go through the real control handler (Task 10's `rootfsCtlHarness`), not a scripted `CmdStatus`. |
| +- **A1 (Plan 1).** The copy gate is `approved_rootfs_copy_test.go`, with an inventory, a struck list and a built list (`rootfsCopyIDs`, `rootfsCopyStruck`, `rootfsCopyBuilt`) that accept `RFS-3-C` ids. |
| +- **A2 (this plan, on Plan 2's staging).** A staged rootfs version's process declaration is read from the root-written staged manifest beside its image (`release.ReadStagedManifest(optDir, acct, ver, app)`, `internal/release/versions.go:264`; Plan 2 deviation 3 puts the image at `release.VersionPath`): `ExecBackend.Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error)`, added by Task 10 in `backend_rootfs.go`. `StagedIdentity` names no account or app (`internal/release/staged.go:20-25`), so it takes the row [pf 1.9]. It refuses unless `m.IsRootfs()` and `m.BoxArtifact(platform).SHA256 == id.Digest` (Plan 2's E1 lesson: a manifest read must belong to the image it names). Plan 3 never reads a manifest from tenant-writable ground. |
| +- **A3 (Plan 2).** The rootfs launch file carries the process to run by name and never an argv: `instancectl.Launch{Schema: LaunchSchemaRootfs, Runtime: registry.RuntimeRootfsV1, Process: <name>, Env}` with `Argv` empty (the trampoline refuses a tenant argv), written by `writeRootfsLaunchFor(p, role, gen, host, process, env []string)` (`prepare.go:283`), its env always `rootfsLaunchEnv(vars)` (`rootfs.go:93`), never `childEnv` [pf 1.6]. The control service resolves the command from the staged manifest (spec C4) into root's `RootfsLaunch`. A member's `carlos run -- <args>` reaches root as `instancectl.StagedImage.Argv` in the `/cmd` request body, and the tenant launch file then names `Process: "cmd"`; root resolves `Argv[0]` against the image's `PATH`. |
| +- **A4 (Plan 2, consumed by Group W only).** Worker units: `instancectl.WorkerUnitName(host, name)` (instance string `WorkerInstance(iid, name)`), a per-worker launch file `instancectl.WorkerLaunchFileName(name)` (the trampoline reads it, `internal/instanceexec/exec.go:174`), a per-worker log socket `instancectl.WorkerLogSocket(host, name)`, exit records `WorkerExitRecordName(name, inv)`, and the control-client pair on `activator.RootfsControl` (`control.go:55`, `:58`): `StartRootfsWorker(ctx, host, name string, memoryMax int64, img instancectl.StagedImage) (string, error)` and `StopRootfs(ctx, host string, role instancectl.Role, gen uint64, worker string, kill bool) error` [pf 1.3]. The agent side of a worker is unbuilt on main [pf 1.4]; W1 builds it. |
| +- **A5 (Plan 2).** For a rootfs row, `ExecBackend.BuildIdentity` (`backend_exec.go:1842`) and `LiveIdentity` (`:1793`) name the staged image (it sits at `VersionPath`), `Start` and `StartGenExe` dispatch to Plan 2's `startRootfsGen` (`rootfs.go:189`), and a one-off command from an image goes through `RootfsControl.CmdRootfs(ctx, host, memoryMax, img instancectl.StagedImage) (string, error)` (`control.go:59`), never `CmdExe`. `StartStaged` has no rootfs arm on main; Task N1 adds it [pf 1.1]. `CmdRootfs` types only a 403 (`internal/instancectl/client.go:484-506`); Task N1 types the rest [pf 1.7]. Task 10 adds `stagedImageOf(id release.StagedIdentity, process string, argv []string) instancectl.StagedImage` (`Path: id.StagedPath, Version: id.Version, Digest: id.Digest`) beside `stagedExeOf` (`identity.go:98`). |
| +- **A6 (Plan 2).** The rootfs `web` start is Plan 2's own function, `(*ExecBackend).startRootfs` in `internal/activator/rootfs.go:227`, not a branch of `spawnUnitFrom`; it composes the web environment with Plan 2's `rootfsVars(vars map[string]string, sock, dbPath string) map[string]string` (`rootfs.go:83`). The 120 s health bound is Plan 2's `rootfsHealthTimeout` (`rootfs.go:40`, from `release.RootfsHealthTimeout`); Task N1 adds `healthBoundFor(rt registry.Route) time.Duration` (`rootfsHealthTimeout` for a rootfs row, `spawnHealthTimeout`, 30 s, otherwise) and uses it wherever a successor's health is bounded [pf 1.2]. The tier is answered by `b.tier(rt)` (`backend_exec.go:434`) and `GenTier` (`genbackend.go:283`), whose base for a rootfs row is Plan 2's `rootfsTier` (`cgroup.TierChildren`, R9) and which #328 wraps with `SizedLimit` (`rootfs.go:42-47`). Plan 3 code never reads `rootfsTier` directly [pf 1.8]. |
| +- **A7 (Plan 2).** The box-side placement refusal (`host.RootfsPlacementAllowed`) runs on every rootfs start, inside Plan 2's `rootfsGates` (`rootfs.go:128-162`). Plan 3 adds no placement check of its own; Task 7 asks the same gates earlier, before the lease [pf 2.1]. |
| +- **A8 (Plan 2, Astra R1 finding 1).** The cmd unit of a rootfs row is polled, stopped and proven gone as `RootfsUnitName(RoleCmd, host)`, never as the binary `carlos-instance-cmd@`: Plan 2's runtime-aware `cmdUnit` (names under "Cross-plan changes"). Every `CmdUnit` this plan returns for a rootfs row (Task 10's release, Task 12's run) is that unit, and each task's backend tests go through the real control handler (Task 10's `rootfsCtlHarness`), not a scripted `CmdStatus`. |
| |
| ## Global Constraints |
| |
| - Values from the spec and the index, verbatim: `release` timeout default 600 s, at most the `carlos run` maximum (`runs.MaxTimeout`, 6 h); at most 4 workers, names `^[a-z][a-z0-9-]{0,15}$` (`release.ValidWorkerName`); health bound for rootfs `web` 120 s; runtime values `""` and `"rootfs-v1"`, anything else refuses before materialization or start. |
| - Residency (always-awake design, adopted by spec §5.6): poll every 2 s; per-host backoff 1, 2, 4, 8, 16, 32, then 60 s, with 0 to 20% positive jitter; a run healthy for 60 s resets the count; at most 4 proactive starts in flight on a box; a request never bypasses the backoff. Never approximated with timers, dummy requests or a huge idle window. |
| -- Worker restart pacing is the co-spawn sidecar's: `sidecarRestartBase` 2 s doubling to `sidecarRestartMax` 60 s, reset after `sidecarHealthyRun` 60 s (`internal/activator/activator.go:779`). |
| +- 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). |
| +- 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]. |
| - 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. |
| - Tests: locally only the touched packages, `go test ./internal/<pkg>/ -run 'TestX|TestY' -count=1`; CI runs the full suite. Leave `GOCACHE` at its default. Socket tests need a short `TMPDIR` (the repo's recipe: a short directory the runner creates and removes by name). Race-bearing tests are named in their task and run once with `-race` before the task's commit. New `internal/host` tests call `t.Parallel()` unless they set env, cwd, umask, log output or package vars. |
| -- Census: Task 2 changes registry reads that root performs. If `TestPlan14RootReadCensus` (`internal/provision/plan14_root_reads_test.go`) fails, re-pin through the census overlay recipe and post the proposal on amadan #280; the branch waits for that ruling like every other. |
| -- A box with host lifecycle claim control armed (`Config.HostWrites.Enabled`; instancectl answers 503 to every legacy route, `claimAwareLegacy`, `internal/instancectl/server.go:1066`) refuses every rootfs start, worker, `release` and run, with the reason in `carlos logs` (Task 7). Supporting it belongs to the claim's activation (#250), which must add `worker` and the rootfs cmd to the reservation protocol beside `main`, `seed`, `sidecar` and `cmd`. |
| +- No census task: main's census runs at merge (Paul, 2026-10-25) [pf 4.1]. The two invariants the census stood in for are tests: root reads SQLite only through the service-user child (Task 15), and Plan 3's diff touches no `internal/instancectl` file except `client.go` (gate A) [pf 4.2]. |
| +- Claims: host lifecycle claims are shelved. Plan 3 adds no reader of `Config.HostWrites` [pf 3.1]. While the switch exists, Plan 2's `rootfsGates` still refuses under it (`rootfs.go:155`), and Task 7's early gate inherits that, so nothing goes unrefused. |
| - Commits end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. |
| |
| ## Review Focus |
| |
| -1. **A console older than this series rewrites a rootfs record and drops `runtime`.** An old binary's `UpdateRecord` re-marshals its own struct. The new `WriteRecord` guard cannot stop an old binary, so the box must: the row keeps `runtime` and its hibernation, the pass logs the mismatch, and nothing is converged or retired. Test: Task 4, `TestStrippedRecordLeavesRootfsRowAlone`. |
| +1. **A console older than this series rewrites a rootfs record and drops `runtime`.** An old binary's `UpdateRecord` re-marshals its own struct. The new `WriteRecord` guard cannot stop an old binary, so the box must: the row keeps `runtime` and its hibernation, the pass logs the mismatch, and nothing is converged or retired. Tests: Task 4, `TestStrippedRecordLeavesRootfsRowAlone`; Task 2, `TestUpsertKeepsRootfsHibernation` (a full-row `Upsert`, such as `carlos add`'s, keeps it too). |
| 2. **The agent restarts while a `release` is running.** The cmd unit dies with the edge (`BindsTo`), the row's good build is unchanged, and the next start must run `release` again rather than start `web` on a half-migrated database. Test: Task 11, `TestReleaseRerunsAfterInterruptedWake`. |
| -3. **A declared worker that exits 0 at once** (a one-shot mistaken for a worker) must be restarted with backoff and reach the crash-loop state, never parked as finished, and `web` must not notice. Test: Task 9, `TestCleanExitingWorkerIsRestartedNotParked`. |
| +3. **A declared worker that exits 0 at once** (a one-shot mistaken for a worker) must be restarted with backoff and reach the crash-loop state, never parked as finished, and `web` must not notice. Test: W1, `TestCleanExitingWorkerIsRestartedNotParked`. |
| 4. **A resident that has served loses its local database and its replica is missing.** It must refuse to start rather than boot an empty database a member would read as data loss. Test: Task 7, `TestServedRootfsNeverBootsEmpty`. |
| 5. **A request storm against a crash-looping resident.** Requests must get 503 with `Retry-After` during the backoff, coalesce on one wake, and never start a second. Test: Task 8, `TestResidentRequestsCannotBypassBackoff` and `TestResidentRequestAndTickRaceOneWake` (race). |
| 6. **The box loses the instance's lease while a migration runs (C7).** On a cold wake the entry is `actWaking`, which the sweep's lease check skips, so `runRelease`'s own supervisor must stop the release and prove its unit gone before the lease's safety deadline, and the wake must start nothing after it. Tests: Task 10, `TestReleaseStopsBeforeTheSafetyDeadline`; Task 11, `TestColdWakeReleaseStopsOnLeaseLoss` and `TestSwapReleaseStopsOnLeaseLoss`. |
| 7. **A rootfs command's unit is the rootfs cmd template's (finding 1).** A running release or run must read as running, and its stop must prove the rootfs unit's cgroup empty, through the real control handler with no binary cmd unit present. Tests: Task 10, `TestReleasePollsTheRootfsCmdUnit` and `TestReleaseStopProvesTheRootfsCmdUnitGone`; Task 12, `TestRootfsRunPollsAndStopsTheRootfsUnit`. |
| 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). |
| |
| --- |
| |
| ## File structure |
| |
| -| path | responsibility | |
| -|---|---| |
| -| `internal/registry/runtime.go` (new) | `Route.Rootfs`, `ActivatorOwned`, `Resident`, `ErrRuntimeFixed` (Plan 2 owns `RuntimeRootfsV1`, `ValidRuntime` and the column) | |
| -| `internal/registry/registry.go` | `Upsert`'s replication arm, `normalizeRoute`, `SetHibernate`'s refusal, `ResidentInstances` | |
| -| `internal/registry/remote_dispatch.go` | `ResidentInstances` over the remote registry | |
| -| `internal/provision/runtime.go` (new) | `RuntimeRootfsV1` alias, `RuntimeFromManifest`, `ErrRuntimeProtected`, `runtimeFixed`, `RootfsMoveError`, `rootfsMoveRefusal` | |
| -| `internal/provision/provision.go`, `record_sequence.go`, `offline_move.go` | `Record.Runtime`, `ValidateShape`'s rails, `CreateRecord`, `WriteRecord`'s guard, the move refusals | |
| -| `internal/provision/reconcile.go` | `RouteFor`, `everywhereClass`, `everywhereRoute`, `shapeMismatch`, the owned arm | |
| -| `internal/activator/layout.go`, `wakeidentity.go`, `activator.go` | `ActivatorManaged` and the serve gates on the shared predicate; the idle exemption; the residency hooks; worker and release hooks in wake, stop and sweep | |
| -| `internal/activator/rootfs_service.go` (new; Plan 2 owns `rootfs.go`) | start gates, `ArmRootfs`, `healthBoundFor`, wake ceiling, first-wake budget, residency state and `rootfsTick` | |
| -| `internal/activator/rootfsenv.go` (new) | `rootfsWorkerVars`, `rootfsCmdVars` (on Plan 2's `rootfsVars`) | |
| -| `internal/activator/rootfsworkers.go` (new) | worker lifecycle, supervision, handover, stop proof, `RootfsWorkers` | |
| -| `internal/activator/backend_rootfs.go` (new) | `ExecBackend.Processes`, `StartRootfsWorker`, `RootfsWorkerGone`, `StartRelease`, `ReleaseEnv`, `stagedImageOf` | |
| -| `internal/activator/rootfsrelease.go` (new) | `releaseDue`, `releaseTimeout`, `ReleaseError`, `leaseWatch`, `Service.runRelease` and its lease supervisor | |
| -| `internal/activator/rootfsdb.go` (new) | `ExecBackend.PlaceRootfsDB`, the empty SQLite database of D7 | |
| -| `internal/activator/backend_exec.go` | `execLease.SafeUntil`, `execLease.Lost` (forwarding `*lease.Held`) | |
| -| `internal/activator/rootfs_ctl_harness_test.go` (new) | `rootfsCtlHarness`: the real `instancectl.Server` handler and client behind an `ExecBackend` (Tasks 10, 12) | |
| -| `internal/activator/cmd.go`, `cmdunit.go`, `swap.go`, `swaphold.go`, `wakeplan.go`, `opset.go`, `generations_file.go`, `prepare.go` | release and run integration, the stop proof, the generations pins | |
| -| `internal/edge/edge.go`, `internal/ops/litestream.go`, `internal/ops/hibernate_verify.go`, `internal/rollout/policy.go`, `internal/host/socket_advice.go`, `internal/host/probes.go`, `internal/host/schedule_wiring.go`, `internal/layout/pass.go` | the consumer inventory (Task 5) | |
| -| `internal/rollout/events.go`, `status.go`, `manager.go`; `internal/rolloutwords/words.go`; `internal/status/snapshot.go` | reason words, events, `HostRollout.Workers` | |
| -| `internal/host/rollout.go`, `runexec.go`, `runevents.go`, `systemapply.go` | `ArmRootfs` wiring, the run refusal, the rollback floor | |
| -| `internal/runs/runs.go`, `internal/console/apiruns.go`, `run.go` | `--version` | |
| -| `internal/console/seedmove.go`, `apiinstancemove.go`, `apiinstancemove_offline.go`, `fleets.go` | the move doors' rootfs refusal | |
| -| `docs/site/cli.md` | `carlos run` on rootfs rows and `--version` | |
| +| path | responsibility | task | |
| +|---|---|---| |
| +| `internal/activator/rootfs_invariants_test.go` (new) | the INV-1, INV-2, INV-4 guards and INV-5's launch-env table | 1, rows added by 6, 10, 12, W1 | |
| +| `internal/activator/binary_golden_test.go`, `testdata/binary_golden/` (new) | INV-6's binary goldens | 1 | |
| +| `internal/registry/runtime.go` (new) | `Route.Rootfs`, `ActivatorOwned`, `Resident`, `ErrRuntimeFixed` (Plan 2 owns `RuntimeRootfsV1`, `ValidRuntime` and the column) | 2 | |
| +| `internal/registry/registry.go`, `remote.go`, `remote_dispatch.go` | `Upsert`'s hibernate and replication arms, `normalizeRoute`, `SetHibernate`'s refusal, `ResidentInstances`; `ErrRuntimeFixed` over the remote registry | 2 | |
| +| `cli.go` | `carlos add` refuses an existing rootfs host (a diagnostic) | 2 | |
| +| `internal/provision/runtime.go` (new) | `RuntimeRootfsV1` alias, `RuntimeFromManifest`, `ErrRuntimeProtected`, `runtimeFixed`, `RootfsMoveError`, `rootfsMoveRefusal` | 3, 13 | |
| +| `internal/provision/provision.go`, `record_sequence.go`, `offline_move.go` | `Record.Runtime`, `ValidateShape`'s rails, `WriteRecord`'s guard, the move refusals | 3, 13 | |
| +| `internal/provision/reconcile.go` | `RouteFor`, `everywhereClass`, `everywhereRoute`, `shapeMismatch`, the owned arm | 4 | |
| +| `internal/activator/layout.go`, `wakeidentity.go`, `activator.go` | `ActivatorManaged` and the serve gates on the shared predicate; the idle exemption; the residency hooks; release hooks in wake, stop and sweep | 5, 7, 8, 11 | |
| +| `internal/release/pins.go` | `BuildStateKept` on `ActivatorOwned` | 5 | |
| +| `internal/activator/rootfsenv.go` (new) | `rootfsCmdVars` (Task 6), `rootfsWorkerVars` (W1), on Plan 2's `rootfsVars` | 6, W1 | |
| +| `internal/activator/genbackend.go`, `swap.go`, `wakeplan.go`, `backend_exec.go` | `StartStaged`'s rootfs arm; `KillHost`/`EmptyHost` refuse rootfs; the health bound in `genHealthy` and the verdict floor; `HasSidecar` false for rootfs | N1 | |
| +| `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/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 | |
| +| `internal/edge/edge.go`, `internal/ops/litestream.go`, `internal/ops/hibernate_verify.go`, `internal/rollout/policy.go`, `internal/host/socket_advice.go`, `internal/host/probes.go`, `internal/host/schedule_wiring.go`, `internal/layout/pass.go` | the consumer inventory | 5 | |
| +| `internal/rollout/events.go`; `internal/rolloutwords/words.go`; `internal/status/snapshot.go` | reason words, events | 10, 11 | |
| +| `internal/rollout/status.go`, `manager.go`; `internal/status/snapshot.go` | `HostRollout.Workers` | W3 | |
| +| `internal/host/rollout.go`, `runexec.go`, `runevents.go`, `systemapply.go` | `ArmRootfs` wiring, the run refusal, the rollback floor | 7, 12, 15 | |
| +| `internal/runs/runs.go`, `internal/console/apiruns.go`, `run.go`, `approved_run_copy_test.go` | `--version`; RUN-C47 superseded | 12 | |
| +| `internal/console/seedmove.go`, `apiinstancemove.go`, `apiinstancemove_offline.go`, `fleets.go` | the move doors' rootfs words | 13 | |
| +| `docs/site/cli.md` | `carlos run` on rootfs rows and `--version` | 12 | |
| |
| --- |
| |
| -### Task 1: Plan 3's rows in the copy deck, and Paul's review |
| +## Group A (Plan 3 merges after gate A) |
| + |
| +### Task 1: Plan 3's copy rows, and the invariant guards |
| |
| -No later task writes a string of this plan until this one has merged with the rows approved. |
| +**Review:** not cross-model (pre-flight §7). Its guards are what later reviews lean on, so the controller checks each guard's mutation evidence (Step 4). |
| + |
| +No later task writes a string of this plan until this one has merged with the rows approved, and no later task starts until the guards are green on its base. |
| |
| **Files:** |
| -- Modify (only for rows the series deck lacks): `docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md`, `approved_rootfs_copy_test.go` (`rootfsCopyIDs`) |
| +- Verify only: `docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md`, `approved_rootfs_copy_test.go` (the amendment already rewrote the RFS-3 file cells and struck RFS-3-C13 there, with `rootfsCopyStruck` [pf 8.3, 3.1]) |
| +- Create: `internal/activator/rootfs_invariants_test.go`, `internal/activator/binary_golden_test.go`, `internal/activator/testdata/binary_golden/` (golden files), `internal/activator/testdata/rootfs_verb_guard/` (guard fixtures) |
| |
| **Interfaces:** |
| -- Consumes: Plan 1 Task 1's gate (A1). |
| -- Produces: approved rows `RFS-3-C01`..`RFS-3-C29`; every later task appends the ids it writes to the gate's built list. (`RFS-3-C29` was added in the Astra R1 fix round, after the series review, so Step 2 brings it to the deck and Step 3 to Paul.) |
| +- Consumes: Plan 1 Task 1's gate (A1); main's activator as Plan 2 left it. |
| +- Produces: approved rows `RFS-3-C01`..`RFS-3-C29` less the struck C13; every later task appends the ids it writes to the gate's built list. The guards below, green on main. |
| + |
| +Plan 1 Task 1 assembled every plan's table into the series deck and Paul's review of the whole series came through it (approved 2026-10-24 by delegation, a Luna copy pass; see the deck header). The amendment of 2026-10-26 changed no text: it set each RFS-3 file cell to the bare path with the old cell as its note, because `copyRow.Path()` keeps backticks (`approved_moves_copy_test.go:122-127`) and the applied check would fail the first time a task built an RFS-3 id [pf 8.3]; and it struck C13 [pf 3.1]. |
| |
| -Plan 1 Task 1 assembles every plan's table into the series deck and gets Paul's review of the whole series in one pass (index, Copy). This task confirms this plan's rows came through it, the way Plan 6 Task 1 does. |
| +The guards (each passes on main and fails on a violation; fixtures prove each rejection, Plan 2's guard shape): |
| |
| -- [ ] **Step 1:** `grep -c '^| RFS-3-' docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md`. Expected: 29, every one `approved`. If so, skip to Step 4 with nothing to commit. |
| -- [ ] **Step 2:** For each row of this plan's table the deck lacks (a row added after the series review), append it in the deck's format, status `pending`, add its id to `rootfsCopyIDs`, and run `go test . -run 'TestRootfsCopy' -count=1` (PASS). |
| -- [ ] **Step 3:** (Note: the deck was approved by delegation on 2026-10-24 (Paul asked for a Luna copy pass instead of a string-by-string review; see the deck header), so the gate's approval step is satisfied; this step is for rows added after that date.) Invoke the `copy-review` skill on those rows only, wait for Paul's edits, apply them verbatim to the deck and to this plan's string table, and mark each row `approved`. Read `result.json` before any restart of the review server. |
| -- [ ] **Step 4:** Run the gate again (PASS); commit the deck and the gate if Step 2 changed them. |
| +- **`TestRootfsFilesNameNoBinaryVerb` (INV-1).** Loads `internal/activator` with types (`golang.org/x/tools/go/packages`, already in `go.mod`) and walks the non-test files matching `rootfs*.go` and `backend_rootfs.go`. Fails on any call or method value that resolves to a method of the binary `Control` interface named `Stop`, `StopGen`, `Cmd`, `CmdExe` or `CmdStatus` (and `cmdExeStarter.CmdExe`); on any reference to `KillHost`, `EmptyHost`, `hostKiller`, `hostEmptier`, `childEnv`, `openHostCleanup` or a `Cgroups` field's `OpenCleanup`. Resolution is by type, so `up.Stop` on a `*unitProc` (`rootfs.go:243`) passes and `ctl := b.Control; f := ctl.Stop` fails. Fixtures under `testdata/rootfs_verb_guard/`: a direct call, a method value, an alias through a local variable, `childEnv` in a launch, `KillHost` on a `SplitBackend`. |
| +- **`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. |
| +- **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. |
| + - `TestGenHealthyBoundBinary`: `genHealthy` (`swap.go:358`) and `verdictFloorGate` (`wakeplan.go:478`) on a binary row bound the wait by `spawnHealthTimeout` (`backend_exec.go:43`): with it shrunk, a socket that answers after the bound fails and one that answers before passes. |
| + - `TestKillHostBinaryGolden`: `KillHost` (`genbackend.go:583`) and `EmptyHost` (`:623`) on a binary row: an absent cgroup answers nil, a populated one is killed and emptied (the cgroup fake's call log). |
| + - `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 4:** Commit. |
| |
| ```bash |
| -git add docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md approved_rootfs_copy_test.go |
| -git commit -m "rootfs apps plan 3: copy rows RFS-3-C01..C29, approved" |
| +git add internal/activator/rootfs_invariants_test.go internal/activator/binary_golden_test.go internal/activator/testdata/ |
| +git commit -m "rootfs apps plan 3: invariant guards INV-1, 2, 4, 5 and the binary goldens (INV-6)" |
| ``` |
| |
| --- |
| |
| ### Task 2: The shared predicates over Plan 2's runtime column |
| |
| +**Review:** cross-model (pre-flight §7): registry semantics that root reads (runtime, hibernation, replication). |
| + |
| **Files:** |
| - Create: `internal/registry/runtime.go`, `internal/registry/runtime_test.go` |
| -- Modify: `internal/registry/registry.go`: `Upsert`'s `ON CONFLICT` replication arm (`:1179`); `normalizeRoute` (`:1228`); `SetHibernate` (`:2495`); `ResidentInstances` beside `AlwaysOnWorkers` (`:2559`). The column itself (`Route.Runtime`, the migration, `routeCols` at 56, `scanRoute`, `routeArgs`, Upsert's `runtime=routes.runtime` arm), `RuntimeRootfsV1` and `ValidRuntime` are Plan 2 Task 2's (index decision 1); this task consumes them. |
| -- Modify: `internal/registry/remote_dispatch.go` (`:284`, the `ResidentInstances` case) |
| -- Test: `internal/registry/registry_test.go` (`TestUpsertRoundTripsAllColumns`, `:64`) |
| +- Modify: `internal/registry/registry.go`: `Upsert`'s `ON CONFLICT` hibernate arm (`:1273`) and replication arm (`:1280`) (`Upsert` is `:1256`; `tenantChangedSQL` `:1253`); `normalizeRoute` (`:1321`); `SetHibernate` (`:2725`); `ResidentInstances` beside `AlwaysOnWorkers` (`:2789`). The column itself (`Route.Runtime`, the migration, `routeColCount` 61 at `:972`, `scanRoute`, `routeArgs`, Upsert's `runtime=CASE WHEN tenantChanged ...` arm at `:1299`), `RuntimeRootfsV1` and `ValidRuntime` are Plan 2 Task 2's (index decision 1); this task consumes them. |
| +- Modify: `internal/registry/remote.go:17` (`ErrRuntimeFixed` joins `remoteErrors`); `internal/registry/remote_dispatch.go` (the `ResidentInstances` case beside `AlwaysOnWorkers`, `:299`) |
| +- Modify: `cli.go` (`carlos add`, before its `Upsert` at `:333`): an existing rootfs host is refused with a diagnostic |
| +- Test: `internal/registry/registry_test.go` (`TestUpsertRoundTripsAllColumns`, `:65`); `internal/registry/remote_test.go`; `cli_add_rootfs_test.go` (new) |
| |
| **Interfaces:** |
| - Consumes: Plan 2's `registry.Route.Runtime`, `RuntimeRootfsV1`, `ValidRuntime`. |
| @@ -168,9 +232,12 @@ git commit -m "rootfs apps plan 3: copy rows RFS-3-C01..C29, approved" |
| ``` |
| |
| Rules the code must keep: |
| -- `Upsert` keeps `routes.runtime` on conflict (Plan 2's rule, pinned there by `TestUpsertNeverChangesRuntime`). A row's runtime changes only by deletion and a new mint. |
| -- The replication invariant becomes "a rung means the activator replicates": `normalizeRoute` clears `Replication` only when `!t.Hibernate && t.Runtime == ""`, and the conflict arm becomes `WHEN excluded.hibernate = 0 AND routes.runtime = '' THEN ''`. The always-awake design's `SetHibernate(false)` trap (it clears the rung) cannot reach a rootfs row because of the next rule. |
| +- `Upsert` keeps `routes.runtime` on conflict unless the tenant changed (Plan 2's rule, pinned by `TestUpsertNeverChangesRuntime`, `registry_test.go:2958`). A row's runtime changes only by deletion and a new mint, or by a re-tenant, which is a new life (Plan 2, ledger 17) [pf 1.10]. |
| +- Hibernation of a rootfs row is fixed the same way [pf 1.10]. The conflict arm becomes `hibernate=CASE WHEN routes.runtime != '' AND NOT (<tenantChangedSQL>) THEN routes.hibernate ELSE excluded.hibernate END`. So a full-row `Upsert` of an existing rootfs host, such as `carlos add`'s (`cli.go:333`), never flips a hibernating row or a resident, and a re-tenanted host takes the incoming value. |
| +- The replication invariant becomes "a rung means the activator replicates": `normalizeRoute` clears `Replication` only when `!t.Hibernate && t.Runtime == ""`, and the conflict arm becomes `WHEN excluded.hibernate = 0 AND (CASE WHEN <tenantChangedSQL> THEN excluded.runtime ELSE routes.runtime END) = '' THEN ''`, keyed on the effective runtime, not `routes.runtime` [pf 1.10]. The always-awake design's `SetHibernate(false)` trap (it clears the rung) cannot reach a rootfs row because of the next rule. |
| - `SetHibernate` refuses a row whose runtime is not `""` with `ErrRuntimeFixed`, changing nothing (`UPDATE ... WHERE host = ? AND runtime = ''`, then a `Get` to tell "no row" from "rootfs row"). |
| +- `ErrRuntimeFixed` joins `remoteErrors` (`remote.go:17`), so `errors.Is` holds across the service-user child that root's `carlos route hibernate` uses (`cli.go:1575`) [pf 1.11]. The mixed-version carry of Plan 2 (ledger 18) is closed for this sentinel: the child runs the same binary, the pinned `/proc/self/exe` (`internal/host/registrychild_exec_linux.go:17-23`). |
| +- `carlos add` refuses a host whose existing row is rootfs, with a diagnostic naming the host and saying a rootfs row comes from its record (log, not copy), before its `Upsert`. |
| - `ResidentInstances` selects `kind = 'instance' AND runtime = 'rootfs-v1' AND hibernate = 0 AND (status = '' OR status = 'ready') AND hold_op = '' AND import_gate = '' AND socket != '' AND backing = '' AND tunnel = ''`, ordered by host. |
| - `runtime` is not in `Fingerprint()` (Plan 2's comment on the field). `SnapshotFingerprint` covers it through `routeCols`. |
| |
| @@ -183,36 +250,48 @@ func TestRoutePredicates(t *testing.T) // table: binary hibernating (owned, not |
| 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) |
| +func TestUpsertKeepsRootfsHibernation(t *testing.T) |
| + // a resident and a hibernating rootfs row, each re-Upserted with Hibernate flipped: stored value unchanged; |
| + // a binary row's flip through Upsert still lands (today's behaviour) |
| +func TestRetenantedHostTakesRuntimeAndHibernation(t *testing.T) |
| + // a rootfs resident re-Upserted under another account (tenantChangedSQL true) with Runtime "" and Hibernate true: |
| + // the row takes both, and its replication follows the binary rule |
| func TestSetHibernateRefusesRootfsRows(t *testing.T) |
| // errors.Is(err, ErrRuntimeFixed) for both directions; row byte-identical after; binary row still flips |
| +func TestRemoteSetHibernateRefusesRootfsRows(t *testing.T) |
| + // the same refusal through OpenRemote: errors.Is(err, ErrRuntimeFixed) on the parent's side |
| func TestResidentInstancesSelects(t *testing.T) |
| // in: resident ready, resident status ""; out: rootfs hibernating, binary awake, held (hold_op "move"), |
| // status "failed", import gate set, sidecar, unit-backed |
| +// cli_add_rootfs_test.go (root package) |
| +func TestAddRefusesAnExistingRootfsHost(t *testing.T) // carlos add over a rootfs row: refused, row unchanged; a binary row re-adds as today |
| ``` |
| |
| -(`TestUpsertRoundTripsAllColumns`, `TestUpsertNeverChangesRuntime` and `TestMigrateAddsRuntimeToAnOldRegistry` are Plan 2's.) Extend the remote round-trip test that covers `AlwaysOnWorkers` (find it with `grep -n AlwaysOnWorkers internal/registry/*_test.go`) to call `ResidentInstances`. |
| +(`TestUpsertRoundTripsAllColumns`, `TestUpsertNeverChangesRuntime` and `TestMigrateAddsRuntimeToAnOldRegistry` are Plan 2's.) Extend `TestRemoteRegistryRoundTrip` (`remote_test.go:38`) to call `ResidentInstances` through `OpenRemote` (no remote test covers `AlwaysOnWorkers` today, so this is the first of its kind). |
| |
| -- [ ] **Step 2:** Run `go test ./internal/registry/ -run 'TestRoutePredicates|TestResidentKeepsItsReplicationRung|TestSetHibernateRefusesRootfsRows|TestResidentInstancesSelects|TestUpsertNeverChangesRuntime' -count=1`. Expected: FAIL, `Rootfs` undefined (Plan 2's `TestUpsertNeverChangesRuntime` passes). |
| -- [ ] **Step 3:** Add the predicates, the replication arm, `SetHibernate`'s refusal and `ResidentInstances` (with its remote-dispatch case) to the rules above. |
| -- [ ] **Step 4:** Run Step 2's command. Expected: PASS. Run `go test ./internal/provision/ -run TestPlan14RootReadCensus -count=1`; on a digest change follow the Global Constraints' census line. |
| +- [ ] **Step 2:** Run `go test ./internal/registry/ -run 'TestRoutePredicates|TestResidentKeepsItsReplicationRung|TestUpsertKeepsRootfsHibernation|TestRetenantedHostTakes|TestSetHibernateRefusesRootfsRows|TestRemoteSetHibernateRefuses|TestResidentInstancesSelects|TestUpsertNeverChangesRuntime|TestRemoteRegistryRoundTrip' -count=1` and `go test . -run TestAddRefusesAnExistingRootfsHost -count=1`. Expected: FAIL, `Rootfs` undefined (Plan 2's `TestUpsertNeverChangesRuntime` passes). |
| +- [ ] **Step 3:** Add the predicates, the two conflict arms, `normalizeRoute`'s rule, `SetHibernate`'s refusal, the remote sentinel, `ResidentInstances` (with its remote-dispatch case) and `carlos add`'s refusal, to the rules above. |
| +- [ ] **Step 4:** Run Step 2's commands and `go test ./internal/registry/ -run 'Upsert|Remote|Hibernate|Replication' -count=1`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| -git add internal/registry/ |
| -git commit -m "registry: ActivatorOwned and Resident predicates over routes.runtime; ResidentInstances" |
| +git add internal/registry/ cli.go cli_add_rootfs_test.go |
| +git commit -m "registry: ActivatorOwned and Resident predicates over routes.runtime; rootfs hibernation fixed in Upsert and SetHibernate; ResidentInstances" |
| ``` |
| |
| --- |
| |
| ### Task 3: `Record.Runtime`: the rails, the mint helper, fixed against every writer |
| |
| +**Review:** cross-model (pre-flight §7): the record decides root's admission. |
| + |
| **Files:** |
| - Create: `internal/provision/runtime.go`, `internal/provision/runtime_test.go` |
| -- Modify: `internal/provision/provision.go`: `Record` (field after `Hibernate`, `:107`); `ValidateShape` (`:559`); `CreateRecord` (`:882`) |
| -- Modify: `internal/provision/record_sequence.go`: `WriteRecord` (`:117`) calls `runtimeFixed` before its `Put` |
| +- Modify: `internal/provision/provision.go`: `Record` (field after `Hibernate`, `:119`); `ValidateShape` (`:639`); `CreateRecord` (`:967`, unchanged; see below) |
| +- Modify: `internal/provision/record_sequence.go`: `WriteRecord` (`:120`) calls `runtimeFixed` before its `Put` |
| |
| **Interfaces:** |
| -- Consumes: `registry.RuntimeRootfsV1`, `registry.ValidRuntime` (Plan 2 Task 2); Plan 1's `release.Manifest.Kind == "rootfs"` and `Manifest.Hibernate`. |
| +- Consumes: `registry.RuntimeRootfsV1`, `registry.ValidRuntime` (Plan 2 Task 2); Plan 1's `release.Manifest.Kind == "rootfs"` (`IsRootfs`, `internal/release/release.go:153`) and `Manifest.Hibernate`. |
| - Produces: |
| ```go |
| // Record.Runtime string `json:"runtime,omitempty"` |
| @@ -244,7 +323,7 @@ func TestOrdinaryWritersCannotChangeRuntime(t *testing.T) |
| func TestRawWriteThatDropsRuntimeIsRefused(t *testing.T) |
| // WriteRecord(key, storedRootfsBody, bodyWithoutRuntimeKey, etag) -> ErrRuntimeProtected (an old writer's shape) |
| func TestBinaryRecordBytesUnchanged(t *testing.T) |
| - // a binary record marshals with no "runtime" key (TestRecordWireShapeIsAdditive keeps passing too) |
| + // a binary record marshals with no "runtime" key (TestRecordWireShapeIsAdditive, provision_test.go:24, keeps passing too) |
| ``` |
| |
| - [ ] **Step 2:** Run `go test ./internal/provision/ -run 'TestValidateShapeRuntime|TestRuntimeFromManifest|TestOrdinaryWritersCannotChangeRuntime|TestRawWriteThatDropsRuntime|TestBinaryRecordBytesUnchanged|TestRecordWireShapeIsAdditive' -count=1`. Expected: FAIL, `Runtime` undefined. |
| @@ -261,8 +340,10 @@ git commit -m "provision: Record.Runtime; rootfs rails; runtime and rootfs hiber |
| |
| ### Task 4: Reconcile materializes the runtime |
| |
| +**Review:** cross-model (pre-flight §7): the record decides root's admission. |
| + |
| **Files:** |
| -- Modify: `internal/provision/reconcile.go`: `everywhereClass` (`:268`), `everywhereRoute` (`:334`), `RouteFor` (`:436`), `shapeMismatch` (`:614`), the owned arm (`:1323-1365`) |
| +- Modify: `internal/provision/reconcile.go`: `everywhereClass` (`:310`), `everywhereRoute` (`:376`), `RouteFor` (`:478`), `shapeMismatch` (`:666`), the owned arm's hibernation converge (`:1540-1575`, the `SetHibernate` call at `:1570`) |
| - Create: `internal/provision/reconcile_rootfs_test.go` |
| |
| **Interfaces:** |
| @@ -274,10 +355,12 @@ Rules: |
| - `everywhereClass` and `everywhereRoute` answer false first for a rootfs record or row: it is home-boxed. |
| - `shapeMismatch` adds `existing.Runtime != want.Runtime` (named in its message as `runtime %q/%q`), so a hand-added row is never adopted across kinds. |
| - Owned arm: when `existing.Runtime != rec.Runtime`, log one line (`provision: %s: record runtime %q, row %q: the runtime is fixed at mint; leaving the row's runtime and hibernation alone`) and skip the hibernation converge. When `existing.Rootfs()`, never call `SetHibernate`; a record that disagrees about hibernation logs the same kind of line. Every other column converges as today. This is Review Focus 1: an old console's rewrite never changes what the box runs. |
| -- Unknown runtime on a record: `ValidateShape` already protects the host (scan, `:914`): not minted, not converged, not retired. |
| -- The domains pass's platform apex row (`mintedRoute`, `internal/domains/reconcile.go:881`) copies no runtime, by design: it is an alias with `Platform` set and no process, the edge proxies it to the source's canonical socket, and nothing in the activator owns it. Task 5's edge test pins that (found by Plan 4, its self-review). |
| +- Unknown runtime on a record: `ValidateShape` already protects the host (the scan, `:1083`): not minted, not converged, not retired. |
| +- Held staging passes no runtime: only the held (move) mint reaches it (`mintHeld`, `:2046`, its `RouteFor` at `:2062`). Task 13 refuses every move transition of a rootfs record, so no held rootfs row is ever minted, and `TestMoveTransitionsRefuseRootfs` asserts it. Plan 2's carry of this to claim activation is closed: claims are shelved. No code here [pf 2.3]. |
| +- The domains pass's platform apex row (`mintedRoute`, `internal/domains/reconcile.go:875`) copies no runtime, by design: it is an alias with `Platform` set and no process, the edge proxies it to the source's canonical socket, and nothing in the activator owns it. Task 5's edge test pins that (found by Plan 4, its self-review). |
| +- Edit only these lines. The cleanup is deleting `claimInstall` and `cfg.ClaimEnabled` beside them (`:1503-1515`); on a merge conflict keep its deletion [pf 3.3]. |
| |
| -- [ ] **Step 1: Write the failing tests** with the package's reconcile harness (memory store plus a temp registry, as `TestReconcileMints` does): |
| +- [ ] **Step 1: Write the failing tests** with the package's reconcile harness (memory store plus a temp registry, as `TestReconcileMints`, `reconcile_test.go:145`, does): |
| |
| ```go |
| func TestReconcileMintsRootfsNested(t *testing.T) // flat-mode box (cfg.Layout nil): row Runtime rootfs-v1, Hibernate false, |
| @@ -306,31 +389,36 @@ git commit -m "provision: reconcile mints rootfs rows nested and seedless; never |
| |
| ### Task 5: Every reader asks the shared predicate |
| |
| +**Review:** cross-model (pre-flight §7): who replicates a resident's database. A wrong `FleetDBsWithSkipped` puts two litestream writers on one replica. |
| + |
| 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`. |
| |
| **Files and changes:** |
| |
| | site | today | becomes | |
| |---|---|---| |
| -| `internal/activator/layout.go:64` `ActivatorManaged` | `rt.Kind == "instance" && rt.Hibernate && ...` | `rt.ActivatorOwned() && rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""` | |
| -| `internal/activator/wakeidentity.go:61-64` | runtime not compared | `began.Runtime != now.Runtime` is a changed route | |
| -| `internal/activator/activator.go:5328` `ServeScheduled`, `:5336` and `:5369` `serve` | `rt.Hibernate` | `rt.ActivatorOwned()` | |
| -| `internal/edge/edge.go:747` (generation proxy), `:868` (`hib`), `:901` (no-activator advice) | `t.Kind == "instance" && t.Hibernate` | `t.ActivatorOwned()` | |
| +| `internal/activator/layout.go:63` `ActivatorManaged` | `rt.Kind == "instance" && rt.Hibernate && ...` | `rt.ActivatorOwned() && rt.Socket != "" && rt.Backing == "" && rt.Tunnel == ""` | |
| +| `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/rollout/policy.go:168` `Managed` | `release.Adoptable(rt) && rt.Hibernate` | `release.Adoptable(rt) && rt.ActivatorOwned()` | |
| -| `internal/host/socket_advice.go:42`, `:83`; `internal/host/probes.go:310`; `internal/host/schedule_wiring.go:342` | `rt.Hibernate` | `rt.ActivatorOwned()` | |
| -| `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 fenced recheck (`:747`) refuse one the same way | |
| +| `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/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 | |
| |
| Deliberately unchanged, each for the reason given (the implementer adds a one-line comment at each): |
| - `internal/schedule/converge.go:479`: `!rt.Hibernate` zeroes the idle window, which is right for a resident (it never sleeps, so no timer holds it awake). |
| -- `internal/release/adopt.go:1236`: a resident adopts in the awake group, whose restart callback is a no-op for an exec row (`internal/host/rootrestart.go:433`); the scheduler moves it (Task 11). |
| -- `internal/host/restart.go:765`, `internal/host/agent.go:4317`: unit-only paths; exec rows are bounced by the agent. |
| +- `internal/release/adopt.go:1241`: a resident adopts in the awake group, whose restart callback is a no-op for an exec row (`internal/host/rootrestart.go:433`); the scheduler moves it (Task 11). |
| +- `internal/host/restartscope.go:496`: a narrowed restart skips only a hibernating host; a resident is not asleep, so it goes to the same restart callback, the no-op above, and the scheduler moves it [pf 1.13]. |
| +- `internal/host/restart.go:765`, `internal/host/agent.go:4474` (`makeStartRoute`): unit-only paths; exec rows are bounced by the agent. |
| - `internal/appconfig/sync.go:641`: a resident's config change is a bounce, and the rootfs tick restarts it (Task 8). |
| -- `internal/host/movesphase1.go:679`: already refuses (nested); Task 13 refuses earlier, with a reason. |
| -- `internal/caps/converge.go`: exec rows never materialize capabilities (`internal/host/caps_pass.go:180`). |
| -- `internal/status/snapshot.go:958`, `internal/console/overview.go`, `instances.go`, `view.go`: display; a resident reads as running, which is true. |
| +- `internal/caps/converge.go`: exec rows never materialize capabilities (`internal/host/caps_pass.go:181`). |
| +- `internal/status/snapshot.go:967-975`, `internal/console/overview.go`, `instances.go`, `view.go`: display; a resident reads as running, which is true. |
| - `internal/provision/seedswap.go:50`: a rootfs record carries no seed (D5). |
| -- `internal/activator/activator.go:4952` (due wakes): a resident is never due-woken; the rootfs tick starts it. |
| +- `internal/activator/activator.go:5013` (due wakes, in `sweepOnce`): a resident is never due-woken; the rootfs tick starts it. |
| + |
| +(The first draft listed `internal/host/movesphase1.go:679` here. R4a of the claims cleanup deletes it, and Task 13 refuses every move earlier; the line is dropped [pf 1.13, 3.4].) |
| |
| - [ ] **Step 1: Write the failing tests**, one file per package, each with a resident row (`Kind instance, Runtime rootfs-v1, Hibernate false`, nested socket and DB): |
| |
| @@ -348,50 +436,57 @@ func TestFleetDBsExcludesResidentRootfs(t *testing.T) // the resident's DB is |
| // HibernatingHosts; a binary hibernate=false row's DB is still replicated box-wide (as TestFleetDBsDiscoversNestedDatabases sets up) |
| // 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 |
| +func TestSocketAdvisoryLeavesOwnedResident(t *testing.T) // warnExternalSockets(owns true) returns nothing for it; not owned, the |
| + // activator-managed diagnostic is the one logged |
| 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 |
| // internal/layout/rootfs_pass_test.go |
| func TestPassNeverMovesRootfsRows(t *testing.T) // flat mode, nested rootfs row: Result "kept", files untouched, no journal |
| ``` |
| |
| - [ ] **Step 2:** Run each package's tests with `-run` on the names above. Expected: FAIL. |
| -- [ ] **Step 3:** Make the changes in the table. |
| -- [ ] **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'`). Expected: PASS. |
| +- [ ] **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 5: Commit** |
| |
| ```bash |
| -git add internal/activator internal/edge internal/ops internal/rollout internal/host internal/layout |
| +git add internal/activator internal/edge internal/ops internal/rollout internal/release internal/host internal/layout |
| git commit -m "rootfs: every activator-ownership reader asks Route.ActivatorOwned; the layout pass never moves a rootfs row" |
| ``` |
| |
| --- |
| |
| -### Task 6: The environment contract |
| +### Task 6: The environment contract (the cmd half) |
| + |
| +**Review:** not cross-model (pre-flight §7): a pure composer, behind INV-5. |
| + |
| +The worker half of the first draft (`rootfsWorkerVars` and the `prepare.go` worker branch) is W1's [pf 6.1]. |
| |
| **Files:** |
| - Create: `internal/activator/rootfsenv.go`, `internal/activator/rootfsenv_test.go` |
| -- Test only: Plan 2's `startRootfs` (`internal/activator/rootfs.go`, A6) gets the generation's own socket from `StartGenExe` (D1); this task pins it |
| -- Modify: `internal/activator/prepare.go:71-99`: `RoleWorker` reads no env file (its env is the generation's, Task 9), binds no control listener, and binds its own log listener at `instancectl.WorkerLogSocket(host, name)` (A4; the path Plan 2's `WorkerDropIn` points `StandardOutput=` at) |
| +- Test only: Plan 2's `startRootfsGen` (`internal/activator/rootfs.go:189`, A6) gets the generation's own socket from `StartGenExe` (D1); this task pins it |
| +- Modify: `internal/activator/rootfs_invariants_test.go` (INV-5's composer row) |
| |
| **Interfaces:** |
| -- Consumes: Plan 2's `rootfsVars(vars map[string]string, sock, dbPath string) map[string]string` (web: `rootfsVars(b.agentOwnedVars(rt, sock+".control", fileEnv, haveControl), sock, dbPath)`, already in `startRootfs`); `agentOwnedVars` (`internal/activator/backend_exec.go:2310`), `cmdVars` (`cmdunit.go:124`), `withVar`. |
| +- Consumes: Plan 2's `rootfsVars(vars map[string]string, sock, dbPath string) map[string]string` (web: `rootfsVars(b.agentOwnedVars(rt, sock+".control", fileEnv, haveControl), sock, dbPath)`, already in `startRootfs`, `rootfs.go:227`); `agentOwnedVars` (`internal/activator/backend_exec.go:2359`), `cmdVars` (`cmdunit.go:124`), `withVar`, `rootfsLaunchEnv` (`rootfs.go:93`). |
| - Produces: |
| ```go |
| - // workers: Plan 2's rootfsVars with sock = rt.Socket (D1), over the generation's launch file env |
| - func (b *ExecBackend) rootfsWorkerVars(rt registry.Route, dbPath string, genEnv map[string]string) map[string]string |
| - // release and carlos run: cmdVars, then CARLOS_SOCKET=rt.Socket (D1); runID and runDir "" for release, which |
| - // then carries neither CARLOS_RUN_ID nor CARLOS_RUN_DIR |
| + // release and carlos run: rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath) (D1); |
| + // runID and runDir "" for release, which then carries neither CARLOS_RUN_ID nor CARLOS_RUN_DIR |
| func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string |
| ``` |
| |
| -`CARLOS_SOCKET` and `CARLOS_DB` are set after the file environment, so a tenant's `.env` cannot point them elsewhere. Binary rows are untouched: their argv still carries `--socket` and `--db`, and no composer here runs for them. The environment is never logged. |
| +`CARLOS_SOCKET` and `CARLOS_DB` are set after the file environment, so a tenant's `.env` cannot point them elsewhere. Binary rows are untouched: their argv still carries `--socket` and `--db`, and no composer here runs for them. The environment is never logged. A launch file built from these vars always goes through `rootfsLaunchEnv`, never `childEnv`, which starts from `os.Environ()` (`backend_exec.go:2880`) [pf 1.6]. |
| |
| -- [ ] **Step 1: Write the failing tests.** Production-wired: `nestedBackend(t, ctl, unit)` (`internal/activator/unitproc_test.go:126`) with `fakeControl`, a rootfs route, generations on, a `.env` holding `SHOP_MODE=live`, `CARLOS_SOCKET=/tmp/x` and `CARLOS_DB=/x`. |
| +- [ ] **Step 1: Write the failing tests.** Production-wired: `nestedBackend(t, ctl, unit)` (`internal/activator/unitproc_test.go:225`) with `fakeControl`, a rootfs route, generations on, a `.env` holding `SHOP_MODE=live`, `CARLOS_SOCKET=/tmp/x` and `CARLOS_DB=/x`. |
| |
| ```go |
| func TestRootfsWebLaunchCarriesTheContract(t *testing.T) { |
| - // StartGen(ctx, rt, 7, true); read launch.gen.7.json from the instance directory |
| + // StartGenExe(ctx, rt, 7, true, id); read launch.gen.7.json from the instance directory |
| env := launchEnvMap(t, dir, instancectl.GenLaunchFileName(7)) |
| want := map[string]string{ |
| "CARLOS_SOCKET": genSocket(rt, 7), // the generation's own, not rt.Socket and not the .env's |
| @@ -402,44 +497,114 @@ func TestRootfsWebLaunchCarriesTheContract(t *testing.T) { |
| // plus CARLOS_CONTROL_SOCKET == genSocket+".control", CARLOS_ADMIN_TOKEN present |
| } |
| func TestRootfsCmdVarsFollowTheRunRule(t *testing.T) // CARLOS_SOCKET == rt.Socket; no CARLOS_CONTROL_SOCKET, no CARLOS_PURGE; |
| - // CARLOS_DB set; release (runID "") carries no CARLOS_RUN_ID or CARLOS_RUN_DIR |
| -func TestRootfsWorkerVarsAreWebVars(t *testing.T) // every key of the web env with CARLOS_SOCKET == rt.Socket |
| + // CARLOS_DB set; release (runID "") carries no CARLOS_RUN_ID or CARLOS_RUN_DIR; the .env's CARLOS_SOCKET and CARLOS_DB lose |
| func TestBinaryLaunchUnchanged(t *testing.T) // a binary row's launch.run.json argv has --socket and --db; no CARLOS_SOCKET key |
| -func TestWorkerRoleReadsNoSidecarEnv(t *testing.T) // a planted <host>-sidecar.env is not read by prepare for RoleWorker |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWebLaunch|TestRootfsCmdVars|TestRootfsWorkerVars|TestBinaryLaunchUnchanged|TestWorkerRoleReadsNoSidecarEnv' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3:** Implement the two composers on Plan 2's `rootfsVars`. Plan 2's `StartGenExe` already passes the generation's socket to `startRootfs`; `TestRootfsWebLaunchCarriesTheContract` pins it. |
| -- [ ] **Step 4:** Run Step 2's command. Expected: PASS. |
| +INV-5 gains its composer row: with `t.Setenv("PATH", "/agent/bin")`, `rootfsLaunchEnv(b.rootfsCmdVars(...))` holds no `PATH` and no `HOME`, and adding `PATH=/app/bin` to the tenant's `.env` puts exactly that value there. |
| + |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWebLaunch|TestRootfsCmdVars|TestBinaryLaunchUnchanged|TestRootfsLaunchFilesCarryOnlyComposedEnv' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement the composer on Plan 2's `rootfsVars`. Plan 2's `StartGenExe` already passes the generation's socket to `startRootfs`; `TestRootfsWebLaunchCarriesTheContract` pins it. |
| +- [ ] **Step 4:** Run Step 2's command and Task 1's guards. Expected: PASS. |
| +- [ ] **Step 5: Commit** |
| + |
| +```bash |
| +git add internal/activator/rootfsenv.go internal/activator/rootfsenv_test.go internal/activator/rootfs_invariants_test.go |
| +git commit -m "activator: CARLOS_SOCKET and CARLOS_DB for rootfs commands; the web contract pinned" |
| +``` |
| + |
| +--- |
| + |
| +### Task N1: A rootfs row swaps, holds and takes a planned wake |
| + |
| +**Review:** cross-model (pre-flight §7): the generation start in swaps, holds and planned wakes; a kill-proof refusal; a refusal classification. |
| + |
| +On main a rootfs row can never swap, hold or take a planned wake. The overlap successor (`spawnSuccessor`, `swap.go:398`), the hold pin and every planned wake (`spawnPlanned`, `wakeplan.go:388`, through `startPinnedAt`, `swaphold.go:467`) call `ExecBackend.StartStaged` (`genbackend.go:230`). Its nested arm calls `spawnUnitFrom` (`backend_exec.go:2445`), whose `nestedGate` (`:2740`) refuses a rootfs row with `errRootfsBinaryLaunch`, and `verdictOf` reads that as gateNoOwnership (`swap.go:248`). Under D2 that is every deploy and every resident restart the scheduler plans [pf 1.1]. Tasks 7, 8, 10 and 11 build on this task. |
| + |
| +**Files:** |
| +- 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/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`). |
| +- Produces: |
| + ```go |
| + func healthBoundFor(rt registry.Route) time.Duration // rootfsHealthTimeout (120 s) for a rootfs row; spawnHealthTimeout (30 s) otherwise |
| + 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") |
| + // CmdRootfs: 403 -> ErrStagedImage (today); startRefused(status) -> ErrStartRefused; 502 and transport stay plain |
| + ``` |
| + |
| +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). |
| +- **`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. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `rootfs_staged_test.go`, production-wired where root is asked: `nestedBackend` (`unitproc_test.go:225`) with Plan 2's `fakeControl` (it implements `RootfsControl`), a rootfs row, generations on, build B staged with its root-written manifest; the Service tests drive the real `Service.Swap` and `spawnPlanned`, not `fakeBackend`. |
| + |
| +```go |
| +func TestOverlapSwapStartsTheRootfsGeneration(t *testing.T) // Service.Swap overlap, incumbent gen 1, attempt B: fakeControl's log has |
| + // StartRootfs for generation 2 with B's path and digest (never a binary start); SwapOK; e.gen.N == 2 |
| +func TestHoldSwapStartsTheRootfsGeneration(t *testing.T) // ModeHold: the pinned start is StartRootfs with the pin's image; SwapOK |
| +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 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 |
| + // errRootfsKillHost, OpenCleanup never called |
| +func TestHasSidecarFalseForRootfs(t *testing.T) // a planted <host>-sidecar.env: false for a rootfs row; StartSidecar still refuses it |
| +``` |
| + |
| +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 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** |
| |
| ```bash |
| -git add internal/activator/rootfsenv.go internal/activator/rootfsenv_test.go internal/activator/prepare.go |
| -git commit -m "activator: CARLOS_SOCKET and CARLOS_DB for every rootfs process" |
| +git add internal/activator internal/instancectl/client.go |
| +git commit -m "activator: StartStaged starts rootfs generations; the rootfs health bound in swaps and planned wakes; CmdRootfs types root's refusals; KillHost, EmptyHost and HasSidecar refuse rootfs rows" |
| ``` |
| |
| --- |
| |
| ### Task 7: Where a rootfs row may start, and how long its wake may take |
| |
| +**Review:** cross-model (pre-flight §7): gates before the lease; D7 writes a file into the tenant-writable directory. |
| + |
| **Files:** |
| -- Create: `internal/activator/rootfs_service.go` (this task's half; `rootfs.go` is Plan 2's), `internal/activator/rootfs_gate_test.go` |
| +- 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` (`:1755`, the ceiling), `doWake` (`:2090`, the gate before step 0.5; after step 2 the served-never-empty check and the placeholder; after step 5 the placeholder's first sync), `begin` (`:1471`, the gate before an entry is made), `serveWakeError` (`:5423`) |
| -- Modify: `internal/activator/backend_unit.go:313` (beside `SplitBackend.SeedPlaced`): `SplitBackend.PlaceRootfsDB` dispatches on `Backing` like it; a side without `rootfsDBPlacer` answers `errNoRootfsDB` |
| -- Modify: `internal/activator/wakeplan.go:381` and `awaitWake` (`activator.go:1592`): `firstWakeBudgetFor(rt)` |
| -- Modify: `internal/host/rollout.go:399`: `svc.ArmRootfs()` once the manager has armed (not in `refuseManaged`, `:210`) |
| +- 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/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`) |
| |
| **Interfaces:** |
| -- Consumes: `a.cfg.HostWrites.Enabled`, `a.gens`, `runs.MaxTimeout`, `firstWakeKillReserve` (`wakeplan.go:232`), Plan 2's `rootfsHealthTimeout` (A6). |
| +- Consumes: `a.gens`, `runs.MaxTimeout`, `firstWakeKillReserve` (`wakeplan.go:232`), N1's `healthBoundFor`, Plan 2's `rootfsGates` (`rootfs.go:128`) and `refuseRootfs`. |
| - Produces: |
| ```go |
| func (a *Service) ArmRootfs() // a.rootfsArmed.Store(true); only internal/host calls it |
| - func (a *Service) rootfsRefusal(rt registry.Route) error // nil for a binary row; for rootfs: |
| - // !registry.ValidRuntime(rt.Runtime) -> errRuntimeUnknown; a.cfg.HostWrites.Enabled -> errRootfsClaim; |
| - // !a.gens || !a.rootfsArmed.Load() -> errRootfsUnarmed |
| - var errRootfsClaim, errRootfsUnarmed, errRuntimeUnknown, errRootfsReplicaMissing error |
| - func healthBoundFor(rt registry.Route) time.Duration // rootfsHealthTimeout (120 s) for a rootfs row; spawnHealthTimeout (30 s) otherwise |
| + // 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. |
| + 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). |
| + 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 |
| |
| @@ -452,21 +617,27 @@ git commit -m "activator: CARLOS_SOCKET and CARLOS_DB for every rootfs process" |
| // sql.Open("sqlite", path), "PRAGMA busy_timeout=5000", "PRAGMA journal_mode=WAL" (writes page 1), Close, read, remove |
| ``` |
| |
| +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: |
| -- `doWake` and `begin` refuse a rootfs row on `rootfsRefusal` before the lease, the restore or any entry state: `acquires == 0`. The wake's member event is `RFS-3-C12` with the fragment `RFS-3-C13` (claims) or `RFS-3-C14` (unarmed); an unknown runtime logs only (no member can cause it). `serveWakeError` answers these 503 "instance failed to wake" (today's text). |
| +- **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`. |
| - `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. |
| -- The first-wake budget: a planned first wake of a rootfs build gets the rootfs health bound plus the kill reserve, so a 120 s Rails boot is judged on its own bound, not the binary 55 s. |
| +- The first-wake budget: a planned first wake of a rootfs build gets the rootfs health bound plus the kill reserve, so a 120 s Rails boot is judged on its own bound, not the binary 55 s. N1 already sizes the verdict floor to the same bound. |
| - Served never boots empty (Review Focus 4): after `Restore` reports `fresh` for a rootfs row whose `GoodVersion != ""`, the wake refuses with `errRootfsReplicaMissing` (member event `RFS-3-C15`), gives the lease back and starts nothing, and no placeholder is written. A first boot (`GoodVersion == ""`) proceeds. This check runs before the placeholder below and is not changed by it: the placeholder is only ever written for a row that has never served. |
| - The placeholder (D7, Review Focus 8): on a rootfs first boot (`fresh`, `GoodVersion == ""`), right after the check above and still under the wake's lease (step 1), before the planner's `release` (Task 11) and before `web`: `PlaceRootfsDB(ctx, rt)` through `rootfsDBPlacer`; a backend without it fails the wake with `errNoRootfsDB` and gives the lease back. A placement error fails the wake the same way (nothing has started). Then `ctx.Err() != nil || !a.wakeAllowed(host)` is checked again, as after `Restore`. A binary row never takes this path: it has its seed and creates its own file. |
| -- `ExecBackend.PlaceRootfsDB`: the database path is the row's nested `DBPath` (Task 4), split with `splitDBPath`. The instance directory is the tenant uid's to write, so the file is written as `placeSeed` writes one (`seedplace.go:373`): `emptySQLiteDB()`'s bytes to `.carlos-db-placeholder.tmp` through `instancefs.OpenBeneath(dir, tmp, O_CREATE|O_EXCL|O_WRONLY, 0o600)`, fsync, pinned by identity (`openSameFile`, `sameFileAt`), `lease.CheckDB` through the descriptor, then `instancefs.RenameBetween` onto the base name, only when nothing is at the base name (an entry there, of any kind, is left alone and logged: `Restore` saw none, so something else made it, and it is never overwritten). The temp name is removed on every path. The SQLite driver never opens a tenant-writable path; it only ever opens the agent's private copy. |
| +- `ExecBackend.PlaceRootfsDB`: the database path is the row's nested `DBPath` (Task 4), split with `splitDBPath` (`seedplace.go:327`). The instance directory is the tenant uid's to write, so the file is written as `placeSeed` writes one (`seedplace.go:373`): `emptySQLiteDB()`'s bytes to `.carlos-db-placeholder.tmp` through `instancefs.OpenBeneath(dir, tmp, O_CREATE|O_EXCL|O_WRONLY, 0o600)`, fsync, pinned by identity (`openSameFile`, `sameFileAt`, `seedplace.go:415`, `:433`), `lease.CheckDB` through the descriptor, then `instancefs.RenameBetweenNoReplace` (`instancefs/dirs_linux.go:137`) onto the base name [pf 8.6]. EEXIST means something is at the base name: `Restore` saw none, so something else made it; the file there, of any kind, is left alone and the refusal logged, and it is never overwritten. There is no check-then-rename window. The temp name is removed on every path. The SQLite driver never opens a tenant-writable path; it only ever opens the agent's private copy. |
| - First sync: after step 5's `Replicate`, a wake that placed the placeholder calls `SyncAndWait` on the replica once (the shape of step 5b, `SeedPlaced`), so the replica holds a database before the scheduler can record the build as good. A failed sync logs and does not fail the wake: the replicator keeps trying on its interval and the next sleep's checkpoint uploads it. If neither lands and the local file is later lost, the next wake reads "served, no database, no replica" and refuses (`RFS-3-C15`), which is the safe direction. |
| |
| -- [ ] **Step 1: Write the failing tests** with `fakeBackend` (`internal/activator/activator_test.go:353`): |
| +- [ ] **Step 1: Write the failing tests** with `fakeBackend` (`internal/activator/activator_test.go:353`, gaining `restores` and `materialized` counters and an optional `rootfsStartable` answer): |
| |
| ```go |
| -func TestRootfsWakeRefusedWithClaimsArmed(t *testing.T) // cfg.HostWrites.Enabled: ServeHTTP 503; fb.acquires == 0; event names C13 |
| -func TestRootfsWakeRefusedUnarmed(t *testing.T) // gens on, ArmRootfs not called: same, C14; after ArmRootfs it wakes |
| +func TestRootfsRefusalPrecedesTheLease(t *testing.T) // INV-3. table over every reason: unknown runtime; gens off; ArmRootfs not |
| + // 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 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 |
| func TestRootfsWakeCeiling(t *testing.T) // the ctx fakeBackend.Acquire sees has Deadline >= now+5m+6h for rootfs, |
| @@ -479,11 +650,12 @@ func TestServedRootfsPlacesNoPlaceholder(t *testing.T) // restoreFresh true, G |
| func TestBinaryFreshWakePlacesNothing(t *testing.T) // binary hibernating row, restoreFresh true: fb.placeholders == 0, the seed runs as today |
| func TestRootfsPlaceholderFailureStartsNothing(t *testing.T) // PlaceRootfsDB errors: wake fails, fb.starts == 0, lease given back; |
| // a backend without rootfsDBPlacer: errNoRootfsDB, same |
| -// internal/activator/rootfsdb_test.go, production-wired: a real ExecBackend (nestedBackend, unitproc_test.go:126), the real |
| +// internal/activator/rootfsdb_test.go, production-wired: a real ExecBackend (nestedBackend, unitproc_test.go:225), the real |
| // Restore (restoreReplica, the package var, stubbed over a test bucket directory: a replica is a file copied there), and a |
| // lease fake whose Replicator.SyncAndWait copies the local database into that directory |
| func TestPlaceRootfsDBWritesAnEmptySQLiteDatabase(t *testing.T) // file at NestedDBPath, lease.CheckDB passes, journal mode wal, |
| - // no tables, mode 0600; a planted symlink or file at the base name is left as it was and nothing is written through it |
| + // no tables, mode 0600; a planted symlink or file at the base name is left as it was, nothing is written through it, and |
| + // the temp name is gone |
| func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) // Review Focus 8. A web fake that serves and never opens CARLOS_DB: |
| // first wake places the placeholder, serves, and the test bucket holds it after the first sync; set GoodVersion "v1"; |
| // (a) stop and wake again on the same box: the warm file is used, no refusal, no new placeholder; |
| @@ -492,26 +664,30 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) // Review Focus 8. A web |
| // (c) empty the test bucket too and wake: errRootfsReplicaMissing, nothing started, no placeholder written |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run '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` to `C15` from the deck and add their ids to the built list. |
| -- [ ] **Step 4:** Run Step 2's command, 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. |
| +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 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** |
| |
| ```bash |
| git add internal/activator internal/host/rollout.go approved_rootfs_copy_test.go |
| -git commit -m "activator: rootfs rows start only with overlap swaps armed and claims off; first boot places an empty database; never boot empty after serving" |
| +git commit -m "activator: rootfs rows refused before the lease unless overlap swaps are armed and the box's rootfs gates pass; first boot places an empty database; never boot empty after serving" |
| ``` |
| |
| --- |
| |
| ### Task 8: Residency: always-on nested instances |
| |
| +**Review:** cross-model (pre-flight §7): crash detection, stop accounting, restarts under a lease. |
| + |
| **Files:** |
| -- Modify: `internal/activator/rootfs_service.go` (residency), `internal/activator/activator.go`: `actEntry` (`:469`, `resident bool`), `Service` (`:1134`, the residency fields), `Start` (`:4417`, the second ticker), `sweepOnce` (`:4644`, the idle exemption), `begin` (the backoff refusal), `wake` (the outcome hook in its final critical section), `finishStop` (`:4344`, the stop hook), `serveWakeError` (`errResidentBackoff`) |
| +- Modify: `internal/activator/rootfs_service.go` (residency), `internal/activator/activator.go`: `actEntry` (`:469`, `resident bool`), `Service` (`:1134`, the residency fields), `Start` (`:4451`, the second ticker), `sweepOnce` (`:4533`; the idle exemption at `hibernates :=`, `:4693`), `begin` (`:1484`, the backoff refusal), `wake` (`:1760`, the outcome hook in its final critical section), `finishStop` (`:4378`, the stop hook), `serveWakeError` (`:5494`, `errResidentBackoff`) |
| - Create: `internal/activator/rootfs_resident_test.go` |
| |
| **Interfaces:** |
| -- Consumes: `registry.Registry.ResidentInstances` (through `a.due`), Task 7's gate. |
| +- Consumes: `registry.Registry.ResidentInstances` (through `a.due`), Task 7's `rootfsStartRefusal`. |
| - Produces: |
| ```go |
| type ResidentLister interface{ ResidentInstances() ([]registry.Route, error) } // *registry.Registry satisfies it; |
| @@ -524,25 +700,26 @@ git commit -m "activator: rootfs rows start only with overlap swaps armed and cl |
| type residentState struct { |
| failures int |
| retryAt time.Time |
| - starting bool // a proactive wake of this host is in flight |
| + starting bool // a proactive wake of this host is in flight |
| restarts int |
| - refused string // "claim" | "unarmed" | "" : logged once per change |
| + refused string // the current refusal's text, "" when none: logged once per change |
| } |
| type errResidentBackoff struct{ retryAfter time.Duration } |
| func (a *Service) rootfsTick() |
| + func (a *Service) superviseRootfsLocked(e *actEntry) // a no-op in group A; W1 fills it with worker supervision |
| func (a *Service) noteResidentWakeLocked(e *actEntry, err error) |
| func (a *Service) noteResidentStopLocked(e *actEntry) |
| // Service: residents map[string]*residentState; residentStarting int; residentJitter func() float64 |
| ``` |
| |
| -`rootfsTick` runs on its own `residentPoll` ticker inside the sweeper goroutine `Start` launches, after `<-a.Startup`, so Shutdown's `close(sweepStop); <-sweepDone` (`:5156`) stops it with the sweep. Each tick: |
| +`rootfsTick` runs on its own `residentPoll` ticker inside the sweeper goroutine `Start` launches, after `<-a.Startup`, so Shutdown's `close(sweepStop); <-sweepDone` (`:5223`) stops it with the sweep. Each tick: |
| |
| 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 (`:4577`), so a crash is seen within 2 s rather than the sweep's 30. (Task 9 adds worker supervision here.) |
| -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). `rootfsRefusal(rt) != nil` sets `st.refused` and skips, with one log line and one `RFS-3-C12` event per change of `st.refused`. 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)`. |
| +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)`. |
| |
| 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 a `rootfsRefusal` error: `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 unless the error is `ErrFenced`, `errShuttingDown` or marked `errRootfsRefused` (INV-4): `failures++`, `retryAt = now + residentBackoff(failures, jitter())`. |
| - `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. |
| @@ -569,14 +746,18 @@ func TestResidentNotRestartedWhenRetiredFencedOrShutDown(t *testing.T) // row go |
| // released; Shutdown: none, and the tick has stopped (sweepDone closed) |
| func TestResidentListingFailureStopsNothing(t *testing.T) // lister errors for 20 ticks: the awake resident keeps its entry and rep |
| 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 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 |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestResident' -count=1`. Expected: FAIL. |
| +INV-3's table gains its `rootfsTick` rows: every reason, `acquires == restores == materialized == 0`. |
| + |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestResident|TestRootfsRefusalPrecedesTheLease' -count=1`. Expected: FAIL. |
| - [ ] **Step 3:** Implement to the rules; write `RFS-3-C11` and `RFS-3-C16`, add their ids to the built list. |
| -- [ ] **Step 4:** Run Step 2's command, then `go test -race ./internal/activator/ -run 'TestResidentRequestAndTickRaceOneWake|TestResidentCrashDuringStopIsOneStop' -count=3`, then the families the hooks touch: `-run 'Sweep|Idle|Converge|Bounce|Retire|Shutdown|Wake'`. Expected: PASS. |
| +- [ ] **Step 4:** Run Step 2's command, then `go test -race ./internal/activator/ -run 'TestResidentRequestAndTickRaceOneWake|TestResidentCrashDuringStopIsOneStop' -count=3`, then the families the hooks touch: `-run 'Sweep|Idle|Converge|Bounce|Retire|Shutdown|Wake'`, and Task 1's guards. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| @@ -586,103 +767,31 @@ git commit -m "activator: always-on rootfs instances: boot start, crash restart |
| |
| --- |
| |
| -### Task 9: Workers |
| - |
| -**Files:** |
| -- Create: `internal/activator/rootfsworkers.go`, `internal/activator/backend_rootfs.go` (worker half), `internal/activator/rootfsworkers_test.go` |
| -- Modify: `internal/activator/activator.go`: `actEntry` (worker fields), `doWake` step 6 (`:2605`, start after the sidecar step), `stop` (`:3982`, workers stopped first), `rootfsTick` (supervision) |
| -- Modify: `internal/activator/opset.go:681` `releasable` (the worker proof), `internal/activator/generations_file.go:177` `entryGenerationsLocked` (worker builds) |
| -- No change to `internal/activator/control.go`: the worker verbs are Plan 2's `RootfsControl` (A4) |
| - |
| -**Interfaces:** |
| -- Consumes: A2 (`release.ReadStagedManifest`), A4 (Plan 2's `RootfsControl.StartRootfsWorker`, `StopRootfs`, `WorkerUnitName`, `WorkerLaunchFileName`, `WorkerLogSocket`), Plan 2's `writeRootfsLaunchFor`, `rootfsControl()`, `rootfsTier`; Task 6's `rootfsWorkerVars`, `launchEnvProc` (`unitProc.LaunchEnv`), `waitRoleCgroupEmpty` (`backend_exec.go:1646`). |
| -- Produces: |
| - ```go |
| - // The control verbs are Plan 2's activator.RootfsControl (StartRootfsWorker, StopRootfs); no new control interface. |
| - type RootfsWorkerBackend interface { |
| - Processes(id release.StagedIdentity) (map[string]release.Process, error) // A2 |
| - StartRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, genEnv map[string]string) (Proc, error) |
| - // (its first call is the egress readiness slot Plan 5 Task 7 fills, before rc.StartRootfsWorker; Astra R2 finding 4) |
| - RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error // RootfsControl.StopRootfs(ctx, host, RoleWorker, 0, name), then the unit's cgroup proven empty |
| - } |
| - func workerNames(procs map[string]release.Process) []string // sorted; not web, release or console; ValidWorkerName; at most 4 |
| - type rootfsWorker struct { |
| - name string |
| - proc Proc |
| - gen uint64 // the generation whose build and env it runs |
| - started, retryAt time.Time |
| - backoff time.Duration |
| - restarts int |
| - crashLoop, starting bool |
| - 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 StartRootfsWorker 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 |
| - // actEntry: rootfsWorkers map[string]*rootfsWorker; strayRootfsWorkers []*rootfsWorker |
| - ``` |
| - |
| -Rules: |
| -- **Start after `web` is healthy** (spec §5.4): in `doWake` after step 6, for a rootfs row, on the wake's generation `w.gen`: one `StartRootfsWorker` per name, from that generation's staged image and its launch env (`launchEnvProc`), 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 from the build the generation runs, never from the live link. More than 4 names, or an invalid one, starts no worker and logs once; `web` serves. |
| -- **Supervision** in `rootfsTick`, 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:4823`); a start that lost its entry stops what it started and proves it gone before `startDone` closes. |
| -- **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`) and `RootfsWorkerGone`; unproven ones go to `strayRootfsWorkers`. `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. |
| -- **Pins:** `entryGenerationsLocked` adds the build of every worker and stray (`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`. |
| - |
| -```go |
| -func TestRootfsWorkersStartAfterWebHealthy(t *testing.T) // log order: start(web) ok, then start(jobs), start(mailer); a failed web |
| - // start starts no worker |
| -func TestRootfsWorkerCrashNeverStopsWeb(t *testing.T) // jobs exits ten times: entry stays awake, rep not closed, delays 2,4,...,60 s |
| - // (fake clock), crash-loop event once |
| -func TestCleanExitingWorkerIsRestartedNotParked(t *testing.T) // exit status 0 every time: same as above |
| -func TestRootfsWorkersStopFirstAndProven(t *testing.T) // Bounce: log order gone(jobs) before stop(web) before rep.Close; |
| - // with RootfsWorkerGone failing once: stop pending, rep open, lease held; next sweep proves it and finishes the stop |
| -func TestRootfsWorkerStartRacesStop(t *testing.T) // RACE: a restart blocked inside StartRootfsWorker 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 TestRootfsWorkerLaunchIsTheGenerationsEnv(t *testing.T) // backend: StartRootfsWorker got the generation's image (StagedImage path, digest, Process "jobs"), memory_max the rootfs tier; the |
| - // worker's launch file (A4) has Process "jobs" and env == rootfsWorkerVars over the gen's launch env |
| -func TestWorkerImagePinnedWhileItRuns(t *testing.T) // generationsSnapshotLocked lists the worker's build while it runs and while stray |
| -func TestRootfsWorkersReport(t *testing.T) // the four states |
| -``` |
| - |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWorker|TestCleanExitingWorker|TestTooManyWorkers|TestWorkerImagePinned' -count=1`. 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`, and `-run 'Stop|Sidecar|Releasable|Generations'`. Expected: PASS. |
| -- [ ] **Step 5: Commit** |
| - |
| -```bash |
| -git add internal/activator approved_rootfs_copy_test.go |
| -git commit -m "activator: rootfs workers start after web is healthy, restart with backoff, stop first and are proven gone" |
| -``` |
| - |
| ---- |
| - |
| ### Task 10: The release runner |
| |
| +**Review:** cross-model (pre-flight §7): release lease supervision and the cmd unit proof. |
| + |
| **Files:** |
| -- Create: `internal/activator/rootfsrelease.go`, `internal/activator/rootfsrelease_test.go`, `internal/activator/rootfs_ctl_harness_test.go` |
| -- Modify: `internal/activator/backend_rootfs.go` (release half), `internal/activator/cmdunit.go` (`StartCmd`'s body 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/backend_exec.go:763` (`execLease.SafeUntil`, `execLease.Lost`, beside `Err`) |
| -- Modify: `internal/rolloutwords/words.go` (events), `internal/status/snapshot.go:403` (reason words) |
| +- 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/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) |
| |
| **Interfaces:** |
| -- Consumes: `CmdUnit` (`cmdunit.go:95`), `cmdHold` (`cmd.go:140`), `listenCmdStream`, `runPendingRecord` (`beforeexec.go:319`), `recordBuild` (`beforeexec.go:45`), `withExecGate`/`runExecGate` (`swap.go:391`, `containment.go:57`), `leaseLost`'s shape (`activator.go:357`), `errSwapLeaseLost` (`swapadmit.go:12`), `cmdStopBound` (`cmd.go:68`), `instanceEnvLayer`, `EnsureAdminTokenBeneath`, `ensureInstanceKeyFor`, `replicaKeyGate`, A2, A3, A5, A8 (Plan 2's runtime-aware cmd unit), Task 6's `rootfsCmdVars`; `lease.Held.SafeUntil`/`Lost` and `lease.Replicator.SafeUntil`/`Lost` (`internal/lease/lease.go:227-231`, `:466-470`). |
| +- Consumes: `CmdUnit` (`cmdunit.go:95`), `cmdHold` (`cmd.go:91`, `newCmdHold` `:140`), `cmdBusyLocked` (`cmd.go:284`), `listenCmdStream`, `runPendingRecord` (`beforeexec.go:319`), `recordBuild` (`beforeexec.go:45`), `withExecGate`/`runExecGate` (`genbackend.go:80`, `:96`), `leaseLost`'s shape (`activator.go:357`), `errSwapLeaseLost` (`swapadmit.go:12`), `cmdStopBound` (`cmd.go:68`), `instanceEnvLayer`, `EnsureAdminTokenBeneath`, `ensureInstanceKeyFor`, `replicaKeyGate`, `release.ReadStagedManifest` (`versions.go:264`), `Manifest.IsRootfs`/`BoxArtifact` (`release.go:153`, `:169`), A3, A5, A8 (Plan 2's runtime-aware cmd unit), Task 6's `rootfsCmdVars`, N1's typed `CmdRootfs`; `lease.Held.SafeUntil`/`Lost` and `lease.Replicator.SafeUntil`/`Lost` (`internal/lease/lease.go:237-241`, `:476-480`). |
| - Produces: |
| ```go |
| type ReleaseBackend interface { |
| - Processes(id release.StagedIdentity) (map[string]release.Process, error) |
| + // 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(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 runExecGate(ctx) immediately before CmdRootfs; a refusal there is launchRefused and nothing reached root. |
| - // Its first call is the egress readiness slot (Astra R2 finding 4): Plan 5 Task 7 puts b.EgressReady(ctx, rt.Host) there, before |
| - // runPendingRecord and runExecGate, so a migration reaches a database granted with this deploy; nothing in this plan. |
| + // StartRelease runs runPendingRecord(ctx) and runExecGate(ctx) immediately before CmdRootfs; a refusal there is |
| + // launchRefused and nothing reached root. |
| StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) |
| } |
| + func stagedImageOf(id release.StagedIdentity, process string, argv []string) instancectl.StagedImage // beside stagedExeOf |
| // leaseWatch is the held lease a release runs under: the wake's Lease on a cold wake (execLease, before it becomes a |
| // replica), e.rep (*lease.Replicator) in an overlap swap. Both production types have it; a lease without it runs no release. |
| type leaseWatch interface { |
| @@ -712,8 +821,8 @@ git commit -m "activator: rootfs workers start after web is healthy, restart wit |
| 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 |
| 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; the lease-loss error above; |
| - // ctx's own error when ctx ended; errSwapBusy when a run holds the cmd unit |
| + // 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 |
| const ( status.ReasonRelease = "release"; status.ReasonReleaseTimeout = "release-timeout" ) |
| ``` |
| |
| @@ -736,34 +845,39 @@ own := func() error { |
| ``` |
| |
| `runRelease`, in order: |
| -1. `procs := Processes(id)`; 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` through `cmdHoldsLocked`) and `RunCmd` starts nothing beside it. |
| -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 its egress readiness slot (empty here; Plan 5 Task 7 fills it, Astra R2 finding 4), then `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. |
| +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. |
| +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, childEnv(env))` (A3: schema 2, no argv) and `RootfsControl.CmdRootfs(ctx, host, rootfsTier.MemoryMax, stagedImageOf(id, release.ProcessRelease, nil))` (A5); 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)`), 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 hold detached: 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. |
| +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). |
| 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. |
| |
| -The callers (Task 11) treat the lease-loss error as they treat `errSwapLeaseLost` today: an overlap abandons (`stepResult`, `swap.go:229`); 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). |
| +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`). |
| |
| -- [ ] **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()`, `server.go:306`) 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()`. 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). |
| +- [ ] **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). |
| |
| ```go |
| func TestReleaseDue(t *testing.T) // table: rootfs, B != good: due; B == good (version and digest): not; |
| // same version, other digest: due; no release process: not; binary row: not |
| func TestReleaseTimeoutBounds(t *testing.T) // 0 -> 600 s; 120 -> 120 s; 7 h -> 6 h |
| // backend half, rootfsCtlHarness |
| +func TestProcessesBelongToTheImage(t *testing.T) // [pf 1.9] B's manifest: B's processes; a manifest whose rootfs artifact digest |
| + // differs from id.Digest, or a binary manifest: refused |
| func TestReleaseRunsInTheCmdUnitFromTheNewImage(t *testing.T) // systemctl log starts carlos-instance-rootfs-cmd@<host>; root's resolved |
| // launch names B's path and digest and Process "release", never the live link's; launch.cmd.json has Process "release", |
| - // CARLOS_DB nested, CARLOS_SOCKET == rt.Socket, no CARLOS_CONTROL_SOCKET; the build state names B before the /cmd request |
| + // CARLOS_DB nested, CARLOS_SOCKET == rt.Socket, no CARLOS_CONTROL_SOCKET; the build state names B before the /cmd request; |
| + // the /cmd memory_max is b.tier(rt).MemoryMax |
| func TestReleasePollsTheRootfsCmdUnit(t *testing.T) // the rootfs cmd unit active/running under the started invocation, no binary |
| // cmd unit: three successive Polls answer CmdRunning, never CmdGone; flip it to inactive, Result exit-code, ExecMainStatus 3: |
| // Poll answers CmdDone with Status "3" |
| func TestReleaseStopProvesTheRootfsCmdUnitGone(t *testing.T) // StopAndSettle: the log has "stop carlos-instance-rootfs-cmd@<host>.service" |
| // 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 |
| 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 |
| @@ -774,6 +888,8 @@ func TestReleaseExecGateRefusesAtTheLastMoment(t *testing.T) // the gate flips t |
| 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 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 |
| @@ -793,9 +909,11 @@ func TestStopSettlesARunningRelease(t *testing.T) // RACE: Bounce while t |
| // before rep.Close (ordered log); RunCmd during the release starts no unit. Run with -race. |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRelease|TestStopSettlesARunningRelease' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| +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 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`, and the cmd families (`-run 'Cmd|RunCmd'`), which the `startCmdUnit` refactor touches. Expected: PASS. |
| +- [ ] **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** |
| |
| ```bash |
| @@ -805,52 +923,58 @@ git commit -m "activator: the rootfs release command runs in the rootfs cmd unit |
| |
| --- |
| |
| -### Task 11: Release at deploy and at wake; workers handed over in an overlap |
| +### Task 11: Release at deploy and at wake |
| + |
| +**Review:** cross-model (pre-flight §7): C7 and C8 at four sites. |
| + |
| +The worker handover of the first draft's step 8, `TestOverlapHandsOverWorkersNeverTwoSets` and the cold-wake "no worker started" assertions are W2's [pf 6.1]. This task leaves one hook where workers will start. |
| |
| **Files:** |
| -- Modify: `internal/activator/swap.go`: `swapOverlap` between step 3a's `admit` (`:546`) and step 3's `spawnSuccessor` (`:554`), so the release passes the same attempt gate (`:541`) the successor does, and the successor's own gate runs again after it; step 8 (`:683`) |
| +- Modify: `internal/activator/swap.go`: `swapOverlap` (`:415`) between step 3a's `admit` (`:554`) and step 3's `spawnSuccessor` (`:561`), so the release passes the same attempt gate (`gate := ...`, `:549-553`) the successor does, and the successor's own gate runs again after it; step 8 (`:690`, beside `replaceSidecar`), the workers hook |
| - Modify: `internal/activator/swaphold.go:352` `startPinnedChecked` |
| - Modify: `internal/activator/wakeplan.go:370` `spawnPlanned` |
| -- Modify: `internal/activator/activator.go` `doWake` step 4 (`:2391`, the identity branch) and its start-error switch |
| +- Modify: `internal/activator/activator.go` `doWake` step 4 (`:2421`; the planned and pinned branches at `:2540`, `:2544`, the identity branch `ib != nil` at `:2546`) and its start-error switch (`:2571`); after step 6 (`:2638`), the workers hook |
| - Modify: `internal/rollout/events.go:36` `reasonWord`; `internal/rolloutwords/words.go` (`reasons`) |
| - Create: `internal/activator/rootfs_deploy_test.go`, `internal/rollout/rootfs_reason_test.go` |
| |
| **Interfaces:** |
| -- Consumes: Task 10's `runRelease`, `leaseWatch`, `ReleaseError`, `errReleaseUnproven`, `errReleaseLeaseLost`, `errReleaseNoLease`; Task 9's `stopRootfsWorkers`, `startRootfsWorkers`; each site's existing ownership gate: `swapOverlap`'s attempt gate (the `memberCurrentLocked` closure of step 3a, `swap.go:541`, which it hands `spawnSuccessor`), `startPinnedChecked`'s `gate` (`swaphold.go:353`), `planGate(ctx, e, lease, plan, plan.Boot)` (`wakeplan.go:144`), and for `doWake`'s pinned branch `leaseLost(lease)` then `a.wakeOwned(ctx, e)`. |
| +- Consumes: Task 10's `runRelease`, `leaseWatch`, `ReleaseError`, `errReleaseUnproven`, `errReleaseLeaseLost`, `errReleaseNoLease`, `Processes`; N1's rootfs `StartStaged` and `healthBoundFor`; each site's existing ownership gate: `swapOverlap`'s attempt gate (the `memberCurrentLocked` closure of step 3a, `swap.go:549`, which it hands `spawnSuccessor`), `startPinnedChecked`'s `gate` (`swaphold.go:353`), `planGate(ctx, e, lease, plan, build string)` (`wakeplan.go:145`, called with `plan.Boot.Version`), and for `doWake`'s pinned branch `leaseLost(lease)` then `a.wakeOwned(ctx, e)`. |
| - Produces: |
| ```go |
| - func (a *Service) handOverRootfsWorkers(e *actEntry) // stop and prove the old set, then start the set of e.gen |
| // 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 |
| + // "activator: %s: build %s declares workers (%s); this box does not run workers yet" (a diagnostic, D8). W1 and W2 fill it. |
| ``` |
| |
| 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, 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, and the lease-loss error, abandon through `stepResult` (`errSwapLeaseLost` is already there, `swap.go:229`); otherwise `failSwap` 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)` when the release ran, so the hold reports down, as a hold build that ran and failed does today. The lease-loss error is 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 | the wake's `lease`; `planGate(ctx, e, lease, plan, plan.Boot)` | 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 is not B's failure: it is 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: `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 | |
| | 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 (`activator.go:4563`), 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. |
| - |
| -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:2376`): 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, no worker. 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. |
| +`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. |
| |
| -Every site in the table reaches root through `StartRelease`, so each `release` waits for the bounded egress readiness pass first once Plan 5 lands (its slot, Task 10 step 3; Astra R2 finding 4): a release that migrates a database granted with this deploy finds it open, and is never failed for a connection the periodic pass had not opened yet. Workers (`StartRootfsWorker`, Task 9) and `carlos run` (the rootfs `StartCmd`, Task 12) carry the same slot before their root call. |
| +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. |
| |
| `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. |
| |
| -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. |
| +The workers hook (D8): `doWake` calls `a.rootfsWorkersHook(ctx, e, rt, w.gen)` after step 6, for a rootfs row, once `web` is healthy; `swapOverlap` calls it at step 8, beside `replaceSidecar`, for the new generation. In group A it only logs, once per wake or swap, when the build declares workers; it starts nothing and never fails the wake. W1 makes the `doWake` call start the generation's workers, and W2 makes the step 8 call hand them over. |
| |
| -- [ ] **Step 1: Write the failing tests** on the existing swap fixtures (`internal/activator/swap_fixture_test.go`), with `fakeBackend` implementing Tasks 9 and 10's interfaces and an ordered event log: |
| +- [ ] **Step 1: Write the failing tests** on the existing swap fixtures (`internal/activator/swap_fixture_test.go`), with `fakeBackend` implementing Task 10's interface and an ordered event log: |
| |
| ```go |
| func TestOverlapReleaseFailureKeepsTheIncumbent(t *testing.T) // incumbent gen 1 on A; attempt B, release exits 1: SwapFailed, |
| // Reason has prefix "release", Executed true; StartStaged never called; e.gen.N == 1; the incumbent's proc not stopped; |
| - // AppSocket unchanged; workers of gen 1 untouched |
| + // AppSocket unchanged |
| func TestOverlapReleaseTimeoutKeepsTheIncumbent(t *testing.T) // same with a timeout; Reason prefix "release timed out" |
| func TestOverlapRunsReleaseBeforeTheSuccessor(t *testing.T) // log: release(B) done, then StartStaged(B), then switch |
| func TestOverlapAbandonsWhileARunIsOpen(t *testing.T) // e.cmd set: SwapAbandoned, no release, no spawn |
| +func TestSwapReleaseRefusedByRootAbandons(t *testing.T) // INV-4 [pf 1.7]. rootfsCtlHarness behind the real client: root answers |
| + // 503 on /cmd mid-swap: SwapAbandoned, no OnGen failure, no failure-book entry, the incumbent serving |
| func TestHoldReleaseFailureIsDown(t *testing.T) // ModeHold: old stopped, release fails: SwapDown, pinExec true |
| func TestAsleepRowRunsReleaseBeforeServing(t *testing.T) // hibernating rootfs row, plan boots B (not good): release then Start; |
| // a request waiting on the wake is proxied only after Start |
| @@ -861,8 +985,8 @@ func TestReleaseRerunsAfterInterruptedWake(t *testing.T) // the wake is canc |
| // GoodVersion unchanged; a new Service over the same registry runs release(B) again before Start |
| func TestColdWakeReleaseStopsOnLeaseLoss(t *testing.T) // Review Focus 6. Hibernating rootfs row, plan boots B; fakeLease.lost |
| // closed while release(B) polls (the entry is actWaking, so no sweep helps): the release unit is stopped and proven before |
| - // fakeLease's until; the wake fails with errSwapLeaseLost; fb.starts == 0 (no web, no fallback A), no worker started; no |
| - // ReleaseError and no OnGen failure for B; the ordered log has settle(release) before release-lease; GoodVersion unchanged |
| + // fakeLease's until; the wake fails with errSwapLeaseLost; fb.starts == 0 (no web, no fallback A); no ReleaseError and no |
| + // OnGen failure for B; the ordered log has settle(release) before release-lease; GoodVersion unchanged |
| 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 |
| @@ -874,50 +998,56 @@ func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) // RACE: fakeRep.lo |
| // for the release hold (cmdHold.stop joins it), the incumbent stopped once, rep.Close after the proof. 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 TestOverlapHandsOverWorkersNeverTwoSets(t *testing.T) // RACE: timeline of worker starts/stops with generation: every gen-1 stop |
| - // precedes every gen-2 start, and gen-2 starts follow the successor's health; with one gen-1 worker unproven, no gen-2 worker |
| - // starts until a tick proves it. Run with -race. |
| +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 |
| func TestReasonWordRelease(t *testing.T) // "release: the release command of build v2 exited with status 1" -> |
| // ReasonRelease; "release timed out: ..." -> ReasonReleaseTimeout; existing words unchanged |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapRelease|TestOverlapRunsRelease|TestOverlapAbandonsWhileARun|TestHoldReleaseFailure|TestAsleepRowRunsRelease|TestFirstWakeReleaseFailure|TestRestartDoesNotRerunRelease|TestReleaseRerunsAfterInterruptedWake|TestColdWakeRelease|TestSwapRelease|TestReleaseRefusedWhenOwnershipEnds|TestOverlapHandsOverWorkers' -count=1` 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|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 'TestOverlapHandsOverWorkers|TestSwapReleaseLeaseLossRacesTheSweep' -count=3`, and the swap and wake-plan families (`-run 'Swap|Hold|Planned|FirstWake|Overlap'`, and `go test ./internal/rollout/ -run 'Reason|Scheduler' -count=1`). Expected: PASS. |
| +- [ ] **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** |
| |
| ```bash |
| git add internal/activator internal/rollout internal/rolloutwords approved_rootfs_copy_test.go |
| -git commit -m "rootfs: release gates every move onto a new build; a failure keeps the incumbent; workers handed over after the switch" |
| +git commit -m "rootfs: release gates every move onto a new build; a failure keeps the incumbent; a refusal is never the build's failure" |
| ``` |
| |
| --- |
| |
| ### Task 12: `carlos run` on rootfs rows, and `--version` |
| |
| +**Review:** cross-model (pre-flight §7): the rootfs run's cmd unit proof. |
| + |
| **Files:** |
| -- Modify: `internal/activator/cmdunit.go` `StartCmd` (`:172`), `CmdSpec` (`:38`); `internal/activator/cmd.go` `RunCmd` (`:449`); `internal/activator/generations_file.go:177` (a run's build pinned) |
| -- Modify: `internal/runs/runs.go` (`Meta`, `Request`, `RefusedVersion`); `internal/console/apiruns.go` (`runClassRefusal` `:55`, the version check beside `runMetaRefusal`); `internal/host/runexec.go:78` (`runResultForLaunch`, the spec's `Build`), `internal/host/runevents.go:65` (`runRefusedWords`); `run.go` (`:28` usage, `:64` the flag, `:697` `runExit`) |
| -- Modify: `docs/site/cli.md` (the `carlos run` section, `:581`) |
| +- Modify: `internal/activator/cmdunit.go` `StartCmd` (`:172`; its rootfs arm replaces the `nestedGate` refusal at `:179` for rootfs rows only [pf 8.7]), `CmdSpec` (`:38`); `internal/activator/cmd.go` `RunCmd` (`:449`, `spec.serving` at `:600-602`); `internal/activator/generations_file.go:177` (a run's build pinned) |
| +- Modify: `internal/runs/runs.go` (`Meta` `:146`, `Request` `:174`, `RefusedVersion` beside `RefusedFlat` `:47`); `internal/console/apiruns.go` (`runClassRefusal` `:268`, the version check beside `runMetaRefusal` `:286`); `internal/host/runexec.go:77` (`runResultForLaunch`, the spec's `Build`), `internal/host/runevents.go:70` (`runRefusedWords`); `run.go` (`:30` usage, the flag beside `--timeout` at `:71`, `:740` `runExit`) |
| +- Modify: `approved_run_copy_test.go`: `runCopySuperseded` [pf 8.4] |
| +- Modify: `docs/site/cli.md` (the `### carlos run` section, `:587`) |
| - Create: `internal/activator/rootfs_cmd_test.go`, `internal/console/apiruns_rootfs_test.go`; tests in `run_test.go`, `internal/host/runexec_test.go` |
| +- Modify: `internal/activator/rootfs_invariants_test.go` (INV-1 and INV-5 run rows) |
| |
| **Interfaces:** |
| -- Consumes: Task 6's `rootfsCmdVars`, A3, A5, A8 (Plan 2's runtime-aware cmd unit), Task 10's `startCmdUnit` and `rootfsCtlHarness`, `ExecBackend.BuildIdentity` (`backend_exec.go:1809`), `release.GetManifest` (`internal/release/release.go:710`). |
| +- Consumes: Task 6's `rootfsCmdVars`, A3, A5, A8 (Plan 2's runtime-aware cmd unit), N1's typed `CmdRootfs`, Task 10's `startCmdUnit`, `stagedImageOf` and `rootfsCtlHarness`, `ExecBackend.BuildIdentity` (`backend_exec.go:1842`), `release.GetManifest` (`internal/release/release.go:804`). |
| - Produces: |
| ```go |
| // activator.CmdSpec.Build string: "" runs the serving generation's build (today); a version runs that staged build |
| var ErrCmdVersion = errors.New("activator: the build named for a run is not staged on this box") |
| // runs.Meta.Version, runs.Request.Version string `json:"version,omitempty"`; const runs.RefusedVersion = "version" |
| + // approved_run_copy_test.go: a pinned, test-only map of run-deck ids a later deck's built row replaces |
| + var runCopySuperseded = map[string]string{"RUN-C47": "RFS-3-C18"} |
| ``` |
| |
| Rules: |
| -- `StartCmd` on a rootfs row (its first call is the egress readiness slot Plan 5 Task 7 fills, before `CmdRootfs`; Astra R2 finding 4): the tenant launch file is Plan 2's schema 2 with `Process: "cmd"` and no argv; the argv is `spec.Args` as given (no live-link prefix), sent to root as `StagedImage.Argv` through `RootfsControl.CmdRootfs(ctx, host, rootfsTier.MemoryMax, stagedImageOf(id, "", spec.Args))` (A3, A5); env `rootfsCmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir)`; the image identity is required (a rootfs command always names its image; none refuses with `errNoCmdExe`). 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`, `settleCmds` and the sweep's `retryCmdSettlesLocked` 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. |
| +- `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. |
| -- Console: `runClassRefusal` passes a rootfs record that does not hibernate (`rec.Runtime == provision.RuntimeRootfsV1`), and keeps the fleet refusal for every record (D4): 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. |
| +- 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`. |
| -- With claim control armed `RunCmd` already refuses (`ErrCmdClaim`, `cmd.go:450`); nothing changes there. |
| +- The run gate [pf 8.4]: RFS-3-C18 replaces `runUsageRun` (`run.go:30`), which is the run deck's built and approved RUN-C47 (`docs/superpowers/plans/2026-10-08-carlos-run-copy.md:96`), and the run deck has no struck status. In the same commit, `runCopySuperseded` (pinned, test-only) is honoured by `TestRunBuiltCopyIsApplied` (`approved_run_copy_test.go:138`) and `TestRunCopyIsFullyBuilt` (`:192`): a superseded id is not checked as applied, and counts as built while its replacing id is in `rootfsCopyBuilt` and applied. A test pins the map's one entry. |
| +- (The first draft's line on `ErrCmdClaim`, `cmd.go:31`, is struck: claims are shelved and the cleanup removes it [pf 3.2].) |
| |
| - [ ] **Step 1: Write the failing tests:** |
| |
| @@ -925,12 +1055,13 @@ Rules: |
| // internal/activator/rootfs_cmd_test.go |
| func TestRootfsCmdRunsArgsInTheImage(t *testing.T) // rootfsCtlHarness: the /cmd request carries StagedImage.Argv == spec.Args (no /opt/carlos/live |
| // prefix) and the serving image, and the systemctl log starts carlos-instance-rootfs-cmd@<host>; launch.cmd.json is schema 2 |
| - // with Process "cmd" and no Argv; env has CARLOS_SOCKET == rt.Socket and CARLOS_RUN_ID |
| + // with Process "cmd" and no Argv; env has CARLOS_SOCKET == rt.Socket and CARLOS_RUN_ID, and no PATH from the agent |
| func TestRootfsRunPollsAndStopsTheRootfsUnit(t *testing.T) // Review Focus 7. rootfsCtlHarness, the run started through Service.RunCmd |
| // on an awake rootfs entry, no binary cmd unit: the handle's Poll answers CmdRunning while the rootfs unit runs and CmdDone |
| // with its status after it exits; Stop sends "stop carlos-instance-rootfs-cmd@<host>.service" (never "stop carlos-instance-cmd@") |
| // and is unproven while the rootfs unit's cgroup is populated; a Bounce during the run keeps the stop pending, lease and |
| // replica held, until the rootfs cgroup empties |
| +func TestRootfsRunRefusedByRootIsARefusal(t *testing.T) // the harness answers /cmd 503: errors.Is(err, errRootfsRefused), nothing started |
| 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 |
| @@ -942,15 +1073,19 @@ func TestRunDoorVersionChecks(t *testing.T) // "v 1": 400 C19; unknown b |
| func TestRunResultForVersionRefusal(t *testing.T) // Refused "version", Detail the build |
| // run_test.go |
| func TestRunVersionFlag(t *testing.T) // --version v2 reaches meta.Version; runExit for RefusedVersion: exit 3 and C21 |
| +// approved_run_copy_test.go |
| +func TestRunCopySupersededIsPinned(t *testing.T) // runCopySuperseded == {"RUN-C47": "RFS-3-C18"}; RFS-3-C18 is built and applied |
| ``` |
| |
| -- [ ] **Step 2:** Run the four packages' tests with `-run` on these names (the activator ones under the short `TMPDIR`: the harness binds a unix socket). Expected: FAIL. |
| -- [ ] **Step 3:** Implement; write `RFS-3-C17` to `C22`, `C26`, `C27`, `C28` (the `docs/site/cli.md` paragraphs; C28 is the fleet sentence Plan 6 Task 16 strikes, after the section's existing paragraph on hibernating instances), and add their ids to the built list. |
| -- [ ] **Step 4:** Run Step 2's commands, plus `go test . -run 'TestRun|TestDocsite' -count=1` and `go test ./internal/docsite/ -count=1`. Expected: PASS. |
| +The invariant tables gain the run rows: INV-1, the run's `cmdUnit` through the harness; INV-5, the run launch file under `t.Setenv("PATH", "/agent/bin")`. |
| + |
| +- [ ] **Step 2:** Run the four packages' tests and the root package's with `-run` on these names (the activator ones under the short `TMPDIR`: the harness binds a unix socket). Expected: FAIL. |
| +- [ ] **Step 3:** Implement; write `RFS-3-C17` to `C22`, `C26`, `C27`, `C28` (the `docs/site/cli.md` paragraphs; C28 is the fleet sentence Plan 6 Task 16 strikes, after the section's existing paragraph on hibernating instances, `cli.md:601`), and add their ids to the built list. |
| +- [ ] **Step 4:** Run Step 2's commands, plus `go test . -run 'TestRun|TestDocsite|TestRootfsCopy|TestRootfsBuilt' -count=1` and `go test ./internal/docsite/ -count=1`, and Task 1's guards and goldens. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| -git add internal/activator internal/runs internal/console internal/host run.go run_test.go docs/site/cli.md approved_rootfs_copy_test.go |
| +git add internal/activator internal/runs internal/console internal/host run.go run_test.go docs/site/cli.md approved_rootfs_copy_test.go approved_run_copy_test.go |
| git commit -m "carlos run: rootfs rows run in their image; --version runs a staged build" |
| ``` |
| |
| @@ -958,190 +1093,385 @@ git commit -m "carlos run: rootfs rows run in their image; --version runs a stag |
| |
| ### Task 13: Moves refuse rootfs rows |
| |
| +**Review:** not cross-model (pre-flight §7): console doors over provision checks. The control is in `provision`; the doors only give the words. |
| + |
| **Files:** |
| -- Modify: `internal/provision/runtime.go` (`RootfsMoveError`, `rootfsMoveRefusal`); `internal/provision/provision.go` (`SetRecordRegion` `:918`, `MoveRequest` `:1291`, `MoveStartTransition` `:1328`); `internal/provision/offline_move.go:157` |
| -- Modify: `internal/console/seedmove.go` (`refuseRootfsMove`, `placeRootfsBlock`, `rootfsMoveConflict`); the callers `apiinstancemove.go:410`, `:566`, `apiinstancemove_offline.go:487`, `fleets.go:622`, `:713` |
| +- Modify: `internal/provision/runtime.go` (`RootfsMoveError`, `rootfsMoveRefusal`); `internal/provision/provision.go` (`SetRecordRegion` `:1000`, `MoveRequest` `:1444`, `MoveStartTransition` `:1481`); `internal/provision/offline_move.go` (`OfflineStage`, `:166`) |
| +- Modify: `internal/console/seedmove.go` (`refuseRootfsMove`, `placeRootfsBlock`, `rootfsMoveConflict`); the callers `apiinstancemove.go:411`, `apiinstancemove_offline.go:490`, `fleets.go:622`, `:713` |
| - Create: `internal/provision/rootfs_move_test.go`, `internal/console/rootfs_move_test.go` |
| |
| **Interfaces:** |
| - Produces: |
| ```go |
| type RootfsMoveError struct{ Host string } // wraps ErrMoveConflict, as SeedMoveError does (seed.go:320) |
| - func rootfsMoveRefusal(rec *Record) error // non-nil for a rootfs record; called beside each seedMoveRefusal |
| + func rootfsMoveRefusal(rec *Record) error // non-nil for a rootfs record; called at every seedMoveRefusal call site |
| func (s *Server) refuseRootfsMove(w http.ResponseWriter, rec *provision.Record) bool // 409 RFS-3-C23 |
| func placeRootfsBlock(ctx context.Context, st release.Store, acct, app string) (bool, error) // any rootfs record of the app |
| func rootfsMoveConflict(err error) string // RFS-3-C24 for a RootfsMoveError met under a CAS, "" otherwise |
| ``` |
| |
| -`SetRecordRegion` refuses only when the region changes, so a placement that leaves a rootfs instance where it is still succeeds. `carlos apps place` refuses before it writes the app's placement when any record of the app is rootfs (`placeRootfsBlock`, read as `placeSeedBlock` reads, `seedmove.go:43`), so no placement is left half-applied. The box already refuses a nested row (`routeRefusal`, `internal/host/movesphase1.go:675`); this makes the refusal early and says why. |
| +The control is the provision transitions: `MoveRequest`, `MoveStartTransition`, `OfflineStage` and `SetRecordRegion` [pf 3.4]. `rootfsMoveRefusal` is called beside `seedMoveRefusal` (`seed.go:330`) at every one of its call sites (`provision.go:1003`, `:1446`, `:1483`, `offline_move.go:182`), so a door added later, such as self-serve member moves, inherits it. The console doors (`apiinstancemove.go:411`, `apiinstancemove_offline.go:490`, `fleets.go:622` and `:713`) only give the words, C23 and C24, before the transition would refuse anyway. |
| + |
| +`SetRecordRegion` refuses only when the region changes, so a placement that leaves a rootfs instance where it is still succeeds. `carlos apps place` refuses before it writes the app's placement when any record of the app is rootfs (`placeRootfsBlock`, read as `placeSeedBlock` reads, `seedmove.go:44`, which now takes a `*provision.LifetimeJudge`), so no placement is left half-applied. (The first draft cited the box's nested-row refusal in `movesphase1.go` and the Phase 1 half of the move door, `apiinstancemove.go:557-567`; R4a of the claims cleanup deletes both, so neither is cited or edited [pf 3.4].) |
| |
| - [ ] **Step 1: Write the failing tests:** |
| |
| ```go |
| func TestMoveTransitionsRefuseRootfs(t *testing.T) // MoveRequest, MoveStartTransition, OfflineStage: errors.As(err, *RootfsMoveError), |
| - // errors.Is(err, ErrMoveConflict); record unchanged |
| + // errors.Is(err, ErrMoveConflict); record unchanged; and a rootfs record never reaches the held mint (mintHeld) [pf 2.3] |
| func TestSetRecordRegionRefusesARootfsMove(t *testing.T) // other region: refused; same region: nil |
| +func TestEverySeedMoveRefusalSiteRefusesRootfs(t *testing.T) // go/ast over internal/provision's non-test files: every function that |
| + // calls seedMoveRefusal also calls rootfsMoveRefusal on the same record, and the set of such functions is pinned |
| func TestMoveDoorsRefuseRootfs(t *testing.T) // POST .../move and the offline door: 409 with C23, no record write |
| func TestPlaceRefusesAnAppWithRootfsInstances(t *testing.T) // 409 C24 before the app placement is written (store read-back unchanged) |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/provision/ -run 'TestMoveTransitionsRefuseRootfs|TestSetRecordRegionRefusesARootfsMove' -count=1` and `go test ./internal/console/ -run 'TestMoveDoorsRefuseRootfs|TestPlaceRefusesAnAppWithRootfs' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/provision/ -run 'TestMoveTransitionsRefuseRootfs|TestSetRecordRegionRefusesARootfsMove|TestEverySeedMoveRefusalSite' -count=1` and `go test ./internal/console/ -run 'TestMoveDoorsRefuseRootfs|TestPlaceRefusesAnAppWithRootfs' -count=1`. Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C23` and `C24`, add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's commands and the move families (`-run 'Move|Place|Offline'` in both packages). Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| git add internal/provision internal/console approved_rootfs_copy_test.go |
| -git commit -m "moves: refuse rootfs instances at every move door and at carlos apps place" |
| +git commit -m "moves: refuse rootfs instances in every move transition and at carlos apps place" |
| ``` |
| |
| --- |
| |
| -### Task 14: Worker states in the rollout report |
| +### Task 15: The rootfs rollback floor in `carlos system apply` |
| + |
| +**Review:** cross-model (pre-flight §7): root-run (`carlos system apply`). |
| |
| -Plan 4 renders runtime and workers in the CLI and reads them from the rollout report (its D3). This task produces exactly the shape Plan 4 names; the release failure needs no field (Task 11's reason words). |
| +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/status/snapshot.go:322` (`HostRollout.Workers`, `WorkerState`) |
| -- Modify: `internal/rollout/manager.go:30` (`Activator` gains `RootfsWorkers`), `internal/rollout/status.go:19` (filled per host), `internal/rollout/fake_test.go` (the fake gains the method) |
| -- Create: `internal/rollout/rootfs_status_test.go` |
| +- Modify: `internal/host/systemapply.go` `install` (`:493`, after the layout guard at `:525`) |
| +- Create: `internal/host/systemapply_rootfs_test.go` |
| |
| **Interfaces:** |
| -- Consumes: Task 9's `Service.RootfsWorkers`. |
| -- Produces (Plan 4's D3, verbatim): |
| +- Consumes: the candidate's staged unit set (`newUnits`, `:506`), the applier's `openRegistry` seam (`:251`), which defaults to `openSystemRegistry` (`:176`), as `layoutReversalReasons` (`:1241`) uses it. |
| +- Produces: |
| ```go |
| - type WorkerState struct { |
| - Name string `json:"name"` |
| - State string `json:"state"` // running | restarting | crash-loop | stopped |
| - Restarts int `json:"restarts,omitempty"` |
| + const rootfsInstanceUnit = "carlos-instance-rootfs@.service" // the contract's template name |
| + func rootfsRowsPresent(reg *registry.Registry) ([]string, error) // hosts whose row has Runtime != "", sorted; |
| + // reg is the *Registry openSystemRegistry returns (the service-user child), never one root opens itself |
| + 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`). |
| + |
| +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`. |
| + |
| +- [ ] **Step 1: Write the failing tests** (no `t.Parallel()`: the applier's seams are package vars where the layout floor's tests set them): |
| + |
| +```go |
| +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 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 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 commit -m "system apply: a box with rootfs instances refuses a platform release that cannot run them" |
| +``` |
| + |
| +--- |
| + |
| +### Task 16: Gate A (Plan 3 is mergeable) |
| + |
| +**Review:** not cross-model (pre-flight §7). |
| + |
| +- [ ] **Step 1:** Merge `origin/main`, keeping the claims cleanup's deletions on conflict [pf 3.3]. `go build ./... && go vet ./...` and `gofmt -l .` (empty). Expected: clean. |
| +- [ ] **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 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]. |
| + |
| +--- |
| + |
| +## Group W: workers (may merge after Plan 3) |
| + |
| +Plan 3 may merge without this group. Until it lands, a build that declares workers serves `web`, and Task 11's hook logs once per wake that this box does not run workers yet (D8). Plan 4 depends on this group (index), because its sample app may declare workers. The dependency cannot be cut further [pf 6.1]. |
| + |
| +The agent side of a worker is unbuilt on main [pf 1.4]: `prepareKeyedAt` (`prepare.go:59`) takes no worker name and its default arm reads the sidecar env (`:102-109`); `logSocketFor` (`:239`) keys by role, giving `<iid>.worker.sock`, not `WorkerLogSocket(host, name)`; `exitPrefix` (`:188`) and `recordName` (`unitproc.go:455`) use role and gen; `writeRootfsLaunchFor` (`:283`) writes `launch.worker.json`, but the trampoline reads `WorkerLaunchFileName(name)` (`internal/instanceexec/exec.go:174`); `newUnitProcFor` (`unitproc.go:106`) refuses `RoleWorker`, because `unitNameFor` (`:146`) answers `""`; `stopRole` (`:165-171`) passes worker `""`, which root answers with 400 (`internal/instancectl/rootfs.go:1130-1133`). W1 builds that identity end to end. If a worker fault family reaches fix round 3, the group stops and the controller decides whether to simplify or refuse up front; group A is unaffected. |
| + |
| +### Task W1: Workers |
| + |
| +**Review:** cross-model (pre-flight §7): worker proofs, strays, `releasable`. |
| + |
| +This is the first draft's Task 9, with the worker identity, Task 6's worker half and the pre-flight's worker rows [pf 6.1, 1.3, 1.4, 1.5, 2.4, 8.1, 8.2]. |
| + |
| +**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/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) |
| +- Modify: `internal/activator/rootfs_invariants_test.go` (INV-1 and INV-5 worker rows) |
| +- No change to `internal/activator/control.go`: the worker verbs are Plan 2's `RootfsControl` (A4) |
| + |
| +**Interfaces:** |
| +- Consumes: Task 10's `Processes(rt, id)` and `stagedImageOf`; A4 (`RootfsControl.StartRootfsWorker`, `StopRootfs` with its `kill` argument, `WorkerUnitName`, `WorkerLaunchFileName`, `WorkerLogSocket`, `WorkerExitPrefix`, `WorkerExitRecordName`); Plan 2's `writeRootfsLaunchFor`, `rootfsControl()` (`rootfs.go:107`), `rootfsLaunchEnv`, `unitEvents` (`rootfs.go:423`); `agentOwnedVars` (`backend_exec.go:2359`); `launchEnvProc` (`unitProc.LaunchEnv`); `waitUnitCgroupEmpty` (`backend_exec.go:1685`). |
| +- Produces: |
| + ```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) |
| + // 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 |
| } |
| - // HostRollout.Workers []WorkerState `json:"workers,omitempty"` |
| - // rollout.Activator: RootfsWorkers(host string) []activator.WorkerReport |
| + // workers: rootfsVars over the generation's agent-owned vars, with sock = rt.Socket (D1) [pf 8.1] |
| + func (b *ExecBackend) rootfsWorkerVars(rt registry.Route, g Gen, dbPath string, genEnv map[string]string) map[string]string |
| + // = rootfsVars(b.agentOwnedVars(rt, g.Control, genEnv, haveControl), rt.Socket, dbPath) |
| + func (b *ExecBackend) prepareWorker(rt registry.Route, name string) (instancePaths, *logListener, error) |
| + // directories, no env file, no control listener, the log listener at WorkerLogSocket(host, name), WorkerExitPrefix(name) cleared |
| + func (b *ExecBackend) writeRootfsWorkerLaunch(p instancePaths, host, name string, env []string) error // WorkerLaunchFileName(name) |
| + func rootfsUnitFor(rt registry.Route, role instancectl.Role, gen uint64, worker string) string |
| + // WorkerUnitName(host, worker) for RoleWorker; RootfsUnitName otherwise. unitNameFor is not widened (Plan 2 fix F4) |
| + func workerNames(procs map[string]release.Process) []string // sorted; not web, release or console; ValidWorkerName; at most 4 |
| + type rootfsWorker struct { |
| + name string |
| + proc Proc |
| + gen uint64 // the generation whose build and env it runs |
| + started, retryAt time.Time |
| + backoff time.Duration |
| + restarts int |
| + crashLoop, starting bool |
| + 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) 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 |
| + // actEntry: rootfsWorkers map[string]*rootfsWorker; strayRootfsWorkers []*rootfsWorker; unitProc: worker string |
| ``` |
| |
| -`Manager.Status` asks the activator after it has released every scheduler lock, in the same pass that asks `Current` and `Owns` (`askActivator`, the lock order its doc states). A binary host reports no `workers` key. |
| +Rules: |
| +- **The worker identity** [pf 1.4]: a `unitProc.worker` field; `rootfsUnitFor` answers `WorkerUnitName` for a worker; `prepareWorker` makes the directories, reads no env file (a worker's env is its generation's), binds no control listener, binds its log listener at `WorkerLogSocket(host, name)` (the path Plan 2's `WorkerDropIn` points `StandardOutput=` at) and clears `WorkerExitPrefix(name)`; `writeRootfsWorkerLaunch` writes `WorkerLaunchFileName(name)`, schema 2, `Process: <name>`, no argv; `stopRole` passes the worker name; `recordName` and `removeLaunch` have worker forms. Each is tested through `fakeControl` and the real file names. |
| +- **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. |
| +- **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. |
| +- **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 test:** |
| +- [ ] **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. |
| |
| ```go |
| -func TestRolloutReportCarriesWorkers(t *testing.T) // fake activator answers two workers for a rootfs host: Status().Hosts[host].Workers |
| - // has both, in name order; a binary host's JSON has no "workers" key |
| +func TestRootfsWorkersStartAfterWebHealthy(t *testing.T) // log order: start(web) ok, then start(jobs), start(mailer); a failed web |
| + // start starts no worker |
| +func TestRootfsWorkerCrashNeverStopsWeb(t *testing.T) // jobs exits ten times: entry stays awake, rep not closed, delays 2,4,...,60 s |
| + // (fake clock), crash-loop event once |
| +func TestCleanExitingWorkerIsRestartedNotParked(t *testing.T) // exit status 0 every time: same as above |
| +func TestRootfsWorkersStopFirstAndProven(t *testing.T) // Bounce: log order gone(jobs) before stop(web) before rep.Close; |
| + // with RootfsWorkerGone failing once: stop pending, rep open, lease held; next sweep proves it and finishes the stop |
| +func TestRootfsWorkerStopAnswers(t *testing.T) // [pf 2.4] fakeControl answers the worker /stop 409, then 204: a stray after |
| + // 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 |
| + // 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, |
| + // 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 TestRootfsWorkersReport(t *testing.T) // the four states |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/rollout/ -run TestRolloutReportCarriesWorkers -count=1`. Expected: FAIL. |
| -- [ ] **Step 3:** Implement. |
| -- [ ] **Step 4:** Run Step 2's command and `go test ./internal/rollout/ -run 'Status' -count=1`. Expected: PASS. |
| +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 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** |
| |
| ```bash |
| -git add internal/status internal/rollout |
| -git commit -m "rollout: the box reports each rootfs instance's worker states" |
| +git add internal/activator approved_rootfs_copy_test.go |
| +git commit -m "activator: rootfs workers start after web is healthy, restart with backoff, stop first and are proven gone" |
| ``` |
| |
| --- |
| |
| -### Task 15: The rootfs rollback floor in `carlos system apply` |
| +### Task W2: Workers handed over in an overlap |
| |
| -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`). |
| +**Review:** cross-model (pre-flight §7): never two worker sets. |
| + |
| +This is the first draft's Task 11 step 8, its `TestOverlapHandsOverWorkersNeverTwoSets` and its cold-wake "no worker" assertions [pf 6.1]. |
| |
| **Files:** |
| -- Modify: `internal/host/systemapply.go` `install` (`:493`, after the layout guard) |
| -- Create: `internal/host/systemapply_rootfs_test.go` |
| +- Modify: `internal/activator/swap.go` (step 8, `:690`: Task 11's `rootfsWorkersHook` becomes the handover), `internal/activator/rootfsworkers.go` |
| +- Modify: `internal/activator/rootfs_deploy_test.go` |
| |
| **Interfaces:** |
| -- Consumes: the candidate's staged unit set (`newUnits`, `:506`), `openSystemRegistry` (`:176`). |
| +- Consumes: W1's `stopRootfsWorkers`, `startRootfsWorkers`, `rootfsWorkersGone`; Task 11's hook. |
| - Produces: |
| ```go |
| - const rootfsInstanceUnit = "carlos-instance-rootfs@.service" // the contract's template name |
| - func rootfsRowsPresent(reg *registry.Registry) ([]string, error) // hosts whose row has Runtime != "", sorted |
| - const systemApplyRootfsRefusal = "<RFS-3-C25>" |
| + func (a *Service) handOverRootfsWorkers(e *actEntry) // stop and prove the old set, then start the set of e.gen |
| ``` |
| |
| -When the candidate's units lack `rootfsInstanceUnit` and the registry has a rootfs row, the apply is refused before the journal (`errSystemRefused`, the layout guard's wrapping), naming the hosts. A registry that will not open or list is itself the reason, as `layoutReversalReasons` treats it (`:1241`). 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`). |
| +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. |
| |
| -- [ ] **Step 1: Write the failing tests** (no `t.Parallel()`: the applier's seams are package vars where the layout floor's tests set them): |
| +- [ ] **Step 1: Write the failing tests:** |
| |
| ```go |
| -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 TestOverlapHandsOverWorkersNeverTwoSets(t *testing.T) // RACE: timeline of worker starts/stops with generation: every gen-1 stop |
| + // precedes every gen-2 start, and gen-2 starts follow the successor's health; with one gen-1 worker unproven, no gen-2 worker |
| + // starts until a tick proves it. Run with -race. |
| +func TestOverlapReleaseFailureLeavesWorkersAlone(t *testing.T) // release(B) exits 1: gen-1 workers untouched, none of B's started |
| +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 |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/host/ -run 'TestApplyRefusesACandidateWithoutRootfs|TestApplyAllowsWithoutRootfs|TestApplyAllowsACandidateWithRootfs' -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 2:** Run `go test ./internal/activator/ -run 'TestOverlapHandsOverWorkers|TestOverlapReleaseFailureLeavesWorkers|TestColdWakeReleaseLeaseLossStartsNoWorker|TestConfigAttemptHandsOverWorkers' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** Run Step 2's command, `go test -race ./internal/activator/ -run 'TestOverlapHandsOverWorkers' -count=3`, and `-run 'Swap|Overlap|ColdWake|Worker'`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| -git add internal/host/systemapply.go internal/host/systemapply_rootfs_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" |
| +git add internal/activator |
| +git commit -m "activator: rootfs workers handed over after the switch; never two worker sets" |
| ``` |
| |
| --- |
| |
| -### Task 16: The plan's gate |
| +### Task W3: Worker states in the rollout report |
| |
| -- [ ] **Step 1:** `go build ./... && go vet ./...` and `gofmt -l .` (empty). Expected: clean. |
| -- [ ] **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/ -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|TestDocsite` group. Expected: PASS. |
| -- [ ] **Step 4:** `go test -race ./internal/activator/ -run 'TestResidentRequestAndTickRaceOneWake|TestResidentCrashDuringStopIsOneStop|TestRootfsWorkerStartRacesStop|TestStopSettlesARunningRelease|TestReleaseLeaseLossRacesExit|TestSwapReleaseLeaseLossRacesTheSweep|TestOverlapHandsOverWorkersNeverTwoSets' -count=1`. Expected: PASS. |
| -- [ ] **Step 5:** Every `RFS-3-C` id is in the gate's built list: `go test . -run TestRootfsCopy -count=1`. Expected: PASS. Push the branch to amadan; CI runs the full suite. Post on #250 that the claim's activation now owes `worker` and the rootfs cmd in the reservation protocol. |
| +**Review:** not cross-model (pre-flight §7). |
| + |
| +This is the first draft's Task 14. Plan 4 renders runtime and workers in the CLI and reads them from the rollout report (its D3). This task produces exactly the shape Plan 4 names; the release failure needs no field (Task 11's reason words). |
| + |
| +**Files:** |
| +- Modify: `internal/status/snapshot.go:328` (`HostRollout.Workers`, `WorkerState`) |
| +- Modify: `internal/rollout/manager.go:30` (`Activator` gains `RootfsWorkers`), `internal/rollout/status.go:19` (filled per host, in `askActivator`, `:142`), `internal/rollout/fake_test.go` (the fake gains the method) |
| +- Create: `internal/rollout/rootfs_status_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: W1's `Service.RootfsWorkers`. |
| +- Produces (Plan 4's D3, verbatim): |
| + ```go |
| + type WorkerState struct { |
| + Name string `json:"name"` |
| + State string `json:"state"` // running | restarting | crash-loop | stopped |
| + Restarts int `json:"restarts,omitempty"` |
| + } |
| + // HostRollout.Workers []WorkerState `json:"workers,omitempty"` |
| + // rollout.Activator: RootfsWorkers(host string) []activator.WorkerReport |
| + ``` |
| + |
| +`Manager.Status` asks the activator after it has released every scheduler lock, in the same pass that asks `Current` and `Owns` (`askActivator`, the lock order its doc states). A binary host reports no `workers` key. |
| + |
| +- [ ] **Step 1: Write the failing test:** |
| + |
| +```go |
| +func TestRolloutReportCarriesWorkers(t *testing.T) // fake activator answers two workers for a rootfs host: Status().Hosts[host].Workers |
| + // has both, in name order; a binary host's JSON has no "workers" key |
| +``` |
| + |
| +- [ ] **Step 2:** Run `go test ./internal/rollout/ -run TestRolloutReportCarriesWorkers -count=1`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** Run Step 2's command and `go test ./internal/rollout/ -run 'Status' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Commit** |
| + |
| +```bash |
| +git add internal/status internal/rollout |
| +git commit -m "rollout: the box reports each rootfs instance's worker states" |
| +``` |
| + |
| +--- |
| + |
| +### Task W gate |
| + |
| +- [ ] **Step 1:** Merge `origin/main` as gate A did; Steps 1 and 2 of gate A. Expected: clean. |
| +- [ ] **Step 2:** `go test ./internal/activator/ ./internal/rollout/ ./internal/status/ -count=1` under `nice`, one package at a time. Expected: PASS. |
| +- [ ] **Step 3:** `go test -race ./internal/activator/ -run 'TestRootfsWorkerStartRacesStop|TestOverlapHandsOverWorkersNeverTwoSets' -count=1`. Expected: PASS. |
| +- [ ] **Step 4:** Gate A's Step 5 (the invariants, the `instancectl` diff). Every live `RFS-3-C` id, C08 to C10 included, is in the built list: `go test . -run 'TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. The controller pushes; CI runs the full suite. |
| |
| --- |
| |
| ## String table |
| |
| -Every row goes to the deck in Task 1 and reaches code only once approved. `%s` and `%d` are the placeholders the code formats. |
| +Every row goes to the deck in Task 1 and reaches code only once approved. `%s` and `%d` are the placeholders the code formats. Each file cell is the one file that holds the literal, with the where-it-appears note in parentheses (pre-flight 8.3; the texts did not change). |
| |
| | id | file | text | |
| |---|---|---| |
| -| RFS-3-C01 | `internal/rolloutwords/words.go` (`reasons["release"]`, read after "because") | its release command failed | |
| -| RFS-3-C02 | `internal/rolloutwords/words.go` (`reasons["release-timeout"]`) | its release command did not finish in time | |
| -| RFS-3-C03 | `internal/rolloutwords/words.go` (`EventReleaseStarted`) | running the release command of build %s | |
| -| RFS-3-C04 | `internal/rolloutwords/words.go` (`EventReleaseDone`) | the release command of build %s finished in %s | |
| -| RFS-3-C05 | `internal/rolloutwords/words.go` (`EventReleaseFailed`; also `ReleaseError.Error`) | the release command of build %s exited with status %d | |
| -| RFS-3-C06 | `internal/rolloutwords/words.go` (`EventReleaseSignal`; also `ReleaseError.Error`) | the release command of build %s was ended by signal %s | |
| -| RFS-3-C07 | `internal/rolloutwords/words.go` (`EventReleaseTimedOut`; also `ReleaseError.Error`) | the release command of build %s did not finish within %s, so it was stopped | |
| -| RFS-3-C08 | `internal/rolloutwords/words.go` (`EventWorkerStarted`) | worker %s started | |
| -| RFS-3-C09 | `internal/rolloutwords/words.go` (`EventWorkerExited`) | worker %s exited with status %d. starting it again in %s | |
| -| RFS-3-C10 | `internal/rolloutwords/words.go` (`EventWorkerCrashLoop`) | worker %s keeps exiting. it is started again once a minute | |
| -| RFS-3-C11 | `internal/rolloutwords/words.go` (`EventResidentExited`) | instance exited. starting it again in %s | |
| -| RFS-3-C12 | `internal/rolloutwords/words.go` (`EventRootfsRefused`) | this box cannot run the instance: %s | |
| -| RFS-3-C13 | `internal/rolloutwords/words.go` (`RootfsRefusedClaims`, fills C12) | host claims are armed here | |
| -| RFS-3-C14 | `internal/rolloutwords/words.go` (`RootfsRefusedUnarmed`, fills C12) | overlap swaps are not armed here | |
| -| RFS-3-C15 | `internal/activator/rootfs_service.go` (`errRootfsReplicaMissing`, the member's wake reason) | the instance has served before and its database replica is missing, so it was not started with an empty database | |
| -| RFS-3-C16 | `internal/activator/activator.go` (`serveWakeError`, the 503 body for `errResidentBackoff`) | instance is restarting; retry shortly | |
| -| RFS-3-C17 | `run.go` (the `--version` flag's help) | a build of the app to run instead of the one the instance serves | |
| -| RFS-3-C18 | `run.go` (`runUsageRun`, replacing today's approved line at `:28`) | usage: carlos run --app <app> --instance <host> [--file <path>]... [--timeout 30m] [--version <build>] -- <arg>... | |
| -| RFS-3-C19 | `internal/console/apiruns.go` (400) | %s is not a build name | |
| -| RFS-3-C20 | `internal/console/apiruns.go` (409) | %s has no build %s | |
| -| RFS-3-C21 | `run.go` (`runExit`, refused version) | %s: build %s is not on the instance's box, so the run did not start | |
| -| RFS-3-C22 | `internal/host/runevents.go` (`runRefusedWords`, version) | the build is not on the box | |
| -| RFS-3-C23 | `internal/console/seedmove.go` (`refuseRootfsMove`, 409) | %s is a rootfs instance, and a rootfs instance does not move. create a new instance where you want it | |
| -| RFS-3-C24 | `internal/console/seedmove.go` (`rootfsMoveConflict`, `carlos apps place`) | this app's instances are rootfs instances, which do not move. create new instances where you want them | |
| -| RFS-3-C25 | `internal/host/systemapply.go` (`systemApplyRootfsRefusal`) | %s cannot run rootfs instances, and this box still has: %s. delete those instances before installing it | |
| -| RFS-3-C26 | `docs/site/cli.md` (`carlos run`, a paragraph) | --version runs another build of the app against the instance, for example the build a deploy is about to bring in. The build must already be on the instance's box. The command still gets the environment the instance serves with. | |
| -| RFS-3-C27 | `docs/site/cli.md` (`carlos run`, a paragraph) | For a rootfs app the command after -- runs inside the instance's image and is found on the image's PATH. | |
| -| RFS-3-C28 | `docs/site/cli.md` (`carlos run`, the same paragraph) | carlos run does not reach instances on a customer fleet yet. | |
| -| RFS-3-C29 | `internal/rolloutwords/words.go` (`EventReleaseLeaseLost`) | the release command of build %s was stopped because this box no longer holds the instance. it runs again on the next attempt | |
| - |
| -Count: 29 (RFS-3-C29 added in the Astra R1 fix round; Task 1 Step 2 takes it to the deck and Paul). (RFS-3-C28 is live until Plan 6 Task 16 marks it struck when runs reach fleet boxes, R7.) |
| +| RFS-3-C01 | internal/rolloutwords/words.go (reasons["release"], read after "because") | its release command failed | |
| +| RFS-3-C02 | internal/rolloutwords/words.go (reasons["release-timeout"]) | its release command did not finish in time | |
| +| RFS-3-C03 | internal/rolloutwords/words.go (EventReleaseStarted) | running the release command of build %s | |
| +| RFS-3-C04 | internal/rolloutwords/words.go (EventReleaseDone) | the release command of build %s finished in %s | |
| +| RFS-3-C05 | internal/rolloutwords/words.go (EventReleaseFailed; also ReleaseError.Error) | the release command of build %s exited with status %d | |
| +| RFS-3-C06 | internal/rolloutwords/words.go (EventReleaseSignal; also ReleaseError.Error) | the release command of build %s was ended by signal %s | |
| +| RFS-3-C07 | internal/rolloutwords/words.go (EventReleaseTimedOut; also ReleaseError.Error) | the release command of build %s did not finish within %s, so it was stopped | |
| +| RFS-3-C08 | internal/rolloutwords/words.go (EventWorkerStarted) | worker %s started | |
| +| RFS-3-C09 | internal/rolloutwords/words.go (EventWorkerExited) | worker %s exited with status %d. starting it again in %s | |
| +| RFS-3-C10 | internal/rolloutwords/words.go (EventWorkerCrashLoop) | worker %s keeps exiting. it is started again once a minute | |
| +| RFS-3-C11 | internal/rolloutwords/words.go (EventResidentExited) | instance exited. starting it again in %s | |
| +| RFS-3-C12 | internal/rolloutwords/words.go (EventRootfsRefused) | this box cannot run the instance: %s | |
| +| RFS-3-C13 | internal/rolloutwords/words.go (RootfsRefusedClaims, fills C12; struck 2026-10-26 by the Plan 3 pre-flight, row 3.1: host lifecycle claims are shelved and Plan 3 reads no claim switch) | host claims are armed here | |
| +| RFS-3-C14 | internal/rolloutwords/words.go (RootfsRefusedUnarmed, fills C12) | overlap swaps are not armed here | |
| +| RFS-3-C15 | internal/activator/rootfs_service.go (errRootfsReplicaMissing, the member's wake reason) | the instance has served before and its database replica is missing, so it was not started with an empty database | |
| +| RFS-3-C16 | internal/activator/activator.go (serveWakeError, the 503 body for errResidentBackoff) | instance is restarting; retry shortly | |
| +| RFS-3-C17 | run.go (the --version flag's help) | a build of the app to run instead of the one the instance serves | |
| +| RFS-3-C18 | run.go (runUsageRun, replacing today's approved line at :30, RUN-C47, which Plan 3 Task 12 marks superseded in the run gate) | usage: carlos run --app <app> --instance <host> [--file <path>]... [--timeout 30m] [--version <build>] -- <arg>... | |
| +| RFS-3-C19 | internal/console/apiruns.go (400) | %s is not a build name | |
| +| RFS-3-C20 | internal/console/apiruns.go (409) | %s has no build %s | |
| +| RFS-3-C21 | run.go (runExit, refused version) | %s: build %s is not on the instance's box, so the run did not start | |
| +| RFS-3-C22 | internal/host/runevents.go (runRefusedWords, version) | the build is not on the box | |
| +| RFS-3-C23 | internal/console/seedmove.go (refuseRootfsMove, 409) | %s is a rootfs instance, and a rootfs instance does not move. create a new instance where you want it | |
| +| RFS-3-C24 | internal/console/seedmove.go (rootfsMoveConflict, carlos apps place) | this app's instances are rootfs instances, which do not move. create new instances where you want them | |
| +| RFS-3-C25 | internal/host/systemapply.go (systemApplyRootfsRefusal) | %s cannot run rootfs instances, and this box still has: %s. delete those instances before installing it | |
| +| RFS-3-C26 | docs/site/cli.md (carlos run, a paragraph) | --version runs another build of the app against the instance, for example the build a deploy is about to bring in. The build must already be on the instance's box. The command still gets the environment the instance serves with. | |
| +| RFS-3-C27 | docs/site/cli.md (carlos run, a paragraph) | For a rootfs app the command after -- runs inside the instance's image and is found on the image's PATH. | |
| +| RFS-3-C28 | docs/site/cli.md (carlos run, the same paragraph) | carlos run does not reach instances on a customer fleet yet. | |
| +| RFS-3-C29 | internal/rolloutwords/words.go (EventReleaseLeaseLost) | the release command of build %s was stopped because this box no longer holds the instance. it runs again on the next attempt | |
| + |
| +Count: 29 rows, 28 live, 1 struck (RFS-3-C13). (RFS-3-C28 is live until Plan 6 Task 16 marks it struck when runs reach fleet boxes, R7.) Built by: C12, C14, C15 Task 7; C11, C16 Task 8; C03 to C07 and C29 Task 10; C01, C02 Task 11; C17 to C22 and C26 to C28 Task 12; C23, C24 Task 13; C25 Task 15; C08 to C10 W1. |
| |
| ## Hand-offs to other plans |
| |
| -- **Plan 4.** The create door calls `provision.RuntimeFromManifest` on the creating release and writes `Runtime` and `Hibernate` before `ValidateShape` (Plan 4 Task 3 already does this inline; the helper gives both the same answer). The member door that refuses a never-sleeping instance (`internal/console/apiinstances.go:~1026`) must pass a rootfs record. The console refusal to move the platform channel below the first rootfs release sits beside `layoutDowngradeBlocked`. The CLI's runtime and workers cells read Task 14's `HostRollout.Workers`. A console must not be rolled back below this plan's release once rootfs records exist: an older console strips `runtime` on rewrite (Task 4 keeps the box safe, but the record then reads as binary in the console's own views). |
| +- **Plan 4.** The create door calls `provision.RuntimeFromManifest` on the creating release and writes `Runtime` and `Hibernate` before `ValidateShape` (Plan 4 Task 3 already does this inline; the helper gives both the same answer). The member door that refuses a never-sleeping instance (`internal/console/apiinstances.go`) must pass a rootfs record. The console refusal to move the platform channel below the first rootfs release sits beside `layoutDowngradeBlocked`. The CLI's runtime and workers cells read W3's `HostRollout.Workers`, so Plan 4 depends on Group W (index). A console must not be rolled back below this plan's release once rootfs records exist: an older console strips `runtime` on rewrite (Task 4 keeps the box safe, but the record then reads as binary in the console's own views). |
| - **Plans-caps Plan 3b** (never-sleep refusals): never refuse a rootfs record on the customer's own boxes (spec §5.6); a resident has no idle clock, so the box's plans idle hook never reaches it (Task 8). |
| -- **#250 (claim activation):** add `worker` and the rootfs cmd unit to the reservation protocol; until then every rootfs launch refuses on a claim-armed box (Task 7). |
| +- **Claims cleanup (#404, design-live-moves-ha).** Plan 3 adds no reader of the claim switch and depends on none of the code R3 to R9 delete. Each Plan 3 task merges `origin/main` first and keeps the cleanup's deletions on conflict. The first draft's hand-off to #250 (adding `worker` and the rootfs cmd to the claim reservation protocol) is struck: claims are shelved [pf 3.2]. |
| - **Plan 6:** an interactive session runs in a unit of its own role (`RoleTTY`, Plan 6 D1), not the cmd unit, so it never shares the host's cmd unit with `release` or a run; Plan 6 Task 9 decides what a swap does to an open session (a deploy ends it with the stop's reason). Plan 6 Task 16 carries `carlos run` to fleet boxes over its door (R7) and removes the fleet arm of `runClassRefusal`, striking RFS-3-C28. |
| |
| ## Questions only Paul can answer |
| |
| -None open. The one this plan raised, `carlos run` on fleet boxes (D4), Paul answered on 2026-10-24 (index ruling R7): it is carried over Plan 6's box-dials-the-console door, Plan 6 Task 16; until then it is refused there, and the spec §6 step 1 sample does not depend on it. |
| +None open. The one this plan raised, `carlos run` on fleet boxes (D4), Paul answered on 2026-10-24 (index ruling R7): it is carried over Plan 6's box-dials-the-console door, Plan 6 Task 16; until then it is refused there, and the spec §6 step 1 sample does not depend on it. Paul's 2026-10-25 rulings (no census task; claims shelved) are applied above. |
| |
| ## Self-review notes |
| |
| -- Spec coverage. §5.0 record half: Tasks 2 to 4 (and the mint helper for Plan 4). §5.2 environment: Task 6; deploy overlap and worker handover: Task 11. §5.2.1: Tasks 10 and 11 (overlap, hold, hibernating wake, first boot, rollback leaves the schema, distinct from seeds by D5). §5.4: Task 9 (start after healthy, stop first, cap 4, crash restart, crash loop in logs and status, Task 14). §5.5 `carlos run` and `--version`: Task 12; moves: Task 13; seeds: D5. §5.6: Tasks 7 and 8 (boot, crash, adoption, ceiling, no idle, replication with the activator, Task 5's ops change), the version floor (Task 15 and Plans 2 and 4), no local database (every rootfs row keeps its SQLite path, Task 4), plans-caps (hand-off). §7 C5: every process is a unit (Tasks 9, 10, 12); C7: release and workers run under the incumbent's or the wake's lease, and a release is gated on ownership and stopped and proven gone before the lease's safety deadline (Tasks 10 and 11, Astra R1 finding 2); C8: Task 11's overlap tests. B1-4's empty SQLite file: D7, Task 7. |
| -- What the claim-armed box does: Global Constraints and Task 7 (residency, wake, workers and release refuse; `RunCmd` already refuses). |
| -- 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 `rootfsWorkerVars`, `rootfsCmdVars` in Tasks 9, 10, 12; Plan 2's `RootfsControl` verbs (A4, A5) and Task 9's `stagedImageOf` in Tasks 9, 10, 12; `runRelease`, `leaseWatch`, `ReleaseError`, `errReleaseUnproven`, `errReleaseLeaseLost`, `errReleaseNoLease` (Task 10) in Task 11; Task 10's `startCmdUnit` and `rootfsCtlHarness` in Task 12; `rootfsDBPlacer`, `PlaceRootfsDB` (Task 7) in Task 11's first-boot order; `RootfsWorkers`, `WorkerReport` (Task 9) in Task 14; `stopRootfsWorkers`, `rootfsWorkersGone`, `handOverRootfsWorkers` in Tasks 9 and 11. |
| +- Spec coverage. §5.0 record half: Tasks 2 to 4 (and the mint helper for Plan 4). §5.2 environment: Task 6 and W1; deploy overlap: N1 and Task 11; worker handover: W2. §5.2.1: Tasks 10 and 11 (overlap, hold, hibernating wake, first boot, rollback leaves the schema, distinct from seeds by D5). §5.4: W1 (start after healthy, stop first, cap 4, crash restart, crash loop in logs and status, W3). §5.5 `carlos run` and `--version`: Task 12; moves: Task 13; seeds: D5. §5.6: Tasks 7 and 8 (boot, crash, adoption, ceiling, no idle, replication with the activator, Task 5's ops change), the version floor (Task 15 and Plans 2 and 4), no local database (every rootfs row keeps its SQLite path, Task 4), plans-caps (hand-off). §7 C5: every process is a unit (Tasks 10, 12, W1); C7: release and workers run under the incumbent's or the wake's lease, and a release is gated on ownership and stopped and proven gone before the lease's safety deadline (Tasks 10 and 11, Astra R1 finding 2); C8: N1's swap tests and Task 11's overlap tests. B1-4's empty SQLite file: D7, Task 7. |
| +- 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`). |
| +- **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. |
| + - 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). |
| + - 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. |