| index cf84e67a6..ddde9b02d 100644 |
| --- a/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md |
| +++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md |
| @@ -53,7 +53,7 @@ The preflight of 2026-10-30 (`.superpowers/sdd/2026-10-24-rootfs-apps-6-interact |
| |
| **Call A1: root kills a rootfs one-shot unit at lease loss.** This goes beyond the letter of PF-3, so the review should check it. PF-3 has cmd and tty holds stopped and proven at lease loss beside the workers, in the shape Plan 3 accepted for workers (no kill: root refuses one for a worker). For runs and sessions that shape alone does not close Task 12 R1 P1 #1, the failure this amendment was asked to fix. A stop is SIGTERM, then SIGKILL after `TimeoutStopSec=20` (`internal/host/units/carlos-instance-rootfs-cmd@.service:36`). After the loss, another box may acquire the lease once the safety margin has passed. Root's `/stop` refuses `kill=1` for anything but a generation (see preflight §1 row 6; the rule is in `parseRequest`, `internal/instancectl/server.go`), and Astra's fix for P1 #1 named that root-side change. So Task 7a makes it: |
| - root accepts `kill=1` on a rootfs stop of a one-shot role (`instancectl.OneShot`: cmd, and tty once Task 5 names it), and kills with the generations' `killGen` (`internal/instancectl/gen.go:459`); |
| -- the agent kills cmd holds (Task 7a) and tty holds (Task 9) at the loss, beside `killResidentGens` and `stopRootfsWorkersAtLoss`; |
| +- the agent kills cmd holds (Task 7a) and tty holds (Task 9) at the loss, beside `killResidentGens` and `stopRootfsWorkersAtLoss`, on every rootfs row, hibernating or resident (rev 2: the lease watch is installed for every rootfs entry, and the tick's fallback reaches a hibernating entry's one-shots; a rootfs one-shot whose entry is not under the watch is refused before it starts); |
| - at `residentLeaseShort` the agent stops them gracefully (30 s before the safety deadline, `residentDrainBudget`; a 20 s stop fits); |
| - a start in flight at the loss is killed at once and again when its start returns; |
| - a rootfs one-shot starts only while the lease is safe for at least `oneShotStartLead()` more, the worker rule (`workerStartLead`, `internal/activator/rootfsworkers.go:122-150`). |
| @@ -67,10 +67,34 @@ Workers keep Plan 3's shape. Cost if wrong: one more root verb under the census |
| **Cross-plan changes.** |
| - The index's Plan 3 row still lists "`carlos run` for rootfs (off fleet boxes) and `--version`". Rootfs runs are now Plan 6 Task 7a, and `--version` is deferred (#431). The index line changes when this plan merges. |
| - `plan3_groups_test.go`: Task 7a moves RFS-3-C27 from `plan3CopyRuns` to `plan3CopyA`, the group `carlos run` belonged to before the cut. Task 16 takes RFS-3-C28 out of `plan3CopyRuns` when it strikes the row. |
| -- The zero-downtime deck's record `zdd.apps-set.nothing` (`docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json:53`) holds today's `appsSetNothing`. Task 4 changes it to RFS-6-C47's approved text in the same commit, or `TestZeroDowntimeCopyIsApplied` goes red. |
| +- Two other checked records hold today's `appsSetNothing`: `zdd.apps-set.nothing` (`docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json:53`, `TestZeroDowntimeCopyIsApplied`) and `IP1-57` (`docs/superpowers/plans/2026-10-21-instance-policy-copy.json:82`, `TestInstancePolicyCopyIsApplied`). Task 4 changes both to RFS-6-C47's approved text in the same commit as the code (rev 2, Astra R1 P1-4). |
| |
| String IDs added or changed: RFS-6-C47 (revised, pending) and RFS-6-C65 (new, pending). Task 7a builds RFS-3-C27 (approved). Task 16 strikes RFS-3-C28 (PF-13). |
| |
| +### Amendment rev 2: review dispositions (Astra R1 of the amendment) |
| + |
| +Findings from `docs/superpowers/reviews/CODEX-FINDINGS-rootfs-plan6-amendment-R1.md`, each checked against the code at c24e7a04 first. All seven are accepted. Where a case could be refused up front instead of tolerated, it is refused (AGENTS.md stopping rules). |
| + |
| +- **P1-1, hibernating rootfs commands never reach the lease kill: accepted.** Checked: `installProcLocked` (`internal/activator/activator.go`) installs the lease watch only for `Resident()`, which excludes hibernating rootfs rows (`internal/registry/runtime.go`), and `rootfsTick`'s fallback (`rootfs_service.go`) also asks `Resident()`. Fix, in Task 7a: |
| + - the watch is installed for every rootfs entry. Its resident-only actions stay resident-only; its one-shot stop and kill apply to every rootfs entry, awake or stopping, with a start in flight killed again when it returns; |
| + - the tick's fallback reaches a hibernating entry's one-shots; |
| + - both callers of the changed `residentLeaseLostLocked` run the returned funcs off `a.mu`; |
| + - a rootfs one-shot whose entry is not under the watch is refused before it starts. |
| + |
| + Task 9 covers the tty role on the same paths. Witnesses: `TestHibernatingRootfsLeaseLossKillsItsRun`, `TestHibernatingRootfsTickFallbackKillsItsRun`, `TestRootfsRunRefusedWhenUnwatched` (Task 7a) and `TestHibernatingRootfsLeaseLossKillsItsSession` (Task 9). |
| +- **P1-2, no interface carries the declared-process selector: accepted.** Checked: `TTYSpec` had only the terminal fields, `CmdSpec` (`internal/activator/cmdunit.go`) has no process field, and root gives a declared process its own env and working directory but an argv web's (`internal/instancectl/rootfs.go`, `resolveRootfsLaunch`). Fix: `CmdSpec.Process`, carried end to end (Task 8's six-hop list). The CLI's `Open.Process` is kept by the console (Task 10, which no longer rewrites `Open` to the resolved argv), forwarded by the splice (Task 11) and set by the box (Task 12). The backend picks `rootfsCmdLaunch{Process}` or `{Argv}`, exactly one. Tests: `TestRootfsTTYKeepsTheDeclaredProcess` (Task 8), `TestRootfsTTYDeclaredProcessKeepsItsEnvAndDir` (Task 6), `TestInteractiveWorkerPassesTheProcessThrough` (Task 12), and the extended `TestConsoleProcessResolvesFromTheManifest` and `TestSpliceCarriesBothWays`. |
| +- **P1-3, renaming the cleanup owner breaks the pinned removal guards: accepted.** Checked: `rootfsRemovalOwners` names `cleanCmdExe` (`internal/instancectl/rootfs_removal_guard_test.go`), `removalAllowPins` pins it, and its ceiling refuses any new entry (`internal/activator/rootfs_invariants_test.go`). Fix (Task 6): no owner is renamed or added. `cleanCmdExe`, `removeCmdExe` and instancectl's `startRootfsCmd` keep their names and gain a role parameter. The guard lists stay byte for byte. Task 6 runs all four guards: `TestRootfsFilesAreRemovedOnlyBehindTheProof`, `TestRootfsRemovalGuardFixtures`, `TestRootfsRemovalOwnersUnchanged` and `TestRootfsInvariantTablesOnlyGrow`. In the same family, Task 7a's rootfs run arm and `KillOneShot` move into `backend_rootfs.go`, so the INV-1 verb guard reads them. `oneShotKiller` joins `rootfsSeamInterfaces`, and Task 8 adds the binary tty verbs to `rootfsBinaryVerbs`. Both are detector lists that may only grow. |
| +- **P1-4, C47's third checked consumer: accepted.** Checked: `IP1-57` in `docs/superpowers/plans/2026-10-21-instance-policy-copy.json:82` holds today's text, and `TestInstancePolicyCopyIsApplied` (`approved_instance_policy_copy_test.go:42`) checks it. Fix (Task 4): all three checked records change in one commit (RFS-6-C47, `zdd.apps-set.nothing`, `IP1-57`), and the task runs all three gates. A `git grep` before the edit confirms there is no fourth. |
| +- **P1-5, a pickup retry after draining cannot fit the window: accepted, refused up front.** Checked: `lifetimeSettle` = 60 s (`internal/console/lifetimes_cutover.go:44`) runs from the drain's start or the last legacy unit, `runs.PickupWindow` = 60 s, and runs past their deadline are never picked (`internal/host/runs.go`, `consider`). So a fleet run queued when a drain starts can never be picked in time. Fix (Task 16): the relay answers not-picked with `Why: "cutover"`, the box never redials it, and the run expires as an unpicked run does (the CLI at its deadline, the sweep after activation). It needs no new copy. A run picked before the drain finishes normally; its finish CAS lands after activation. Test: `TestQueuedFleetRunAtACutoverExpires`, with the gate and run clocks advancing together. |
| +- **P2-6, the request budget left out reads: accepted.** Task 10's budget now counts: |
| + - the setting reads, 1 on the console and 1 on the box; |
| + - the judge's slot GET on every judged record read; |
| + - logical transitions apart from CAS retries; |
| + - the one extra clear attempt, and when it happens. |
| +- **P2-7, the deck's totals were wrong: accepted.** Recounted from the rows: 401 rows, 397 live (2 of them pending), 4 struck. Plan 1 has 99 rows and Plan 4 146, 2 of them struck. |
| + |
| +String IDs added or changed in rev 2: none. |
| + |
| --- |
| |
| ## Contract deviations |
| @@ -421,13 +445,19 @@ git commit -m "provision: the interactive session marker and reconcile's hook (r |
| - Create: `internal/console/apiinteractivesetting.go`; Modify: `internal/console/authcli.go` (register beside `/swap`; see preflight §1 row 4) |
| - Modify: `apps_swap.go` (usage, strings, flag, request), `apps_updates.go` (`appsSetRun`; see preflight §1 row 4) |
| - Modify: `internal/console/svcroutes_test.go` (`policyDoors`, `closedDoors`); `internal/console/testdata/claim-routes.txt`; `internal/console/claim_invariant_fixtures_test.go` (a door fixture beside the swap fixture; see preflight §1 row 4) |
| -- Modify: `docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json` (the `zdd.apps-set.nothing` record takes RFS-6-C47's approved text) |
| +- Modify: `docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json` (the `zdd.apps-set.nothing` record takes RFS-6-C47's approved text) and `docs/superpowers/plans/2026-10-21-instance-policy-copy.json` (the `IP1-57` record, `:82`, takes it too; rev 2, Astra R1 P1-4) |
| - Test: `internal/appconfig/interactive_test.go`, `internal/console/apiinteractivesetting_test.go`, `apps_swap_test.go`, `apps_updates_test.go` |
| |
| **Amended 2026-10-30 (PF-10, PF-21, PF-24, PF-12).** |
| - Do not start this task until RFS-6-C47 is `approved`. C47 is revised to keep `--egress-allow` and `--size`, which `apps set` gained with instance policy (#328/#329); the string table below has the draft. |
| - `appsSetRun` is now `appsSetRun(ctx, sess, acct, app, swap *swapPolicyReq, policy updatePolicyReq, change *policyChange)` (`apps_updates.go`). Append `interactive *bool` after `change`, and extend its nothing-given check: `swap == nil && policy == nil && change == nil && interactive == nil`. `runAppsSet`'s own check (`apps_swap.go`, before `resolveMode`) gets the same clause. |
| -- Count `appsSetNothing` at the base commit before the edit (the copy-review scope trap). At c24e7a04 there is one definition (`apps_swap.go:41`) and three uses (`apps_swap.go:100`, `:169`, `apps_updates.go:94`). Two tests compare by the name (`apps_swap_test.go:54`, `apps_updates_test.go:247`), and one record holds the text: `zdd.apps-set.nothing` in the zero-downtime deck, checked by `TestZeroDowntimeCopyIsApplied`. Change the definition and the record in one commit. The tests follow by name. |
| +- Count `appsSetNothing` at the base commit before the edit (the copy-review scope trap). At c24e7a04 there is one definition (`apps_swap.go:41`) and three uses (`apps_swap.go:100`, `:169`, `apps_updates.go:94`). Two tests compare by the name (`apps_swap_test.go:54`, `apps_updates_test.go:247`), so they follow by name. |
| +- **Every checked consumer of the text (rev 2, Astra R1 P1-4).** Three records are checked as applied to `apps_swap.go`, and all three change in Task 4's one commit, to RFS-6-C47's approved text, byte for byte: |
| + 1. `RFS-6-C47` in `docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md`, which joins `rootfsCopyBuilt` and is then checked by `TestRootfsBuiltCopyIsApplied`; |
| + 2. `zdd.apps-set.nothing` in `docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json:53`, checked by `TestZeroDowntimeCopyIsApplied` (`approved_copy_zdd_test.go`); |
| + 3. `IP1-57` in `docs/superpowers/plans/2026-10-21-instance-policy-copy.json:82`, checked by `TestInstancePolicyCopyIsApplied` (`approved_instance_policy_copy_test.go:42`). |
| + |
| + Check for a fourth before the edit, with `git grep -n 'nothing to set. Pass --swap' -- '*.json' '*.md' '*.go'`. At c24e7a04 the only other hits are notes and Luna briefs (`docs/superpowers/notes/copy-instance-policy-plan1.md`, `docs/superpowers/specs/LUNA-COPY-*-INSTANCE-POLICY.md`), which no test reads. They are history and are left as they are. |
| - `policyDoors` already holds `/{app}/policy`. Add `/{app}/interactive` beside it. |
| - The claim fixture uses the harness's `bab` path, as Step 4 writes it (PF-24). The behavioural tests in Step 1 use accounts `bah` and `baj` and the app `shop`. |
| - Rewrite the deck's file cells of RFS-6-C38 to C47 to the paths written (PF-12). |
| @@ -480,12 +510,12 @@ Expected: FAIL. |
| - Add `route PUT /api/cli/apps/{account}/{app}/interactive` to `claim-routes.txt`. |
| - Add a door fixture: `claimAPI(http.MethodPut, "/api/cli/apps/bab/shop/interactive", `{"interactive":true}`)`, the swap fixture's shape. |
| |
| -Run: the Step 2 commands, then `go test ./internal/console/ -run 'TestEveryCLIDoorNamesItsRoles|TestClaimConsoleRouteCensus|TestClaimConsoleMutationInvariant' -count=1` and `go test . -run 'TestAppsSet|TestZeroDowntimeCopyIsApplied|TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. |
| +Run: the Step 2 commands, then `go test ./internal/console/ -run 'TestEveryCLIDoorNamesItsRoles|TestClaimConsoleRouteCensus|TestClaimConsoleMutationInvariant' -count=1` and `GOFLAGS=-buildvcs=false go test . -run 'TestAppsSet|TestZeroDowntimeCopyIsApplied|TestInstancePolicyCopyIsApplied|TestRootfsCopy|TestRootfsBuilt' -count=1`. Expected: PASS. |
| |
| - [ ] **Step 5: Commit** (add RFS-6-C38 to C47 to the built list) |
| |
| ```bash |
| -git add internal/appconfig internal/console apps_swap.go apps_swap_test.go apps_updates.go apps_updates_test.go approved_rootfs_copy_test.go docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json |
| +git add internal/appconfig internal/console apps_swap.go apps_swap_test.go apps_updates.go apps_updates_test.go approved_rootfs_copy_test.go docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md docs/superpowers/plans/2026-10-07-zero-downtime-deploys-6-copy.json docs/superpowers/plans/2026-10-21-instance-policy-copy.json |
| git commit -m "interactive: the per-app setting and carlos apps set --interactive (rootfs plan 6)" |
| ``` |
| |
| @@ -589,9 +619,15 @@ git commit -m "units: the tty templates; /dev/pts hidden in every instance names |
| - **Role-aware throughout (PF-7).** |
| - `handleCmdStatus`, which refuses every role but cmd today, takes the role from its route. |
| - `cmdLocks` is keyed by (role, host), so a session's start never waits behind a run's lock on the same host. |
| - - The rootfs branch's `startRootfsCmd` takes the role (unit, preflight role, exe dir), and its JIT drop-in, reload and effective-property check stay shared (R11). |
| - - `rootfsUnitOf` and `stopRootfs` learn `RoleTTY`. `stopRootfs`'s cmd-only cleanup becomes `OneShot(role)` (`cleanOneShotExe(ctx, role, host, true)`). |
| + - The rootfs branch's `startRootfsCmd` takes the role (unit, preflight role, exe dir), and its JIT drop-in, reload and effective-property check stay shared (R11). It keeps its name. |
| + - `rootfsUnitOf` and `stopRootfs` learn `RoleTTY`. `stopRootfs`'s cmd-only cleanup becomes `OneShot(role)`. |
| + - **The cleanup keeps its owner's name (rev 2, Astra R1 P1-3).** Root's file removals are pinned by function name, so no owner is renamed or added. `cleanCmdExe` keeps its name and gains the role: `func (s *Server) cleanCmdExe(ctx context.Context, role Role, host string, rootfs bool) error`. It serves both one-shot roles: the role's unit, its lock (keyed by role and host), the role's rootfs files behind `removeRootfsUnitFiles`, and the role's binary sources through `removeCmdExe(role, iid)`. `removeCmdExe` and the instancectl `startRootfsCmd` keep their names too. Every caller passes `RoleCmd` or `RoleTTY`; no forwarding wrapper is added. The pinned lists stay byte for byte as they are: |
| + - `rootfsRemovalOwners` (with `cleanCmdExe`, `startRootfsCmd`, `stopRootfs`) and `rawRemovalOwners` (with `removeCmdExe`) in `internal/instancectl/rootfs_removal_guard_test.go`; |
| + - `removalAllowPins` and its ceiling in `internal/activator/rootfs_invariants_test.go`, which may never gain an entry. |
| + |
| + Task 6's checks run all four guards: `TestRootfsFilesAreRemovedOnlyBehindTheProof` and `TestRootfsRemovalGuardFixtures` (instancectl), `TestRootfsRemovalOwnersUnchanged` and `TestRootfsInvariantTablesOnlyGrow` (activator). |
| - `resolveRootfsLaunch` gives `RoleTTY` the `RoleCmd` rule (a declared process other than `web`, or an argv), in place of today's "role tty has no rootfs unit". |
| + - Test `TestRootfsTTYDeclaredProcessKeepsItsEnvAndDir` (rev 2, P1-2): a staged manifest whose `console` process and `web` have different `env` and `working_dir`, and the same command. `POST /tty` with `process=console` writes a root launch with the console's env and working directory. The argv body with that same command gets web's. |
| - Tests: `TestTTYAndCmdLocksAreSeparate` (a cmd start held mid-flight does not block `POST /tty` for the same host; two `POST /tty` for one host serialize); `TestRootfsTTYStopNamesTheTTYUnit` (`POST /stop?role=tty&runtime=rootfs` stops `carlos-instance-rootfs-tty@…`, removes `rootfs/tty/`, and leaves `rootfs/cmd/` alone). |
| - **Role sets (PF-27).** `/stop` and `/reset` take `RoleTTY` beside `RoleWorker`. Worker rules are not touched. |
| - **Census (PF-14).** The control service is root code. Re-pin through the 2026-10-26 recipe on the branch's one overlay (Global Constraints). Astra approves on #280. Do not wait for Paul. |
| @@ -636,7 +672,7 @@ Replace every `== RoleCmd` that means "a one-shot" with `OneShot(role)`. |
| |
| - [ ] **Step 4: Run the package's tests and the root-read census** |
| |
| -Run: `go test ./internal/instancectl/ -run 'TTY|Cmd|Sweep|Stop|Reset|Names' -count=1`, then `go test ./internal/provision/ -run TestPlan14RootReadCensus -count=1`. Expected: PASS. The control service is root code, so if the census moves, re-pin it with the overlay recipe (amended 2026-10-30, PF-14: `make census-card`, CLAIMS, `make census-propose`; Astra approves on #280; Paul is not asked). |
| +Run: `go test ./internal/instancectl/ -run 'TTY|Cmd|Sweep|Stop|Reset|Names|TestRootfsFilesAreRemovedOnlyBehindTheProof|TestRootfsRemovalGuardFixtures' -count=1`, `TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestRootfsRemovalOwnersUnchanged|TestRootfsInvariantTablesOnlyGrow' -count=1`, then `go test ./internal/provision/ -run TestPlan14RootReadCensus -count=1`. Expected: PASS. The control service is root code, so if the census moves, re-pin it with the overlay recipe (amended 2026-10-30, PF-14: `make census-card`, CLAIMS, `make census-propose`; Astra approves on #280; Paul is not asked). |
| |
| - [ ] **Step 5: Commit** |
| |
| @@ -719,8 +755,8 @@ This task depends on Task 5 (`instancectl.OneShot`) and Task 6 (`stopRootfs` and |
| - Modify: `internal/activator/cmdunit.go` (`StartCmd` takes the rootfs arm before every binary step; `CmdSpec.AfterSettled`; see preflight §1 row 8) |
| - Modify: `internal/activator/backend_rootfs.go` (`startRootfsCmd` takes a `rootfsCmdLaunch`; `StartRelease` passes its process; see preflight §1 row 8) |
| - Modify: `internal/activator/cmd.go` (`RunCmd`: the lease headroom for a rootfs row and `AfterSettled` on every path; `cmdHold` gains `afterSettled`; `stopOneShotsAtLeaseLocked`; see preflight §1 row 9) |
| -- Modify: `internal/activator/rootfs_service.go` (`residentLeaseShort`, `residentLeaseLost`; see preflight §1 row 9) |
| -- Modify: `internal/activator/unitproc.go` (`KillOneShot` beside `stopRole`), `internal/activator/backend_unit.go` (`SplitBackend.KillOneShot`) |
| +- Modify: `internal/activator/rootfs_service.go` (`residentLeaseShort`, `residentLeaseLost`, `residentLeaseLostLocked`, `rootfsTick`'s fallback; see preflight §1 row 9), `internal/activator/activator.go` (`installProcLocked` watches every rootfs entry, rev 2) |
| +- Modify: `internal/activator/backend_rootfs.go` (`startRootfsRun`, `KillOneShot`; rev 2: here, not `unitproc.go`, so the INV-1 guard reads them), `internal/activator/backend_unit.go` (`SplitBackend.KillOneShot`), `internal/activator/rootfs_invariants_test.go` (`rootfsSeamInterfaces` gains `oneShotKiller`) |
| - Modify: `internal/instancectl/server.go` (`parseRequest`'s kill rule), `internal/instancectl/rootfs.go` (`stopRootfs` with `kill` for a one-shot role), `internal/instancectl/client.go` (`StopRootfs` types an unproven one-shot kill as `ErrGenUnproven`) |
| - Modify: `internal/console/apiruns.go` (`runClassRefusal`'s always-on arm; see preflight §1 row 10) |
| - Modify: `internal/host/runexec.go` (`execute` hands the run directory to `AfterSettled`; `cleanUp`; see preflight §1 row 16) |
| @@ -729,7 +765,7 @@ This task depends on Task 5 (`instancectl.OneShot`) and Task 6 (`stopRootfs` and |
| - Test: `internal/activator/rootfs_invariants_test.go` (INV-1, INV-4 and INV-5 run rows), `internal/activator/rootfs_test.go` (`TestRootfsRowsNeverTakeABinaryLaunch`'s cmd row), `internal/activator/cmd_test.go`, `internal/instancectl/rootfs_test.go`, `internal/host/runexec_linux_test.go` |
| |
| **Interfaces:** |
| -- Consumes (Plan 3, on main): `startRootfsCmd` and `stagedImageOf` (`internal/activator/backend_rootfs.go`), `rootfsCmdVars` (`rootfsenv.go:20`), `rootfsLaunchEnv`, `rootfsGates`, `refuseRootfs` and `errRootfsRefused` (`rootfs.go`), `errPartialStagedIdentity` (`identity.go:99`), `rootfsCtlHarness` (`rootfs_ctl_harness_test.go:70`), `watchOf` (`rootfsrelease.go:50`), `workerProofBound`, `workerHeadroom`'s shape (`rootfsworkers.go:115-150`), `residentDrainBudget`, `killResidentGens`, `stopRootfsWorkersAtLoss`, `genKiller` (`opset.go:168`); `killGen` (`internal/instancectl/gen.go:459`). From Task 5: `instancectl.OneShot`. From Task 6: the role-aware `stopRootfs` and `cleanOneShotExe`. |
| +- Consumes (Plan 3, on main): `startRootfsCmd` and `stagedImageOf` (`internal/activator/backend_rootfs.go`), `rootfsCmdVars` (`rootfsenv.go:20`), `rootfsLaunchEnv`, `rootfsGates`, `refuseRootfs` and `errRootfsRefused` (`rootfs.go`), `errPartialStagedIdentity` (`identity.go:99`), `rootfsCtlHarness` (`rootfs_ctl_harness_test.go:70`), `watchOf` (`rootfsrelease.go:50`), `workerProofBound`, `workerHeadroom`'s shape (`rootfsworkers.go:115-150`), `residentDrainBudget`, `killResidentGens`, `stopRootfsWorkersAtLoss`, `genKiller` (`opset.go:168`); `killGen` (`internal/instancectl/gen.go:459`). From Task 5: `instancectl.OneShot`. From Task 6: the role-aware `stopRootfs` and `cleanCmdExe` (its name kept, rev 2). |
| - Produces: |
| ```go |
| // internal/activator |
| @@ -761,9 +797,12 @@ func oneShotStartLead() time.Duration // instancectl.DeadlineControl + workerPro |
| var errOneShotNoHeadroom = errors.New("activator: the instance's lease is too close to its safety deadline to start a command") |
| func (a *Service) oneShotHeadroom(rep Rep) error // workerHeadroom with oneShotStartLead; nil without a lease signal |
| func (a *Service) stopOneShotsAtLeaseLocked(e *actEntry, rt registry.Route, kill bool) []func() |
| +func oneShotHoldsLocked(e *actEntry) bool // len(cmdHoldsLocked(e)) > 0 here; Task 9: either role |
| +func (a *Service) residentLeaseLostLocked(e *actEntry, err error) (gens []uint64, oneShots []func()) // rev 2: gens nil for a hibernating entry |
| +func (b *ExecBackend) startRootfsRun(ctx context.Context, rt registry.Route, spec CmdSpec) (CmdUnit, error) // backend_rootfs.go (rev 2) |
| // one func per hold of e that may be running (cmdHoldsLocked here; Task 9 widens it to both roles), run off a.mu: |
| // kill false (residentLeaseShort): h.stop(ctx, StopLeaseLost) bounded by cmdStopBound; |
| -// kill true (residentLeaseLostLocked): KillOneShot(rt, role) at once, again once h.started closes with a unit, |
| +// kill true (residentLeaseLostLocked, and the tick's fallback): KillOneShot(rt, role) at once, again once h.started closes with a unit, |
| // then h.stop(ctx, StopLeaseLost) to settle streams and record the reason. A failed kill or settle is logged; |
| // the entry's stop path still keeps the lease's release until the hold is proven (settleCmds). |
| |
| @@ -780,7 +819,7 @@ func (a *Service) stopOneShotsAtLeaseLocked(e *actEntry, rt registry.Route, kill |
| ``` |
| |
| Rules: |
| -- **`StartCmd` on a rootfs row.** The layout check (`ErrCmdNotNested`) and `checkCmdRunDir` stay first and shared. A rootfs row then leaves the binary path before `nestedGate`: |
| +- **`StartCmd` on a rootfs row.** The layout check (`ErrCmdNotNested`) and `checkCmdRunDir` stay first and shared. A rootfs row then leaves the binary path before `nestedGate`, into `func (b *ExecBackend) startRootfsRun(ctx context.Context, rt registry.Route, spec CmdSpec) (CmdUnit, error)`. That function lives in `backend_rootfs.go`, as does `KillOneShot`, so the INV-1 verb guard (`TestRootfsFilesNameNoBinaryVerb`, which reads `rootfs*.go` and `backend_rootfs.go` whole) reads every rootfs arm of this task (rev 2). `StartCmd` in `cmdunit.go` only dispatches to it. `oneShotKiller` joins `rootfsSeamInterfaces`, a detector list that may only grow, so the guard also reads `SplitBackend.KillOneShot`. |
| - `spec.serving` is required. `RunCmd` sets it from the serving generation, whose rootfs `Gen` carries `Build`, `StagedPath` and `Digest`. Without one, the run is refused with `refuseRootfs(errNoCmdExe)`, and a partial one with `refuseRootfs(errPartialStagedIdentity)`. Nothing is laid out. |
| - `spec.genEnv` is required (`errNoGenEnv`), and `replicaKeyGate` is asked as for a binary run. |
| - Then `startRootfsCmd(ctx, rt, id, rootfsCmdLaunch{Argv: spec.Args}, b.rootfsCmdVars(rt, spec.genEnv, b.pathsFor(rt).dbPath, spec.RunID, spec.RunDir), spec.Stdout, spec.Stderr)`, where `id` is `spec.serving` as a `release.StagedIdentity`. The argv is `spec.Args` exactly as given, with no live-link prefix. The image's PATH finds its first word. |
| @@ -791,9 +830,13 @@ Rules: |
| - Right after its last check under `a.mu` (the one after `recordBuild`), and before `StartCmd`, a rootfs row's run asks `oneShotHeadroom(e.rep)` off `a.mu`. Less than `oneShotStartLead()` left refuses with `&CmdStoppedError{Reason: StopLeaseLost}` through `abandon`, and nothing starts. |
| - The `releaseOps` refusal stays: a run and a release share the cmd unit. |
| - `AfterSettled` is honoured on every path, as its comment says. Its once-guard lives on the hold. A refusal before the hold exists (`ErrCmdClaim`, `ErrCmdNotInstance`, `ErrCmdNotNested`, `*CmdWakeError`, `ErrCmdBusy`, the first `*CmdStoppedError`) calls it before returning. |
| -- **Lease** (Call A1). |
| - - `residentLeaseShort` calls `stopOneShotsAtLeaseLocked(e, e.route, false)` for an entry that is the host's, awake or already stopping, and runs the funcs off `a.mu`. Today it returns early for an entry that is not awake. That early return now skips only `beginStopLocked`. |
| - - `residentLeaseLostLocked(e, err) ([]uint64, []func())` returns the kill funcs beside the generation numbers, whatever the entry's state. `residentLeaseLost` runs them in the same `WaitGroup` as `stopRootfsWorkersAtLoss`, beside `killResidentGens`. |
| +- **Lease** (Call A1; rev 2, Astra R1 P1-1: every rootfs row, hibernating or resident). |
| + - **The watch covers every rootfs entry.** Today `installProcLocked` installs the lease watch only for `e.route.Resident()`, so a hibernating rootfs row's run or session would never reach the kill. It now installs it for `e.route.Rootfs()`. The watch's existing actions stay resident-only: `beginStopLocked` at short and at loss, the generation kills and the worker stops. A hibernating row's web keeps today's path (the sweep's `rep.Err` stop). The one-shot actions below apply to every rootfs entry. `residentWatchedLocked` (`rootfsworkers.go`) already answers for any entry, so it needs no change. A hibernating row's replica is the same `execLease` (`ActivatorLeased` covers every row with a runtime), so it carries the lease signal (`residentOwnership`). |
| + - `residentLeaseShort` calls `stopOneShotsAtLeaseLocked(e, e.route, false)` for an entry that is the host's, in any state (awake or stopping, resident or hibernating), and runs the funcs off `a.mu`. Today it returns early for an entry that is not awake. That early return now skips only the resident's `beginStopLocked`. |
| + - `residentLeaseLostLocked(e, err) (gens []uint64, oneShots []func())`. `gens` is today's list for a resident, and nil for a hibernating entry (its generations stay the sweep's) and for an entry that is no longer the host's. `oneShots` holds the kill funcs for every rootfs entry that is the host's, whatever its state. Both callers change: |
| + - `residentLeaseLost` runs the funcs in the same `WaitGroup` as `stopRootfsWorkersAtLoss` and `killResidentGens`. Those two still run only when `gens != nil`. |
| + - The tick's fallback (`rootfsTick`, `rootfs_service.go`, for a replica with no lease signal) widens its condition from `e.route.Resident()` to `e.route.Rootfs() && (e.route.Resident() || oneShotHoldsLocked(e))`. It latches `e.ownerKilled` as today, and runs each returned func with `go f()` off `a.mu`, beside today's `go a.killResidentGens` and `go a.stopRootfsWorkersAtLoss` for a resident. |
| + - **Refused up front when unwatched.** `RunCmd`'s last check under `a.mu` refuses a rootfs one-shot whose entry is not under the watch (`!residentWatchedLocked(e)`). This is the worker rule (`rootfsworkers.go`, the install refuses an unwatched resident worker). The refusal is `&CmdStoppedError{Reason: StopLeaseLost}`, and nothing starts. So no rootfs run or session can start where no lease path would reach it. |
| - **Console** (PF-2): the always-on arm passes a rootfs record, for runs here and for sessions through Task 10's `instanceClassRefusal`. A rootfs record placed on a fleet still gets the fleet sentence. |
| - **Box** (P1 #4): |
| - `execute` sets `spec.AfterSettled` to remove the run's directory (`runs.RemoveRunDir`; an error is logged). |
| @@ -838,6 +881,16 @@ func TestResidentLeaseShortStopsTheRunBeforeTheDrain(t *testing.T) // hanging re |
| func TestRootfsRunRefusedWithoutLeaseHeadroom(t *testing.T) // SafeUntil now+oneShotStartLead()-1ms at the last check: |
| // *CmdStoppedError{StopLeaseLost}; StartCmd never called; AfterSettled once |
| func TestBinaryRunsNeverAskTheLeaseKill(t *testing.T) // a binary always-on row's run: no KillOneShot asked on any path |
| +// rev 2 (Astra R1 P1-1): a hibernating rootfs row (Hibernate true, Runtime rootfs-v1), woken by RunCmd: |
| +func TestHibernatingRootfsLeaseLossKillsItsRun(t *testing.T) // the watch is installed at the wake's install (ownerDone non-nil); |
| +// at short the run's stop starts; at loss KillOneShot(rt, RoleCmd) is asked at once; no KillGen and no worker stop are asked |
| +// (its web stays the sweep's); an entry already stopping (idle stop, drain stalled) gets the same kill |
| +func TestHibernatingRootfsTickFallbackKillsItsRun(t *testing.T) // a replica with no lease signal and Err() set: one tick asks |
| +// KillOneShot once (latched), off a.mu; a later tick asks nothing more |
| +func TestRootfsRunRefusedWhenUnwatched(t *testing.T) // an awake rootfs entry whose replica has a lease signal but no watch running: |
| +// RunCmd answers *CmdStoppedError{StopLeaseLost}; StartCmd never called; AfterSettled once |
| +func TestResidentLeaseWatchUnchangedForResidents(t *testing.T) // TestResidentLeaseHangStopsBeforeTheDeadline's and |
| +// TestResidentLeaseLossKillsAtOnce's expectations still hold (beginStopLocked, KillGen, worker stops) with no run attached |
| // internal/activator/rootfs_invariants_test.go and rootfs_test.go |
| // INV-1 rootfsProofHandles: a "rootfs run cmdUnit (StartCmd)" row through productionBackend, no binary unit present; |
| // INV-4 rootfsRefusals: "a rootfs run with no image (errNoCmdExe, marked)"; |
| @@ -867,7 +920,7 @@ func TestRunDirRemovedWhenNothingStarted(t *testing.T) // RunCmd answers ErrCmdC |
| |
| Run (each with `dangerouslyDisableSandbox`, `nice -n 19`): |
| ```bash |
| -TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestRootfsRun|TestStartReleaseIsUnchanged|TestRunCmdAfterSettledRunsOnceOnEveryPath|TestResidentLeaseLossKills|TestResidentLeaseShortStopsTheRun|TestBinaryRunsNeverAskTheLeaseKill|TestRootfsRowsNeverTakeABinaryLaunch|TestEveryRootfsProofNamesTheRootfsUnit|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv' -count=1 |
| +TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestRootfsRun|TestStartReleaseIsUnchanged|TestRunCmdAfterSettledRunsOnceOnEveryPath|TestResidentLeaseLossKills|TestResidentLeaseShortStopsTheRun|TestBinaryRunsNeverAskTheLeaseKill|TestHibernatingRootfs|TestResidentLeaseWatchUnchangedForResidents|TestRootfsFilesNameNoBinaryVerb|TestRootfsInvariantTablesOnlyGrow|TestResidentProcessInstallsGoThroughOnePlace|TestRootfsRowsNeverTakeABinaryLaunch|TestEveryRootfsProofNamesTheRootfsUnit|TestRootfsRefusalsAreNotBuildFailures|TestRootfsLaunchFilesCarryOnlyComposedEnv' -count=1 |
| TMPDIR=/tmp/g go test ./internal/instancectl/ -run 'TestRootfsOneShotStopKills|TestKillStaysOffTheOtherStops|TestStopRootfsTypesAnUnprovenOneShotKill' -count=1 |
| go test ./internal/console/ -run 'TestRunDoorAdmitsRootfsResident|TestRunDoorStillRefusesARootfsFleetInstance' -count=1 |
| go test ./internal/host/ -run 'TestRunDir' -count=1 |
| @@ -923,6 +976,16 @@ git commit -m "carlos run: rootfs rows run in their image; a one-shot is killed |
| var _ TTYControl = (*instancectl.Client)(nil) |
| ``` |
| - **Consumes, amended.** Task 6's five client verbs (through `TTYControl`), and Task 7a's rootfs `StartCmd` arm, `startRootfsCmd` and `rootfsCmdLaunch`. |
| +- **The declared-process selector, end to end (rev 2, Astra R1 P1-2).** `carlos console` and `run -it -- bin/rails console` can carry the same command. Root, though, runs a declared process with that process's own env and working directory, and an argv with web's (`resolveRootfsLaunch`, `internal/instancectl/rootfs.go`). So the choice travels as a field at every hop and is never inferred from the argv: |
| + 1. CLI: `interactive.Open{Process: release.ProcessConsole, Argv: nil}` for `carlos console`, and `Open{Argv: args}` for `run -it` (Task 13). `Open.Check` refuses both (`ErrProcessWithArgv`, Task 2, on the branch). |
| + 2. Console: `hubSession.open` keeps the `Open` exactly as the CLI sent it. The console checks that the serving manifest declares `console` (RFS-6-C33) and records the resolved argv in the audit row, but it does not rewrite `Open` (Task 10). |
| + 3. Splice: the box receives that `Open` unchanged (Task 11, step 1). |
| + 4. Box: `CmdSpec{TTY: &TTYSpec{…}, Process: open.Process, Args: open.Argv}` (Task 12). |
| + 5. Activator: `StartCmd` checks the shape (above). A rootfs session starts `startRootfsCmd` with `rootfsCmdLaunch{Process: spec.Process}` when `spec.Process != ""`, and `rootfsCmdLaunch{Argv: spec.Args}` otherwise. The launch file names `Process: "console"` or `"cmd"`. |
| + 6. Root: `TTYRootfs` gets `StagedImage{…, Process: "console"}` or `StagedImage{…, Argv: args}`, never both. `resolveRootfsLaunch` gives the console process its own env and working directory (Task 6). |
| + |
| + A binary row with `Process` set is refused before anything starts (`errBinaryProcess`). A binary release declares no processes, so the console has already refused it with RFS-6-C33. The box reports any other start refusal as RFS-6-C31. |
| +- **Binary tty verbs in the INV-1 guard (rev 2).** `rootfsBinaryVerbs` (`internal/activator/rootfs_invariants_test.go`, a detector list that may only grow) gains `"TTYControl": {"TTY", "TTYExe", "TTYStatus"}`, so rootfs code can never reach the binary tty unit. The rootfs tty start and poll use `TTYRootfs` and `TTYStatusRootfs`, and live in `backend_rootfs.go` with Task 7a's run arm. |
| - **Role-aware unit (PF-7).** `cmdUnit` gains `role instancectl.Role`. `Poll` reads `CmdStatus`/`CmdStatusRootfs` for `RoleCmd` and `TTYStatus`/`TTYStatusRootfs` for `RoleTTY`. `StopAndSettle` stops and proves `u.role` (`stopRole(sctx, u.rt, u.role, 0)`, `waitRoleCgroupEmpty(wctx, u.rt, u.role)`), never a hard-coded `RoleCmd` (see preflight §1 row 8). Test `TestTTYUnitPollsAndStopsItsOwnRole`: a tty unit's Poll and StopAndSettle never name a cmd unit, on either runtime. |
| - **The rootfs tty start (PF-1, PF-32).** It is Task 7a's `startRootfsCmd` with the role as a parameter. The pty handoff's stdin socket takes the place of the two stream listeners, and the launch file is `launch.tty.json` (schema 2, `Process` `"console"` or `"cmd"`). It is called with `rootfsCmdLaunch{Process: release.ProcessConsole}` for `carlos console` and `rootfsCmdLaunch{Argv: args}` for `run -it`, at `b.tier(rt)`: there is no `rootfsTier`. The environment is `rootfsLaunchEnv(rootfsVars(ttyVars(...), rt.Socket, dbPath))`, following `ReleaseEnv`'s steps for the rest (see preflight §1 row 8). Task 7a's `spec.serving` and `spec.genEnv` for a rootfs row serve both roles. |
| - Produces: |
| @@ -932,6 +995,11 @@ type TTYSpec struct { |
| Cols, Rows uint16 |
| } |
| // CmdSpec gains: TTY *TTYSpec // non-nil: a session; RunDir is unused and Stdout/Stderr must be nil |
| +// CmdSpec gains (rev 2, Astra R1 P1-2): Process string // a declared process to run instead of Args: "" or release.ProcessConsole. |
| +// Exactly one of Process and Args is set for a session; a run (TTY nil) never sets Process. StartCmd refuses both or neither |
| +// with errCmdLaunchShape, and Process on a binary row with errBinaryProcess, before anything is listened on or written. |
| +var errCmdLaunchShape = errors.New("activator: a command names either a declared process or an argv, exactly one") |
| +var errBinaryProcess = errors.New("activator: a binary row runs no declared process") |
| type Terminal interface { |
| io.Reader // the pty master; reads EIO once the tenant's side has closed |
| io.Writer |
| @@ -964,11 +1032,14 @@ func TestStartCmdTTYOnARootfsRow(t *testing.T) // fake Control: TTYRootfs ca |
| func TestTTYUnitStopAndSettleClosesTheMaster(t *testing.T) |
| func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) // amended 2026-10-30 (PF-7): binary and rootfs: Poll calls TTYStatus / TTYStatusRootfs, StopAndSettle stops role tty and waits on the tty unit's cgroup; no call names a cmd unit |
| func TestStartCmdTTYWithoutTTYControlIsErrNoTTY(t *testing.T) // amended 2026-10-30 (PF-6): a Control that does not implement TTYControl: ErrNoTTY, no socket listened, no launch file |
| +func TestRootfsTTYKeepsTheDeclaredProcess(t *testing.T) // rev 2 (P1-2): spec {Process "console"} and spec {Args ["bin/rails","console"]}, the same command: |
| +// the first's TTYRootfs carries StagedImage.Process "console" and no Argv, launch.tty.json Process "console"; the second's carries Argv and |
| +// Process "", launch.tty.json Process "cmd"; both set, or neither -> errCmdLaunchShape; Process on a binary row -> errBinaryProcess; nothing started in the refusals |
| ``` |
| |
| - [ ] **Step 2: Run them and see them fail** |
| |
| -Run: `go test ./internal/activator/ -run 'TestOpenPTY|TestTTYHandoff|TestStartCmdTTY|TestTTYUnit' -count=1` |
| +Run: `TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestOpenPTY|TestTTYHandoff|TestStartCmdTTY|TestTTYUnit|TestRootfsTTYKeepsTheDeclaredProcess|TestRootfsFilesNameNoBinaryVerb|TestRootfsInvariantTablesOnlyGrow' -count=1` |
| Expected: FAIL. |
| |
| - [ ] **Step 3: Implement** |
| @@ -1007,7 +1078,7 @@ git commit -m "activator: the session's pty and its handoff to the tty unit (roo |
| **Amended 2026-10-30 (PF-3, PF-17, PF-18, Call A1).** |
| - **Lease loss (PF-3).** A rootfs instance's tty hold is stopped and proven at its lease events exactly as Task 7a stops its cmd hold. `stopOneShotsAtLeaseLocked` covers every hold that may be running, of either role (`holdsLocked(e)`, which `cmdHoldsLocked` becomes): |
| - at `residentLeaseShort` it stops the hold gracefully, whether the entry is awake or already stopping; |
| - - at the loss it kills the unit with `KillOneShot(rt, RoleTTY)`, at once and again when a start in flight returns, beside the cmd hold, `killResidentGens` and `stopRootfsWorkersAtLoss`, within the lease margin; |
| + - at the loss it kills the unit with `KillOneShot(rt, RoleTTY)`, at once and again when a start in flight returns, beside the cmd hold, `killResidentGens` and `stopRootfsWorkersAtLoss`, within the lease margin. This holds on a hibernating rootfs row as on a resident one (rev 2: Task 7a's watch covers every rootfs entry, and `oneShotHoldsLocked` counts both roles); |
| - a rootfs session starts only with `oneShotHeadroom` left. |
| |
| The session learns the reason (`Interrupted() == StopLeaseLost`), and the box ends it as interrupted (Task 12). |
| @@ -1043,6 +1114,9 @@ func TestResidentLeaseLossKillsTheSessionOfAnAlreadyStoppingEntry(t *testing.T) |
| func TestResidentLeaseLossKillsASessionWhoseStartIsInFlight(t *testing.T) // the tty StartCmd blocked: KillOneShot(rt, RoleTTY) once at once, |
| // and again when the start returns a unit; the hold is then proven |
| func TestRootfsSessionRefusedWithoutLeaseHeadroom(t *testing.T) // SafeUntil inside oneShotStartLead(): *CmdStoppedError{StopLeaseLost}, no tty start |
| +func TestHibernatingRootfsLeaseLossKillsItsSession(t *testing.T) // rev 2 (Astra R1 P1-1): a hibernating rootfs row woken by RunCmd(tty), with a run beside it: |
| +// at loss KillOneShot(rt, RoleTTY) and KillOneShot(rt, RoleCmd) are both asked at once, no KillGen; the tick fallback (no lease signal) |
| +// reaches the session too; an unwatched entry refuses the session before any tty start |
| // in cmd_test.go: |
| func TestASessionIsNotRefusedForARelease(t *testing.T) // a releaseOps entry for the host: RunCmd(run) -> ErrCmdBusy, RunCmd(tty) admitted; |
| // with a session attached, the release's busy check (rootfsrelease.go) reads not busy |
| @@ -1053,7 +1127,7 @@ func TestASessionHoldsEveryIdleAndStopCheck(t *testing.T) // with only e.tty set |
| |
| - [ ] **Step 2: Run them and see them fail** |
| |
| -Run: `TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestEveryStopPathSettlesTheSession|TestRunCmdHoldsTheIdleTimerForASession|TestASession|TestRunCmdSession|TestResidentLeaseLossKillsTheSession|TestResidentLeaseLossKillsASession|TestRootfsSessionRefusedWithoutLeaseHeadroom' -count=1` |
| +Run: `TMPDIR=/tmp/k go test ./internal/activator/ -run 'TestEveryStopPathSettlesTheSession|TestRunCmdHoldsTheIdleTimerForASession|TestASession|TestRunCmdSession|TestResidentLeaseLossKillsTheSession|TestResidentLeaseLossKillsASession|TestRootfsSessionRefusedWithoutLeaseHeadroom|TestHibernatingRootfsLeaseLossKillsItsSession' -count=1` |
| Expected: FAIL. |
| |
| - [ ] **Step 3: Implement the second slot** |
| @@ -1091,11 +1165,13 @@ git commit -m "activator: a session is held and settled like a run, beside it (r |
| - At the upgrade, the handler ends its request's unit (`endRequestUnit(r.Context())`). A session open for 6 hours therefore never holds a cutover's drain. |
| - Steps 3 to 6 (reserve, grant `Put`, the record CAS, `activate`, the serial bump and the `interactive-start` row) run as one write step: `s.lifetimesStep(ctx, true, …)`, bounded by `interactive.OpenWait` as before. If the gate refuses the step (the gate is draining), the session ends: End refused, `Detail` RFS-6-C37. The reservation is released, and nothing is written. |
| - Every end (the marker clear, the grant delete and the `interactive-end` row) is its own write step. If the gate refuses it while draining, the hub keeps the id in `endPending` with its End, and the sweep finishes it (Task 11). The CLI still gets its End at once. |
| -- **Request budget (PF-22).** Per session: |
| - - On the console: 1 record GET before the upgrade; 2 record CAS (admit, clear), each a GET and a conditional PUT, or 3 when a sweep clears the marker instead; 1 grant PUT and 1 grant DELETE; for `carlos console`, 1 channel pointer GET and 1 manifest GET; 1 serial bump (the existing change-index write). Audit rows are console SQL, not bucket requests. |
| - - On the owning box: 1 grant GET. The marker reaches it on the reconcile pass and change index it already runs, so nothing new is polled. |
| - - On every other box: no request, since each ignores the marker before reading anything (Task 12). |
| - - A box's dial is one WebSocket to the console, kept open for the session. |
| +- **Request budget (PF-22; rev 2, Astra R1 P2-6).** Store requests per session. "Judged" means the context carries the lifetime judge (lifetimes on). A judged record read is then the record GET plus the host incarnation slot GET (`LifetimeJudge.Observe`, `internal/provision/lifetime_judge.go`), and up to three such rounds if the slot moves under it. With lifetimes off (legacy), each read is the record GET alone. |
| + - **Console, before the upgrade:** 1 judged record read (2 GETs judged, 1 legacy), and 1 GET of the app's `config.json` for the interactive setting (`appconfig.GetInteractive`). For `carlos console`, 1 channel pointer GET and 1 manifest GET. |
| + - **Console, two logical record transitions per session: admit and clear.** Each is one `updateRecord`: a judged read (2 GETs judged, 1 legacy) and one conditional PUT. A CAS conflict repeats the read and the PUT, which is a retry, not another transition. When the end step is refused while draining, the sweep makes the clear instead. That replaces the ordinary clear, so it is still one transition. The only extra attempt is a clear the sweep tries after a new session has replaced the marker: one judged read and no PUT (`ErrInteractiveConflict`). |
| + - **Console, other writes:** 1 grant PUT and 1 grant DELETE, and 1 serial bump (the existing change-index write). Audit rows are console SQL, not bucket requests. |
| + - **Owning box:** 1 grant GET and 1 `config.json` GET (the box half of C9, `allowed`). The box reads no record of its own: the marker reaches it on the reconcile pass and change index it already runs, judged there as today. Nothing new is polled. |
| + - **Every other box:** none. It ignores the marker before reading anything (Task 12). |
| + - **Connections:** one WebSocket from the CLI and one from the box, each open for the session. Keepalives are frames, not store requests. |
| - **Perf ring (PF-23).** `consolePerfSkip` skips `GET` on a path that starts `/api/cli/apps/` and ends `/interactive` with an `/instances/` segment, so the setting door's `PUT …/{app}/interactive` is still measured. It also skips the box doors' prefixes (`interactive.AttachPathPrefix`, and Task 16's `interactive.RunAttachPathPrefix`). |
| - **Fixtures (PF-24).** The claim fixture keeps the harness's `bab` path, as Step 4 writes it. The behavioural tests use accounts `bah` and `baj`, the app `shop`, and `shopManifest(app, domain)`. |
| - **File cells (PF-12).** Rewrite the deck's file cells of RFS-6-C27 and C32 to C37 to the paths written. |
| @@ -1127,7 +1203,8 @@ func (h *interactiveHub) release(id string) // drops a reserved, never- |
| type hubSession struct { |
| id, acct, app, host, incarnation, fleet, by string |
| tokenHash [32]byte |
| - open interactive.Open // resolved argv |
| + open interactive.Open // as the CLI sent it (rev 2: never rewritten; Process kept) |
| + argv []string // the resolved command, for the audit row only |
| cli *websocket.Conn |
| attach chan *boxConn // Task 11 hands the box's connection here |
| pickupBy time.Time |
| @@ -1150,7 +1227,7 @@ Before the upgrade, refusals come as JSON errors, in this order (each its own st |
| |
| After the upgrade: |
| 1. Clear the deadlines `ReadTimeout` left on the hijacked connection (`ws.SetDeadline(time.Time{})`; the console's server sets `ReadTimeout` 5 minutes, `internal/console/httpserver.go:20`). |
| -2. Read the `Open` frame within `OpenWait`. It must pass `Normalized().Check()`, else End refused RFS-6-C36. A `console` process resolves to the argv of `Processes["console"]` in the manifest of the version the record's channel serves, else End refused RFS-6-C33. |
| +2. Read the `Open` frame within `OpenWait`. It must pass `Normalized().Check()`, else End refused RFS-6-C36. A `console` process resolves to the argv of `Processes["console"]` in the manifest of the version the record's channel serves, else End refused RFS-6-C33. (Rev 2, Astra R1 P1-2: the resolved argv is used only for this check and the audit row. `hubSession.open` keeps the `Open` exactly as received, `Process: "console"` and no argv, and that is what the box gets, so root runs the declared process with its own env and working directory.) |
| 3. Mint the id and the token, and **reserve the session in the hub** (`s.interactive.reserve(sess)`, finding 10). From here until step 6, every failure releases the reservation (`release(id)`, deferred and disarmed by a successful `activate`), and the steps' store calls run under a context bounded by `interactive.OpenWait`, so a reservation never outlives its admission. |
| 4. Sign the grant (Attach is `interactive.AttachURL(s.cfg.Origin, id)`) and `Put` it at `GrantKey`. |
| 5. Admit on the record (`Console: s.bootID`, `PickupBy: now+60s`, `Live: func(st provision.InteractiveState) bool { return s.interactive.live(st, s.bootID) }`). Because the id is already reserved, any other admission on this console that reads this marker, from the moment the CAS lands, finds it live and is refused with RFS-6-C32; a session of another console boot is dead by `Console`, as before. A refusal deletes the grant, releases the reservation, writes no audit row and ends with its sentence. |
| @@ -1167,7 +1244,7 @@ func TestInteractiveRefusalsInOrder(t *testing.T) // one sub-test per refusal 1- |
| func TestInteractiveAdmitsAFleetInstance(t *testing.T) // a rootfs record on fleet/home: admitted (waiting); a carlos run on the same record is still refused with the fleet sentence (until Task 16) |
| func TestInteractiveRefusedWhenTheAppDisallows(t *testing.T) // C9, console half: setting off -> 409 RFS-6-C27; turning it on admits the same request |
| func TestInteractiveAdmitsAndWaits(t *testing.T) // record has the marker with Console == bootID; grant verifies under ReleasePub with Attach == origin+"/api/box/interactive/"+id; audit interactive-start; first frame Status waiting |
| -func TestConsoleProcessResolvesFromTheManifest(t *testing.T) // Open{Process:"console"} -> hub session argv == manifest's console command; a manifest without one -> End refused, Detail RFS-6-C33 |
| +func TestConsoleProcessResolvesFromTheManifest(t *testing.T) // Open{Process:"console"} -> hub session argv == manifest's console command and hub session open.Process == "console", open.Argv nil (rev 2); a manifest without one -> End refused, Detail RFS-6-C33 |
| func TestPickupWindowExpiresTheSession(t *testing.T) // PickupBy shortened through a hub field: End{Reason: expired}; marker cleared; grant deleted; audit end "expired"; a new request is admitted |
| func TestAdmissionReplacesAMarkerFromAnotherConsoleBoot(t *testing.T) // a marker with Console "old" -> admitted, marker replaced |
| func TestTwoSessionsRaceOneAdmission(t *testing.T) // two clients at once -> one waiting, one 409 RFS-6-C32 naming the first's caller |
| @@ -1258,7 +1335,7 @@ The box door: |
| These are box diagnostics, not human text. The box's label is the fleet name's label, or the `X-Carlos-Box` header for a platform box, used only in End and audit. |
| |
| The splice: |
| -1. Send `Open` to the box. |
| +1. Send `Open` to the box, as the CLI sent it (`hubSession.open`; rev 2, P1-2: `Process` kept, never replaced by the resolved argv). |
| 2. Box to CLI: forward `KindStatus`, `KindData` and the box's `KindEnd`. CLI to box: forward `KindData` and `KindResize`. Answer `KindAlive` per leg; it is never forwarded. |
| 3. Every `Send` is synchronous on its own goroutine, one frame at a time, so a slow reader stalls its writer and nothing queues. |
| 4. Each leg's read deadline is `KeepaliveLost`, refreshed on every frame. The console sends `KindAlive` to both legs every `KeepaliveEvery`. |
| @@ -1278,7 +1355,8 @@ The sweep phase: |
| func TestBoxDoorRefusesWithoutTheToken(t *testing.T) // wrong token, unknown id, bad id -> 404, and the CLI still waits |
| func TestBoxDoorNeedsTheFleetsOwnCredential(t *testing.T) // fleet record: no credential -> 404; another fleet's box -> 404; a detached box -> 404; the right box -> attached |
| func TestBoxDoorTakesOneBox(t *testing.T) // second attach -> 409 |
| -func TestSpliceCarriesBothWays(t *testing.T) // CLI data reaches the box; box data, status and end reach the CLI; resize reaches the box as 4 bytes |
| +func TestSpliceCarriesBothWays(t *testing.T) // CLI data reaches the box; box data, status and end reach the CLI; resize reaches the box as 4 bytes; |
| +// rev 2: a carlos console session's Open reaches the box as {Process: "console", Argv: nil} |
| func TestSpliceAppliesBackpressure(t *testing.T) // a CLI that stops reading: after the transport's buffers fill, the box's Send blocks; the hub's heap growth while the box pushes 64 MiB stays below 4 MiB (runtime.ReadMemStats delta) |
| func TestCLIGoneHangsUpTheBox(t *testing.T) // close CLI -> box receives End{Reason: hangup} |
| func TestBoxGoneEndsTheCLIAsLost(t *testing.T) |
| @@ -1376,7 +1454,7 @@ Then it refuses over the connection, as End refused, for: |
| - `rec.ImportUncommitted()` (`import`); |
| - `RunCmd` errors: `ErrCmdClaim` is `claim`, `ErrCmdNotNested` is `flat`, `*CmdWakeError` is `wake` with its member-safe reason in `Detail`, `ErrTTYBusy` is `busy`. |
| |
| -A newer session id for a host whose session this worker still runs ends the old one first, as `replaced`. Before `RunCmd`, the worker sends Status `starting`; after it returns a handle, Status `started` and the `opened` log line. |
| +A newer session id for a host whose session this worker still runs ends the old one first, as `replaced`. The worker calls `RunCmd` with `CmdSpec{RunID: id, TTY: &activator.TTYSpec{Term, Cols, Rows}, Process: open.Process, Args: open.Argv}` (rev 2, P1-2). Before `RunCmd`, the worker sends Status `starting`; after it returns a handle, Status `started` and the `opened` log line. |
| |
| The bridge: |
| - master to `KindData` (reads of at most 32 KiB); |
| @@ -1396,6 +1474,7 @@ The worker never writes the bucket. |
| |
| ```go |
| func TestInteractiveWorkerIgnoresAForgedGrant(t *testing.T) // grant signed by another key -> dial never called, launcher never called |
| +func TestInteractiveWorkerPassesTheProcessThrough(t *testing.T) // rev 2 (P1-2): Open{Process "console"} -> the launcher's CmdSpec.Process "console", Args nil; Open{Argv} -> Process "", Args the argv |
| func TestInteractiveWorkerRefusesWhenTheAppDisallows(t *testing.T) // C9, box half: allowed false -> End{Refused: "off"} on the connection; launcher.RunCmd never called |
| func TestInteractiveWorkerMapsLaunchRefusals(t *testing.T) // ErrCmdClaim -> claim, ErrCmdNotNested -> flat, *CmdWakeError -> wake + Detail, ErrTTYBusy -> busy |
| func TestInteractiveWorkerOnlyActsOnOwnedRows(t *testing.T) |
| @@ -1645,8 +1724,12 @@ A fleet box cannot make a run's bucket writes (the pickup CAS on the record, the |
| - `/api/box/runs/{id}` is in `lifetimesExempt`, so the relay connection, open as long as the run, holds no unit. |
| - Each record step of `relayRun` is its own `s.lifetimesStep(ctx, true, …)`: the pickup CAS with its read-back, the finish CAS, and rule 5's lost-run finish. |
| - Chunk `Put`s and `result.json` are `runs/` objects, not record work, so they take no unit and go on while the gate drains. |
| - - A pickup refused while draining answers `RunPicked{State: RunStateNotPicked}`. The box forgets the run, as rule 4 says, and the next pass dials again while the run is still queued inside its pickup window. |
| - - A finish refused while draining is retried, each attempt in a fresh step with `untilLanded`'s backoff, until it lands or the console's run sweep (a `lifetimesIteration`) ends the run. |
| + - **A fleet run still queued when the gate starts draining is not picked; it expires (rev 2, Astra R1 P1-5).** The numbers: the pickup window is `runs.PickupWindow` = 60 s from admission (`internal/runs/runs.go:32`). The gate activates no sooner than `lifetimeSettle` = 60 s after the later of the drain's start and the last legacy unit's end (`internal/console/lifetimes_cutover.go:44`, `activateWhenDrained`). The pickup is a console record CAS, which the gate refuses while draining. No run is admitted during draining either: the create is a mutating request, and `TestDrainingRefusesEveryClaimsOffMutation` holds that. So a fleet run queued when the drain starts has at most 60 s of window left and needs at least 60 s of drain. It can never be picked before its deadline, and a retry after activation could never fit. The plan therefore refuses it up front, with no retry: |
| + - The relay answers `RunPicked{State: RunStateNotPicked, Why: RunNotPickedCutover}` and closes. `RunPicked` gains a `Why` field and the constant `RunNotPickedCutover` (in Interfaces below). |
| + - The box's relay sink marks the run id done in its `unfit` map, as for a request it refused. It never dials it again. It writes no result, and the record is unchanged. |
| + - The run ends exactly as any run no box picked up. The CLI's own poll reports it at its pickup deadline (today's "not picked up" line, exit 3). After activation, the console's run sweep (`sweepExpireQueued`, a `lifetimesIteration`) writes the `RefusedExpired` result and the expiry transition. No new string is needed. |
| + - Platform-box runs are unaffected: their pickup is the box's own record write, which the console's gate does not govern. |
| + - A run picked before the drain keeps running through it: chunks and `result.json` land, since `runs/` is not record work. Its finish CAS, refused while draining, is retried in a fresh `lifetimesStep` each time, with backoff from 250 ms doubling to 5 s. It goes on until the CAS lands (the first attempt after activation, so at most `lifetimeSettle` plus 5 s after the drain's last legacy unit ends), until the record no longer names the run as the hello's (`ErrRunConflict`), or until the console stops. If the console stops first, today's lost sweep finishes the run at `Deadline + runs.LostAfter` (1 h). It keeps the relay's `result.json`, because `runs.WriteResult` is create-only. |
| - The run admission's grant `Put` is part of the create request's own mutating unit, as `request.json` is today. |
| - **Fleet owner (PF-16).** The run door uses Task 11's `fleetIdentityOK(reg, name, token, fleet, rec.Account)`, the owner check included. |
| - **Region HA (PF-15) and judged reads (PF-19).** `sinkFor` and the relay act on an HA route only when `HoldsAwake(rec.Host)`, as Task 12 does. Every record read in the relay sink (the read-back after `RunPicked`) goes through `judgedRecord` under the box judge. |
| @@ -1685,8 +1768,10 @@ A fleet box cannot make a run's bucket writes (the pickup CAS on the record, the |
| Box string `json:"box,omitempty"` |
| Boot string `json:"boot,omitempty"` |
| Deadline time.Time `json:"deadline,omitempty"` |
| + Why string `json:"why,omitempty"` // rev 2: RunNotPickedCutover when the console's lifetimes gate is draining |
| } |
| const (RunStatePicked = "picked"; RunStateNotPicked = "not-picked") |
| + const RunNotPickedCutover = "cutover" // rev 2: the box forgets the run for good and never redials it |
| // internal/console |
| func (s *Server) handleBoxRun(w http.ResponseWriter, r *http.Request) // the box door for runs: Task 11's refusals and credential rule |
| func (s *Server) relayRun(ctx context.Context, rel *runRelay, box *boxConn) // performs, as the box would: the pickup transition, each chunk Put, result.json, the finish transition |
| @@ -1734,16 +1819,20 @@ func TestPlatformRunsWorkerIsUnchanged(t *testing.T) // a platform box: buck |
| func TestForgedRunGrantExpiresTheRun(t *testing.T) // a grant signed by another key: no dial; the console's sweep expires the run at PickupWindow with today's result |
| // amended 2026-10-30: |
| func TestFleetRunsWorkerRelaysARootfsRun(t *testing.T) // PF-1: as above, on a rootfs route |
| -func TestRunRelayHoldsNoUnitAcrossACutover(t *testing.T) // PF-4: a relay open and streaming chunks; the cutover is asked: the gate drains within 1 s and activates |
| -// while chunks still land; a pickup asked while draining (a legacy unit held by the test) answers not-picked and the record is unchanged; |
| -// after activation the box's next dial is picked; a finish refused while draining lands after activation, once, judged |
| +func TestRunRelayHoldsNoUnitAcrossACutover(t *testing.T) // PF-4: a relay picked before the drain, streaming chunks; the cutover is asked: the gate drains |
| +// (the relay holds no unit) while chunks still land; the box's End during draining: result.json written at once, the finish CAS refused; |
| +// the gate clock (useLifetimesClock) advanced past lifetimeSettle: activation, then the finish lands once, judged |
| +func TestQueuedFleetRunAtACutoverExpires(t *testing.T) // rev 2 (Astra R1 P1-5): the gate clock and the run clock advance together: a fleet run |
| +// admitted at t0; the drain starts at t0+10s; the box dials at t0+20s: RunPicked{not-picked, Why "cutover"}, the record unchanged, no result; |
| +// the box's next two passes do not dial (a counting dial); at t0+61s the CLI's poll reports not picked up (exit 3); at t0+70s the gate activates; |
| +// the next sweep writes RefusedExpired and the expiry transition once; a pickup is never attempted after activation |
| func TestBoxRunDoorRefusesAFleetOfAnotherAccount(t *testing.T) // PF-16: as Task 11's, at /api/box/runs/{id} |
| func TestRelaySinkOnAnHARouteOnlyWhenItHoldsTheHost(t *testing.T) // PF-15: rt.HA and not held: no grant read, no dial |
| ``` |
| |
| - [ ] **Step 2: Run them to make sure they fail** |
| |
| -Run: `go test ./internal/interactive/ -run 'TestRunGrant|TestRunFrames' -count=1`, `go test ./internal/console/ -run 'TestRunDoorAdmitsAFleetInstance|TestBoxRunDoor|TestRelay|TestRunPickupUsesTheBoxBoot|TestRunHelloIsChecked|TestForgedRunGrant|TestRunRelayHoldsNoUnitAcrossACutover' -count=1`, `go test ./internal/host/ -run 'TestFleetRunsWorker|TestPlatformRunsWorker|TestRelayWorkerStartsNothing|TestRelaySinkOnAnHARoute' -count=1` |
| +Run: `go test ./internal/interactive/ -run 'TestRunGrant|TestRunFrames' -count=1`, `go test ./internal/console/ -run 'TestRunDoorAdmitsAFleetInstance|TestBoxRunDoor|TestRelay|TestRunPickupUsesTheBoxBoot|TestRunHelloIsChecked|TestForgedRunGrant|TestRunRelayHoldsNoUnitAcrossACutover|TestQueuedFleetRunAtACutoverExpires' -count=1`, `go test ./internal/host/ -run 'TestFleetRunsWorker|TestPlatformRunsWorker|TestRelayWorkerStartsNothing|TestRelaySinkOnAnHARoute' -count=1` |
| Expected: FAIL. |
| |
| - [ ] **Step 3: Implement** as above. Move today's runs-worker writes behind `bucketRunSink` first, with no behaviour change, and run `go test ./internal/host/ -run 'TestRuns|TestRunResult' -count=1` (PASS) before adding the relay. |