carlos / platform Public

Platform rolls: the edge holds requests to a restarting local upstream instead of answering 502/503 (#434 option 2). A loopback TCP or unix-socket upstream that refuses, or whose socket is missing, is redialled every 100 ms for up to 13 s under one deadline set when the dial starts (unix upstreams already had this window and now share the code); non-local upstreams are unchanged. A probed route with a local upstream waits for the prober to readmit it, never dialling an ejected upstream: 13 s plus the prober's real readmission time, capped at 30 s (19 s with default health settings). The edge binds :80/:443 before serving and logs one 'edge: listeners:' line naming them. No socket unit, and no unit, root, updater or rollback change: the socket (option 3) comes later in a release that refuses rollback below the first socket-aware build (Paul's ruling, #434). Local witness TestLocalUpstreamRestartWitness: 0 failed requests across tcp, unix and probed routes during an upstream restart under load; 2126 x 502 with the hold off. Known limit: a request already queued at the upstream when it closes is reset (0-4 per restart). Reviews: Astra spec R1 2 P1, R2 1 P1 (rule 2, Paul ruled option 2 then 3), R3 READY AFTER FIXES; whole branch R1 READY AFTER FIXES, fixes applied; census census-ruling-edge-roll-blip approved by Astra (#280), re-sealed on main's chain with the same units and claims.

Prompts:

  I think we can go ahead and build this overnight

Squashed from edge-roll-blip into main.
claude agent, operated by paul@keymail.dev 9665606d0ec6562ba95880971713cddcc74c375d parent 5f90f2a
33 files changed, +3,520 −121
  • .superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md +117 −0
  • .superpowers/sdd/2026-10-27-edge-roll-blip/progress.md +108 −0
  • docs/superpowers/notes/census-proposal-edge-roll-blip.md +21 −0
  • docs/superpowers/plans/2026-10-27-edge-roll-blip.md +366 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch-fixcheck.md +26 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch.md +79 −0
  • docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch-fixcheck.md +10 −0
  • docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch.md +40 −0
  • docs/superpowers/reviews/edge-roll-blip-ledger-minors.md +33 −0
  • docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md +340 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R2.md +127 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R3.md +95 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec.md +99 −0
  • docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R2.md +36 −0
  • docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R3.md +54 −0
  • docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md +63 −0
  • internal/edge/answered.go +6 −4
  • internal/edge/edge.go +165 −55
  • internal/edge/edge_test.go +18 −10
  • internal/edge/edgeerrors_test.go +1 −1
  • internal/edge/genproxy.go +40 −30
  • internal/edge/genproxy_test.go +61 −0
  • internal/edge/listeners.go +38 −0
  • internal/edge/listeners_test.go +71 −0
  • internal/edge/localhold.go +114 −0
  • internal/edge/localhold_probed_test.go +504 −0
  • internal/edge/localhold_test.go +409 −0
  • internal/edge/localhold_witness_test.go +387 −0
  • internal/edge/prober.go +61 −5
  • internal/edge/prober_test.go +11 −11
  • internal/host/applessroute_test.go +12 −5
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv +7 −0

CI passed — run details

landed from edge-roll-blip

diff --git a/.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md b/.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md
new file mode 100644
index 000000000..d214e2d3f
--- /dev/null
+++ b/.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md
@@ -0,0 +1,117 @@
+# Overnight brief: edge-roll-blip (#434 part B)
+
+Paul, 2026-10-27: "I think we can go ahead and build this overnight." Finish line he chose:
+**merge-ready, no merge, no roll.** Read amadan discussion #434 (carlos/platform) first;
+it is the problem statement.
+
+## Goal
+
+A platform roll (`carlos system update` restarting `carlos-edge.service`, and root's adopt
+restarting `console.service`) must become a short queued wait for clients. No refused
+connections, no 502/503 from the restart itself. Today:
+- the edge opens :80/:443 itself, so between stop and start connections are refused;
+- the console restarts once per roll, giving ~10 s of 502 through the edge.
+
+## Scope
+
+IN (part B):
+1. **Edge listeners survive a restart.** The kernel keeps accepting on :80/:443 (and any
+ other public port the edge binds; find them all) while the old edge exits and the new one
+ starts. Candidate mechanisms: a `carlos-edge.socket` unit, or systemd's fd store
+ (`FileDescriptorStoreMax=`, `sd_notify FDSTORE=1`, `FileDescriptorStorePreserve=`). The
+ spec picks one with evidence. Verify the boxes' systemd version (find the AMI / OS in
+ infra/ or the bootstrap code) and the exact semantics of an explicit
+ `systemctl restart` / `stop`+`start` for each mechanism, from systemd's own docs.
+2. **The console no longer 502s while it restarts.** Prefer an edge-side hold: when the
+ edge's dial to a local upstream (console, and any other named-unit / proxied local
+ upstream; it is a general-purpose platform, so no console special case unless forced)
+ fails with refused / no such socket, retry the dial for a bounded window instead of
+ 502ing. A failed dial never reached the upstream, so the retry is safe for any method.
+ Bound it by the request context and a cap in line with the existing wake hold.
+ Socket-activating console.service instead is acceptable only if console's unit lives in
+ this repo and the spec shows it's simpler.
+3. **Local witness, no cloud.** A test or script that restarts a socket-activated edge
+ under load and counts refused/failed requests (0 is the pass). Use what DOCS-T1 offers
+ without sudo: `systemd-socket-activate`, `systemd-run --user`, or a Go test that passes
+ fds the way `testdata/echoapp` and `internal/instancectl/peer_linux.go` already do.
+ Report the measured gap.
+4. A startup log line saying how the edge got its listeners (inherited N from systemd, or
+ bound itself), so the morning roll can be verified from the journal.
+
+OUT: part C (apps surviving an edge restart; it touches region HA's BindsTo/lease premise,
+#440 item 1, so it waits: AGENTS.md stopping rule 4). Any AWS, infra, DNS or box change.
+Releasing, rolling, merging. Dev box measurement (Paul decides that in the morning).
+
+## The hard part: every binary/unit mix must serve
+
+The old edge binds :80 itself. If a socket unit (or a stored fd) holds :80 and an OLD binary
+starts (rollback, the 20 s update gate failing, `carlos-system-recover.service`, a box whose
+updater predates this), it gets EADDRINUSE and the box goes dark. The spec must walk every
+mix: old binary + old units, new + old, new + new, old + new (rollback), first install,
+bootstrap of a fresh box, and the update gate's own rollback path. Find out how units get
+onto a box (embedded `internal/host/units`, who installs them, when, as root?) and how the
+updater restarts the edge. Prefer "refuse up front" (AGENTS.md rule 2 alternatives) over
+tolerance layers. If no mechanism is safe across rollback, say so and stop with options for
+Paul rather than building a risky one.
+
+Also cover: graceful stop must not shut down the shared listener for the successor (closing
+an inherited fd copy is fine; anything that empties the backlog is not); the #281
+listen-first + admission latch interaction; TLS/cert readiness before accepting; the
+`RestrictAddressFamilies`/capability hardening of the unit; cross-compile (darwin/windows
+CI: linux-only code needs `//go:build linux` and a stub).
+
+## Process (AGENTS.md "Stopping rules" bind you and every reviewer you brief)
+
+You are the controller. Keep your own context lean: dispatch children for the heavy work
+and dispatch them in the FOREGROUND (`run_in_background: false`), never background, or the
+root session stalls.
+
+1. **Spec** (child, Opus): `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md`.
+ Short. No user questions; Paul's decisions are above. Note each decision and why.
+2. **Spec review: Astra** (codex, OpenAI quota). Brief from
+ `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, committed beside the spec. Stop at
+ the first round with no P1. Max three rounds. If rule 2 triggers (same fault family twice)
+ or round 3 still has a P1: stop, post the choice on #434, and write it in the handoff.
+3. **Plan** (child): `docs/superpowers/plans/2026-10-27-edge-roll-blip.md` via
+ superpowers:writing-plans. No separate plan review unless the spec review changed the
+ mechanism late. Add one amadan task per plan task (`amadan task add`) and advance each as
+ it closes.
+4. **Build**: superpowers:subagent-driven-development. Per-task Astra review only for tasks
+ touching root, unit install/update/rollback, or termination (rule 3). Everything else is
+ covered by one whole-branch Astra review at the end (same round limits).
+5. **Census**: if the census check fails, follow AGENTS.md / README's census recipe
+ (census-card, CLAIMS, census-propose); the cross-model reviewer (Astra) approves. Never
+ ask Paul for a census ruling.
+6. **Finish**: merge origin/main in, push, wait for branch-tip CI green (re-run once on a
+ known flake and say so). Then `amadan branch handoff`, a reply on #434 with results and
+ the measured gap, and the morning steps for Paul (merge, release, dev-first roll, what
+ to look for in the journal).
+
+## Codex (Astra) mechanics
+
+- Script file per run; launch with the sandbox OFF via `setsid nohup <script> > log 2>&1 &`.
+ Within 20 s check the log exists and grows, and `pgrep -af "codex exec"` shows it.
+- `codex exec -s read-only -c model_reasoning_effort="high" -c 'sandbox_permissions=["disk-full-read-access"]' -o <findings.md> "<prompt>" </dev/null`
+ (always `</dev/null`). Read the header: if reasoning effort says none, restart.
+- Every Codex brief says: do not spawn Anthropic-model subagents or reviewers.
+- Commit the brief and the findings files unedited beside the spec. Verify every code
+ citation before accepting a finding.
+
+## House rules
+
+- Worktree: `.claude/worktrees/edge-roll-blip`, branch `edge-roll-blip`, identity
+ claude~paul@keymail.dev (check `git config user.email` before committing). Push often.
+- Tests: locally only the touched packages, with `-run` where possible; CI does the full
+ run. Never `make test`. Leave GOCACHE at its default. Scratch in `$TMPDIR`. Socket tests
+ may need a short TMPDIR (unix socket path length); see the repo's existing test helpers.
+- Never: `git worktree prune`, a bare `amadan branch merge`, `git stash` without a unique
+ tag, `git checkout -- <file>`, `pkill -f`, pattern deletes (`rm` with globs), `sudo`,
+ binding anything to 0.0.0.0 (use 127.0.0.1 in tests).
+- No tenant names in code, docs or examples (use shop, example.com).
+- User-facing copy: avoid adding any. Operator log lines and diagnostics don't need copy
+ review. If a member-facing string is unavoidable, collect it in the handoff for Paul's
+ morning copy review rather than blocking.
+- Usage limits: commit WIP, write a resume note in `progress.md` here, and stop. The root
+ session resumes you after the reset.
+- Ledger: keep `progress.md` in this directory current (phase, round history, decisions,
+ open items). It's the resume point.
diff --git a/.superpowers/sdd/2026-10-27-edge-roll-blip/progress.md b/.superpowers/sdd/2026-10-27-edge-roll-blip/progress.md
new file mode 100644
index 000000000..96c077c68
--- /dev/null
+++ b/.superpowers/sdd/2026-10-27-edge-roll-blip/progress.md
@@ -0,0 +1,108 @@
+# SDD ledger — plan: docs/superpowers/plans/2026-10-27-edge-roll-blip.md
+
+# edge-roll-blip progress (#434 part B)
+
+Controller started 2026-10-27 (overnight). Finish line: MERGE-READY. No merge/release/roll/infra.
+
+## Phase
+- [x] 1 Spec (child) ae035edf -> docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md
+- [ ] 2 Spec review (Astra, max 3 rounds) -- STOPPED at R2, stopping rule 2 (2026-10-28)
+- [ ] 3 Plan (child) -> docs/superpowers/plans/2026-10-27-edge-roll-blip.md ; amadan tasks
+- [ ] 4 Build (SDD)
+- [ ] 5 Whole-branch Astra review
+- [ ] 6 Merge origin/main, push, CI green, handoff, #434 reply
+
+## Review round history
+- Spec R1 (brief e0b2877a): NOT READY, 2 P1 (rollback compatibility; restart admission), 4 P2. Revised 6e029fd9.
+- Spec R2 (brief dad8843b): NOT READY, 1 P1 (INV-R guard reads failed status query as inactive; SAME FAMILY as R1 P1 -> rule 2), 1 P2 (D10b readmission allowance ignores probe timeout/sequential probing; same family as R1 admission P1). All R1 P2s resolved.
+
+## Decisions
+- D1 carlos-edge.socket (not fd store: stop+start loses store; store handed to old binary on rollback)
+- Rollback: old appliers disable --now added units; ExecStartPre edge-socket-check refuses old binary at socket start
+- Residual: off-road manual downgrade w/o reboot = dark (row 14); morning notes
+- D10 loopback TCP dial hold 13s (same as unix upstream window)
+- R1 fix: INV-R enforced by carlos-edge.service.d guard drop-in (stops socket if binary fails edge-socket-check) + socket ExecStartPre gate; activation is TWO-STEP on existing boxes (roll 2 switch-over, roll 3 first 0-refused). Fresh boxes at once. Decision for Paul.
+- D10b probed local routes held: 13s + rise_after*interval, cap 30s
+- boxes systemd 257 (Debian 13 arm64)
+
+## Open items / resume note
+STOPPED (rule 2). Choice posted on #434 2026-10-28:
+ 1. fix INV-R in one place (fail-closed guard via systemctl show + guard simulation), D10b P2, then spec R3 (last)
+ 2. cut socket activation: ship only D10/D10b local-upstream hold + listener log line
+ 3. refuse up front: 2 now, socket later behind a rollback version floor
+ Recommended 2 then 3. Resume: on Paul's pick, revise spec accordingly (R3 is the last round if option 1;
+ options 2/3 shrink scope -- a cut spec still counts as round 3 of this design), then plan, build, branch review, CI.
+
+## RESUMED 2026-10-28: Paul ruled "2 then 3" (#434)
+Scope now: local-upstream hold (D10 loopback dial hold 13 s; D10b probed local routes wait for readmission, R2 P2 timing fix) + startup log line reworded for no-socket build. NO socket, no unit/root/updater/rollback change. Socket design -> "Later: option 3" section, not built.
+Next: spec revision -> Astra R3 (FINAL; P1 => stop, post cut, no R4) -> plan -> SDD build -> witness (restart local upstream under load via edge, count 502/503) -> branch review -> merge main -> CI.
+
+## Spec R3 + plan
+- Spec R3 (brief 70a10389, FINAL): READY AFTER FIXES, 0 P1, 4 P2 (hold deadline bounds each dial; witness isolation; D8 empty-addr normalization + bound addr; wake-wait claim). P2s applied 91e351a1. Plan 9476af66. amadan tasks 925-930.
+
+## SDD preflight scan
+| Pair/task | Produces -> consumes | Found |
+|---|---|---|
+| T1->T2 | newEdge, localHold, noHold, defaultLocalHold | consistent |
+| T1->T3 | retryLocalDial, localDialHold | consistent |
+| T1->T4 | localHold{dial,cap,probe,dialer}, isLocalUpstream, newEdge | consistent; T4 changes newEdge to build newProberSet(hold) |
+| T2->T4 | runRestartWitness, witnessStats; T4 adds `probed` subtest | consistent |
+| T1/T4/T5 share edge.go | different regions (tcpProxy/New; multiProxy/newProberSet; RunWithActivatorReady listen) | no overlap |
+| T1 self | tests vs code agree; Step 6 only covers internal/edge callers | gap: external edge.New callers (root e2e_test.go, deploy_e2e_test.go, dbforward_e2e_test.go, internal/host/*, internal/fleetapi, internal/domains) |
+| T2 self | negative control per-instance, no global mutation | ok (R3 P2) |
+| T3 self | ok | ok |
+| T4 self | formula defaults 19 s matches spec | ok |
+| T5 self | ok | ok |
+| T6 | cross-compile builds | ok |
+- Ruling: T1 implementer greps the external edge.New callers for routes that expect a fast failure on a refused loopback addr, runs those tests (targeted -run) and reports durations; fix only if one now fails or slows by the hold — why: plan left it to CI, a CI timeout would cost a round trip — cost if wrong: one extra test run.
+- Ruling: per-task review is a Sonnet task reviewer (spec + quality), not Astra/Opus — why: AGENTS.md rule 3 reserves Astra/Opus per-task review for risk areas (none here), SDD needs a task gate — cost if wrong: a defect caught later in the whole-branch Astra review.
+- Ruling: go test runs with the Bash sandbox off (read-only go cache, unix socket() refused in sandbox) — cost if wrong: none.
+
+## SDD tasks
+Task 1: complete (commits e6ad40aa..0d6dc493, review clean)
+Task 1: minor (deferred): applessroute_test.go `deadAddr` var now names a hang-up server (rename hangupAddr)
+Task 1: minor (deferred): 100 ms timing windows in TestNonLoopbackAddrRouteFailsAtOnce / TestLocalHoldOffKeepsInstant502 may flake under load
+Task 1: minor (deferred): cut && !retryable -> errHoldExpired also catches an unrelated non-retryable error at the deadline (filed as timeout)
+Task 1: note: external test fixture TestErrshipAppLessRouteWritesNothing changed refused -> hang-up (52 s -> 0.14 s); reviewer judged purpose intact
+Task 2: complete (commits 8116b09b..0f2ae3b2, review clean)
+Task 2: witness run: tcp gap=1.504s req=2738 502=0 503=0 other=0 max=1.506s; unix gap=1.502s req=2813 0/0/0 max=1.508s; tcp-hold-off 502=2181
+Task 2: minor (deferred): duplicate pass checks tcp/unix -> checkWitness helper
+Task 2: minor (deferred): no "was held" floor (max >= gap/2) so unix could pass vacuously
+Task 2: minor (deferred): p50/p99 over all requests hide the hold; add held=<n> count
+Task 2: minor (deferred): CARLOS_RATE_LIMIT env could turn witness load into 429s; pin e.rateMode = RateOff per Edge
+- Ruling: Task 4 folds Task 2's four witness minors in (it edits the same file and adds the probed subtest) — why: cheap hardening before a third copy of the checks — cost if wrong: a slightly larger Task 4 diff.
+Task 3: complete (commits 81528751..af1172dd, review clean)
+Task 3: minor (deferred): dialGenUntil repeats retryLocalDial loop skeleton (brief-mandated shape; generation logic inside loop)
+Task 3: minor (deferred): no test pins generation-dial "retryable error stops at deadline, no extra attempt"
+Task 3: minor (deferred): cut && non-retryable masks e.g. ErrPeerMismatch at the deadline as errHoldExpired (same as retryLocalDial)
+Task 4: complete (commits 0a9793c5..53bce5ef, review clean)
+Task 4: witness probed: gap=1.501s req=2486 ok=2486 502=0 503=0 other=0 max=1.710s held=8
+Task 4: minor (deferred): no probed-path test for client cancel mid-hold (no Eject)
+Task 4: minor (deferred): 100 ms slack in WaitsForReadmission/EmptyLiveSetOnArrivalWaits/HoldSurvivesReload (restart 200 ms vs 550 ms hold)
+Task 4: minor (deferred): 150 ms want503At / 100 ms RemoteOnly/MixedSet bounds CI-sensitive
+Task 4: minor (deferred): DelayedProbe helper goroutine calls t.Cleanup/t.Errorf off the test goroutine
+Task 4: minor (deferred): multiProxy DialContext ~100 lines, 4 nesting levels
+Task 4: minor (deferred): reload dropping the route mid-hold waits the full hold (bounded, by design)
+Task 4: note: prober transport dials via hold.dialer (nil in prod); hold.probe<=0 -> probeTimeout
+- Ruling: Task 6 also fixes the CI-timing minors (Task 1 100 ms windows; Task 4 minors 1-4) before CI sees them — why: a flaky CI run costs a round trip overnight — cost if wrong: a slightly larger cleanup diff.
+Task 5: complete (commits 65e4e8d5..41a36bff, review clean)
+Task 5: minor (deferred): ":0 " guard in listeners_test nearly vacuous; no test of %w-unwrap / empty-flag bind; non-dev bind path untested beyond helpers (largebox test covers it in CI)
+Task 6: fix round 1/5 (1 addressed, 0 open — cancel test now drives DialContext directly: Go detaches dial ctx from request; commits 0608fe9c..005fd4ac)
+Task 6: complete (commits 1ee33d28..005fd4ac, review clean after 1 fix round)
+Task 6: note: gofmt/vet/darwin+windows builds clean; combined new tests PASS plain 10.5 s, -race 15.6 s
+Task 6: minor (deferred): edge.go multiProxy "client left so don't eject" comment only true for direct DialContext callers (dial ctx detached)
+Task 6: finding: witness/probed flaked 1 in ~9 runs: 502=2 'proxy error: EOF' = requests queued in the upstream's accept backlog when its Shutdown closed the listener (kernel RST). Real-world boundary case the dial hold cannot cover (connect succeeded).
+- Ruling: do NOT add an idempotent-request replay in this branch; instead Task 7 makes the witness classify 502s by the Edge's recorded cause, pass on zero refused/timeout/no-upstream failures, and report boundary resets separately (bounded by worker count) — why: replaying GETs changes request semantics beyond Paul's option-2 ruling and the R3-reviewed spec; offered to Paul as a follow-up — cost if wrong: a few GETs at the exact upstream listener-close boundary still 502 until the follow-up.
+Task 7: complete (commits 9ba1743c..18b9bd39, review clean)
+Task 7: witness -count=10: 3/10 runs had boundary resets (probed 3, probed 1, unix 2); -race run probed 4, tcp 1; all within bound 8
+Task 7: minor (deferred): no per-cause breakdown on failure; reset bound not time-correlated with Shutdown
+
+## Branch phase
+- Merged origin/main (01f1edc1). Census failed (Edge.Reload, RunWithActivatorReady body; envelope internal/edge) -> census-propose fe5e9dc5; census tests pass.
+- CI on fe5e9dc5 started. Whole-branch Astra R1: brief 513f94fe, running (log $TMPDIR/erb/astra-branch-r1.log); also gives census verdicts (record on #280).
+- Branch R1 (Astra, brief 513f94fe, reviewed fe5e9dc5): READY AFTER FIXES, 0 P1, 2 P2 (deadline masks unrelated errors; cancel test isolation), 1 P3. Census units + envelope APPROVED.
+- Fix 54e35662; Astra fix check e2607f19: both P2 RESOLVED, no new issues, envelope re-APPROVED. Census verdict recorded on #280.
+- Merged origin/main again (09767fb0), census overlay re-sealed on top of team-scoped-credentials. CI PASSED on 09767fb0.
+- Ruling: keep the SDD workspace (BRIEF.md and progress.md are committed there and are the resume point) instead of deleting it per the SDD skill — cost if wrong: two small committed files.
+- Final witness (09767fb0): tcp 2713 req 0 fail max 1.512s gap 1.509s; unix 2707/0 max 1.512s; probed 2363/0 max 1.710s; hold-off 502=2126.
+STATE: MERGE-READY pending CI on the final docs tip. Not merged, not released, not rolled.
diff --git a/docs/superpowers/notes/census-proposal-edge-roll-blip.md b/docs/superpowers/notes/census-proposal-edge-roll-blip.md
new file mode 100644
index 000000000..f9f27be44
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-edge-roll-blip.md
@@ -0,0 +1,21 @@
+# Census approval: edge-roll-blip
+
+Ruling `census-ruling-edge-roll-blip`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/edge.go` `Edge.Reload` | body | unchanged (52) | the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites |
+| `internal/edge/edge.go` `RunWithActivatorReady` | body | unchanged (5) | the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites |
+
+Envelopes re-pinned: `internal/edge`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/edge.go` `Edge.Reload`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged
+- `internal/edge/edge.go` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites
+
+Seal: `2cced1b359b64855bacc94c64e0370e6b78cfe2c4947d6d4944915b3a05c6a7c` → `886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-27-edge-roll-blip.md b/docs/superpowers/plans/2026-10-27-edge-roll-blip.md
new file mode 100644
index 000000000..10396f8bf
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-edge-roll-blip.md
@@ -0,0 +1,366 @@
+# Edge roll blip (#434 part B) 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:** When a loopback or unix upstream restarts, requests through the edge wait for it
+instead of getting 502 or 503, and the edge logs one line once its own listeners are bound.
+
+**Architecture:** One deadline-bounded retry loop (`retryLocalDial`) shared by unix dials and a
+new loopback TCP dial (D10). Probed routes with a local addr retry live-set passes until a
+computed hold (D10b), without dialing ejected upstreams. Hold settings live on each `Edge`
+(`localHold`), never in mutable globals. D8 binds before serving and logs the bound addresses.
+
+**Tech Stack:** Go 1.26, `net/http`, `httputil.ReverseProxy`, `net/netip`. Package
+`internal/edge` only.
+
+**Spec:** `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md` (rev 4). Read §2-§6 and
+§10 before any task.
+
+## Global Constraints
+
+- Hold values (spec §2-§3): `localDialHold = 13 * time.Second`, `localHoldCap = 30 * time.Second`,
+ `probeTimeout = 2 * time.Second` (all stay `const`), retry/poll step 100 ms,
+ `multiDialTimeout` 3 s unchanged.
+- `localHold.dial <= 0` turns D10 off (today's transport, no `DialContext` wrapper);
+ `Hold` returns `(0, false)` when `dial <= 0` or `cap <= 0`, which turns D10b off.
+- No test mutates a package global. Tests build their Edge with `newEdge(reg, act, hold)`.
+- Causes unchanged: refused past hold `CauseRefused` (502); a cut stalled TCP attempt
+ `CauseTimeout` (502); probed past hold `CauseNoUpstream` (503 + `Retry-After: 2`).
+- Operator log lines only, no member copy; neutral hosts (`shop.example.com`). No unit file,
+ root, updater, install or rollback change.
+- Tests: only `./internal/edge/` with `-run`, `-count=1`. Never `make test` or the full suite;
+ CI runs it. Leave `GOCACHE` at its default. The sandbox mounts `~/.cache/go-build`
+ read-only and refuses unix `socket()`, so run `go test`/`go build` outside it.
+- Unix sockets: use `shortSockDir(t)` (`internal/edge/door_test.go:902`); `genSockDir(t)`
+ (`genproxy_test.go:112`) is the same shape. Both `os.MkdirTemp("", ...)` under `$TMPDIR`. If
+ a socket test fails with `bind: invalid argument` (sun_path too long), rerun it with
+ `mkdir -p /tmp/g && TMPDIR=/tmp/g go test ...`; the sockets are removed by the helpers'
+ cleanup.
+- Commits end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Never
+ `git stash`, `git checkout -- <file>`, pattern deletes.
+- Rule 3 (AGENTS.md): no task touches a security gate, root, termination, a cache,
+ production storage, billing or a redirect, so no per-task Astra/Opus review; one
+ whole-branch review before merge.
+
+## Review Focus
+
+1. Tests elsewhere that reach a refused loopback addr through `edge.New` (root `e2e_test.go`,
+ `deploy_e2e_test.go`, `internal/host/applessroute_test.go`, `internal/fleetapi`) now wait
+ 13 s or more instead of failing fast. Expected: CI durations barely move; if one slows, the
+ fix is its own route, not a weaker hold. Task 1 Step 6 covers this package's set.
+2. `localhost:P` resolves to both `::1` and `127.0.0.1`; refused on both must still retry
+ (Task 1, `TestLoopbackAddrRouteHolds/localhost`).
+3. Many requests held at once on a down upstream all release at the hold, with no goroutine
+ left behind (Task 1, `TestHeldDialsReleaseAfterHold`).
+4. A Reload during a held probed request: the request keeps its entry deadline and sees the
+ new live set (Task 4, `TestProbedHoldSurvivesReload`).
+5. A stalled loopback attempt (accepting nothing) is cut at the deadline, not 3 s or 13 s
+ later (Task 1, `TestRetryLocalDialBlockingAttemptEndsAtDeadline`; Task 4,
+ `TestProbedDeadlineMidPassDoesNotEject`).
+
+---
+
+### Task 1: Loopback TCP routes hold the dial (D10)
+
+Rule 3 gates: no.
+
+**Files:**
+- Create: `internal/edge/localhold.go`, `internal/edge/localhold_test.go`
+- Modify: `internal/edge/edge.go` (`Edge` struct; `New` at `:457`; `tcpProxy` calls at
+ `:851,864`; `tcpProxy` at `:2736`), `internal/edge/answered.go:58-64` (comment gains
+ loopback TCP and probed routes)
+- Modify (tests that need the old instant failure): `internal/edge/edge_test.go`,
+ `internal/edge/edgeerrors_test.go`
+
+**Interfaces (Produces):**
+```go
+const localDialHold = 13 * time.Second
+const localHoldCap = 30 * time.Second
+type localHold struct {
+ dial, cap, probe time.Duration
+ dialer func(ctx context.Context, network, addr string) (net.Conn, error) // test seam; nil = net.Dialer
+}
+func defaultLocalHold() localHold // {localDialHold, localHoldCap, probeTimeout, nil}
+func isLocalUpstream(addr string) bool
+var errHoldExpired = fmt.Errorf("edge: local upstream hold expired: %w", context.DeadlineExceeded)
+func retryLocalDial(ctx context.Context, deadline time.Time, attempt func(context.Context) (net.Conn, error)) (net.Conn, error)
+func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) // New = newEdge(reg, act, defaultLocalHold())
+func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy
+// test helper in localhold_test.go:
+func noHold() localHold // localHold{probe: probeTimeout}
+```
+
+- [ ] **Step 1: Write the failing tests** in `localhold_test.go`:
+ - `TestIsLocalUpstream`: true for `127.0.0.1:80`, `127.9.9.9:80`, `[::1]:80`,
+ `localhost:80`; false for `10.0.0.5:80`, `example.com:80`, `nonsense`.
+ - `TestRetryLocalDialServesWhenUpstreamReturns`: attempt returns `ECONNREFUSED` (wrapped in
+ `*net.OpError`) twice, then a `net.Pipe` end; got conn, 3 attempts.
+ - `TestRetryLocalDialReturnsLastRefusalAtDeadline`: always refused, deadline now+300 ms;
+ `errors.Is(err, syscall.ECONNREFUSED)`, elapsed in [300 ms, 450 ms).
+ - `TestRetryLocalDialBlockingAttemptEndsAtDeadline`: attempt blocks on `<-actx.Done()` and
+ returns `actx.Err()`; deadline now+200 ms; `errors.Is(err, errHoldExpired)` and
+ `errors.Is(err, context.DeadlineExceeded)`, elapsed < 300 ms.
+ - `TestRetryLocalDialNonRetryableFailsAtOnce`: `errors.New("boom")`, exactly one attempt.
+ - Edge-level, each on `newEdge(reg, nil, localHold{dial: d, probe: probeTimeout})` behind
+ `httptest.NewServer(e)`, route `{Host: "shop.example.com", Kind: "service", Status:
+ "ready", Addr: a}`:
+ - `TestLoopbackAddrRouteHolds` with subtests `127.0.0.1` and `localhost`: `a` from
+ `deadAddr(t)` (host swapped to `localhost` in the second); a listener answering 200 on
+ `a` starts after 300 ms; `d` 2 s; GET gives 200.
+ - `TestLoopbackAddrRouteRefusedPastHold`: `d` 200 ms, nothing listens; 502, and with
+ `e.EnableErrors(sink)` (`memErrSink`, `edgeerrors_test.go:21`) the record's cause is
+ `apperr.CauseRefused`.
+ - `TestNonLoopbackAddrRouteFailsAtOnce`: `a` = `10.0.0.5:80`, `hold.dialer` counts calls
+ and returns a refused `*net.OpError`; 502 within 100 ms, exactly 1 call.
+ - `TestHeldDialClientCancelReturnsAtOnce`: dead `a`, `d` 2 s, client request context
+ times out at 100 ms; `Do` returns within 300 ms.
+ - `TestHeldDialPOSTBodyArrives`: upstream starts after 300 ms and echoes the body; a
+ 64 KiB POST body arrives byte-identical.
+ - `TestHeldDialWebSocketUpgrade`: `upgradeEchoBackend` (as in `edge_test.go:2030`) started
+ on a reserved port after 300 ms; the upgrade echoes.
+ - `TestHeldDialsReleaseAfterHold`: 50 concurrent GETs, `d` 300 ms, all 502 within 1 s;
+ `runtime.NumGoroutine()` returns to within 10 of its baseline within 2 s.
+ - `TestLocalHoldOffKeepsInstant502`: `noHold()`, dead `a`; 502 within 100 ms.
+
+- [ ] **Step 2: Run, expect FAIL (undefined: `isLocalUpstream`, `newEdge`, ...)**
+
+Run: `go test ./internal/edge/ -run 'TestIsLocalUpstream|TestRetryLocalDial|TestLoopbackAddrRoute|TestNonLoopbackAddrRoute|TestHeldDial|TestLocalHoldOff' -count=1`
+
+- [ ] **Step 3: Implement `localhold.go`**
+
+`isLocalUpstream`: `net.SplitHostPort`, then `host == "localhost"` or
+`netip.ParseAddr(host)` ok and `IsLoopback()`. `retryLocalDial` per spec §2 "One deadline":
+each attempt on `context.WithDeadline(ctx, deadline)`; on error, if `ctx.Err() != nil` return
+it; if the attempt context is done (deadline cut, parent not) return `errHoldExpired`; if not
+`isRetryableDialErr`, return it; if no time left, return it; else wait min(100 ms, time left)
+or `ctx.Done()`. It always makes the first attempt.
+
+- [ ] **Step 4: Wire the Edge**
+
+Add `hold localHold` to `Edge`; `New` becomes `newEdge(reg, act, defaultLocalHold())`, with
+`e.hold` set before the startup Reload. `tcpProxy(addr, hold)`: when `hold.dial > 0 &&
+isLocalUpstream(addr)`, `Transport.DialContext` = fixed `deadline := time.Now().Add(hold.dial)`
+then `retryLocalDial` over `hold.dialer` or a `net.Dialer{}`; otherwise
+`Transport.DialContext = hold.dialer` (nil in production: today's transport). Both call sites
+pass `e.hold`. Update the `answered.go:58-64` comment.
+
+- [ ] **Step 5: Run Step 2's command, expect PASS**
+
+- [ ] **Step 6: Keep the package's refused-loopback tests fast**
+
+Run: `go test ./internal/edge/ -run 'TestEdgeFilesUnavailableByCause|TestLegacySingleAddrRouteUnchanged|TestMultiAddrWithoutHealthServesFirstUnprobed' -count=1 -v`
+Any that now takes 13 s or more (unprobed route on `deadAddr`) switches its `New(reg, nil)` to
+`newEdge(reg, nil, noHold())`; its assertions stay as they are. Rerun, expect PASS, each
+under 1 s.
+
+- [ ] **Step 7: Commit** `edge-roll-blip: D10, loopback TCP routes hold the dial`
+
+### Task 2: Restart witness (`tcp`, `unix`, negative control)
+
+Rule 3 gates: no.
+
+**Files:**
+- Create: `internal/edge/localhold_witness_test.go`
+
+**Interfaces:**
+- Consumes: `newEdge`, `localHold`, `noHold()` (Task 1); `openReg`, `shortSockDir`.
+- Produces: `runRestartWitness(t *testing.T, e *Edge, listen func() (net.Listener, error)) witnessStats`
+ (`listen` binds the upstream's fixed address, called once per server),
+ and `witnessStats{requests, ok, s502, s503, other int; p50, p99, max time.Duration}` (added
+ wait), reused by Task 4's `probed` subtest.
+
+- [ ] **Step 1: Write `TestLocalUpstreamRestartWitness`** per spec §6: `testing.Short()` skips;
+ subtests `t.Parallel()`, each on its own `newEdge` and `httptest.NewServer(e)`:
+ - `tcp`: unprobed `Addr` route to a reserved `127.0.0.1:P`, `defaultLocalHold()`.
+ - `unix`: `Socket` route under `shortSockDir(t)`; `runtime.GOOS == "windows"` skips.
+ - `tcp-hold-off` (negative control): as `tcp` on `newEdge(reg, nil, noHold())`.
+ The runner: upstream `http.Server` answering `/` and `/healthz` 200; eight workers on
+ keep-alive clients send `GET /` with Host `shop.example.com`; 1 s baseline; then
+ `Shutdown` with a 5 s drain context, a 1.5 s gap (port refuses or socket file absent), a new
+ `http.Server` on the same address; 1 s more. Count by status, transport errors as `other`.
+ Added wait = latency minus baseline p50. Each subtest logs:
+ ```go
+ t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v", ...)
+ ```
+ Pass for `tcp` and `unix`: `s502 == 0 && s503 == 0 && other == 0` and `max < gap+time.Second`.
+ Pass for `tcp-hold-off`: `s502 > 0`.
+
+- [ ] **Step 2: Run, expect PASS with three log lines**
+
+Run: `go test ./internal/edge/ -run TestLocalUpstreamRestartWitness -count=1 -v`
+
+- [ ] **Step 3: Prove it can fail.** Temporarily give the `tcp` subtest `noHold()`; rerun;
+ expect FAIL on `s502`. Restore by editing the line back (never `git checkout --`).
+
+- [ ] **Step 4: Commit** `edge-roll-blip: local restart witness (tcp, unix, hold-off control)`
+
+### Task 3: Unix dials on the shared loop and constant
+
+Rule 3 gates: no.
+
+**Files:**
+- Modify: `internal/edge/genproxy.go:39-63` (`dialUnixRetrying` body becomes a
+ `retryLocalDial` call with `deadline := time.Now().Add(localDialHold)`, resolving the socket
+ inside the attempt), `:85-86` (`dialGen`: same deadline, each attempt on
+ `context.WithDeadline`, wait min(100 ms, time left)), `:311-312` (`waitServingGen` on
+ `localDialHold`); `internal/edge/edge.go:3502-3508` (comment names `localDialHold`).
+
+**Interfaces:** Consumes `retryLocalDial`, `localDialHold` (Task 1). Produces nothing new.
+
+- [ ] **Step 1: Make the change**; `grep -n '13 \* time.Second' internal/edge/genproxy.go`
+ returns nothing.
+- [ ] **Step 2: Run the existing unix and generation tests, expect PASS unchanged**
+
+Run: `go test ./internal/edge/ -run 'TestDialUnixRetrying|TestAppSocketProxy|TestGenPools|TestGenRoundTripper|TestUnixSocketUpstream|TestLocalUpstreamRestartWitness/unix' -count=1`
+
+- [ ] **Step 3: Commit** `edge-roll-blip: unix dials share the local hold loop and window`
+
+### Task 4: Probed routes with a local upstream wait for readmission (D10b)
+
+Rule 3 gates: no.
+
+**Files:**
+- Modify: `internal/edge/prober.go` (`newProberSet` at `:126`, `newHostProber` at `:188`,
+ `Sync` call at `:292`, new `Hold`), `internal/edge/edge.go` (`newEdge` builds
+ `newProberSet(hold)`; `multiProxy` at `:2817` and its call at `:871`)
+- Modify: `internal/edge/prober_test.go` (nine `newProberSet()` calls become
+ `newProberSet(defaultLocalHold())`), `internal/edge/edge_test.go`
+ (`TestSingleAddrWithHealthGets503Semantics`, `TestAllUpstreamsDownAnswers503WithRetryAfter`
+ and any other probed `deadAddr` test that now waits switch to `noHold()`),
+ `internal/edge/localhold_witness_test.go` (`probed` subtest)
+- Create: `internal/edge/localhold_probed_test.go`
+
+**Interfaces:**
+- Consumes: `localHold`, `isLocalUpstream`, `newEdge`, `runRestartWitness`.
+- Produces:
+```go
+func newProberSet(hold localHold) *proberSet // client Timeout and ResponseHeaderTimeout = hold.probe
+func newHostProber(spec probeSpec, client *http.Client, hold localHold) *hostProber // records hp.local, hp.hold
+func (p *proberSet) Hold(host string) (time.Duration, bool) // unknown host: (0, false)
+func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProxy
+```
+
+- [ ] **Step 1: Write the failing tests** in `localhold_probed_test.go`:
+ - `TestHoldMatchesFormula` (table, `newHostProber` with `defaultLocalHold()` on
+ `WithDefaults()`ed specs): one local addr 19 s; local + 1 other 23 s; + 2 27 s; + 3 30 s
+ (cap); remote-only `(0, false)`; raw `Health{}`, `IntervalMS: -1`, `RiseAfter: -1` each
+ 19 s; `dial: 0` gives `(0, false)`.
+ - Behaviour, each through `newEdge` + `httptest.NewServer`, route `Addrs` + `Health:
+ healthJSON(t, provision.Health{Path: testProbePath, IntervalMS: 100, FailAfter: 1,
+ RiseAfter: 2})`, hold `localHold{dial: 300ms, cap: 5s, probe: 50ms}` unless stated:
+ - `TestProbedLocalUpstreamWaitsForReadmission`: the upstream (`countingBackend`-style on a
+ reserved port) is stopped, a GET is sent, it restarts after 200 ms; 200, and its
+ proxied-request counter is exactly 1 (nothing reached it while ejected).
+ - `TestProbedEmptyLiveSetOnArrivalWaits`: as above but the GET waits until
+ `len(e.probers.Live(host)) == 0` first; 200.
+ - `TestProbedLocalStillDownPastHold`: never restarts; 503, `Retry-After: 2`, cause
+ `CauseNoUpstream`, elapsed within 150 ms of `Hold(host)`.
+ - `TestProbedPastCapAnswersAtCap`: `cap: 400ms` (below `dial + R`); 503 within 150 ms of
+ 400 ms.
+ - `TestProbedRemoteOnlyAnswersAtOnce`: `Addrs` `10.0.0.5:80`, `hold.dialer` refuses; 503
+ within 100 ms.
+ - `TestProbedMixedSetWithLiveUpstreamServesAtOnce`: `deadAddr` plus a live backend; 200
+ within 100 ms.
+ - `TestProbedDelayedProbeServedWithinR` (spec §10 "Delayed probe"): three loopback
+ upstreams whose `/healthz` blocks past `probe`, ordered before one restarting
+ upstream; served at readmission, measured readmission at most `R` from the formula.
+ - `TestProbedDeadlineMidPassDoesNotEject`: `Addrs` `deadAddr` + `10.0.0.9:80`,
+ `frozenHealth()`, `cap: 400ms`, `hold.dialer` blocks on `10.0.0.9:80` until its
+ context ends; 503 `CauseNoUpstream` within 150 ms of 400 ms, and
+ `e.probers.Live(host)` still contains `10.0.0.9:80`.
+ - `TestProbedHoldSurvivesReload`: upstream down, GET in flight, `e.Reload()` after 100 ms,
+ upstream back after 200 ms; 200.
+ - In the witness: subtest `probed`, `Addrs` route to `127.0.0.1:P`, `Health{Path:
+ "/healthz", IntervalMS: 100, FailAfter: 1, RiseAfter: 2}`, `defaultLocalHold()`; pass
+ when zero failures and `max < gap + R`, with `R` from `Hold`'s formula.
+
+- [ ] **Step 2: Run, expect FAIL**
+
+Run: `go test ./internal/edge/ -run 'TestHoldMatchesFormula|TestProbed|TestLocalUpstreamRestartWitness' -count=1 -v`
+
+- [ ] **Step 3: Implement the hold in `prober.go`.** In `newHostProber`, after clamping:
+ `N = len(hp.order)`, `I = hp.interval`, `r = hp.riseAt`, `T = hold.probe`;
+ `G = max(I, T) + (N-1)*T`; `R = r*G + T`; `hp.hold = min(hold.dial+R, hold.cap)`;
+ `hp.local` = any `hp.order` addr passes `isLocalUpstream`, and false when `hold.dial <= 0`
+ or `hold.cap <= 0`. `proberSet` keeps `hold` for `Sync`'s `newHostProber` call.
+
+- [ ] **Step 4: Implement the passes in `multiProxy`'s `DialContext`** (spec §3):
+```go
+hold, local := p.Hold(host)
+var deadline time.Time
+if local { deadline = time.Now().Add(hold) }
+for {
+ // one pass: today's walk over a fresh p.Live(host); each attempt on
+ // context.WithTimeout(ctx, multiDialTimeout), and also WithDeadline(deadline) when local;
+ // dial via hold.dialer when non-nil.
+ // A failed attempt with ctx.Err() != nil: return it, no Eject (today).
+ // A failed attempt after the deadline has passed: budget exhaustion, no Eject,
+ // return errNoLiveUpstream. Any other failure: Eject, next addr (today).
+ // No connection: if !local or no time left, return errNoLiveUpstream (wrapped as today);
+ // else wait min(100ms, time left) or ctx.Done(), and pass again.
+}
+```
+ An empty live set is a pass with nothing to dial. `ErrorHandler` unchanged.
+
+- [ ] **Step 5: Run Step 2's command, expect PASS**
+
+- [ ] **Step 6: Keep the existing probed tests fast**
+
+Run: `go test ./internal/edge/ -run 'TestMultiUpstream|TestDialFailureRetriesOtherUpstream|TestSingleAddrWithHealth|TestAllUpstreamsDown|TestUpstreamStates|TestProber|TestEjectIsImmediate|TestAliasSharesMultiUpstreamEntry' -count=1 -v`
+Any that now waits for a hold switches to `newEdge(reg, nil, noHold())`; rerun, expect PASS.
+
+- [ ] **Step 7: Commit** `edge-roll-blip: D10b, probed local upstreams wait for readmission`
+
+### Task 5: D8, bind before serving and log the bound listeners
+
+Rule 3 gates: no. The :80 handler (ACME and redirect) and the TLS config are untouched; only
+how the listeners are bound changes, as `ListenAndServe(TLS)` does it internally.
+
+**Files:**
+- Create: `internal/edge/listeners.go`, `internal/edge/listeners_test.go`
+- Modify: `internal/edge/edge.go:3642-3649` (dev block), `:3814-3829` (http + https)
+
+**Interfaces (Produces):**
+```go
+func listenAddr(flag, def string) string // "" -> def (":http" or ":https"), else flag
+func listen(name, flag, def string) (net.Listener, error) // err: fmt.Errorf("edge: %s listener %s: %w", name, flag, err)
+func listenersLine(httpLn net.Listener, httpFlag string, httpsLn net.Listener, httpsFlag string) string // httpsLn nil = dev form
+```
+
+- [ ] **Step 1: Write the failing tests**
+ - `TestListenAddrNormalizesEmpty`: `("", ":http")` gives `:http`; `("", ":https")` gives
+ `:https`; `("127.0.0.1:8080", ":http")` gives `127.0.0.1:8080`.
+ - `TestListenNamesTheListenerOnFailure`: hold `127.0.0.1:0`'s port with one listener, then
+ `listen("http", addr, ":http")`; error starts `edge: http listener 127.0.0.1:`.
+ - `TestListenersLineGivesBoundAddresses`: two `listen` calls on `127.0.0.1:0`; the line is
+ exactly `fmt.Sprintf("edge: listeners: bound http %s and https %s itself (flags %q %q)",
+ h.Addr(), s.Addr(), "127.0.0.1:0", "127.0.0.1:0")` and does not contain `:0 `.
+ - `TestListenersLineDevForm`: `listenersLine(h, "127.0.0.1:0", nil, "")` is
+ `fmt.Sprintf("edge: listeners: bound http %s itself (dev mode; flag %q)", h.Addr(), "127.0.0.1:0")`.
+
+- [ ] **Step 2: Run, expect FAIL**
+
+Run: `go test ./internal/edge/ -run 'TestListenAddr|TestListenNames|TestListenersLine' -count=1`
+
+- [ ] **Step 3: Implement `listeners.go`; wire `RunWithActivatorReady`.** Bind on the calling
+ goroutine before the serve goroutines: `listen("http", *httpAddr, ":http")`, then (not dev)
+ `listen("https", *httpsAddr, ":https")`, `log.Fatal(err)` on failure; `log.Print` the
+ line; the goroutines call `srv.Serve(ln)` and `httpsSrv.ServeTLS(ln, "", "")`, keeping the
+ `http.ErrServerClosed` check and today's `serving N route(s)` / `DEV MODE` lines.
+
+- [ ] **Step 4: Run Step 2's command, expect PASS**
+
+- [ ] **Step 5: Commit** `edge-roll-blip: D8, bind before serving and log the bound listeners`
+
+### Task 6: Vet, format, cross-compile
+
+Rule 3 gates: no.
+
+- [ ] **Step 1:** `gofmt -l internal/edge/` prints nothing.
+- [ ] **Step 2:** `go vet ./internal/edge/` passes.
+- [ ] **Step 3:** `GOOS=darwin GOARCH=arm64 go build ./...` and
+ `GOOS=windows GOARCH=amd64 go build ./...` both succeed (spec §5 D11).
+- [ ] **Step 4:** Once, the branch's new tests together:
+ `go test ./internal/edge/ -run 'TestIsLocalUpstream|TestRetryLocalDial|TestLoopbackAddrRoute|TestNonLoopbackAddrRoute|TestHeldDial|TestLocalHoldOff|TestHoldMatchesFormula|TestProbed|TestListen|TestLocalUpstreamRestartWitness' -count=1 -v`;
+ PASS, and copy the four `local-hold witness:` lines for the #434 reply.
+- [ ] **Step 5:** Commit any fixes as `edge-roll-blip: vet and gofmt`; otherwise nothing.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch-fixcheck.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch-fixcheck.md
new file mode 100644
index 000000000..e56106b67
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch-fixcheck.md
@@ -0,0 +1,26 @@
+# Fix check: edge-roll-blip whole-branch round 1 P2 fixes + census on the fix (not a new round)
+
+Repo carlos/platform, branch `edge-roll-blip`. Under review: only the fix diff
+`f5993f52..54e35662` (`git diff f5993f52..54e35662`).
+
+Round 1 (`docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch.md`) was READY
+AFTER FIXES with two P2s. Per AGENTS.md stopping rule 1 the P2 fixes do not reopen the review;
+two checks still apply to the diff they produce, inside the same budget: the census, and
+whether the fix changed any security, root, termination or production-storage behaviour.
+
+Do exactly this:
+1. For P2-1 (failure-cause preservation at the hold deadline) and P2-2 (cancel-test isolation):
+ one line each, RESOLVED / PARTLY / NOT, with file:line.
+2. Any new problem the fix diff itself introduced (P1/P2/P3), with file:line. Nothing outside
+ the fix diff.
+3. Census: the fix re-pinned the `internal/edge` envelope (overlay
+ `internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv`, card
+ `docs/superpowers/notes/census-proposal-edge-roll-blip.md`). Verdict APPROVE or REJECT
+ for the envelope on the fix diff: reject if it lets root open, run, query or follow
+ anything it did not before from a path or input a tenant, an app or a box agent can
+ create, write or name, or weakens a check, refusal, validation, argument or environment
+ root relies on.
+End with one line: `FIX CHECK: CLEAN` or `FIX CHECK: OPEN <list>`.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run
+the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch.md
new file mode 100644
index 000000000..6ab400638
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-edge-roll-blip-branch.md
@@ -0,0 +1,79 @@
+# Review brief: edge-roll-blip whole branch (#434 part B, option 2), round 1 of 3
+
+Repo carlos/platform, branch `edge-roll-blip`, commit fe5e9dc57052161113924df354af9d45bea4cb4e (the commit before this brief).
+Under review: the diff `ee066183642d4b8e374f4fa5052b0b92349a60fc..fe5e9dc57052161113924df354af9d45bea4cb4e` (origin/main is merged in; review the branch's own changes:
+`git diff ee066183642d4b8e374f4fa5052b0b92349a60fc..fe5e9dc57052161113924df354af9d45bea4cb4e`). Mostly `internal/edge/`, one test fixture in
+`internal/host/applessroute_test.go`, census overlay files, and docs.
+Authorities: the spec `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md`
+(rev 4; its own review ended at round 3, READY AFTER FIXES, P2s applied) and the plan
+`docs/superpowers/plans/2026-10-27-edge-roll-blip.md`; AGENTS.md. Do not review against
+unmerged branches.
+
+You are an independent reviewer. Read the spec, then the diff, and check the code against
+the spec and against the existing code it touches.
+
+## Fixed: do not re-argue
+
+- Paul's ruling, 2026-10-28, on amadan #434 ("2 then 3"): scope is the local-upstream hold
+ plus a startup log line. No `carlos-edge.socket`, no unit, root, updater, install or
+ rollback change. The spec's "Later: option 3" section is not built and not under review.
+- Controller ruling (in `docs/superpowers/reviews/edge-roll-blip-ledger-minors.md`): no
+ idempotent-request replay in this branch. Requests queued in a local upstream's accept
+ backlog when it closes its listener are reset after connect; the dial hold cannot cover
+ them, and the witness counts them separately as `resets` (bounded by its 8 workers).
+ You may say whether that ruling leaves a defect, but not as a P1 unless the code is wrong.
+
+## What to check
+
+1. D10 (`localhold.go`, `tcpProxy`, `genproxy.go` unix paths): local detection, one
+ absolute deadline bounding every attempt and wait, what is retried, causes filed
+ (`answered.go`/`proxyCause`), no goroutine or connection leak, behaviour unchanged for
+ non-local upstreams and with the hold off.
+2. D10b (`prober.go` Hold/readmitHold, `multiProxy` DialContext): never dials an ejected
+ upstream; no Eject on budget exhaustion or cancel; formula vs the prober's real tick
+ schedule; races on shared prober state; the prober transport now dialing through
+ `hold.dialer` (nil in production).
+3. D8 (`listeners.go`, `RunWithActivatorReady`): binding behaviour identical to
+ `ListenAndServe(TLS)` (empty-address defaults, TLS config, fatal message the large-box
+ test greps), no change to when the edge accepts relative to startup/latch/certs.
+4. Tests: do they test behaviour, would they fail on the regressions they name, are they
+ fast and non-flaky in CI (loaded, sometimes -race), and does the witness
+ (`localhold_witness_test.go`) measure honestly.
+5. Cross-compile (darwin/windows) and anything linux-only.
+6. Triage the deferred minors in `docs/superpowers/reviews/edge-roll-blip-ledger-minors.md`:
+ name any that must be fixed before merge.
+
+## Census (AGENTS.md "The census")
+
+The census card is `docs/superpowers/notes/census-proposal-edge-roll-blip.md` (overlay
+`internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv`). Give a verdict for every
+unit and the re-pinned envelope (`internal/edge`), citing the lines you read: reject if the
+change lets root open, run, query or follow anything it did not before from a path or input a
+tenant, an app or a box agent can create, write or name; if it weakens a check, refusal,
+validation, argument or environment root relies on; or if the diff cannot settle it.
+Otherwise approve.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of
+ any newly changed security, root, termination or production-storage behaviour, still check
+ the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep
+the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the area, the problem, the evidence (file:line,
+verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks
+(its fault family). Then the census verdicts (one line per unit and envelope). End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run
+the full test suites (a focused `go test ./internal/edge/ -run X` is fine if you need one).
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch-fixcheck.md b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch-fixcheck.md
new file mode 100644
index 000000000..6e6571023
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch-fixcheck.md
@@ -0,0 +1,10 @@
+Reviewed only `f5993f52..54e35662`, within round 1’s fix check.
+
+- **P2-1: RESOLVED** — [localhold.go:60](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold.go:60) and [genproxy.go:112](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/genproxy.go:112): deadline translation now requires a context or timeout error; unrelated peer-mismatch and control-endpoint errors retain their identity.
+- **P2-2: RESOLVED** — [localhold_probed_test.go:433](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold_probed_test.go:433): only the marked request dial can signal entry and cancellation. The final live-set assertion checks for erroneous post-cancellation ejection.
+- **New P1/P2/P3 problems introduced by the fix: none found.**
+- **Census: APPROVE — `internal/edge` envelope**, [overlay:7](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv:7). The production changes narrow error translation. They add no root access, preserve endpoint and peer refusals, and weaken no security check. No termination or production-storage behavior changes.
+
+`git diff --check` passed. Tests, mutation checks, and the census test were not executed in the read-only sandbox; this verdict rests on source inspection. No files edited.
+
+FIX CHECK: CLEAN
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch.md b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch.md
new file mode 100644
index 000000000..0e84efd2b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-FINDINGS-edge-roll-blip-branch.md
@@ -0,0 +1,40 @@
+Reviewed `ee066183642d4b8e374f4fa5052b0b92349a60fc..fe5e9dc57052161113924df354af9d45bea4cb4e`, whole-branch round 1.
+
+**P1: none found.**
+
+**P2-1 — Error classification: deadline expiry masks unrelated failures.**
+At [localhold.go:75](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold.go:75) and [genproxy.go:111](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/genproxy.go:111), any non-retryable error becomes `errHoldExpired` when the attempt context has expired. Context expiry does not establish that it caused the error.
+
+A peer mismatch or control-endpoint refusal returned around the deadline therefore loses its identity and is filed as a timeout. The connection remains refused; this is a diagnostic defect, not an authorization bypass.
+
+Fix both paths to translate only an error attributable to the attempt’s deadline. Preserve unrelated errors and add regression cases for an expired context accompanied by a distinct non-retryable error.
+
+**Fault family:** failure-cause preservation. This promotes the matching Task 1/3 ledger minor to a required fix.
+
+**P2-2 — Cancellation test: health probes can satisfy the request-dial signals.**
+The callback at [localhold_probed_test.go:426](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold_probed_test.go:426) closes shared `entered` and `dialAborted` channels. It also runs for probes through [prober.go:156](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/prober.go:156). `frozenHealth()` still permits the initial probe tick.
+
+If that probe closes `entered` first, the test can cancel before the request dial starts. The request then returns through the pre-attempt cancellation check; the probe’s timeout supplies `dialAborted`. The test can pass without exercising cancellation during a request dial or its post-dial no-ejection branch.
+
+Fix the fixture to use an initialized prober state without a running probe loop, or identify the request dial separately. Verify that introducing erroneous post-cancellation ejection makes the test fail.
+
+**Fault family:** cancellation-test isolation.
+
+**P3-1 — Witness: “boundary resets” are not correlated with the boundary.**
+[localhold_witness_test.go:184](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold_witness_test.go:184) counts resets across the entire run; [line 253](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold_witness_test.go:253) exempts all of them up to eight. Consequently, unrelated resets during baseline or after recovery can pass as shutdown-boundary resets.
+
+Follow up by correlating exempted failures with requests overlapping listener shutdown and reporting the remaining causes separately. This does not require request replay or block the approved bounded-reset policy.
+
+**Fault family:** witness attribution.
+
+The remaining ledger minors do not require fixes before merge.
+
+Verification: `git diff --check` passed. Focused tests could not start because the read-only sandbox rejected Go’s work-directory creation. Tests, race checks and cross-compilation were therefore not independently executed. No files were edited.
+
+**Census verdicts — reviewed tip `fe5e9dc57052161113924df354af9d45bea4cb4e`:**
+
+- **APPROVE — `Edge.Reload`**, existing `legacy / accepted-legacy` disposition: [edge.go:855](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:855). Changes pass immutable hold settings into existing proxy constructors; route selection and authority checks remain intact.
+- **APPROVE — `RunWithActivatorReady`**, existing `legacy / accepted-legacy` disposition: [edge.go:3732](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:3732) and [edge.go:3911](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:3911). Binding preserves address defaults, TLS configuration, startup preparation and fatal-message compatibility; no new untrusted input or root read.
+- **APPROVE — `internal/edge` envelope**: reviewed construction, retry, generation, probing and listener changes at [edge.go:466](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:466), [localhold.go:36](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/localhold.go:36), [genproxy.go:45](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/genproxy.go:45), [prober.go:134](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/prober.go:134), and [listeners.go:11](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/listeners.go:11). Unix endpoint and peer checks remain enforced; no authority expansion or weakened refusal found.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/edge-roll-blip-ledger-minors.md b/docs/superpowers/reviews/edge-roll-blip-ledger-minors.md
new file mode 100644
index 000000000..fb8cbd585
--- /dev/null
+++ b/docs/superpowers/reviews/edge-roll-blip-ledger-minors.md
@@ -0,0 +1,33 @@
+# edge-roll-blip: deferred minors and controller rulings from the SDD ledger (input to the whole-branch review)
+
+- Ruling: T1 implementer greps the external edge.New callers for routes that expect a fast failure on a refused loopback addr, runs those tests (targeted -run) and reports durations; fix only if one now fails or slows by the hold — why: plan left it to CI, a CI timeout would cost a round trip — cost if wrong: one extra test run.
+- Ruling: per-task review is a Sonnet task reviewer (spec + quality), not Astra/Opus — why: AGENTS.md rule 3 reserves Astra/Opus per-task review for risk areas (none here), SDD needs a task gate — cost if wrong: a defect caught later in the whole-branch Astra review.
+- Ruling: go test runs with the Bash sandbox off (read-only go cache, unix socket() refused in sandbox) — cost if wrong: none.
+Task 1: minor (deferred): applessroute_test.go `deadAddr` var now names a hang-up server (rename hangupAddr)
+Task 1: minor (deferred): 100 ms timing windows in TestNonLoopbackAddrRouteFailsAtOnce / TestLocalHoldOffKeepsInstant502 may flake under load
+Task 1: minor (deferred): cut && !retryable -> errHoldExpired also catches an unrelated non-retryable error at the deadline (filed as timeout)
+Task 2: minor (deferred): duplicate pass checks tcp/unix -> checkWitness helper
+Task 2: minor (deferred): no "was held" floor (max >= gap/2) so unix could pass vacuously
+Task 2: minor (deferred): p50/p99 over all requests hide the hold; add held=<n> count
+Task 2: minor (deferred): CARLOS_RATE_LIMIT env could turn witness load into 429s; pin e.rateMode = RateOff per Edge
+- Ruling: Task 4 folds Task 2's four witness minors in (it edits the same file and adds the probed subtest) — why: cheap hardening before a third copy of the checks — cost if wrong: a slightly larger Task 4 diff.
+Task 3: minor (deferred): dialGenUntil repeats retryLocalDial loop skeleton (brief-mandated shape; generation logic inside loop)
+Task 3: minor (deferred): no test pins generation-dial "retryable error stops at deadline, no extra attempt"
+Task 3: minor (deferred): cut && non-retryable masks e.g. ErrPeerMismatch at the deadline as errHoldExpired (same as retryLocalDial)
+Task 4: minor (deferred): no probed-path test for client cancel mid-hold (no Eject)
+Task 4: minor (deferred): 100 ms slack in WaitsForReadmission/EmptyLiveSetOnArrivalWaits/HoldSurvivesReload (restart 200 ms vs 550 ms hold)
+Task 4: minor (deferred): 150 ms want503At / 100 ms RemoteOnly/MixedSet bounds CI-sensitive
+Task 4: minor (deferred): DelayedProbe helper goroutine calls t.Cleanup/t.Errorf off the test goroutine
+Task 4: minor (deferred): multiProxy DialContext ~100 lines, 4 nesting levels
+Task 4: minor (deferred): reload dropping the route mid-hold waits the full hold (bounded, by design)
+- Ruling: Task 6 also fixes the CI-timing minors (Task 1 100 ms windows; Task 4 minors 1-4) before CI sees them — why: a flaky CI run costs a round trip overnight — cost if wrong: a slightly larger cleanup diff.
+Task 5: minor (deferred): ":0 " guard in listeners_test nearly vacuous; no test of %w-unwrap / empty-flag bind; non-dev bind path untested beyond helpers (largebox test covers it in CI)
+Task 6: minor (deferred): edge.go multiProxy "client left so don't eject" comment only true for direct DialContext callers (dial ctx detached)
+- Ruling: do NOT add an idempotent-request replay in this branch; instead Task 7 makes the witness classify 502s by the Edge's recorded cause, pass on zero refused/timeout/no-upstream failures, and report boundary resets separately (bounded by worker count) — why: replaying GETs changes request semantics beyond Paul's option-2 ruling and the R3-reviewed spec; offered to Paul as a follow-up — cost if wrong: a few GETs at the exact upstream listener-close boundary still 502 until the follow-up.
+Task 7: minor (deferred): no per-cause breakdown on failure; reset bound not time-correlated with Shutdown
+
+## Follow-up list after the whole-branch review (P3s and offers; none start a round)
+
+- Branch R1 P3-1: the witness's tolerated `resets` are not tied to the shutdown moment. A reset in the baseline or after recovery would also be tolerated (up to 8).
+- Offer to Paul: one replay of a bodiless idempotent request (GET/HEAD) when a local upstream resets after connect. The witness sees 0 to 4 such resets per restart, in about 3 of 10 runs. The dial hold cannot cover them.
+- Option 3 (Paul's ruling): `carlos-edge.socket` in a release that refuses rollback or apply to a build older than the first socket-aware build. See the spec, "Later: option 3".
diff --git a/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md b/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md
new file mode 100644
index 000000000..00f287647
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md
@@ -0,0 +1,340 @@
+# Edge roll blip (#434 part B): design
+
+Status: revision 4, 2026-10-28, branch `edge-roll-blip`. Cut to option 2 by Paul's ruling on
+amadan #434 ("2 then 3"), after review rounds 1 and 2 (§9). Round 3, the last, was READY AFTER
+FIXES; this revision applies its four P2s and the review is closed (AGENTS.md "Stopping rules" 1).
+The brief is `.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md`; the ruling narrows it.
+
+Goal: when a local upstream restarts (root's adopt restarting `console.service` once per roll,
+or any loopback or unix upstream restarting), clients of routes through the edge wait for it
+instead of getting 502 or 503. The edge's own listeners are not changed here: the edge still
+binds :80 and :443 itself, so its own restart still refuses connections for its gap. That
+part is option 3, a later slice (§8).
+
+Scope: D10 (unprobed local upstream: dial retried instead of 502), D10b (probed route with a
+local upstream: wait for readmission instead of 503), D8 (a startup log line) and the witness
+(§6). Numbers are kept from the reviewed revisions so the findings still point at the right
+decision; D1-D7 and D9 were the socket design (§8). No unit file, root, updater, install,
+bootstrap or rollback change.
+
+## 1. Evidence
+
+### 1.1 Local upstream dials today
+
+**Unix upstreams already hold.** Every unix dial the edge makes retries `ECONNREFUSED` and
+`ENOENT` every 100 ms for 13 s: `unixProxy` (`internal/edge/edge.go:2708`, dial `:2720-2721`)
+via `dialUnixWithRetry` (`:3509`); the generation transports (`genproxy.go:203,208`) via
+`dialUnixRetrying` (`:39-40`) and `dialGen` (`:85-86`); and `waitServingGen` (`:311-312`).
+The window is sized for "the instance drain (10s) plus rebind" (`edge.go:3502-3508`); the
+predicate is `isRetryableDialErr` (`:3513-3515`); the 13 s is three literals
+(`genproxy.go:40,86,312`). Unix upstreams need nothing new beyond naming the window.
+
+**Addr (TCP) routes do not hold.** The route's `Health` column selects the proxy
+(`edge.go:846-871`):
+- Empty: `tcpProxy` (`:2736`), whose `http.Transport` has no `DialContext`. A refused dial
+ goes to `defaultProxyError` (`:627`): a bare 502, cause `CauseRefused` (`:604`).
+- Set: `multiProxy` (`:2817`). It dials only the prober's live set. An empty set returns
+ `errNoLiveUpstream` at once (`:2836-2839`). A refused upstream is ejected (`:2876`). A
+ pass with no connection answers 503 + `Retry-After: 2`, cause `CauseNoUpstream`
+ (`:2889-2892`).
+
+**The prober** (`internal/edge/prober.go`). `Sync` normalizes each spec with
+`Health.WithDefaults` (`:265`; defaults `interval_ms` 2000, `rise_after` 2,
+`internal/provision/provision.go:295-325`). `newHostProber` then clamps non-positive values
+(`prober.go:188-232`, interval at `:216`, rise at `:222`). `run` ticks at the interval
+(`:421`). `tick` probes the host's addrs **in turn**, each bounded by `probeTimeout` = 2 s
+(`:50`, client at `:130,143`). So a tick can outlast the interval, and missed ticks collapse
+into one back-to-back tick (`:441-446`; `time.Ticker` keeps a one-element buffer,
+`$GOROOT/src/time/tick.go:40-42`). Readmission takes `rise_after` consecutive passes
+(`:525`). `Eject` and every failed probe reset the pass count (`:356`, `:534`).
+
+**Dial context.** Go 1.26 dials on a context detached from the request
+(`$GOROOT/src/net/http/transport.go:1524-1529`). The request still returns on its own
+context at once (`:1583`). A held dial keeps running after the client leaves, and ends at
+its hold.
+
+**The console** listens on `127.0.0.1:8090` (`cmd/console/main.go:758-759`). It exits on
+SIGTERM without a drain (`:592-601`). Its route is **unprobed** if hand-added with `carlos add
+--addr` and stamped with `carlos route --unit` (`cli.go:610-616`), **probed** if minted from a
+record with `Health` (`internal/provision/reconcile.go:573,634-650`). D10 and D10b cover both,
+so the design does not need to know which shape a box has.
+
+### 1.2 Other holds and paths it meets
+
+- **The wake hold.** Activator-owned requests wait on the startup latch (`awaitStartup`,
+ `internal/activator/activator.go:1572`) and on wakes, then go to the edge's proxy
+ (`:5874,5889`); the activator's own `socketClient` (`backend_exec.go:3430`) only
+ health-checks a waking instance. An ordinary wake wait is bounded by `wakeWaitBound` = 30 s
+ (`:1141`). A first wake extends that to its own budget (`awaitWake`, `:1780`): 55 s for a
+ binary row (`wakeplan.go:231`), a rootfs row's health bound plus the kill reserve
+ (`rootfs_service.go:44`). So 30 s is not a platform maximum. Activator routes are unix
+ (`addr with hibernate` is refused at mint, `provision.go:747`), so D10/D10b never stack on
+ the wake hold and an activator route's worst case (its wake wait, then 13 s unix hold) is
+ unchanged.
+- **The edge's servers** have no `WriteTimeout` (`edge.go:3811-3815`), so nothing cuts a held
+ request. The update gate probes `http://127.0.0.1/` on :80, which redirects and never
+ proxies (`internal/host/systemapply.go:214-226`): unaffected.
+- **Cause notes.** Past `clientGoneGrace` (5 s) a client that leaves is `CauseAbandoned`
+ and filed; before it, `client_gone` (`internal/edge/answered.go:58-65`, `edge.go:594-612`).
+
+## 2. D10: unprobed local upstreams retry the dial
+
+- **One window.** The const `localDialHold = 13 * time.Second` replaces the three literals
+ (`genproxy.go:40,86,312`).
+- **Settings per Edge, not globals.** `New` stores `localHold{dial: localDialHold, cap:
+ localHoldCap, probe: probeTimeout, dialer: nil}` on the Edge and builds its prober set with
+ `newProberSet(hold)`, which uses `probe` for its client and all three for `Hold` (§3).
+ `tcpProxy` and `multiProxy` take them from their Edge at Reload; `dialer` is a test seam
+ (nil means a `net.Dialer`); the consts are the defaults. Unix paths keep the const. A test
+ sets its own Edge's values before its first Reload. No test changes a package global, so
+ parallel witnesses cannot see each other's settings, and a detached dial that outlives its
+ test touches only its own Edge.
+- **One deadline.** `dialUnixRetrying`'s loop becomes `retryLocalDial(ctx, deadline, attempt)`.
+ The caller fixes `deadline` once, on entry, before the first attempt. Each attempt runs on
+ `context.WithDeadline(ctx, deadline)` and each wait is min(100 ms, time left), so no attempt
+ or wait outlives the hold. It retries while `isRetryableDialErr`. Outcomes: connected; a
+ non-retryable error, at once; the deadline passes after a retryable error, which is
+ returned (502, `CauseRefused`); the deadline cuts an attempt that had not failed on its
+ own, giving `errHoldExpired` wrapping `context.DeadlineExceeded` (502, `CauseTimeout`, by
+ `proxyCause`'s existing rule, `edge.go:605`). A client cancel never reaches the dial (it is
+ detached, §1.1); `proxyCause` checks the request's context first (`:595`), so a leaver
+ stays `client_gone` or `CauseAbandoned`. `dialUnixRetrying` and the new TCP dial call it.
+ `dialGen` keeps its own loop (each attempt also checks for a generation move) with the same
+ deadline and per-attempt context.
+- **Which TCP addrs.** `tcpProxy(addr, hold)` gets a `DialContext` (`retryLocalDial` over a
+ plain `net.Dialer{}`, the zero transport's dialer) only when `isLocalUpstream(addr)`: the
+ host is a loopback IP literal (`netip.Addr.IsLoopback`: 127/8, `::1`) or `localhost`. D10b shares the
+ predicate. A non-local addr, including the box's own non-loopback IPs, keeps the instant 502:
+ a refused remote box is an outage, not a restart.
+- **After the hold**, still refused: 502, `CauseRefused`, as today but 13 s later.
+
+## 3. D10b: probed routes with a local upstream wait for readmission
+
+**The rule.** `newHostProber` records, from its clamped values, `local` (any addr in
+`hp.order` passes `isLocalUpstream`) and `hold` (below); `proberSet.Hold(host)
+(time.Duration, bool)` returns them, so `multiProxy` still never sees the addr list. Its
+dialer works in passes: each reads `Live(host)` and walks it exactly as today (dial, eject on
+failure, return the first connection). When a pass ends with no connection and the host is
+`local`, it waits 100 ms and passes again until the hold ends, then returns
+`errNoLiveUpstream` (503 + `Retry-After: 2`, `CauseNoUpstream`). A host with no local addr
+answers at once, as today.
+
+**One deadline.** For a local host the dialer fixes `deadline = entry + hold` once, before the
+first pass. Each dial runs on `context.WithDeadline(ctx, deadline)` and keeps
+`multiDialTimeout`, so an attempt ends at the earlier of 3 s and the deadline. Each wait
+between passes is min(100 ms, time left). An attempt the deadline cuts (its own context done,
+the dial context not) is budget exhaustion, not upstream failure: no `Eject`, and the dialer
+returns `errNoLiveUpstream` (503, `CauseNoUpstream`). An attempt that fails on its own
+(refused, or its 3 s timeout before the deadline) ejects as today. A non-local host gets no
+deadline.
+
+**Admission is unchanged.** Only the live set is dialed and only the prober readmits; an
+ejected upstream is never dialed, and a held request only waits. A live upstream that answers
+serves at once; the hold starts only when nothing live connects.
+
+**The readmission allowance** comes from the schedule the prober actually runs: `N` =
+`len(hp.order)`, `I` = `hp.interval`, `r` = `hp.riseAt` (the normalized, clamped values
+`run` and `record` use), `T` = the set's `probe`. One probe of a given addr starts at most `G`
+after the one before it:
+
+ G = max(I, T) + (N − 1) × T
+
+When a tick fits in the interval, the next one starts `I` after it, and in the worst case
+the addrs probed before this one take `T` each. When a tick overruns, the next tick starts as
+soon as it ends (`prober.go:441-446`), and at most `N` probes of `T` each separate two
+probes of the same addr. Once the upstream answers again, its `r`-th pass completes within
+
+ R = r × G + T
+
+and the request's hold is `hold = min(dial + R, cap)` (defaults 13 s and `localHoldCap` =
+30 s): the time the upstream may be gone, plus its readmission once back. The cap is D10b's own
+policy, set equal to the ordinary wake wait (`wakeWaitBound`); first wakes can wait longer
+(§1.2). The hold bounds the wait for a connection; the response then takes what it takes.
+
+| Defaults (I 2 s, r 2, T 2 s), every other addr black-holed | G | R | hold |
+|---|---|---|---|
+| one local upstream | 2 s | 6 s | 19 s |
+| local plus 1 | 4 s | 10 s | 23 s |
+| local plus 2 | 6 s | 14 s | 27 s |
+| local plus 3 or more | 8 s or more | 18 s or more | 30 s (capped) |
+
+**When readmission can take longer than the cap.** Two cases. First, when probing is slow:
+many addrs that time out rather than refuse, i.e. black-holed remote upstreams in a mixed
+set (three of them with defaults are already over the cap). Second, when the operator
+configured a long cadence (`I` 10 s and `r` 2 give `R` = 22 s). In both cases a request
+whose local upstream comes back late gets **503 + `Retry-After: 2`** at 30 s, the same answer
+as today, only later; a retry after readmission is served. The cap is not raised: a request
+held longer than an ordinary wake wait is worse than an early 503 the client can retry. `G` and `R` are bounds; a refusing local upstream
+is probed in milliseconds, so real readmission is near `r × I`. The bound only costs time when
+the upstream stays down: the request then waits the full hold before its 503.
+
+## 4. Safety (D10 and D10b)
+
+- **Any method.** A failed dial sent nothing, and `RoundTrip` writes no request and reads no
+ body before it has a connection, so a retried dial is safe for POST or any method and the
+ body arrives intact. **Upgrades** take the same dial and are held the same way.
+- **A client that leaves** is released at once (the request returns on its own context). The
+ detached dial runs to its hold and never past it (§2, §3); a connection it makes then goes to `tcpProxy`'s idle pool
+ or is closed (`multiProxy` has keep-alives off). A `multiProxy` pass whose context ends
+ still returns without ejecting (`edge.go:2855-2870`).
+- **Causes** are unchanged: refused after the hold is `CauseRefused` (502), no live upstream
+ after the hold is `CauseNoUpstream` (503), and a leaver is `client_gone` or, past 5 s,
+ `CauseAbandoned`, exactly as a unix route's hold is filed today. The comment at
+ `answered.go:58-64` gains loopback TCP and probed routes.
+
+## 5. D8: the startup log line, and D11: cross-compile
+
+**D8.** At serve time the edge binds before it serves. `listenAddr(flag, def)` first maps an
+empty flag to `:http` or `:https`, as `ListenAndServe` and `ListenAndServeTLS` do
+(`$GOROOT/src/net/http/server.go:3372,3727`); then `net.Listen("tcp", ...)` for http, then
+https (outside dev mode), with today's fatal messages on failure (`edge: http listener %s:
+%v`, `edge: https listener %s: %v`, `edge.go:3820,3827`). Then it logs one line and calls
+`Serve(ln)` and `ServeTLS(ln, "", "")`, which is what `ListenAndServe(TLS)` does after its own
+normalization and bind, so the behaviour is unchanged. The line gives each listener's actual
+address (`ln.Addr()`, so a `:0` flag shows the allocated port), then the flags (`edge.go:3549-3550`):
+
+ edge: listeners: bound http [::]:80 and https [::]:443 itself (flags ":80" ":443")
+ edge: listeners: bound http 127.0.0.1:8080 itself (dev mode; flag "127.0.0.1:8080")
+
+Unlike today's `serving N route(s)`,
+which prints before the bind, the line means both binds succeeded, so the journal gives the
+edge's own refused window per roll: old process's `edge: draining and shutting down` to the
+new one's `edge: listeners:`. The socket slice extends the prefix (`edge: listeners: inherited
+2 from systemd (:80 fd 3, :443 fd 4)`, mixed forms). Operator log, not member copy. Morning
+check: `journalctl -u carlos-edge -g 'edge: listeners:|draining and shutting down'`.
+
+**D11.** No linux-only code: `syscall.ECONNREFUSED`/`ENOENT`, `net/netip` and `net.Listen`
+already build on darwin and windows in this package. CI's cross-builds check it.
+
+## 6. Witness (local, CI, 127.0.0.1 only)
+
+`internal/edge/localhold_witness_test.go`, `TestLocalUpstreamRestartWitness`. It is skipped
+under `-short`; its subtests run in parallel, each on its own Edge (§2), about 5 s in all. It runs the real proxy path
+in-process: an `Edge` from `New(openReg(t), nil)` served by `httptest.NewServer(e)` on
+127.0.0.1, routes Reloaded from the registry as in `edge_test.go:1684-1700`. No build, no
+sudo, no systemd. Subtests: `tcp`, an unprobed `Addr` route to `127.0.0.1:P`; `unix`, a
+`Socket` route under `shortSockDir` (`door_test.go:902`), skipped on windows; `probed`, an
+`Addrs` route to `127.0.0.1:P` with `Health{Path: "/healthz", IntervalMS: 100, FailAfter: 1,
+RiseAfter: 2}`.
+
+Each subtest's one upstream is an `http.Server` on a fixed address answering `/` and
+`/healthz` with 200. Eight workers send `GET /` (Host `shop.example.com`) through the edge on
+keep-alive clients. After 1 s of steady load (the baseline) the upstream restarts:
+`Shutdown` with a 5 s drain (as the instance drain does), a 1.5 s gap in which the port
+refuses or the socket is absent, then a new `http.Server` on the same address. Load runs 1 s
+more. Every response is counted by status, transport errors separately.
+
+**Pass:** zero 502, zero 503 and zero other failures. Each request's added wait is its
+latency minus the baseline p50. The max added wait must stay under gap + 1 s for `tcp` and
+`unix`, and under gap + `R` for `probed`. Each subtest reports one line:
+
+ t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v", ...)
+
+The #434 reply quotes these numbers. **Negative control:** the `tcp` case runs again on its own Edge with
+a dial hold of 0, and its count of 502s must be above 0, so the witness can fail.
+The console's undrained `os.Exit` is not modelled: those resets are a known limit (§7), not
+the edge's.
+
+## 7. Known limits
+
+- **The edge's own restart** still refuses new connections from its `Shutdown` until the new
+ process binds: option 3 (§8). D8 makes the gap measurable from the journal.
+- **In-flight requests** on a local upstream that exits undrained (the console's `os.Exit`)
+ are reset and still 502, as is a request with a body on a pooled `tcpProxy` connection that
+ dies under it (the transport replays only replayable requests on a reused connection).
+- **A local upstream that stays down** answers after the hold (13 s unprobed, 19-30 s
+ probed), and each held request costs a goroutine and a loopback dial or live-set read every
+ 100 ms until then. Unix routes already make both trades.
+- **WebSockets** on the edge drop when the edge restarts: part C.
+
+## 8. Later: option 3 (not built here)
+
+`carlos-edge.socket` holds :80 and :443 in PID 1, and the edge takes them through
+`LISTEN_FDS`. It ships as its own slice, in a release that **refuses any rollback or apply to
+a build older than the first socket-aware build**. That release refuses to install unless
+both the installed binary and `carlos.prev` are at or above that build. It also refuses
+`system update --file`, rollback and recovery targets below it. So no pre-socket rollback
+code, recovery unit or binary ever runs on a box where the socket can be active.
+
+The socket design reviewed in rounds 1 and 2 is at `dad8843b` (D1-D9, the §4 mix table, the
+witnesses). The slice keeps its evidence and must answer these findings:
+- **R1 P1-1** (rollback compatibility). Recovery can rename an old binary in
+ (`systemapply.go:1892`) and return before socket removal (`:1927`, `:2061`). That leaves
+ the old binary behind an active socket. Boot recovery runs `carlos.prev`'s code.
+- **R2 P1** (rollback compatibility, the same family). A guard that reads a failed
+ `systemctl` status query as "inactive" admits an incompatible binary. Every check must
+ fail closed on an unknown state (cf. `systemunits.go:101-108`).
+- **R1 P2 floor.** `release.LayoutFloor` (v0.25.0) is conditional (`systemapply.go:583`).
+ The new floor must be unconditional, and enforced by the code that runs install,
+ rollback and recovery.
+- **R1 P2s** on listener compatibility (absent vs incompatible inherited listeners), fd-store
+ evidence (`FileDescriptorStorePreserve=yes`) and witness binary identity: resolved in the
+ round-2 text; keep those resolutions.
+- The hand script (`scripts/update-platform-binary.sh`, platform-infrastructure) copies units
+ and binaries outside the applier: the slice gates it or retires it.
+
+The slice is designed, reviewed and built under its own round budget, after this merges.
+
+## 9. Review history and dispositions
+
+R1 (brief `e0b2877a`): NOT READY, 2 P1, 4 P2. R2 (brief `dad8843b`): NOT READY, 1 P1 in the
+rollback-compatibility family again and 1 P2 in the restart-admission family again. Stopping
+rule 2 triggered; the choice went to #434; Paul ruled on 2026-10-28: option 2 now, then 3.
+
+| Finding | Family | Disposition |
+|---|---|---|
+| R1 P1-1: recovery leaves an old binary behind an active socket | rollback compatibility | Out of scope by ruling (socket slice, §8) |
+| R1 P1-2: probed local upstreams still 503 | restart admission | Fixed here: D10b holds probed routes with a local addr, admission unchanged (§3) |
+| R1 P2: closing an unmatched inherited listener | listener ownership | Out of scope by ruling (socket slice) |
+| R1 P2: layout floor wrong and conditional | compatibility eligibility | Out of scope by ruling. §8 requires an unconditional floor |
+| R1 P2: W2 did not select the built binary | verification identity | Out of scope (W2 went with the socket). The new witness runs this tree's code in-process (§6) |
+| R1 P2: fd-store preservation setting | mechanism evidence | Out of scope by ruling (socket slice) |
+| R2 P1: guard treats a failed status query as inactive | rollback compatibility | Out of scope by ruling. Listed for the slice (§8) |
+| R2 P2: readmission allowance ignores probe timeout and sequential probing | restart admission | Fixed here: `R = r × G + T` with `G = max(I, T) + (N−1) × T`, from normalized and clamped settings. The 30 s cap is kept, and the cases past it are stated (§3). Tests for the delayed probe, the mixed set and past the cap are in §10 |
+
+R3 (brief `70a10389`): READY AFTER FIXES, no P1, 4 P2, no P3. P2s fixed:
+- Hold deadline (bounded dial lifetime): one absolute deadline from entry bounds every attempt
+ and wait; budget exhaustion is its own outcome, never ejects (§2, §3; tests §10).
+- Witness isolation (verification isolation): hold settings and probe timeout live on each
+ Edge, injected by tests; no package global is mutated (§2, §6, §10).
+- D8 binding (startup bind compatibility): empty flags normalized to `:http`/`:https` before
+ binding; the line logs `ln.Addr()` beside the flags (§5).
+- Wake-wait claim (timeout-contract accuracy): 30 s is the ordinary wake wait and D10b's own
+ cap; first wakes extend beyond it (§1.2, §3).
+
+## 10. Test plan
+
+Locally, only `internal/edge`, with `-run`. CI runs the full set. For speed, tests shorten
+their own Edge's dial hold, cap and probe timeout (§2); no test changes a package global.
+
+- **`isLocalUpstream`:** `127.0.0.1:p`, `127.9.9.9:p`, `[::1]:p` and `localhost:p` are local.
+ `10.0.0.5:p`, `example.com:p` and a malformed addr are not.
+- **D10 (`tcp`):** refused then listening within the hold gives 200; past a shortened hold,
+ 502 with `CauseRefused`; a non-loopback addr gives 502 at once with one dial attempt
+ (instrumented dialer); a client cancel returns at once; a POST body arrives intact after a
+ held dial; a WebSocket upgrade works after a hold. **Blocking attempt:** an attempt that blocks until its
+ context ends returns at the deadline (502, `CauseTimeout`), not after it.
+- **D10 (unix):** the existing `dialUnixWithRetry` and `dialGen` tests pass unchanged on the
+ shared constant and loop.
+- **D10b:** a single local upstream refused before the probe notices, then back: 200 once
+ readmitted, and no connection reaches it while ejected (the upstream counts them). The live
+ set already empty on arrival: the same. Still down past the hold: 503 + `Retry-After: 2`.
+ Remote-only route: 503 at once. Mixed set with a live upstream: served at once. **Deadline mid-pass:** a mixed set whose
+ live remote addr's dial blocks (instrumented dialer) gives 503 `CauseNoUpstream` at the
+ hold, and that addr is still live afterwards (not ejected).
+ **Delayed probe:** three upstreams whose `/healthz` blocks past a shortened `probe`
+ are probed before one restarting local upstream; the request is served at readmission,
+ inside its computed hold, and the measured readmission is at most `R`. **Past the cap:**
+ `dial + R` over a shortened `cap` gives 503 at the cap. `Hold` from raw
+ `Health{}`, negative interval and negative rise matches the formula on clamped values.
+- **D8:** `listenAddr` maps `""` to `:http`/`:https` and keeps an explicit addr; a
+ `127.0.0.1:0` bind logs the allocated port; both log forms pinned. A bind failure keeps
+ today's fatal message.
+- **Witness:** §6, in CI.
+
+## 11. Out of scope
+
+Part C (apps surviving an edge restart; `BindsTo=`, #440 item 1). The socket slice (§8) and
+any unit file, root, updater, install, bootstrap, recovery or rollback change.
+Socket-activating `console.service`; a console drain; the relay's ports. Any AWS, DNS, infra
+or box change, and the hand script. Release, roll and merge.
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R2.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R2.md
new file mode 100644
index 000000000..7d197b02c
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R2.md
@@ -0,0 +1,127 @@
+# Review brief: edge-roll-blip design spec (#434 part B), round 2 of 3
+
+Repo carlos/platform, branch `edge-roll-blip`, commit 6e029fd91c51aaf56768b83044d04cfebab7902b (the commit before this brief).
+Under review: `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md`.
+Authorities: the code on this branch (which is main plus docs only), AGENTS.md,
+and the binding brief `.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md`.
+Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code. The systemd man pages on
+this machine (systemd 257, the same major as the boxes) are the authority
+for systemd semantics: `man systemd.socket`, `man systemd.service`,
+`man systemd.unit`, `man systemctl`, `man sd_listen_fds`.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in BRIEF.md: part B only (edge listeners survive a
+ restart; edge holds requests to a restarting local upstream instead of
+ 502; local witness; startup log line). Part C (instances surviving an
+ edge restart, BindsTo) is OUT. No AWS, infra, DNS or box changes. No
+ console special case unless forced. Prefer refusing up front over
+ tolerance layers.
+
+## What to check
+
+1. Rollback safety, the hard part. Walk the spec's §4 table against the
+ real updater, gate, rollback, recovery and bootstrap code
+ (`systemapply.go` and friends, `internal/host/units`, the bootstrap
+ script/code). Is there any mix (old/new binary x old/new units, first
+ install, fresh bootstrap, gate rollback, `carlos-system-recover`,
+ runtime OnFailure recovery, downgrade by `system update --file`) where
+ an old binary starts while a socket unit holds :80/:443 and the box
+ goes dark, beyond the one the spec names (row 14)? Verify the claim
+ that every binary a box can roll back to records added units and runs
+ `disable --now` on them during rollback (cite the version and line).
+2. D4 (`ExecStartPre=carlos system edge-socket-check`): does an unknown
+ `system` verb really exit non-zero in every build a box could hold?
+ Does a failed ExecStartPre on a socket unit leave the port unbound and
+ not wedge `carlos-edge.service` (`Wants=`/`After=`)?
+3. D3/D7: unit dependency semantics. Does `Wants=` + `After=` on the
+ socket give the ordering the spec claims for `systemctl restart
+ carlos-edge` (old edge exits before the socket starts at first
+ install)? Does `restart carlos-edge` leave an active socket alone? Is
+ excluding the socket from `armedUnits` coherent with how
+ `enabledUnits`/`armedUnits`/`ensureSystemUnits` actually work?
+4. D5: fd inheritance. Correct LISTEN_PID/LISTEN_FDS handling, close-on-
+ exec, no leak of the public listeners or LISTEN_* env to tenant/exec
+ children (the activator, the guard drop-in's `syscall.Exec`). Is
+ matching by port correct with `BindIPv6Only=both` and the existing
+ `-http`/`-https` flags (and dev mode)?
+5. D6: graceful stop. Does anything in the edge's shutdown path
+ (http.Server.Shutdown, any custom drain, TLS, HTTP/3 if any) call
+ shutdown(2) or otherwise empty the shared accept queue?
+6. #281 listen-first + admission latch and TLS readiness: with
+ connections queued in a held backlog, is anything served before certs
+ and the latch are ready, or does anything hang forever?
+7. D10: the loopback dial hold. Is retrying ECONNREFUSED on loopback TCP
+ safe for every method and for upgrades? Does it interact badly with
+ probed routes, the wake hold, `answered.go` cause classification,
+ timeouts, or the activator's own dial logic? Is 13 s coherent with the
+ existing limits?
+8. Unit hardening (`RestrictAddressFamilies`, capabilities,
+ `SystemCallFilter`) and cross-compile (darwin/windows need linux-only
+ code behind `//go:build linux` and a stub).
+9. §7 local witness: will it actually measure what it claims, on a
+ machine without sudo, binding 127.0.0.1 only?
+
+## Round 2
+
+Earlier rounds: round 1, `docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md`
+(NOT READY: P1 recovery leaves an old binary behind an active socket, fault
+family "rollback compatibility"; P1 probed local routes still 503, fault
+family "restart admission"; four P2s). The spec's "Round 1 dispositions"
+section says how each was handled. The round number counts every earlier
+review of this design or change, under any file name or reviewer.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not.
+Carry every unresolved or partly resolved finding forward at its current
+severity, then add new findings. The verdict covers everything
+outstanding, earlier rounds included. Name the fault family beside every
+finding; say explicitly if a new finding is in the same family as a
+round-1 P1 (rollback compatibility, or restart admission).
+
+Round-2 focus, in addition to the list above:
+- INV-R and its two enforcement points (the `carlos-edge.service.d`
+ guard drop-in and the socket's `ExecStartPre=` gate). Check that the
+ drop-in really survives every old unit set and old applier/rollback
+ path, that stopping the socket from inside the edge's own start cannot
+ deadlock or wedge the service under systemd 257's job engine, and that
+ the two-step activation (drop-in written only by this build's root code)
+ holds on every §4 row, including fresh bootstrap and the hand script.
+- D10b, the probed-route hold: readmission timing, never dialing an
+ ejected upstream, the empty-live-set case, mixed local/remote sets,
+ and the cap.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R3.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R3.md
new file mode 100644
index 000000000..0156e9006
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec-R3.md
@@ -0,0 +1,95 @@
+# Review brief: edge-roll-blip design spec (#434 part B), round 3 of 3 (FINAL)
+
+Repo carlos/platform, branch `edge-roll-blip`, commit 016261301b35311943d99b87d46c7ac353ae14aa (the commit before this brief).
+Under review: `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md`.
+Authorities: the code on this branch (main plus docs only), AGENTS.md.
+Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- **Paul's ruling, 2026-10-28, recorded on amadan #434 ("2 then 3"):** this
+ branch's whole scope is the local-upstream hold (a refused or missing
+ local upstream gets its dial retried within the 13 s window instead of
+ 502; probed local routes wait for prober readmission instead of 503)
+ plus a startup log line. There is NO `carlos-edge.socket`, and no unit,
+ root, updater, install, bootstrap or rollback change. The socket design
+ is parked in the spec's "Later: option 3" section and is NOT built here.
+- **Every socket, listener-handoff, INV-R and rollback-compatibility
+ finding from rounds 1 and 2 is out of scope by ruling.** Do not raise
+ findings against the "Later: option 3" section; it is a note for a
+ future slice, not a design under review.
+- Part C (instances surviving an edge restart) is out. No console special
+ case unless forced.
+
+## What to check
+
+1. D10 (unprobed routes): the shared local dial retry. Is "local" decided
+ correctly (loopback IP literals, `localhost`, unix sockets) and never
+ for a remote addr? Is retrying refused/ENOENT safe for every method,
+ for request bodies, and for upgrades (WebSockets)? Is it bounded by the
+ request context and the 13 s cap, with no goroutine or connection leak
+ (Go 1.26 transport dial detachment)? Does the unification with the
+ existing unix retry in `genproxy.go` change any current unix behaviour?
+2. D10b (probed routes): the hold never dials an ejected upstream; the
+ readmission allowance formula matches the prober's real schedule
+ (`prober.go`: sequential per-tick probing, `probeTimeout`, `rise_after`,
+ `interval`, clamping); the 30 s cap; mixed local/remote sets; the
+ empty-live-set case; behaviour when readmission exceeds the cap.
+3. Interaction with the wake hold (`wakeWaitBound`), the activator's own
+ dial path, `answered.go` cause classification and access logs/metrics,
+ timeouts, and client disconnects during the hold.
+4. The startup log line: accurate for every way the edge binds (dev mode,
+ -http/-https flags), and cheap.
+5. The local witness: does it exercise the real proxy path, bind
+ 127.0.0.1 only, fail when the hold is off, stay fast and non-flaky in
+ CI, and report the measured wait?
+6. Cross-compile (darwin/windows CI) and any test seam it adds.
+
+## Round 3 (FINAL)
+
+Earlier rounds of this design:
+- Round 1, `docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md`:
+ NOT READY. P1 rollback compatibility (socket), P1 restart admission
+ (probed local routes 503), 4 P2.
+- Round 2, `docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R2.md`:
+ NOT READY. P1 rollback compatibility again (socket guard), so stopping
+ rule 2 triggered; P2 restart admission (readmission allowance ignored
+ probe timeout and sequential probing).
+- Paul then cut the socket (ruling above). The spec's "Review history and
+ dispositions" section maps each finding.
+
+First give one line per round-1 and round-2 P1/P2: "out of scope by
+ruling", resolved, partly, or not. Carry forward any in-scope finding not
+fully resolved at its current severity, then add new findings. Name the
+fault family beside each. This is the last round: there is no round 4.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks (its fault family). End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed. Also say whether the P1s share
+ one cause, and whether refusing the case up front or cutting the
+ feature would remove them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec.md
new file mode 100644
index 000000000..fce400295
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-edge-roll-blip-spec.md
@@ -0,0 +1,99 @@
+# Review brief: edge-roll-blip design spec (#434 part B), round 1 of 3
+
+Repo carlos/platform, branch `edge-roll-blip`, commit ae035edf31327fa959ddd370c898ef2ec22f8545 (the commit before this brief).
+Under review: `docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md`.
+Authorities: the code on this branch (which is main plus docs only), AGENTS.md,
+and the binding brief `.superpowers/sdd/2026-10-27-edge-roll-blip/BRIEF.md`.
+Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code. The systemd man pages on
+this machine (systemd 257, the same major as the boxes) are the authority
+for systemd semantics: `man systemd.socket`, `man systemd.service`,
+`man systemd.unit`, `man systemctl`, `man sd_listen_fds`.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in BRIEF.md: part B only (edge listeners survive a
+ restart; edge holds requests to a restarting local upstream instead of
+ 502; local witness; startup log line). Part C (instances surviving an
+ edge restart, BindsTo) is OUT. No AWS, infra, DNS or box changes. No
+ console special case unless forced. Prefer refusing up front over
+ tolerance layers.
+
+## What to check
+
+1. Rollback safety, the hard part. Walk the spec's §4 table against the
+ real updater, gate, rollback, recovery and bootstrap code
+ (`systemapply.go` and friends, `internal/host/units`, the bootstrap
+ script/code). Is there any mix (old/new binary x old/new units, first
+ install, fresh bootstrap, gate rollback, `carlos-system-recover`,
+ runtime OnFailure recovery, downgrade by `system update --file`) where
+ an old binary starts while a socket unit holds :80/:443 and the box
+ goes dark, beyond the one the spec names (row 14)? Verify the claim
+ that every binary a box can roll back to records added units and runs
+ `disable --now` on them during rollback (cite the version and line).
+2. D4 (`ExecStartPre=carlos system edge-socket-check`): does an unknown
+ `system` verb really exit non-zero in every build a box could hold?
+ Does a failed ExecStartPre on a socket unit leave the port unbound and
+ not wedge `carlos-edge.service` (`Wants=`/`After=`)?
+3. D3/D7: unit dependency semantics. Does `Wants=` + `After=` on the
+ socket give the ordering the spec claims for `systemctl restart
+ carlos-edge` (old edge exits before the socket starts at first
+ install)? Does `restart carlos-edge` leave an active socket alone? Is
+ excluding the socket from `armedUnits` coherent with how
+ `enabledUnits`/`armedUnits`/`ensureSystemUnits` actually work?
+4. D5: fd inheritance. Correct LISTEN_PID/LISTEN_FDS handling, close-on-
+ exec, no leak of the public listeners or LISTEN_* env to tenant/exec
+ children (the activator, the guard drop-in's `syscall.Exec`). Is
+ matching by port correct with `BindIPv6Only=both` and the existing
+ `-http`/`-https` flags (and dev mode)?
+5. D6: graceful stop. Does anything in the edge's shutdown path
+ (http.Server.Shutdown, any custom drain, TLS, HTTP/3 if any) call
+ shutdown(2) or otherwise empty the shared accept queue?
+6. #281 listen-first + admission latch and TLS readiness: with
+ connections queued in a held backlog, is anything served before certs
+ and the latch are ready, or does anything hang forever?
+7. D10: the loopback dial hold. Is retrying ECONNREFUSED on loopback TCP
+ safe for every method and for upgrades? Does it interact badly with
+ probed routes, the wake hold, `answered.go` cause classification,
+ timeouts, or the activator's own dial logic? Is 13 s coherent with the
+ existing limits?
+8. Unit hardening (`RestrictAddressFamilies`, capabilities,
+ `SystemCallFilter`) and cross-compile (darwin/windows need linux-only
+ code behind `//go:build linux` and a stub).
+9. §7 local witness: will it actually measure what it claims, on a
+ machine without sudo, binding 127.0.0.1 only?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R2.md b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R2.md
new file mode 100644
index 000000000..d6c271275
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R2.md
@@ -0,0 +1,36 @@
+Reviewed `dad8843b`. No files changed or full test suites run. Amadan #434 was inaccessible from the sandbox; the committed binding brief supplied the scope.
+
+Round-one dispositions:
+
+- **P1-1, rollback compatibility: partly resolved.** The persistent drop-in covers the original recovery gap, but its failure handling can still admit an incompatible binary. Remains **P1** below.
+- **P1-2, restart admission: partly resolved.** D10b addresses immediate rejection and empty live sets. Its readmission calculation remains incorrect; that residual issue is **P2** below.
+- **P2, listener compatibility: resolved.** D5 distinguishes absent listeners from incompatible inherited listeners.
+- **P2, rollback version floor: resolved.** The spec correctly states the conditional v0.25.0 floor and removes reliance on it.
+- **P2, witness binary selection: resolved.** W2 specifies the temporary build for both commands and checks inheritance before measuring.
+- **P2, fd-store preservation: resolved.** D1 now distinguishes the preservation settings.
+
+1. **P1 — D4: the rollback guard treats a failed status query as proof that the socket is inactive.**
+
+ **Evidence:** The exact shell line at [design:212](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:212) ends with `systemctl stop carlos-edge.socket || ! systemctl -q is-active carlos-edge.socket`. Negation accepts *every* unsuccessful status query, including inability to contact the manager or execute `systemctl`. Existing code explicitly distinguishes a failed query from a reported state at [systemunits.go:101](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/host/systemunits.go:101).
+
+ I reproduced the shell logic without touching systemd: with a failing predicate and shell functions returning 1 for both `systemctl` calls, the guard exits **0**.
+
+ **Failure scenario:** Recovery restores an old binary at [systemapply.go:1892](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/host/systemapply.go:1892), then fails before socket removal. At the next edge start, the old binary rejects the predicate. Both the stop command and subsequent status query fail while PID 1 retains the listeners. E-start nevertheless succeeds, and the old edge fails to bind with `EADDRINUSE`.
+
+ **Concrete fix:** After a failed stop, require an explicit manager response proving the socket is inactive or absent. An unavailable or unparseable status must fail the guard. Add a witness where both commands fail while the socket remains active; it must prevent `ExecStart`.
+
+ **Fault family:** **INV-R / rollback compatibility — the same family as round-one P1-1.** Failure to establish listener ownership must not authorize an incompatible edge.
+
+2. **P2 — D10b: the readmission allowance excludes probe duration and sequential probing.**
+
+ **Evidence:** [Design:320](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:320) calls `rise_after × interval` the maximum readmission time. However, probes have a two-second timeout at [prober.go:50](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/prober.go:50), and each tick probes upstreams sequentially. [Prober.go:441](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/prober.go:441) explicitly explains that a tick can exceed its interval.
+
+ **Failure scenario:** An already-ejected mixed set contains three black-holed remote upstreams followed by one restarting local upstream. Remote probes consume approximately six seconds per pass. The local upstream returns at ten seconds, passes probes around twelve and eighteen seconds, and is readmitted after the default seventeen-second hold has already returned 503.
+
+ **Concrete fix:** Derive the allowance from the actual sequential probe schedule and response timeout, using normalized health settings. Retain the thirty-second cap, but explicitly describe cases where readmission can exceed it. Add delayed-probe and mixed-set witnesses.
+
+ **Fault family:** **INV-H / restart admission — the same family as round-one P1-2.** The bounded hold must account for the admission mechanism it waits on.
+
+INV-R remains blocking in two consecutive rounds, so stopping rule 2 applies. Stop the fix loop and return the prescribed choice to Paul: refuse unsupported cases up front, cut socket activation, or revise the single enforcement point with a guard test covering this failure.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R3.md b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R3.md
new file mode 100644
index 000000000..10f100657
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec-R3.md
@@ -0,0 +1,54 @@
+- R1 P1-1 — rollback compatibility: **out of scope by ruling**.
+- R1 P1-2 — restart admission: **resolved**; D10b covers refused connections and empty live sets without bypassing the prober.
+- R1 P2 — inherited-listener ownership: **out of scope by ruling**.
+- R1 P2 — compatibility eligibility/version floor: **out of scope by ruling**.
+- R1 P2 — witness binary identity: **out of scope by ruling**; the replacement witness exercises this tree in-process.
+- R1 P2 — fd-store mechanism evidence: **out of scope by ruling**.
+- R2 P1 — rollback guard failure handling: **out of scope by ruling**.
+- R2 P2 — restart-admission timing: **resolved**; the revised allowance accounts for sequential probes, probe duration, normalized settings and readmission beyond the cap.
+
+Reviewed `70a10389c66344b0d0c2e8b6f7cf4f6797aa1846` against this branch’s code and installed Go source. No files changed, subagents spawned or test suites run. No P1 findings.
+
+1. **P2 — §§2–4: the hold needs an explicit deadline covering individual dials.**
+
+ **Problem and evidence:** [D10](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:81) reuses a loop whose deadline is checked only after an attempt returns ([genproxy.go:48](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/genproxy.go:48)). Its proposed zero-value TCP dialer has no timeout ([net/dial.go:127](/home/paulca/.local/go-dist/src/net/dial.go:127)). D10b walks each live set “exactly as today,” where the timeout is **three seconds per address**, not per pass ([edge.go:2775](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:2775)). Neither algorithm explicitly passes the remaining hold budget into those attempts.
+
+ **Failure scenario:** A local TCP attempt stalls after earlier refusals, exceeding 13 seconds. A mixed-set pass starts near its deadline and spends additional seconds dialing remote addresses, exceeding the promised 30-second response bound. Request cancellation does not stop that detached work: Go removes the request deadline and cancellation at [transport.go:1529](/home/paulca/.local/go-dist/src/net/http/transport.go:1529).
+
+ **Fix:** Specify one absolute deadline from entry into the local dial operation, including its initial pass. Bound each attempt and polling wait by the remaining budget. Define cap exhaustion separately from client cancellation and upstream failure, preserving the promised status/cause and avoiding ejection caused solely by budget exhaustion. Add a blocking-attempt test and a mixed-set test that reaches the deadline during a pass.
+
+ **Fault family:** bounded dial lifetime and resource retention.
+
+2. **P2 — §§6 and 10: parallel witnesses must not mutate shared hold settings concurrently.**
+
+ **Problem and evidence:** The witness’s subtests run in parallel ([design:181](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:181)), while its negative control changes package-global `localDialHold` to zero ([design:202](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:202)). That setting also controls the positive TCP, Unix and probed cases. The design specifies no isolation between them.
+
+ **Failure scenario:** The negative control overlaps a positive witness, disabling its hold or racing a read of the global. A correct implementation then produces intermittent failures or race-detector failures. Returning from a canceled request alone does not establish that its detached dial has finished.
+
+ **Fix:** Put the positive parallel cases inside a group that completes before running a serial negative control. Stop their probers and finish outstanding dials before changing or restoring globals. Alternatively, inject immutable per-instance settings. Apply the same isolation rule to shortened `probeTimeout` and `localHoldCap`.
+
+ **Fault family:** verification isolation.
+
+3. **P2 — §5 D8: direct binding does not preserve every existing address-flag behavior.**
+
+ **Problem and evidence:** [Design:159](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:159) replaces `ListenAndServe*` with `net.Listen` on the raw flag values and claims unchanged behavior. Go substitutes `:http` for an empty HTTP address ([server.go:3372](/home/paulca/.local/go-dist/src/net/http/server.go:3372)) and `:https` for an empty HTTPS address ([server.go:3727](/home/paulca/.local/go-dist/src/net/http/server.go:3727)). Direct `net.Listen` does not perform those substitutions. Also, logging the raw `:0` flag does not identify the allocated port ([net/dial.go:956](/home/paulca/.local/go-dist/src/net/dial.go:956)).
+
+ **Failure scenario:** Explicit `-http ""` or `-https ""` changes from the standard service port to an automatically allocated port. With `-http 127.0.0.1:0`, the startup line reports port zero rather than the endpoint actually bound.
+
+ **Fix:** Preserve the existing empty-address normalization before binding. Log the actual listener address, optionally alongside the configured value. Cover empty addresses, explicit addresses and port-zero allocation in D8’s tests.
+
+ **Fault family:** startup bind compatibility and diagnostic accuracy.
+
+4. **P2 — §1.2 and §3: 30 seconds is not the existing maximum wake wait.**
+
+ **Problem and evidence:** [Design:64](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:64) describes 30 seconds plus the Unix hold as the activator’s worst case; §3 calls 30 seconds the platform’s longest client wait. However, `awaitWake` extends first-wake deadlines ([activator.go:1780](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/activator/activator.go:1780)). The binary budget is 55 seconds ([wakeplan.go:231](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/activator/wakeplan.go:231)); rootfs uses its health bound plus the kill reserve ([rootfs_service.go:44](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/activator/rootfs_service.go:44)).
+
+ **Failure scenario:** A first-wake request legitimately remains queued beyond the documented maximum. The comparison used to justify D10b’s cap is therefore inaccurate, although the chosen cap remains reasonable.
+
+ **Fix:** Describe 30 seconds as the ordinary wake-wait bound and D10b’s independent policy cap. Record the existing first-wake extension and remove the claimed global maximum. No activator change is needed.
+
+ **Fault family:** timeout-contract accuracy.
+
+These P2s should be fixed without reopening review. Round 3 is final.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md
new file mode 100644
index 000000000..8381c5332
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-FINDINGS-edge-roll-blip-spec.md
@@ -0,0 +1,63 @@
+Reviewed round 1 at `e0b2877a`. No files changed or test suites run. Amadan #434 was inaccessible from the sandbox; the committed binding brief supplied the scope.
+
+1. **P1 — §4 rows 6/8/9: recovery can leave an old binary behind an active socket indefinitely.**
+
+ D4 checks the binary only when the socket starts. At boot, the socket can pass that check before recovery replaces the binary. `restoreFiles` then renames the old binary into place at [systemapply.go:1892](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/host/systemapply.go:1892), but can return on a directory-sync error or failed staging before reaching socket removal at line 1927. `recoverIfNeeded` returns immediately on that failure at line 2061. The recovery unit has no automatic retry.
+
+ **Failure scenario:** interrupted first installation boots with the new binary and socket; recovery restores the old binary, then fails before disabling the socket. On an unguarded box, the old edge starts and fails with `EADDRINUSE`. D4 never reruns because the socket remains active. Row 8’s “active socket implies a socket-aware binary” claim is false.
+
+ **Fix:** enforce socket release before replacing a socket-aware binary with an incompatible one. Require compatible apply/recovery machinery before enabling this feature; refuse activation on older paths unless an independent compatibility guard covers them. Test failures after the rename and before unit removal, including boot recovery.
+
+ **Fault family:** rollback compatibility—an incompatible edge must never start while PID 1 holds its ports.
+
+2. **P1 — D10: probed local upstreams still fail requests during a restart.**
+
+ D10 explicitly excludes `multiProxy`, although the binding brief requires local upstream restarts to become queued waits without 502/503. A valid `Health` configuration selects `multiProxy` at [edge.go:846](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:846). That proxy immediately rejects an empty live set at line 2838, ejects a refused upstream at line 2876, and returns 503 at line 2892.
+
+ **Failure scenario:** a single probed loopback upstream restarts. Requests receive immediate 503 responses, even if it returns well within 13 seconds. This also leaves the console outcome dependent on an unverified route-shape assumption.
+
+ **Fix:** define a bounded hold for probed local routes too, preserving health admission: wait for an eligible local upstream to return rather than dialing an ejected endpoint. Test both refusal-before-probe-update and already-empty-live-set cases.
+
+ **Fault family:** restart admission—supported local route shapes must receive the promised bounded wait.
+
+3. **P2 — D5: closing an unmatched inherited listener does not guarantee successful fallback.**
+
+ [Design lines 230–236](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:230) require IP matching, close unmatched descriptors, and claim malformed handoffs cost only a blip. But D6 correctly establishes that PID 1 retains its own socket reference.
+
+ **Failure scenario:** the socket holds dual-stack wildcard port 80, while the service specifies `-http 127.0.0.1:80`. Rejecting the wildcard descriptor and closing the child’s copy leaves PID 1 holding the conflicting port. Fallback binding fails and the edge exits through the fatal listener path at [edge.go:3820](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/edge/edge.go:3820).
+
+ **Fix:** distinguish absent listeners from incompatible inherited listeners. Define supported address compatibility, require matching socket overrides for restricted addresses, and reject conflicting configurations before activation. Remove the unconditional availability guarantee and test this collision.
+
+ **Fault family:** listener ownership and configured bind scope.
+
+4. **P2 — §1.3: the asserted rollback version floor is incorrect and conditional.**
+
+ [Design line 92](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:90) says the layout floor refuses everything below v0.24.2. The actual constant is **v0.25.0** at [layoutintent.go:211](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/release/layoutintent.go:211), and [systemapply.go:583](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/internal/host/systemapply.go:583) refuses only when `layoutReversalReasons()` is nonempty. This is not an unconditional minimum updater version.
+
+ **Failure scenario:** a flat box admits an older release that the compatibility argument incorrectly excludes.
+
+ **Fix:** state the actual conditional floor and establish the supported applier/recovery baseline independently. I verified that **v0.18.0** records `UnitsAdded` at `internal/host/systemapply.go:353`, invokes `disable --now` at line 523, and passes `UnitsAdded` into restoration at line 797; those facts do not establish an unconditional installation floor.
+
+ **Fault family:** compatibility eligibility—version exclusions must follow enforced checks.
+
+5. **P2 — §7 W2: the witness does not consistently select the binary it builds.**
+
+ [W2 lines 376–379](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:376) retain D2’s socket lines except for listed overrides. Those overrides leave `ExecStartPre=/opt/carlos/carlos system edge-socket-check` intact, while the service uses bare `ExecStart=carlos edge …`. Neither selects the temporary build explicitly. `/opt/carlos/carlos` is absent on this machine.
+
+ **Failure scenario:** the socket check fails before binding, or the service executes another installed binary; the witness cannot establish the proposed handoff.
+
+ **Fix:** use the temporary build’s absolute path in both commands, remove both system-account directives for the user units, and assert socket activity and inherited-listener logs before measuring.
+
+ **Fault family:** verification identity—the witness must exercise the built binary and intended activation path.
+
+6. **P2 — D1: the fd-store comparison omits the supported preservation setting.**
+
+ [Design line 138](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-roll-blip/docs/superpowers/specs/2026-10-27-edge-roll-blip-design.md:138) categorically says stop/start loses stored descriptors. Installed systemd 257 documentation, `systemd.service(5)`, `FileDescriptorStorePreserve=`—decompressed source lines 1568–1586—documents `yes`, which retains them until the inactive unit is unreferenced and unloaded.
+
+ **Failure scenario:** the mechanism comparison rejects configured preservation using the default setting’s behavior.
+
+ **Fix:** distinguish default `restart` preservation from `yes`, including its unit-retention condition. The lack of fresh-boot listeners and rollback incompatibility remain separate reasons to prefer socket units.
+
+ **Fault family:** mechanism evidence—compare supported configurations accurately.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/edge/answered.go b/internal/edge/answered.go
index 8a6c6ee8b..bba7ec852 100644
--- a/internal/edge/answered.go
+++ b/internal/edge/answered.go
@@ -58,10 +58,12 @@ const causeClientGone = "client_gone"
// clientGoneGrace is how long a client may wait before its leaving stops
// being its own business. Past it the wait is the finding: a dead unix
-// socket is redialled for 13s (dialUnixWithRetry) and a wedged instance is
-// never timed out at all, so a monitor or a visitor that gives up first is
-// the only way those outages end — and filing nothing for them would hide
-// exactly the worst ones (apperr.CauseAbandoned).
+// socket, a refused loopback TCP upstream and a probed route with a local
+// upstream are all held for 13s or more (dialUnixWithRetry, retryLocalDial)
+// and a wedged instance is never timed out at all, so a monitor or a
+// visitor that gives up first is the only way those outages end — and
+// filing nothing for them would hide exactly the worst ones
+// (apperr.CauseAbandoned).
var clientGoneGrace = 5 * time.Second // a var only so a test can shorten it
// withOutcome returns r carrying a fresh outcome and the outcome itself.
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 28a421f0c..838665aa8 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -97,7 +97,10 @@ type Activator interface {
// its backend. The host→backend map is swapped atomically, so reloads and
// zero-downtime deploys never drop a live connection.
type Edge struct {
- reg *registry.Registry
+ reg *registry.Registry
+ // hold is this Edge's local-upstream hold settings (localhold.go), set
+ // before the startup Reload and read by it.
+ hold localHold
upstreams atomic.Pointer[map[string]upstream]
// act, when non-nil, is the hibernation activator: hibernate-flagged
// instance routes stop being always-on backends and become on-demand
@@ -455,7 +458,13 @@ type upstream struct {
// New builds an Edge over reg and performs the startup reload. act may be nil
// (no hibernation).
func New(reg *registry.Registry, act Activator) (*Edge, error) {
- e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
+ return newEdge(reg, act, defaultLocalHold())
+}
+
+// newEdge is New with the local-upstream hold settings given, so a test can
+// shorten or turn off a hold on its own Edge without touching a global.
+func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) {
+ e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
planLimiter: ratelimit.NewLimiter(time.Now, 100_000)}
e.geo = geo.NewSwappable()
@@ -848,7 +857,7 @@ func (e *Edge) Reload() error {
var p *httputil.ReverseProxy
switch {
case t.Health == "":
- p = tcpProxy(addrs[0])
+ p = tcpProxy(addrs[0], e.hold)
default:
var h provision.Health
if err := json.Unmarshal([]byte(t.Health), &h); err != nil {
@@ -861,14 +870,14 @@ func (e *Edge) Reload() error {
// as long as it exists.
e.logThrottled("health-parse "+t.Host, fmt.Sprintf(
"route %s: unparseable health config (%v) — serving %s unprobed", t.Host, err, addrs[0]))
- p = tcpProxy(addrs[0])
+ p = tcpProxy(addrs[0], e.hold)
break
}
// Raw parse, deliberately un-normalized: Sync runs every spec
// through Health.WithDefaults itself, and normalizing here too
// would just be a second place to keep in step with it.
probeSpecs[t.Host] = probeSpec{Host: t.Host, Addrs: addrs, Health: h}
- p = multiProxy(t.Host, e.probers)
+ p = multiProxy(t.Host, e.probers, e.hold)
}
p.ModifyResponse = e.responseModifier(t)
proxy = p
@@ -2733,7 +2742,28 @@ func unixProxy(socketPath string) *httputil.ReverseProxy {
// tcpProxy reverse-proxies to a TCP upstream at http://addr with the same
// Host preservation and idle bounds as unixProxy — this is what lets
// whole-app tenants sit behind the edge without unix-socket support.
-func tcpProxy(addr string) *httputil.ReverseProxy {
+//
+// A loopback upstream is this box's own process, so a refused dial there is
+// a restart in progress: the dial is retried for hold.dial (one deadline
+// fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote
+// addr, keeps the stock dialer (hold.dialer is nil in production).
+func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
+ tr := &http.Transport{
+ MaxIdleConns: 32,
+ IdleConnTimeout: 90 * time.Second,
+ DialContext: hold.dialer,
+ }
+ if hold.dial > 0 && isLocalUpstream(addr) {
+ dial := hold.dialer
+ if dial == nil {
+ dial = (&net.Dialer{}).DialContext
+ }
+ tr.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) {
+ return retryLocalDial(ctx, time.Now().Add(hold.dial), func(actx context.Context) (net.Conn, error) {
+ return dial(actx, network, a)
+ })
+ }
+ }
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
setForwarded(pr)
@@ -2743,17 +2773,15 @@ func tcpProxy(addr string) *httputil.ReverseProxy {
pr.Out.Host = pr.In.Host // backend sees the real hostname
scrubInboundPurgeHeader(pr)
},
- Transport: &http.Transport{
- MaxIdleConns: 32,
- IdleConnTimeout: 90 * time.Second,
- },
+ Transport: tr,
ErrorHandler: defaultProxyError(proxyCause),
}
}
// errNoLiveUpstream is the sentinel multiProxy's dialer returns when a probed
// route has nothing left to try — an empty live set, or every live upstream
-// refusing the dial inside this one request. multiProxy's ErrorHandler turns
+// refusing the dial inside this one request — or, for a route with a local
+// upstream, when its D10b hold ends first. multiProxy's ErrorHandler turns
// it into 503 + Retry-After: 2, the same "nobody is home right now, come back
// shortly" answer errFleetDark gets, rather than the ReverseProxy default's
// 502 (which reads as "your backend is broken" and is what an UNPROBED addr
@@ -2814,7 +2842,7 @@ const multiDialTimeout = 3 * time.Second
// handshake per request to a backend that is, in every deployment this exists
// for, on the same network. The unprobed tcpProxy path keeps its pool
// untouched.
-func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
+func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProxy {
// Per-ROUTE cursor: closed over by this proxy alone, so two routes cannot
// interleave their rotations (a global counter would make a two-upstream
// route's balance depend on the request rate of every other route on the
@@ -2822,7 +2850,10 @@ func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
// upstream set — which is what you want, since the set it was counting
// over no longer exists.
var cursor atomic.Uint64
- dialer := &net.Dialer{Timeout: multiDialTimeout}
+ dial := hold.dialer
+ if dial == nil {
+ dial = (&net.Dialer{}).DialContext
+ }
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
setForwarded(pr)
@@ -2833,50 +2864,109 @@ func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
scrubInboundPurgeHeader(pr)
},
Transport: &http.Transport{
+ // The dialer works in passes (D10b, spec §3). A pass walks a fresh
+ // Live snapshot once; a host with no local upstream gets one pass,
+ // as before. A host with a local upstream, when a pass connects
+ // nothing, waits 100ms and passes again until its hold ends: the
+ // local upstream is restarting, and the prober will readmit it.
+ // Only the live set is ever dialed, so a held request waits for
+ // readmission; it never dials an ejected upstream itself.
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
- live := p.Live(host)
- if len(live) == 0 {
- return nil, errNoLiveUpstream
+ holdFor, local := p.Hold(host)
+ // One deadline, fixed on entry, bounds every attempt and
+ // every wait between passes.
+ var deadline time.Time
+ if local {
+ deadline = time.Now().Add(holdFor)
+ }
+ var (
+ lastErr error
+ tried int
+ )
+ noLive := func() error {
+ if tried == 0 {
+ if local {
+ return fmt.Errorf("%w for %s within its %v hold", errNoLiveUpstream, host, holdFor)
+ }
+ return errNoLiveUpstream
+ }
+ return fmt.Errorf("%w for %s: %d dial(s) refused, last: %v",
+ errNoLiveUpstream, host, tried, lastErr)
}
- // Start where the last request left off, then walk the whole
- // snapshot once. Snapshot rather than re-reading Live per
- // attempt: each Eject below shrinks the live set, and re-reading
- // would skip untried upstreams as the list moved under us.
- //
- // The index arithmetic stays in uint64 all the way to the
- // modulo. Converting the counter to int first would wrap
- // NEGATIVE once it passed 2^31 on a 32-bit box (the Pi fleet),
- // and Go's modulo keeps the sign — so the very next request
- // after that wrap would index out of range and panic the edge.
- start := cursor.Add(1) - 1
- n := uint64(len(live))
- var lastErr error
- for i := range live {
- if err := ctx.Err(); err != nil {
- // The client went away (or the request deadline
- // expired) mid-loop. Stop, and do NOT eject: a dial we
- // abandoned says nothing about the upstream's health,
- // and marking it down here would take a healthy box out
- // of rotation because one user hit stop.
- return nil, err
+ for {
+ live := p.Live(host)
+ if len(live) > 0 {
+ // Start where the last pass left off, then walk the
+ // whole snapshot once. Snapshot rather than re-reading
+ // Live per attempt: each Eject below shrinks the live
+ // set, and re-reading would skip untried upstreams as
+ // the list moved under us.
+ //
+ // The index arithmetic stays in uint64 all the way to
+ // the modulo. Converting the counter to int first would
+ // wrap NEGATIVE once it passed 2^31 on a 32-bit box
+ // (the Pi fleet), and Go's modulo keeps the sign — so
+ // the very next request after that wrap would index out
+ // of range and panic the edge.
+ start := cursor.Add(1) - 1
+ n := uint64(len(live))
+ for i := range live {
+ if err := ctx.Err(); err != nil {
+ // The client went away (or the request deadline
+ // expired) mid-loop. Stop, and do NOT eject: a
+ // dial we abandoned says nothing about the
+ // upstream's health, and marking it down here
+ // would take a healthy box out of rotation
+ // because one user hit stop.
+ return nil, err
+ }
+ addr := live[(start+uint64(i))%n]
+ // Each attempt ends at the earlier of
+ // multiDialTimeout and the hold's deadline.
+ until := time.Now().Add(multiDialTimeout)
+ if local && deadline.Before(until) {
+ until = deadline
+ }
+ actx, cancel := context.WithDeadline(ctx, until)
+ conn, err := dial(actx, network, addr)
+ cancel()
+ if err == nil {
+ return conn, nil
+ }
+ lastErr = err
+ tried++
+ if ctx.Err() != nil {
+ return nil, err // as above: our own cancellation, not the upstream's fault
+ }
+ if local && !time.Now().Before(deadline) {
+ // The hold ran out mid-attempt: the budget is
+ // spent, not the upstream. No Eject.
+ return nil, noLive()
+ }
+ // The fast path the probe cadence cannot match: a
+ // box that died since the last tick is out of
+ // rotation now, for every other in-flight request
+ // too, instead of collecting failures until
+ // fail_after.
+ p.Eject(host, addr)
+ }
}
- addr := live[(start+uint64(i))%n]
- conn, err := dialer.DialContext(ctx, network, addr)
- if err == nil {
- return conn, nil
+ if !local {
+ return nil, noLive()
}
- lastErr = err
- if ctx.Err() != nil {
- return nil, err // as above: our own cancellation, not the upstream's fault
+ left := time.Until(deadline)
+ if left <= 0 {
+ return nil, noLive()
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(min(localDialStep, left)):
+ }
+ if !time.Now().Before(deadline) {
+ return nil, noLive()
}
- // The fast path the probe cadence cannot match: a box that
- // died since the last tick is out of rotation now, for
- // every other in-flight request too, instead of collecting
- // failures until fail_after.
- p.Eject(host, addr)
}
- return nil, fmt.Errorf("%w for %s: %d upstream(s) refused, last: %v",
- errNoLiveUpstream, host, len(live), lastErr)
},
// No MaxIdleConns/IdleConnTimeout twin of tcpProxy's: with
// keep-alives off nothing is ever pooled, so the idle bounds that
@@ -3501,7 +3591,7 @@ func backhaulProxy(host, eip, box, auth, doorAuth string, assetFill bool, tr htt
// dialUnixWithRetry masks the brief gap during an instance restart: while the
// old process has exited and the new one hasn't rebound the socket, dials fail
-// with ENOENT/ECONNREFUSED. Retry those for a short window so no in-flight
+// with ENOENT/ECONNREFUSED. Retry those for localDialHold so no in-flight
// request is dropped; any other error fails fast. The window must exceed a
// deploy's socket-absent gap — the instance drain (10s) plus rebind — so an
// in-flight request is never 502'd mid-deploy; a sustained-down backend hangs
@@ -3640,10 +3730,17 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
// connection exhaustion. No ReadTimeout/WriteTimeout — those would
// break long-lived proxied WebSockets.
srv := &http.Server{Addr: *httpAddr, Handler: e, ReadHeaderTimeout: 10 * time.Second}
+ // Bound here, on this goroutine, as ListenAndServe would; the line
+ // below means the bind succeeded.
+ ln, err := listen("http", *httpAddr, ":http")
+ if err != nil {
+ log.Fatal(err)
+ }
+ log.Print(listenersLine(ln, *httpAddr, nil, ""))
go func() {
log.Printf("edge: DEV MODE — plain HTTP, serving %d route(s) on %s (registry %s)",
len(e.current()), *httpAddr, *registryPath)
- if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
log.Fatalf("edge: http listener %s: %v", *httpAddr, err)
}
}()
@@ -3814,16 +3911,29 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
httpSrv := &http.Server{Addr: *httpAddr, Handler: acmeAndFallback, ReadHeaderTimeout: 10 * time.Second}
httpsSrv := &http.Server{Addr: *httpsAddr, Handler: e, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second}
+ // Bind both before serving either, on this goroutine, as ListenAndServe
+ // and ListenAndServeTLS do internally (empty flags become :http and
+ // :https). The line below means both binds succeeded.
+ httpLn, err := listen("http", *httpAddr, ":http")
+ if err != nil {
+ log.Fatal(err)
+ }
+ httpsLn, err := listen("https", *httpsAddr, ":https")
+ if err != nil {
+ log.Fatal(err)
+ }
+ log.Print(listenersLine(httpLn, *httpAddr, httpsLn, *httpsAddr))
+
// :80 serves the ACME HTTP-01 challenge and redirects everything else.
go func() {
- if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ if err := httpSrv.Serve(httpLn); err != nil && err != http.ErrServerClosed {
log.Fatalf("edge: http listener %s: %v", *httpAddr, err)
}
}()
go func() {
log.Printf("edge: serving %d route(s) on %s (registry %s, acme cache %s)",
len(e.current()), *httpsAddr, *registryPath, *acmeCache)
- if err := httpsSrv.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
+ if err := httpsSrv.ServeTLS(httpsLn, "", ""); err != nil && err != http.ErrServerClosed {
log.Fatalf("edge: https listener %s: %v", *httpsAddr, err)
}
}()
diff --git a/internal/edge/edge_test.go b/internal/edge/edge_test.go
index 89c2f5278..4e61314ec 100644
--- a/internal/edge/edge_test.go
+++ b/internal/edge/edge_test.go
@@ -1776,9 +1776,10 @@ func TestAllUpstreamsDownAnswers503WithRetryAfter(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ // noHold: the point here is the 503 itself, not the D10b wait.
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
- t.Fatalf("New: %v", err)
+ t.Fatalf("newEdge: %v", err)
}
defer e.probers.Stop()
srv := httptest.NewServer(e)
@@ -1818,9 +1819,10 @@ func TestSingleAddrWithHealthGets503Semantics(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ // noHold: the point here is the 503 itself, not the D10b wait.
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
- t.Fatalf("New: %v", err)
+ t.Fatalf("newEdge: %v", err)
}
defer e.probers.Stop()
srv := httptest.NewServer(e)
@@ -1919,7 +1921,7 @@ func TestLegacySingleAddrRouteUnchanged(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -1990,7 +1992,15 @@ func TestReloadSwapsUpstreamSet(t *testing.T) {
// whatever it reads with tag so a test can tell WHICH upstream served it.
func upgradeEchoBackend(t *testing.T, tag string) string {
t.Helper()
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ts := httptest.NewServer(upgradeEchoHandler(tag))
+ t.Cleanup(ts.Close)
+ return ts.Listener.Addr().String()
+}
+
+// upgradeEchoHandler is upgradeEchoBackend's handler, for a test that
+// starts its own listener.
+func upgradeEchoHandler(tag string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == testProbePath {
w.WriteHeader(http.StatusOK)
return
@@ -2015,9 +2025,7 @@ func upgradeEchoBackend(t *testing.T, tag string) string {
}
buf.WriteString(tag + ":" + line)
buf.Flush()
- }))
- t.Cleanup(ts.Close)
- return ts.Listener.Addr().String()
+ })
}
// TestMultiUpstreamServesWebSocketUpgrade guards the one thing multiProxy's
@@ -2151,7 +2159,7 @@ func TestMultiAddrWithoutHealthServesFirstUnprobed(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatalf("New: %v", err)
}
diff --git a/internal/edge/edgeerrors_test.go b/internal/edge/edgeerrors_test.go
index 2f98961e1..59a51b261 100644
--- a/internal/edge/edgeerrors_test.go
+++ b/internal/edge/edgeerrors_test.go
@@ -198,7 +198,7 @@ func TestEdgeFilesUnavailableByCause(t *testing.T) {
t.Fatal(err)
}
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatal(err)
}
diff --git a/internal/edge/genproxy.go b/internal/edge/genproxy.go
index f876386b2..eb29f0f4b 100644
--- a/internal/edge/genproxy.go
+++ b/internal/edge/genproxy.go
@@ -37,30 +37,19 @@ var errNoGeneration = fmt.Errorf("edge: instance has no current generation: %w",
// resolve is asked before the first dial and again before every retry, so a
// dial that races a switch lands on the generation that is current by then.
func dialUnixRetrying(ctx context.Context, d *net.Dialer, resolve func() (string, bool)) (net.Conn, error) {
- const window = 13 * time.Second
- deadline := time.Now().Add(window)
- for {
- var (
- conn net.Conn
- err error
- )
- if sock, ok := resolve(); ok {
- conn, err = unixdial.Checked(ctx, d, sock)
- } else {
- err = errNoGeneration
- }
- if err == nil {
- return conn, nil
- }
- if ctx.Err() != nil || !isRetryableDialErr(err) || time.Now().After(deadline) {
- return nil, err
- }
- select {
- case <-ctx.Done():
- return nil, ctx.Err()
- case <-time.After(100 * time.Millisecond):
+ return dialUnixUntil(ctx, time.Now().Add(localDialHold), d, resolve)
+}
+
+// dialUnixUntil is dialUnixRetrying with the hold's deadline given, so a
+// test can shorten it without a package global.
+func dialUnixUntil(ctx context.Context, deadline time.Time, d *net.Dialer, resolve func() (string, bool)) (net.Conn, error) {
+ return retryLocalDial(ctx, deadline, func(actx context.Context) (net.Conn, error) {
+ sock, ok := resolve()
+ if !ok {
+ return nil, errNoGeneration
}
- }
+ return unixdial.Checked(actx, d, sock)
+ })
}
// genMovedError is a generation pool's dial giving up: its own socket is
@@ -83,10 +72,19 @@ func (e *genMovedError) Error() string {
// current or no generation is; once another one is current, own is gone for
// good and the dial returns genMovedError.
func dialGen(ctx context.Context, d *net.Dialer, src GenSource, host string, own GenInfo) (net.Conn, error) {
- const window = 13 * time.Second
- deadline := time.Now().Add(window)
+ return dialGenUntil(ctx, time.Now().Add(localDialHold), d, src, host, own)
+}
+
+// dialGenUntil is dialGen with the hold's deadline given. Like
+// retryLocalDial, each attempt runs on a context that ends at the deadline
+// and each wait is min(100ms, time left); an attempt the deadline cut
+// short gives errHoldExpired.
+func dialGenUntil(ctx context.Context, deadline time.Time, d *net.Dialer, src GenSource, host string, own GenInfo) (net.Conn, error) {
for {
- conn, err := unixdial.Checked(ctx, d, own.Socket)
+ actx, cancel := context.WithDeadline(ctx, deadline)
+ conn, err := unixdial.Checked(actx, d, own.Socket)
+ cut := actx.Err() != nil // read before cancel, which would also set it
+ cancel()
if err == nil {
// Spec §7.2 (rev 17): if the generation stops being current
// before the dial completes, the request is retried against the
@@ -105,8 +103,17 @@ func dialGen(ctx context.Context, d *net.Dialer, src GenSource, host string, own
return nil, &genMovedError{to: cur}
}
err = errNoGeneration
+ cut = false
}
- if ctx.Err() != nil || !isRetryableDialErr(err) || time.Now().After(deadline) {
+ if ctx.Err() != nil {
+ return nil, err
+ }
+ retryable := isRetryableDialErr(err)
+ if !retryable && cutByDeadline(cut, err) {
+ return nil, errHoldExpired
+ }
+ left := time.Until(deadline)
+ if !retryable || left <= 0 {
return nil, err
}
if cur, ok := src.ServingGen(host); ok && (cur.N != own.N || cur.Socket != own.Socket) {
@@ -115,7 +122,10 @@ func dialGen(ctx context.Context, d *net.Dialer, src GenSource, host string, own
select {
case <-ctx.Done():
return nil, ctx.Err()
- case <-time.After(100 * time.Millisecond):
+ case <-time.After(min(localDialStep, left)):
+ }
+ if !time.Now().Before(deadline) {
+ return nil, err
}
}
}
@@ -306,10 +316,10 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
}
}
-// waitServingGen waits, within the dial's 13 s retry window and ctx, for
+// waitServingGen waits, within the dial's localDialHold window and ctx, for
// host to have a current generation, asking every 100 ms.
func waitServingGen(ctx context.Context, src GenSource, host string) (GenInfo, bool) {
- deadline := time.Now().Add(13 * time.Second)
+ deadline := time.Now().Add(localDialHold)
for {
if g, ok := src.ServingGen(host); ok {
return g, true
diff --git a/internal/edge/genproxy_test.go b/internal/edge/genproxy_test.go
index 35ec93dbf..d7cc7c742 100644
--- a/internal/edge/genproxy_test.go
+++ b/internal/edge/genproxy_test.go
@@ -16,6 +16,8 @@ import (
"syscall"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/unixdial"
)
// fakeGens is a GenSource a test drives by hand: switchTo is plan 3's
@@ -506,3 +508,62 @@ func TestGenRoundTripperGivesUpWhenEveryGenerationIsStale(t *testing.T) {
t.Fatalf("body closed %d times, want 1", got)
}
}
+
+// blockingDialer is a Dialer whose connect never completes: its control
+// hook parks until the attempt's context ends, as a stuck dial would.
+func blockingDialer() *net.Dialer {
+ return &net.Dialer{ControlContext: func(ctx context.Context, _, _ string, _ syscall.RawConn) error {
+ <-ctx.Done()
+ return ctx.Err()
+ }}
+}
+
+// An attempt is bounded by the one hold deadline: a dial that blocks gives
+// errHoldExpired at the deadline instead of outliving the hold.
+func TestDialUnixRetryingAttemptEndsAtTheDeadline(t *testing.T) {
+ dir := genSockDir(t)
+ resolve := func() (string, bool) { return filepath.Join(dir, "x.sock"), true }
+ start := time.Now()
+ _, err := dialUnixUntil(context.Background(), start.Add(300*time.Millisecond), blockingDialer(), resolve)
+ if !errors.Is(err, errHoldExpired) || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, want errHoldExpired wrapping DeadlineExceeded", err)
+ }
+ if took := time.Since(start); took < 250*time.Millisecond || took > 2*time.Second {
+ t.Fatalf("returned after %v, want about 300ms", took)
+ }
+}
+
+func TestDialGenAttemptEndsAtTheDeadline(t *testing.T) {
+ dir := genSockDir(t)
+ own := GenInfo{Socket: filepath.Join(dir, "x.sock"), N: 1}
+ src := newFakeGens(true)
+ src.switchTo("inst.example.com", own)
+ start := time.Now()
+ _, err := dialGenUntil(context.Background(), start.Add(300*time.Millisecond), blockingDialer(), src, "inst.example.com", own)
+ if !errors.Is(err, errHoldExpired) || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, want errHoldExpired wrapping DeadlineExceeded", err)
+ }
+ if took := time.Since(start); took < 250*time.Millisecond || took > 2*time.Second {
+ t.Fatalf("returned after %v, want about 300ms", took)
+ }
+}
+
+// A dial that outlasts the deadline and then fails for its own reason (a
+// listener bound to another path) keeps that reason.
+func TestDialGenKeepsUnrelatedErrorAtDeadline(t *testing.T) {
+ dir := genSockDir(t)
+ own := GenInfo{Socket: filepath.Join(dir, "x.sock"), N: 1}
+ src := newFakeGens(true)
+ src.switchTo("inst.example.com", own)
+ d := &net.Dialer{ControlContext: func(ctx context.Context, _, _ string, _ syscall.RawConn) error {
+ <-ctx.Done()
+ return unixdial.ErrPeerMismatch
+ }}
+ _, err := dialGenUntil(context.Background(), time.Now().Add(200*time.Millisecond), d, src, "inst.example.com", own)
+ if !errors.Is(err, unixdial.ErrPeerMismatch) {
+ t.Fatalf("err = %v, want ErrPeerMismatch", err)
+ }
+ if errors.Is(err, errHoldExpired) || errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, an unrelated error is not a hold timeout", err)
+ }
+}
diff --git a/internal/edge/listeners.go b/internal/edge/listeners.go
new file mode 100644
index 000000000..4b054f802
--- /dev/null
+++ b/internal/edge/listeners.go
@@ -0,0 +1,38 @@
+package edge
+
+import (
+ "fmt"
+ "net"
+)
+
+// listenAddr maps an empty listen flag to def (":http" or ":https"), as
+// net/http's ListenAndServe and ListenAndServeTLS do for an empty Addr, and
+// keeps any other value as given.
+func listenAddr(flag, def string) string {
+ if flag == "" {
+ return def
+ }
+ return flag
+}
+
+// listen binds one of the edge's public listeners, the way ListenAndServe
+// does before it serves. On failure the error names the listener and the
+// flag as typed: "edge: http listener :80: listen tcp :80: ...".
+func listen(name, flag, def string) (net.Listener, error) {
+ ln, err := net.Listen("tcp", listenAddr(flag, def))
+ if err != nil {
+ return nil, fmt.Errorf("edge: %s listener %s: %w", name, flag, err)
+ }
+ return ln, nil
+}
+
+// listenersLine is the one startup line that says both binds succeeded. It
+// gives each listener's actual address (so a ":0" flag shows the allocated
+// port) beside the flag. httpsLn nil is the dev form: plain HTTP only.
+func listenersLine(httpLn net.Listener, httpFlag string, httpsLn net.Listener, httpsFlag string) string {
+ if httpsLn == nil {
+ return fmt.Sprintf("edge: listeners: bound http %s itself (dev mode; flag %q)", httpLn.Addr(), httpFlag)
+ }
+ return fmt.Sprintf("edge: listeners: bound http %s and https %s itself (flags %q %q)",
+ httpLn.Addr(), httpsLn.Addr(), httpFlag, httpsFlag)
+}
diff --git a/internal/edge/listeners_test.go b/internal/edge/listeners_test.go
new file mode 100644
index 000000000..6a879c858
--- /dev/null
+++ b/internal/edge/listeners_test.go
@@ -0,0 +1,71 @@
+package edge
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "testing"
+)
+
+func TestListenAddrNormalizesEmpty(t *testing.T) {
+ for _, c := range []struct{ flag, def, want string }{
+ {"", ":http", ":http"},
+ {"", ":https", ":https"},
+ {"127.0.0.1:8080", ":http", "127.0.0.1:8080"},
+ } {
+ if got := listenAddr(c.flag, c.def); got != c.want {
+ t.Errorf("listenAddr(%q, %q) = %q, want %q", c.flag, c.def, got, c.want)
+ }
+ }
+}
+
+func TestListenNamesTheListenerOnFailure(t *testing.T) {
+ held, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Close()
+ ln, err := listen("http", held.Addr().String(), ":http")
+ if err == nil {
+ ln.Close()
+ t.Fatal("listen on a held address succeeded")
+ }
+ if want := "edge: http listener 127.0.0.1:"; !strings.HasPrefix(err.Error(), want) {
+ t.Fatalf("error = %q, want prefix %q", err, want)
+ }
+}
+
+func TestListenersLineGivesBoundAddresses(t *testing.T) {
+ h, err := listen("http", "127.0.0.1:0", ":http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close()
+ s, err := listen("https", "127.0.0.1:0", ":https")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ got := listenersLine(h, "127.0.0.1:0", s, "127.0.0.1:0")
+ want := fmt.Sprintf("edge: listeners: bound http %s and https %s itself (flags %q %q)",
+ h.Addr(), s.Addr(), "127.0.0.1:0", "127.0.0.1:0")
+ if got != want {
+ t.Fatalf("line = %q, want %q", got, want)
+ }
+ if strings.Contains(got, ":0 ") {
+ t.Fatalf("line shows an unallocated port: %q", got)
+ }
+}
+
+func TestListenersLineDevForm(t *testing.T) {
+ h, err := listen("http", "127.0.0.1:0", ":http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close()
+ got := listenersLine(h, "127.0.0.1:0", nil, "")
+ want := fmt.Sprintf("edge: listeners: bound http %s itself (dev mode; flag %q)", h.Addr(), "127.0.0.1:0")
+ if got != want {
+ t.Fatalf("line = %q, want %q", got, want)
+ }
+}
diff --git a/internal/edge/localhold.go b/internal/edge/localhold.go
new file mode 100644
index 000000000..b6692f84f
--- /dev/null
+++ b/internal/edge/localhold.go
@@ -0,0 +1,114 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/netip"
+ "os"
+ "time"
+)
+
+// localDialHold is how long a request waits for a local upstream that is
+// restarting: the unix-socket redial window (it exceeds a deploy's
+// socket-absent gap), now shared by loopback TCP routes.
+const localDialHold = 13 * time.Second
+
+// localHoldCap bounds the whole hold of a probed route with a local
+// upstream (dial plus readmission). It equals the ordinary wake wait.
+const localHoldCap = 30 * time.Second
+
+// localHold is one Edge's hold settings. They live on the Edge, not in
+// package globals, so tests that shorten them cannot see each other.
+type localHold struct {
+ dial, cap, probe time.Duration
+ // dialer is a test seam; nil means a plain net.Dialer.
+ dialer func(ctx context.Context, network, addr string) (net.Conn, error)
+}
+
+// defaultLocalHold is what New gives every Edge.
+func defaultLocalHold() localHold {
+ return localHold{dial: localDialHold, cap: localHoldCap, probe: probeTimeout}
+}
+
+// isLocalUpstream reports whether addr (host:port) names this box's own
+// loopback: a loopback IP literal or "localhost". A refused dial there is
+// a restart in progress; a refused remote box is an outage.
+func isLocalUpstream(addr string) bool {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return false
+ }
+ if host == "localhost" {
+ return true
+ }
+ ip, err := netip.ParseAddr(host)
+ return err == nil && ip.IsLoopback()
+}
+
+// errHoldExpired is what retryLocalDial returns when the deadline cut an
+// attempt that had not failed on its own. It wraps DeadlineExceeded so
+// proxyCause files it as a timeout.
+var errHoldExpired = fmt.Errorf("edge: local upstream hold expired: %w", context.DeadlineExceeded)
+
+// cutByDeadline reports whether err is the attempt's own deadline talking:
+// the attempt context had ended (cut) and err is what a dial returns when
+// that ends it (a context error, or a timeout from the net or os layer).
+// An unrelated error that merely lands at the deadline (a peer mismatch,
+// a refused control endpoint) is not, and keeps its identity.
+func cutByDeadline(cut bool, err error) bool {
+ if !cut {
+ return false
+ }
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || errors.Is(err, os.ErrDeadlineExceeded) {
+ return true
+ }
+ var ne net.Error
+ return errors.As(err, &ne) && ne.Timeout()
+}
+
+// localDialStep is the pause between attempts.
+const localDialStep = 100 * time.Millisecond
+
+// retryLocalDial calls attempt until it connects, fails in a way that
+// cannot heal (not isRetryableDialErr), or deadline passes. The caller
+// fixes deadline once, before the first attempt. Each attempt runs on a
+// context that ends at deadline and each wait is min(100ms, time left), so
+// nothing outlives the hold. It always makes the first attempt. At the
+// deadline it returns the last retryable error; an attempt the deadline cut
+// short (and failed with its deadline error) gives errHoldExpired; any
+// other non-retryable error is returned as it is. A cancelled ctx returns ctx's error.
+func retryLocalDial(ctx context.Context, deadline time.Time, attempt func(context.Context) (net.Conn, error)) (net.Conn, error) {
+ for {
+ actx, cancel := context.WithDeadline(ctx, deadline)
+ conn, err := attempt(actx)
+ cut := actx.Err() != nil // read before cancel, which would also set it
+ cancel()
+ if err == nil {
+ return conn, nil
+ }
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ retryable := isRetryableDialErr(err)
+ if !retryable && cutByDeadline(cut, err) {
+ return nil, errHoldExpired
+ }
+ if !retryable {
+ return nil, err
+ }
+ left := time.Until(deadline)
+ if left <= 0 {
+ return nil, err
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(min(localDialStep, left)):
+ }
+ if !time.Now().Before(deadline) {
+ return nil, err
+ }
+ }
+}
diff --git a/internal/edge/localhold_probed_test.go b/internal/edge/localhold_probed_test.go
new file mode 100644
index 000000000..20feb2257
--- /dev/null
+++ b/internal/edge/localhold_probed_test.go
@@ -0,0 +1,504 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// readmitBound is spec §3's R, computed here independently of prober.go:
+// n upstreams probed every interval, rise passes to rejoin, probe timeout T.
+func readmitBound(n int, interval time.Duration, rise int, probe time.Duration) time.Duration {
+ g := max(interval, probe) + time.Duration(n-1)*probe
+ return time.Duration(rise)*g + probe
+}
+
+func TestHoldMatchesFormula(t *testing.T) {
+ local := "127.0.0.1:8080"
+ others := []string{"10.0.0.1:80", "10.0.0.2:80", "10.0.0.3:80"}
+ def := provision.Health{}.WithDefaults()
+ off := defaultLocalHold()
+ off.dial = 0
+ for _, tc := range []struct {
+ name string
+ addrs []string
+ health provision.Health
+ hold localHold
+ want time.Duration
+ ok bool
+ }{
+ {"one local", []string{local}, def, defaultLocalHold(), 19 * time.Second, true},
+ {"local plus 1", []string{local, others[0]}, def, defaultLocalHold(), 23 * time.Second, true},
+ {"local plus 2", []string{local, others[0], others[1]}, def, defaultLocalHold(), 27 * time.Second, true},
+ {"local plus 3 capped", append([]string{local}, others...), def, defaultLocalHold(), 30 * time.Second, true},
+ {"remote only", others, def, defaultLocalHold(), 0, false},
+ {"raw Health{}", []string{local}, provision.Health{}, defaultLocalHold(), 19 * time.Second, true},
+ {"negative interval", []string{local}, provision.Health{IntervalMS: -1}, defaultLocalHold(), 19 * time.Second, true},
+ {"negative rise", []string{local}, provision.Health{RiseAfter: -1}, defaultLocalHold(), 19 * time.Second, true},
+ {"dial 0", []string{local}, def, off, 0, false},
+ {"cap 0", []string{local}, def, localHold{dial: localDialHold, probe: probeTimeout}, 0, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ p := newProberSet(tc.hold)
+ hp := newHostProber(probeSpec{Host: "shop.example.com", Addrs: tc.addrs, Health: tc.health}, p.client, tc.hold)
+ p.mu.Lock()
+ p.hosts["shop.example.com"] = hp // not started: Hold reads only what newHostProber fixed
+ p.mu.Unlock()
+ got, ok := p.Hold("shop.example.com")
+ if got != tc.want || ok != tc.ok {
+ t.Fatalf("Hold = (%v, %v), want (%v, %v)", got, ok, tc.want, tc.ok)
+ }
+ })
+ }
+ if d, ok := newProberSet(defaultLocalHold()).Hold("unknown.example.com"); d != 0 || ok {
+ t.Fatalf("Hold(unknown) = (%v, %v), want (0, false)", d, ok)
+ }
+}
+
+// probedHold is the shortened hold the D10b behaviour tests run on unless
+// they say otherwise: one upstream gets min(800ms + 250ms, 5s) = 1050ms. The
+// generous dial leaves the tests that restart an upstream at 100-200ms
+// 600ms of slack on a loaded CI box.
+func probedHold() localHold {
+ return localHold{dial: 800 * time.Millisecond, cap: 5 * time.Second, probe: 50 * time.Millisecond}
+}
+
+// fastHealth probes every 100ms, fails on one miss and rejoins on two passes.
+func fastHealth() provision.Health {
+ return provision.Health{Path: testProbePath, IntervalMS: 100, FailAfter: 1, RiseAfter: 2}
+}
+
+// probedEdge is an Edge over one probed service route at addrs.
+func probedEdge(t *testing.T, addrs []string, h provision.Health, hold localHold) (*Edge, *httptest.Server) {
+ t.Helper()
+ reg := openReg(t)
+ csv := ""
+ for i, a := range addrs {
+ if i > 0 {
+ csv += ","
+ }
+ csv += a
+ }
+ if err := reg.Upsert(registry.Route{
+ Host: "shop.example.com", Kind: "service", Status: "ready",
+ Addrs: csv, Health: healthJSON(t, h),
+ }); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return e, srv
+}
+
+// countingHandler counts proxied requests and answers "ok"; probes are
+// answered but never counted.
+func countingHandler(hits *atomic.Int64) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == testProbePath {
+ return
+ }
+ hits.Add(1)
+ io.WriteString(w, "ok")
+ })
+}
+
+// probedGet sends one GET for shop.example.com and returns the response
+// (body drained) and how long it took.
+func probedGet(t *testing.T, url string) (*http.Response, time.Duration) {
+ t.Helper()
+ start := time.Now()
+ resp := getHostHeader(t, url, "shop.example.com")
+ return resp, time.Since(start)
+}
+
+func TestProbedLocalUpstreamWaitsForReadmission(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d after %v (hold %v), want 200 once readmitted", resp.StatusCode, el, mustHold(t, e))
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("proxied requests = %d, want exactly 1 (nothing reaches an ejected upstream)", n)
+ }
+}
+
+func TestProbedEmptyLiveSetOnArrivalWaits(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ waitFor(t, 2*time.Second, "the probe to empty the live set", func() bool {
+ return len(e.probers.Live("shop.example.com")) == 0
+ })
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d after %v, want 200 once readmitted", resp.StatusCode, el)
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("proxied requests = %d, want exactly 1", n)
+ }
+}
+
+func mustHold(t *testing.T, e *Edge) time.Duration {
+ t.Helper()
+ d, ok := e.probers.Hold("shop.example.com")
+ if !ok {
+ t.Fatalf("Hold(shop.example.com) = (%v, false), want a local hold", d)
+ }
+ return d
+}
+
+// want503At checks a held request's 503: Retry-After 2, cause
+// CauseNoUpstream, and elapsed in [at, at+300ms).
+func want503At(t *testing.T, resp *http.Response, el, at time.Duration, sink *memErrSink) {
+ t.Helper()
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d after %v, want 503", resp.StatusCode, el)
+ }
+ if got := resp.Header.Get("Retry-After"); got != "2" {
+ t.Fatalf("Retry-After = %q, want 2", got)
+ }
+ if el < at || el >= at+300*time.Millisecond {
+ t.Fatalf("503 after %v, want within 300ms of %v", el, at)
+ }
+ waitFor(t, time.Second, "the edge error record", func() bool { return len(sink.snap()) > 0 })
+ recs := sink.snap()
+ if len(recs) != 1 || recs[0].Cause != apperr.CauseNoUpstream {
+ t.Fatalf("records = %+v, want one with cause %q", recs, apperr.CauseNoUpstream)
+ }
+}
+
+func TestProbedLocalStillDownPastHold(t *testing.T) {
+ e, srv := probedEdge(t, []string{deadAddr(t)}, fastHealth(), probedHold())
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ hold := mustHold(t, e)
+ if want := probedHold().dial + readmitBound(1, 100*time.Millisecond, 2, 50*time.Millisecond); hold != want {
+ t.Fatalf("Hold = %v, want %v", hold, want)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold, sink)
+}
+
+func TestProbedPastCapAnswersAtCap(t *testing.T) {
+ hold := probedHold()
+ hold.cap = 400 * time.Millisecond
+ e, srv := probedEdge(t, []string{deadAddr(t)}, fastHealth(), hold)
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ if got := mustHold(t, e); got != hold.cap {
+ t.Fatalf("Hold = %v, want the cap %v", got, hold.cap)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold.cap, sink)
+}
+
+func TestProbedRemoteOnlyAnswersAtOnce(t *testing.T) {
+ hold := probedHold()
+ hold.dialer = func(context.Context, string, string) (net.Conn, error) { return nil, refusedErr() }
+ e, srv := probedEdge(t, []string{"10.0.0.5:80"}, fastHealth(), hold)
+ if d, ok := e.probers.Hold("shop.example.com"); ok {
+ t.Fatalf("Hold = (%v, true), want no hold for a remote-only route", d)
+ }
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
+ t.Fatalf("status = %d Retry-After %q, want 503 and 2", resp.StatusCode, resp.Header.Get("Retry-After"))
+ }
+ if el > 300*time.Millisecond {
+ t.Fatalf("503 after %v, want within 300ms (a hold would take a second)", el)
+ }
+}
+
+func TestProbedMixedSetWithLiveUpstreamServesAtOnce(t *testing.T) {
+ live, hits := countingBackend(t, "A")
+ _, srv := probedEdge(t, []string{deadAddr(t), live}, fastHealth(), probedHold())
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d, live upstream hits = %d, want 200 from it", resp.StatusCode, hits.Load())
+ }
+ if el > 300*time.Millisecond {
+ t.Fatalf("200 after %v, want within 300ms (a hold would take a second)", el)
+ }
+}
+
+// TestProbedDelayedProbeServedWithinR is spec §10 "Delayed probe": three
+// upstreams whose health check blocks past the probe timeout are probed
+// before the restarting one, so its readmission takes the longest the
+// formula allows for. It must still come within R, and the held request is
+// served then.
+func TestProbedDelayedProbeServedWithinR(t *testing.T) {
+ release := make(chan struct{})
+ var slowHits atomic.Int64
+ var slow []string
+ for i := 0; i < 3; i++ {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == testProbePath {
+ select {
+ case <-r.Context().Done():
+ case <-release:
+ }
+ return
+ }
+ slowHits.Add(1)
+ io.WriteString(w, "slow")
+ }))
+ t.Cleanup(ts.Close)
+ slow = append(slow, ts.Listener.Addr().String())
+ }
+ t.Cleanup(func() { close(release) }) // runs before the servers close
+ a := deadAddr(t)
+ hold := probedHold()
+ e, srv := probedEdge(t, append(slow, a), fastHealth(), hold)
+ r := readmitBound(4, 100*time.Millisecond, 2, hold.probe)
+ if got := mustHold(t, e); got != hold.dial+r {
+ t.Fatalf("Hold = %v, want dial + R = %v", got, hold.dial+r)
+ }
+ waitFor(t, 2*time.Second, "every upstream to leave the live set", func() bool {
+ return len(e.probers.Live("shop.example.com")) == 0
+ })
+
+ // The upstream comes back 100ms into the request's hold; a watcher
+ // stamps the moment the prober readmits it.
+ // The goroutine never touches t: it reports a listen failure on listenErr
+ // and owns the restarted server, which it closes when the test's cleanup
+ // (registered before it starts, so an early Fatalf cannot skip it) stops
+ // it and waits for it to finish.
+ var hits atomic.Int64
+ back := make(chan time.Time, 1)
+ readmitted := make(chan time.Time, 1)
+ listenErr := make(chan error, 1)
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ t.Cleanup(func() {
+ close(stop)
+ <-done
+ })
+ go func() {
+ defer close(done)
+ select {
+ case <-time.After(100 * time.Millisecond):
+ case <-stop:
+ return
+ }
+ ln, err := net.Listen("tcp", a)
+ if err != nil {
+ listenErr <- fmt.Errorf("listen %s: %w", a, err)
+ close(back)
+ close(readmitted)
+ return
+ }
+ s := httptest.NewUnstartedServer(countingHandler(&hits))
+ s.Listener.Close()
+ s.Listener = ln
+ s.Start()
+ defer s.Close()
+ back <- time.Now()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case <-stop:
+ close(readmitted)
+ return
+ default:
+ }
+ if slices.Contains(e.probers.Live("shop.example.com"), a) {
+ readmitted <- time.Now()
+ <-stop // keep serving until the test is over
+ return
+ }
+ time.Sleep(2 * time.Millisecond)
+ }
+ close(readmitted)
+ }()
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d after %v, hits = %d, want 200 from the readmitted upstream", resp.StatusCode, el, hits.Load())
+ }
+ if n := slowHits.Load(); n != 0 {
+ t.Fatalf("ejected slow upstreams served %d requests, want 0", n)
+ }
+ upAt, ok1 := <-back
+ inAt, ok2 := <-readmitted
+ if !ok1 || !ok2 {
+ select {
+ case err := <-listenErr:
+ t.Fatal(err)
+ default:
+ }
+ t.Fatalf("upstream never came back or was never readmitted")
+ }
+ if took := inAt.Sub(upAt); took > r {
+ t.Fatalf("readmission took %v, want at most R = %v", took, r)
+ } else {
+ t.Logf("readmission %v (R %v), served after %v (hold %v)", took, r, el, hold.dial+r)
+ }
+}
+
+func TestProbedDeadlineMidPassDoesNotEject(t *testing.T) {
+ const remote = "10.0.0.9:80"
+ hold := probedHold()
+ hold.cap = 400 * time.Millisecond
+ var plain net.Dialer
+ hold.dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ if addr == remote {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ return plain.DialContext(ctx, network, addr)
+ }
+ e, srv := probedEdge(t, []string{deadAddr(t), remote}, frozenHealth(), hold)
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ if got := mustHold(t, e); got != hold.cap {
+ t.Fatalf("Hold = %v, want the cap %v", got, hold.cap)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold.cap, sink)
+ if live := e.probers.Live("shop.example.com"); !slices.Contains(live, remote) {
+ t.Fatalf("live set = %v, want %s still live: the hold ran out, the upstream did not fail", live, remote)
+ }
+}
+
+func TestProbedHoldSurvivesReload(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ reloaded := make(chan error, 1)
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ reloaded <- e.Reload()
+ }()
+ resp, el := probedGet(t, srv.URL)
+ if err := <-reloaded; err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d after %v, hits = %d, want 200 across the reload", resp.StatusCode, el, hits.Load())
+ }
+}
+
+// TestProbedClientCancelDuringHoldDoesNotEject: when the request context ends
+// while the multi-upstream dial is parked on an upstream, the dial stops at
+// once and the upstream is not taken for failing. The local address refuses
+// and is ejected by the dial itself; the remote one hangs until its context
+// ends, and must still be live afterwards.
+//
+// This drives the Transport's DialContext directly, with a context the test
+// cancels. An end-to-end version (cancel an http.Client request, watch the
+// edge) cannot prove this: since Go 1.23 http.Transport hands DialContext a
+// context detached from the request's cancellation (context.WithoutCancel),
+// so a client that walks away never reaches the dial at all, and http.Client.Do
+// returns on its own context whatever the edge does.
+func TestProbedClientCancelDuringHoldDoesNotEject(t *testing.T) {
+ const (
+ host = "shop.example.com"
+ remote = "10.0.0.9:80"
+ )
+ hold := probedHold()
+ var plain net.Dialer
+ // entered: the dial is parked on the remote. dialAborted: that attempt saw
+ // its context end, i.e. the cancel reached the attempt's context. The
+ // prober's transport dials through hold.dialer too, and its first probe
+ // tick runs whatever the health says, so only a dial whose context
+ // carries requestDialKey (set on the test's own DialContext call below)
+ // signals: a probe cannot satisfy either channel.
+ type requestDialKey struct{}
+ entered := make(chan struct{})
+ dialAborted := make(chan struct{})
+ var enteredOnce, abortedOnce sync.Once
+ hold.dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ if addr == remote {
+ if ctx.Value(requestDialKey{}) == nil {
+ // A probe of the remote: it hangs like the request's dial
+ // but signals nothing.
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ enteredOnce.Do(func() { close(entered) })
+ <-ctx.Done()
+ abortedOnce.Do(func() { close(dialAborted) })
+ return nil, ctx.Err()
+ }
+ return plain.DialContext(ctx, network, addr)
+ }
+ e, _ := probedEdge(t, []string{deadAddr(t), remote}, frozenHealth(), hold)
+ if got := mustHold(t, e); got < 2*time.Second {
+ t.Fatalf("Hold = %v, want a hold far longer than the cancel below", got)
+ }
+ if live := e.probers.Live(host); len(live) != 2 || !slices.Contains(live, remote) {
+ t.Fatalf("live set = %v, want both upstreams live before the dial", live)
+ }
+ tr, ok := multiProxy(host, e.probers, hold).Transport.(*http.Transport)
+ if !ok {
+ t.Fatal("multiProxy transport is not an *http.Transport")
+ }
+
+ ctx, cancel := context.WithCancel(context.WithValue(context.Background(), requestDialKey{}, true))
+ defer cancel()
+ type result struct {
+ conn net.Conn
+ err error
+ }
+ res := make(chan result, 1)
+ go func() {
+ conn, err := tr.DialContext(ctx, "tcp", multiDialHost)
+ res <- result{conn, err}
+ }()
+
+ // Wait for the dial to be parked on the remote (the refused local one is
+ // ejected on the way, in whichever order they come), then cancel.
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the dial never reached the remote upstream")
+ }
+ cancel()
+
+ // The cancel must reach the attempt: a dial that ignored its context
+ // would sit here until multiDialTimeout.
+ select {
+ case <-dialAborted:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("the remote dial was not aborted within 500ms of the cancel")
+ }
+ var r result
+ select {
+ case r = <-res:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("DialContext did not return within 500ms of the cancel")
+ }
+ if r.err == nil {
+ r.conn.Close()
+ t.Fatal("DialContext succeeded, want the cancelled dial to fail")
+ }
+ if !errors.Is(r.err, context.Canceled) {
+ t.Fatalf("DialContext error = %v, want the cancellation", r.err)
+ }
+ // DialContext has returned, so its post-dial branch (where an Eject would
+ // happen) has run: the remote must have stayed live.
+ if live := e.probers.Live(host); !slices.Contains(live, remote) {
+ t.Fatalf("live set = %v, want %s still live: the caller left, the upstream did not fail", live, remote)
+ }
+}
diff --git a/internal/edge/localhold_test.go b/internal/edge/localhold_test.go
new file mode 100644
index 000000000..314a4b996
--- /dev/null
+++ b/internal/edge/localhold_test.go
@@ -0,0 +1,409 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/unixdial"
+)
+
+// noHold is D10 off: today's transport, an instant 502 on a refused loopback
+// dial. Tests whose point is the failure itself build their Edge on it.
+func noHold() localHold { return localHold{probe: probeTimeout} }
+
+// refusedErr is what a dial to a port nobody listens on returns.
+func refusedErr() error {
+ return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
+}
+
+func TestIsLocalUpstream(t *testing.T) {
+ for _, a := range []string{"127.0.0.1:80", "127.9.9.9:80", "[::1]:80", "localhost:80"} {
+ if !isLocalUpstream(a) {
+ t.Errorf("isLocalUpstream(%q) = false, want true", a)
+ }
+ }
+ for _, a := range []string{"10.0.0.5:80", "example.com:80", "nonsense"} {
+ if isLocalUpstream(a) {
+ t.Errorf("isLocalUpstream(%q) = true, want false", a)
+ }
+ }
+}
+
+func TestRetryLocalDialServesWhenUpstreamReturns(t *testing.T) {
+ a, b := net.Pipe()
+ defer a.Close()
+ defer b.Close()
+ var calls int
+ conn, err := retryLocalDial(context.Background(), time.Now().Add(5*time.Second),
+ func(context.Context) (net.Conn, error) {
+ calls++
+ if calls <= 2 {
+ return nil, refusedErr()
+ }
+ return a, nil
+ })
+ if err != nil {
+ t.Fatalf("retryLocalDial: %v", err)
+ }
+ if conn != a || calls != 3 {
+ t.Fatalf("conn ok = %v, calls = %d, want the pipe end after 3 attempts", conn == a, calls)
+ }
+}
+
+func TestRetryLocalDialReturnsLastRefusalAtDeadline(t *testing.T) {
+ start := time.Now()
+ _, err := retryLocalDial(context.Background(), start.Add(300*time.Millisecond),
+ func(context.Context) (net.Conn, error) { return nil, refusedErr() })
+ el := time.Since(start)
+ if !errors.Is(err, syscall.ECONNREFUSED) {
+ t.Fatalf("err = %v, want the last refusal", err)
+ }
+ if errors.Is(err, errHoldExpired) {
+ t.Fatalf("err = %v, a refusal at the deadline is not errHoldExpired", err)
+ }
+ if el < 300*time.Millisecond || el >= 450*time.Millisecond {
+ t.Fatalf("elapsed = %v, want in [300ms, 450ms)", el)
+ }
+}
+
+func TestRetryLocalDialBlockingAttemptEndsAtDeadline(t *testing.T) {
+ start := time.Now()
+ _, err := retryLocalDial(context.Background(), start.Add(200*time.Millisecond),
+ func(actx context.Context) (net.Conn, error) {
+ <-actx.Done()
+ return nil, actx.Err()
+ })
+ el := time.Since(start)
+ if !errors.Is(err, errHoldExpired) || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, want errHoldExpired wrapping DeadlineExceeded", err)
+ }
+ if el >= 300*time.Millisecond {
+ t.Fatalf("elapsed = %v, want < 300ms", el)
+ }
+}
+
+// An attempt that waits out its deadline and then fails for a reason of
+// its own keeps that reason: the deadline having passed does not make it
+// a timeout.
+func TestRetryLocalDialKeepsUnrelatedErrorAtDeadline(t *testing.T) {
+ for _, cause := range []error{unixdial.ErrPeerMismatch, unixdial.ErrControlEndpoint, errors.New("peer mismatch")} {
+ start := time.Now()
+ _, err := retryLocalDial(context.Background(), start.Add(150*time.Millisecond),
+ func(actx context.Context) (net.Conn, error) {
+ <-actx.Done()
+ return nil, fmt.Errorf("dial: %w", cause)
+ })
+ if !errors.Is(err, cause) {
+ t.Fatalf("cause %v: err = %v, want the cause back", cause, err)
+ }
+ if errors.Is(err, errHoldExpired) || errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("cause %v: err = %v, an unrelated error is not a hold timeout", cause, err)
+ }
+ }
+}
+
+// The deadline errors a real dial returns when its context ends it all
+// count as the deadline talking.
+func TestCutByDeadlineClassifiesDialErrors(t *testing.T) {
+ timeoutOp := &net.OpError{Op: "dial", Net: "unix", Err: os.ErrDeadlineExceeded}
+ for name, c := range map[string]struct {
+ cut bool
+ err error
+ want bool
+ }{
+ "context deadline": {true, context.DeadlineExceeded, true},
+ "wrapped canceled": {true, &net.OpError{Op: "dial", Err: context.Canceled}, true},
+ "os deadline": {true, timeoutOp, true},
+ "not cut": {false, context.DeadlineExceeded, false},
+ "peer mismatch": {true, unixdial.ErrPeerMismatch, false},
+ "wrapped control refusal": {true, fmt.Errorf("x: %w", unixdial.ErrControlEndpoint), false},
+ } {
+ if got := cutByDeadline(c.cut, c.err); got != c.want {
+ t.Errorf("%s: cutByDeadline = %v, want %v", name, got, c.want)
+ }
+ }
+}
+
+func TestRetryLocalDialNonRetryableFailsAtOnce(t *testing.T) {
+ var calls int
+ boom := errors.New("boom")
+ _, err := retryLocalDial(context.Background(), time.Now().Add(5*time.Second),
+ func(context.Context) (net.Conn, error) { calls++; return nil, boom })
+ if !errors.Is(err, boom) || calls != 1 {
+ t.Fatalf("err = %v, calls = %d, want boom after exactly one attempt", err, calls)
+ }
+}
+
+// holdEdge is an Edge over one ready service route at addr, with the dial
+// hold d and nothing else changed.
+func holdEdge(t *testing.T, addr string, hold localHold) (*Edge, *httptest.Server) {
+ t.Helper()
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: addr}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return e, srv
+}
+
+func holdGet(t *testing.T, url string) (int, string) {
+ t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, url, nil)
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("GET: %v", err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(b)
+}
+
+// listenLater starts handler on addr after delay, reusing a port deadAddr
+// reserved. The server is closed with the test.
+func listenLater(t *testing.T, addr string, delay time.Duration, h http.Handler) {
+ t.Helper()
+ var (
+ mu sync.Mutex
+ ts *httptest.Server
+ )
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ time.Sleep(delay)
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ t.Errorf("listen %s: %v", addr, err)
+ return
+ }
+ s := httptest.NewUnstartedServer(h)
+ s.Listener.Close()
+ s.Listener = ln
+ s.Start()
+ mu.Lock()
+ ts = s
+ mu.Unlock()
+ }()
+ t.Cleanup(func() {
+ <-done
+ mu.Lock()
+ defer mu.Unlock()
+ if ts != nil {
+ ts.Close()
+ }
+ })
+}
+
+func TestLoopbackAddrRouteHolds(t *testing.T) {
+ for _, host := range []string{"127.0.0.1", "localhost"} {
+ t.Run(host, func(t *testing.T) {
+ a := deadAddr(t)
+ listenAddr := a
+ if host == "localhost" {
+ _, port, _ := net.SplitHostPort(a)
+ a = net.JoinHostPort("localhost", port)
+ }
+ listenLater(t, listenAddr, 300*time.Millisecond, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "back")
+ }))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+ start := time.Now()
+ code, body := holdGet(t, srv.URL)
+ if code != http.StatusOK || body != "back" {
+ t.Fatalf("got %d %q after %v, want 200 back", code, body, time.Since(start))
+ }
+ })
+ }
+}
+
+func TestLoopbackAddrRouteRefusedPastHold(t *testing.T) {
+ e, srv := holdEdge(t, deadAddr(t), localHold{dial: 200 * time.Millisecond, probe: probeTimeout})
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el < 200*time.Millisecond {
+ t.Fatalf("502 after %v, before the hold ended", el)
+ }
+ recs := sink.snap()
+ if len(recs) != 1 || recs[0].Cause != apperr.CauseRefused {
+ t.Fatalf("records = %+v, want one with cause %q", recs, apperr.CauseRefused)
+ }
+}
+
+func TestNonLoopbackAddrRouteFailsAtOnce(t *testing.T) {
+ var calls atomic.Int32
+ hold := localHold{dial: 2 * time.Second, probe: probeTimeout,
+ dialer: func(context.Context, string, string) (net.Conn, error) {
+ calls.Add(1)
+ return nil, refusedErr()
+ }}
+ _, srv := holdEdge(t, "10.0.0.5:80", hold)
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el > 500*time.Millisecond {
+ t.Fatalf("502 after %v, want within 500ms (a hold would take seconds)", el)
+ }
+ if n := calls.Load(); n != 1 {
+ t.Fatalf("dialer calls = %d, want exactly 1", n)
+ }
+}
+
+func TestHeldDialClientCancelReturnsAtOnce(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), localHold{dial: 2 * time.Second, probe: probeTimeout})
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
+ req.Host = "shop.example.com"
+ start := time.Now()
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ resp.Body.Close()
+ }
+ if el := time.Since(start); el > 300*time.Millisecond {
+ t.Fatalf("Do returned after %v, want within 300ms of the client giving up", el)
+ }
+}
+
+func TestHeldDialPOSTBodyArrives(t *testing.T) {
+ a := deadAddr(t)
+ listenLater(t, a, 300*time.Millisecond, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Read it all before the first write: HTTP/1 does not let a handler
+ // stream a response while the request body is still arriving.
+ b, _ := io.ReadAll(r.Body)
+ w.Write(b)
+ }))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+ body := strings.Repeat("0123456789abcdef", 4096) // 64 KiB
+ req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(body))
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("POST: %v", err)
+ }
+ defer resp.Body.Close()
+ got, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK || string(got) != body {
+ t.Fatalf("status %d, echoed %d bytes, want 200 and %d identical bytes", resp.StatusCode, len(got), len(body))
+ }
+}
+
+func TestHeldDialWebSocketUpgrade(t *testing.T) {
+ a := deadAddr(t)
+ listenLater(t, a, 300*time.Millisecond, upgradeEchoHandler("ws"))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+
+ c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
+ if err != nil {
+ t.Fatalf("dial edge: %v", err)
+ }
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(5 * time.Second))
+ fmt.Fprint(c, "GET /ws HTTP/1.1\r\nHost: shop.example.com\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n")
+ buf := make([]byte, 0, 512)
+ tmp := make([]byte, 256)
+ for !strings.Contains(string(buf), "\r\n\r\n") {
+ n, err := c.Read(tmp)
+ if err != nil {
+ t.Fatalf("read handshake: %v (got %q)", err, buf)
+ }
+ buf = append(buf, tmp[:n]...)
+ }
+ if !strings.HasPrefix(string(buf), "HTTP/1.1 101") {
+ t.Fatalf("handshake = %q, want 101", buf)
+ }
+ fmt.Fprint(c, "hello\n")
+ rest := string(buf[strings.Index(string(buf), "\r\n\r\n")+4:])
+ for !strings.Contains(rest, "\n") {
+ n, err := c.Read(tmp)
+ if err != nil {
+ t.Fatalf("read echo: %v (got %q)", err, rest)
+ }
+ rest += string(tmp[:n])
+ }
+ if rest != "ws:hello\n" {
+ t.Fatalf("echo = %q, want %q", rest, "ws:hello\n")
+ }
+}
+
+func TestHeldDialsReleaseAfterHold(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), localHold{dial: 300 * time.Millisecond, probe: probeTimeout})
+ http.DefaultClient.CloseIdleConnections()
+ base := runtime.NumGoroutine()
+
+ var wg sync.WaitGroup
+ codes := make(chan int, 50)
+ start := time.Now()
+ for i := 0; i < 50; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ codes <- -1
+ return
+ }
+ resp.Body.Close()
+ codes <- resp.StatusCode
+ }()
+ }
+ wg.Wait()
+ close(codes)
+ if el := time.Since(start); el > time.Second {
+ t.Fatalf("50 held GETs took %v, want within 1s", el)
+ }
+ for c := range codes {
+ if c != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", c)
+ }
+ }
+ http.DefaultClient.CloseIdleConnections()
+ deadline := time.Now().Add(2 * time.Second)
+ for runtime.NumGoroutine() > base+10 {
+ if time.Now().After(deadline) {
+ t.Fatalf("goroutines = %d, baseline %d: held dials did not release", runtime.NumGoroutine(), base)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+func TestLocalHoldOffKeepsInstant502(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), noHold())
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el > 500*time.Millisecond {
+ t.Fatalf("502 after %v, want within 500ms (a hold would take seconds)", el)
+ }
+}
diff --git a/internal/edge/localhold_witness_test.go b/internal/edge/localhold_witness_test.go
new file mode 100644
index 000000000..3c941e96e
--- /dev/null
+++ b/internal/edge/localhold_witness_test.go
@@ -0,0 +1,387 @@
+package edge
+
+import (
+ "context"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// witnessStats is what one restart run measured. p50, p99 and max are the
+// ADDED wait: each request's latency minus the baseline p50 (the latency of
+// requests that finished before the restart began).
+type witnessStats struct {
+ requests, ok, s502, s503, other int
+ p50, p99, max time.Duration
+ // gap is how long the upstream refused, from the start of its Shutdown
+ // until the new server was listening.
+ gap time.Duration
+ // held counts requests whose added wait exceeded witnessHeldOver.
+ held int
+ // resets and refused split s502 by the cause the edge filed for it
+ // (apperr.CauseReset, apperr.CauseRefused). A reset is the boundary case
+ // the dial hold cannot cover: the kernel had already accepted the
+ // connection into the old upstream's backlog when its Shutdown closed the
+ // listener, so the dial succeeded and the connection was then reset.
+ resets, refused int
+}
+
+const (
+ witnessHost = "shop.example.com"
+ witnessWorkers = 8
+ // witnessPace is each worker's pause between requests. It keeps the load
+ // steady rather than a spin; it is not a synchronization sleep.
+ witnessPace = 5 * time.Millisecond
+ witnessBaseline = time.Second
+ witnessGap = 1500 * time.Millisecond
+ witnessAfter = time.Second
+ // witnessHeldOver is the added wait past which a request counts as held.
+ witnessHeldOver = 100 * time.Millisecond
+ // witnessMaxResets bounds the boundary resets a positive run may see: at
+ // most one in-flight request per worker can sit in the old upstream's
+ // backlog when its listener closes.
+ witnessMaxResets = witnessWorkers
+)
+
+type witnessSample struct {
+ start, end time.Time
+ status int // 0 = transport error
+}
+
+// witnessUpstream answers / and /healthz with 200.
+func witnessUpstream() *http.Server {
+ mux := http.NewServeMux()
+ ok := func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") }
+ mux.HandleFunc("/", ok)
+ mux.HandleFunc("/healthz", ok)
+ return &http.Server{Handler: mux}
+}
+
+// runRestartWitness drives eight keep-alive workers through e (served by an
+// httptest server on 127.0.0.1) at the host witnessHost. listen binds the
+// upstream's fixed address and is called once per server: first to start it,
+// then again after the gap to bring the restarted one up. The runner does
+// baseline load, Shutdown with a 5 s drain, a gap in which the address
+// refuses, the restart, and load for another second.
+func runRestartWitness(t *testing.T, e *Edge, listen func() (net.Listener, error)) witnessStats {
+ t.Helper()
+
+ // Proxy failures are filed through the edge's own error sink, which is
+ // how the witness tells a boundary reset from a refused dial.
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ srv := httptest.NewServer(e)
+ defer srv.Close()
+
+ up1 := witnessUpstream()
+ l1, err := listen()
+ if err != nil {
+ t.Fatalf("listen (first): %v", err)
+ }
+ go up1.Serve(l1)
+
+ client := &http.Client{
+ Timeout: 15 * time.Second,
+ Transport: &http.Transport{MaxIdleConnsPerHost: witnessWorkers},
+ }
+ defer client.CloseIdleConnections()
+
+ stop := make(chan struct{})
+ var (
+ mu sync.Mutex
+ samples []witnessSample
+ wg sync.WaitGroup
+ )
+ for i := 0; i < witnessWorkers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ var mine []witnessSample
+ defer func() {
+ mu.Lock()
+ samples = append(samples, mine...)
+ mu.Unlock()
+ }()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ req, _ := http.NewRequest(http.MethodGet, srv.URL+"/", nil)
+ req.Host = witnessHost
+ s := witnessSample{start: time.Now()}
+ resp, err := client.Do(req)
+ if err == nil {
+ _, err = io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ if err == nil {
+ s.status = resp.StatusCode
+ }
+ }
+ s.end = time.Now()
+ mine = append(mine, s)
+ select {
+ case <-stop:
+ return
+ case <-time.After(witnessPace):
+ }
+ }
+ }()
+ }
+
+ time.Sleep(witnessBaseline)
+
+ // The restart, as the instance drain does it.
+ shutStart := time.Now()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ if err := up1.Shutdown(ctx); err != nil {
+ t.Errorf("upstream Shutdown: %v", err)
+ }
+ cancel()
+ time.Sleep(witnessGap)
+
+ up2 := witnessUpstream()
+ l2, err := listen()
+ if err != nil {
+ close(stop)
+ wg.Wait()
+ t.Fatalf("listen (restart): %v", err)
+ }
+ restarted := time.Now()
+ go up2.Serve(l2)
+ defer up2.Close()
+
+ time.Sleep(witnessAfter)
+ close(stop)
+ wg.Wait()
+
+ // Baseline: requests that finished before the restart began.
+ var base []time.Duration
+ for _, s := range samples {
+ if s.end.Before(shutStart) && s.status == http.StatusOK {
+ base = append(base, s.end.Sub(s.start))
+ }
+ }
+ if len(base) == 0 {
+ t.Fatalf("no baseline requests completed in %v", witnessBaseline)
+ }
+ sortDurations(base)
+ baseP50 := percentile(base, 0.50)
+
+ st := witnessStats{gap: restarted.Sub(shutStart)}
+ for _, rec := range sink.snap() {
+ if rec.Status != http.StatusBadGateway {
+ continue
+ }
+ switch rec.Cause {
+ case apperr.CauseReset:
+ st.resets++
+ case apperr.CauseRefused:
+ st.refused++
+ }
+ }
+ var added []time.Duration
+ for _, s := range samples {
+ st.requests++
+ switch s.status {
+ case http.StatusOK:
+ st.ok++
+ case http.StatusBadGateway:
+ st.s502++
+ case http.StatusServiceUnavailable:
+ st.s503++
+ default:
+ st.other++
+ }
+ w := s.end.Sub(s.start) - baseP50
+ if w < 0 {
+ w = 0
+ }
+ if w > witnessHeldOver {
+ st.held++
+ }
+ added = append(added, w)
+ }
+ sortDurations(added)
+ st.p50 = percentile(added, 0.50)
+ st.p99 = percentile(added, 0.99)
+ st.max = added[len(added)-1]
+ return st
+}
+
+func sortDurations(d []time.Duration) {
+ sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
+}
+
+// percentile reads the q quantile from an ascending slice.
+func percentile(d []time.Duration, q float64) time.Duration {
+ if len(d) == 0 {
+ return 0
+ }
+ return d[int(float64(len(d)-1)*q)]
+}
+
+func logWitness(t *testing.T, route string, st witnessStats) {
+ t.Helper()
+ t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v held=%d resets=%d",
+ route, st.gap.Round(time.Millisecond), st.requests, st.ok, st.s502, st.s503, st.other, st.p50, st.p99, st.max, st.held, st.resets)
+}
+
+// checkWitness is the pass rule for a held route: no failures, a max added
+// wait under gap+extra, and at least gap/2 of it, so a run in which nothing
+// was actually held (the restart missed the load) cannot pass.
+//
+// One failure is tolerated, and only in a bounded number: a 502 the edge
+// filed as a reset. It is a request whose connection the old upstream's
+// kernel backlog had accepted when Shutdown closed the listener, so the dial
+// held nothing back and the connection was reset. At most one per worker can
+// be in that state. Every other 502 (refused, timeout, proxy) still fails.
+func checkWitness(t *testing.T, st witnessStats, extra time.Duration) {
+ t.Helper()
+ if st.s503 != 0 || st.other != 0 || st.s502-st.resets != 0 {
+ t.Errorf("failures during restart: 502=%d (of which resets=%d) 503=%d other=%d, want none but boundary resets", st.s502, st.resets, st.s503, st.other)
+ }
+ if st.resets > witnessMaxResets {
+ t.Errorf("boundary resets = %d, want at most %d (one per worker)", st.resets, witnessMaxResets)
+ }
+ if st.max >= st.gap+extra {
+ t.Errorf("max added wait %v, want under gap+%v = %v", st.max, extra, st.gap+extra)
+ }
+ if st.max < st.gap/2 {
+ t.Errorf("max added wait %v, want at least gap/2 = %v: no request was held through the restart", st.max, st.gap/2)
+ }
+}
+
+// witnessEdge builds the witness's Edge with the rate limiter off on that
+// Edge alone, so the eight workers measure the hold and nothing else.
+func witnessEdge(t *testing.T, reg *registry.Registry, hold localHold) *Edge {
+ t.Helper()
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ e.rateMode = RateOff
+ t.Cleanup(e.probers.Stop)
+ return e
+}
+
+// reserveLoopbackAddr picks a free 127.0.0.1 port and releases it, so the
+// route can name an address the upstream binds later.
+func reserveLoopbackAddr(t *testing.T) string {
+ t.Helper()
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("reserve port: %v", err)
+ }
+ addr := l.Addr().String()
+ l.Close()
+ return addr
+}
+
+// listenTCPFixed binds addr, retrying briefly in case the kernel has not yet
+// released it.
+func listenTCPFixed(addr string) func() (net.Listener, error) {
+ return func() (net.Listener, error) {
+ var lastErr error
+ for i := 0; i < 50; i++ {
+ l, err := net.Listen("tcp", addr)
+ if err == nil {
+ return l, nil
+ }
+ lastErr = err
+ time.Sleep(20 * time.Millisecond)
+ }
+ return nil, lastErr
+ }
+}
+
+func witnessTCPEdge(t *testing.T, hold localHold) (*Edge, func() (net.Listener, error)) {
+ t.Helper()
+ addr := reserveLoopbackAddr(t)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addr: addr, Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ return witnessEdge(t, reg, hold), listenTCPFixed(addr)
+}
+
+// TestLocalUpstreamRestartWitness restarts a local upstream under load and
+// counts what the edge did with the requests that arrived while it refused.
+// Its log lines are the evidence quoted for the roll blip.
+func TestLocalUpstreamRestartWitness(t *testing.T) {
+ if testing.Short() {
+ t.Skip("restart witness takes about 5 s")
+ }
+
+ t.Run("tcp", func(t *testing.T) {
+ t.Parallel()
+ e, listen := witnessTCPEdge(t, defaultLocalHold())
+ st := runRestartWitness(t, e, listen)
+ logWitness(t, "tcp", st)
+ checkWitness(t, st, time.Second)
+ })
+
+ t.Run("unix", func(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("unix sockets")
+ }
+ sock := filepath.Join(shortSockDir(t), "app.sock")
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "instance", Socket: sock, Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e := witnessEdge(t, reg, defaultLocalHold())
+ st := runRestartWitness(t, e, func() (net.Listener, error) { return net.Listen("unix", sock) })
+ logWitness(t, "unix", st)
+ checkWitness(t, st, time.Second)
+ })
+
+ // A probed route: the probe ejects the upstream when it goes, the
+ // requests wait for its readmission, and readmission takes up to R.
+ t.Run("probed", func(t *testing.T) {
+ t.Parallel()
+ addr := reserveLoopbackAddr(t)
+ h := provision.Health{Path: "/healthz", IntervalMS: 100, FailAfter: 1, RiseAfter: 2}
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addrs: addr, Health: healthJSON(t, h), Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ hold := defaultLocalHold()
+ e := witnessEdge(t, reg, hold)
+ r := readmitBound(1, 100*time.Millisecond, 2, hold.probe)
+ if got, ok := e.probers.Hold(witnessHost); !ok || got != min(hold.dial+r, hold.cap) {
+ t.Fatalf("Hold = (%v, %v), want (%v, true)", got, ok, min(hold.dial+r, hold.cap))
+ }
+ st := runRestartWitness(t, e, listenTCPFixed(addr))
+ logWitness(t, "probed", st)
+ checkWitness(t, st, r)
+ })
+
+ // Negative control: with the dial hold off the same restart must 502,
+ // or the witness above could not have failed.
+ t.Run("tcp-hold-off", func(t *testing.T) {
+ t.Parallel()
+ e, listen := witnessTCPEdge(t, noHold())
+ st := runRestartWitness(t, e, listen)
+ logWitness(t, "tcp-hold-off", st)
+ if st.s502 == 0 {
+ t.Errorf("502 count = 0 with the hold off, want > 0 (the witness cannot fail)")
+ }
+ if st.refused*2 <= st.s502 {
+ t.Errorf("refused 502s = %d of %d, want most of them: the control must fail on the refused dial the hold removes", st.refused, st.s502)
+ }
+ })
+}
diff --git a/internal/edge/prober.go b/internal/edge/prober.go
index 5ebc6d21b..030e65ab3 100644
--- a/internal/edge/prober.go
+++ b/internal/edge/prober.go
@@ -121,13 +121,25 @@ type proberSet struct {
mu sync.Mutex
hosts map[string]*hostProber
client *http.Client
+ // hold is the Edge's local-upstream hold (localhold.go), which Sync
+ // hands to every hostProber so each can work out its own D10b hold.
+ hold localHold
}
-func newProberSet() *proberSet {
+// newProberSet builds the set with hold.probe as the probe timeout (T in
+// the readmission formula, spec §3), and hold.dialer, when set, as the
+// probes' dialer, so a test's instrumented dialer sees the probes too. A
+// non-positive probe falls back to probeTimeout: an unbounded probe would
+// stall every tick behind one black-holed upstream.
+func newProberSet(hold localHold) *proberSet {
+ if hold.probe <= 0 {
+ hold.probe = probeTimeout
+ }
return &proberSet{
hosts: make(map[string]*hostProber),
+ hold: hold,
client: &http.Client{
- Timeout: probeTimeout,
+ Timeout: hold.probe,
// A redirect is not health: an upstream answering 302 has not
// served the configured status, and following the hop would
// probe something the operator never named.
@@ -140,7 +152,8 @@ func newProberSet() *proberSet {
// bounded tightly, since every probed upstream holds one.
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 90 * time.Second,
- ResponseHeaderTimeout: probeTimeout,
+ ResponseHeaderTimeout: hold.probe,
+ DialContext: hold.dialer, // nil: the default dialer
},
},
}
@@ -170,6 +183,12 @@ type hostProber struct {
ctx context.Context
done chan struct{}
+ // local and hold are D10b's (spec §3), fixed here and never changed:
+ // local when any addr is this box's loopback, and hold how long a
+ // request may wait for the live set to readmit one.
+ local bool
+ hold time.Duration
+
mu sync.Mutex
order []string // addrs in spec order — Live/State iterate this, not the map
state map[string]*upstreamState
@@ -185,7 +204,7 @@ type upstreamState struct {
lastError string
}
-func newHostProber(spec probeSpec, client *http.Client) *hostProber {
+func newHostProber(spec probeSpec, client *http.Client, hold localHold) *hostProber {
h := spec.Health
hp := &hostProber{
spec: spec,
@@ -231,10 +250,34 @@ func newHostProber(spec probeSpec, client *http.Client) *hostProber {
// Rule 1: everything starts live.
hp.state[addr] = &upstreamState{up: true, since: now}
}
+ hp.hold, hp.local = readmitHold(hp.order, hp.interval, hp.riseAt, hold)
hp.ctx, hp.cancel = context.WithCancel(context.Background())
return hp
}
+// readmitHold is D10b's hold for a probed host (spec §3), from the clamped
+// cadence the prober actually runs. One probe of an addr starts at most
+//
+// G = max(I, T) + (N-1)*T
+//
+// after the one before it (I the interval, T the probe timeout, N the
+// addrs), so an upstream that is back rejoins within R = r*G + T (r the
+// rise count). The hold is min(dial + R, cap). ok is false when no addr is
+// local, or when the dial hold or cap is off: such a host answers at once.
+func readmitHold(order []string, interval time.Duration, rise int, hold localHold) (time.Duration, bool) {
+ if hold.dial <= 0 || hold.cap <= 0 || !slices.ContainsFunc(order, isLocalUpstream) {
+ return 0, false
+ }
+ t := hold.probe
+ g := max(interval, t) + time.Duration(len(order)-1)*t
+ r := time.Duration(rise)
+ // Saturate rather than overflow: a hand-written rise_after can be huge.
+ if g > 0 && r > hold.cap/g {
+ return hold.cap, true
+ }
+ return min(hold.dial+r*g+t, hold.cap), true
+}
+
// stop cancels the goroutine's context — aborting any in-flight probe at once,
// so this does not wait out the 2s client timeout — and blocks until it has
// exited.
@@ -289,7 +332,7 @@ func (p *proberSet) Sync(want map[string]probeSpec) {
// that removed the outgoing prober, so a concurrent Live never
// observes a replaced host as having no upstreams — a gap there
// would be a 503 for a route that is perfectly healthy.
- hp := newHostProber(w, p.client)
+ hp := newHostProber(w, p.client, p.hold)
p.hosts[host] = hp
started = append(started, hp)
}
@@ -329,6 +372,19 @@ func (p *proberSet) Live(host string) []string {
return out
}
+// Hold reports host's D10b hold: how long multiProxy may wait for the live
+// set to readmit an upstream, and whether the host has a local upstream at
+// all. An unknown host, or one with no local addr, is (0, false).
+func (p *proberSet) Hold(host string) (time.Duration, bool) {
+ p.mu.Lock()
+ hp := p.hosts[host]
+ p.mu.Unlock()
+ if hp == nil || !hp.local {
+ return 0, false
+ }
+ return hp.hold, true
+}
+
// Eject drops addr from host's live set immediately — the in-request
// dial-failure fast path, so a box that died between probe ticks costs one
// retry rather than up to fail_after × interval of 502s. Fails is set to
diff --git a/internal/edge/prober_test.go b/internal/edge/prober_test.go
index 381e99e67..2876466f8 100644
--- a/internal/edge/prober_test.go
+++ b/internal/edge/prober_test.go
@@ -71,7 +71,7 @@ func TestProberFailsAwayAndBack(t *testing.T) {
}.WithDefaults(),
}
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
// Optimism: a fresh Sync must not 503 a healthy fleet while the first
// probes run, so both upstreams are live before any probe has landed.
@@ -132,7 +132,7 @@ func TestProberSendsConfiguredHostHeader(t *testing.T) {
// HostHeader set: it wins over the route host, so a shared upstream that
// vhosts on Host can be probed on the name it actually answers to.
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
Addrs: []string{ts.Listener.Addr().String()},
@@ -155,7 +155,7 @@ func TestProberSendsConfiguredHostHeader(t *testing.T) {
// HostHeader unset: the route host is substituted — WithDefaults
// deliberately leaves HostHeader empty so the prober can see "unset".
- p2 := newProberSet()
+ p2 := newProberSet(defaultLocalHold())
defer p2.Stop()
p2.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -175,7 +175,7 @@ func TestSyncStopsVanishedHosts(t *testing.T) {
backend, ok, hits := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
spec := probeSpec{
Host: "m.example.com",
@@ -249,7 +249,7 @@ func TestSyncReplacesChangedSpecWithoutAGap(t *testing.T) {
}
}
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{host: spec(aAddr, bAddr)})
waitFor(t, 2*time.Second, "the outgoing addr set to be probed", func() bool {
@@ -321,7 +321,7 @@ func TestSyncNormalizesHealthBeforeComparing(t *testing.T) {
backend, ok, _ := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
proberFor := func() *hostProber {
p.mu.Lock()
@@ -367,7 +367,7 @@ func TestEjectIsImmediateAndProbeRejoins(t *testing.T) {
t.Cleanup(b.Close)
aAddr, bAddr := a.Listener.Addr().String(), b.Listener.Addr().String()
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -438,7 +438,7 @@ func TestProberClampsNonPositiveInterval(t *testing.T) {
Host: "m.example.com",
Addrs: []string{"10.0.0.1:80"},
Health: provision.Health{IntervalMS: ms},
- }, nil)
+ }, nil, defaultLocalHold())
if hp.interval != fallbackProbeInterval {
t.Errorf("interval_ms %d clamped to %v, want the %v fallback", ms, hp.interval, fallbackProbeInterval)
}
@@ -449,7 +449,7 @@ func TestProberClampsNonPositiveInterval(t *testing.T) {
// panic.
backend, ok, hits := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -482,7 +482,7 @@ func TestProberClampsNonPositiveFailAndRiseCounts(t *testing.T) {
Host: "m.example.com",
Addrs: []string{addr},
Health: provision.Health{Path: "/", Status: 200, IntervalMS: 20, FailAfter: -1, RiseAfter: 0},
- }, nil)
+ }, nil, defaultLocalHold())
if hp.failAt != fallbackFailAfter || hp.riseAt != fallbackRiseAfter {
t.Fatalf("clamped counts = fail %d rise %d, want %d/%d", hp.failAt, hp.riseAt, fallbackFailAfter, fallbackRiseAfter)
}
@@ -528,7 +528,7 @@ func TestProberStateReturnsCopies(t *testing.T) {
backend, ok, _ := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
addr := backend.Listener.Addr().String()
p.Sync(map[string]probeSpec{"m.example.com": {
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go
index 8bed6c30b..20c3ab63d 100644
--- a/internal/host/applessroute_test.go
+++ b/internal/host/applessroute_test.go
@@ -81,14 +81,21 @@ func captureShipLog(t *testing.T) *bytes.Buffer {
// TestErrshipAppLessRouteWritesNothing is the dev-bucket regression end to
// end. The route is the shape found on leo-climbing: an instance row with
-// an account, no app, and a TCP upstream nobody listens on. Every request
-// is a refused 502 that the edge files under (bab, ""). The errors shipper
+// an account, no app, and a TCP upstream that fails every request. Every
+// request is a 502 that the edge files under (bab, ""). The errors shipper
// must write nothing for it (it once wrote apps/bab//errors/...), prune
// nothing, keep shipping the app beside it, and say so once.
func TestErrshipAppLessRouteWritesNothing(t *testing.T) {
- dead := httptest.NewServer(http.NotFoundHandler())
+ // An upstream that hangs up on every request: still a 502 the edge files,
+ // but not a refused dial, which a loopback route now holds for 13s
+ // (edge.localDialHold) waiting for a restarting process to come back.
+ dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if c, _, err := w.(http.Hijacker).Hijack(); err == nil {
+ c.Close()
+ }
+ }))
+ t.Cleanup(dead.Close)
deadAddr := dead.Listener.Addr().String()
- dead.Close() // nothing listens here now: every dial is refused
reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
if err != nil {
@@ -120,7 +127,7 @@ func TestErrshipAppLessRouteWritesNothing(t *testing.T) {
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadGateway {
- t.Fatalf("%s answered %d, want a refused 502", host, resp.StatusCode)
+ t.Fatalf("%s answered %d, want a 502", host, resp.StatusCode)
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 69eb69fd4..b156ee056 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -22,3 +22,4 @@ plan14-root-reads-retire-join-units-on-adopt.tsv 9e0c4a0c3c5299f68a046e989f49f35
plan14-root-reads-team-scoped-credentials.tsv b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b
plan14-root-reads-rootfs-apps-3-release.tsv 2cced1b359b64855bacc94c64e0370e6b78cfe2c4947d6d4944915b3a05c6a7c
plan14-root-reads-rootfs-overlap-demand.tsv 2cced1b359b64855bacc94c64e0370e6b78cfe2c4947d6d4944915b3a05c6a7c
+plan14-root-reads-edge-roll-blip.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f
diff --git a/internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv b/internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv
new file mode 100644
index 000000000..d08ddf8f6
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-edge-roll-blip.tsv
@@ -0,0 +1,7 @@
+# Census overlay edge-roll-blip, written by census-propose (#369). census-ruling-edge-roll-blip, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-edge-roll-blip.md.
+# 2 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy f199794b321215a252cbb56c3ca1d34f5ce21d1c0928cffcaa35623e6761dc07 internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites registry:Account@20309,registry:Alias@18478,registry:Alias@18565,registry:Alias@18801,registry:FleetBox@5526,registry:Health@7671,registry:Health@7797,registry:Host@13212,registry:Host@15119,registry:Host@15427,registry:Host@15454,registry:Host@16255,registry:Host@16521,registry:Host@18604,registry:Host@6080,registry:Host@8280,registry:Host@8375,registry:Host@8663,registry:Host@8689,registry:Host@8741,registry:Kind@11548,registry:Kind@11570,registry:Kind@8837,registry:Kind@8897,registry:Name@20299,registry:Prefix@16496,registry:Region@2252,registry:Socket@15435,registry:Socket@5633,registry:Socket@6144,registry:Status@1835,registry:Target@16508,registry:Tunnel@4574,registry:Tunnel@4630,registry:Version@11529,registry:Version@11631,whole:Fleet@20249,whole:Fleet@20278,whole:Route@130,whole:Route@15487,whole:Route@15494,whole:Route@15590,whole:Route@17399,whole:Route@4692,whole:Route@5590,whole:Route@6200,whole:Route@648,whole:Route@8814,whole:Route@8887,whole:Route@8947,whole:RouteAlias@18449,whole:RoutePath@16233 d8c48c887841a643a6d9db6d58c8b7213c8024e8b2f6c6c25f355db03413a9f8
+@legacy 528f68a4cbb7495c8fd1f8466db17b41c33a36bfcaaff49ae8ea8306d88004fa internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 bd0fe0c5d01e83e4de5bb755d791cf9e53168be3083424df147c879004c784bf
+internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites registry:Account@20309,registry:Alias@18478,registry:Alias@18565,registry:Alias@18801,registry:FleetBox@5526,registry:Health@7671,registry:Health@7797,registry:Host@13212,registry:Host@15119,registry:Host@15427,registry:Host@15454,registry:Host@16255,registry:Host@16521,registry:Host@18604,registry:Host@6080,registry:Host@8280,registry:Host@8375,registry:Host@8663,registry:Host@8689,registry:Host@8741,registry:Kind@11548,registry:Kind@11570,registry:Kind@8837,registry:Kind@8897,registry:Name@20299,registry:Prefix@16496,registry:Region@2252,registry:Socket@15435,registry:Socket@5633,registry:Socket@6144,registry:Status@1835,registry:Target@16508,registry:Tunnel@4574,registry:Tunnel@4630,registry:Version@11529,registry:Version@11631,whole:Fleet@20249,whole:Fleet@20278,whole:Route@130,whole:Route@15487,whole:Route@15494,whole:Route@15590,whole:Route@17399,whole:Route@4692,whole:Route@5590,whole:Route@6200,whole:Route@648,whole:Route@8814,whole:Route@8887,whole:Route@8947,whole:RouteAlias@18449,whole:RoutePath@16233 d8c48c887841a643a6d9db6d58c8b7213c8024e8b2f6c6c25f355db03413a9f8
+internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites;rev3=census-ruling-edge-roll-blip;basis=the :80/:443 (and dev) listeners are bound on the calling goroutine with net.Listen via listen()/listenAddr (same empty-address defaults as ListenAndServe) before the serve goroutines, which now call Serve/ServeTLS on them, and one log line names the bound addresses; no read added, same 5 sites data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 bd0fe0c5d01e83e4de5bb755d791cf9e53168be3083424df147c879004c784bf
+@coverage internal/edge 2704220c7fb97c7f3c80af6324edff5981943a0a0885c8f56b601b047f7db979