carlos / platform Public

edge-held-streams: plan rev 2 after Astra plan round 1 (#432)

Summary

Accepts all twelve plan-round-1 findings: transition-site guard instead of a stop-call allowlist, real-child witnesses in internal/activator, exported HeldConfig, write deadlines reset after each write (HTTP/2), slotWriter on the hold branch, the mark recorded before stripping and kept on tunnel routes, lifecycle simulation, per-host counts, corrected test selectors, mktemp scratch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ae6eb493fd5836f1814cc081fccf6ff0ad042463 parent cd61c9d
2 files changed, +287 −68
  • docs/superpowers/plans/2026-10-28-edge-held-streams.md +112 −68
  • docs/superpowers/plans/CODEX-FINDINGS-edge-held-streams-plan.md +175 −0

CI passed — run details

diff --git a/docs/superpowers/plans/2026-10-28-edge-held-streams.md b/docs/superpowers/plans/2026-10-28-edge-held-streams.md
index 47faee011..88041ff0b 100644
--- a/docs/superpowers/plans/2026-10-28-edge-held-streams.md
+++ b/docs/superpowers/plans/2026-10-28-edge-held-streams.md
@@ -4,7 +4,7 @@
**Goal:** A browser's `EventSource` opened with `carlos_hold=1` on a hibernating instance is held by the edge while the instance sleeps and resumed with `Last-Event-ID` when it wakes, without ever counting as activity or waking anything.
-**Architecture:** The activator gains a held-leg registry: it admits each upstream leg with the sidecar rules, records it against the entry and generation under `a.mu`, and cancels it synchronously in `beginStopLocked` and in the swap's switch. The edge classifies marked requests once, right after upstream lookup, and runs each held stream as one stream task that relays whole SSE events from legs served through the route's own `up.proxy`, writes bare-comment heartbeats, and reopens on a wake hook or a 25 s tick.
+**Architecture:** The activator gains a held-leg registry: it admits each upstream leg with the sidecar rules, records it against the entry and generation under `a.mu`, and cancels it synchronously at the only three places a serving process can stop serving: `beginStopLocked` (the one transition out of `actAwake`), `installProcLocked` (the one place an entry's process changes, which is inside the swap's switch), and every removal of an entry. The edge classifies marked requests once, right after upstream lookup, and runs each held stream as one stream task that relays whole SSE events from legs served through the route's own `up.proxy`, writes bare-comment heartbeats, and reopens on a wake hook or a 25 s tick.
**Tech Stack:** Go (stdlib `net/http`, `httputil.ReverseProxy`), existing `internal/activator`, `internal/edge`, `internal/status`, `internal/host` packages.
@@ -20,7 +20,7 @@
- Heartbeat is the bare line `: ping\n` with no blank line after it.
- Edge-owned held response headers: `200`, `Content-Type: text/event-stream`, `Cache-Control: no-store`.
- Must cross-compile for darwin and windows (`GOOS=darwin go vet ./internal/edge ./internal/activator`, same for windows).
-- Tests that bind unix sockets (activator, edge, host) run **outside the Bash sandbox** with `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false` (`mkdir -p /tmp/k` first; empty it when done). Run only the touched packages with `-run`; never `make test` or `go test ./...` locally (CI runs the full suite).
+- Tests that bind unix sockets (activator, edge, host) run **outside the Bash sandbox** in a scratch root of your own: `T=$(mktemp -d /tmp/hsXXXX)` (short, because unix socket paths cap at 107 bytes and the session `$TMPDIR` is too long for the activator's longest test path), then `TMPDIR=$T GOFLAGS=-buildvcs=false go test …`, then `rm -rf "$T"`. Below, `$T` means that directory. Remove only the directory you created; leave `GOCACHE` at its default. Run only the touched packages with `-run`; never `make test` or `go test ./...` locally (CI runs the full suite).
- No tenant names in code, tests or docs: use `shop.example.com`-style hosts.
- Commits end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`; each commit carries Prompt/Summary sections per the amadan skill.
@@ -39,8 +39,10 @@
**Files:**
- Create: `internal/activator/heldlegs.go`
- Create: `internal/edge/heldleg.go` (only the `HeldLeg` interface; `internal/activator` already imports `internal/edge`, so one declared type serves both packages and `*activator.Service` can satisfy `edge.Activator` in Task 3)
-- Modify: `internal/activator/activator.go` (`actEntry` gains `heldLegs`; `beginStopLocked` calls `cancelHeldLegsLocked(e, 0)` first; `Service` gains `heldWakeHook atomic.Pointer[func(string)]`)
-- Modify: `internal/activator/swap.go` (in the switch critical section, directly after `a.interruptCmdsLocked(e, retiring.gen.N, …)`, call `a.cancelHeldLegsLocked(e, retiring.gen.N)`)
+- Modify: `internal/activator/activator.go`: `actEntry` gains `heldLegs`; `Service` gains `heldWakeHook atomic.Pointer[func(string)]`; and the three cancellation points, each under `a.mu`:
+ - `beginStopLocked` (~line 2989; it holds the package's only `e.state = actStopping`, line 3003): `a.cancelHeldLegsLocked(e, 0)` as its first statement;
+ - `installProcLocked` (~line 3025; the only `e.proc =` assignment for an entry): when `e.gen.N != g.N`, `a.cancelHeldLegsLocked(e, e.gen.N)` before the assignment. The swap's switch (`swap.go` ~line 666) installs the successor through it, before `genRetired` and the retiring generation's drain, so no `swap.go` change is needed;
+ - every `delete(a.entries, e.host)` (today `activator.go` ~2031 and ~4766, `recoveryprobe.go` ~221, `swaphold.go` ~332): `a.cancelHeldLegsLocked(e, 0)` immediately before it.
- Modify: `internal/activator/activator.go` (wake success path near `close(e.ready)` ~line 2152), `internal/activator/recoveryprobe.go` (where `e.probeHeld = false`), `internal/activator/maintenance.go` (both `delete(a.fences, host)` sites): call `a.noteHeldAdmissible(host)` after `a.mu` is released
- Test: `internal/activator/heldlegs_test.go`
@@ -59,26 +61,40 @@
- `TestAdmitHeldLegAwakeNoActivity`: wake the host with one ordinary request, record `e.inflight` and `e.lastActive`; `AdmitHeldLeg` succeeds; both unchanged; `len(e.heldLegs) == 1`; after `leg.Done()`, 0.
- `TestBeginStopCancelsHeldLegsBeforeStop`: backend `Proc.Stop` records `legCtx.Err()` at call time; admit a leg, run the idle sweep past the window; assert the recorded error is `context.Canceled`.
- `TestAdmitHeldLegAfterStopRefused`: begin a stop; `AdmitHeldLeg` returns `ErrHeldAsleep`.
- - `TestHeldAdmissibleMatchesAdmit`: table over states (asleep, waking, awake, stopping, fenced, probeHeld, rep.Err()!=nil, proc exited, shutting down, Startup open): `HeldAdmissible(host)` is true iff an `AdmitHeldLeg` with an already-cancelled ctx returns nil.
+ - `TestHeldAdmissibleMatchesAdmit`: table over host states (asleep, awake, stopping, fenced, probeHeld, `rep.Err() != nil`, proc exited, shutting down, `Startup` nil, `Startup` closed, `Startup` still open): for each, `HeldAdmissible(host)` is true iff `AdmitHeldLeg` with a live `context.WithTimeout(ctx, 100*time.Millisecond)` returns nil without waiting (assert it returned in under 50 ms when admitted). Waking is excluded from the table: admission joins it, which is a wait by design.
+ - `TestAdmitHeldLegCancelledContext`: awake host, already-cancelled ctx → `context.Canceled`, no leg registered.
+ - `TestInstallProcCancelsPreviousGenLegs`: with generations on, admit a leg on generation N; install generation N+1 through `installProcLocked`; the leg's context is cancelled and a leg admitted afterwards is registered on N+1.
+ - `TestEntryRemovalCancelsHeldLegs`: a leg on an entry removed by a failed recovery probe is cancelled.
- `TestHeldWakeHookFires`: hook records hosts; a completed wake, a probe release and a fence lift each record the host once.
-- [ ] **Step 2: Run** `cd internal/activator && TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run 'TestAdmitHeldLeg|TestBeginStopCancelsHeldLegs|TestHeldAdmissible|TestHeldWakeHook' -count=1 .` (sandbox off). Expected: build failure, `AdmitHeldLeg` undefined.
+- [ ] **Step 2: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestAdmitHeldLeg|TestBeginStopCancelsHeldLegs|TestHeldAdmissible|TestHeldWakeHook|TestInstallProcCancels|TestEntryRemovalCancels' -count=1 ./internal/activator` (sandbox off). Expected: build failure, `AdmitHeldLeg` undefined.
- [ ] **Step 3: Implement** `heldlegs.go` and the call sites above. The wake hook is loaded and called only after `a.mu` is unlocked (same discipline as `genRetired`). Leg ids come from an `atomic.Uint64`.
-- [ ] **Step 4: Run** the Step 2 command, then `go test -run 'TestSidecar|TestServe' -count=1 .` to check the sidecar path is untouched. Expected: PASS.
+- [ ] **Step 4: Run** the Step 2 command, then `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestActivatorSidecarRequestsInvisibleToActivity|TestSidecar' -count=1 ./internal/activator` to check the sidecar contract is untouched. Expected: PASS.
- [ ] **Step 5: Commit** `activator: held-leg admission, registry and synchronous cancellation (#432)`.
-### Task 2: Stop-site guard and the swap simulation's held-leg invariants
+### Task 2: Transition-site guard and the activator simulation's held-leg invariants
+
+**Why a transition guard, not a stop-call guard (plan review r1 P1-4).** The package has about 25 process-termination call sites (`stopMember`, `genChildProof`, `reapMembersLocked`, `reapUnprovenWake` in `opset.go`; `respawnWorkerLocked`; `killFailed` in `wakeplan.go`; the start-failure kills in `backend_exec.go`; `startRootfs`, `killResidentGens`; `claimwake.go`'s; the sidecar stops), most of them for processes that never served. A leg can only be registered on the **current** generation of an **`actAwake`** entry (Task 1's predicate). So a process a leg is connected to can only be told to stop after one of three things, and each cancels first: the entry leaves `actAwake` (only `beginStopLocked` assigns `actStopping`), the entry's current process changes (only `installProcLocked` assigns `e.proc`), or the entry is removed (`delete(a.entries, …)`). The guard pins those three facts; the simulation checks the property itself.
**Files:**
- Create: `internal/activator/heldlegs_guard_test.go`
- Modify: `internal/activator/swap_sim_test.go`
**Interfaces:**
-- Consumes: Task 1's `AdmitHeldLeg`, `HeldLeg`, `actEntry.heldLegs`.
-
-- [ ] **Step 1: Write `TestProcessStopSitesCancelHeldLegs`** (guard): scan `internal/activator/*.go` (non-test) for `.Stop(` calls on a `Proc` and for `KillGen(`; every hit must be in an allowlist map `file:function → reason`. Seed the allowlist with today's sites and their reasons: `stop` (reached only via `beginStopLocked`), `finishPendingStop`/`retryPendingStop` (retries of a stop `beginStopLocked` began), `reapShedLocked` (shed swap members never admitted legs: a member is not current until the switch), `cleanupFailedWake` (never `actAwake`, so no legs), `reapStraySidecarsLocked`/`replaceSidecar` and the sidecar stop helpers (sidecar processes, not instance legs). A new site fails the test with a message naming the file and function and pointing at §3.2.
-- [ ] **Step 2: Extend `TestSwapInvariants`**: add a random action "admit a held leg on a random host" (`AdmitHeldLeg` with a short-lived ctx; on success record `{host, gen N, proc id, leg}` in `simWorld`), and "finish a held leg" (`Done()`). Add invariant **I4** in `simProc.Stop` and `simBackend.KillGen`: any recorded leg on that process or generation whose `Context().Err() == nil` is a violation `I4: p%d stopped with held leg %d uncancelled`. Add **I5** at each step: no recorded leg's admission changed the host entry's `inflight` (sample `inflight` before and after the admit under `a.mu`). Keep the existing seeds count and PAR.
-- [ ] **Step 3: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false nice -n 19 go test -run 'TestProcessStopSites|TestSwapInvariants' -count=1 ./internal/activator` (sandbox off). Expected: PASS. Then remove the `cancelHeldLegsLocked` call from the swap switch, rerun, and confirm I4 fires; restore it. (Mutation must still compile.)
-- [ ] **Step 4: Commit** `activator: guard process-stop sites and simulate held legs through swaps (#432)`.
+- Consumes: Task 1's `AdmitHeldLeg`, `edge.HeldLeg`, `actEntry.heldLegs`, `cancelHeldLegsLocked`.
+
+- [ ] **Step 1: Write `TestHeldLegTransitionSites`** (guard), parsing the package's non-test files with `go/ast` (not regexes), receiver-aware:
+ - every assignment of `actStopping` to a `.state` field is inside `(*Service).beginStopLocked`, and `beginStopLocked`'s first statement calls `cancelHeldLegsLocked`;
+ - every assignment to the `proc` field of a value of type `*actEntry` is inside `(*Service).installProcLocked`, and that function calls `cancelHeldLegsLocked` before the assignment (`wakeTarget`/`genMember` `proc` fields are other types and are not matched);
+ - every `delete(a.entries, …)` call is immediately preceded, in the same block, by a `cancelHeldLegsLocked(…, 0)` call;
+ - failures name the file, line and enclosing function, and point at spec §3.2.
+ Then mutate: add a second `e.state = actStopping` inside an existing function (for example `Bounce`) and confirm the guard fails; add a `delete(a.entries, …)` without the call and confirm it fails; restore.
+- [ ] **Step 2: Extend `TestSwapInvariants`** with held legs:
+ - actions: "admit a held leg" on a random host, and "finish a held leg" (`Done()`); on admit, record `{host, gen N, proc id, leg}` in `simWorld`;
+ - **I4** in `simProc.Stop` and `simBackend.KillGen`: a recorded leg on that process or generation whose `Context().Err() == nil` is a violation `I4: p%d stopped with held leg %d uncancelled`;
+ - **I5** (activity invisibility), observed without interference: the admit action first takes a per-host sim lock that the sim's ordinary-request actions also take, so no ordinary request starts or ends on that host during the admit. Under it, read `e.inflight`, `e.lastActive` and the backend's start count for the host, call `AdmitHeldLeg`, read them again: any change is `I5: held admission on %s changed %s`. An admit on an asleep host must leave the start count unchanged (no wake).
+ Keep the existing seeds count and PAR.
+- [ ] **Step 3: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false nice -n 19 go test -run 'TestHeldLegTransitionSites|TestSwapInvariants' -count=1 ./internal/activator` (sandbox off). Expected: PASS. Mutate: remove the `cancelHeldLegsLocked` call from `installProcLocked`; rerun and confirm I4 fires on an overlap swap; restore. (Mutations must still compile.)
+- [ ] **Step 4: Commit** `activator: guard held-leg transition sites; simulate held legs through swaps (#432)`.
### Task 3: Edge seam and writer plumbing
@@ -104,7 +120,7 @@
- `func (c *countingWriter) Unwrap() http.ResponseWriter`
- [ ] **Step 1: Write `TestCountingWriterSupportsWriteDeadline`**: wrap an `httptest` server's writer in `countingWriter`; `http.NewResponseController(cw).SetWriteDeadline(time.Now().Add(time.Second))` returns nil, and `Flush` via the controller returns nil.
-- [ ] **Step 2: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run TestCountingWriterSupportsWriteDeadline -count=1 ./internal/edge` (sandbox off). Expected: FAIL (`feature not supported`).
+- [ ] **Step 2: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run TestCountingWriterSupportsWriteDeadline -count=1 ./internal/edge` (sandbox off). Expected: FAIL (`feature not supported`).
- [ ] **Step 3: Implement** the interface change, `Unwrap`, and the fakes. Add a compile-time assertion in `internal/host` (which imports both): `var _ edge.Activator = (*activator.Service)(nil)`.
- [ ] **Step 4: Run** Step 2's command, then `go vet ./internal/edge ./internal/activator ./internal/host`. Expected: PASS, no vet errors.
- [ ] **Step 5: Commit** `edge: held-leg methods on the Activator seam; countingWriter unwraps (#432)`.
@@ -141,43 +157,46 @@
**Files:**
- Create: `internal/edge/heldstream.go`
-- Test: `internal/edge/heldstream_test.go`
+- Test: `internal/edge/heldstream_test.go`, `internal/edge/heldstream_sim_test.go`
**Interfaces:**
- Consumes: Task 3's `Activator` (via `e.act`), Task 4's `sseReader`.
- Produces:
```go
- type heldConfig struct {
- PerHost, PerBox int
- MaxHold, Commit, LegHeader, WriteDeadline, Tick time.Duration
- ReopenSpacing, ShortLeg, BackoffCap time.Duration
- ShortLegsToClose int
+ // HeldConfig is exported so tests in other packages (Task 8, internal/activator) can shorten it.
+ type HeldConfig struct {
+ PerHost, PerBox int
+ MaxHold, Commit, LegHeader, WriteDeadline, Tick time.Duration
+ ReopenSpacing, ShortLeg, BackoffCap time.Duration
+ ShortLegsToClose int
}
- var defaultHeldConfig = heldConfig{64, 4096, time.Hour, 2*time.Second, 10*time.Second, 10*time.Second, 25*time.Second, time.Second, 30*time.Second, 30*time.Second, 5}
+ var DefaultHeldConfig = HeldConfig{64, 4096, time.Hour, 2*time.Second, 10*time.Second, 10*time.Second, 25*time.Second, time.Second, 30*time.Second, 30*time.Second, 5}
+ func (e *Edge) SetHeldConfig(c HeldConfig) // before serving; replaces the held set
type heldSet struct { /* per-host map of *heldStream, box count, counters (Task 7) */ }
- func newHeldSet(cfg heldConfig) *heldSet
+ func newHeldSet(cfg HeldConfig) *heldSet
func (s *heldSet) wake(host string) // non-blocking: signal every stream on host
func (s *heldSet) closeHost(host string) // close every stream on host (reload: no longer managed)
+ func (s *heldSet) hosts() []string // hosts with at least one held stream
// serveHeld runs one held stream to completion. proxy is up.proxy; rt is up.route.
func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler)
func stripHoldMarker(rawQuery string) (stripped string, marked bool)
```
- `Edge` gains `held *heldSet`, built in `New` with `defaultHeldConfig`; tests override `e.held` with a short config.
+ `Edge` gains `held *heldSet`, built in `New` with `DefaultHeldConfig`.
Behaviour, all from §3.3, §3.6, §3.7 (read them):
- Register in the host's set first; over a cap → write `200`, `Content-Type: text/event-stream`, `Cache-Control: no-store`, body `retry: 30000\n\n`, return. Never calls the activator.
- Leg: `legReq := r.Clone(leg.Context())`, `RawQuery` stripped, hop-by-hop headers and `X-Carlos-Sidecar` removed, `Accept-Encoding: identity`, `Last-Event-ID` = cursor (omit when no cursor). Run `proxy.ServeHTTP(legWriter, legReq)` in its own goroutine with `recover()` turning `http.ErrAbortHandler` into "leg ended". `legWriter` is an internal `http.ResponseWriter`+`Flusher` that delivers status and a header copy once, then pipes body bytes into an `io.Pipe` read by `newSSEReader`.
- First leg (browser has no response): 200 identity `text/event-stream` → copy captured headers minus `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, hop-by-hop, with `Cache-Control: no-store`, then relay; any 3xx → `204`; 200 non-SSE or non-identity → `502` (throttled log per host); any other status → copy status, headers and body as captured.
-- Commit: if no response 2 s after start, or admission refused, write the edge's own 200 headers and flush; if a cursor exists, write `id: <cursor>\n\n` immediately after.
+- Commit: if no response `Commit` after start, or admission refused, write the edge's own 200 headers and flush; if a cursor exists, write `id: <cursor>\n\n` immediately after.
- Relay: write each non-comment-only block's `Raw`, flush, update the cursor when `HasID`. Drop comment-only blocks.
- Heartbeat: `: ping\n` + flush after `Tick` of downstream silence, only between blocks. Same tick: no open leg and no pending reopen → `HeldAdmissible(host)` → reopen.
- Reopen rule and short legs per §3.6; a leg cancelled by the activator while the host is admissible (swap) or a reopen after a wake is not a short leg.
- Reopen answer not 200 identity SSE (including 3xx) → close the browser's stream.
-- Every downstream write is preceded by `http.NewResponseController(w).SetWriteDeadline(now+WriteDeadline)`; an error ends the stream.
+- **Write deadlines bound one write, never the idle time (plan review r1 P1-3).** Each downstream write-and-flush is `rc.SetWriteDeadline(now+WriteDeadline)`, write, flush, then `rc.SetWriteDeadline(time.Time{})` before the task waits again. On HTTP/2 an armed deadline resets the stream when it expires even with no write pending (Go's `h2_bundle.go`), so leaving it armed across a 25 s heartbeat gap would kill every held stream after 10 s. A write or flush error, including a deadline, ends the stream.
- Max hold: close at the next block boundary after `MaxHold`.
- The stream task is the only goroutine writing `w`.
-- [ ] **Step 1: Write the failing tests** with a scripted fake activator (`AdmitHeldLeg` driven by a test-controlled `asleep` flag and returning legs whose contexts the test can cancel; `HeldAdmissible` mirrors the flag) and a fake `proxy` `http.Handler` that serves scripted SSE (ids, closes on demand). Use `httptest.NewServer` around a handler that calls `e.serveHeld` so real flushing and deadlines apply. Short config: Tick 50 ms, Commit 20 ms, ReopenSpacing 10 ms, ShortLeg 200 ms, BackoffCap 100 ms, MaxHold 2 s.
+- [ ] **Step 1: Write the failing tests** with a scripted fake activator (`AdmitHeldLeg` driven by a test-controlled `asleep` flag and returning legs whose contexts the test can cancel; `HeldAdmissible` mirrors the flag; `ServeHTTP` counts calls) and a fake `proxy` `http.Handler` that serves scripted SSE (ids, closes on demand). Use `httptest.NewServer` around a handler that calls `e.serveHeld` so real flushing and deadlines apply. Short config: Tick 50 ms, Commit 20 ms, ReopenSpacing 10 ms, ShortLeg 200 ms, BackoffCap 100 ms, MaxHold 2 s, WriteDeadline 30 ms.
- `TestHeldAsleepCommitsAndPings`: asleep → response 200 with `Cache-Control: no-store`; within 3 ticks the body contains `: ping\n` and never `: ping\n\n`.
- `TestHeldSeedsCursor`: request with `Last-Event-ID: 42`, asleep → body begins `id: 42\n\n`.
- `TestHeldResumeSendsLastEventID`: awake, proxy sends `id: 1`, `id: 2`, then the test cancels the leg and flips asleep; flips awake and calls `held.wake(host)`; the second leg's request has `Last-Event-ID: 2` and no `carlos_hold` in `RawQuery`.
@@ -188,40 +207,53 @@ Behaviour, all from §3.3, §3.6, §3.7 (read them):
- `TestHeldOverCapRetry`: `PerHost: 1`; second stream gets `retry: 30000\n\n` and EOF; activator admission count unchanged.
- `TestHeldDropsCommentOnlyBlocks`: proxy sends `: app ping\n\n` then `id: 3\ndata: x\n\n` → client body has the second block, not the first.
- `TestHeldStripsSidecarHeader`: client sends `X-Carlos-Sidecar: 1`; the leg request has no such header.
+ - `TestHeldHTTP2IdleSurvivesWriteDeadline`: `httptest.NewUnstartedServer`, `EnableHTTP2 = true`, `StartTLS`; HTTP/2 client; asleep; config `Tick 100 ms`, `WriteDeadline 30 ms`; the stream stays open and receives at least 4 heartbeats over 500 ms. Mutate: skip the deadline reset; confirm it fails; restore.
+ - `TestHeldBlockedWriteEnds`: a client that stops reading (raw TCP conn, small receive buffer) while the proxy floods events → the stream task ends within `WriteDeadline` plus one tick, and the held set count returns to 0.
- `TestStripHoldMarker`: `"a=1&carlos_hold=1&b=%2F"` → `"a=1&b=%2F", true`; `"carlos_hold=2"` → unchanged, false; `"x=1"` → unchanged, false; byte-for-byte preservation of the remaining pairs and their encoding.
-- [ ] **Step 2: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run 'TestHeld|TestStripHoldMarker' -count=1 ./internal/edge` (sandbox off). Expected: FAIL, undefined.
-- [ ] **Step 3: Implement** `heldstream.go`.
-- [ ] **Step 4: Run** Step 2's command three times (`-count=3`) to shake out timing flakes. Expected: PASS.
-- [ ] **Step 5: Commit** `edge: the held-stream task (#432)`.
+- [ ] **Step 2: Write `TestHeldStreamLifecycleSim`** in `heldstream_sim_test.go` (plan review r1 P2-1): a model activator implementing `Activator` with host states `asleep`, `waking`, `awake`, `stopping`, `probeHeld`, `fenced`, changed at random by the sim; admissibility follows spec §3.5; on each transition to admissible it calls the wake hook, dropped with probability 0.5 and delayed at random otherwise; on each transition away from admissible it cancels every leg it admitted (as Task 1 does). N = 1..8 streams per seed, fake proxy as above, short config, 300 seeds, serial, `nice -n 19`. Invariants checked every 5 ms:
+ - **H1**: the model's `ServeHTTP` is never called, and no leg is admitted while the model is not admissible;
+ - **H2**: while the model has been admissible for longer than `Tick + ReopenSpacing + BackoffCap`, every stream not closed has an open leg (no silent stream past one tick, spec G4);
+ - **H3**: a stream never has two legs open at once.
+- [ ] **Step 3: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestHeld|TestStripHoldMarker' -count=1 ./internal/edge` (sandbox off). Expected: FAIL, undefined.
+- [ ] **Step 4: Implement** `heldstream.go`.
+- [ ] **Step 5: Run** Step 3's command with `-count=3` to shake out timing flakes. Expected: PASS. Mutate: drop the tick's `HeldAdmissible` check; confirm H2 fires; restore.
+- [ ] **Step 6: Commit** `edge: the held-stream task (#432)`.
### Task 6: Dispatch wiring, cache bypass, reload and the wake hook
**Files:**
- Modify: `internal/edge/edge.go` (`ServeHTTP`, `Reload`)
- Modify: `internal/edge/assetcatch.go` (`serveAssetLocal`, `serveAssetFillForHop`, `serveAssetFar`: return false for a marked request)
-- Modify: `internal/host/agent.go` (after the edge and activator are both built: `act.SetHeldWakeHook(edge.HeldWake)`)
-- Test: `internal/edge/heldstream_dispatch_test.go`
+- Modify: `internal/host/agent.go` (after the edge and activator are both built: `act.SetHeldWakeHook(e.HeldWake)`)
+- Test: `internal/edge/heldstream_dispatch_test.go`, and a tunnel witness in `internal/edge/tunnel_e2e_test.go`
**Interfaces:**
-- Consumes: Task 5's `serveHeld`, `stripHoldMarker`, `heldSet.closeHost`, `heldSet.wake`.
-- Produces: `func (e *Edge) HeldWake(host string)` (calls `e.held.wake`); `func isHeldStreamRequest(r *http.Request) bool` (GET, `Accept` contains `text/event-stream`, `!isUpgradeRequest(r)`).
+- Consumes: Task 5's `serveHeld`, `stripHoldMarker`, `heldSet.closeHost`, `heldSet.hosts`, `heldSet.wake`.
+- Produces: `func (e *Edge) HeldWake(host string)` (calls `e.held.wake`); `func isHeldStreamRequest(r *http.Request) bool` (GET, `Accept` contains `text/event-stream`, `!isUpgradeRequest(r)`); a request-context flag `heldMarkKey{}` carrying whether the **original** request was marked, set once and read by the cache and asset checks (`func markedRequest(r *http.Request) bool`).
Placement (§3.8), in `Edge.ServeHTTP`:
-1. Directly after the `if !ok { … }` block that follows `up, ok := e.lookupUpstreamPath(host, r.URL.Path)` (~line 1666): compute `marked`. If `up.hibernating && up.route.Hibernate && marked`: if `!isHeldStreamRequest(r)` answer `400` and return; else set a local `held := true`. If marked on any other route: strip the marker from `r.URL.RawQuery` and continue as an ordinary request.
-2. Immediately after the password gate (`e.gate.Admit`, ~line 1926) and before the upgrade branch: `if held { if !e.planThrottleAdmit(w, r, up) { return }; release, ok := e.rateAdmit(w, r, up); if !ok { return }; if release != nil { defer release() }; e.serveHeld(w, r, up.route, up.proxy); return }`.
-3. Shared cache: `cacheable` (~line 2028) gains `&& !hasHoldMarker(r)`, so every edge, including a tunnel hub or a forwarding route, skips lookup and storage for marked requests. `hasHoldMarker` reads `r.URL.RawQuery` via `stripHoldMarker`.
-4. `Reload`: after building the new map, for every host that has held streams and is no longer `hibernating` in the new map, call `e.held.closeHost(host)`.
+1. **Record the mark before anything can strip it** (plan review r1 P1-1): at the top of `ServeHTTP`, before the far-asset/backhaul branch, `_, marked := stripHoldMarker(r.URL.RawQuery)` and store `marked` in the request context (`heldMarkKey{}`). Nothing below re-derives it from the query.
+2. Directly after the `if !ok { … }` block that follows `up, ok := e.lookupUpstreamPath(host, r.URL.Path)` (~line 1666), when `marked`:
+ - `up.hibernating && up.route.Hibernate`: if `!isHeldStreamRequest(r)` answer `400` and return; else set a local `held := true` (the marker is stripped later, inside `serveHeld`, per leg);
+ - `up.viaTunnel` (tunnel or fleet forwarding): **leave the query untouched**; the receiving edge classifies it;
+ - any other route served here (always-on instance, resident, service, static): strip the marker from `r.URL.RawQuery` and continue as an ordinary request.
+3. Immediately after the password gate (`e.gate.Admit`, ~line 1926) and before the upgrade branch, when `held`: `planThrottleAdmit`; then `release, ok := e.rateAdmit(w, r, up)`; if `!ok` return; if `release != nil` { `defer release()`; `w = &slotWriter{ResponseWriter: w, release: release}` }, exactly as the ordinary path does at ~line 2056, so the slot comes back when the held response's headers are written, not when the stream ends (plan review r1 P1-2); then `e.serveHeld(w, r, up.route, up.proxy)`; return. `slotWriter` already forwards `Flush` and `Unwrap`.
+4. Shared cache: `cacheable` (~line 2028) gains `&& !markedRequest(r)`, so every edge, a tunnel hub or a forwarding route included, skips lookup and storage for marked requests whatever happened to the query.
+5. Asset catch: the three asset functions return false when `markedRequest(r)`.
+6. `Reload`: after building the new map, for every host in `e.held.hosts()` that is not `hibernating` in the new map, call `e.held.closeHost(host)`.
- [ ] **Step 1: Write the failing tests** (edge with a registry route `shop.example.com`, `Hibernate: true`, socket route, and a counting fake activator):
- `TestMarkedRequestNeverReachesActivator`: for POST, PUT, GET without SSE `Accept`, and an upgrade, each with `?carlos_hold=1` → 400 and activator `ServeHTTP` count 0.
- `TestMarkedLoginPostIs400`: gated route, marked POST to `/.carlos/gate` with valid credentials → 400, not 303.
- `TestHeldStreamRequestDispatchesToHold`: marked GET with `Accept: text/event-stream`, activator asleep → 200 SSE from the edge, activator `ServeHTTP` count 0.
- - `TestMarkerStrippedOnAlwaysOnRoute`: non-hibernating route → upstream sees the query without `carlos_hold`, normal 200.
- - `TestMarkedRequestSkipsSharedCache`: cache enabled, route forwarded via tunnel (or any non-hibernating route), upstream answers 200 SSE with `Cache-Control: public, max-age=60` and ends; a second identical marked request reaches the upstream again (upstream hit count 2).
+ - `TestHeldStreamFreesRateSlotAtHeaders`: rate limit on with an instance concurrency of 1; one held stream open (headers received); a second, ordinary request to the same host is admitted, not shed.
+ - `TestMarkerStrippedOnAlwaysOnRoute`: non-hibernating local route → upstream sees the query without `carlos_hold`, normal 200.
+ - `TestMarkedRequestSkipsSharedCacheAfterStrip`: cache enabled, always-on route (the marker is stripped), upstream answers 200 SSE with `Cache-Control: public, max-age=60` and ends; a second identical marked request reaches the upstream again (upstream hit count 2).
- `TestReloadClosesHeldStreamsForUnmanagedHost`: hold a stream, flip the route to `Hibernate: false`, `Reload()` → client body ends.
-- [ ] **Step 2: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run 'TestMarked|TestHeldStreamRequest|TestMarkerStripped|TestReloadClosesHeld' -count=1 ./internal/edge` (sandbox off). Expected: FAIL.
+ - In `tunnel_e2e_test.go`, `TestTunnelForwardsHoldMarkerAndSkipsCache` (mandatory, using that file's hub-and-box harness): a marked SSE request to a tunnel-served host arrives at the receiving box's edge with `carlos_hold=1` still in its query, its activator's `ServeHTTP` count stays 0 (it is held there), and the hub's shared cache stores nothing for it.
+- [ ] **Step 2: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestMarked|TestHeldStreamRequest|TestHeldStreamFreesRateSlot|TestMarkerStripped|TestReloadClosesHeld|TestTunnelForwardsHoldMarker' -count=1 ./internal/edge` (sandbox off). Expected: FAIL.
- [ ] **Step 3: Implement** the placement above and the asset-catch bypasses; wire the hook in `internal/host/agent.go`.
-- [ ] **Step 4: Run** Step 2's command, then `go test -run 'TestGate|TestCache|TestRate|TestAsset' -count=1 ./internal/edge` and `go vet ./internal/host`. Expected: PASS.
+- [ ] **Step 4: Run** Step 2's command, then `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestGate|TestCache|TestRate|TestAsset|TestTunnel' -count=1 ./internal/edge` and `go vet ./internal/host`. Expected: PASS.
- [ ] **Step 5: Commit** `edge: classify carlos_hold requests, hold branch after the gate, no shared caching of marked requests (#432)`.
### Task 7: Counters in the box status
@@ -237,44 +269,52 @@ Placement (§3.8), in `Edge.ServeHTTP`:
```go
// internal/status
type HeldStreams struct {
- Held int `json:"held"`
- Resumes int64 `json:"resumes"`
- OverCap int64 `json:"over_cap"`
- Closes map[string]int64 `json:"closes,omitempty"` // reasons: refused, redirect, max_hold, short_legs, unmanaged, write_deadline
+ Held int `json:"held"`
+ Hosts map[string]int `json:"hosts,omitempty"` // held now, per host; hosts with none are absent
+ Resumes int64 `json:"resumes"`
+ OverCap int64 `json:"over_cap"`
+ Closes map[string]int64 `json:"closes,omitempty"` // reasons: refused, redirect, max_hold, short_legs, unmanaged, write_deadline
}
// internal/edge
func (e *Edge) HeldStreamStats() status.HeldStreams
```
- Box totals only in the snapshot (the snapshot is a published wire shape; per-host counts stay in `heldSet` for logs). Additive field, `omitempty` on the pointer; nil when the edge has no held streams and has never held one.
+ Additive field, `omitempty` on the pointer; nil when the edge has never held a stream. Per-host counts are spec §3.9's (plan review r1 P2-3).
-- [ ] **Step 1: Write the failing tests**: `TestHeldStreamStatsCounts` (one held, one over cap, one closed by redirect → `Held 1, OverCap 1, Closes["redirect"] 1`); `TestSnapshotCarriesHeldStreams` (probe with `HeldStreams` set → `box.Metrics.HeldStreams` equal; nil → absent key in JSON).
-- [ ] **Step 2: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run 'TestHeldStreamStats|TestSnapshotCarriesHeldStreams' -count=1 ./internal/edge ./internal/status` (sandbox off). Expected: FAIL.
+- [ ] **Step 1: Write the failing tests**: `TestHeldStreamStatsCounts` (one held on `a.example.com`, one over cap, one closed by redirect → `Held 1, Hosts{"a.example.com":1}, OverCap 1, Closes["redirect"] 1`; after the held stream closes, `Hosts` has no entry for the host); `TestSnapshotCarriesHeldStreams` (probe with `HeldStreams` set → `box.Metrics.HeldStreams` equal; nil → absent key in JSON).
+- [ ] **Step 2: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run 'TestHeldStreamStats|TestSnapshotCarriesHeldStreams' -count=1 ./internal/edge ./internal/status` (sandbox off). Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** Step 2's command. Expected: PASS.
- [ ] **Step 5: Commit** `edge, status: held-stream counters in the box snapshot (#432)`.
-### Task 8: Production-wired witnesses
+### Task 8: Production-wired witnesses with a real child
+
+**Why here (plan review r1 P1-5, P1-6).** `internal/host`'s `wakeFixture` app is in-process and its stop is `srv.Close()`, so it cannot show a graceful drain waiting on a stream. The activator's own tests run a **real child**: `stageServingLive` (`internal/activator/activator_test.go` ~6240) points `live/<host>` at the test binary, `TestMain` runs `fakeAppMain` when `ACTIVATOR_FAKE_APP=1`, and `ExecBackend` spawns and SIGTERMs it. `internal/activator` already imports `internal/edge`, so these witnesses build a real edge there with `edge.New(reg, svc)` and shorten it with `e.SetHeldConfig` (Task 5).
**Files:**
-- Create: `internal/host/heldstream_e2e_test.go`. Harness: `wakeFixture(t, host, idle, handler)` (`internal/host/schedule_wake_test.go:167`) gives a real registry, a real `activator.Service` and a `fakeInstance` app on a unix socket whose stop is a graceful `http.Server.Shutdown`. Build the edge with `edge.New(reg, svc)` as `TestPlatformAliasWakesItsSleepingInstance` does (`internal/host/aliaswake_test.go`), and wire `svc.SetHeldWakeHook(e.HeldWake)` as `agent.go` does. For the overlap swap use `genDeliveryFixture` (`internal/host/generations_test.go:43`); if it cannot drive an overlap swap, put that one witness in `internal/activator` beside the swap tests on its real-`Service` harness, and say so in the task report.
-- The instance handler (in the test file): `GET /live` serves SSE, an `id:` per event, resumes after `Last-Event-ID`; a test-held channel emits one event to every open stream (the `Notify` stand-in); `/live?expire=1` answers 401; `/live?redirect=1` answers 303. Record each stop's duration by timing `Proc.Stop` from a wrapping backend or the fixture.
+- Modify: `internal/activator/activator_test.go` (`fakeAppMain` gains an SSE mode, `ACTIVATOR_FAKE_APP_SSE=1`)
+- Create: `internal/activator/heldstream_e2e_test.go`
+
+**The child's SSE mode:** serves on its socket with an `http.Server`; `GET /live` writes SSE with an `id:` per event, starting after `Last-Event-ID` when given, and returns as soon as `r.Context()` is done; events come from a counter file the test appends to (the `Notify` stand-in: the handler polls the file every 20 ms and sends each new line as an event); `/live?expire=1` answers 401; `/live?redirect=1` answers 303 to `/login`; `/live?cookie=1` sets `Set-Cookie: s=1; Domain=other.example.com` on its first answer; it records each request's headers as JSON lines to a file named by `ACTIVATOR_FAKE_APP_LOG`; on SIGTERM it calls `srv.Shutdown` with a 15 s context and appends the shutdown's duration in milliseconds to that log. Without cancellation an open `/live` handler holds `Shutdown` until the activator's 20 s `actStopTimeout` SIGKILLs it.
**Interfaces:**
-- Consumes: everything above, through production wiring only. No fake activator.
+- Consumes: everything above, through production wiring only: real registry, real `Service` on `ExecBackend`, real edge, real child. No fake activator.
-- [ ] **Step 1: Write the witnesses**, each with a short idle window and Tick 200 ms via `e.held` override:
- - `TestHeldE2EAsleepNoWake` (case 1): host asleep; open a marked stream; wait 3 idle windows; backend wake count 0; heartbeats received.
+- [ ] **Step 1: Write the witnesses**, each with a short idle window, `SetHeldConfig` with Tick 200 ms, and `svc.SetHeldWakeHook(e.HeldWake)`:
+ - `TestHeldE2EAsleepNoWake` (case 1): host asleep; open a marked stream; wait 3 idle windows; the child was never started; heartbeats received.
- `TestHeldE2EAwakeStillSleeps` (case 2): wake with one plain request; open a marked stream; the instance hibernates after its idle window with the stream open.
- - `TestHeldE2ESleepFastDrain` (case 3, Review Focus 3): stream open, instance idles out; the recorded stop duration is under 2 s (an uncancelled stream would hold `Shutdown` until `actStopTimeout`). Mutate: drop the `cancelHeldLegsLocked` call in `beginStopLocked`, confirm this witness fails, restore.
- - `TestHeldE2EResumeAcrossSleep` (case 4): events 1–2 relayed; sleep; a plain request wakes it and `POST /notify` emits event 3; the browser receives event 3 next, with no duplicate of 1–2.
- - `TestHeldE2ETwoReconnectsKeepCursor` (Review Focus 1): browser client that implements the SSE spec's last-event-ID buffer rules (dispatch on blank line copies the buffer) reconnects twice across two sleeps with heartbeats between; its second reconnect sends `Last-Event-ID` equal to the last event id it received.
- - `TestHeldE2EAppEndsStreamWhileAwake` (case 5): the child ends `/live` after each event; the stream continues with no wake count increase and spacing ≥ `ReopenSpacing`.
- - `TestHeldE2EOverlapSwap` (case 7, Review Focus 4): with generations on, trigger an overlap swap with a stream open; the retiring generation's drain completes under 2 s and the stream receives the next event from the successor.
- - `TestHeldE2EExpiredSession` (case 13): `?expire=1` while asleep → held; on wake the reopen gets 401 and closes; the reconnect gets 401 directly.
- - `TestHeldE2ELegHeaders`: the child records request headers; a client sending forged `X-Forwarded-For` and `X-Carlos-Sidecar` → the child sees the edge's forwarded chain and no sidecar header.
-- [ ] **Step 2: Run** `TMPDIR=/tmp/k GOFLAGS=-buildvcs=false go test -run TestHeldE2E -count=1 ./internal/host` (sandbox off). Expected: PASS. If one fails, it is a defect in Tasks 1–6: fix it there (with a unit test in that task's file), not in the witness.
-- [ ] **Step 3: Cross-compile check**: `GOOS=darwin go vet ./internal/edge ./internal/activator ./internal/host` and `GOOS=windows go vet` the same. Expected: no errors.
-- [ ] **Step 4: Commit** `host: production-wired witnesses for held streams (#432)`.
+ - `TestHeldE2ESleepFastDrain` (case 3, Review Focus 3): stream open, instance idles out; the child's logged shutdown duration is under 2000 ms. Mutate: drop the `cancelHeldLegsLocked` call in `beginStopLocked`; confirm the logged duration exceeds 2000 ms (or the child is SIGKILLed with no duration logged) and the witness fails; restore.
+ - `TestHeldE2EResumeAcrossSleep` (case 4): events 1–2 relayed; sleep; a plain request wakes it and the test appends event 3; the browser receives event 3 next, with no duplicate of 1–2.
+ - `TestHeldE2ETwoReconnectsKeepCursor` (Review Focus 1): a browser stand-in in the test file that follows the SSE spec's parsing rules (last-event-ID buffer reset per connection; dispatch on a blank line copies it) reconnects twice across two sleeps with heartbeats between; its second reconnect sends `Last-Event-ID` equal to the last event id it received.
+ - `TestHeldE2EAppEndsStreamWhileAwake` (case 5): the child ends `/live` after each event; the stream continues with no new wake and leg spacing ≥ `ReopenSpacing`.
+ - `TestHeldE2EEdgeRestart` (case 6): hold a stream on an asleep host; close that edge's held set (build a second `edge.New` over the same registry and activator to stand in for the restart); the browser reconnects to the second edge; it is held, and the child was never started.
+ - `TestHeldE2EOverlapSwap` (case 7, Review Focus 4): with generations on, using this package's existing overlap-swap harness with the real child (`opset_test.go`/`identity_test.go` use `ACTIVATOR_FAKE_APP`), trigger an overlap swap with a stream open; the retiring generation's logged shutdown is under 2000 ms and the stream receives the next event from the successor.
+ - `TestHeldE2EStopAdmitRace` (case 10): 50 iterations: a stream reconnecting in a tight loop (`ReopenSpacing` 1 ms) while the idle sweep stops the instance; after each stop, the child's log shows no `/live` request that started after its shutdown began, and the shutdown stayed under 2000 ms.
+ - `TestHeldE2EExpiredSession` (case 13): `?expire=1` while asleep → held; on wake the reopen gets 401 and closes; the reconnect gets 401 directly. Same for `?redirect=1` → the reconnect gets 204.
+ - `TestHeldE2ELegHeaders`: a client sending forged `X-Forwarded-For`, a forged edge-proof header and `X-Carlos-Sidecar`; with the edge's forward key set (`withForwardKey`'s key, as the forward-proof tests set it), the child's logged headers show the edge's own forwarded chain, an edge-proof header that verifies with `edgeproof` against that key, and no sidecar header.
+ - `TestHeldE2EFirstLegCookieScoped`: `?cookie=1`, awake; the browser's first response carries the `Set-Cookie` exactly as the edge's cookie scoping rewrites a proxied response's (`cookiescope.go`), not the child's raw header.
+- [ ] **Step 2: Run** `TMPDIR=$T GOFLAGS=-buildvcs=false go test -run TestHeldE2E -count=1 ./internal/activator` (sandbox off). Expected: PASS. If one fails, it is a defect in Tasks 1–6: fix it there (with a unit test in that task's file), not in the witness.
+- [ ] **Step 3: Cross-compile check**: `GOOS=darwin go vet ./internal/edge ./internal/activator ./internal/host` and `GOOS=windows go vet` the same. Expected: no errors. (The e2e file is linux-only if `ExecBackend`'s tests are; match their build tags.)
+- [ ] **Step 4: Commit** `activator: production-wired witnesses for held streams with a real child (#432)`.
### Task 9: Docs for app authors
@@ -283,12 +323,16 @@ Placement (§3.8), in `Edge.ServeHTTP`:
- Modify: `docs/site/nav.json` (a page entry under Reference: slug `live-streams`)
- [ ] **Step 1: Draft the page's prose and run it through the `copy-review` skill before writing it into the file** (house rule: no em dashes; full stop and a new sentence). Content (facts from §3): open the stream with `carlos_hold=1` in its URL; it does not keep the instance awake and does not wake it; it resumes on wake with `Last-Event-ID`, so put an `id:` on every event and resume after it; same-origin only; do not redirect a held stream (the browser stops with a 204), answer 401 or 403 instead; cookies set on a reopened stream are not delivered; over the limit the browser retries in 30 seconds; the edge sends its own heartbeats.
-- [ ] **Step 2: Run** `go test -run TestDocsite -count=1 ./internal/docsite` (the corpus checks links and nav). Expected: PASS.
+- [ ] **Step 2: Run** `go test -run 'TestNavAndFilesAgreeBothWays|TestInternalLinksResolve' -count=1 ./internal/docsite`. Expected: PASS.
- [ ] **Step 3: Commit** `docs: holding live streams on hibernating instances (#432)`.
---
+## Review history
+
+- Round 1 (Astra, `docs/superpowers/plans/CODEX-FINDINGS-edge-held-streams-plan.md`): NOT READY, 7 P1 and 5 P2, all accepted. P1-1 → Task 6 steps 1–2 (mark recorded first; tunnel routes keep the marker); P1-2 → Task 6 step 3 (`slotWriter`); P1-3 → Task 5 (deadline reset, HTTP/2 witness); P1-4 → Task 2 (transition-site guard instead of a stop-call list); P1-5 → Task 5 (`HeldConfig`/`SetHeldConfig` exported); P1-6 → Task 8 (real child in `internal/activator`); P1-7 → Task 1 (live context; nil/closed/open `Startup`); P2-1 → Task 5 step 2 and Task 2 step 2; P2-2 → Task 8 (cases 6, 10, signing, cookies) and Task 6 (mandatory tunnel witness); P2-3 → Task 7 (`Hosts`); P2-4 → Tasks 1 and 9 (test selectors); P2-5 → Global Constraints (`mktemp -d`).
+
## Self-review notes
-- Spec coverage: §3.1 → Tasks 5, 6; §3.2 → Tasks 1, 2, 3; §3.3/3.3a → Tasks 4, 5; §3.4 → Task 6 (forwarding edges untouched except cache bypass), Task 8; §3.5 → Task 1; §3.6 → Task 5; §3.7 → Tasks 5, 6; §3.8 → Tasks 3, 6; §3.9 → Task 7; §5 cases → Task 8 (6, 8, 10, 11, 12 covered by unit tests in Tasks 1, 5, 6; case 6 is the reconnect path of case 1); §7 → Tasks 2, 5, 6, 8.
+- Spec coverage: §3.1 → Tasks 5, 6; §3.2 → Tasks 1, 2, 3; §3.3/3.3a → Tasks 4, 5; §3.4 → Task 6 (tunnel witness), Task 8; §3.5 → Task 1; §3.6 → Task 5; §3.7 → Tasks 5, 6; §3.8 → Tasks 3, 6; §3.9 → Task 7; §5 cases 1–7, 10, 13 → Task 8; cases 8, 11, 12 → Tasks 5, 6, 1; §7 → Tasks 2, 5, 6, 8.
- Per-task review (AGENTS.md stopping rule 3): Tasks 1, 2 and 6 touch termination ordering, a cache and a security gate's ordering, so each gets its own Astra review; the rest are covered by the whole-branch review.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-edge-held-streams-plan.md b/docs/superpowers/plans/CODEX-FINDINGS-edge-held-streams-plan.md
new file mode 100644
index 000000000..5d46a2fe5
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-edge-held-streams-plan.md
@@ -0,0 +1,175 @@
+# Implementation plan review — round 1 of 3
+
+Commit: `cd61c9d941cb5c367f0001b1e41d94494038d315` (verified HEAD).
+
+Reviewed against approved spec rev 3. Its rulings and completed design reviews are unchanged. No files changed, subagents spawned, or tests run. Compilation and test-command findings below come from source inspection.
+
+## P1 findings
+
+### P1-1 — Task 6 strips the marker before tunnel forwarding and before checking cache eligibility
+
+**Section:** Task 6, placement steps 1 and 3, plan lines 210–212.
+
+**Problem and evidence:** Step 1 strips the marker on every route outside the local holding condition. Tunnel and fleet-forwarding routes take that branch: they set `viaTunnel=true` at [edge.go:789](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/edge/edge.go:789), which makes `hibernating=false` at `edge.go:949`. Step 3 then checks the already-modified query with `hasHoldMarker(r)`.
+
+**Failure scenario:** A tunnel hub removes `carlos_hold=1`, so the receiving edge treats the stream as ordinary traffic and can wake the instance or keep it active. On an always-on route, stripping also makes the proposed cache exemption false; Task 6’s cacheable-response test can receive a cached second response.
+
+**Fix:** Preserve the marker on `viaTunnel` forwarding routes. Record the original marked state before stripping, and use that state for subsequent cache and asset exclusions. Require a tunnel witness that verifies both marker delivery and zero activity admission at the receiving edge.
+
+**Fault family:** Forwarding must preserve the non-waking classification; marker removal must not erase cache exclusion.
+
+### P1-2 — Task 6 holds rate-limit slots for the stream’s entire lifetime
+
+**Section:** Task 6, placement step 2, plan line 211.
+
+**Problem and evidence:** The proposed branch calls `rateAdmit` and defers `release`, but never installs `slotWriter`. Existing dispatch explicitly installs it at [edge.go:2056](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/edge/edge.go:2056). `slotWriter.WriteHeader` releases the slot when final headers are written at [ratelimit.go:210](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/edge/ratelimit.go:210).
+
+**Failure scenario:** An already-answered held stream consumes an instance’s busy slot for up to an hour. Enough streams cause ordinary requests to be shed despite the instance doing no work for them. This contradicts spec §3.6’s explicit header-time release.
+
+**Fix:** Wrap the observing writer in `slotWriter` when `release != nil`, retaining the deferred release as a fallback. Test that headers release the slot while the stream remains open.
+
+**Fault family:** Rate-limit occupancy ends at response commitment.
+
+### P1-3 — Task 5 leaves write deadlines armed while waiting for the next heartbeat
+
+**Section:** Task 5, plan lines 173–176.
+
+**Problem and evidence:** The plan sets a deadline before each write but never clears it afterward. The default write deadline is 10 seconds; the heartbeat interval is 25 seconds. In the installed Go 1.26.10 toolchain, HTTP/2’s [SetWriteDeadline implementation](/home/paulca/.local/go-dist/src/net/http/h2_bundle.go:6924) schedules a timer whose [expiry resets the stream](/home/paulca/.local/go-dist/src/net/http/h2_bundle.go:6071), even without a pending write. Extending an already-expired deadline does not recover it.
+
+**Failure scenario:** An asleep host’s HTTP/2 stream commits its response, then gets reset after ten seconds—before its first heartbeat. The proposed plain `httptest.NewServer` tests and short heartbeat intervals do not exercise this.
+
+**Fix:** Bound each write-and-flush operation, then clear its deadline with `SetWriteDeadline(time.Time{})` before waiting. Add an HTTP/2 witness with `Tick > WriteDeadline` that survives multiple idle intervals, plus a blocked-write witness.
+
+**Fault family:** A write-operation timeout must not become an idle-stream timeout.
+
+### P1-4 — Task 2’s stop-site allowlist is incomplete and contains a false reason
+
+**Section:** Task 2, step 1, plan line 78.
+
+**Problem and evidence:** The promised package-wide scan encounters existing calls absent from the seed list, including:
+
+- `stopMember`, `genChildProof`, `reapMembersLocked`, and `reapUnprovenWake`: [opset.go:216](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/activator/opset.go:216), lines 331, 644 and 886.
+- `respawnWorkerLocked`: `activator.go:3909` and `4056`.
+- `killFailed`: `wakeplan.go:329`, `338` and `341`.
+- `startChildAt`, `killGenAfterFailedStart`, and `startUnitAt`: `backend_exec.go:2142`, `2176` and `2716`.
+- `startRootfs`, `killResidentGens`, and the `SplitBackend.KillGen` delegation: `rootfs.go:302`, `rootfs_service.go:952`, and `backend_unit.go:469`.
+- `startAdmitted` and `claimProcess` stop paths: `claimwake.go:585`, `664`, `823`, `831` and `860`.
+
+Moreover, `reapShedLocked` reaps a **worker respawn child**, not “shed swap members”: [activator.go:4658](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/activator/activator.go:4658). Actual swap-member reaping is in `opset.go`.
+
+**Failure scenario:** The proposed guard fails immediately against existing code. Broadening it mechanically would conceal whether serving generations were cancelled before termination. A `file:function` whitelist also permits a new stop call inside an already-listed function, contrary to the promised “new site fails” property.
+
+**Fix:** Supply the complete, receiver-aware call-site inventory and a verified cancellation or non-admission reason for each site. Distinguish candidates from previously serving retiring generations. Track individual sites, and mutation-test an added stop inside an existing allowlisted function.
+
+**Fault family:** Every process-termination site must have an established held-leg cancellation precondition.
+
+### P1-5 — Task 8 cannot access the proposed private edge configuration
+
+**Section:** Tasks 5 and 8, plan lines 165 and 265.
+
+**Problem and evidence:** Task 5 declares `Edge.held`, `heldSet`, and `heldConfig` as unexported. Task 8 puts its tests in `internal/host` and instructs them to override `e.held`. The referenced harness is in package `host`: [schedule_wake_test.go:1](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/host/schedule_wake_test.go:1).
+
+**Failure scenario:** The witnesses fail compilation because package `host` cannot access `edge.Edge.held` or construct its private configuration.
+
+**Fix:** Specify a legal configuration seam or relocate the witnesses to a test arrangement that can access the configuration without introducing the existing `activator → edge` import cycle. Include that seam in the earlier task’s interface contract.
+
+**Fault family:** Cross-task interfaces must obey Go package visibility.
+
+### P1-6 — Task 8’s fixture cannot prove the claimed graceful-drain behavior
+
+**Section:** Task 8, plan lines 259 and 268.
+
+**Problem and evidence:** The plan says `fakeInstance.stop` performs graceful `http.Server.Shutdown`. It actually calls `srv.Close()` at [schedule_wake_test.go:100](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/host/schedule_wake_test.go:100). The fixture explicitly uses no child processes (`schedule_wake_test.go:121`) and disclaims SIGTERM-drain coverage at line 211.
+
+**Failure scenario:** Removing cancellation from `beginStopLocked` still lets the fixture close active connections immediately. The proposed under-two-second assertion can pass with the defect present, so the required mutation check does not work. The fixture also fails the approved real-child requirement.
+
+**Fix:** Specify a real child app whose SIGTERM handler performs graceful shutdown and whose SSE handler exits on request cancellation. Demonstrate that the uncancelled stream delays termination, then that cancellation fixes it. Supply an equivalent real-generation harness for overlap retirement.
+
+**Fault family:** Termination witnesses must exercise graceful process drain and fail when cancellation is removed.
+
+### P1-7 — Task 1’s admissibility test uses a context that admission must reject
+
+**Section:** Task 1, step 1, plan line 62.
+
+**Problem and evidence:** The test equates host admissibility with successful admission using an **already-cancelled** context. Task 1 also requires retaining `BeginSidecarRequest`’s startup admission. That method calls `awaitStartup` at [activator.go:1812](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/activator/activator.go:1812). With a completed, non-nil startup channel, `awaitStartup` returns `ctx.Err()` at `activator.go:1581`.
+
+**Failure scenario:** A healthy awake host after completed startup correctly reports admissible, but admission returns `context.Canceled`. The proposed equivalence assertion fails against correct behavior.
+
+**Fix:** Check immediate admission with a live bounded context and controlled host state. Test cancelled-context behavior separately. Cover both nil startup channels and closed startup channels; nil means no startup wait in existing code.
+
+**Fault family:** Host availability and caller cancellation are separate admission conditions.
+
+## P2 findings
+
+### P2-1 — The required lifecycle simulation is only partially planned
+
+**Section:** Task 2, step 2; self-review coverage claim.
+
+**Problem and evidence:** Spec §7 requires dropped/delayed wake signals, probe hold/release, activity invisibility including `lastActive` and wake initiation, and the one-tick resume bound. Task 2 adds only leg admission/completion, cancellation checks, and `inflight` comparisons. The existing simulator drives activator operations, not held-stream tasks or their timers: [swap_sim_test.go:817](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/activator/swap_sim_test.go:817).
+
+**Failure scenario:** A broken tick fallback or probe-release resume can pass every proposed simulation check. Concurrent ordinary requests also make separate before/after `inflight` samples insufficient to attribute a change to held admission.
+
+**Fix:** Add an explicit stream-lifecycle simulation covering all three approved invariants and signal loss. Define how admission’s accounting effects are observed without interference from concurrent ordinary requests.
+
+**Fault family:** Resume liveness and activity invisibility require lifecycle-level verification.
+
+### P2-2 — Several required production witnesses have no task
+
+**Section:** Task 8 and self-review notes.
+
+**Problem and evidence:** The approved [spec:484](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/docs/superpowers/specs/2026-10-28-edge-held-streams-design.md:484) requires production witnesses for cases 1–7, 10 and 13, plus signing and first-leg cookie scoping. Task 8 lacks explicit edge-restart/reconnect and concurrent stop/admit witnesses. Its header test checks forwarded headers and sidecar stripping, but not signing or cookie scoping. Unit tests are substituted for cases 6 and 10 in plan line 293.
+
+**Failure scenario:** The plan can finish without verifying the production lifecycle races or response transformations the spec expressly requires.
+
+**Fix:** Add named witnesses for those cases and assertions for the signing proof and scoped first-leg `Set-Cookie`. Keep the tunnel witness mandatory rather than allowing “any non-hibernating route” as its substitute.
+
+**Fault family:** Required production behavior must be tested through its actual dispatch and proxy paths.
+
+### P2-3 — Task 7 drops the approved per-host status counts
+
+**Section:** Task 7, plan lines 239–248.
+
+**Problem and evidence:** The plan deliberately publishes box totals only and leaves per-host counts for logs. Approved [spec §3.9](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/docs/superpowers/specs/2026-10-28-edge-held-streams-design.md:409) requires current held counts “per host and total” in the box snapshot.
+
+**Failure scenario:** Operators receive the total but cannot identify the host occupying held-stream capacity from the promised status data.
+
+**Fix:** Add an additive per-host count field and snapshot tests, including removal of hosts with no remaining held streams.
+
+**Fault family:** Published observability must include the approved dimensions.
+
+### P2-4 — Two test selectors do not verify what the plan claims
+
+**Sections:** Task 1, step 4; Task 9, step 2.
+
+**Problem and evidence:**
+
+- `-run TestDocsite` matches no test in `internal/docsite`. The relevant tests are [TestNavAndFilesAgreeBothWays](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/docsite/nav_test.go:14) and [TestInternalLinksResolve](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/docsite/links_test.go:16).
+- `-run 'TestSidecar|TestServe'` excludes the directly relevant [TestActivatorSidecarRequestsInvisibleToActivity](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-held-streams-432/internal/activator/activator_test.go:3052).
+
+**Failure scenario:** A successful command is mistaken for validation of navigation, links, or the existing sidecar invisibility contract.
+
+**Fix:** Name the actual tests in the commands. Include the sidecar invisibility witness explicitly and select the documentation corpus checks by their existing names.
+
+**Fault family:** Verification commands must execute the claimed assertions.
+
+### P2-5 — The shared scratch-directory instruction violates this checkout’s machine rules
+
+**Section:** Global constraints, plan line 23 and repeated test commands.
+
+**Problem and evidence:** The plan requires `TMPDIR=/tmp/k`, creates that fixed directory, and instructs the builder to empty it. The supplied AGENTS instructions prohibit scratch under the shared RAM-backed `/tmp` and deleting files the session did not create.
+
+**Failure scenario:** Independent sessions share the same directory; cleanup can remove another session’s files, and test scratch consumes the prohibited shared RAM disk.
+
+**Fix:** Use a unique directory under the configured disk-backed `$TMPDIR` or the task’s cache directory. Remove only that directory, and retain the default Go build cache.
+
+**Fault family:** Scratch ownership and shared-machine resource isolation.
+
+## P3 findings
+
+None.
+
+## Builder questions
+
+None requiring a change to the approved spec. The real-child harness and test-configuration seam are implementation choices the revised plan should settle.
+
+**NOT READY**
\ No newline at end of file