carlos / platform Public

design: tunnel WebSockets (#471), spec rev 2 (Astra R1)

Astra round 1 NOT READY (1 P1, 4 P2), every finding taken with the
controller's rulings (platform-60):
- R1-1 (P1): every open upgrade records its admitting tenancy; one sweep
  after each Reload's map swap, under the registry mutex shared with
  admission, closes sockets whose host is no longer served for the same
  account, app and fleet (or tunnel), plans or not.
- R1-2: one upgradeReservation per stream, released exactly once on
  every terminal path, with a context.AfterFunc backstop on the hub's
  request context.
- R1-3: the hub-restart witness closes every accepted connection
  (hijacked included) and brings a new hub up on the same address.
- R1-4: the maximum-load guarantee stated as an invariant over named
  constants and proved at the production cap; SETTINGS and the
  connection WINDOW_UPDATE checked separately.
- R1-5: the bufferedConn TLS finding re-verified and withdrawn.
Findings file committed alongside.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c96dd93d9d0926094933fe0de84ab5a9d1e3e777 parent 5153536
2 files changed, +400 −100
  • docs/superpowers/reviews/CODEX-FINDINGS-tunnel-websockets-R1.md +31 −0
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +369 −100
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-tunnel-websockets-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-tunnel-websockets-R1.md
new file mode 100644
index 000000000..a24ab3c04
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-tunnel-websockets-R1.md
@@ -0,0 +1,31 @@
+1. **P1 — §4.7: owner changes leave existing sockets authorized.**
+ **Evidence, verified:** `internal/edge/fleetforward.go:69–76` refuses routes whose account no longer owns the fleet. Reload replaces the routing map (`internal/edge/edge.go:1211–1234`), but neither cancels existing upgrades nor closes channels on ownership changes. `FleetChannelAuth` reads only active box credentials (`internal/registry/fleets.go:636`); `SetDynamicAuth` closes only vanished channel names (`internal/edge/tunnel.go:319–322`).
+ **Failure scenario:** Open a socket, change the fleet owner, and reload. New requests are refused, but the old socket continues carrying traffic indefinitely. The lifecycle table and witness omit this case.
+ **Fix:** Invalidate upgrades when their captured tenancy loses eligibility, including accounts outside plan tracking. Synchronize invalidation with admission and add an owner-change witness checking both endpoints.
+ **Invariant:** An open socket cannot outlive the tenancy authority that admitted it.
+
+2. **P2 — §§4.3, 4.7–4.8: cap reservation cleanup is incomplete.**
+ **Evidence, verified:** The cap is admitted before `RoundTripUpgrade` (`spec:330–339`), but the stated decrement happens through the upgraded body’s `Close` (`spec:486–489`). Refusals return ordinary responses untouched (`spec:366–369`), and validation or parsing errors return no upgraded body. Go’s proxy returns immediately on a transport error (`net/http/httputil/reverseproxy.go:579–585`); its upgraded-body close mechanism is installed only later (`:860–870`).
+ **Failure scenario:** Following the stated cleanup mechanism, repeated gate refusals or malformed handshakes consume the channel’s reservations until legitimate upgrades receive permanent 503s.
+ **Fix:** Specify exactly-once reservation ownership for validation errors, transport errors, ordinary refusals, malformed in-band responses and successful upgrades. Test more than 128 unsuccessful attempts followed by a successful upgrade on the same channel.
+ **Invariant:** Every reserved upgrade slot is released on every terminal path.
+
+3. **P2 — §8.2 case 9: closing the server does not simulate hub restart.**
+ **Evidence, verified:** The proposed witness closes the hub’s server (`spec:705`). Go 1.26.10 explicitly excludes hijacked connections from both `Server.Close` and `Shutdown` (`net/http/server.go:3115–3116`, `:3162–3165`). Tunnel registration hijacks its connection (`internal/edge/tunnel.go:182`), as does the public upgrade.
+ **Failure scenario:** The listener closes while both upgraded connections remain alive; the app socket does not close as asserted.
+ **Fix:** Terminate a subprocess running the hub, or explicitly close all captured hijacked connections to model process death. Keep a separate listener-shutdown case if useful.
+ **Invariant:** The restart witness must exercise loss of established connections.
+
+4. **P2 — §§8.1–8.2: the resource witness does not establish the stated maximum-load guarantee.**
+ **Evidence, verified:** Case 13 stalls one socket (`spec:714–716`), while the guarantee depends on 128 stalled streams retaining 32 MiB (`spec:507–513`). Also, the connection receive window cannot be read from SETTINGS alone as §8.1.6 proposes: x/net v0.60.0 advertises it through a connection-level WINDOW_UPDATE (`http2/server.go:798–801`).
+ **Failure scenario:** An undersized connection window can pass the single-socket witness while allowing enough stalled upgrades to block plain uploads.
+ **Fix:** Saturate the configured upgrade cap using scaled test windows, then complete a plain POST. Verify the production SETTINGS values and initial connection WINDOW_UPDATE separately.
+ **Invariant:** Maximum admitted upgrade traffic leaves usable stream slots and connection credit for plain requests.
+
+5. **P2 — §10.2: the claimed TLS timing failure is unsupported by the pinned implementation.**
+ **Evidence, verified:** The hub flushes the 101 before constructing the HTTP/2 client (`internal/edge/tunnel.go:197–203`). The preface is flushed separately (`x/net/http2/transport.go:539–543`). Go 1.26.10 writes these in separate TLS records (`crypto/tls/conn.go:1254`) and reads application data from one record at a time (`:1392–1403`). TCP packet coalescing therefore does not produce the claimed TLS over-read.
+ **Failure scenario:** An unconditional “two-line” `ConnectionState` forwarding method instead risks breaking supported plaintext buffered connections: a type assertion can panic, while a zero TLS state makes x/net reject the connection (`http2/server.go:336–351`).
+ **Fix:** Correct the side finding. If retaining defensive metadata forwarding, use a TLS-specific wrapper and test buffered plaintext and TLS connections separately.
+ **Invariant:** Buffer preservation must preserve whether the underlying connection actually uses TLS.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
index c3bd2c6a1..1d40a6b70 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -1,18 +1,35 @@
# Tunnel WebSockets: upgraded connections through the fleet tunnel
-Status: DRAFT rev 1, 2026-10-30. Discussion: amadan carlos/platform #471.
+Status: DRAFT rev 2, 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
Go 1.26.10 standard library.
-Review history: none yet. Round budget per AGENTS.md "Stopping rules":
-stop at the first round with no P1; a fourth round needs Paul.
+Revisions:
+- Rev 1 (92fb3af3): first draft.
+- Rev 2: Astra round 1 (`docs/superpowers/reviews/CODEX-FINDINGS-tunnel-websockets-R1.md`,
+ NOT READY, 1 P1 and 4 P2), every finding taken with the controller's
+ rulings (platform-60). Changes are marked **(R1-n)**:
+ an open socket cannot outlive the tenancy that admitted it, swept in
+ one place after every Reload's map swap and synchronised with
+ admission (R1-1, §4.6.1); one upgrade reservation with exactly-once
+ release on every terminal path (R1-2, §4.6.2); the hub-restart witness
+ kills established connections and brings the hub back (R1-3, §8.2
+ case 9); the maximum-load guarantee proved at scale, and the
+ production SETTINGS and connection WINDOW_UPDATE checked separately
+ (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.
## 0. Status
-Rev 1, written for Paul and one Astra round. Five open questions (§11),
-each with a recommendation.
+Rev 2. Astra R1 NOT READY; every finding taken. No open questions: the
+controller ruled on all five (§11).
## 1. Intent
@@ -58,8 +75,14 @@ Goals:
and overlap deploys all close or drain upgraded sockets, in bounded
time, with no leaked state on either side.
5. Open WebSockets can never starve a box's plain HTTP traffic across the
- tunnel (stream slots and flow-control windows, §4.8).
-6. No bucket requests, no release floor, no switch.
+ tunnel (stream slots and flow-control windows, §4.8), proved at the
+ production cap (§8.2 case 13) **(R1-4)**.
+6. An open socket never outlives the tenancy that admitted it: when a
+ host stops being served for the same account, app and fleet (owner
+ change, a move to another fleet, the row gone), its sockets close
+ with the Reload that stopped serving it, whether or not plans track
+ the account **(R1-1)**.
+7. No bucket requests, no release floor, no switch.
Non-goals:
@@ -73,8 +96,8 @@ Non-goals:
relate.
- #432 (edge-held SSE streams). SSE already crosses the tunnel as an
ordinary streamed HTTP/2 response.
-- The client address a fleet app sees (§10.1). Found while writing this;
- separate.
+- The client address a fleet app sees (§10.1, filed as #476). Found while
+ writing this; separate.
## 3. What happens today
@@ -180,6 +203,28 @@ From 1a's Task 5 (fleet public routes spec §4.8):
the request context is done (`reverseproxy.go:860-870`). That is the
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
+ the inbound request's context when `ServeHTTP` returns, hijacked or not
+ (`net/http/server.go:2087-2089`). **(R1-2)**
+
+Nothing ties an open upgrade to the tenancy that admitted it **(R1-1)**.
+A forward row is refused once its account no longer owns its fleet
+(`FleetServeEligible`, `internal/edge/fleetforward.go:69-76`), and the
+next Reload swaps in a map without it (`edge.go:1208`, `:1234`). But
+Reload cancels no request. `trackUpgrade` registers only plan-governed
+accounts (`planthrottle.go:103-105`), and only the plans pass cancels
+those. `FleetChannelAuth` lists active box credentials, not owners
+(`internal/registry/fleets.go:636`), and `SetDynamicAuth` closes only
+channel names that vanished (`tunnel.go:319-322`). Today this costs
+nothing, because no upgrade crosses the tunnel. With rev 1's design, a
+socket opened before an owner change would carry traffic for as long as
+it stayed open.
The fleet edge exempts tunneled requests from the rate limit, plan
throttle, guard and request records (`fromTunnel`: `ratelimit.go:130`,
@@ -263,6 +308,10 @@ stream, so the hub's proxy hijacks the client and splices, as it does for
a local app. Both halves live in `internal/tunnelclient`, the leaf
package both sides already import. A box says it speaks this in its
registration, so an old box keeps today's 502 and no floor is needed.
+Every stream is held by one reservation in the hub's open-upgrade
+registry, which records the tenancy that admitted it, counts it against
+the channel's cap, is released exactly once, and is closed by the first
+Reload under which that tenancy no longer holds **(R1-1, R1-2)**.
### 4.2 Why this shape (options)
@@ -320,20 +369,29 @@ platform app already runs.
1. Browser to hub: HTTP/1.1 `GET /cable` with `Connection: Upgrade`,
`Upgrade: websocket`, `Sec-WebSocket-*`, `Origin`, `Cookie`.
-2. Hub `ServeHTTP` (unchanged): guard, geo, forwarded key, lookup to the
- forward row, then the upgrade branch (§4.6): `trackUpgrade`,
- `planUpgradeAdmit`, `rateAdmit`, `fleetProxy`.
+2. Hub `ServeHTTP`: guard, geo, forwarded key, lookup to the forward
+ row, then the upgrade branch (§4.6): `trackUpgrade`,
+ `planUpgradeAdmit`, `rateAdmit`, and (new) the **admission**: the
+ request's host, path and the tenancy of the map entry it was
+ dispatched on (`upstream.tenancy`, §4.6.1) go on the request context.
+ Then `fleetProxy`.
3. Hub `fleetProxy.Rewrite` (unchanged, plus one scrub, §4.4): sets
`X-Forwarded-*`, geo, `Host`, scrubs `Carlos-Purge`.
4. Hub `transportFor(name)` sees an upgrade (`Connection` carries the
`Upgrade` token and `Upgrade` is set; the same predicate the stdlib
- proxy uses) and calls `tunnelclient.RoundTripUpgrade(cc, req)` instead
- of `cc.RoundTrip(req)`, after two gates: the channel advertised the
- capability (§4.9), and the channel is under its upgrade cap (§4.8).
+ proxy uses). It refuses one with no admission on its context (fails
+ closed: an upgrade that did not come through step 2 never crosses),
+ refuses a channel that did not advertise the capability (§4.9), and
+ validates the `Upgrade` token (one RFC 7230 token, printable, at most
+ 64 bytes). None of these holds anything. Then it takes the
+ **reservation** (§4.6.2): under the registry's lock, the tenancy is
+ still current and the channel is under its cap, or it is refused.
+ From here the reservation owns the stream, and `transportFor` calls
+ `tunnelclient.RoundTripUpgrade(ctx, cc, req)` with the reservation's
+ context.
5. `RoundTripUpgrade`:
- clones the request; deletes `Connection` and `Upgrade`; sets
- `Carlos-Tunnel-Upgrade: <token>` (one RFC 7230 token, printable, at
- most 64 bytes, else refused before any stream opens);
+ `Carlos-Tunnel-Upgrade: <token>` (validated in step 4);
- sets the body to the read end of a pipe (unknown length, so HTTP/2
sends HEADERS without END_STREAM);
- `cc.RoundTrip`.
@@ -356,8 +414,11 @@ platform app already runs.
requires `101` with the requested `Upgrade` token, and returns that
response with `Body` set to an `io.ReadWriteCloser`: reads drain the
buffered reader and then the stream, writes go to the pipe, `Close`
- ends both (§4.7). It implements `CloseWrite` (ends the pipe, which
- sends END_STREAM) so the proxy's half-close reaches the box.
+ releases the reservation (§4.6.2). It implements `CloseWrite` (ends
+ the pipe, which sends END_STREAM) so the proxy's half-close reaches
+ the box. A malformed, slow, oversized, non-101 or mismatched in-band
+ response returns an error, and `transportFor` releases the reservation
+ before returning it.
10. Hub proxy (unchanged): `ModifyResponse` runs on the 101
(`reverseproxy.go:589`), the upgrade types match, it hijacks the
browser's conn through `slotWriter` (the rate-limit slot goes back),
@@ -365,9 +426,10 @@ platform app already runs.
If the box answers without the marker (the gate's login page or 302, a
404, a 502 because the app is down, any refusal), step 9 returns that
-response untouched and the hub's proxy copies it to the browser as an
-ordinary answer. The browser's WebSocket fails exactly as it would
-against a platform box.
+response with its body wrapped so that `Close` releases the reservation,
+and the hub's proxy copies it to the browser as an ordinary answer and
+closes the body (`reverseproxy.go:620`). The browser's WebSocket fails
+exactly as it would against a platform box.
### 4.4 Headers
@@ -394,7 +456,9 @@ so an app cannot make the hub read its body as a 101.
the request. It holds because:
- `RoundTripUpgrade` is the only writer of the header, and `transportFor`
- calls it only for a request the stdlib proxy marked as an upgrade;
+ calls it only for a request the stdlib proxy marked as an upgrade and
+ that carries the upgrade branch's admission on its context (§4.3 step
+ 4), holding a reservation;
- the stdlib proxy marks a request as an upgrade on the same predicate
as `isUpgradeRequest` (`Connection` token `Upgrade`, every line;
`edge.go:2286-2293`, `reverseproxy.go:828-833`), so such a request
@@ -421,8 +485,8 @@ request's scheme and host (`allow_same_origin_as_host`), so this is
load-bearing for any Rails app without `config.assume_ssl`. The shop sets
`assume_ssl` (`examples/rails-shop/config/environments/production.rb:28`);
the witness (§8.2) checks the general case. Upgrades get exactly the
-headers plain tunneled requests get. §10 notes two pre-existing gaps in
-those headers.
+headers plain tunneled requests get. §10.1 notes the pre-existing gap
+in the client address (#476).
### 4.5 The gate cookie
@@ -446,10 +510,13 @@ The close path for an awake-throttled account:
1. The agent calls `CloseAccountUpgrades(account)` (`agent.go:1054-1059`);
it cancels every registered context (`planthrottle.go:132-141`).
2. The hub's proxy sees the context done and closes `backConn`
- (`reverseproxy.go:860-870`), which is `RoundTripUpgrade`'s body.
-3. That `Close` closes the pipe and the stream's response body, which
- resets the stream (`RST_STREAM CANCEL`). The hub's splice ends and its
- deferred `conn.Close()` closes the browser's socket.
+ (`reverseproxy.go:860-870`), which is `RoundTripUpgrade`'s body. The
+ reservation's backstop (§4.6.2) fires on the same cancel, so the close
+ does not depend on the proxy having reached its splice.
+3. That `Close` releases the reservation, whose release cancels the
+ stream's context, closes the pipe and closes the stream's response
+ body, which resets the stream (`RST_STREAM CANCEL`). The hub's splice
+ ends and its deferred `conn.Close()` closes the browser's socket.
4. On the box the reset cancels the stream's request context and fails
the shim's `Read`. The box's proxy, in the same handler, closes the
app's socket the same way (`reverseproxy.go:860-870`) and returns, and
@@ -458,14 +525,128 @@ The close path for an awake-throttled account:
So one cancel at the hub closes the browser's socket, the stream and the
app's socket. The witness checks all three, the app side within 2 s.
-Per-channel cap (§4.8) is checked in `transportFor` after the upgrade
-branch has admitted the request. A refusal there is 503 (§4.8), and the
-rate-limit slot it held is released by the handler's deferred release as
-for any refused request.
+The per-channel cap (§4.8) is checked when the reservation is taken,
+after the upgrade branch has admitted the request. A refusal there is 503
+(§4.8), and the rate-limit slot it held is released by the handler's
+deferred release as for any refused request.
The box keeps exempting tunneled requests, unchanged. Nothing on the box
enforces anything new.
+#### 4.6.1 Tenancy: a socket never outlives what admitted it **(R1-1)**
+
+`trackUpgrade` covers only plan-governed accounts, and only the plans
+pass ever cancels it (§3.5). Ownership needs its own rule, for every
+account.
+
+**What is recorded.** Reload already decides, per host, whether and
+where a row goes through a tunnel (`FleetArmVerdict`, `DispatchArm`,
+`edge.go:795`, `:840`). Each upstream it builds for `ArmForward`,
+`ArmFleet` or `ArmTunnel` gains a `tenancy` value:
+
+ tenancy{Arm, Account, App, Fleet, Tunnel}
+
+`ArmForward` and `ArmFleet` take `Account`, `App` and `Fleet` from
+`verdict.Arm[host]` (`FleetServed`, `fleetforward.go:205`), the same
+value that picks the proxy's fleet; `ArmTunnel` takes the row's
+`Account`, `App` and `Tunnel`. The alias and platform-alias folds copy
+the source's upstream, so an alias carries its source's tenancy, which
+is where it goes. Other arms carry none.
+
+**The registry.** The hub's `Edge` owns one `openUpgrades`: a mutex,
+reservations by host, and an open count per `tunnelConn`. A reservation
+records the request's host and path, the tenancy it was admitted under
+(from the admission, §4.3 step 2), and the channel connection it rides.
+
+**The rule.** A reservation is current while
+`e.lookupUpstreamPath(host, path)` on the current map (the same lookup
+the request was dispatched by, `edge.go:1574`) finds an upstream whose
+`tenancy` equals the recorded one. Owner change, a move to another fleet,
+a different app or account at the host, the row gone, refused, or
+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.
+
+**Channel changes.** Reload applies `SetDynamicAuth` before the swap
+(`edge.go:1212`), 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
+served for the same tenancy, which is what the controller's ruling asks.
+
+**Bound.** The registry change that ends a tenancy (the console writes
+the fleets table, the record pass rewrites or deletes the row) moves the
+fingerprint, the edge's 2 s watch reloads (`edge.go:2822-2850`), and the
+sweep closes the socket in that Reload. The close itself is the §4.6
+path from step 3, so both endpoints see it within one round trip. The
+witness asserts both endpoints closed within 2 s of a direct Reload and
+within 5 s of the registry write with the watch running.
+
+#### 4.6.2 The reservation: one object, released exactly once **(R1-2)**
+
+Rev 1 released the cap through the upgraded body's `Close`. The stdlib
+proxy does not close that body on several paths (§3.5), and an ordinary
+refusal has no upgraded body at all, so slots would leak to a permanent
+503.
+
+One object, `upgradeReservation`, created only by `transportFor` (§4.3
+step 4) and owned by it:
+
+- **taken** under the registry mutex: tenancy current, channel under
+ its cap; inserted into the registry and counted against the channel;
+ given its own cancelable context for the stream;
+- **released** by `release()`, guarded by `sync.Once`: cancel the stream
+ context, close the pipe and the stream's response body if any (which
+ resets the stream), remove from the registry, decrement the channel's
+ count. Every caller of `release()` may be redundant; only the first
+ acts.
+
+Who calls `release()`, by terminal path:
+
+| path | released by |
+|---|---|
+| validation error, no admission, old box | nothing taken (refused before reserving) |
+| tenancy stale or channel at cap | nothing taken (refused inside the mutex) |
+| transport error (`cc.RoundTrip` fails, channel gone) | `transportFor`, before returning the error |
+| 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 |
+
+The **backstop**: when the reservation is taken, `transportFor` registers
+`context.AfterFunc(req.Context(), r.release)` on the inbound request's
+context, and stops it on release. `net/http` cancels that context when
+the hub's `ServeHTTP` returns, hijacked or not
+(`net/http/server.go:2087-2089`), and the hub's `ServeHTTP` for an
+upgrade returns only when the socket is over. So every path ends in
+`release()` no later than the end of the request, whatever the stdlib
+proxy did with the response.
+
+The channel's count is keyed by the `tunnelConn` pointer, so a replaced
+connection's streams, which fail and release, decrement the old entry,
+which is deleted at zero. Nothing is ever counted against a connection
+that did not carry it.
+
+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.7 Lifetimes: what closes an upgraded socket
| event | what happens | bound |
@@ -476,17 +657,17 @@ enforces anything new.
| tunnel dies (ping failure, network, the box's agent restarts) | the hub's raw conn closes, every stream on it fails, each hub splice ends and closes its browser; on the box every handler's body read fails and each proxy closes its app socket (or the process is gone) | about 10 s for a silent death (fleet ping cadence, `tunnel.go:58-59`); immediate for a reset |
| re-registration under the same name (`tunnel.go:210-211`) | the old conn is closed: as tunnel death | immediate |
| detach (`SetDynamicAuth` to `CloseChannel`) | as tunnel death. Revocation reaches open sockets too | immediate |
-| rotation | nothing; sockets live on the old conn until the box redials, as plain traffic does | the box's next redial |
-| hub restart (edge roll) | hijacked browser sockets die with the process (`edge.go:4152-4161`); the tunnel conn dies; boxes close their app sockets as above and redial | the hub's restart; boxes redial in 0.25 to 2 s (`tunnelclient.go:42-44`) |
+| rotation | the Reload that applies it sweeps (§4.6.1); a socket whose host is still served for the same tenancy stays on the old conn until the box redials, as plain traffic does | the box's next redial |
+| owner change, move to another fleet, row trashed or gone, row re-pointed **(R1-1)** | the Reload that stops serving the host for that tenancy sweeps its reservations (§4.6.1); each release resets its stream, the hub closes the browser and the box closes the app socket | 2 s watch plus one round trip |
+| hub restart (edge roll) | hijacked browser sockets and the tunnel conn die with the process (`edge.go:4152-4161`: neither `Shutdown` nor `Close` touches hijacked conns, `net/http/server.go:3115-3116`, `:3162-3165`, so it is the process exit that ends them); boxes see the tunnel's TCP close, close their app sockets as above and redial | the hub's restart; boxes redial in 0.25 to 2 s (`tunnelclient.go:42-44`) |
| fleet dark | a new handshake gets 503 `Retry-After: 2` (`errFleetDark`), as plain requests do | |
Action Cable's client reconnects on its own with backoff, so every row
above recovers without a page reload.
-Counters never leak: the per-channel upgrade count (§4.8) lives on the
-`tunnelConn`, not on the name, and is decremented by the upgrade body's
-`Close`, which runs exactly once on every path above (the proxy always
-closes `backConn`). A replaced conn takes its count with it.
+Counters never leak: every row above ends in the reservation's
+`release()`, at the latest through its backstop when the hub's request
+ends (§4.6.2). **(R1-2)**
Hibernation on the box is unchanged: an open socket is in flight for the
activator (§3.7), as on a platform box. The hub never manages a forward
@@ -514,12 +695,31 @@ plain requests need.**
3. **Box-to-hub window (hub receive).** Unchanged: 4 MiB per stream,
1 GiB per connection. 128 sockets whose browsers stop reading cost the
hub at most 512 MiB for that channel. That is no worse than today's
- 250 slow plain downloads (1 GiB), so v1 leaves it; §11 Q2 offers the
- tightening.
+ 250 slow plain downloads (1 GiB), so v1 leaves it (controller's call,
+ §11).
Why 128 and not more: raising the slot count above 250 raises the hub's
worst case in point 3 for plain and upgraded traffic alike. 128 keeps
-every existing worst case where it is. Q1 asks Paul.
+every existing worst case where it is (controller's call, §11).
+
+**The constants and their invariant (R1-4).** Four named values, one
+place each: `tunnelclient.MaxStreams` (250), `tunnelclient.StreamWindow`
+(1 MiB), `tunnelclient.ConnWindow` (160 MiB) on the box, and the hub's
+`tunnelUpgradeCap` (128). The guarantee holds exactly when
+
+ tunnelUpgradeCap < MaxStreams
+ ConnWindow >= tunnelUpgradeCap x StreamWindow + PlainHeadroom (PlainHeadroom = 32 MiB)
+
+A unit test asserts both over the production values, so a change to any
+one that breaks them fails the gate. What the guarantee says, precisely:
+with the cap's worth of upgraded streams open on one channel and every
+one of their apps not reading, (a) at least `MaxStreams - cap` streams
+remain for plain requests, (b) at least `PlainHeadroom` of connection
+credit remains for plain request bodies, so a plain upload completes,
+and (c) each stalled socket's client is pushed back by flow control
+after at most `StreamWindow` plus kernel socket buffers, so nothing on
+either edge buffers without bound. §8.2 case 13 proves (a) to (c) at the
+production values, not only scaled down.
Idle timeouts: none, as on every edge today (`edge.go:3940-3942`). Dead
peers are covered by the tunnel's 5 s pings on the box side and TCP
@@ -560,18 +760,25 @@ release floor is needed.
- `internal/tunnelclient` (leaf package, stdlib plus x/net only, as its
header requires, `tunnelclient.go:1-14`):
- - `RoundTripUpgrade(cc *http2.ClientConn, req *http.Request) (*http.Response, error)`,
- the hub half;
+ - `RoundTripUpgrade(ctx context.Context, cc *http2.ClientConn, req *http.Request) (*http.Response, error)`,
+ the hub half (it opens and parses; it owns no slot);
- the shim inside `Mark` (`tunnelclient.go:279-288`), the box half;
- `Dial` sends `Carlos-Tunnel-Caps` (`:228-238`);
- - `Serve` builds its `http2.Server` with the §4.8 numbers (`:291-293`).
-- `internal/edge/tunnel.go`: `tunnelConn` gains `caps` and an open-upgrade
- count; `ServeHTTP` records the caps; `transportFor` branches on an
- upgrade, checks caps and cap, and calls `RoundTripUpgrade`.
-- `internal/edge/edge.go`: `fleetProxy` and `tunnelProxy` scrub the two
- marker headers in `Rewrite`, and their error handlers answer the two
- new sentinels (§7); `ServeHTTP` deletes `Carlos-Tunnel-Upgrade` from
- inbound requests.
+ - `Serve` builds its `http2.Server` from `MaxStreams`, `StreamWindow`
+ and `ConnWindow` (§4.8, `:291-293`).
+- `internal/edge/tunnel.go`: `tunnelConn` gains `caps`; `ServeHTTP`
+ records them; `transportFor` branches on an upgrade, checks admission,
+ caps and token, takes the reservation, calls `RoundTripUpgrade`, and
+ releases on its own error paths.
+- `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;
+ `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.
- `internal/apperr/availability.go`: two causes (§7).
- No change in `internal/host`: `tunnelLoop` already passes the edge to
`tunnelclient.Loop`, which applies `Mark`.
@@ -607,10 +814,13 @@ binary's scope (`GOOS=linux go list -deps .` lists both, checked on
a card. Expected classes:
- `body`: `TunnelHub.ServeHTTP`, `TunnelHub.transportFor`, `fleetProxy`,
- `tunnelProxy`, `Edge.ServeHTTP` (one header delete), `tunnelclient.Dial`,
+ `tunnelProxy`, `Edge.ServeHTTP` (one header delete, the admission),
+ `Edge.Reload` (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 two error sentinels;
+ writer and conn, the window and stream constants, `openUpgrades`,
+ `upgradeReservation`, `tenancy`, `Edge.sweepUpgrades`, the error
+ sentinels;
- `envelope`: `internal/edge`, `internal/tunnelclient`,
`internal/apperr`;
- no `reads`: nothing reads a file or root-owned state. The edge runs as
@@ -653,9 +863,15 @@ true for fleet apps too.
5. Close: `Close` on the hub's body resets the stream; the box's conn
`Read` fails and its handler returns. `CloseWrite` delivers EOF to the
box with the other direction still open.
-6. Registration carries `Carlos-Tunnel-Caps: upgrade/1`; `Serve`'s server
- advertises 250 streams and the §4.8 windows (read from the SETTINGS
- frame).
+6. Registration carries `Carlos-Tunnel-Caps: upgrade/1`. A raw x/net
+ `Framer` client on `Serve`'s connection reads the server's first frames
+ and checks two things separately **(R1-4)**: the SETTINGS frame carries
+ `MAX_CONCURRENT_STREAMS` = `MaxStreams` (250) and `INITIAL_WINDOW_SIZE`
+ = `StreamWindow` (1 MiB); and the connection-level WINDOW_UPDATE on
+ stream 0 that follows raises the connection window by
+ `ConnWindow - 65,535` (x/net sends the connection window this way, not
+ in SETTINGS: `http2/server.go:798-801`).
+7. The §4.8 invariant over the production constants.
### 8.2 The production-wired witness, `internal/edge`
@@ -702,19 +918,66 @@ Cases, each against the same scene:
their sockets close within the ping bound; after the loop restarts a
new handshake succeeds.
8. Re-registration and detach close open sockets; rotation does not.
-9. Hub restart: close the hub's server; the app's socket closes.
+9. Hub restart **(R1-3)**. Closing the test server is not a restart:
+ `Server.Close` and `Shutdown` leave hijacked connections open
+ (`net/http/server.go:3115-3116`, `:3162-3165`), and both the tunnel
+ (`tunnel.go:182`) and the public socket are hijacked. The witness
+ serves the hub through a tracking listener that keeps every accepted
+ `net.Conn`. "The hub dies" closes the listener and every accepted
+ connection, hijacked ones included, which is what the kernel does at
+ process exit. Asserted: the client's socket closes; the box's `Loop`
+ sees its tunnel close and the app's socket closes within 2 s. Then a
+ new hub (a fresh `New` over the same registry, `EnableTunnels`,
+ `Reload`) listens on the same address; the box's real `Loop`
+ re-registers within its backoff bound (`tunnelclient.go:42-44`), and a
+ new handshake gets 101. A separate case keeps listener-only
+ `Shutdown` and asserts that open sockets survive it, matching
+ `edge.go:4152-4161`.
10. A plain GET carrying `Carlos-Tunnel-Upgrade: websocket` reaches the
app as a plain GET with no `Upgrade` and no marker; the hub's upgrade
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. Cap: with the cap lowered to 4 for the test, the fifth handshake gets
- 503 `Retry-After: 5`; plain GETs still answer while 4 sockets are
- open; closing one admits the next.
-13. Head-of-line: an app that stops reading one socket while the client
- writes 4 MiB into it; a 2 MiB POST to the same box over the same
- tunnel completes.
+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
+ 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.
+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
+ writing until its write blocks for 500 ms: each socket is pushed
+ back (assert a write deadline trips) after at most `StreamWindow`
+ plus 4 MiB of kernel buffers;
+ - the 129th handshake gets 503 `Retry-After: 5`;
+ - while all 128 stay stalled: 100 concurrent plain GETs, held open
+ by the app until all 100 have arrived, all reach the app (stream
+ slots, (a) in §4.8) and then complete; and a plain 16 MiB POST
+ completes within 10 s with its bytes intact (connection credit,
+ (b));
+ - close the 128; the channel's count returns to 0; a new upgrade
+ succeeds.
+ The same case runs scaled down (cap 8, 16 streams, 64 KiB windows)
+ under `-short`; the production-value run is in the full gate.
14. Request budget: the counting store sees zero calls (§6).
+15. Owner change **(R1-1)**: with a socket open on a forward row of an
+ account plans do not govern (`planGoverned` nil), the fleets table
+ gives the fleet another owner. After a direct Reload, the client and
+ the app both see their sockets close within 2 s; with the watch
+ running instead, within 5 s of the registry write. A new handshake
+ is refused. The same for the row moved to another fleet, for the row
+ deleted, and for a `-tunnel` row re-pointed to another channel.
+16. No false closes: a socket stays open across 20 Reloads that change
+ other hosts, rotate this box's token, and re-mint the same forward
+ row unchanged.
+17. Admission races a Reload: a test hook pauses a handshake between
+ dispatch and reservation; the owner changes and Reload runs; the
+ 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.
The 1a tests `TestForwardUpgradeIsLimitedAtTheHub` and
`TestForwardPlanThrottleAndUpgradeClose` change from "101 or 502" to 101,
@@ -737,9 +1000,9 @@ After the release reaches sophie (the hub) and r10r's box-1:
every 3 s. Rails mounts Action Cable at `/cable` by default. The
sample has no `app/channels` today; if its Rails falls back to the
base connection class this step needs no app change, and if it does
- not, the step waits for Q4's change. The plan checks which before the
+ not, the step waits for the sample change (§11 item 4). The plan checks which before the
roll, locally, with `carlos ship --check`'s image.
-3. With Q4's sample change: open the shop's page in a browser, press
+3. With the sample change (§11 item 4): open the shop's page in a browser, press
"Enqueue a job", and see the count change without a reload.
4. `railsdemo.bab.dev.oncarlos.com` (a hand `ArmFleet` row) answers as
before.
@@ -770,40 +1033,46 @@ builds it:
1. **A fleet app sees the hub's address as the client.** On the box, a
tunneled request's `RemoteAddr` is the hub, and the box's proxy
replaces `X-Forwarded-For` with it (`homemap.go:1428-1446`; the hub's
- chain is trusted only on a verified hop, `:1441`). Rails'
- `request.remote_ip` is the hub for every fleet app. Applies to plain
- and upgraded requests. Recommend its own discussion.
-2. **`bufferedConn` can hide the tunnel's TLS state.** When the box's
- handshake read over-reads past the 101, `Dial` returns a
- `bufferedConn` (`tunnelclient.go:173-178`, `:258-259`) that does not
- expose `ConnectionState`, so the box's HTTP/2 server sees no TLS
- (`x/net/http2/server.go:336`) and `X-Forwarded-Proto` becomes `http`
- for that session. Rare (the 101 and the preface are separate TLS
- records), but a timing bug. A two-line fix (forward
- `ConnectionState`); it can ride this plan as a task because §8.2 case
- 2 asserts the header.
-
-## 11. Open questions for Paul
-
-1. **Cap of 128 open WebSockets per fleet box.** It keeps every existing
- worst case where it is (§4.8). A busier box needs the hub's receive
- window tightened first (Q2). *Recommend: 128 for v1, raise with
- measurement.*
-2. **Tighten the hub's per-stream receive window from 4 MiB to 1 MiB?**
- It bounds the hub's memory for slow readers on plain and upgraded
- traffic alike, at some cost to single large downloads from distant
- boxes. *Recommend: not in this change; a follow-up if a box ever needs
- more than 128 sockets.*
-3. **`-tunnel` hand rows get WebSockets too.** Same transport, no extra
- code, and no hub policy for those kinds, as on platform boxes.
- *Recommend: yes.*
-4. **Add an Action Cable channel to `examples/rails-shop`** (a
- `PingsChannel` streaming "pings", and a page subscription) so "Enqueue
- a job" updates live: the guide's demo, and a fuller live check (§8.3
- step 3). Needs a reship of shop on dev. *Recommend: yes, as the last
- task.*
-5. **File §10.1 (client address on fleet apps) as its own discussion.**
- *Recommend: yes.*
+ chain is trusted only on a verified hop, `:1441`). What the app sees
+ (`request.remote_ip`, its logs, any rate limiting it does itself) is
+ the hub for every fleet app. The platform's own analytics and rate
+ limits are not affected: both run at the hub, which has the real
+ client, and the box skips them for tunneled requests
+ (`analytics.go:117`, `ratelimit.go:130`). Applies to plain and
+ upgraded requests. Filed as #476.
+2. **Withdrawn (R1-5).** Rev 1 said `bufferedConn`
+ (`tunnelclient.go:173-178`) could hide the tunnel's TLS state on a
+ timing race. It cannot, on the pinned versions. The hub flushes its
+ 101 before it builds the HTTP/2 client (`tunnel.go:197-203`), which
+ flushes the preface separately (`x/net/http2/transport.go:539-543`).
+ `crypto/tls` writes each flush as its own record (`conn.go:1254`) and
+ returns application data from one record per `Read` (`conn.go:1392-1403`),
+ so the box's `ReadResponse` buffers nothing past the 101, `Dial`
+ returns the `*tls.Conn` itself, and x/net sees its TLS state
+ (`http2/server.go:336-338`). No change. A defensive
+ `ConnectionState` forward on `bufferedConn` would be wrong as rev 1
+ sketched it: the same wrapper carries plaintext connections in tests,
+ and a zero TLS state makes x/net reject the connection
+ (`http2/server.go:336-351`).
+
+## 11. Decisions (controller, platform-60)
+
+Rev 1's five open questions, as ruled:
+
+1. Cap of 128 open upgrades per fleet box in v1 (§4.8).
+2. The hub's per-stream receive window stays at 4 MiB for now.
+3. `-tunnel` hand rows get WebSockets too.
+4. Add an Action Cable channel to `examples/rails-shop` (a
+ `PingsChannel` and a page subscription) as the plan's last task, so
+ "Enqueue a job" updates live (§8.3 step 3).
+5. The client-address finding is its own discussion (#476).
+
+Round 1's rulings: every open upgrade records the tenancy that admitted
+it and is swept after every Reload's swap, synchronised with admission
+(§4.6.1); one reservation released exactly once (§4.6.2); the restart
+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.
## 12. Rollout