| index d3fbb1156..78fdc72e7 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,9 +2,9 @@ |
| |
| > **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; 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. |
| +**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; `carlos run` works on rootfs rows and gains `--version`; moves refuse rootfs rows (Group A). The `release` process runs from the new image at each deploy and gates the switch once Group R lands, and declared workers run beside `web` once Group W lands; Plan 3 merges with Group A alone, and R and W follow 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. 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. |
| +**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 (Group R, after A) is one service-owned operation in the rootfs cmd unit from the new image: before an overlap swap is admitted, under the incumbent's lease, the swap then running only on a proven pass; and inside a wake (planned, hold, or onto a build the row has not served), under the wake's lease. A failure is the build's failure, so the incumbent keeps serving; losing the lease stops it and proves it gone before the lease's safety deadline, and is never the build's failure. Until Group R lands, an app migrates in its own web command (`db:prepare` before the server, as Rails 8's Docker entrypoint does). Workers (Group W, after A) 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`, `internal/release`; systemd through `instancectl` (Plan 3 changes only `internal/instancectl/client.go` there). |
| |
| @@ -20,32 +20,33 @@ They come from where Plan 2 spun. Plan 2's Task 11 rounds 1 to 5 and its final w |
| |
| - **INV-1. Runtime first, rootfs proof.** Every agent start, stop, kill, poll and proof of a rootfs row (generation, worker, release, run) goes to the rootfs unit and is proven through `unitEvents` (`waitUnitCgroupEmpty`). Never the binary unit, `Control.Stop`/`StopGen`/`Cmd`/`CmdExe`/`CmdStatus`, `KillHost`, `EmptyHost` or a binary cgroup read. |
| - *Guard (Task 1):* `TestRootfsFilesNameNoBinaryVerb`, a go/ast check over the non-test `rootfs*.go` and `backend_rootfs.go` in `internal/activator` that refuses those identifiers and `childEnv`, resolved through selectors and method values. |
| - - *Behaviour (Task 1, then N1, Tasks 10 and 12, and W1):* `TestEveryRootfsProofNamesTheRootfsUnit`, a table over each handle's Stop, Poll and Kill. Its fakes have no binary unit and a populated reported group, so each handle must stay unproven, and `KillHost`/`EmptyHost` refuse a rootfs row. Task 1 lands it with the handles main already has (a rootfs generation's `unitProc`, the rootfs `cmdUnit`), so the runtime dispatch in the shared files the guard does not scan (`cmdunit.go:260-293`, `unitproc.go:146-171`) is covered from the first commit: Task 1's mutation evidence flips each dispatch and shows this test fail [Astra R1 11]. |
| -- **INV-2. No rootfs file goes before the proof.** Agent side: a worker's launch file, exit records and stray entry, and a release or run hold, go only after `RootfsWorkerGone`, or after the cmd unit's `StopAndSettle`, returned nil. Root side: Plan 3 adds no removal owner, and `TestRootfsRemovalGuard`'s allowlist is unchanged. |
| + - *Behaviour (Task 1, then N1, Task 12, R1 and W1):* `TestEveryRootfsProofNamesTheRootfsUnit`, a table over each handle's Stop, Poll and Kill. Its fakes have no binary unit and a populated reported group, so each handle must stay unproven, and `KillHost`/`EmptyHost` refuse a rootfs row. Task 1 lands it with the handles main already has (a rootfs generation's `unitProc`, the rootfs `cmdUnit`), so the runtime dispatch in the shared files the guard does not scan (`cmdunit.go:260-293`, `unitproc.go:146-171`) is covered from the first commit: Task 1's mutation evidence flips each dispatch and shows this test fail [Astra R1 11]. |
| +- **INV-2. No rootfs file goes before the proof.** Agent side: a worker's launch file, exit records and stray entry, a run's hold, and (Group R) a release's record, 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 (Tasks 10 and 11, W1):* an unproven stop keeps the obligation that owns it: a release's `releaseRun` record outlives the wake or swap that started it, keeps its lease, its pin and the wake latch, and is retried by its one reaper until proven (`TestReleaseObligationOutlivesTheWake`, `TestReleaseObligationRetriedUntilProven`); a worker's stray keeps `launch.worker.<name>.json`, its exit records and its pin. Each test's mutation (drop the record or the stray on the failure path) makes it fail [Astra R1 11]. |
| + - *Behaviour (Task 12, W1, Group R):* an unproven stop keeps the obligation that owns it: a run's hold stays in `e.cmdLeft` with its pin until `retryCmdSettlesLocked` proves it (Task 12, `TestRootfsRunPollsAndStopsTheRootfsUnit`); a worker's stray keeps `launch.worker.<name>.json`, its exit records and its pin (W1); a release's record keeps its lease, pin and wake latch (Group R's INV-R1 and INV-R2). Each test's mutation (drop the hold, the stray or the record on the failure path) makes it fail [Astra R1 11]. |
| - **INV-3. Refuse before the lease.** A rootfs row on a box that refuses rootfs is refused before `Acquire`, `Restore`, `LiveIdentity`, `recordBuild` or any entry state. That covers each of Plan 2's gate reasons, unarmed, and an unknown runtime. |
| - *Behaviour (Task 7, with Task 8's rows):* `TestRootfsRefusalPrecedesTheLease`, a table over every reason through `doWake`, `begin` and `rootfsTick`, asserting `acquires == restores == materialized == 0`. No guard passes on main here: the gap this invariant closes is the pre-flight's finding [pf 2.1]. |
| -- **INV-4. A refusal is never a build failure.** Every pre-start refusal is classified gateNoOwnership or stale, and never reaches `OnGen`, `SwapFailed`, the failure book or the resident failure count. That covers `errRootfsRefused`, `ErrStagedImage` and `ErrStartRefused` on `/start` and `/cmd`, unarmed, the release's lease loss and `errSwapBusy`. |
| +- **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, and `errSwapBusy`; Group R's INV-R3 classifies every release result on top of it. |
| - *Guard (Task 1):* `TestRootfsRefusalsAreNotBuildFailures`, a `verdictOf`/`classifyStep` table pinning today's rootfs sentinels. |
| - - *Behaviour (N1, Tasks 8, 10 and 11):* client through activator, root answers 503 on `/cmd` mid-swap. Resident accounting reads the same classification: `residentFailure(err)` (Task 8) is false for every INV-4 case (a refusal, the release's lease loss, `errSwapBusy`, `errReleaseUnproven`, `errWakeUnproven`), and the INV-4 table asserts it row by row [Astra R1 11]. |
| + - *Behaviour (N1, Tasks 8 and 12; R1 and R2 for release):* client through activator, root answers 503 on `/cmd` (Task 12's run; R2's swap release). Resident accounting reads the same classification: `residentFailure(err)` (Task 8) is false for every INV-4 case (a refusal, a lease loss, `errSwapBusy`, `errWakeUnproven`), and the INV-4 table asserts it row by row [Astra R1 11]. |
| - **INV-5. Rootfs launch files carry only the composed environment.** Schema 2, no argv, and `env == rootfsLaunchEnv(vars)`: nothing from the agent's process, so no `PATH` or `HOME` unless the tenant's files set them. `CARLOS_SOCKET` and `CARLOS_DB` are agent-owned. |
| - - *Behaviour (Task 1 for web, then Tasks 6, 10 and 12, then W1):* `TestRootfsLaunchFilesCarryOnlyComposedEnv`, with `t.Setenv("PATH", "/agent/bin")`, over web, release, run and worker. Task 1 lands it with the web row, which holds on main (Plan 2's `rootfsLaunchEnv`); each later task adds its row. |
| + - *Behaviour (Task 1 for web, then Tasks 6 and 12, R1 and W1):* `TestRootfsLaunchFilesCarryOnlyComposedEnv`, with `t.Setenv("PATH", "/agent/bin")`, over web, run, release 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). Every Task 5 predicate change only widens a site by residents: binary instances and binary sidecars keep today's answer at every site, and each site's test has a binary-sidecar row [Astra R1 1]. |
| -- **INV-7. One owner for a running release.** From admission to proof a release is owned by exactly one record, `a.releaseRuns[host]` (Task 10), whatever happens to the entry, the wake or the swap that started it. Every consumer (run admission, idle and run ceilings, stop proofs, pins, wake admission, lease give-back) reads that record and nothing else, and one reaper retries its proof [Astra R1 5, 6]. *Behaviour (Tasks 10 and 11):* the INV-2 tests above, plus `TestReleaseRunConsumersReadTheRecord` (each consumer refuses or waits while the record exists, and stops doing so once it is proven and removed). |
| +- **Group R's own invariants** (INV-R1 to INV-R5: one owner for a running release, one retry path whatever the entry's state, every release result classified, an open release blocking every transition, the swap only on a proven pass) are written at the head of Group R, with their tests. No Group A task contains, calls, waits on or tests release machinery. |
| |
| ## 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) | |
| +| A | 1, 2, 3, 4, 5, 6, N1, 7, 8, D, 12, 13, 15, 16 (gate A) | Plan 3 merges after gate A | |
| +| R | R1, R2, R3, R gate | after A; a later merge; Plan 4 does not depend on it (Paul, 2026-10-26) | |
| +| W | W1, W2, W3, W gate | after A; 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]. |
| +R and W each depend on A only, not on each other, and may be built in either order; both edit Task D's hook sites (`doWake` after step 6, `swapOverlap` step 8), so whichever lands second merges the other's edits there. 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, Task 11's worker handover is W2, Task 10 (the release runner) is R1, and Task 11's release sites are R2 (overlap) and R3 (wakes). Task D is new: the declared-processes read both later groups share. No Group A task consumes anything from Group R or Group W [pf 6.1; Paul, 2026-10-26]. |
| |
| 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. |
| +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, 12, 15, R1, R2, R3, W1, W2. Not reviewed cross-model: 1 and 6 (pure composers, behind INV-5), D (a manifest read and a log line), 13 (console doors over provision checks), W3, 16. |
| |
| ## Review dispositions (Astra R1) |
| |
| @@ -62,7 +63,7 @@ Plan 2 has merged, and provides every name below as built; this plan uses main's |
| - **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`). |
| +- **Lease seams (finding 2, Group R).** None from Plan 2. R1 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) |
| @@ -82,35 +83,35 @@ Each is decided here and proposed for the index's "Where the code differs from t |
| - `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, `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. |
| +- **D3. No "release done" column (Group R).** `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. The overlap swap's pass (R2) is in memory and scoped to one attempt, so an agent restart between a passed release and its swap runs the release again, as this deviation already 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. |
| +- **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 `web` (and before `release`, once Group R lands), 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 and `release` land after the rest [pf 6.1; Paul, 2026-10-26].** Group A runs `web` and `carlos run`. Until Group W lands, a build that declares workers serves `web`; until Group R lands, a build that declares `release` serves `web` without running it. Task D logs both once per wake or swap (diagnostics). An app therefore migrates in its own web command until Group R lands, as Rails 8's Docker entrypoint does (`bin/rails db:prepare` before the server). Plan 4 depends on Group W, because its sample app may declare workers, and not on Group R: its sample migrates in its web command (index). |
| |
| ### What this plan assumes from Plans 1 and 2 beyond the contract |
| |
| 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, 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. |
| +- **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 D in `backend_rootfs.go` (with `SplitBackend` forwarding). `StagedIdentity` names no account or app (`internal/release/staged.go:20-25`), so it takes the row [pf 1.9]. It refuses unless the sibling exists, `m.IsRootfs()`, `m.BoxArtifact(platform)` exists and its `SHA256` equals `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`). |
| +- **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 12 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`. |
| +- **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 12's run, R1's release) is that unit, and each task's backend tests go through the real control handler (Task 12'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. |
| +- Values from the spec and the index, verbatim: `release` timeout (Group R) 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 (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. |
| +- 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 (Group R; in Group A no release runs, and an overlap swap is N1's). |
| - 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 backend interface this plan adds (`rootfsStartable`, `rootfsDBPlacer`, `ReleaseBackend`, `RootfsWorkerBackend`) is implemented on `SplitBackend` too, forwarding to `Exec` for an exec-backed row and refusing a unit-backed one, because production builds the service over a `SplitBackend` (`internal/host/agent.go:524`) whose fields promote nothing. Each is covered by `TestProductionBackendImplementsRootfsSeams` and by at least one integration test run through `productionBackend` [Astra R1 4]. |
| +- Every backend interface this plan adds (`rootfsStartable`, `rootfsDBPlacer`, `ProcessReader`, `ReleaseBackend`, `RootfsWorkerBackend`) is implemented on `SplitBackend` too, forwarding to `Exec` for an exec-backed row and refusing a unit-backed one, because production builds the service over a `SplitBackend` (`internal/host/agent.go:524`) whose fields promote nothing. Each is covered by `TestProductionBackendImplementsRootfsSeams` and by at least one integration test run through `productionBackend` [Astra R1 4]. |
| - Nothing slow runs under `a.mu`: no control-service request, store read or file hash. The shape is reserve under the lock, do the I/O off it, retake the lock and re-check ownership before publishing or launching [Astra R1 8]. |
| - Every exec of a rootfs process names a full staged identity (`stagedIdentityOf`: version, path, digest, demand), and that identity is in the generations file on disk before the exec (`publishBeforeExec`); a failed write starts nothing [Astra R1 3, 9]. Every rootfs memory limit comes from `b.tier(rt)` or the generation's `g.Tier` (A6) [pf 1.8]. |
| - Copy: every user-facing string in this plan is a row of the string table below, written into code only after Paul has approved it in the series deck (`2026-10-24-rootfs-apps-copy.md`). A task that writes one adds its id to the gate's built list in the same commit. No em dashes; a full stop and a new sentence, lower case after it as the run deck does; neutral names (`shop`, `example.com`). |
| @@ -124,16 +125,16 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| ## 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. 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`. |
| +2. **(Group R) 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: R3, `TestReleaseRerunsAfterInterruptedWake`; R2, `TestReleaseRerunsAfterAnAgentRestart`. |
| 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`. |
| +6. **(Group R) 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: R1, `TestReleaseStopsBeforeTheSafetyDeadline`; R3, `TestColdWakeReleaseStopsOnLeaseLoss`; R2, `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 12, `TestRootfsRunPollsAndStopsTheRootfsUnit`; R1, `TestReleasePollsTheRootfsCmdUnit` and `TestReleaseStopProvesTheRootfsCmdUnitGone`. |
| 8. **An app that never opens `CARLOS_DB` restarts (D7).** Test: Task 7, `TestRootfsAppWithoutSQLiteRestarts`; the refusal it must not weaken, `TestServedRootfsNeverBootsEmpty`. |
| 9. **A rootfs row swaps, holds and takes a planned wake [pf 1.1].** On main every one of those starts is refused as gateNoOwnership, so under D2 every deploy would be abandoned while `fakeBackend` tests pass. Tests: N1, `TestOverlapSwapStartsTheRootfsGeneration`, `TestHoldSwapStartsTheRootfsGeneration`, `TestPlannedWakeStartsTheRootfsGeneration`, through `fakeControl`, not `fakeBackend`. |
| 10. **A refused rootfs row costs nothing per retry [pf 2.1].** A resident on a box that refuses rootfs must not take the lease, restore, or materialize the live link on every backoff step. Test: Task 7, `TestRootfsRefusalPrecedesTheLease` (INV-3). |
| -11. **An unproven release outlives its wake [Astra R1 5, 6].** The wake fails and its entry is deleted, but the release's unit may still write the database. The record must keep the lease, the pin and the wake latch, and its one reaper must prove the rootfs cmd unit before anything else runs on the host. Tests: Task 11, `TestReleaseObligationOutlivesTheWake`, `TestReleaseObligationRetriedUntilProven`; Task 10, `TestReleaseRunConsumersReadTheRecord`. |
| +11. **(Group R) An unproven release outlives whatever started it [Astra R1 5, 6; Astra R2 N1, N2, N4].** The wake fails and its entry is deleted, or the swap is abandoned and the incumbent stays awake, or the agent shuts down, but the release's unit may still write the database. The record must keep the lease, the pin and the host's transitions blocked, and its one reaper, in the pass the sweep and Shutdown share, must prove the rootfs cmd unit before anything else runs on the host. Tests: R3, `TestReleaseObligationOutlivesTheWake`, `TestReleaseObligationRetriedUntilProven`; R1, `TestReleaseOpConsumersReadTheRecord`, `TestUnprovenReleaseOnAnAwakeIncumbentIsRetried`, `TestShutdownDrainsReleaseOps`; R2, `TestOpenReleaseBlocksEveryTransition`. |
| |
| --- |
| |
| @@ -141,7 +142,7 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| |
| | 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/rootfs_invariants_test.go` (new) | the INV-1, INV-2, INV-4 guards and INV-5's launch-env table | 1, rows added by N1, 6, 12, R1, 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 | |
| @@ -149,23 +150,23 @@ Each is a name this plan consumes, checked against main at the amendment (a912a3 |
| | `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/activator/layout.go`, `wakeidentity.go`, `activator.go` | `ActivatorManaged` and the serve gates on the shared predicate; the idle exemption; the residency hooks; Task D's hook; Group R's release consumers in wake, stop, sweep and Shutdown | 5, 7, 8, D, R1, R3 | |
| | `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/rootfs_service.go` (new; Plan 2 owns `rootfs.go`) | `healthBoundFor` (N1); start gates, `ArmRootfs`, first-wake budget (7); residency state and `rootfsTick` (8); the wake ceiling (R3) | N1, 7, 8, R3 | |
| | `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); `LaunchRootfsWorker`, `RootfsWorkerGone` (W1) | 10, W1 | |
| -| `internal/activator/rootfsrelease.go` (new) | `releaseDue`, `releaseTimeout`, `ReleaseError`, `leaseWatch`, `releaseRun` and `reapReleaseRunsLocked`, `Service.runRelease` and its lease supervisor | 10 | |
| -| `internal/activator/maintenance.go`, `opset.go` | the failed wake hands an unproven release's lease to its record; `releasable` waits on the record | 10, 11 | |
| -| `internal/activator/backend_unit.go`, `production_backend_test.go` (new) | `SplitBackend` forwarding of every new interface; the production composition and its test | 7, 10, W1 | |
| +| `internal/activator/backend_rootfs.go` (new) | `Processes` (D); `stagedImageOf` (12); `StartRelease`, `ReleaseEnv` (R1); `LaunchRootfsWorker`, `RootfsWorkerGone` (W1) | D, 12, R1, W1 | |
| +| `internal/activator/rootfsrelease.go` (new) | `releaseDue`, `releaseTimeout`, `ReleaseError`, `leaseWatch`, `releaseOp` and `reapReleaseOpsLocked`, `classifyRelease`, `Service.runRelease` and its lease supervisor (R1); `releaseBeforeSwap`, `releasePassed` (R2) | R1, R2 | |
| +| `internal/activator/maintenance.go`, `opset.go` | the failed wake hands an unproven release's lease to its record; `releasable` waits on the record | R1, R3 | |
| +| `internal/activator/backend_unit.go`, `production_backend_test.go` (new) | `SplitBackend` forwarding of every new interface; the production composition and its test | 7, D, R1, W1 | |
| | `internal/release/layoutintent.go` | `RootfsLifecycleFloor` | 15 | |
| -| `internal/activator/rootfs_ctl_harness_test.go` (new) | `rootfsCtlHarness`: the real `instancectl.Server` handler and client behind an `ExecBackend` | 10, used by 12 | |
| -| `internal/activator/cmd.go`, `cmdunit.go`, `swaphold.go`, `generations_file.go` | release and run integration, the stop proof, the generations pins | 10, 11, 12 | |
| +| `internal/activator/rootfs_ctl_harness_test.go` (new) | `rootfsCtlHarness`: the real `instancectl.Server` handler and client behind an `ExecBackend` | 12, used by R1 | |
| +| `internal/activator/cmd.go`, `cmdunit.go`, `swaphold.go`, `generations_file.go` | run integration (12), release integration (R1 to R3), the stop proof, the generations pins | 12, R1, R2, R3 | |
| | `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/events.go`; `internal/rolloutwords/words.go`; `internal/status/snapshot.go` | reason words, events | R1, R2 | |
| | `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 | |
| @@ -196,7 +197,7 @@ The guards (each passes on main and fails on a violation; fixtures prove each re |
| |
| - **`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`). |
| +- **`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 and Task 12's; R1's release sentinels, through `classifyRelease`). |
| - **`TestRootfsLaunchFilesCarryOnlyComposedEnv` (INV-5), web row.** `t.Setenv("PATH", "/agent/bin")` and `t.Setenv("HOME", "/agent")`; production-wired (`nestedBackend`, `unitproc_test.go:225`, with `fakeControl`), a rootfs row with a `.env` holding `SHOP_MODE=live`: `StartGenExe` for generation 7; the launch file `GenLaunchFileName(7)` decodes to schema 2, no argv, `Env == rootfsLaunchEnv(<the vars startRootfs composed>)`, and neither `PATH` nor `HOME` is in it. A table keyed by process, so Tasks 6, 10 and 12 and W1 add `release`, `run` and `worker` rows. |
| - **`TestEveryRootfsProofNamesTheRootfsUnit` (INV-1 behaviour), main's rows.** Production-wired (`nestedBackend` with `fakeControl` and a cgroup fixture whose `cgroup.events` the test sets; no binary unit in any answer, every rootfs unit's group `populated 1`): a rootfs generation's `unitProc` (Stop asks `StopRootfs` for that generation, never `Stop`/`StopGen`, and stays unproven), and the rootfs `cmdUnit` (`Poll` asks `CmdStatusRootfs`; `StopAndSettle` asks `StopRootfs` with `RoleCmd` and fails while `RootfsUnitName(RoleCmd, host)`'s group is populated). A table keyed by handle, so N1, Tasks 10 and 12 and W1 add rows. |
| - **INV-6 goldens** (`binary_golden_test.go`, each byte-compared with a file under `testdata/binary_golden/`, written once from main at Task 1; a later change to a golden file needs its own reason in review): |
| @@ -424,7 +425,7 @@ The rule for every row: a change only widens a site by residents (INV-6). A site |
| |
| 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: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/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 (a swap, through N1's staged start). |
| - `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). |
| @@ -493,8 +494,7 @@ The worker half of the first draft (`rootfsWorkerVars` and the `prepare.go` work |
| - 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 |
| - // 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 |
| + // carlos run: rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath) (D1) |
| func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string |
| ``` |
| |
| @@ -515,7 +515,7 @@ 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; the .env's CARLOS_SOCKET and CARLOS_DB lose |
| + // CARLOS_DB, CARLOS_RUN_ID and CARLOS_RUN_DIR set; 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 |
| ``` |
| |
| @@ -620,9 +620,9 @@ git commit -m "activator: StartStaged starts rootfs generations; the rootfs heal |
| **Files:** |
| - Modify: `internal/activator/rootfs_service.go` (this task's half), create `internal/activator/rootfs_gate_test.go` |
| - Create: `internal/activator/rootfsdb.go`, `internal/activator/rootfsdb_test.go` (D7, Astra R1 finding 8) |
| -- Modify: `internal/activator/activator.go`: `wake` (`:1760`, the ceiling), `doWake` (`:2114`: the gate after step 0's refresh and before step 0.5 at `:2161`; after step 2 at `:2302` the served-never-empty check and the placeholder; after step 5 at `:2616` the placeholder's first sync, in step 5b's shape at `:2628`), `begin` (`:1484`, the gate before an entry is made), `serveWakeError` (`:5494`) |
| +- Modify: `internal/activator/activator.go`: `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` (beside `SplitBackend.SeedPlaced`, `:316`): `SplitBackend.PlaceRootfsDB` and `SplitBackend.rootfsStartable`, each forwarding to `b.Exec` for an exec-backed row whose `Exec` implements the interface and refusing otherwise (`errNoRootfsDB`; `refuseRootfs(errNoRootfsControl)`). Production builds the service over a `SplitBackend` (`internal/host/agent.go:524`), whose fields promote nothing, so an interface only `ExecBackend` implements is invisible in production [Astra R1 4] |
| -- Create: `internal/activator/production_backend_test.go`: `productionBackend(t, eb *ExecBackend) *SplitBackend`, the composition `agent.go:524` builds (`&SplitBackend{Exec: eb, Unit: &UnitBackend{OptDir: ...}}`), and `TestProductionBackendImplementsRootfsSeams`, which asserts the production composition satisfies every interface Plan 3 adds (this task: `rootfsStartable`, `rootfsDBPlacer`; Task 10: `ReleaseBackend`; W1: `RootfsWorkerBackend`) and that a unit-backed row is refused by each |
| +- Create: `internal/activator/production_backend_test.go`: `productionBackend(t, eb *ExecBackend) *SplitBackend`, the composition `agent.go:524` builds (`&SplitBackend{Exec: eb, Unit: &UnitBackend{OptDir: ...}}`), and `TestProductionBackendImplementsRootfsSeams`, which asserts the production composition satisfies every interface Plan 3 adds (this task: `rootfsStartable`, `rootfsDBPlacer`; Task D: `ProcessReader`; R1: `ReleaseBackend`; W1: `RootfsWorkerBackend`) and that a unit-backed row is refused by each |
| - Modify: `internal/activator/wakeplan.go:381` and `awaitWake` (`activator.go:1606`, its deadline at `:1621`): `firstWakeBudgetFor(rt)` |
| - Modify: `internal/host/rollout.go:406`: `svc.ArmRootfs()` once the manager has armed (not in `refuseManaged`, `:210`) |
| |
| @@ -643,7 +643,6 @@ git commit -m "activator: StartStaged starts rootfs generations; the rootfs heal |
| // (taking a.mu briefly), then the backend's rootfsStartable(rt), shared per host (a singleflight, so a request storm on a |
| // cold host asks the gates once). Every non-nil answer of either half is marked with refuseRootfs (errRootfsRefused). |
| var errRootfsUnarmed, errRuntimeUnknown, errRootfsReplicaMissing error |
| - func wakeCeilingFor(rt registry.Route) time.Duration // 5 min; rootfs: 5 min + runs.MaxTimeout |
| func firstWakeBudgetFor(rt registry.Route) time.Duration // firstWakeBudget; rootfs: healthBoundFor(rt) + firstWakeKillReserve |
| |
| // D7: the empty SQLite database of a rootfs first boot. ExecBackend has it; SplitBackend forwards it. |
| @@ -661,10 +660,9 @@ Rules: |
| - **Refuse before the lease (INV-3)** [pf 2.1]: `doWake` and `begin` refuse a rootfs row before `Acquire`, `Restore`, `LiveIdentity`, `recordBuild` or any entry state: `acquires == restores == materialized == 0`. Where each half runs [Astra R1 8]: `begin` asks `rootfsRefusalLocked` under its lock; on the path that would make a new entry (no live entry for the host) it drops `a.mu`, asks `rootfsStartRefusal`, retakes `a.mu` and re-checks from the top of its loop (an entry made meanwhile is coalesced on, as today), so an awake instance's requests never pay the gates and a cold one's pay them once per wake attempt; `doWake` asks `rootfsStartRefusal` off `a.mu` before step 0.5, for wakes that did not come through `begin` (due wakes, planned wakes, the tick); Task 8's tick asks it off `a.mu` for each candidate before it takes the lock to start one. Plan 2's `rootfsGates` still runs inside `Backend.Start`, after `Acquire`, `Restore` and `LiveIdentity` (which materializes the live link); asking it here first means a refused row pays none of that. The wake's member event is `RFS-3-C12` with the fragment `RFS-3-C14` for unarmed. An unknown runtime and a backend gate refusal log only (no member can cause the first; the second carries Plan 2's reason in the log). `serveWakeError` answers these 503 "instance failed to wake" (today's text). Task 8 asks the same gate in `rootfsTick`. |
| - `errRuntimeUnknown` is also returned for a binary-looking row whose `Runtime` is not valid, so no future value degrades to a binary launch. |
| - **Request budget** [pf 2.1]: the early gate's placement read is Plan 2's coalesced owner cache (at most 12 GET an hour per account with a record, 120 without). Residency adds no S3 read beyond a cache miss, and D7 adds one sync per first boot. A refused resident costs no lease cycle. |
| -- The wake ceiling: a rootfs wake may run its `release` (Task 11), which has its own timeout up to 6 h. The other steps keep their own bounds; the ceiling exists for wedged steps and must not cut a declared migration short. |
| - 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. |
| +- 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 `web` (Group R's release, when it lands, runs between the two): `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` (`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. |
| |
| @@ -683,8 +681,6 @@ func TestRootfsGatesThroughTheProductionBackend(t *testing.T) // productionBacke |
| 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, |
| - // and <= now+5m+1s for a binary row |
| func TestServedRootfsNeverBootsEmpty(t *testing.T) // restoreFresh true, row GoodVersion "v1": wake error is errRootfsReplicaMissing, |
| // fb.starts == 0, fb.releases == 1 |
| func TestFirstRootfsWakeMayBootFresh(t *testing.T) // restoreFresh true, GoodVersion "": fb.starts == 1, fb.seeds == 0 (no seed for rootfs), |
| @@ -709,7 +705,7 @@ func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) // Review Focus 8. A web |
| |
| INV-4's table gains `errRootfsUnarmed` and `errRuntimeUnknown`, each marked by `refuseRootfs`. |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsRefusalPrecedesTheLease|TestRootfsGatesRunOffTheLock|TestRootfsGatesThroughTheProductionBackend|TestProductionBackendImplementsRootfsSeams|TestRootfsWakeRefused|TestBinaryWakeNotGated|TestUnknownRuntimeNeverWakes|TestRootfsWakeCeiling|TestServedRootfsNeverBootsEmpty|TestFirstRootfsWakeMayBootFresh|TestServedRootfsPlacesNoPlaceholder|TestBinaryFreshWakePlacesNothing|TestRootfsPlaceholderFailureStartsNothing|TestPlaceRootfsDB|TestRootfsAppWithoutSQLiteRestarts' -count=1` (the production-wired ones need the short `TMPDIR` of the Global Constraints). Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsRefusalPrecedesTheLease|TestRootfsGatesRunOffTheLock|TestRootfsGatesThroughTheProductionBackend|TestProductionBackendImplementsRootfsSeams|TestRootfsWakeRefused|TestBinaryWakeNotGated|TestUnknownRuntimeNeverWakes|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** |
| @@ -759,11 +755,11 @@ git commit -m "activator: rootfs rows refused before the lease unless overlap sw |
| |
| 1. Off `a.mu`: `routes, err := lister.ResidentInstances()`. An error logs and ends the tick. It is never read as "no residents": nothing is stopped and nothing forgotten (incomplete discovery is not retirement). |
| 2. Under `a.mu`, return if `a.shuttingDown`. For every awake rootfs entry (resident or not) whose `e.proc.Exited()`: `e.unexpectedExit = true; a.beginStopLocked(e, StopExited)`, the sweep's own crash arm (`:4614`), so a crash is seen within 2 s rather than the sweep's 30. Then `a.superviseRootfsLocked(e)` for every awake rootfs entry: one hook, a no-op until W1 [pf 6.1]. |
| -3. Forget `a.residents[host]` for hosts no longer listed. For each listed route, in host order, skip when: `a.fences[host] != 0`; any live entry; `a.unprovenWakes[host]`, `a.straySidecars[host]` or `a.releaseRuns[host]` (the uncertainty latches; the last is Task 10's, and until then absent); `st.starting`; `a.now().Before(st.retryAt)`; `a.residentStarting >= residentStartCeiling` (stop the loop). A route that passes every skip is a candidate. Candidates are collected under `a.mu`, and the lock is dropped to ask `rootfsStartRefusal(ctx, rt)` for each (off `a.mu`, Astra R1 8); then, under `a.mu` again, every skip is re-checked before anything starts. A refusal sets `st.refused` and skips, counting no failure, with one log line per change of `st.refused` and, for unarmed, one `RFS-3-C12` event (fragment `RFS-3-C14`) per change [pf 2.1]. Otherwise make `e := &actEntry{host, route: rt, state: actWaking, ready: make(chan struct{}), resident: true}`, publish it, set `st.starting`, `a.residentStarting++`, and `go a.wake(e)`. |
| +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; Group R adds its release record); `st.starting`; `a.now().Before(st.retryAt)`; `a.residentStarting >= residentStartCeiling` (stop the loop). A route that passes every skip is a candidate. Candidates are collected under `a.mu`, and the lock is dropped to ask `rootfsStartRefusal(ctx, rt)` for each (off `a.mu`, Astra R1 8); then, under `a.mu` again, every skip is re-checked before anything starts. A refusal sets `st.refused` and skips, counting no failure, with one log line per change of `st.refused` and, for unarmed, one `RFS-3-C12` event (fragment `RFS-3-C14`) per change [pf 2.1]. Otherwise make `e := &actEntry{host, route: rt, state: actWaking, ready: make(chan struct{}), resident: true}`, publish it, set `st.starting`, `a.residentStarting++`, and `go a.wake(e)`. |
| |
| Outcome and stop accounting, both under `a.mu`: |
| - `noteResidentWakeLocked` (in `wake`'s final critical section, for any wake of a resident row, proactive or by request): a proactive wake clears `starting` and decrements `residentStarting`. A failed wake counts a failure only when `residentFailure(err)`: `failures++`, `retryAt = now + residentBackoff(failures, jitter())`. Otherwise `retryAt = now` and nothing is counted [Astra R1 11]. |
| -- `residentFailure(err error) bool` is false for every ownership end and refusal, the INV-4 set: `ErrFenced`, `errShuttingDown`, `context.Canceled`, anything `verdictOf` answers gateNoOwnership or superseded for (so `errRootfsRefused`, `errSwapLeaseLost` and with it the release's lease loss), `errSwapBusy`, `errReleaseUnproven` and `errWakeUnproven` (both latch the host until their record is proven, Task 10, so a backoff would only add to it). It is true for the build's own failures (`*ReleaseError`, a health failure, a crash at start) and for anything unclassified, such as an `Acquire` that fails on a store outage, which must back off rather than retry every 2 s. Tasks 10 and 11 define the sentinels it names; until then it names those that exist. |
| +- `residentFailure(err error) bool` is false for every ownership end and refusal, the INV-4 set: `ErrFenced`, `errShuttingDown`, `context.Canceled`, anything `verdictOf` answers gateNoOwnership or superseded for (so `errRootfsRefused` and `errSwapLeaseLost`), `errSwapBusy` and `errWakeUnproven` (it latches the host until its record is proven, so a backoff would only add to it). It is true for the build's own failures (a health failure, a crash at start) and for anything unclassified, such as an `Acquire` that fails on a store outage, which must back off rather than retry every 2 s. Group R extends it through `classifyRelease`: only a failed release counts. |
| - `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. |
| @@ -793,8 +789,7 @@ func TestResidentReplicationIsTheActivators(t *testing.T) // the awake resident' |
| func TestResidentRefusalCountsNoFailure(t *testing.T) // rootfsStartable refusing for 20 ticks: failures == 0, acquires == 0, |
| // one log line; after it clears, the next tick starts the resident with no backoff |
| func TestResidentFailureClassification(t *testing.T) // [Astra R1 11] table over residentFailure: each INV-4 case false (a refusal, |
| - // errSwapLeaseLost wrapping errReleaseLeaseLost, errSwapBusy, errReleaseUnproven, errWakeUnproven, ErrFenced, shutdown); |
| - // *ReleaseError, a health failure and an Acquire store error true; and through the tick: a wake failing with each false case |
| + // errSwapLeaseLost, errSwapBusy, errWakeUnproven, ErrFenced, shutdown); a health failure and an Acquire store error true; and through the tick: a wake failing with each false case |
| // leaves failures == 0 |
| func TestResidentRequestAndTickRaceOneWake(t *testing.T) // RACE: 50 goroutines ServeHTTP a cold resident while the tick runs every |
| // 1 ms; fb.acquires == 1 and fb.starts == 1. Run with -race. |
| @@ -815,311 +810,60 @@ git commit -m "activator: always-on rootfs instances: boot start, crash restart |
| |
| --- |
| |
| -### Task 10: The release runner |
| +### Task D: Declared processes this box does not run yet |
| |
| -**Review:** cross-model (pre-flight §7): release lease supervision and the cmd unit proof. |
| +**Review:** not cross-model (pre-flight §7 lists no such task; it reads a root-written manifest and only logs). |
| + |
| +Group A runs `web` and `carlos run`. A rootfs build may also declare workers (Group W) and a `release` process (Group R). This task gives both later groups the one manifest read they share, and makes a box without them say so (D8) [Paul, 2026-10-26]. |
| |
| **Files:** |
| -- Create: `internal/activator/rootfsrelease.go`, `internal/activator/rootfsrelease_test.go`, `internal/activator/rootfs_ctl_harness_test.go`, `internal/activator/backend_rootfs.go` (this task's half: `Processes`, `stagedImageOf`, `StartRelease`, `ReleaseEnv`) |
| -- Modify: `internal/activator/cmdunit.go` (`StartCmd`'s body, `:172`, becomes `startCmdUnit`, shared; it builds Plan 2's runtime-aware `cmdUnit` for both runtimes, A8) |
| -- Modify: the consumers of the one release record (INV-7, the table below): `internal/activator/cmd.go` (`RunCmd`'s admission beside `cmdBusyLocked`, `:284`), `internal/activator/activator.go` (the idle arm, `:4709`; the max-run arm, `:4743`; `beginStopLocked`, `:2687`; doWake's wake latch, `:2183`; the sweep calls `reapReleaseRunsLocked`), `internal/activator/opset.go` (`releasable`, `:681`), `internal/activator/maintenance.go` (`cleanupFailedWake`, `:360`), `internal/activator/generations_file.go` (the snapshot lists every record's build), `internal/activator/rootfs_service.go` (the tick skips a host with a record) |
| -- Modify: `internal/activator/backend_unit.go`: `SplitBackend.Processes`, `ReleaseEnv`, `StartRelease`, forwarding to `b.Exec` for an exec-backed row and refusing a unit-backed one (`refuseRootfs(errNoRootfsControl)`) [Astra R1 4]; `production_backend_test.go` gains the `ReleaseBackend` row |
| -- Modify: `internal/activator/backend_exec.go:787` (`execLease.SafeUntil`, `execLease.Lost`, beside `Err`) |
| -- Modify: `internal/rolloutwords/words.go` (events), `internal/status/snapshot.go:410` (reason words, beside `ReasonHealth`) |
| -- Modify: `internal/activator/rootfs_invariants_test.go` (INV-1, INV-4 and INV-5 rows) |
| +- Create: `internal/activator/backend_rootfs.go` (`Processes`), `internal/activator/rootfs_processes_test.go` |
| +- Modify: `internal/activator/backend_unit.go` (`SplitBackend.Processes`, forwarding to `b.Exec` for an exec-backed row and refusing a unit-backed one, `refuseRootfs(errNoRootfsControl)`); `internal/activator/production_backend_test.go` (the `ProcessReader` row) |
| +- Modify: `internal/activator/activator.go`: `doWake` after step 6 (`:2638`), the declared-processes hook; `internal/activator/swap.go`: step 8 (`:690`, beside `replaceSidecar`), the same hook |
| |
| **Interfaces:** |
| -- 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`). |
| +- Consumes: `release.ReadStagedManifest` (`internal/release/versions.go:264`), `Manifest.IsRootfs`/`BoxArtifact` (`release.go:153`, `:169`), N1's `stagedIdentityOf`. |
| - Produces: |
| ```go |
| - type ReleaseBackend interface { |
| + type ProcessReader interface { |
| // Processes reads the root-written staged manifest of id for rt's account and app [pf 1.9], with root's own check |
| // (instancectl/rootfs.go:226-231): ReadStagedManifest(optDir, RouteAccount(rt), id.Version, rt.App); its documented |
| // (nil, nil) for an absent sibling (versions.go:236-240, :267-269) is a refusal, never "no processes"; !m.IsRootfs() |
| // refuses; art, ok := m.BoxArtifact(platform) with !ok refuses; !strings.EqualFold(art.SHA256, id.Digest) refuses. |
| - // An id with no Digest refuses before any read [Astra R1 3]. |
| + // An id with no Digest refuses before any read [Astra R1 3]. Every refusal is marked refuseRootfs. |
| Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error) |
| - ReleaseEnv(rt registry.Route) (map[string]string, error) // the delivered files a successor would launch with, composed by rootfsCmdVars |
| - // StartRelease runs runPendingRecord(ctx) and runExecGate(ctx) immediately before CmdRootfs; a refusal there is |
| - // 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 { |
| - Err() error |
| - SafeUntil() (time.Time, error) |
| - Lost() <-chan struct{} |
| - } |
| - func (l *execLease) SafeUntil() (time.Time, error) // l.held.SafeUntil() |
| - func (l *execLease) Lost() <-chan struct{} // l.held.Lost() |
| - func releaseDue(rt registry.Route, id release.StagedIdentity, procs map[string]release.Process) bool |
| - // rt.Rootfs() && procs has release.ProcessRelease && !(id.Version == rt.GoodVersion && id.Digest == rt.GoodDigest) |
| - func releaseTimeout(p release.Process) time.Duration // 600 s when TimeoutSec <= 0; capped at runs.MaxTimeout |
| - // releaseStopLead is how far ahead of the lease's safety deadline a release is stopped. One StopAndSettle is at most |
| - // DeadlineControl (30 s) + actStopTimeout (20 s) + two drains (2 x 5 s) = 60 s, so cmdStopBound (2 min) leaves room for a |
| - // second attempt. A healthy lease never comes this close: LeaseTTL is 15 min, renewed every 5. Vars so tests shrink them. |
| - var releaseStopLead = cmdStopBound |
| - var releaseLeaseRecheck = 5 * time.Second // how often the supervisor re-reads SafeUntil |
| - type ReleaseError struct { |
| - Build, Signal string |
| - Exit int |
| - TimedOut bool |
| - Took time.Duration |
| - } |
| - func (e *ReleaseError) Error() string // RFS-3-C05, C06 or C07 formatted: the member-facing reason a failed wake carries |
| - var errReleaseUnproven = errors.New("activator: a release command's unit is not proven stopped") |
| - var errReleaseNoLease = errors.New("activator: the lease a release would run under cannot report its safety deadline") |
| - var errReleaseLeaseLost = errors.New("activator: the instance's lease ended while its release command ran") |
| - // returned as fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost): an ownership end (gateNoOwnership), never the build's failure |
| - // releaseRun is the one owner of a running release (INV-7), from admission until its unit is proven gone, whatever |
| - // happens to the entry, wake or swap that started it [Astra R1 5, 6]. Service.releaseRuns map[string]*releaseRun, by host. |
| - type releaseRun struct { |
| - build release.StagedIdentity // full identity (stagedIdentityOf); pinned in the generations file while the record lives |
| - hold *cmdHold // the cmd unit's stop and settle; one attempt at a time (busy) |
| - cancel context.CancelCauseFunc |
| - owner *actEntry // the entry whose wake or swap started it; nil once that entry is gone |
| - owed Lease // a failed wake's lease, kept here while the unit is unproven; given back after the proof |
| - retryAt time.Time |
| - busy bool // runRelease is settling it, or the reaper is |
| } |
| - var errReleaseRunOpen = errors.New("activator: a release command of this instance is still running or not proven stopped") |
| - func (a *Service) reapReleaseRunsLocked() // the sweep's one retry path: each record with no owner, or an owner whose stop |
| - // waits on it, not busy and past retryAt, gets one settle off a.mu (actStopTimeout); proven: the record goes, its owed |
| - // lease is given back (or a.oweRelease), the generations file is rewritten |
| - func (a *Service) runRelease(ctx context.Context, e *actEntry, rt registry.Route, id release.StagedIdentity, held leaseWatch, gate func() error) error |
| - // nil when not due; *ReleaseError; errReleaseUnproven; errReleaseNoLease; the gate's own refusal; a Processes refusal; |
| - // root's pre-start refusal; the lease-loss error above; ctx's own error when ctx ended; errSwapBusy when a run holds the cmd unit |
| - const ( status.ReasonRelease = "release"; status.ReasonReleaseTimeout = "release-timeout" ) |
| + func (a *Service) rootfsProcessesHook(ctx context.Context, e *actEntry, rt registry.Route, g Gen) |
| + // group A: reads Processes(rt, stagedIdentityOf(g)) off a.mu and logs once per wake or swap, as diagnostics: |
| + // "activator: %s: build %s declares workers (%s); this box does not run workers yet" and |
| + // "activator: %s: build %s declares a release process; this box does not run it yet, so the app's web command must |
| + // prepare its own database" ; a refused read logs once. It starts nothing and never fails a wake or a swap. |
| + // W1 makes the doWake call start workers and W2 the step 8 call hand them over; R1 drops the release line. |
| ``` |
| |
| -`gate` is the calling site's ownership gate, the one its own exec already passes (Task 11's table names each): it takes `a.mu` itself and answers whether this entry is still the host's, with no fence, no shutdown, the attempt or plan still current, and the site's lease held. `runRelease` adds the lease's deadline to it: |
| - |
| -```go |
| -own := func() error { |
| - if err := gate(); err != nil { |
| - return err |
| - } |
| - if err := held.Err(); err != nil { |
| - return fmt.Errorf("%w: %v", errSwapLeaseLost, err) // leaseLost's shape over the watch |
| - } |
| - until, err := held.SafeUntil() |
| - if err != nil || time.Until(until) <= releaseStopLead { |
| - return fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost) |
| - } |
| - return nil |
| -} |
| -``` |
| - |
| -`runRelease`, in order: |
| -1. `procs, err := Processes(rt, id)`. Any error is a refusal to start, marked with `refuseRootfs`, never "no release process, not due": nothing starts, `web` included [pf 1.9]. Not due: return nil. `held == nil`: `errReleaseNoLease`, nothing started (a caller whose `Lease` or `Rep` is not a `leaseWatch` passes nil). |
| -2. `own()`; a refusal returns it and starts nothing. Under `a.mu`: refuse with `errSwapBusy` when `cmdBusyLocked(e)` (a member's run holds the host's one cmd unit), and with `errReleaseRunOpen` when `a.releaseRuns[rt.Host]` exists in any state (so no release ever overwrites another's record); else create the record (`build: id`, `hold: newCmdHold("release", cancel, a.now)` with `starting` set, `owner: e`, `busy: true`). Then, off `a.mu`, `a.publishBeforeExec()`: the record's build is now in the generations file before anything runs, and a failed write removes the record and returns `errStagedBuildNotPublished` (abandonment, never the build's failure) [Astra R1 9]. |
| -3. `recordBuild(ctx, rt.Host, id.Version)`: the build state names the release's build before it touches the data (settings §4.2). `StartRelease` then runs `runPendingRecord(ctx)` and `runExecGate(ctx)` immediately before `CmdRootfs`, as the exec seam does, so a cold wake's pending record is written before `release` runs, not at `web`'s exec, and ownership is checked at the last moment before root is asked. (No egress step: #328 checks on root's side, in `startRootfsCmd` [pf 2.5].) |
| -4. Event `RFS-3-C03`. `rctx, trip := context.WithCancelCause(ctx)` with `releaseTimeout(procs[release.ProcessRelease])` over it. |
| -5. `StartRelease(withExecGate(rctx, own), rt, id, ReleaseEnv(rt), out)`: `startCmdUnit` with Plan 2's `writeRootfsLaunchFor(p, RoleCmd, 0, rt.Host, release.ProcessRelease, rootfsLaunchEnv(env))` (A3: schema 2, no argv, nothing of the agent's environment [pf 1.6]) and `RootfsControl.CmdRootfs(ctx, host, b.tier(rt).MemoryMax, stagedImageOf(id, release.ProcessRelease, nil))` (A5, the sized tier [pf 1.8]). An `ErrStagedImage` or `ErrStartRefused` answer is marked with `refuseRootfs`: root refused before anything ran, so it is a refusal, never the build's failure (INV-4) [pf 1.7]. The unit it returns, with or without an error, is Plan 2's runtime-aware `cmdUnit` (A8): it polls `RootfsUnitName(RoleCmd, host)` and stops and proves that unit, never the binary `carlos-instance-cmd@`. `out` is a line writer into the app log sink (`b.logEmitter(rt)`, `prepare.go:259`), both streams, at most `runs.MaxOutputBytes`, after which lines are dropped and one diagnostic logged. A `launchRefused` start returns the gate's error with the record removed: nothing ran. |
| -6. **Lease supervision**, from the moment the unit may run until it is proven gone: a goroutine re-reads `held.SafeUntil()` every `releaseLeaseRecheck` and wakes at once on `held.Lost()`. It trips (`trip(errReleaseLeaseLost)`) when `Lost()` closes, when `SafeUntil` errors, or when `time.Until(until) <= releaseStopLead`, keeping the last `until` it read as the deadline. It uses the real clock, as the lease does (`SafeUntil` is monotonic), not `a.now`. |
| -7. Poll (`unit.Poll`, the 30 s long-poll) until done or `rctx` ends. Then stop and settle whatever happened, through the record's `hold.stop`, with the reason `StopLeaseLost` after a trip. After a trip the settle is retried until it is proven or the deadline from step 6 passes; otherwise it is bounded by `cmdStopBound`. A failed settle is `errReleaseUnproven` (wrapped with `errSwapLeaseLost` after a trip); the record stays, `busy` is cleared and `retryAt` set, and from then on the sweep's `reapReleaseRunsLocked` is its only retrier (INV-2, INV-7). |
| -8. Results, in this order: a trip is the lease-loss error, whatever the unit's exit (a release that exited 0 on a box that no longer holds the lease is not success), with event `RFS-3-C29` once the unit is proven gone, and never a `ReleaseError`; `ctx` itself ended (a fence, a stop, shutdown): `ctx.Err()`, no event, never a build failure; exit 0: event `RFS-3-C04`, nil; non-zero, a signal, or the timeout: `*ReleaseError` and its event. |
| -9. Once proven: remove the record under `a.mu`, rewrite the generations file off it, stop the supervisor. |
| - |
| -The callers (Task 11) treat the lease-loss error as they treat `errSwapLeaseLost` today: an overlap abandons (`classifyStep`, `swap.go:134`, through `verdictOf`, `:234`); a wake fails and gives the lease back only when the record is gone (the unit proven), and otherwise hands its lease to the record (`owed`) before its entry is deleted (Task 11). |
| +Until Group R lands, an app migrates in its own web command, as Rails 8's Docker entrypoint does (`bin/rails db:prepare` before the server starts). Plan 4's sample app does exactly that (Hand-offs), so nothing in spec §6 step 1 waits for Group R. |
| |
| -**Who reads the record (INV-7).** Every consumer of "is a release running or unproven for this host" reads `a.releaseRuns[host]`, never an entry field, so an entry's deletion cannot drop the obligation [Astra R1 5, 6]: |
| - |
| -| consumer | main's code | with a record for the host | |
| -|---|---|---| |
| -| a member's run | `RunCmd`'s admission, beside `cmdBusyLocked` (`cmd.go:284`) | refused as busy (the run's existing busy answer); no run beside a release | |
| -| another release | `runRelease` step 2 | `errReleaseRunOpen` | |
| -| idle sleep | the sweep's idle arm, `e.cmd == nil` (`activator.go:4709`) | the owner entry is never idle-stopped, so a hibernating incumbent keeps serving through an overlap migration (C8) | |
| -| max-run recycle | `e.workerMaxRun` arm (`activator.go:4743`) | applies only to sidecar entries (`e.worker`), never a rootfs owner; unchanged, and `TestReleaseRunConsumersReadTheRecord` pins that it never fires for one | |
| -| a stop of the owner | `beginStopLocked` (`:2687`) | cancels the record (`cancel(cause)`), so `runRelease` settles it at once; `releasable(e)` (`opset.go:681`) is false until the record is gone, so replication and the lease are held | |
| -| a wake of the host | doWake's latch (`activator.go:2183`), the tick's skip | refused with `errWakeUnproven` while the record exists and its owner is not this wake | |
| -| the failed wake's cleanup | `cleanupFailedWake` (`maintenance.go:360`), then the entry's deletion (`activator.go:1860`) | the wake's lease moves to `owed` (never released, never left to TTL alone), `owner = nil`; the record outlives the entry | |
| -| pins | `entryGenerationsLocked` and the snapshot | every record's `build` is listed, whatever its owner; published before the release execs (step 2) | |
| -| retries | `retryCmdSettlesLocked` (`cmd.go:399`) is a run's | untouched; a release's one retry path is `reapReleaseRunsLocked` | |
| - |
| -`settleCmds` and `cmdHoldsLocked` (a member's runs) are unchanged: a release is not a run and does not sit in `e.cmd` or `e.cmdLeft`. |
| - |
| -- [ ] **Step 1: Write the failing tests.** The backend half goes through the real control handler, not a scripted fake (Astra R1 finding 1): `rootfsCtlHarness` in `rootfs_ctl_harness_test.go` serves a real `instancectl.Server` (`Handler()`, `internal/instancectl/server.go:380`) on a unix socket under the short `TMPDIR`, with `PeerOK` returning nil; `Systemctl` a fake keyed by unit name (each unit's `show` answer, and `start`/`stop` recorded in order and changing that unit's state); `CgroupRoot` a fixture tree whose `cgroup.events` per unit the test sets; `OptDir` with build B staged at `release.VersionPath` and its root-written staged manifest (Plan 2's rootfs server fixture shape); `HostApp` answering the row's account and app; `ExeRoot` and `DropInDir` under `t.TempDir()`; a switch that makes the handler answer `/cmd` with a chosen pre-start status. The `ExecBackend` is `nestedBackend` with `Control: instancectl.NewClient(sock)` and `CgroupEvents` reading the same fixture tree. The binary `carlos-instance-cmd@<host>.service` exists in no answer: `show` reports it with no invocation and inactive, and its cgroup is absent, so a test passes only if every poll, stop and proof names the rootfs unit. The Service half uses `fakeBackend` implementing `ReleaseBackend`, with `fakeLease` and `fakeRep` implementing `leaseWatch` (a `lost` channel the test closes, an `until` the test sets or advances). |
| +- [ ] **Step 1: Write the failing tests:** |
| |
| ```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; |
| - // 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 record removed, nothing started |
| -func TestReleaseExitNonZero(t *testing.T) // the rootfs unit exits with status 3: *ReleaseError{Exit: 3}; event C05; |
| - // one stop of the rootfs unit |
| -func TestReleaseTimesOut(t *testing.T) // the rootfs unit stays running past a shrunk timeout: TimedOut, stop sent to |
| - // the rootfs unit and its cgroup proven empty, event C07 |
| -func TestReleaseUnprovenKeepsTheRecord(t *testing.T) // the rootfs unit's cgroup stays populated: errReleaseUnproven; a.releaseRuns[host] |
| - // still set, its build in the persisted generations file; the next sweep's reaper proves it once the group empties, then |
| - // the record and the pin go |
| -func TestReleaseExecGateRefusesAtTheLastMoment(t *testing.T) // the gate flips to refusing after step 2: launchRefused, no /cmd request |
| - // in the log, the record removed, the gate's error returned |
| -func TestReleaseOutputReachesTheAppLog(t *testing.T) // lines the unit writes to both streams reach the fake EventSink's App lines; |
| - // past the cap they stop |
| -// Service half, fakeBackend |
| func TestProcessesRefusesAPartialOrAbsentManifest(t *testing.T) // [Astra R1 3] no sibling (ReadStagedManifest nil, nil), no box artifact, |
| - // an id with no Digest: each refused, nothing started |
| -func TestReleaseRunConsumersReadTheRecord(t *testing.T) // INV-7. with a record for the host: RunCmd refused; a second runRelease |
| - // errReleaseRunOpen; sweepOnce past the idle window does not stop the owner (a hibernating incumbent); a Bounce stop stays |
| - // pending (releasable false) with rep open; a ServeHTTP to the cold host and a resident tick both refused errWakeUnproven |
| - // once the owner is gone; the persisted generations file lists the build. Remove the record (proven): each consumer |
| - // proceeds |
| -func TestReleaseBuildPublishedBeforeExec(t *testing.T) // [Astra R1 9] the generations file on disk names the release's build before |
| - // the /cmd request; a failed write: errStagedBuildNotPublished, no /cmd request, no record left |
| -func TestReleaseThroughTheProductionBackend(t *testing.T) // [Astra R1 4] productionBackend over the rootfsCtlHarness ExecBackend: the |
| - // service's type assertion finds ReleaseBackend and the release runs in the rootfs cmd unit; a unit-backed row is refused |
| -func TestReleaseRefusedWhenTheManifestIsNotTheImage(t *testing.T) // [pf 1.9] Processes errors: errRootfsRefused, StartRelease never |
| - // called; through doWake, web is not started either |
| -func TestReleaseRefusedWhileARunHoldsTheUnit(t *testing.T) // e.cmd set: errSwapBusy, StartRelease never called |
| -func TestReleaseGatedOnOwnership(t *testing.T) // table, StartRelease never called in each: the site gate refuses (entry |
| - // superseded, fence raised, shutdown); held.Err set; SafeUntil less than releaseStopLead ahead: errors.Is(err, errSwapLeaseLost); no event |
| -func TestReleaseNeedsAWatchableLease(t *testing.T) // held nil: errReleaseNoLease, nothing started |
| -func TestReleaseStopsOnLostLease(t *testing.T) // close fakeLease.lost while the release polls: the record's stop runs with |
| - // StopLeaseLost and is proven before until; errors.Is(err, errSwapLeaseLost) and errors.Is(err, errReleaseLeaseLost); no |
| - // ReleaseError; event C29 after the proof |
| -func TestReleaseStopsBeforeTheSafetyDeadline(t *testing.T) // renewals stall: lost never closes, until frozen at now+lead+300ms, with |
| - // releaseStopLead 200 ms and releaseLeaseRecheck 10 ms: the stop starts by until-lead+recheck and is proven before until |
| -func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) // until advanced by 1 s every 20 ms (lead 200 ms): the release runs to |
| - // exit 0 unstopped, event C04, nil |
| -func TestReleaseLeaseLossUnprovenLeavesTheHold(t *testing.T) // lost closes, every settle fails until past until: errReleaseUnproven and |
| - // errSwapLeaseLost both match; the record stays (owned by the reaper); no C29 |
| -func TestReleaseLeaseLossRacesExit(t *testing.T) // RACE: lost closes as the unit reports done with status 0: one settle, |
| - // the result is the lease-loss error, never nil. Run with -race. |
| -func TestStopSettlesARunningRelease(t *testing.T) // RACE: Bounce while the release polls: the release unit is stopped and settled |
| - // before rep.Close (ordered log); RunCmd during the release starts no unit. Run with -race. |
| -``` |
| - |
| -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|TestProcessesRefuses|TestRelease|TestStopSettlesARunningRelease|TestProductionBackend|TestEveryRootfsProof|TestRootfsRefusalsAreNot|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| -- [ ] **Step 3:** Implement; write `RFS-3-C03` to `C07` and `RFS-3-C29`, add their ids to the built list. |
| -- [ ] **Step 4:** Run Step 2's command, `go test -race ./internal/activator/ -run 'TestStopSettlesARunningRelease|TestReleaseLeaseLossRacesExit|TestReleaseStopsOnLostLease' -count=3`, the cmd families (`-run 'Cmd|RunCmd'`), which the `startCmdUnit` refactor touches, and Task 1's guards and goldens (`TestBinaryStartCmdLaunchGolden` must stay byte-identical). Expected: PASS. |
| -- [ ] **Step 5: Commit** |
| - |
| -```bash |
| -git add internal/activator internal/rolloutwords internal/status approved_rootfs_copy_test.go |
| -git commit -m "activator: the rootfs release command runs in the rootfs cmd unit from the new image, supervised by the instance's lease" |
| -``` |
| - |
| ---- |
| - |
| -### 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` (`: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 (`: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`, `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 |
| - // 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, stagedIdentityOf(g)) declares workers, log once per wake or swap |
| - // "activator: %s: build %s declares workers (%s); this box does not run workers yet" (a diagnostic, D8). W1 and W2 fill it. |
| - ``` |
| - |
| -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: `id, err := stagedIdentityOf(m.gen)` (N1; a refusal abandons) then `a.runRelease(mctx, e, rt, id, watchOf(e.rep), gate)`. Never `genIdentity`, which answers two values and no digest (`generations_file.go:220`) [Astra R1 3] | the incumbent's replica `e.rep` (a `*lease.Replicator`); the attempt gate the successor's spawn passes | `dropMember`; a cancelled or stale error, a refusal (`errRootfsRefused`), and the lease-loss error, abandon through `classifyStep` (`errSwapLeaseLost` is already in `verdictOf`, `swap.go:234`); otherwise `failSwap` (`swap.go:114`) with the reason above and `Executed` true. The incumbent was never touched (C8). `errSwapBusy` abandons, and the scheduler retries after its deferral | |
| -| hold swap | `startPinnedChecked`, after its gate, before `startPinnedAt`, on `stagedIdentityOf(pin)` | the wake's `lease`; its `gate` | the old build is already stopped; `markPinExec(e)` (`swaphold.go:378`) when the release ran, so the hold reports down, as a hold build that ran and failed does today. The lease-loss error and a refusal are the gate's NoOwnership refusal, as `leaseLost(lease)` there already is | |
| -| planned wake (asleep row, or a resident's restart, scheduler choosing B) | `spawnPlanned`, after `checkPlan` and before `healthBy` is computed, on `plan.Boot`, already a full `StagedIdentity` with its digest (`wakeplan.go:25`); `healthBy` is then measured from the release's end, and the verdict floor uses `healthBoundFor(rt)` (N1) | the wake's `lease`; `planGate(ctx, e, lease, plan, plan.Boot.Version)` | treated as B failing at its start: `executed` and `crashed` include `*ReleaseError`, so a first wake with a fallback boots the good build and records B's failure (`w.failed`, `w.fellBack`). The lease-loss error and a refusal are not B's failure: they are gateNoOwnership like every `planGate` refusal, nothing more is started, and no fallback runs | |
| -| other wakes with a pinned identity | `doWake`, right before the `ib != nil` branch, on `id` | the wake's `lease`; `leaseLost(lease)` then `a.wakeOwned(ctx, e)` | the wake fails with the error | |
| - |
| -`watchOf(x any) leaseWatch` is `x.(leaseWatch)` or nil (and `runRelease` then refuses with `errReleaseNoLease`); the cold-wake sites pass `watchOf(lease)`. On a cold wake the entry is `actWaking`, which the sweep's lease check never visits (it runs for awake entries, `activator.go:4606`), so Task 10's supervisor is the only thing watching the lease while the migration runs; in a swap the sweep also sees a lost `e.rep` and begins a `StopLeaseLost` stop, which cancels the record (`beginStopLocked`) and waits for it (`releasable`); the settle stays `runRelease`'s, then the reaper's, never a second attempt beside it (INV-7). |
| - |
| -In `doWake`'s start-error switch, `errReleaseUnproven` (with or without the lease-loss error) means the unit may still write the database. Leaving the lease to its TTL is not enough [Astra R1 5]: `wake()` deletes the failed entry (`activator.go:1860`), `unprovenWake` (`opset.go:741`) carries generation and legacy-run evidence but no command hold, and nothing would block the next wake or retry the proof. So the obligation is already the record's (Task 10): `cleanupFailedWake` (`maintenance.go:360`) finds `a.releaseRuns[host]` owned by this wake, moves the wake's lease into its `owed` field instead of giving it back or closing it, and clears `owner`; the entry then goes as today, and the record keeps the pin, the wake latch and the lease until the reaper proves the unit and gives the lease back. The lease-loss error with the unit proven gone gives the lease back (`giveBack`, which a lost lease answers harmlessly) and starts nothing after it: no `web`, no fallback. Restart and config attempts re-run the serving build, which is the good build, so `releaseDue` is false (D3). A rootfs row is never seeded (D5), so on a first boot `release` runs after the restore and the placeholder (Task 7) and before `web`. A release stopped by lease loss leaves `GoodVersion` unchanged, so the next attempt, on whichever box then holds the lease, runs it again. |
| - |
| -`reasonWord` answers `status.ReasonReleaseTimeout` for a reason starting `release timed out` and `status.ReasonRelease` for one starting `release`, before its other arms (`exited` would otherwise match `ReasonExit`). `rolloutwords.Reason` renders them as `RFS-3-C01` and `C02`, so the existing `swap.failed` event and the REASON column say why without new code. |
| - |
| -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 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 |
| -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 |
| -func TestFirstWakeReleaseFailureFallsBack(t *testing.T) // planned first wake, fallback A: release(B) fails; A boots, w.fellBack, |
| - // B's failure is handed to OnGen |
| -func TestRestartDoesNotRerunRelease(t *testing.T) // CauseRestart onto the good build: no release |
| -func TestReleaseRerunsAfterInterruptedWake(t *testing.T) // the wake is cancelled while release polls (Shutdown): the unit settled, |
| - // 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 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 |
| - // released: it is the record's owed lease; the entry is deleted and the record is not |
| -func TestSwapReleaseStopsOnLeaseLoss(t *testing.T) // Review Focus 6. Incumbent gen 1 on A, attempt B; fakeRep.lost closed while |
| - // release(B) polls: release unit proven before until; SwapAbandoned (not SwapFailed), StartStaged never called, no C05..C07 |
| - // event, C29 once; the next sweep stops the incumbent with StopLeaseLost (today's arm) and its releasable waits on the record, which runRelease has proven |
| -func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) // RACE: fakeRep.lost closed and sweepOnce run at once: one settle attempt |
| - // at a time on the record (busy), the incumbent stopped once, rep.Close after the record is gone. Run with -race. |
| -func TestReleaseRefusedWhenOwnershipEndsBeforeItStarts(t *testing.T) // each site: a fence raised (overlap: the attempt superseded) |
| - // between admission and runRelease: no StartRelease, the site's NoOwnership outcome |
| -func TestReleaseObligationOutlivesTheWake(t *testing.T) // INV-2, INV-7 [Astra R1 5]. cold wake, release(B) unproven (its cgroup stays |
| - // populated): the complete wake() fails and its entry is deleted; a.releaseRuns[host] keeps B's pin (the persisted |
| - // generations file names it), the lease is the record's owed lease and is not released; a second ServeHTTP and a resident |
| - // tick are both refused errWakeUnproven with acquires unchanged; RunCmd is refused |
| -func TestReleaseObligationRetriedUntilProven(t *testing.T) // the same, then the group empties: the next sweep's reaper proves the rootfs |
| - // cmd unit (never the binary one), gives the owed lease back, drops the pin from the file on disk, and the next request wakes |
| -func TestIncumbentNeverIdlesThroughAMigration(t *testing.T) // [Astra R1 6] hibernating rootfs incumbent, overlap release(B) running past |
| - // cfg.Idle of fake time: sweepOnce does not stop the incumbent (C8); after the release ends it may idle as before |
| -func TestRunAfterAnUnprovenReleaseIsRefused(t *testing.T) // [Astra R1 6] overlap release unproven, swap abandoned, entry still awake: |
| - // RunCmd refused and a new attempt's release refused errReleaseRunOpen until the reaper proves the record |
| -func TestDeclaredWorkersAreLoggedNotStarted(t *testing.T) // D8. a build declaring jobs: one log line per wake and per swap, no |
| - // worker start asked of root, the wake and the swap succeed |
| -// internal/rollout/rootfs_reason_test.go |
| -func TestReasonWordRelease(t *testing.T) // "release: the release command of build v2 exited with status 1" -> |
| - // ReasonRelease; "release timed out: ..." -> ReasonReleaseTimeout; existing words unchanged |
| + // an id with no Digest: each refused |
| +func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) // D8. a build declaring jobs and release: one log line each per wake and per |
| + // swap; nothing asked of root beyond web; the wake and the swap succeed; a refused read logs once and the wake still serves |
| +func TestProcessesThroughTheProductionBackend(t *testing.T) // [Astra R1 4] productionBackend: the type assertion finds ProcessReader; |
| + // a unit-backed row is refused |
| ``` |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestOverlapRelease|TestOverlapRunsRelease|TestOverlapAbandonsWhileARun|TestSwapReleaseRefusedByRoot|TestHoldReleaseFailure|TestAsleepRowRunsRelease|TestFirstWakeReleaseFailure|TestRestartDoesNotRerunRelease|TestReleaseRerunsAfterInterruptedWake|TestColdWakeRelease|TestSwapRelease|TestReleaseRefusedWhenOwnershipEnds|TestReleaseObligation|TestIncumbentNeverIdlesThroughAMigration|TestRunAfterAnUnprovenRelease|TestDeclaredWorkersAreLogged' -count=1` (under the short `TMPDIR`) and `go test ./internal/rollout/ -run TestReasonWordRelease -count=1`. Expected: FAIL. |
| -- [ ] **Step 3:** Implement to the table; write `RFS-3-C01` and `C02`, add their ids to the built list. |
| -- [ ] **Step 4:** Run Step 2's commands, `go test -race ./internal/activator/ -run 'TestSwapReleaseLeaseLossRacesTheSweep' -count=3`, the swap and wake-plan families (`-run 'Swap|Hold|Planned|FirstWake|Overlap'`, and `go test ./internal/rollout/ -run 'Reason|Scheduler' -count=1`), and Task 1's guards. Expected: PASS. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestProcesses|TestDeclaredProcesses|TestProductionBackendImplementsRootfsSeams' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** Run Step 2's command, the swap and wake families (`-run 'Swap|Overlap|Wake'`) 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; a refusal is never the build's failure" |
| +git add internal/activator |
| +git commit -m "activator: read a rootfs build's declared processes from its own image's manifest; log what this box does not run yet" |
| ``` |
| |
| --- |
| @@ -1129,7 +873,9 @@ git commit -m "rootfs: release gates every move onto a new build; a failure keep |
| **Review:** cross-model (pre-flight §7): the rootfs run's cmd unit proof. |
| |
| **Files:** |
| -- 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) |
| +- Create: `internal/activator/rootfs_ctl_harness_test.go` (`rootfsCtlHarness`, below; Group R reuses it) |
| +- Modify: `internal/activator/backend_rootfs.go` (`stagedImageOf`, beside Task D's `Processes`) |
| +- Modify: `internal/activator/cmdunit.go`: `StartCmd`'s body (`:172`) becomes `startCmdUnit`, shared by both runtimes, which builds Plan 2's runtime-aware `cmdUnit` (A8; Group R's release reuses it); 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`) |
| @@ -1137,9 +883,13 @@ git commit -m "rootfs: release gates every move onto a new build; a failure keep |
| - 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), N1's typed `CmdRootfs`, Task 10's `startCmdUnit`, `stagedImageOf` and `rootfsCtlHarness`, `ExecBackend.BuildIdentity` (`backend_exec.go:1842`), `release.GetManifest` (`internal/release/release.go:804`). |
| +- Consumes: Task 6's `rootfsCmdVars`, A3, A5, A8 (Plan 2's runtime-aware cmd unit), N1's typed `CmdRootfs` and `stagedIdentityOf`, `ExecBackend.BuildIdentity` (`backend_exec.go:1842`), `release.GetManifest` (`internal/release/release.go:804`). |
| - Produces: |
| ```go |
| + func stagedImageOf(id release.StagedIdentity, process string, argv []string) instancectl.StagedImage // beside stagedExeOf |
| + // (identity.go:98): Path id.StagedPath, Version id.Version, Digest id.Digest, Process, Argv |
| + func (b *ExecBackend) startCmdUnit(ctx context.Context, rt registry.Route, spec CmdSpec, launch cmdLaunch) (CmdUnit, error) |
| + // StartCmd's body with the launch (argv for a binary row; Process and StagedImage for a rootfs row) as its one variable |
| // 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" |
| @@ -1147,10 +897,11 @@ git commit -m "rootfs: release gates every move onto a new build; a failure keep |
| var runCopySuperseded = map[string]string{"RUN-C47": "RFS-3-C18"} |
| ``` |
| |
| +`rootfsCtlHarness` (`rootfs_ctl_harness_test.go`) is the real control handler behind an `ExecBackend` (Astra R1 finding 1): 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. |
| + |
| Rules: |
| -- `StartCmd` on a rootfs row: the tenant launch file is Plan 2's schema 2 with `Process: "cmd"` and no argv, its env `rootfsLaunchEnv(rootfsCmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir))` [pf 1.6]; the argv is `spec.Args` as given (no live-link prefix), sent to root as `StagedImage.Argv` through `RootfsControl.CmdRootfs(ctx, host, b.tier(rt).MemoryMax, stagedImageOf(id, "", spec.Args))` (A3, A5, the sized tier [pf 1.8]); the image identity is required (a rootfs command always names its image; none refuses with `errNoCmdExe`). An `ErrStagedImage` or `ErrStartRefused` answer is marked with `refuseRootfs` [pf 1.7]. The `CmdUnit` it returns, on success and on a failed start alike, is Plan 2's runtime-aware unit (A8, through Task 10's `startCmdUnit`): `RunCmd`'s `Poll`, its `Stop`, `interruptCmdsLocked` (`cmd.go:377`), `settleCmds` (`:415`) and the sweep's `retryCmdSettlesLocked` (`:399`) all reach `RootfsUnitName(RoleCmd, host)` and prove that unit's cgroup empty, never the binary cmd unit's (Astra R1 finding 1). A binary row is unchanged (INV-6). No egress step: #328 checks in root's `startRootfsCmd` [pf 2.5]. |
| +- `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 this task'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 != ""` resolves the build before it takes its admission lock, never under `a.mu` [Astra R1 8]: `BuildIdentity` (`backend_exec.go:1842`) hashes the whole image (`release.FileSHA256`, `:1857`), and `RunCmd` holds `a.mu` from its admission loop until `:615`, where it sets `spec.serving` (`cmd.go:600`). So `id, err := b.BuildIdentity(rt, spec.Build)` runs once, off the lock, after `Prepare` and before the loop; an error ends the run before anything starts with `ErrCmdVersion` (wrapped). Under the lock, at `:600`, `spec.serving = stagedExeOf(id)` (a rootfs row's `StartCmd` turns that identity into `stagedImageOf`) and `h.build = id`, the full identity, digest included. Root checks the digest again at the start, so a file replaced between the hash and the start is refused as `ErrStagedImage` (a refusal). `recordBuild` names `spec.Build`, which is the build about to touch the data. The environment stays the serving generation's (merge ruling M3). Pins [Astra R1 9]: `entryGenerationsLocked` adds `h.build` for every hold not proven settled, and `RunCmd` calls `a.publishBeforeExec()` off the lock after `recordBuild` and before `StartCmd`, so the generations file on disk names the run's build before it execs; a failed write abandons the run (`errStagedBuildNotPublished`), nothing started. This works for binary rows too: `CmdExe` already mounts a staged binary. |
| -- `RunCmd` is refused as busy while `a.releaseRuns[host]` exists (INV-7, Task 10's table): a run never starts beside a release, running or unproven. |
| - Console: `runClassRefusal` passes a rootfs record that does not hibernate (`rec.Runtime == provision.RuntimeRootfsV1`; today's `!rec.HibernateOrDefault()` arm, `apiruns.go:274`, refuses it), and keeps the fleet refusal for every record (D4, `:279-281`): a `carlos run` on a fleet box is refused with today's sentence until Plan 6 Task 16 carries it over the box-dials-the-console door (R7), and that task removes the fleet arm. The CLI page says so (RFS-3-C28). With `meta.Version != ""`: `release.ValidVersion` or 400 `RFS-3-C19`; `release.GetManifest(ctx, store, acct, app, version)` not found, 409 `RFS-3-C20`; written to `request.json`'s `Version` and the `run-start` audit row's version. |
| - Box: the runs worker sets `CmdSpec.Build = req.Version`. `runResultForLaunch` maps `ErrCmdVersion` to `Result{Refused: runs.RefusedVersion, Detail: req.Version}`; `runRefusedWords` says `RFS-3-C22`; the CLI's `runExit` prints `RFS-3-C21` with `r.Detail` and exits 3. |
| - CLI: `--version <build>` (help `RFS-3-C17`), sent as `meta.version`; the usage line becomes `RFS-3-C18`. |
| @@ -1193,7 +944,7 @@ The invariant tables gain the run rows: INV-1, the run's `cmdUnit` through the h |
| |
| - [ ] **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 4:** Run Step 2's commands, the cmd families the `startCmdUnit` refactor touches (`go test ./internal/activator/ -run 'Cmd|RunCmd' -count=1`), plus `go test . -run 'TestRun|TestDocsite|TestRootfsCopy|TestRootfsBuilt' -count=1` and `go test ./internal/docsite/ -count=1`, and Task 1's guards and goldens (`TestBinaryStartCmdLaunchGolden` must stay byte-identical). Expected: PASS. |
| - [ ] **Step 5: Commit** |
| |
| ```bash |
| @@ -1310,15 +1061,421 @@ git commit -m "system apply: a box with rootfs instances refuses a platform rele |
| - [ ] **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|TestReleaseObligation|TestReleaseRunConsumersReadTheRecord|TestResidentFailureClassification|TestProductionBackendImplementsRootfsSeams|TestRootfsHealthWindowIsTheRootfsBound|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` and `go test ./internal/ops/ -run 'TestFleetDBsStillExcludesHibernatingSidecars' -count=1` (PASS). Plan 3's diff touches no `internal/instancectl` file except `client.go` [pf 4.2]: `git diff --name-only origin/main...HEAD -- internal/instancectl` prints exactly `internal/instancectl/client.go`. |
| -- [ ] **Step 6:** Every live `RFS-3-C` id except W1's (`C08`, `C09`, `C10`) is in the gate's built list, and C13 is in none: `go test . -run 'TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. The controller pushes the branch to amadan; CI runs the full suite; main's census runs at merge [pf 4.1]. |
| +- [ ] **Step 4:** `go test -race ./internal/activator/ -run 'TestResidentRequestAndTickRaceOneWake|TestResidentCrashDuringStopIsOneStop' -count=1`. Expected: PASS. |
| +- [ ] **Step 5:** The invariants hold: `go test ./internal/activator/ -run 'TestRootfsFilesNameNoBinaryVerb|TestRootfsRemovalOwnersUnchanged|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv|TestEveryRootfsProofNamesTheRootfsUnit|TestRootfsRefusalPrecedesTheLease|TestResidentFailureClassification|TestProductionBackendImplementsRootfsSeams|TestRootfsHealthWindowIsTheRootfsBound|TestBinary.*Golden|TestGenHealthyBoundBinary' -count=1` and `go test ./internal/ops/ -run 'TestFleetDBsStillExcludesHibernatingSidecars' -count=1` (PASS). Plan 3's diff touches no `internal/instancectl` file except `client.go` [pf 4.2]: `git diff --name-only origin/main...HEAD -- internal/instancectl` prints exactly `internal/instancectl/client.go`. |
| +- [ ] **Step 6:** Group A contains no release machinery: `grep -n 'releaseOp\|runRelease\|ReleaseError\|leaseWatch' internal/activator/*.go` finds nothing. Every live `RFS-3-C` id except W1's (`C08`, `C09`, `C10`) and Group R's (`C01` to `C07`, `C29`) 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 R: the release process (built after Group A) |
| + |
| +Group A and Group W merge without this group (Paul, 2026-10-26). Until it lands, a build that declares `release` serves `web` and Task D logs that this box does not run it, and an app migrates in its own web command, as Rails 8's Docker entrypoint does (`bin/rails db:prepare` before the server). Plan 4's sample app migrates that way, and Plan 4 does not depend on this group (index). |
| + |
| +Group R depends on Group A only. Group W does not depend on it, and it does not depend on Group W: they may be built in either order after A. Both edit `doWake` after step 6 and `swapOverlap` step 8 (Task D's hook); whichever lands second merges the other's edits there, and R adds one line to W's two worker gates if W landed first (R1's consumer table, last row). |
| + |
| +The design is the decoupled one Astra proposed in its round-2 review and Paul chose: |
| +- **Overlap swap (R2).** `release` is one service-owned operation that runs under the incumbent's lease before the swap is admitted. The swap is admitted only after the release succeeded and its unit is proven stopped, and it receives that as an attempt-scoped, in-memory result (`releasePassed`), against which it rechecks the attempt, the target build and ownership. No release runs inside `swapOverlap`. After an agent restart nothing is remembered, so the release runs again, which D3 allows. |
| +- **Cold wake, planned wake, hold (R3).** `release` stays inside the wake's restored-data and lease lifetime: it needs the restored database and the wake's lease, and runs between the restore (and Task 7's placeholder) and `web`. |
| +- **One owner (R1).** Both run through the same operation and the same record, `a.releaseOps[host]`, from admission to proof, with one retry path in the shared pending-proof pass and one classification of every result. |
| + |
| +### Group R invariants |
| + |
| +Each has its enforcing test; R1 lands the tests and R2 and R3 add their rows. Group A's INV-1, INV-4 and INV-5 tables gain release rows in R1 (the release `cmdUnit`, the release sentinels, the release launch file). |
| + |
| +- **INV-R1. One owner for a running release.** From admission to proof a release is owned by exactly one record, `a.releaseOps[host]`, whatever happens to the entry, wake or swap that started it [Astra R1 5, 6]. Every consumer reads that record and nothing else. *Test:* `TestReleaseOpConsumersReadTheRecord` (R1), a table over every row of R1's consumer table, each refusing or waiting while the record exists and proceeding once it is removed. |
| +- **INV-R2. One retry path, whatever the entry's state.** A record whose operation has finished with its proof outstanding is retried by `reapReleaseOpsLocked`, in `finishPendingStops` (`activator.go:4228`), the pass the sweep (`:4577`) and Shutdown (`:5232`, `:5273`, `:5329`) both run, regardless of whether its owner entry is awake, stopping or gone [Astra R2 N1, N2]. *Tests:* `TestUnprovenReleaseOnAnAwakeIncumbentIsRetried`, `TestShutdownDrainsReleaseOps` (R1). |
| +- **INV-R3. Every release result has one classification.** `classifyRelease` (R1) maps every result to exactly one of passed, failed, unproven, refused or cancelled, from the record's state and the typed result; nothing reaches `classifyStep`'s default of `stepFailed` (`swap.go:162`) [Astra R2 N6]. A release is the build's failure only as a `*ReleaseError` with its unit proven gone. *Test:* `TestEveryReleaseResultIsClassified` (R1), through the overlap, planned-wake, hold and resident-accounting outcomes. |
| +- **INV-R4. An open release blocks every transition of the host, checked first.** Every swap admission (any mode, any cause), every wake and every run of a host with a record is refused before anything decides whether the selected build needs a release, and again at the final exec gate [Astra R2 N4]. *Test:* `TestOpenReleaseBlocksEveryTransition` (R2), with an unproven B release followed by a config attempt onto good build A and by a build that declares no release. |
| +- **INV-R5. The swap runs only on a proven pass.** An overlap swap of a build that needs a release is admitted only with a `releasePassed` for this attempt and this build's full identity, with no record open, and with ownership rechecked at admission and at the exec. *Test:* `TestSwapAdmittedOnlyOnAProvenPass` (R2). |
| + |
| +### Task R1: The release operation |
| + |
| +**Review:** cross-model (pre-flight §7): release lease supervision, the cmd unit proof, the one owner and its drain. |
| + |
| +**Files:** |
| +- Create: `internal/activator/rootfsrelease.go`, `internal/activator/rootfsrelease_test.go` |
| +- Modify: `internal/activator/backend_rootfs.go` (`StartRelease`, `ReleaseEnv`); `internal/activator/backend_unit.go` (`SplitBackend.StartRelease`, `ReleaseEnv`, forwarding to `b.Exec` for an exec-backed row and refusing a unit-backed one, `refuseRootfs(errNoRootfsControl)`) [Astra R1 4]; `production_backend_test.go` (the `ReleaseBackend` row) |
| +- Modify: `internal/activator/backend_exec.go:787` (`execLease.SafeUntil`, `execLease.Lost`, beside `Err`) |
| +- Modify: the consumers of the record (the table below): `internal/activator/cmd.go` (`RunCmd`'s admission, beside `cmdBusyLocked`, `:284`); `internal/activator/activator.go` (the plan-disabled arm, `:4688`; the idle arm, `:4709`; the instance awake ceiling, `:4758`; `beginStopLocked`, `:2687`; doWake's wake latch, `:2183`; `finishPendingStops`, `:4228`; Shutdown's drain count, `:5327`, and `logUnresolvedAtExit`, `:5347`); `internal/activator/opset.go` (`releasable`, `:681`); `internal/activator/maintenance.go` (`cleanupFailedWake`, `:360`); `internal/activator/generations_file.go` (the snapshot lists every record's build); `internal/activator/rootfs_service.go` (the tick skips a host with a record; `residentFailure` gains the release sentinels); `internal/activator/swap.go` (`Service.Swap`'s admission, `:297`, R2) |
| +- 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 release rows); `internal/activator/rootfs_processes_test.go` (Task D's release log line goes) |
| + |
| +**Interfaces:** |
| +- Consumes: Task D's `Processes`; Task 12's `startCmdUnit`, `stagedImageOf` and `rootfsCtlHarness`; N1's `stagedIdentityOf` and typed `CmdRootfs`; Task 6's `rootfsCmdVars`; `CmdUnit` (`cmdunit.go:95`), `cmdHold` (`cmd.go:91`, `newCmdHold` `:140`), `cmdBusyLocked` (`cmd.go:284`), `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`), `publishBeforeExec` (`generations_file.go:250`), `lease.Held.SafeUntil`/`Lost` and `lease.Replicator.SafeUntil`/`Lost` (`internal/lease/lease.go:237-241`, `:476-480`). |
| +- Produces: |
| + ```go |
| + type ReleaseBackend interface { |
| + ReleaseEnv(rt registry.Route) (map[string]string, error) // the delivered files a successor would launch with, composed by rootfsCmdVars |
| + // StartRelease runs runPendingRecord(ctx) and runExecGate(ctx) immediately before CmdRootfs; a refusal there is |
| + // launchRefused and nothing reached root. |
| + StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) |
| + } |
| + // leaseWatch is the held lease a release runs under: the wake's Lease (execLease, before it becomes a replica) in R3, |
| + // the incumbent's e.rep (*lease.Replicator) in R2. Both production types have it; a lease without it runs no release. |
| + type leaseWatch interface { |
| + Err() error |
| + SafeUntil() (time.Time, error) |
| + Lost() <-chan struct{} |
| + } |
| + func (l *execLease) SafeUntil() (time.Time, error) // l.held.SafeUntil() |
| + func (l *execLease) Lost() <-chan struct{} // l.held.Lost() |
| + func releaseDue(rt registry.Route, id release.StagedIdentity, procs map[string]release.Process) bool |
| + // rt.Rootfs() && procs has release.ProcessRelease && !(id.Version == rt.GoodVersion && id.Digest == rt.GoodDigest) |
| + func releaseTimeout(p release.Process) time.Duration // 600 s when TimeoutSec <= 0; capped at runs.MaxTimeout |
| + // releaseStopLead is how far ahead of the lease's safety deadline a release is stopped. One StopAndSettle is at most |
| + // DeadlineControl (30 s) + actStopTimeout (20 s) + two drains (2 x 5 s) = 60 s, so cmdStopBound (2 min) leaves room for a |
| + // second attempt. A healthy lease never comes this close: LeaseTTL is 15 min, renewed every 5. Vars so tests shrink them. |
| + var releaseStopLead = cmdStopBound |
| + var releaseLeaseRecheck = 5 * time.Second // how often the supervisor re-reads SafeUntil |
| + type ReleaseError struct { |
| + Build, Signal string |
| + Exit int |
| + TimedOut bool |
| + Took time.Duration |
| + } |
| + func (e *ReleaseError) Error() string // RFS-3-C05, C06 or C07 formatted: the member-facing reason a failed wake carries |
| + // releaseOp is the one owner of a release (INV-R1), from admission until its unit is proven gone. |
| + // Service.releaseOps map[string]*releaseOp, by host. |
| + type releaseOp struct { |
| + build release.StagedIdentity // full identity (stagedIdentityOf); pinned in the generations file while the record lives |
| + hold *cmdHold // the cmd unit's stop and settle |
| + cancel context.CancelCauseFunc |
| + owner *actEntry // the entry it runs beside (R2's incumbent, R3's waking entry); nil once that entry is gone |
| + owed Lease // R3: a failed wake's lease, kept while the unit is unproven; given back after the proof |
| + state opState // opRunning (runRelease owns the settle) | opUnproven (finished, proof outstanding: the reaper owns it) |
| + retryAt time.Time |
| + busy bool // one settle attempt at a time |
| + } |
| + var errReleaseOpen = fmt.Errorf("%w: a release command of this instance is still running or not proven stopped", errSwapBusy) |
| + var errReleaseUnproven = errors.New("activator: a release command's unit is not proven stopped") |
| + var errReleaseNoLease = errors.New("activator: the lease a release would run under cannot report its safety deadline") |
| + var errReleaseLeaseLost = errors.New("activator: the instance's lease ended while its release command ran") |
| + // returned as fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost): an ownership end, never the build's failure |
| + type releaseOutcome int // releasePassed | releaseFailed | releaseUnproven | releaseRefused | releaseCancelled |
| + func classifyRelease(host string, err error) releaseOutcome // INV-R3, the table below |
| + func (a *Service) runRelease(ctx context.Context, e *actEntry, rt registry.Route, id release.StagedIdentity, held leaseWatch, gate func() error) error |
| + func (a *Service) reapReleaseOpsLocked() // in finishPendingStops: each record in opUnproven, not busy, past retryAt, whatever |
| + // its owner's state, gets one settle off a.mu (actStopTimeout); proven: the record goes, its owed lease is given back |
| + // (or a.oweRelease), the generations file is rewritten |
| + const ( status.ReasonRelease = "release"; status.ReasonReleaseTimeout = "release-timeout" ) |
| + ``` |
| + |
| +`gate` is the calling site's ownership gate (R2 and R3 name each): it takes `a.mu` itself and answers whether this entry is still the host's, with no fence, no shutdown, the attempt or plan still current, and the site's lease held. `runRelease` adds the lease's deadline to it: |
| + |
| +```go |
| +own := func() error { |
| + if err := gate(); err != nil { |
| + return err |
| + } |
| + if err := held.Err(); err != nil { |
| + return fmt.Errorf("%w: %v", errSwapLeaseLost, err) // leaseLost's shape over the watch |
| + } |
| + until, err := held.SafeUntil() |
| + if err != nil || time.Until(until) <= releaseStopLead { |
| + return fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost) |
| + } |
| + return nil |
| +} |
| +``` |
| + |
| +`runRelease`, in order: |
| +1. Under `a.mu`, before anything else, the open-release check (INV-R4) [Astra R2 N4]: a record for `rt.Host` in any state refuses with `errReleaseOpen`. Then `procs, err := Processes(rt, id)` off the lock. 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`, marked with `refuseRootfs`, 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), and with `errReleaseOpen` when a record appeared meanwhile; else create the record (`build: id`, `hold: newCmdHold("release", cancel, a.now)` with `starting` set, `owner: e`, `state: opRunning`, `busy: true`). Then, off `a.mu`, `a.publishBeforeExec()`: the record's build is in the generations file before anything runs, and a failed write removes the record and returns `errStagedBuildNotPublished` (a refusal) [Astra R1 9]. |
| +3. `recordBuild(ctx, rt.Host, id.Version)`: the build state names the release's build before it touches the data (settings §4.2). `StartRelease` then runs `runPendingRecord(ctx)` and `runExecGate(ctx)` immediately before `CmdRootfs`, as the exec seam does, so a cold wake's pending record is written before `release` runs, not at `web`'s exec, and ownership is checked at the last moment before root is asked. (No egress step: #328 checks on root's side, in `startRootfsCmd` [pf 2.5].) |
| +4. Event `RFS-3-C03`. `rctx, trip := context.WithCancelCause(ctx)` with `releaseTimeout(procs[release.ProcessRelease])` over it. |
| +5. `StartRelease(withExecGate(rctx, own), rt, id, ReleaseEnv(rt), out)`: Task 12's `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 and the record is removed: nothing ran. |
| +6. **Lease supervision**, from the moment the unit may run until it is proven gone: a goroutine re-reads `held.SafeUntil()` every `releaseLeaseRecheck` and wakes at once on `held.Lost()`. It trips (`trip(errReleaseLeaseLost)`) when `Lost()` closes, when `SafeUntil` errors, or when `time.Until(until) <= releaseStopLead`, keeping the last `until` it read as the deadline. It uses the real clock, as the lease does (`SafeUntil` is monotonic), not `a.now`. |
| +7. Poll (`unit.Poll`, the 30 s long-poll) until done or `rctx` ends. Then stop and settle whatever happened, through the record's `hold.stop`, with the reason `StopLeaseLost` after a trip. After a trip the settle is retried until it is proven or the deadline from step 6 passes; otherwise it is bounded by `cmdStopBound`. A failed settle leaves the record in `opUnproven` with `busy` cleared and `retryAt` set, and returns `errReleaseUnproven` (wrapped with `errSwapLeaseLost` after a trip). From then on `reapReleaseOpsLocked` is its only retrier, whatever its owner's state (INV-R2) [Astra R2 N1]. |
| +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; exit 0: event `RFS-3-C04`, nil; non-zero, a signal, or the timeout: `*ReleaseError` and its event (C05, C06, C07), which is returned only once the unit is proven gone (otherwise step 7's `errReleaseUnproven` is the result). |
| +9. Once proven: remove the record under `a.mu`, rewrite the generations file off it, stop the supervisor. |
| + |
| +**Every result, classified (INV-R3)** [Astra R2 N6]. `classifyRelease(host, err)` reads the record first, so "the unit may still run" is never confused with "this build failed": |
| + |
| +| result | record after the call | outcome | R2 (overlap) | R3 planned first wake | R3 hold | R3 other pinned wake | resident accounting | |
| +|---|---|---|---|---|---|---|---| |
| +| any error | still there (`opUnproven`) | unproven | `SwapAbandoned`; nothing more runs; the record blocks the host (INV-R4) | the wake fails; its lease goes to the record (`owed`); no fallback, B not failed | `SwapDown` with no build failure recorded; lease to the record | the wake fails; lease to the record | no failure counted (the record latches the host) | |
| +| nil | gone | passed | the swap may be admitted with `releasePassed` | `web` starts | the pinned start runs | `web` starts | n/a | |
| +| `*ReleaseError` | gone | failed | `SwapFailed`, `Executed` true, reason "release: ..." or "release timed out: ..." | B's failure: fallback to the good build, `w.failed` | `SwapDown`, `markPinExec` | the wake fails with B's failure | counts | |
| +| lease loss (`errSwapLeaseLost`) | gone | cancelled | `SwapAbandoned` | the wake fails, no fallback, B not failed | `SwapDown`, no build failure | the wake fails | no failure | |
| +| `ctx.Err()`, a fence, shutdown | gone | cancelled | `SwapAbandoned` | as lease loss | as lease loss | as lease loss | no failure | |
| +| `errReleaseOpen`, `errSwapBusy` | (another's, or none) | refused | `SwapAbandoned`; the scheduler retries after its deferral | refused before anything ran (the wake latch, INV-R4) | `SwapAbandoned` (Swap's admission) | refused | no failure | |
| +| `errRootfsRefused` (a `Processes` refusal, `errReleaseNoLease`, root's `ErrStagedImage`/`ErrStartRefused`), `errStagedBuildNotPublished`, a gate refusal | gone | refused | `SwapAbandoned` | the wake fails, B not failed, no fallback | `SwapAbandoned` | the wake fails | no failure | |
| + |
| +R2 and R3 map the outcome with this table and never pass a release error to `classifyStep`, whose default is `stepFailed` (`swap.go:162`). `residentFailure` (Task 8) is true for a release result only when the outcome is failed. |
| + |
| +**Who reads the record (INV-R1).** Every consumer of "is a release running or unproven for this host" reads `a.releaseOps[host]`, never an entry field, so an entry's deletion cannot drop the obligation [Astra R1 5, 6; Astra R2 N1 to N4]: |
| + |
| +| consumer | main's code | with a record for the host | |
| +|---|---|---| |
| +| a member's run | `RunCmd`'s admission, beside `cmdBusyLocked` (`cmd.go:284`) | refused as busy (the run's existing busy answer); no run beside a release | |
| +| another release | `runRelease` step 1, before the due decision | `errReleaseOpen` | |
| +| any swap of the host | `Service.Swap` (`swap.go:297`), before the mode switch and before any due decision (R2) | `abandon(errReleaseOpen)` for every mode and cause: a config or restart attempt onto the good build and a build with no release are refused too [Astra R2 N4] | |
| +| the plan-disabled stop | `!activeProbe(e) && e.cmd == nil && a.disabled(e.route)` (`activator.go:4688`) | deferred while the owner has a record, as "never mid-command" already defers it for a run; R2 also refuses to start a release for a disabled route, so at most the one in flight defers the stop [Astra R2 N3] | |
| +| idle sleep | `hibernates && e.inflight == 0 && e.cmd == nil` (`activator.go:4709`) | the owner is never idle-stopped, so a hibernating incumbent keeps serving through an overlap migration (C8) | |
| +| the instance awake ceiling | `maxRunFor` arm, `!e.worker && hibernates && e.cmd == nil` (`activator.go:4758`) | deferred while the owner has a record; it fires on the first sweep after the record goes [Astra R2 N3] | |
| +| a stop of the owner | `beginStopLocked` (`:2687`) | cancels the record (`cancel(cause)`), so `runRelease` settles it at once; `releasable(e)` (`opset.go:681`) is false until the record is gone, so replication and the lease are held | |
| +| a wake of the host | doWake's latch (`activator.go:2183`), the tick's skip | refused with `errWakeUnproven` while the record exists and its owner is not this wake | |
| +| the failed wake's cleanup | `cleanupFailedWake` (`maintenance.go:360`), then the entry's deletion (`activator.go:1860`) | the wake's lease moves to `owed` (never released, never left to TTL alone), `owner = nil`; the record outlives the entry | |
| +| the one retry path | `finishPendingStops` (`activator.go:4228`), run by the sweep (`:4577`) and by Shutdown (`:5232`, `:5273`, `:5329`) | `reapReleaseOpsLocked`, for every record in `opUnproven`, whatever its owner's state [Astra R2 N1] | |
| +| Shutdown's drain | `left := len(a.unprovenWakes) + len(a.owedReleases)` (`activator.go:5327`), `logUnresolvedAtExit` (`:5347`) | `+ len(a.releaseOps)`: Shutdown keeps running the pass until every record is proven or its budget ends, and names each one left at exit [Astra R2 N2] | |
| +| pins | `entryGenerationsLocked` and the snapshot | every record's `build` is listed, whatever its owner; published before the release execs (step 2) | |
| +| a member run's retries | `retryCmdSettlesLocked` (`cmd.go:399`) | untouched: a release is not a run and never sits in `e.cmd` or `e.cmdLeft` | |
| +| a worker start (if Group W has landed) | W1's `workerGate` and `workerWakeGate` | refused while a record exists (whichever of R and W lands second adds this line) | |
| + |
| +- [ ] **Step 1: Write the failing tests.** The backend half goes through Task 12's `rootfsCtlHarness`, not a scripted fake (Astra R1 finding 1). 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 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; |
| + // 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 record removed, nothing started |
| +func TestReleaseExitNonZero(t *testing.T) // the rootfs unit exits with status 3: *ReleaseError{Exit: 3}; event C05; |
| + // one stop of the rootfs unit |
| +func TestReleaseTimesOut(t *testing.T) // the rootfs unit stays running past a shrunk timeout: TimedOut, stop sent to |
| + // the rootfs unit and its cgroup proven empty, event C07 |
| +func TestReleaseUnprovenKeepsTheRecord(t *testing.T) // the rootfs unit's cgroup stays populated: errReleaseUnproven; a.releaseOps[host] |
| + // still set, its build in the persisted generations file; the next sweep's reaper proves it once the group empties, then |
| + // the record and the pin go |
| +func TestReleaseExecGateRefusesAtTheLastMoment(t *testing.T) // the gate flips to refusing after step 2: launchRefused, no /cmd request |
| + // in the log, the record removed, the gate's error returned |
| +func TestReleaseOutputReachesTheAppLog(t *testing.T) // lines the unit writes to both streams reach the fake EventSink's App lines; |
| + // past the cap they stop |
| +// Service half, fakeBackend |
| +func TestReleaseOpConsumersReadTheRecord(t *testing.T) // INV-R1. with a record for the host, each consumer row: RunCmd refused; a |
| + // second runRelease errReleaseOpen; Swap of any mode and cause abandoned; sweepOnce past the idle window, past a maxRunFor |
| + // ceiling (installed) and with the route plan-disabled does not stop the owner; a Bounce stop stays pending (releasable |
| + // false) with rep open; with the owner gone, a ServeHTTP to the cold host and a resident tick are refused errWakeUnproven; |
| + // the persisted generations file lists the build. Remove the record (proven): each consumer proceeds |
| +func TestUnprovenReleaseOnAnAwakeIncumbentIsRetried(t *testing.T) // INV-R2 [Astra R2 N1]. the owner stays awake; the first settle fails: |
| + // opUnproven; a later finishPendingStops proves it once the group empties; the pin leaves the file on disk; a new release |
| + // and a run are admitted again |
| +func TestShutdownDrainsReleaseOps(t *testing.T) // INV-R2 [Astra R2 N2]. (a) an ownerless record (a failed wake's, owed lease |
| + // held): Shutdown does not return while it is unproven within its budget, retries it in its poll, proves it, gives the |
| + // lease back; (b) a stopping incumbent whose release's first settle fails and a later one succeeds: Shutdown waits and |
| + // proves it; (c) still unproven at the deadline: logUnresolvedAtExit names the host and the record |
| +func TestEveryReleaseResultIsClassified(t *testing.T) // INV-R3 [Astra R2 N6]. a table over every row of the classification table: |
| + // classifyRelease's outcome; and for errReleaseOpen, errReleaseNoLease and a plain errReleaseUnproven, through the overlap, |
| + // planned-wake and resident paths: never SwapFailed, never OnGen failure, never a failure-book entry, never a resident failure |
| +func TestReleaseBuildPublishedBeforeExec(t *testing.T) // [Astra R1 9] the generations file on disk names the release's build before |
| + // the /cmd request; a failed write: errStagedBuildNotPublished, no /cmd request, no record left |
| +func TestReleaseThroughTheProductionBackend(t *testing.T) // [Astra R1 4] productionBackend over the rootfsCtlHarness ExecBackend: the |
| + // service's type assertion finds ReleaseBackend and the release runs in the rootfs cmd unit; a unit-backed row is refused |
| +func TestReleaseRefusedWhenTheManifestIsNotTheImage(t *testing.T) // [pf 1.9] Processes errors: errRootfsRefused, StartRelease never called |
| +func TestReleaseRefusedWhileARunHoldsTheUnit(t *testing.T) // e.cmd set: errSwapBusy, StartRelease never called |
| +func TestReleaseGatedOnOwnership(t *testing.T) // table, StartRelease never called in each: the site gate refuses (entry |
| + // superseded, fence raised, shutdown); held.Err set; SafeUntil less than releaseStopLead ahead: errors.Is(err, errSwapLeaseLost); no event |
| +func TestReleaseNeedsAWatchableLease(t *testing.T) // held nil: errReleaseNoLease, nothing started |
| +func TestReleaseStopsOnLostLease(t *testing.T) // close fakeLease.lost while the release polls: the record's stop runs with |
| + // StopLeaseLost and is proven before until; errors.Is(err, errSwapLeaseLost) and errors.Is(err, errReleaseLeaseLost); no |
| + // ReleaseError; event C29 after the proof |
| +func TestReleaseStopsBeforeTheSafetyDeadline(t *testing.T) // renewals stall: lost never closes, until frozen at now+lead+300ms, with |
| + // releaseStopLead 200 ms and releaseLeaseRecheck 10 ms: the stop starts by until-lead+recheck and is proven before until |
| +func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) // until advanced by 1 s every 20 ms (lead 200 ms): the release runs to |
| + // exit 0 unstopped, event C04, nil |
| +func TestReleaseLeaseLossUnprovenLeavesTheHold(t *testing.T) // lost closes, every settle fails until past until: errReleaseUnproven and |
| + // errSwapLeaseLost both match; the record stays, finished with proof outstanding, and the reaper owns it; no C29 |
| +func TestReleaseLeaseLossRacesExit(t *testing.T) // RACE: lost closes as the unit reports done with status 0: one settle, |
| + // the result is the lease-loss error, never nil. Run with -race. |
| +func TestStopSettlesARunningRelease(t *testing.T) // RACE: Bounce while the release polls: the release unit is stopped and settled |
| + // before rep.Close (ordered log); RunCmd during the release starts no unit. Run with -race. |
| +``` |
| + |
| +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, the release sentinels with `classifyRelease`'s outcome; INV-5, the release launch file under `t.Setenv("PATH", "/agent/bin")`; `TestRootfsCmdVarsFollowTheRunRule` gains the release case (runID "" carries no `CARLOS_RUN_ID` or `CARLOS_RUN_DIR`). |
| + |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestReleaseDue|TestReleaseTimeout|TestRelease|TestUnprovenReleaseOnAnAwakeIncumbent|TestShutdownDrainsReleaseOps|TestEveryReleaseResult|TestStopSettlesARunningRelease|TestProductionBackend|TestEveryRootfsProof|TestRootfsRefusalsAreNot|TestRootfsLaunchFilesCarry|TestRootfsCmdVars' -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|TestShutdownDrainsReleaseOps' -count=3`, the families the consumers touch (`-run 'Cmd|RunCmd|Sweep|Idle|Shutdown|Releasable|Disabled|MaxRun'`), and Task 1's guards and goldens. Expected: PASS. |
| +- [ ] **Step 5: Commit** |
| + |
| +```bash |
| +git add internal/activator internal/rolloutwords internal/status approved_rootfs_copy_test.go |
| +git commit -m "activator: the rootfs release operation: one owner from admission to proof, in the rootfs cmd unit, supervised by its lease, drained at shutdown" |
| +``` |
| + |
| +--- |
| + |
| +### Task R2: Release before an overlap swap |
| + |
| +**Review:** cross-model (pre-flight §7): C8 and the swap's admission. |
| + |
| +**Files:** |
| +- Modify: `internal/activator/swap.go`: `Service.Swap` (`:297`, the open-release check and the release step before the mode switch); `swapOverlap` (`:415`): its admission closure (`:455-490`) and step 3a's gate (`:549-553`) recheck the pass; `internal/activator/rootfsrelease.go` (`releaseBeforeSwap`, `releasePassed`) |
| +- Modify: `internal/rollout/events.go:36` `reasonWord`; `internal/rolloutwords/words.go` (`reasons`) |
| +- Create: `internal/activator/rootfs_swap_release_test.go`, `internal/rollout/rootfs_reason_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: R1's `runRelease`, `classifyRelease`, `releaseDue`, the record; Task D's `Processes`; `ownedLocked` (`swapadmit.go:88`); the attempt's full identity (`Attempt.Build`, `StagedPath`, `Digest`, `Demand`, `swap.go:42-48`). |
| +- Produces: |
| + ```go |
| + // releasePassed is an attempt-scoped, in-memory result: B's release succeeded and its unit is proven stopped. |
| + type releasePassed struct { |
| + host string |
| + schedRev uint64 // the attempt's SchedRev |
| + build release.StagedIdentity // the attempt's full identity |
| + } |
| + func (a *Service) releaseBeforeSwap(ctx context.Context, at Attempt, newest func(string) uint64) (*releasePassed, SwapResult, bool) |
| + // (nil, _, true): no release is due, the swap proceeds without a pass; (pass, _, true): proceed with it; |
| + // (nil, res, false): the release's outcome as a SwapResult (R1's table), and the swap is never admitted |
| + // SwapResult.Reason for a release failure: "release: " + err.Error(), or "release timed out: " + err.Error() |
| + ``` |
| + |
| +`Service.Swap`, for every mode and cause, first asks under `a.mu` whether `a.releaseOps[at.Host]` exists, and abandons with `errReleaseOpen` if it does, before the mode switch and before any due decision (INV-R4) [Astra R2 N4]. Then, for `ModeOverlap` on a rootfs row (the foreign-row hold fallback, `swap.go:309-321`, goes to R3's hold path), `releaseBeforeSwap`: |
| + |
| +1. Under `a.mu`: the incumbent `e` must pass `ownedLocked(e, false)` (awake, its replica's lease held, no fence, no shutdown) and `!a.disabled(e.route)`, and the attempt must be the newest (`newest(at.Host) == at.SchedRev`); otherwise the swap's ordinary abandonment. |
| +2. `id := release.StagedIdentity{Version: at.Build, StagedPath: at.StagedPath, Digest: at.Digest, Demand: at.Demand}`, `release.VerifyStaged(id)`; `runRelease(ctx, e, rt, id, watchOf(e.rep), gate)` where `gate` is step 1 again under `a.mu`. `watchOf(x any) leaseWatch` is `x.(leaseWatch)` or nil. |
| +3. Not due (nil with no record ever made): proceed without a pass. Otherwise `classifyRelease`: passed gives `&releasePassed{at.Host, at.SchedRev, id}`; every other outcome is mapped by R1's table to a `SwapResult` and returned (never through `classifyStep`). |
| + |
| +`swapOverlap` then runs as on main with no release inside it, except that its admission closure (`:455-490`, beside `errSwapBusy`) and step 3a's gate (`:549-553`) both refuse unless: no record is open for the host, and, when a release was due, the pass names this host, this `SchedRev` and the member's full identity (`m.gen`'s `stagedIdentityOf` equal to `pass.build`) (INV-R5). Ownership is rechecked by those gates as today (`memberCurrentLocked`). A pass is held only in this call's stack: an agent restart forgets it, and the next attempt runs the release again (D3). |
| + |
| +Between the pass and the swap's admission no record exists, so the incumbent may idle or be stopped meanwhile; the swap's admission then finds it not awake and abandons, which is the ordinary outcome. |
| + |
| +`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. |
| + |
| +- [ ] **Step 1: Write the failing tests** on the existing swap fixtures (`internal/activator/swap_fixture_test.go`), with `fakeBackend` implementing R1'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; no member admitted, StartStaged never called; e.gen.N == 1; the incumbent's |
| + // proc not stopped; AppSocket unchanged |
| +func TestOverlapReleaseTimeoutKeepsTheIncumbent(t *testing.T) // same with a timeout; Reason prefix "release timed out" |
| +func TestOverlapRunsReleaseBeforeTheSwapIsAdmitted(t *testing.T) // log: release(B) start, release(B) proven, then the member's admission, |
| + // then StartStaged(B), then switch |
| +func TestSwapAdmittedOnlyOnAProvenPass(t *testing.T) // INV-R5. a pass for another SchedRev, another digest of B, or none while B's |
| + // release is due: the admission refuses (SwapAbandoned); a pass whose release unit is still unproven is never issued |
| +func TestOpenReleaseBlocksEveryTransition(t *testing.T) // INV-R4 [Astra R2 N4]. B's release unproven (record open): a config attempt |
| + // onto good build A, a restart attempt, a hold attempt and an overlap of build C that declares no release: each SwapAbandoned |
| + // with errReleaseOpen before any due decision or member; once the reaper proves the record, the next attempt proceeds |
| +func TestOverlapAbandonsWhileARunIsOpen(t *testing.T) // e.cmd set: SwapAbandoned, no release, no member |
| +func TestSwapReleaseRefusedByRootAbandons(t *testing.T) // INV-4 [pf 1.7]. rootfsCtlHarness behind the real client: root answers |
| + // 503 on /cmd: SwapAbandoned, no OnGen failure, no failure-book entry, the incumbent serving |
| +func TestSwapReleaseStopsOnLeaseLoss(t *testing.T) // Review Focus 6. fakeRep.lost closed while release(B) polls: release unit |
| + // proven before until; SwapAbandoned (not SwapFailed), no member, no C05..C07 event, C29 once |
| +func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) // RACE: fakeRep.lost closed and sweepOnce run at once: one settle attempt |
| + // at a time on the record (busy), the incumbent stopped once, rep.Close after the record is gone. Run with -race. |
| +func TestUnprovenSwapReleaseIsNotABuildFailure(t *testing.T) // INV-R3. release exits 1 and its settle fails: SwapAbandoned (unproven), |
| + // not SwapFailed; once proven, the next attempt reruns the release |
| +func TestIncumbentNeverIdlesThroughAMigration(t *testing.T) // [Astra R1 6, Astra R2 N3] hibernating rootfs incumbent, release(B) running |
| + // past cfg.Idle of fake time and past an installed maxRunFor ceiling: sweepOnce stops it for neither (C8); after the |
| + // release ends the ceiling fires on the next sweep |
| +func TestNoReleaseForADisabledRoute(t *testing.T) // the route plan-disabled: no release starts, SwapAbandoned |
| +func TestReleaseRerunsAfterAnAgentRestart(t *testing.T) // the release passed, then the Service is replaced before the swap: a new |
| + // Service over the same registry runs release(B) again before admitting B (D3) |
| +// 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|TestOverlapRunsReleaseBefore|TestSwapAdmittedOnlyOnAProvenPass|TestOpenReleaseBlocksEveryTransition|TestOverlapAbandonsWhileARun|TestSwapRelease|TestUnprovenSwapRelease|TestIncumbentNeverIdles|TestNoReleaseForADisabledRoute|TestReleaseRerunsAfterAnAgentRestart' -count=1` (under the short `TMPDIR`) and `go test ./internal/rollout/ -run TestReasonWordRelease -count=1`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement; write `RFS-3-C01` and `C02`, add their ids to the built list. |
| +- [ ] **Step 4:** Run Step 2's commands, `go test -race ./internal/activator/ -run 'TestSwapReleaseLeaseLossRacesTheSweep' -count=3`, the swap families (`-run 'Swap|Overlap|Hold'`, 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 runs before an overlap swap is admitted; the swap runs only on a proven pass; a failure keeps the incumbent" |
| +``` |
| + |
| +--- |
| + |
| +### Task R3: Release inside a wake |
| + |
| +**Review:** cross-model (pre-flight §7): C7 under the wake's lease; the failed wake's obligation. |
| + |
| +**Files:** |
| +- Modify: `internal/activator/swaphold.go:352` `startPinnedChecked`; `internal/activator/wakeplan.go:370` `spawnPlanned`; `internal/activator/activator.go`: `wake` (`:1760`, the ceiling), `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`); `internal/activator/maintenance.go` (`cleanupFailedWake`, `:360`); `internal/activator/rootfs_service.go` (`wakeCeilingFor`) |
| +- Create: `internal/activator/rootfs_wake_release_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: R1's operation, record and `classifyRelease`; N1's `healthBoundFor` and `stagedIdentityOf`; Task 7's placeholder order; each site's existing ownership gate: `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 wakeCeilingFor(rt registry.Route) time.Duration // 5 min; rootfs: 5 min + runs.MaxTimeout |
| + ``` |
| + |
| +Where `release` runs inside a wake, under the wake's own lease (`held` is `watchOf(lease)`) and the site's gate, and what each outcome means is R1's classification table: |
| + |
| +| path | where | lease (`held`) and `gate` | failure | |
| +|---|---|---|---| |
| +| hold swap | `startPinnedChecked`, after its gate, before `startPinnedAt`, on `stagedIdentityOf(pin)` | the wake's `lease`; its `gate` | the old build is already stopped; `markPinExec(e)` (`swaphold.go:378`) when the release ran, so the hold reports down, as a hold build that ran and failed does today. The lease-loss error and a refusal are the gate's NoOwnership refusal, as `leaseLost(lease)` there already is | |
| +| planned wake (asleep row, or a resident's restart, scheduler choosing B) | `spawnPlanned`, after `checkPlan` and before `healthBy` is computed, on `plan.Boot`, already a full `StagedIdentity` with its digest (`wakeplan.go:25`); `healthBy` is then measured from the release's end, and the verdict floor uses `healthBoundFor(rt)` (N1) | the wake's `lease`; `planGate(ctx, e, lease, plan, plan.Boot.Version)` | treated as B failing at its start: `executed` and `crashed` include `*ReleaseError`, so a first wake with a fallback boots the good build and records B's failure (`w.failed`, `w.fellBack`). The lease-loss error and a refusal are not B's failure: they are gateNoOwnership like every `planGate` refusal, nothing more is started, and no fallback runs | |
| +| other wakes with a pinned identity | `doWake`, right before the `ib != nil` branch, on `id` | the wake's `lease`; `leaseLost(lease)` then `a.wakeOwned(ctx, e)` | the wake fails with the error | |
| + |
| +The wake ceiling (`wakeCeilingFor`, in `wake`, `:1760`): a rootfs wake may run its `release`, 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. |
| + |
| +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 R1's supervisor is the only thing watching the lease while the migration runs. |
| + |
| +When the wake's release ends unproven, the unit may still write the database, and leaving the lease to its TTL is not enough [Astra R1 5]: `wake()` deletes the failed entry (`activator.go:1860`), and `unprovenWake` (`opset.go:741`) carries generation and legacy-run evidence but no command hold. So `cleanupFailedWake` (`maintenance.go:360`) finds `a.releaseOps[host]` owned by this wake, moves the wake's lease into its `owed` field instead of giving it back or closing it, and clears `owner`; the entry then goes as today, and the record keeps the pin, the wake latch and the lease until `reapReleaseOpsLocked` proves the unit and gives the lease back (INV-R1, INV-R2). 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 Task 7's placeholder 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. |
| + |
| +- [ ] **Step 1: Write the failing tests** with `fakeBackend` implementing R1's interface and an ordered event log: |
| + |
| +```go |
| +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 |
| +func TestFirstWakeReleaseFailureFallsBack(t *testing.T) // planned first wake, fallback A: release(B) fails; A boots, w.fellBack, |
| + // B's failure is handed to OnGen |
| +func TestRestartDoesNotRerunRelease(t *testing.T) // CauseRestart onto the good build: no release |
| +func TestReleaseRerunsAfterInterruptedWake(t *testing.T) // the wake is cancelled while release polls (Shutdown): the unit settled, |
| + // GoodVersion unchanged; a new Service over the same registry runs release(B) again before Start |
| +func TestRootfsWakeCeiling(t *testing.T) // the ctx fakeBackend.Acquire sees has Deadline >= now+5m+6h for rootfs, |
| + // and <= now+5m+1s for a binary row |
| +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 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 TestReleaseRefusedWhenOwnershipEndsBeforeItStarts(t *testing.T) // each wake site: a fence raised between admission and runRelease: |
| + // no StartRelease, the site's NoOwnership outcome |
| +func TestReleaseObligationOutlivesTheWake(t *testing.T) // INV-R1 [Astra R1 5]. cold wake, release(B) unproven (its cgroup stays |
| + // populated): the complete wake() fails and its entry is deleted; a.releaseOps[host] keeps B's pin (the persisted |
| + // generations file names it), the lease is the record's owed lease and is not released; a second ServeHTTP and a resident |
| + // tick are both refused errWakeUnproven with acquires unchanged; RunCmd is refused |
| +func TestReleaseObligationRetriedUntilProven(t *testing.T) // the same, then the group empties: the next finishPendingStops proves the |
| + // rootfs cmd unit (never the binary one), gives the owed lease back, drops the pin from the file on disk, and the next |
| + // request wakes |
| +func TestNoWorkerAfterAFailedRelease(t *testing.T) // only when Group W has landed: a cold wake whose release ends in lease loss, |
| + // refusal or failure, and an overlap whose release fails, start no worker of B and leave gen 1's workers untouched |
| +func TestUnprovenWakeReleaseIsNotABuildFailure(t *testing.T) // INV-R3. planned first wake, release(B) exits 1 and its settle fails: the |
| + // wake fails, B is not recorded failed, no fallback to A runs beside the unproven unit |
| +``` |
| + |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestHoldReleaseFailure|TestAsleepRowRunsRelease|TestFirstWakeReleaseFailure|TestRestartDoesNotRerunRelease|TestReleaseRerunsAfterInterruptedWake|TestRootfsWakeCeiling|TestColdWakeRelease|TestReleaseRefusedWhenOwnershipEnds|TestReleaseObligation|TestUnprovenWakeRelease' -count=1` (under the short `TMPDIR`). Expected: FAIL. |
| +- [ ] **Step 3:** Implement to the table. |
| +- [ ] **Step 4:** Run Step 2's command, the wake-plan families (`-run 'Hold|Planned|FirstWake|Wake|Restore|Seed'`), and Task 1's guards. Expected: PASS. |
| +- [ ] **Step 5: Commit** |
| + |
| +```bash |
| +git add internal/activator |
| +git commit -m "rootfs: release runs inside the wake's lease before web; an unproven release keeps the lease, the pin and the host latched" |
| +``` |
| + |
| +--- |
| + |
| +### Task R gate |
| + |
| +- [ ] **Step 1:** Merge `origin/main` (Group A merged, and Group W if it has), keeping the claims cleanup's deletions on conflict. Gate A's Steps 1 and 2. Expected: clean. |
| +- [ ] **Step 2:** `go test ./internal/activator/ ./internal/rollout/ ./internal/rolloutwords/ ./internal/status/ -count=1` under `nice`, one package at a time. Expected: PASS. |
| +- [ ] **Step 3:** `go test -race ./internal/activator/ -run 'TestStopSettlesARunningRelease|TestReleaseLeaseLossRacesExit|TestReleaseStopsOnLostLease|TestSwapReleaseLeaseLossRacesTheSweep|TestShutdownDrainsReleaseOps' -count=1`. Expected: PASS. |
| +- [ ] **Step 4:** Gate A's Step 5, plus Group R's invariants: `-run 'TestReleaseOpConsumersReadTheRecord|TestUnprovenReleaseOnAnAwakeIncumbentIsRetried|TestShutdownDrainsReleaseOps|TestEveryReleaseResultIsClassified|TestOpenReleaseBlocksEveryTransition|TestSwapAdmittedOnlyOnAProvenPass'`. `RFS-3-C01` to `C07` and `C29` are in the built list: `go test . -run 'TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. The controller pushes; CI runs the full suite. |
| |
| --- |
| |
| ## 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]. |
| +Plan 3 may merge without this group, and this group does not depend on Group R. Until it lands, a build that declares workers serves `web`, and Task D'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. |
| |
| @@ -1332,13 +1489,13 @@ This is the first draft's Task 9, with the worker identity, Task 6's worker half |
| - Create: `internal/activator/rootfsworkers.go`, `internal/activator/rootfsworkers_test.go` |
| - Modify: `internal/activator/backend_rootfs.go` (worker half: `LaunchRootfsWorker`, `RootfsWorkerGone`); `internal/activator/rootfsenv.go` (`rootfsWorkerVars`) |
| - Modify: `internal/activator/prepare.go` (`prepareWorker`, `writeRootfsWorkerLaunch`, the worker forms of `removeLaunch`), `internal/activator/unitproc.go` (`unitProc.worker`, `rootfsUnitFor`, `stopRole` with the worker name, the worker form of `recordName`) |
| -- Modify: `internal/activator/activator.go`: `actEntry` (worker fields), Task 11's `rootfsWorkersHook` in `doWake` after step 6 (`:2638`), `stop` (`:3916`, workers stopped first), Task 8's `superviseRootfsLocked` (supervision) |
| +- Modify: `internal/activator/activator.go`: `actEntry` (worker fields), Task D's `rootfsProcessesHook` 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`). |
| +- Consumes: Task D's `Processes(rt, id)` and Task 12's `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. |
| @@ -1385,9 +1542,12 @@ Rules: |
| - **The launch environment** [pf 1.6, 8.1]: `env == rootfsLaunchEnv(rootfsWorkerVars(rt, g, dbPath, genEnv))`, where `genEnv` is the generation's launch file environment (`launchEnvProc`) before the agent-owned variables, and `g.Control` is the generation's control socket, which a worker keeps (D1). The test compares it with web's launch file, less `CARLOS_SOCKET`. Never `childEnv` (INV-1, INV-5). |
| - **The tier** [pf 1.8]: `memoryMax` is the worker's generation's `g.Tier.MemoryMax`, never `rootfsTier`. |
| - **The stop** [pf 1.3, 1.5]: `RootfsWorkerGone` is `StopRootfs(ctx, host, RoleWorker, 0, name, false)` then `waitUnitCgroupEmpty(ctx, rt, WorkerUnitName(host, name))` (`unitEvents`, the reported group, R-b). `kill` is always false: a worker whose stop cannot be proven stays a stray, with no kill escalation in v1; root has no tested worker kill (`killGen`, `internal/instancectl/rootfs.go:1144`, is a generation's). Any `StopRootfs` error is unproven: `ErrGenUnproven`, a 409 in-flight answer (`rootfs_unitlock.go:162`) or transport. |
| -- **Start after `web` is healthy** (spec §5.4): Task 11's hook in `doWake` after step 6 becomes `startRootfsWorkers` for a rootfs row, on the wake's generation `w.gen`: one `LaunchRootfsWorker` per name, from that generation's staged image and its launch env, off `a.mu`, under the wake's context and after `a.wakeAllowed(host)`. A worker that fails to start is not a wake failure (members before bots, the co-spawn rule); it is installed as exited so the tick restarts it. The declaration is read through `Processes(rt, stagedIdentityOf(w.gen))`, from the build the generation runs, never from the live link. A `Processes` refusal starts no worker and logs once; `web` serves. More than 4 names, or an invalid one, starts no worker and logs once; `web` serves. |
| +- **Start after `web` is healthy** (spec §5.4): Task D's hook in `doWake` after step 6 starts the workers (`startRootfsWorkers`) for a rootfs row, on the wake's generation `w.gen`: one `LaunchRootfsWorker` per name, from that generation's staged image and its launch env, off `a.mu`, under the wake's context, each through `workerWakeGate(e, w.gen, w.rep)` (below). A worker that fails to start is not a wake failure (members before bots, the co-spawn rule); it is installed as exited so the tick restarts it. The declaration is read through `Processes(rt, stagedIdentityOf(w.gen))`, from the build the generation runs, never from the live link. A `Processes` refusal starts no worker and logs once; `web` serves. More than 4 names, or an invalid one, starts no worker and logs once; `web` serves. |
| - **Supervision** in Task 8's `superviseRootfsLocked`, for each awake rootfs entry: a worker whose `proc.Exited()` and that is not `starting` is a crash whatever its exit status (Review Focus 3: a worker's record says it runs). Before a restart its unit is proven gone (`RootfsWorkerGone`); unproven, it moves to `strayRootfsWorkers` and no restart runs beside it. Backoff is the sidecar's (Global Constraints). A worker whose backoff has reached `sidecarRestartMax` is in crash loop: event `RFS-3-C10` once on entry, then `RFS-3-C09` at most once a minute. Every other exit emits `RFS-3-C09`. A start emits `RFS-3-C08`. The restart runs off `a.mu` and re-checks entry identity (`a.entries[host] == e0`) and `e0.state == actAwake` before it installs, the sidecar restart's shape (`activator.go:4873-4920`); a start that lost its entry stops what it started and proves it gone before `startDone` closes. |
| -- **The worker exec gate** [Astra R1 7]: every worker start, the first after the wake and every restart, passes `workerGate(e, w)` immediately before root is asked, riding in on the context (`withExecGate`) as a generation's gate does, and `LaunchRootfsWorker` asks `runExecGate(ctx)` after its preparation and before `StartRootfsWorker`. `workerGate` takes `a.mu` and refuses unless: `a.ownedLocked(e, waking)` holds (`swapadmit.go:88`: the entry is the host's, awake (or, for the wake's own first start, still the waking entry whose lease the wake holds), its replica's lease not lost, no fence, no shutdown); `e.gen.N == w.gen` (the generation the worker belongs to is still the serving one, so a swap that switched meanwhile starts none of the old set); no stray of that worker's name is unproven; and no release record is open for the host. The backend's own rootfs gates run in `LaunchRootfsWorker` before its preparation, as `rootfsGates` does for web. This is `startSidecar`'s shape (`activator.go:2828`), which checks ownership before and after its preparation. A refused start starts nothing and is not a crash; the post-start identity check (below) stays, for a start that raced a stop after the gate. |
| +- **The worker exec gates** [Astra R1 7; Astra R2 N5]: every worker start passes a gate immediately before root is asked, riding in on the context (`withExecGate`) as a generation's gate does, and `LaunchRootfsWorker` asks `runExecGate(ctx)` after its preparation and before `StartRootfsWorker`. There are two gates, because a cold wake's first start and a later start see different state: |
| + - `workerWakeGate(e, g Gen, rep Rep)`, for the first start inside `doWake` after step 6. On main the waking entry has neither its generation nor its replica yet: `wake()` installs `e.gen` (`activator.go:1895`) and `e.rep` (`:1863`) only after `doWake` returns, and `ownedLocked(e, true)` skips the lease check for a waking entry by design (`swapadmit.go:94`). So the gate receives the wake's own generation (`w.gen`) and its replica (`w.rep`, which step 5 made, `activator.go:2621-2622`) and refuses unless, under `a.mu`: `ownedLocked(e, true)` (the entry is the host's, no fence, no shutdown); `e.state == actWaking`; `rep != nil && rep.Err() == nil` (the wake's lease is still held); the worker's `gen` is `g.N`; and no stray of that worker's name is unproven. |
| + - `workerGate(e, w)`, for every later start (a restart, W2's handover): `ownedLocked(e, false)` (`swapadmit.go:88`: awake, its replica's lease held, no fence, no shutdown); `e.gen.N == w.gen` (the generation the worker belongs to is still the serving one, so a swap that switched meanwhile starts none of the old set); no stray of that worker's name is unproven. |
| + - Group R, if it lands, adds "no release record open for the host" to both (its consumer table). The backend's own rootfs gates run in `LaunchRootfsWorker` before its preparation, as `rootfsGates` does for web. This is `startSidecar`'s shape (`activator.go:2828`), which checks ownership before and after its preparation. A refused start starts nothing and is not a crash; the post-start identity check (below) stays, for a start that raced a stop after the gate. |
| - **Pins** [Astra R1 9]: a worker's `build` is set before its start, `entryGenerationsLocked` adds every worker's and every stray's `build`, and the start calls `a.publishBeforeExec()` off `a.mu` before `LaunchRootfsWorker`; a failed write starts nothing (`errStagedBuildNotPublished`) and retries on the next tick. The pin is the worker's own identity, not its generation's member entry, so it survives `dropMember` of the retiring generation (`swap.go:685`), which W2's handover runs after. |
| - **Through the production backend** [Astra R1 4]: `SplitBackend.LaunchRootfsWorker` and `SplitBackend.RootfsWorkerGone` forward to `b.Exec` for an exec-backed row and refuse a unit-backed one; `production_backend_test.go` gains the `RootfsWorkerBackend` row, and the worker tests below run once through `productionBackend`. |
| - **Never takes `web` down:** no worker path calls `beginStopLocked`. |
| @@ -1424,8 +1584,12 @@ func TestRootfsWorkerIdentity(t *testing.T) // prepareWorker reads |
| // StopRootfs with worker "jobs" and kill false; unitNameFor(rt, RoleWorker, 0) is still "" |
| func TestWorkerImagePinnedWhileItRuns(t *testing.T) // the persisted generations file (read from disk) names the worker's build |
| // before root is asked, while it runs, while it is stray after a failed proof, and after its generation is dropped |
| -func TestWorkerGateRefusesAtTheLastMoment(t *testing.T) // [Astra R1 7] during LaunchRootfsWorker's preparation: the lease is lost, a |
| - // fence is raised, or a swap switches to a new generation: each time root is asked nothing and no worker runs |
| +func TestWorkerGateRefusesAtTheLastMoment(t *testing.T) // [Astra R1 7] a restart: during LaunchRootfsWorker's preparation the lease is |
| + // lost, a fence is raised, or a swap switches to a new generation: each time root is asked nothing and no worker runs |
| +func TestColdWakeWorkerGate(t *testing.T) // [Astra R2 N5] through the real wake(): (a) a declared worker starts inside |
| + // doWake after step 6 while the entry is still actWaking, root is asked once with the wake's generation, and after wake() |
| + // installs e.gen the worker is supervised under it; (b) the wake's replica reports lease loss during the worker's |
| + // preparation: root is asked nothing, no worker runs, and the wake's own outcome is today's for a lost lease |
| func TestWorkersThroughTheProductionBackend(t *testing.T) // productionBackend: the workers start and are proven gone through it; a |
| // unit-backed row is refused |
| func TestRootfsWorkersReport(t *testing.T) // the four states |
| @@ -1433,7 +1597,7 @@ func TestRootfsWorkersReport(t *testing.T) // the four states |
| |
| The invariant tables gain the worker rows: INV-1, the worker handle's Stop and Poll (no binary unit, populated reported group: unproven); INV-5, the worker launch file under `t.Setenv("PATH", "/agent/bin")`. |
| |
| -- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWorker|TestCleanExitingWorker|TestTooManyWorkers|TestWorkerProcessesRefusal|TestWorkerImagePinned|TestWorkerGate|TestWorkersThroughTheProductionBackend|TestProductionBackend|TestEveryRootfsProof|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| +- [ ] **Step 2:** Run `go test ./internal/activator/ -run 'TestRootfsWorker|TestCleanExitingWorker|TestTooManyWorkers|TestWorkerProcessesRefusal|TestWorkerImagePinned|TestWorkerGate|TestColdWakeWorkerGate|TestWorkersThroughTheProductionBackend|TestProductionBackend|TestEveryRootfsProof|TestRootfsLaunchFilesCarry' -count=1` under the short `TMPDIR`. Expected: FAIL. |
| - [ ] **Step 3:** Implement; write `RFS-3-C08` to `C10`, add their ids to the built list. |
| - [ ] **Step 4:** Run Step 2's command, `go test -race ./internal/activator/ -run 'TestRootfsWorkerStartRacesStop|TestRootfsWorkersStopFirst' -count=3`, `-run 'Stop|Sidecar|Releasable|Generations|Prepare|UnitProc'`, and Task 1's guards and goldens. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -1449,20 +1613,20 @@ git commit -m "activator: rootfs workers start after web is healthy, restart wit |
| |
| **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]. |
| +This is the first draft's Task 11 step 8 and its `TestOverlapHandsOverWorkersNeverTwoSets` [pf 6.1]. The release-and-worker assertions (no worker after a failed release) are Group R's, added by whichever of R and W lands second. |
| |
| **Files:** |
| -- Modify: `internal/activator/swap.go` (step 8, `:690`: Task 11's `rootfsWorkersHook` becomes the handover), `internal/activator/rootfsworkers.go` |
| +- Modify: `internal/activator/swap.go` (step 8, `:690`: Task D's `rootfsProcessesHook` becomes the handover), `internal/activator/rootfsworkers.go` |
| - Modify: `internal/activator/rootfs_deploy_test.go` |
| |
| **Interfaces:** |
| -- Consumes: W1's `stopRootfsWorkers`, `startRootfsWorkers`, `rootfsWorkersGone`; Task 11's hook. |
| +- Consumes: W1's `stopRootfsWorkers`, `startRootfsWorkers`, `rootfsWorkersGone`, `workerGate`; Task D's hook. |
| - Produces: |
| ```go |
| func (a *Service) handOverRootfsWorkers(e *actEntry) // stop and prove the old set, then start the set of e.gen |
| ``` |
| |
| -Worker handover (spec §5.2): at step 8, beside `replaceSidecar`, `a.handOverRootfsWorkers(e)`. By then the new `web` has passed its health check and is serving. It stops and proves every worker of the retiring generation, then starts the new generation's set. A worker it cannot prove stays stray and the new set waits; the tick starts it once every stray is proven. A config attempt with the same build hands over too, so workers pick up new config. Two worker sets never run at once. A cold wake whose release ends in lease loss, refusal or failure starts no worker. The retiring set's pins are the workers' own (`rootfsWorker.build`, W1), so `dropMember` of the retiring generation (`swap.go:685`) before the handover leaves them listed until each is proven gone [Astra R1 9]. |
| +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 retiring set's pins are the workers' own (`rootfsWorker.build`, W1), so `dropMember` of the retiring generation (`swap.go:685`) before the handover leaves them listed until each is proven gone [Astra R1 9]. |
| |
| - [ ] **Step 1: Write the failing tests:** |
| |
| @@ -1470,9 +1634,6 @@ Worker handover (spec §5.2): at step 8, beside `replaceSidecar`, `a.handOverRoo |
| 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 |
| func TestRetiringWorkersStayPinnedAfterDropMember(t *testing.T) // the persisted generations file names gen 1's build after dropMember, |
| // while a gen-1 worker is stray, and drops it once the stray is proven |
| @@ -1580,11 +1741,11 @@ Every row goes to the deck in Task 1 and reaches code only once approved. `%s` a |
| | 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. |
| +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; C17 to C22 and C26 to C28 Task 12; C23, C24 Task 13; C25 Task 15 (Group A); C03 to C07 and C29 R1; C01, C02 R2 (Group R); C08 to C10 W1 (Group W). |
| |
| ## 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`) 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). |
| +- **Plan 4.** Plan 4 depends on Groups A and W, not on Group R (Paul, 2026-10-26). Its sample Rails app migrates in its web command, as Rails 8's own Docker entrypoint does: `bin/rails db:prepare` runs before Puma starts, and the sample declares no `release` process until Group R lands (a declared one would be logged and not run, D8). Once Group R lands, the sample may move the migration into `release`. 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). |
| - **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. |
| @@ -1595,12 +1756,12 @@ None open. The one this plan raised, `carlos run` on fleet boxes (D4), Paul answ |
| |
| ## 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 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. |
| +- Spec coverage. §5.0 record half: Tasks 2 to 4 (and the mint helper for Plan 4). §5.2 environment: Task 6, W1 and R1; deploy overlap: N1, with R2's release before it; worker handover: W2. §5.2.1: Group R (R2 overlap, R3 hold, hibernating wake and first boot; rollback leaves the schema; distinct from seeds by D5); until it lands, the app's web command migrates (D8). §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, no idle, replication with the activator, Task 5's ops change), R3's wake ceiling, 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 12, R1, 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 (R1); C8: N1's swap tests and R2's (the incumbent is never touched by a release, and never idle-stopped or ceiling-stopped during one). 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. |
| +- Names used across tasks: `ActivatorOwned`, `ActivatorLeased`, `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 Task 12 and R1 and W1's `rootfsWorkerVars`; `healthBoundFor` and `stagedIdentityOf` (N1) in Tasks 7, 12, D, R1 to R3, W1; `rootfsStartRefusal`, `rootfsStartable` and `productionBackend` (Task 7) in Tasks 8, D, R1, W1; Task D's `Processes` and `rootfsProcessesHook` in R1 and W1, W2; Task 12's `startCmdUnit`, `stagedImageOf` and `rootfsCtlHarness` in R1 and W1; Task 8's `superviseRootfsLocked` and `residentFailure` filled by W1 and extended by R1; R1's `releaseOp`, `runRelease`, `classifyRelease`, `leaseWatch`, `ReleaseError` in R2 and R3; R2's `releasePassed` in `swapOverlap`; `rootfsDBPlacer`, `PlaceRootfsDB` (Task 7) in R3's first-boot order; `RootfsWorkers`, `WorkerReport` (W1) in W3; `stopRootfsWorkers`, `rootfsWorkersGone`, `workerGate`, `workerWakeGate`, `handOverRootfsWorkers` in W1 and W2. |
| - Proportion: decisions, signatures and test assertions; bodies only where the order of steps is the decision (`rootfsTick`, `runRelease`). |
| -- **Who owns a running `release`, admission to proof (INV-7, round 2).** One owner: the Service, through one record per host, `a.releaseRuns[host]` (Task 10). One obligation record: it holds the build's full identity (the pin), the cmd unit's hold (the stop and settle), the cancel, the entry that started it while that entry lives, and the lease it must give back if that entry's wake failed. One retry path: `runRelease` settles while it runs; once it returns unproven, only the sweep's `reapReleaseRunsLocked` retries, one attempt at a time (`busy`). Admission creates the record before anything else and publishes the pin before root is asked; the proof is the only thing that removes it. Every consumer reads that record and nothing else: a member's run and another release are refused; the owner is never idle-stopped or max-run recycled; the owner's stop cancels it and `releasable` waits for it; a wake of the host is latched; the failed wake's cleanup hands the lease to it; the generations file lists its build. No entry field (`e.cmd`, `e.cmdLeft`, the first draft's `releaseHold`) says whether a release runs, so deleting an entry cannot drop the obligation, and the run paths (`settleCmds`, `cmdHoldsLocked`, `retryCmdSettlesLocked`) are untouched. |
| -- **Decoupling `release` from the wake and swap lifecycle (flagged, not done).** My view: it would be simpler for the overlap swap and not for the cold wake. In a swap, running `release` as its own owned step before the attempt (the scheduler admits a release for B under the incumbent's replica, waits for its record to be proven and its result, then admits the swap with no release in it) would take the release case out of `swapOverlap`'s step 3a and 3 entirely, and the swap would never have to classify a release error. The cost is a durable "release passed for B" marker, the column D3 rejected, so that a swap admitted later knows not to re-run it, and a second scheduler state. In a cold wake the release needs the wake's own lease and the restored database, and runs between restore and `web`; a separate step would have to acquire the lease, restore, run, then hand the lease to the wake, and that hand-off is the hard part this record already avoids. So the record above is the smaller change for both; if a round 3 finds this family again in the swap path, decoupling the swap side (a release step with its own record, before the attempt) is the change I would make first. |
| +- **Who owns a running `release`, admission to proof (Group R, round 3).** One owner: the Service, through one operation record per host, `a.releaseOps[host]` (R1). One obligation record: it holds the build's full identity (the pin), the cmd unit's hold (the stop and settle), the cancel, the entry it runs beside while that entry lives, the lease it must give back if a wake's entry went, and its state (running, or finished with proof outstanding). One retry path: `runRelease` settles while it runs; once it returns unproven, only `reapReleaseOpsLocked` retries, in `finishPendingStops`, the pass the sweep and Shutdown share, whatever the owner's state, and Shutdown counts the records in its drain and names any left at exit. Admission refuses while a record exists, before any decision about whether a release is due, and publishes the pin before root is asked; the proof is the only thing that removes the record. Every consumer reads that record and nothing else (R1's table: runs, other releases, every swap admission, the plan-disabled stop, idle, the instance awake ceiling, the owner's stop and `releasable`, wakes, the failed wake's lease, pins, worker starts). Every result has one classification (R1's table), and only a `*ReleaseError` with its unit proven gone is the build's failure. |
| +- **Release is decoupled from the overlap swap (Paul, 2026-10-26; Astra round-2 review).** The round-2 view was that decoupling would be simpler for the swap and not for the cold wake, at the cost of a durable "release passed" marker. Astra's review showed the marker is unnecessary: an attempt-scoped, in-memory pass handed straight to the swap, with attempt, target and ownership rechecked, is enough, and an agent restart reruns the release, which D3 already allows. Paul chose that design and moved `release` out of Group A into its own Group R, built after A: R2 runs the release as its own operation before the swap is admitted, and `swapOverlap` contains no release step; R3 keeps the cold-wake, planned-wake and hold release inside the wake's restored-data and lease lifetime, where the hand-off cost is real. Group A contains, calls, waits on and tests no release machinery (gate A Step 6 greps for it). |
| - **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. |
| @@ -1608,4 +1769,5 @@ None open. The one this plan raised, `carlos run` on fleet boxes (D4), Paul answ |
| - Refusal before the lease (Task 7, INV-3) through the backend's own gates, with a request budget; the claim reason, `errRootfsClaim`, RFS-3-C13 (struck in the deck and the gate's struck list) and its test removed; the census line and run removed, replaced by Task 15's no-`registry.Open` test and gate A's `instancectl` diff check; dead claim references (`claimAwareLegacy`, `ErrCmdClaim`, the #250 post and hand-off) struck. |
| - Task 2: `Upsert` keeps a rootfs row's hibernation unless re-tenanted, the replication arm keys on the effective runtime, `carlos add` refuses an existing rootfs host, `ErrRuntimeFixed` crosses the remote registry. Task 5: `BuildStateKept`, `socket_advice.go:121` and `restartscope.go:496` added, `movesphase1.go` dropped. Task 7: `RenameBetweenNoReplace`. Task 10: `Processes` checks the image's digest, root's refusals are refusals, launch env `rootfsLaunchEnv`, the sized tier. Task 12: the same, plus `runCopySuperseded` for RUN-C47. Task 13: the provision transitions are the control, a test enumerates the `seedMoveRefusal` sites, the Phase 1 citations dropped. Every agent-side egress slot struck (#328 checks on root's side). |
| - **Round 2 (Astra plan review R1 of b3a40781, 7 P1 and 4 P2; map in amend-report.md "Round 2"):** Task 5 widens only (`ActivatorLeased` keeps hibernating binary sidecars where today's no-kind sites have them); N1's staged arm launches without a health wait and every rootfs `Gen` carries its full identity (`stagedIdentityOf`), with the manifest read's (nil, nil) and `BoxArtifact` cases refused; every new interface goes through `SplitBackend` with a production-composition test; one `releaseRun` record owns a release from admission to proof (INV-7), outliving a failed wake with its lease, pin and latch, read by every consumer; a final worker exec gate (`workerGate`) and `LaunchRootfsWorker` (the pre-flight's `StartWorker` collides with the binary worker start); gates, `BuildIdentity` and pins off `a.mu` and published before exec; the rollback floor is a release floor (`RootfsLifecycleFloor`), not the unit set; INV tests cover the shared dispatch files, the agent-held obligations, a real health response between the bounds and resident accounting (`residentFailure`). |
| + - **Round 3 (Astra plan review R2 of bbac6804: 8 of 11 fixed, N1 to N6 new; Paul's decision of 2026-10-26; map in amend-report.md "Round 3"):** `release` leaves Group A for its own Group R (R1 the operation, R2 before an overlap swap, R3 inside a wake, R gate), with INV-R1 to INV-R5. N1: retries keyed on the operation's state, not the entry's. N2: the reaper in `finishPendingStops` and the records in Shutdown's drain and exit report. N3: the instance awake ceiling and the plan-disabled stop in the consumer table. N4: the open-release check at every swap admission and wake, before the due decision. N6: one classification for every release result. N5 (Group W): `workerWakeGate` takes the wake's generation and replica. New Task D in Group A holds the declared-processes read both later groups share and logs what the box does not run yet; Task 12 holds the shared `startCmdUnit`, `stagedImageOf` and the control harness. Plan 4 depends on A and W, not R: its sample migrates with `db:prepare` before Puma. |
| - 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. |