fix: no manifest read or hash before the lease for stateful wakes
Use retained good-build and stateful projection evidence to bypass canonical
declaration reads on recovery wakes and config/recovery swaps. Keep unplanned
stateful live-link capture and materialization after Acquire and Restore.
Carry stateless evidence across fallback and retain R18 refusal behavior.
Memoize verified immutable declarations by account, app, version and artifact
digest; use cached staged hashing. Preserve the baseline pre-exec hash.
Cover the real host reader with a counting store and read-byte measurements,
post-restore repoints, memo identity isolation and both mode transitions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbellpushed by claude agent, operated by paul@keymail.dev77ce6804e67067f66aa7159bc41aa53b29cb933eparent 28cebb8
<task-notification>
<task-id>aa0621bcffa811c48</task-id>
<tool-use-id>toolu_015fVTeEaBaeiE6hPgBtVqy6</tool-use-id>
<output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/412bbef6-9468-4e8d-b9fe-5343bad21de8/tasks/aa0621bcffa811c48.output</output-file>
<status>completed</status>
<summary>Agent "Re-review Task 4 fix round 1" finished</summary>
<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>
<result>**Per-finding verdicts**
- **I1 / R22: ADDRESSED.** `internal/console/rootfs.go:39-58` lists `control/system/router/` and filters it through `systemChannelOf`, the same way `fleetfloor.go:179-190` does. It verifies every channel pointer against the root key, and each must be at or above `StatelessRuntimeFloor`. A failed listing, an unreadable or unparseable pointer, a version below the floor, or an empty listing all refuse. The app channel argument is now ignored (`_ string`). The memo key `stateless-system-pointer:all` gives one snapshot per mutation, shared by the preflight and the conditional-write callback. The tests now use the real platform channels `stable` and `canary`, separate from the app channel `canary/shop`. They cover all channels at the floor (accept), one channel below (refuse) and an unreadable listing (`failList`, refuse) at `stateless_floor_test.go:58-94`. They also assert one listing per mutation and none for a stateful selection (`:88-94`, `:149-164`).
- **I2 / R23: ADDRESSED, using R23's fail-open option.** The rollback pointer holds version history only, not the storage declaration, so the zero-read contract can't be restored. `rootfs.go:73-82` reads the target manifest once per version per mutation. The memo is extended to that key at `reqmemo.go:78`, and a failed read is memoised too. An unreadable manifest returns nil, which admits. Only a readable `Stateless` manifest reaches the floor check. The test is renamed to `TestRollbackWithoutACatalogAdmitsUnreadableManifest` (`plancaps_doors_test.go:887`). API and browser rollback both succeed with both manifests deleted, with exactly one manifest read each. The transport-failure case and reuse of the failed read are covered by `stateless_floor_test.go:348`.
- **R24, unseed: ADDRESSED.** `registry.go:3116-3142` now writes `stateless=?` in both directions, under the same full-row comparison inside a transaction. `remote_dispatch.go:324` carries the mode in the existing `On` field. `adopt.go:1844-1849` fires when `m.Stateless != rt.Stateless`. The never-served guard requires empty `GoodVersion` and `ServingVersion`, plus `running == ""`. The guard moved from `Version` because adoption itself stamps `Version` before any wake. `release/stateless_adopt_test.go:9` drives stateless v1, then stateful v2, then stateless v3, all before the first wake.
- **R24, request counter: ADDRESSED.** The rig now has an atomic counter (`rootfs_wake_release_test.go:233,312`), and `stateless_resident_test.go:92` reads it. A positive control at `:129` proves a real wake request increments it. It counts only requests sent through the rig's `wake` helper, which is what the ruling asked for.
**New breakage (this diff only): none Critical or Important.**
- **Stateful selections:** rollback, pending promote, pin and fast-track read at most one target manifest per mutation and never refuse on it (R23 allows this). They never list or read platform pointers.
- **Every console path that selects a readable stateless declaration still gets the floor check:**
- by version: rollback (API, browser, callback), pending promote, pin and fast-track
- by manifest: promote, new canary and instance create
- a changed rollback target uses a different memo key, so it gets its own check
- **Platform-channel listing:** it runs once per mutation, and only for stateless targets. It isn't reachable from GET views, because every caller is a write door behind `withWriteMemo`.
- **Never-served guard:** an activator-managed stateless build that has served has `serving_version` stamped by `SetServingMode` on every successful wake (`activator.go:2245`), so the unseed can't clear it. `runningVersion` returns "" for activator units (`host/rootrestart.go:132-135`), so the protection rests on `ServingVersion` alone (plus `GoodVersion` where set).
- **Fleet box check:** it is still reached only from `apiinstances.go:2331`, where `fleetActive` is already loaded. Nothing new was loaded.
**Out of scope (minor)**
- The guard is only as good as `SetServingMode`, which only logs on failure. If that write failed, a serving row could look never-served, and its mode bit could be flipped toward the staged build's mode before `PointLive`. Before this diff that could only happen in the seed direction, and only with `Version == ""`.
- A pointer deleted between the listing and its GET refuses here, whereas `fleetfloor` passes it. This fails closed and is transient.
- Under R22, a stale `canary/<branch>` system pointer below v0.34.0 refuses every stateless selection, and there is no override. That follows the ruling, but it's worth knowing before the dev step.
- The verification key is `RootSigner(Key).RootPublicKey()`, not `cfg.ReleasePub`. This carries over from R21.
- The header comment in `reqmemo.go` still says a write memo holds no manifest.
**Census:** consistent with the code.
- `Registry.SeedStateless`: drops `registry:Version`, adds `registry:GoodVersion`. The basis now describes seed and unseed and calls `Version` a staging stamp.
- `adoptHost`: the same swap of `Version` for `GoodVersion`.
- `dispatchRemote`: `registry:On` goes to ×2.
- The seal is now 8b80aab5…, and the chain tsv and coverage digests were regenerated.
- The record-write census needed no change, since the same column is written. The serving-evidence guard change is described accurately in the claim text.
No tests were run; I had no specific doubt that needed one.
**Verdict: all addressed**</result>
<usage><subagent_tokens>92708</subagent_tokens><tool_uses>24</tool_uses><duration_ms>242211</duration_ms></usage>
</task-notification>
Humancodex~paul@keymail.dev
<task-notification>
<task-id>ab5f479edbb814c62</task-id>
<tool-use-id>toolu_01KZtMU6eDRLLKBap6s8aAMM</tool-use-id>
<output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/412bbef6-9468-4e8d-b9fe-5343bad21de8/tasks/ab5f479edbb814c62.output</output-file>
<status>completed</status>
<summary>Agent "Final whole-branch review Plan 1" finished</summary>
<note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>
<result>### Review method
I reviewed in five passes rather than reading the 1.1 MB package end to end:
1. The stateful wake path, swap and stop path in `internal/activator`.
2. How the host wires things up (`agent.go`, `rollout.go`) and the rollout manager and failure book.
3. Registry, provision and ops (migration, upsert, forward rows, typed writers, Litestream).
4. The console: fleet replica API, runtime floor, CLI ship.
5. Copy and docs against the SR-1 deck rows.
I ran one scratch test (in a temporary worktree under `$TMPDIR`, since removed) to prove a stateful wake doubt. I also ran the five Review Focus tests. All five pass.
### Strengths
- The new fields don't break old data. `stateless` is omitempty in the manifest, ship metadata, `Gen` and `Route`. The registry adds a column with default 0. The fingerprint and snapshot hash only change when the flag is set. Old failure-book readers skip the new key.
- Coordinator fencing is careful. The client never trusts a client-supplied expiry, checks box, boot and term on every reply, and computes the safety deadline from request start. The typed writers recheck lifetime and term inside the CAS retry. `replicaFieldsFixed` stops unrelated record writers from clobbering the new fields, and still allows tombstones (Task 2 I1).
- Release-before-serve (R14) holds end to end. `PrepareStatelessRelease` writes the phase before exec. `statelessFinalRecord` at the exec gate needs a fresh record read showing `released` for this deploy ID, target and lifetime before the web process can start.
- Coordinator loss can't stop serving. `servingError` returns nil for stateless generations, `watchResidentLeaseLocked` skips them, and residency uses `lifecycleDone`.
- The fleet API checks auth before revealing anything, checks again under the record lock, and gives an identical 404 for every rejection. It takes the box identity from the authenticated header, not the payload. The follower path in `followerEscrowEnv` never publishes or mints.
- The copy matches. SR-1-C01 through C09 and C12 match the deck byte for byte, and the docs build C10 and C13. No em dashes were added outside a test assertion. C11 (which mentions `--copies`, a flag that doesn't exist yet) is correctly not built.
### Issues
#### Critical (Must Fix)
**C1. Stateful wakes now make a bucket GET and a full uncached hash before taking the lease, on every wake.** This fails the "inert for existing apps" gate.
- **Where:**
- `internal/host/agent.go:607` always sets `svc.StorageDeclaration`.
- `internal/activator/activator.go:2678` calls `storageMode` before the lease for every planned wake and every unplanned wake with a live version.
- In production that resolves to `release.CanonicalRuntimeSelection`. That function does `FileSHA256(path)` (uncached, `runtime_selection.go:21`) and then `GetManifestRaw` (`:29`).
- **Proof:** the steady-state recovery plan (`decideWake` → `recovery`, when `installed == GoodVersion`) carries no `Declarations`, so it falls through to the store. My scratch test on a recovery-planned stateful wake counted exactly one `StorageDeclaration` call.
- **Why the tests missed it:** `TestStatelessStatefulWakeHashesOneCapture` uses a fake declaration source built on the cached `VerifyStaged`. In production the hash is re-read in full and an S3 GET is added.
- **Also affected:** `Swap` (`swap.go:355`) hits the same path for config restarts and recovery attempts, which carry no `Declaration`. That contradicts `manager.resolve`'s own comment that recovery is "not checked against the canonical manifest".
- **Base behaviour:** no manifest read in the activator at all.
- **Effect on stateful apps:**
- Higher cold-wake latency: an S3 round trip plus a full re-read of the rootfs image, against a 376 ms cold-wake target.
- Wakes now depend on the bucket. During a bucket slowdown every wake waits on SDK retries before failing open.
- One S3 request per wake, fleet-wide.
- **Fix:** manifests are immutable, so memoize the declaration in-process, keyed by (account, app, version, artifact digest). Use `FileSHA256Cached`, or reuse the digest the caller already verified, instead of `FileSHA256`. Better still, skip the lookup for stateful routes when the route projection, `Gen` and good-build evidence all say stateful and the staged sibling manifest says stateful. Keep the canonical read for projected or stateless cases (R18 still holds). Add a host-level test that drives the real `storageDeclaration` with a counting store and asserts zero GETs on a stateful recovery wake.
#### Important (Should Fix)
**I1. A second, unordered writer of `serving_version` on every stateful wake.** `activator.go:2245` calls `SetServingMode` synchronously before `close(e.ready)` on every successful wake.
- This includes worker wakes, which the rollout manager deliberately skips (`if g.Worker return`), and boxes with rollout off.
- It adds a registry update (an RPC to the registry child) to every wake's critical path.
- `serving_version` is user-visible through `status/snapshot.go:1029` and `instanceupdates`. Unmanaged boxes now report values they didn't before. An empty `spawnVersion` would clear the rollout's value.
- This was logged as a deferred minor. I'm promoting it under the inertness gate.
- **Fix:** call it only when `w.gen.Stateless` differs from the row's `Stateless`, or only for stateless generations. Skip worker entries.
**I2. Routine refusals before exec mark the deploy permanently `failed`.** `statelessrelease.go:155`: any gate refusal before `releasing` is written becomes terminal `failed`. That covers `errShuttingDown`, fences, `errSwapSuperseded`, and the binary path's `VerifyStaged`/`gate()`.
- After an agent restart the failure book returns the same deploy ID, and `old.Phase == "failed"` returns `errReleaseNotPassed`.
- So a platform roll or restart during a stateless deploy wedges that build until someone re-promotes. On a first deploy the instance never serves.
- The plan's own smoke ("restart and a failed release") is likely to hit this.
- **Fix:** keep `failed` only for a `*ReleaseError` (the command ran and exited non-zero) and a digest mismatch. Leave other refusals before `releasing` at `pending`, which R11 already lets a later attempt retake.
**I3. A slow console can stall the whole box's fast tick.** `agent.go:2932`: `d.coordinator.Tick(ctx)` runs at the head of every `fastTick` and holds `opMu` across one HTTP renewal per held authority (30 s timeout each, sequential).
- During a console outage, stage, adopt and restart convergence for all apps on that box, stateful ones included, is delayed by up to N×30 s per tick.
- It only affects boxes holding a stateless authority, so it's dormant today, but it is a stateful side effect once a stateless app shares a box.
- **Fix:** run renewals in their own goroutine on the tick signal, or bound the total time per tick.
#### Minor (Nice to Have)
- **M1.** `swap.go:355` and `storageMode`: for a stateful attempt whose staged copy has changed, the refusal text changes from `staging: …` to "could not verify this build's storage declaration". It is still abandoned either way. Keep `VerifyStaged` errors unwrapped for stateful routes.
- **M2.** `escrow_authority.go` `prepareStatelessEscrow`: after any agent restart the box is a permanent follower. Every hibernating stateless wake then does `hostfiles.Load`, plus `followerEscrowEnv`'s manifest and sealed reads (about 7 GETs per wake). That is allowed per wake, but costly. Cache "trio complete" per lifetime.
- **M3.** `fleetbind.go` `statelessBindingPublisher.publish` only publishes while this box holds the coordinator. An unlabelled stateless instance whose coordinator lapsed is never rebound. That's harmless for labelled fleets (forward rows use `FleetLabel`); note it for Plan 2.
- **M4.** An older console or operator-CLI record writer re-marshals `Record` without `coordinator` and `replica_deploy`. That drops release evidence and leads to a rerun of the (repeat-safe) release command. This is the expected mixed-version window; record it in the rollout note.
### Deferred-minor triage
**Task 1**
- `ship_check.go:497` advice names a `/data` path the stateless check no longer mounts: can wait
- variadic `stateless ...bool` and echo inlined 3x: can wait
- `stateless_test.go:1113` weak conflict assertion: can wait (largely addressed in F2)
- `cli.go:280` usage omits `--stateless`: can wait
- `docs/site/cli.md` paragraph order: can wait
- copy test patches deck blank lines: can wait
- `CanonicalStateless` pins `adoptPlatform`: can wait
- `-race` not re-run after the argv fix: can wait (Task 4 race gates ran)
- re-ship with changed declaration plus rebuilt bytes gets a generic conflict: can wait
- first-ship race maps to 502 by string match: can wait
- C03 prefixed "ship: manifest: ": can wait
**Task 2**
- pre-exec refusals recorded terminal `failed`: **must fix before merge** (I2)
- legacy records without `record_seq` never bump serial: can wait (check that the smoke instance's record has `record_seq`, otherwise re-wakes refuse until the backstop pass)
- `Deploy.Previous` never filled: can wait
- `failures.go:1349` ignores record evidence and never prunes `replica_releases`: can wait
- replica routes registered inside `registerCLIRoutes`: can wait
- Tick holds `opMu` across the network: **must fix before merge** (I3; its effect reaches stateful apps)
- authority expiry between commit and replay: can wait
- release handler checks term first: can wait
- renew against a retired record treated as transient: can wait
- retire mid-release drops the coordinator: can wait
- dead `held` branch and duplicated mapping: can wait
- store corruption retried as 503: can wait
**Task 3a**
- `%w` on fallback: can wait (resolved by N1)
- `SetServingMode` on every wake including workers: **must fix before merge** (I1)
- stateless first wake skips health budget and recovery selection: can wait
- import grouping: can wait
- planned stateful wake with changed staged copy refuses before the lease (from base): can wait
- lost "start <host>:" prefix, open mutex, mismatch text: can wait
- unplanned stateful wake reads the live link before the lease, so a repoint runs the superseded build: **must fix before merge** (it goes away with the C1 fix)
- cached digest feeds `declinedLivePin`/sidecar: can wait
- `ensureLiveLink`/Materialize before the lease: **must fix before merge** (same C1 scope, stateful pre-lease work)
- rootfs build discovered stateless only under the lease: can wait
**Task 3b**
- the C06 sentinel wraps conflict ALERTs and claims "existing copies keep serving" on a first copy: can wait (fix the wording before real users)
- follower reads sealed items up to 3x: can wait
- import grouping and `p.mu` held across I/O: can wait
- `hostfiles.Load` before checking `RetryAt`: can wait (see M2)
- SplitBackend bare `ErrFenced`: can wait
- non-held Acquire errors set no retry time: can wait
**CI fix**
- missing-row swap runs `storageMode` before the fence; claim fixture grouping: can wait (the C1 fix shrinks it)
**Task 4**
- rollback reads the target manifest up to 3x: can wait
- local operator `PromoteOnLadder` bypasses the console floor: can wait
- unseed guard relies on `SetServingMode` (log only): can wait
- a stale `canary/<branch>` platform pointer refuses every stateless selection: can wait for merge, **must resolve before the dev smoke** (see the R22 concern)
- pointer deleted between list and GET refuses; RootSigner vs `ReleasePub`; stale `reqmemo` comment: can wait (`rootfsfloor.go` uses the same RootSigner key, so they match in production)
### Ruling concerns
- **R22.** Requiring every platform channel pointer to be at or above v0.34.0 includes abandoned `canary/<branch>` pointers. That will likely block the dev smoke, with no override. R21's own reasoning says a lagging box only runs the build stateful at copies=1, which is harmless. So the floor is low-stakes, and a brittle superset is the wrong trade. Better options:
- judge only the channels boxes actually report following, from the box reports already memoized per write request; or
- ignore pointers that no box follows.
- **R18.** The ruling itself is sound. But it is being implemented as "consult the canonical manifest on every stateful wake", which causes C1. R18 is compatible with the immutable-manifest memo, so the ruling stands and the implementation should change.
- **R13 / R10.** Using the reconcile cache as the observation source is right for request budget. But together with the deferred legacy `record_seq` minor, a re-wake can see stale deploy state and refuse with SR-1-C05 until the backstop pass. Make sure the smoke uses an instance whose record has `record_seq`.
### Declined to judge
- The HA ownership agreement (#511, R2): it covers Plans 2-3, outside Plan 1.
- Census verdict quality: independent #280 reviewers approved each task, and I didn't re-run census.
- The live dev smoke and operator-evidence note: excluded by the brief (R4).
- Paul's own copy review of the delegated rows (R1, R6, R7): a process choice, not code.
- Full-suite CI results: CI is the authority; I only ran focused tests.
- Multi-copy behaviour and the `StatelessReplicasFloor` gate: Plan 2+.
- Whether `docs/site` publishes on merge: it's a deploy-process question, and the text itself is approved.
- The `bindingBlocked` cross-box clock rules: unchanged existing behaviour.
### Assessment
**Ready to merge (dormant, default-off)?** With fixes
**Reasoning:** The stateless machinery is careful and well fenced: release-before-serve, coordinator term fencing and follower no-mint all hold, and the five Review Focus tests pass. But the branch is not inert for existing apps. Every stateful wake (and config/recovery swap) now does a canonical manifest GET plus an uncached full artifact hash before the lease, and writes `serving_version` on the wake's critical path. That changes the latency, bucket dependence and visible status of every app. C1, I1 and I3 must be fixed for the stateful merge gate. I2 should be fixed before the dev smoke, or a routine restart mid-deploy wedges a stateless app.
Relevant files: `internal/activator/activator.go`, `internal/activator/stateless.go`, `internal/activator/statelessrelease.go`, `internal/activator/swap.go`, `internal/release/runtime_selection.go`, `internal/host/agent.go`, `internal/console/rootfs.go` (all under `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-1/`).
Note for the controller: inside the sandbox the default Go cache (`~/.cache/go-build`) is read-only. I ran the focused tests outside the sandbox with the default cache and left `GOCACHE` alone.</result>
<usage><subagent_tokens>256339</subagent_tokens><tool_uses>63</tool_uses><duration_ms>688554</duration_ms></usage>
</task-notification>
@@ -59,7 +59,12 @@ var errStatelessSecretsWaiting = errors.New("the new copy is waiting for the ins
var errStorageDeclaration = errors.New("could not verify this build's storage declaration, so it was not started")
+type storageProjectionKey struct{}
+
func (a *Service) storageMode(ctx context.Context, rt registry.Route, id release.StagedIdentity) (bool, string, error) {
+ if projected, _ := ctx.Value(storageProjectionKey{}).(bool); projected {
+ rt.Stateless = true
+ }
if observed, ok := ctx.Value(storageModeKey{}).(storageModeObservation); ok && observed.id == id && observed.account == rt.Account && observed.app == rt.App {