edge-held-streams: implementation plan (#432)
Human
Prompt
go ahead (Paul approved design rev 3)
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
Nine tasks: activator held-leg admission and synchronous cancellation, stop-site guard and swap-sim invariants, edge seam, SSE reader, the held-stream task, dispatch wiring and cache bypass, status counters, production-wired witnesses, app-author docs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+294
−0
docs/superpowers/plans/2026-10-28-edge-held-streams.md+294 −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| new file mode 100644 |
| index 000000000..47faee011 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-28-edge-held-streams.md |
| @@ -0,0 +1,294 @@ |
| +# Edge-held event streams Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A 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. |
| + |
| +**Tech Stack:** Go (stdlib `net/http`, `httputil.ReverseProxy`), existing `internal/activator`, `internal/edge`, `internal/status`, `internal/host` packages. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-28-edge-held-streams-design.md` (rev 3, approved by Paul 2026-10-28). Read it before any task; section references below (§n) are to it. |
| + |
| +## Global Constraints |
| + |
| +- Marker: query parameter `carlos_hold` with exact value `1`. Any other value is not a marker. |
| +- A marked request to a hibernating route (`up.hibernating && up.route.Hibernate`) never reaches `act.ServeHTTP`, the asset catch, the shared cache, or the upgrade branch. |
| +- Held legs never call `begin`, never change `inflight` or `lastActive`, never start a wake. |
| +- No bucket read, registry read or S3 request on the hold path. |
| +- Constants (tunable, shapes fixed): per-host cap 64; per-box cap 4096; max hold 1 h; first-response commit 2 s; leg header timeout 10 s; downstream write deadline 10 s; heartbeat/tick 25 s; event cap 64 KiB; reopen spacing 1 s; short leg < 30 s; short-leg backoff 1 s, 2 s, 4 s … cap 30 s; 5 short legs in a row close; over-cap answer `retry: 30000`. |
| +- 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). |
| +- 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. |
| + |
| +## Review Focus |
| + |
| +1. A browser that reconnects twice across two sleeps must still send the right `Last-Event-ID` the second time (heartbeats and comment-only app blocks must not reset it). Pinned in Task 4 and Task 8. |
| +2. An app that answers a held stream with a redirect (session expired) must not make the browser fetch an unmarked URL that wakes the instance. Pinned in Task 5. |
| +3. An instance with streams open must stop within its normal drain time, never at the 20 s `actStopTimeout`. Pinned in Task 1 and Task 8. |
| +4. An overlap swap with streams open must move them to the new generation without the old generation's drain waiting. Pinned in Task 2 (simulation) and Task 8. |
| +5. A marked request on a forwarding edge (tunnel hub, hop) must never be served from, or stored in, the shared cache. Pinned in Task 6. |
| + |
| +--- |
| + |
| +### Task 1: Activator held-leg admission and cancellation |
| + |
| +**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` (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` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `edge.HeldLeg` in `internal/edge/heldleg.go`: `type HeldLeg interface { Context() context.Context; Done() }` |
| + - `func (a *Service) AdmitHeldLeg(ctx context.Context, rt registry.Route) (edge.HeldLeg, error)` — `BeginSidecarRequest`'s loop (same errors: `ErrFenced`, `errSidecarAsleep`, `errWakeTimeout`, `ctx.Err()`), except the admitting branch registers a leg under `a.mu` before returning. Exported sentinel `ErrHeldAsleep = errSidecarAsleep`. |
| + - `func (a *Service) HeldAdmissible(host string) bool` |
| + - `func (a *Service) SetHeldWakeHook(f func(host string))` (nil removes) |
| + - internal: `func (a *Service) heldAdmissibleLocked(e *actEntry) bool` — the single predicate (§3.5): `Startup` closed and `lifeCtx` live, entry present, `actAwake`, `!e.proc.Exited()`, `e.rep == nil || e.rep.Err() == nil`, no fence, `!e.probeHeld`, `!a.shuttingDown`. `AdmitHeldLeg`'s admit branch is exactly "this predicate is true"; its stop-initiating side effects (lost lease, dead child → `beginStopLocked`) stay in `AdmitHeldLeg`, outside the predicate. |
| + - internal: `func (a *Service) cancelHeldLegsLocked(e *actEntry, gen uint64)` — `gen == 0` cancels every leg on the entry; otherwise only legs registered on that generation number. Only calls cancel funcs. |
| + - internal: `type heldLeg struct { gen uint64; ctx context.Context; cancel context.CancelFunc; a *Service; host string; id uint64 }`; `actEntry.heldLegs map[uint64]*heldLeg`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `heldlegs_test.go`, against a real `Service` built with this package's existing test helpers (the ones `activator_test.go` uses for a hibernating route with a fake backend): |
| + - `TestAdmitHeldLegAsleepRefusesWithoutWake`: no entry → `errors.Is(err, ErrHeldAsleep)`; backend `Start` call count stays 0. |
| + - `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. |
| + - `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 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 5: Commit** `activator: held-leg admission, registry and synchronous cancellation (#432)`. |
| + |
| +### Task 2: Stop-site guard and the swap simulation's held-leg invariants |
| + |
| +**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)`. |
| + |
| +### Task 3: Edge seam and writer plumbing |
| + |
| +**Files:** |
| +- Modify: `internal/edge/edge.go` (`Activator` interface) |
| +- Modify: `internal/edge/usagemeter.go` (`countingWriter.Unwrap`) |
| +- Modify: every type implementing `edge.Activator` in tests: `internal/edge/edge_test.go` (`fakeActivator`, `refusingActivator`, `hijackCheckingActivator`, `activatorFunc`), `internal/edge/alias_test.go` (`routeRecordingActivator`), and any other the compiler names |
| +- Test: `internal/edge/usagemeter_test.go` |
| + |
| +**Interfaces:** |
| +- Produces, in `internal/edge`: |
| + ```go |
| + // HeldLeg already exists (Task 1, internal/edge/heldleg.go). |
| + type Activator interface { |
| + ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool |
| + RetireExcept(keep map[string]bool) |
| + AdmitHeldLeg(ctx context.Context, rt registry.Route) (HeldLeg, error) |
| + HeldAdmissible(host string) bool |
| + SetHeldWakeHook(f func(host string)) |
| + } |
| + ``` |
| + `activator.Service` satisfies it because Task 1's `AdmitHeldLeg` returns `edge.HeldLeg`. Test fakes: `AdmitHeldLeg` returns an error (`errors.New("asleep")`), `HeldAdmissible` false, hook no-op, unless a test needs more. |
| + - `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 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)`. |
| + |
| +### Task 4: SSE event reader |
| + |
| +**Files:** |
| +- Create: `internal/edge/sse.go` |
| +- Test: `internal/edge/sse_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + const sseMaxEvent = 64 << 10 |
| + type sseBlock struct { |
| + Raw []byte // the block's lines as received, normalized to "\n", ending in "\n\n" |
| + CommentOnly bool // every line is a comment (starts with ':') |
| + HasID bool |
| + ID string // valid only when HasID; "" means the spec's reset |
| + } |
| + type sseReader struct { /* bufio over the leg body */ } |
| + func newSSEReader(r io.Reader) *sseReader |
| + func (s *sseReader) Next() (sseBlock, error) // io.EOF at clean end; errSSEEventTooLarge over the cap; a partial block at EOF is dropped and reported as io.ErrUnexpectedEOF |
| + ``` |
| + `ID` follows the SSE spec: an `id` field whose value contains NUL is ignored (does not set `HasID`); the last `id` field in the block wins. Lines end in `\r\n`, `\r` or `\n`. A leading UTF-8 BOM on the first line is stripped. |
| + |
| +- [ ] **Step 1: Write table tests** `TestSSEReader`: (a) `"id: 7\ndata: x\n\n"` → one block, `HasID`, `ID=="7"`; (b) `"id\n\n"` → `HasID`, `ID==""`; (c) `"id: a\x00b\ndata: x\n\n"` → `HasID==false`; (d) `": ping\n\n"` → `CommentOnly`; (e) `"\xEF\xBB\xBFdata: x\r\n\r\n"` → `Raw=="data: x\n\n"`; (f) `"data: x\n"` then EOF → `io.ErrUnexpectedEOF`, no block; (g) a 70 KiB data line → `errSSEEventTooLarge`; (h) `"retry: 5\n\n"` → one block, not comment-only. |
| +- [ ] **Step 2: Run** `go test -run TestSSEReader -count=1 ./internal/edge` (sandbox fine: no sockets). Expected: FAIL, undefined. |
| +- [ ] **Step 3: Implement** `sse.go`. |
| +- [ ] **Step 4: Run** Step 2's command. Expected: PASS. |
| +- [ ] **Step 5: Commit** `edge: SSE block reader for held streams (#432)`. |
| + |
| +### Task 5: The held-stream task |
| + |
| +**Files:** |
| +- Create: `internal/edge/heldstream.go` |
| +- Test: `internal/edge/heldstream_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 |
| + } |
| + 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} |
| + type heldSet struct { /* per-host map of *heldStream, box count, counters (Task 7) */ } |
| + 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) |
| + // 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. |
| + |
| +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. |
| +- 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. |
| +- 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. |
| + - `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`. |
| + - `TestHeldRedirectBecomes204`: awake, proxy answers `303 Location: /login` → client sees 204, and the fake activator's `ServeHTTP` count is 0. |
| + - `TestHeldPassThrough401`: awake, proxy answers 401 with a body → client sees 401 and the body. |
| + - `TestHeldReopenRefusedCloses`: after a relayed event, leg ends; reopen answers 403 → client body ends (EOF). |
| + - `TestHeldShortLegsClose`: proxy ends every leg at once after one event → stream closes after 5 legs, and no two legs started less than `ReopenSpacing` apart. |
| + - `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. |
| + - `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)`. |
| + |
| +### 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` |
| + |
| +**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)`). |
| + |
| +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)`. |
| + |
| +- [ ] **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). |
| + - `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. |
| +- [ ] **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 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 |
| + |
| +**Files:** |
| +- Modify: `internal/edge/heldstream.go` (counters on `heldSet`) |
| +- Modify: `internal/status/snapshot.go` (probe input and `Box.Metrics` gain `HeldStreams *HeldStreams`) |
| +- Modify: `internal/host/agent.go` (fill it from the edge where `GeoIP: geoIPState()` is filled, ~line 4351) |
| +- Test: `internal/edge/heldstream_test.go`, `internal/status/snapshot_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```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 |
| + } |
| + // 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. |
| + |
| +- [ ] **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 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 |
| + |
| +**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. |
| + |
| +**Interfaces:** |
| +- Consumes: everything above, through production wiring only. 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. |
| + - `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)`. |
| + |
| +### Task 9: Docs for app authors |
| + |
| +**Files:** |
| +- Create: `docs/site/live-streams.md` |
| +- 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 3: Commit** `docs: holding live streams on hibernating instances (#432)`. |
| + |
| +--- |
| + |
| +## 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. |
| +- 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. |