| index 1d40a6b70..0247109fd 100644 |
| --- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md |
| +++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md |
| @@ -1,6 +1,6 @@ |
| # Tunnel WebSockets: upgraded connections through the fleet tunnel |
| |
| -Status: DRAFT rev 2, 2026-10-30. Discussion: amadan carlos/platform #471. |
| +Status: DRAFT rev 3, 2026-10-30. Discussion: amadan carlos/platform #471. |
| Branch `design-tunnel-websockets-471`, cut from main `65fd8060` (fleet |
| public routes, #457 Phase 1a). Every repo file:line below is on that |
| commit. Library lines are `golang.org/x/net v0.60.0` (`go.mod:28`) and the |
| @@ -21,15 +21,30 @@ Revisions: |
| (R1-4, §4.8, §8.1.6, §8.2 case 13); the `bufferedConn` TLS finding |
| withdrawn (R1-5, §10). The controller's calls on rev 1's open |
| questions are recorded in §11. |
| - |
| -Review history: Astra R1 NOT READY (1 P1, 4 P2). This is the text for |
| -round 2 of 3. Round budget per AGENTS.md "Stopping rules": stop at the |
| -first round with no P1; a fourth round needs Paul. |
| +- Rev 3: Astra round 2 (`CODEX-FINDINGS-tunnel-websockets-R2.md`, NOT |
| + READY, 1 P1 and 1 P2; R1-2 to R1-5 resolved, R1-1 partly). Changes |
| + are marked **(R2-n)**: one reload mutex held from the registry read |
| + through the map swap and the upgrade sweep, inside `Reload` itself so |
| + every caller takes it, with the lock order stated and the watcher's |
| + fingerprint recorded only after its own serialised Reload has swapped |
| + and swept (R2-1, §4.6.1, §4.6.3); a `ModifyResponse` failure releases |
| + through the body, and the backstop is witnessed on paths that really |
| + leave the body open (R2-2, §3.5, §4.6.2, §8.2 case 12). Also the |
| + author's sweep of every path that publishes or reads the routing map |
| + relative to the upgrade registry (§4.6.3). |
| + |
| +Review history: Astra R1 NOT READY (1 P1, 4 P2); R2 NOT READY (1 P1, |
| +1 P2). R1-1 and R2-1 are one fault family (an open socket cannot outlive |
| +its admitting tenancy), so stopping rule 2 has triggered; the |
| +controller's ruling takes its third option: state the invariant, enforce |
| +it in one place (the reload mutex), and check it with a deterministic |
| +interleaving witness and a guard test (§8.2 cases 18 and 19). This is the |
| +text for round 3 of 3, the last. |
| |
| ## 0. Status |
| |
| -Rev 2. Astra R1 NOT READY; every finding taken. No open questions: the |
| -controller ruled on all five (§11). |
| +Rev 3. Astra R1 and R2 NOT READY; every finding taken. No open |
| +questions: the controller ruled on all five (§11) and on both rounds. |
| |
| ## 1. Intent |
| |
| @@ -204,12 +219,14 @@ From 1a's Task 5 (fleet public routes spec §4.8): |
| whole close mechanism: cancel the context, and the proxy closes |
| `backConn`. |
| - That close is installed only once the proxy has hijacked the client. |
| - On a transport error the proxy returns at once (`reverseproxy.go:579-585`); |
| - on a 101 it drops the response without closing its body when |
| - `ModifyResponse` fails (`:590-592`), when the upgrade types differ |
| - (`:842-845`), when the body is not writable (`:847-851`) or when the |
| - writer cannot hijack (`:854-857`). An ordinary response's body is |
| - closed by a defer (`:620`). What does always happen: `net/http` cancels |
| + On a transport error the proxy returns at once (`reverseproxy.go:579-585`). |
| + A failing `ModifyResponse` closes the body before calling the error |
| + handler (`modifyResponse`, `:395-397`), on a 101 (`:590`) as on any |
| + response. On a 101 the proxy drops the response **without** closing |
| + its body when the upgrade types differ (`:842-845`), when the body is |
| + not writable (`:847-851`) or when the writer cannot hijack |
| + (`:854-857`). An ordinary response's body is closed by a defer |
| + (`:620`). **(R2-2)** What does always happen: `net/http` cancels |
| the inbound request's context when `ServeHTTP` returns, hijacked or not |
| (`net/http/server.go:2087-2089`). **(R1-2)** |
| |
| @@ -567,23 +584,91 @@ re-pointed to another `Tunnel`: each makes the comparison fail. A Reload |
| that changes nothing about the host leaves it current, so the frequent |
| reloads of a busy registry close nothing. |
| |
| -**One place, after the swap, synchronised with admission.** Reload calls |
| -`e.sweepUpgrades()` immediately after `e.upstreams.Store(&m)` |
| -(`edge.go:1234`). The sweep takes the registry's mutex, checks every |
| -reservation against the map now current, and closes (§4.6.2) every one |
| -that is no longer current. Taking a reservation (§4.3 step 4) does its |
| -tenancy check under the same mutex against `e.current()`. So for any |
| -admission racing a Reload, either the reservation was inserted before |
| -the sweep took the lock (the sweep then judges it against the new map), |
| -or it is taken after (its own check then reads the new map, because the |
| -swap happened before the sweep). No reservation can be admitted against |
| -the old map after the sweep. Between dispatch and reservation a request |
| -holds no reservation, so a request dispatched on the old map and reserving |
| -after the swap is refused at reservation: 502, cause `tunnel`, and the |
| -box sees nothing. |
| +**One place: the reload mutex (R2-1).** Rev 2 synchronised the sweep |
| +with admission but left publication outside any lock. `Reload` has no |
| +serialisation today and several callers (§4.6.3), so a slow Reload A |
| +built from an older registry read could publish its map after a newer |
| +Reload B had published a revoking one; both sweeps would then judge |
| +against A's stale map, and the watcher, which ran B, would record the |
| +new fingerprint as handled (`edge.go:2873`) and never reload again for |
| +it. |
| + |
| +Rev 3 adds `e.reloadMu`, a `sync.Mutex` taken as the first statement of |
| +`Reload` and held until it returns: through every registry read |
| +(`List`, `FleetChannelAuth`, `ListFleets`, `ListRegional`; `edge.go:730`, |
| +`:781-785`, `:1202`), the build and the folds, `SetDynamicAuth` |
| +(`:1212`), the prober sync, the map swap (`:1234`), the activator |
| +reconcile that follows it, and the new `sweepUpgrades` call placed right |
| +after the swap. Because the lock is inside `Reload`, every caller takes |
| +it by construction: the startup reload in `New` (`:495`), |
| +`EnableStatic`'s (`:4202`), `enableTunnelsFromEnv`'s (`:4247`), the |
| +watcher (`:2865`), SIGHUP (`:3919`) and the layout pass through |
| +`layoutReload` (`internal/host/agent.go:1038`). A guard test (§8.2 case |
| +19) keeps `e.upstreams.Store` at exactly one call site, inside `Reload`, |
| +after the lock. |
| + |
| +What it buys: Reloads run one at a time, each reads the registry after |
| +the previous one published, and the registry reads that decide tenancy |
| +are fresh connections (`List`, `registry.go:1092-1115`; |
| +`FleetChannelAuth` and `ListFleets` over `freshFleetsConn`, |
| +`fleets.go:286`, `:631`). So maps are published in the order their snapshots |
| +were read, the map current after any Reload is at least as new as that |
| +Reload's own read, and the sweep that follows each swap judges every |
| +open socket against it. The cost: Reloads wait for each other. Requests and |
| +admission never take `reloadMu`, so serving does not wait on a Reload. |
| + |
| +**Synchronised with admission.** The sweep takes the upgrade registry's |
| +mutex (`openUpgrades.mu`), checks every reservation against the map now |
| +current, and removes every one that is no longer current. Taking a |
| +reservation (§4.3 step 4) does its tenancy check under the same mutex |
| +against `e.current()`. For any admission racing a Reload: either the |
| +reservation was inserted before that Reload's sweep took the lock (the |
| +sweep judges it against the new map), or it is taken after the swap (its |
| +own check reads the new map). No reservation can be admitted against a |
| +map older than the latest swap once that swap's sweep has run, and no |
| +older map can be swapped in afterwards, because the next swap belongs to |
| +a later Reload with a later read. A request dispatched on the old map |
| +and reserving after the swap is refused at reservation: 502, cause |
| +`tunnel`, and the box sees nothing. |
| + |
| +The sweep removes stale reservations under `openUpgrades.mu`, then |
| +releases them after dropping it, each on its own goroutine: `release()` |
| +closes streams, and network teardown must never run under a lock or |
| +hold up a Reload. A removed reservation is no longer counted as current |
| +by anything; its socket closes within the §4.6 bound. |
| + |
| +**The watcher's bookkeeping.** `Watch` already records a fingerprint as |
| +handled only when its own `Reload` returns nil (`edge.go:2856-2873`). |
| +With the lock, that return means its Reload has swapped and swept. The |
| +fingerprint is read before the Reload takes the lock and reads the |
| +registry (`:2839`), so the state it names is never newer than the map |
| +that Reload published. A newer write moves the fingerprint, and the next |
| +tick reloads. A failed Reload records nothing and the next tick retries, |
| +as today. |
| + |
| +**Lock order.** `reloadMu` is outermost. Under it, `Reload` takes, one |
| +at a time and never nested in each other, `TunnelHub.mu` (inside |
| +`SetDynamicAuth` and `CloseChannel`; the raw close already runs outside |
| +it, `tunnel.go:333-346`), the existing prober and activator locks it |
| +already takes today, and `openUpgrades.mu` (the sweep). Admission |
| +(`transportFor`) takes `TunnelHub.mu` to find the connection and read |
| +its caps, drops it, then takes `openUpgrades.mu`; it never takes |
| +`reloadMu`, and nothing is called under `openUpgrades.mu` but map |
| +operations and `lookupUpstreamPath`, which is lock-free over the |
| +atomically loaded map (`edge.go:1574-1576`). `release()` takes |
| +`openUpgrades.mu` alone. The plan-tracking mutex `e.upgradesMu` |
| +(`edge.go:360`) is separate: `CloseAccountUpgrades` cancels contexts |
| +under it, and `context.AfterFunc` runs each reservation's `release` on |
| +its own goroutine, so the two are never held together. No path holds |
| +`openUpgrades.mu` or `TunnelHub.mu` while waiting for `reloadMu`, so the |
| +new edge in the lock graph cannot close a cycle. The layout pass calls |
| +`Reload` from inside its own serialisation (`internal/layout/pass.go:882-891`, |
| +`:1270-1277`) as it does today; `Reload` takes no layout lock, so that |
| +order is unchanged. |
| |
| **Channel changes.** Reload applies `SetDynamicAuth` before the swap |
| -(`edge.go:1212`), so the same sweep follows every detach and rotation. |
| +(`edge.go:1212`), under the same lock, so the same sweep follows every |
| +detach and rotation. |
| A detach also closes the channel itself (`tunnel.go:319-322`), which |
| ends every stream on it (§4.7). A rotation closes nothing by itself: |
| a socket on the old connection stays only while its host is still |
| @@ -626,8 +711,10 @@ Who calls `release()`, by terminal path: |
| | malformed, oversized, slow, non-101 or mismatched in-band response | `transportFor`, before returning the error | |
| | ordinary refusal or any response without the marker | the wrapped body's `Close`, which the proxy defers (`reverseproxy.go:620`) | |
| | 101, then the socket closes | the upgraded body's `Close` (proxy, `reverseproxy.go:860-870`) | |
| -| 101 dropped by the proxy (`ModifyResponse` fails, type mismatch, no hijack: `reverseproxy.go:590-592`, `:842-857`) | the backstop | |
| -| the sweep (§4.6.1), `CloseAccountUpgrades`, client gone | the sweep calls it directly; the others through the backstop | |
| +| `ModifyResponse` fails, on a 101 or any other response **(R2-2)** | the body's `Close`: the proxy closes it before its error handler (`reverseproxy.go:395-397`) | |
| +| 101 dropped by the proxy with its body open: the writer cannot hijack (`reverseproxy.go:854-857`) | the backstop | |
| +| 101 dropped for an upgrade-type mismatch or a body that is not writable (`:842-851`) | not reachable from this transport: `RoundTripUpgrade` refuses a mismatched token itself (§4.3 step 9, released by `transportFor`) and always returns a writable body; the backstop would cover them if it were | |
| +| the sweep (§4.6.1), `CloseAccountUpgrades`, client gone | the sweep calls it on its own goroutine after removing the reservation; the others through the backstop | |
| |
| The **backstop**: when the reservation is taken, `transportFor` registers |
| `context.AfterFunc(req.Context(), r.release)` on the inbound request's |
| @@ -647,6 +734,34 @@ Test (§8.2 case 12): 200 failed attempts on one channel, mixing every |
| terminal path above, then a successful upgrade on the same channel, with |
| the channel's count asserted 0 between them. |
| |
| +#### 4.6.3 Every path that publishes or reads the map, against the registry **(R2-1)** |
| + |
| +The author's sweep of this fault family on `65fd8060`, so round 3 judges |
| +the whole set rather than one interleaving. |
| + |
| +| path | what it does to the map or the registry | how it stands | |
| +|---|---|---| |
| +| `New`'s startup `Reload` (`edge.go:495`) | builds and swaps the first map | under `reloadMu`; no listener yet, so no socket exists | |
| +| `EnableStatic` (`:4202`) and `enableTunnelsFromEnv` (`:4247`) | rebuild at startup | under `reloadMu`, like every Reload | |
| +| `Watch` (`:2822-2876`) | fingerprint, then `Reload`, then records it | under `reloadMu`; records only after its own Reload swapped and swept (§4.6.1) | |
| +| SIGHUP (`:3915-3925`) | `Reload` | under `reloadMu` | |
| +| the layout pass (`internal/host/agent.go:1038`, `layoutleg.go:291`, `layout/pass.go:891`, `:1277`) | `Reload` after a move commits | under `reloadMu`; its own lock is outside and `Reload` never takes it | |
| +| `e.upstreams.Store` (`edge.go:1234`) | the only publication | one call site, inside `Reload`; guard test §8.2 case 19 | |
| +| `SetDynamicAuth` (`edge.go:1212`, `tunnel.go:314-324`) and `CloseChannel` (`:333-346`) | detach closes a channel; rotation swaps hashes | called only from `Reload`, under `reloadMu`; the sweep after the swap judges every socket | |
| +| tunnel registration (`TunnelHub.ServeHTTP`, `tunnel.go:209-216`) | replaces a channel's connection | touches no map; the old connection's streams end and release (§4.6.2); tenancy does not name a connection, so a re-registered box is judged as before | |
| +| the fingerprint (`registry.go:3815-3960`) | decides whether the watcher reloads | covers the routes' account, app, region and tunnel columns, the fleets table's owner and the fleet boxes' tokens and status, so every tenancy change moves it | |
| +| registry reads inside `Reload` | the snapshot | `List`, `FleetChannelAuth` and `ListFleets` open fresh connections (`registry.go:1092-1115`, `fleets.go:286`, `:631`). `ListRegional` reads the long-lived handle (`registry.go:3554`) and can be stale; that is pre-existing and cannot re-authorise a tenancy, because regional rows only copy or deny entries already in the map and `refusedHosts` removes every refused host after that fold (`edge.go:1208`) | |
| +| request dispatch (`ServeHTTP`, `lookupUpstreamPath`) | reads the current map without a lock | may dispatch on a map about to be replaced; harmless, because the reservation re-checks under `openUpgrades.mu` (§4.6.1) | |
| +| admission (`transportFor`) | re-checks tenancy | under `openUpgrades.mu`, never `reloadMu` | |
| +| `CloseAccountUpgrades` (`planthrottle.go:132-141`) | cancels plan-tracked contexts | under `e.upgradesMu` only; releases run through the backstop on their own goroutines | |
| +| the edges-file writer and the alias pass | compute `FleetArmVerdict` from their own listings | publish nothing that serves; no socket depends on them | |
| +| hub restart | a new process | its registry of open upgrades starts empty, and every old socket died with the old process (§4.7) | |
| + |
| +Found by the sweep and fixed above: the unserialised `Reload` (R2-1). |
| +Found and left, as pre-existing and harmless to this invariant: |
| +`ListRegional`'s long-lived handle. Nothing else publishes or reads the |
| +map relative to the registry. |
| + |
| ### 4.7 Lifetimes: what closes an upgraded socket |
| |
| | event | what happens | bound | |
| @@ -773,9 +888,10 @@ release floor is needed. |
| - `internal/edge/upgrades.go` (new): `openUpgrades`, `upgradeReservation` |
| (take, `release` once, backstop), `tenancy`, and `Edge.sweepUpgrades` |
| **(R1-1, R1-2)**. |
| -- `internal/edge/edge.go`: Reload sets `upstream.tenancy` in the three |
| - tunnel arms and calls `sweepUpgrades` right after the map swap |
| - (`:1234`); the upgrade branch puts the admission on the context; |
| +- `internal/edge/edge.go`: `Edge` gains `reloadMu`; Reload takes it |
| + first and holds it to the end **(R2-1)**, sets `upstream.tenancy` in |
| + the three tunnel arms and calls `sweepUpgrades` right after the map |
| + swap (`:1234`); the upgrade branch puts the admission on the context; |
| `fleetProxy` and `tunnelProxy` scrub the two marker headers in |
| `Rewrite`, and their error handlers answer the new sentinels (§7); |
| `ServeHTTP` deletes `Carlos-Tunnel-Upgrade` from inbound requests. |
| @@ -815,7 +931,8 @@ a card. Expected classes: |
| |
| - `body`: `TunnelHub.ServeHTTP`, `TunnelHub.transportFor`, `fleetProxy`, |
| `tunnelProxy`, `Edge.ServeHTTP` (one header delete, the admission), |
| - `Edge.Reload` (tenancy on three arms, the sweep call), `tunnelclient.Dial`, |
| + `Edge.Reload` (the reload mutex, tenancy on three arms, the sweep |
| + call), `tunnelclient.Dial`, |
| `tunnelclient.Serve`, `markedHandler.ServeHTTP`; |
| - `new`: `tunnelclient.RoundTripUpgrade` and its conn type, the shim's |
| writer and conn, the window and stream constants, `openUpgrades`, |
| @@ -938,14 +1055,26 @@ Cases, each against the same scene: |
| branch counter did not move. |
| 11. An old box (a `Loop` built without the caps header): 502 with cause |
| `tunnel_upgrade_unsupported`; plain GETs unaffected. |
| -12. Reservations never leak **(R1-2)**: 200 failed attempts on one |
| - channel at the production cap of 128, mixing every terminal path of |
| - §4.6.2 (no gate cookie, a 404, a box handler that answers a |
| +12. Reservations never leak **(R1-2, R2-2)**: 200 failed attempts on |
| + one channel at the production cap of 128, mixing every terminal path |
| + of §4.6.2 (no gate cookie, a 404, a box handler that answers a |
| malformed in-band 101, one that answers a 101 with the wrong |
| `Upgrade`, a token over 64 bytes, a channel killed mid-handshake, a |
| - `ModifyResponse` that fails on the 101, a client that disconnects |
| - mid-handshake); the channel's count is 0 after each; then a |
| - successful upgrade on the same channel. |
| + client that disconnects mid-handshake); the channel's count is 0 |
| + after each; then a successful upgrade on the same channel. Each |
| + reservation records which caller released it first (a test hook), and |
| + two paths are asserted by that record, not only by the count: |
| + - `ModifyResponse` failing on the 101: released by the body's |
| + `Close`, observed from inside the proxy's error handler, before the |
| + request ends (`reverseproxy.go:395-397`); |
| + - the backstop, on a path that really leaves the body open: the hub |
| + served through its real `http.Server` behind a wrapper whose |
| + `ResponseWriter` does not implement `http.Hijacker`, so the proxy |
| + takes `reverseproxy.go:854-857` and returns without closing the |
| + 101's body. The count stays 1 while the handler runs, is 0 once |
| + `net/http` cancels the request context, and the first releaser is |
| + the `AfterFunc`. The box sees its stream reset and closes the |
| + app's socket. |
| 13. Maximum load **(R1-4)**, at the production values (`MaxStreams` 250, |
| `StreamWindow` 1 MiB, `ConnWindow` 160 MiB, cap 128), on one tunnel: |
| - 128 upgrades open, every app side not reading, and each client |
| @@ -978,6 +1107,30 @@ Cases, each against the same scene: |
| handshake resumes and is refused at reservation (502), and the app |
| sees nothing. With the hook pausing between reservation and the |
| stream instead, the sweep closes it. |
| +18. Two Reloads interleave **(R2-1)**, deterministically, with test hooks |
| + in `Reload` after the build (before taking the swap path) and after |
| + the swap (before the sweep). A socket is open on a forward row. |
| + Reload A starts while the fleet's owner is the row's account and is |
| + paused after its build; the owner changes in the registry; Reload B |
| + is started; A resumes. Asserted with the reload mutex: B cannot read |
| + the registry until A has swapped and swept (B blocks on `reloadMu`, |
| + observed through the hook never firing for B while A is paused); |
| + after both, the current map is B's (the host refused), the socket is |
| + closed at both endpoints within 2 s, and a new handshake is refused. |
| + Fingerprint bookkeeping: the same interleaving with B driven by the |
| + real `Watch` loop (A from a direct call standing in for SIGHUP); |
| + `Watch` records the new fingerprint only after B's Reload has |
| + swapped and swept (a hook on the record), and a Reload that fails |
| + after the owner change records nothing, so the next tick retries and |
| + closes the socket. The same case with the order reversed (B revoking |
| + first, A authorising after, reading the newer registry) ends with |
| + the host refused too, because A's read happens after B's swap. The |
| + test fails on rev 2's code (no `reloadMu`): there A publishes its |
| + stale map after B and the socket survives. |
| +19. Guard test: a go/ast check over `internal/edge` that |
| + `e.upstreams.Store` has exactly one call site, inside `Reload`, and |
| + that `Reload`'s first statement locks `e.reloadMu` with a deferred |
| + unlock; and that `SetDynamicAuth` is called only from `Reload`. |
| |
| The 1a tests `TestForwardUpgradeIsLimitedAtTheHub` and |
| `TestForwardPlanThrottleAndUpgradeClose` change from "101 or 502" to 101, |
| @@ -1074,6 +1227,14 @@ witness kills established connections (§8.2 case 9); the maximum-load |
| guarantee is proved at the production cap (§8.2 case 13); §10.2 |
| re-verified and withdrawn. |
| |
| +Round 2's rulings: one reload mutex held from the registry read through |
| +the swap and the sweep, taken by every Reload caller, with the watcher |
| +recording a fingerprint only after its own serialised Reload swapped and |
| +swept, the lock order stated and admission never taking the reload |
| +mutex (§4.6.1, §4.6.3, §8.2 cases 18 and 19); the `ModifyResponse` |
| +classification corrected and the backstop witnessed on a path that |
| +really leaves the body open (§3.5, §4.6.2, §8.2 case 12). |
| + |
| ## 12. Rollout |
| |
| - **No switch, no dormancy.** It is on as soon as both ends run it, and |