carlos / platform Public

edge: refuse sockets to a full stream pool before dialling

Review round 2 (#1535).

An upgrade request (isUpgradeRequest) toward a box whose stream pool is
already full is answered backhaul-streams-busy 503 + Retry-After 2 with
no dial and no request slot, counted as a stream shed. It is advisory
and only refuses; the stream slot is still taken at the 101, which is
refused there if the pool filled in between. Both refusals share one
answer helper and one log key.

A 101 refused by local stream admission still runs the hop's response
observation, so a forward notes the destination's 101 and does not mark
a healthy destination suspect. The doc states the sender's cost per
destination box.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0ac9f0e35a57c03bc7c007c0a720d8ba81fd69e1 parent fb535eb
2 files changed, +183 −15
  • internal/edge/backhaul_streams_test.go +130 −4
  • internal/edge/edge.go +53 −11
diff --git a/internal/edge/backhaul_streams_test.go b/internal/edge/backhaul_streams_test.go
index 728cd7629..aaa9a630a 100644
--- a/internal/edge/backhaul_streams_test.go
+++ b/internal/edge/backhaul_streams_test.go
@@ -8,6 +8,7 @@ package edge
import (
"bufio"
"context"
+ "crypto/tls"
"errors"
"fmt"
"io"
@@ -594,8 +595,9 @@ func peerFront(t *testing.T, e *Edge) *httptest.Server {
// The incident, end to end through the real backhaul handler: more open
// WebSockets than the request pool has slots, each moved to the stream pool
// at its 101, and ordinary GETs to the same home box still succeed. Then the
-// stream pool saturates: the next 101 is refused with 503 + Retry-After 2,
-// no slot leaks in either pool, and a socket that ends gives its slot back.
+// stream pool saturates: the next socket is refused before it dials with
+// 503 + Retry-After 2, no slot leaks in either pool, and a socket that ends
+// gives its slot back.
func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
e, m, _ := hopEdge(t, "annie", "local.test")
const n = 3
@@ -645,8 +647,8 @@ func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
t.Fatalf("socket over the stream cap: %+v, want 503 + Retry-After 2 from backhaul-streams-busy", refused)
}
io.Copy(io.Discard, refused.Body)
- if rec.get().n != homeSaw+1 {
- t.Fatal("the refused socket never reached the home: it must be refused at the 101, not at admission")
+ if rec.get().n != homeSaw {
+ t.Fatal("the socket over a full stream pool reached the home: it must be refused before the dial")
}
if got := e.BackhaulSheds(); got.Streams != 1 || got.Requests != 0 {
t.Fatalf("BackhaulSheds = %+v, want one stream shed", got)
@@ -768,3 +770,127 @@ func TestBackhaulStreamDoorExempt(t *testing.T) {
t.Cleanup(rel)
}
}
+
+// armHopObserve runs fn once, on the first hop event named event: the
+// moment after admission and before the dial (hopTo).
+func armHopObserve(t *testing.T, event string, fn func()) {
+ t.Helper()
+ var once sync.Once
+ hook := func(ev, _ string) {
+ if ev == event {
+ once.Do(fn)
+ }
+ }
+ regionalObserve.Store(&hook)
+ t.Cleanup(func() { regionalObserve.Store(nil) })
+}
+
+// The advisory check: with the stream pool already full, an upgrade request
+// is refused before it dials or takes a request slot, while an ordinary GET
+// to the same box is untouched.
+func TestBackhaulUpgradeRefusedBeforeDialWhenStreamsFull(t *testing.T) {
+ e, m, _ := hopEdge(t, "annie", "local.test")
+ backhaulStreamCap(t, 1)
+ rec, eip := fakeHomeEdge(t, wsHome(t, nil))
+ homedOn(t, m, "betty", eip, "example.com")
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ rel, ok, _ := e.backhaulAcquireStream("betty", "")
+ if !ok {
+ t.Fatal("stream slot refused")
+ }
+ t.Cleanup(rel)
+
+ c, resp := openBackhaulSocket(t, srv, "")
+ if c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" ||
+ resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" {
+ t.Fatalf("socket toward a full stream pool: %+v, want 503 + Retry-After 2 from backhaul-streams-busy", resp)
+ }
+ if n := rec.get().n; n != 0 {
+ t.Fatalf("the home saw %d request(s), want none: no dial", n)
+ }
+ if got := e.BackhaulSheds(); got != (BackhaulSheds{Streams: 1}) {
+ t.Fatalf("BackhaulSheds = %+v, want one stream shed", got)
+ }
+ if got := poolCount(&e.backhaulInflight, "betty"); got != 0 {
+ t.Fatalf("request pool = %d, want 0: the refusal took no request slot", got)
+ }
+ resp2, err := backhaulGetter(t, e)("example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp2.Body.Close()
+ if resp2.StatusCode != http.StatusOK {
+ t.Fatalf("GET with the stream pool full: %d, want 200", resp2.StatusCode)
+ }
+}
+
+// The race the advisory check cannot see: the stream pool has room at
+// admission and fills before the home's 101. The 101 is refused, the home
+// was reached, and neither pool leaks.
+func TestBackhaulStreamRaceRefusedAt101(t *testing.T) {
+ e, m, _ := hopEdge(t, "annie", "local.test")
+ backhaulStreamCap(t, 1)
+ rec, eip := fakeHomeEdge(t, wsHome(t, nil))
+ homedOn(t, m, "betty", eip, "example.com")
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ armHopObserve(t, "backhaul", func() {
+ rel, ok, _ := e.backhaulAcquireStream("betty", "")
+ if !ok {
+ t.Error("the racing stream slot was refused")
+ return
+ }
+ t.Cleanup(rel)
+ })
+
+ c, resp := openBackhaulSocket(t, srv, "")
+ if c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" {
+ t.Fatalf("socket that lost the race: %+v, want the 503 at its 101", resp)
+ }
+ if n := rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d request(s), want 1: refused at the 101", n)
+ }
+ if got := e.BackhaulSheds(); got != (BackhaulSheds{Streams: 1}) {
+ t.Fatalf("BackhaulSheds = %+v, want one stream shed", got)
+ }
+ waitFor(t, 10*time.Second, "the request slot back", func() bool {
+ return poolCount(&e.backhaulInflight, "betty") == 0
+ })
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 1 {
+ t.Fatalf("stream pool = %d, want only the racing slot", got)
+ }
+}
+
+// A forward whose destination answers 101 but whose stream slot is refused
+// here is still noted as the destination's 101: a local refusal must not
+// mark a healthy destination suspect.
+func TestForwardHAStreamRefusalAt101NotesTheDestination101(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ backhaulStreamCap(t, 1)
+ armHopObserve(t, "forward", func() {
+ rel, ok, _ := x.a.edge.backhaulAcquireStream("betty", "")
+ if !ok {
+ t.Error("the racing stream slot was refused")
+ return
+ }
+ t.Cleanup(rel)
+ })
+ raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 10*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := tls.Client(raw, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12})
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", fwHost)
+ resp, err := http.ReadResponse(bufio.NewReader(c), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" {
+ t.Fatalf("handshake = %d (%s), want the stream pool's 503", resp.StatusCode, resp.Header.Get("X-Carlos-Answer"))
+ }
+ laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 })
+ x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty", Status: http.StatusSwitchingProtocols}})
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 75702ba21..367d5c0da 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4738,17 +4738,21 @@ const defaultBackhaulMaxInflight = 128
// client key) and give the request slot back (backhaulStreamAt101). A
// stream pool with no room fails the hop there: the backend connection is
// closed and the client gets 503 + Retry-After: 2, or the 429 for a share
-// refusal. So a stream slot is only ever a real upgraded socket.
+// refusal. So a stream slot is only ever a real upgraded socket. An upgrade
+// request toward a box whose stream pool is already full is refused the
+// same way before it dials (hopTo), so retries against a full pool cost no
+// request slot and never reach the app.
//
// What a socket costs, estimated and not measured: about 100 KB per upgraded
// hop on each of the two boxes, from the proxy's two 32 KiB copy buffers,
// the TLS state and three goroutines. A full default pool is about 50 MB on
-// the sender and the same on the home box per sending sibling. The home box
-// carries that same cost for a visitor who opens the socket to it directly,
-// and it has no cap on direct upgrades (planthrottle.go's refusal of a
-// throttled account aside), so a relayed socket adds no exposure beyond the
-// same visitors connecting directly. The sum over the home box's siblings is
-// the worst case.
+// the home box per sending sibling. The sender pays the same per
+// destination box, so its own worst case is that times the number of home
+// boxes it forwards to. The home box carries that same cost for a visitor
+// who opens the socket to it directly, and it has no cap on direct upgrades
+// (planthrottle.go's refusal of a throttled account aside), so a relayed
+// socket adds no exposure beyond the same visitors connecting directly. The
+// sum over the home box's siblings is its worst case.
//
// Not reclassified in this slice: a long-lived response to an ordinary
// request (server-sent events, a long poll) still holds a request-pool slot
@@ -5041,6 +5045,18 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri
// Containment (the egress ruling, 2026-08-24), between the last guard and
// the dial: backhaulAdmit answers a refused hop itself. Every hop starts
// on a request slot, upgrade request or not (backhaulMaxStreams).
+ //
+ // An upgrade request toward a box whose stream pool is already full is
+ // refused first, with no dial: it could only be refused at its 101, after
+ // holding a request slot for the handshake and reaching the app. This is
+ // advisory, and only ever refuses: the header admits nothing, and the
+ // stream slot is still taken at the 101, which is refused there if
+ // another socket took the last slot in between.
+ if isUpgradeRequest(r) && e.backhaulStreamsFull(box) {
+ e.refuseBackhaulStream(box, eip)
+ answerBackhaulStreamsBusy(w)
+ return false
+ }
clientKey := e.backhaulClientKey(r)
releaseSlot, ok := e.backhaulAdmit(w, r, eip, box)
if !ok {
@@ -5080,11 +5096,17 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri
// ModifyResponse makes the proxy close the backend connection (the 101's
// body) and call ErrorHandler, which answers it below, before any other
// error handling (a retry must not take a refused upgrade elsewhere).
+ // The destination did answer, and well: onResponse still sees its 101,
+ // so a forward's health observation (forwardHAObserved) records a
+ // success and not a destination failure. Only the scrub is skipped.
modify := p.ModifyResponse
p.ModifyResponse = func(resp *http.Response) error {
if resp.StatusCode == http.StatusSwitchingProtocols {
stream, err := e.backhaulStreamAt101(box, eip, clientKey)
if err != nil {
+ if onResponse != nil {
+ onResponse(resp)
+ }
return err
}
request := slot
@@ -5102,7 +5124,7 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri
case errors.Is(err, errBackhaulStreamShare):
writeRateLimited(w, time.Second)
case errors.Is(err, errBackhaulStreamsBusy):
- Unavailable(w, "backhaul-streams-busy", "temporarily busy", 2)
+ answerBackhaulStreamsBusy(w)
case fail != nil:
fail(w, r, err)
default:
@@ -5172,14 +5194,34 @@ func (e *Edge) backhaulStreamAt101(box, eip, clientKey string) (releaseSlot func
e.backhaulShed.fairShare.Add(1)
return nil, errBackhaulStreamShare
case !ok:
- e.backhaulShed.streams.Add(1)
- e.logThrottled("backhaul-streams-saturated "+box,
- fmt.Sprintf("backhaul to %s (%s) is at its stream cap (%d open WebSockets); answering 503 with Retry-After: 2", box, eip, backhaulMaxStreams.Load()))
+ e.refuseBackhaulStream(box, eip)
return nil, errBackhaulStreamsBusy
}
return releaseSlot, nil
}
+// backhaulStreamsFull reports whether box's stream pool is at its cap now:
+// hopTo's advisory refusal of an upgrade request before it dials. A read of
+// the counter, so it can be stale either way; the 101 decides.
+func (e *Edge) backhaulStreamsFull(box string) bool {
+ v, ok := e.backhaulStreamInflight.Load(box)
+ return ok && v.(*atomic.Int64).Load() >= backhaulMaxStreams.Load()
+}
+
+// refuseBackhaulStream counts and logs one stream-pool saturation, at
+// admission or at the 101, under one per-box log key.
+func (e *Edge) refuseBackhaulStream(box, eip string) {
+ e.backhaulShed.streams.Add(1)
+ e.logThrottled("backhaul-streams-saturated "+box,
+ fmt.Sprintf("backhaul to %s (%s) is at its stream cap (%d open WebSockets); answering 503 with Retry-After: 2", box, eip, backhaulMaxStreams.Load()))
+}
+
+// answerBackhaulStreamsBusy is the stream pool's 503, the one place its
+// site is named (each Unavailable site is one call site).
+func answerBackhaulStreamsBusy(w http.ResponseWriter) {
+ Unavailable(w, "backhaul-streams-busy", "temporarily busy", 2)
+}
+
// backhaulTransport is the cached outbound transport for one home box. The
// TRANSPORT is what is cached and the ReverseProxy above is what is rebuilt
// per request: a proxy value is two closures, while a transport owns the