carlos / platform Public

edge: raise the held-stream cap to 1,000 per host; size PerBox per box

A busy live page on one app was cut off at 64 held streams. PerHost is
now 1,000 (Rastrillo's live hub serves 1,000 per process). PerBox comes
from the box: an eighth of its memory at 256 KiB a stream (measured
232 KiB over TLS and HTTP/2 with the leg open, 95 KiB asleep), never
under PerHost, and within the open-file limit after a reserve.

Streams a tunnel or link channel delivered keep one of the channel's 250
HTTP/2 streams for their life, so they get their own cap of 64 per box;
past it they get the same retry answer.

Witnesses: 200 streams on one host through a real activator and child
(TestHeldE2EManyStreamsOneHost), the per-channel cap through a real hub
and tunnel loop, and the cap arithmetic.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 80d95fa3fbbabf8800f98c1c5a56b8fa4fcafbe3 parent cdf9818
7 files changed, +345 −12
  • internal/activator/heldstream_e2e_test.go +61 −0
  • internal/edge/heldbudget.go +64 −0
  • internal/edge/heldbudget_linux.go +19 −0
  • internal/edge/heldbudget_other.go +7 −0
  • internal/edge/heldstream.go +29 −9
  • internal/edge/heldstream_test.go +86 −3
  • internal/edge/tunnel_e2e_test.go +79 −0
diff --git a/internal/activator/heldstream_e2e_test.go b/internal/activator/heldstream_e2e_test.go
index 23d5e5506..d21e087b4 100644
--- a/internal/activator/heldstream_e2e_test.go
+++ b/internal/activator/heldstream_e2e_test.go
@@ -589,6 +589,67 @@ func TestHeldE2ESleepFastDrain(t *testing.T) {
}
}
+// heldLoadStreams is the load witness's browsers on one host: well past the
+// old per-host cap of 64.
+const heldLoadStreams = 200
+
+// The cap (§3.6, rev 4): one host holds far more than 64 streams on the
+// production caps. heldLoadStreams browsers connect to one asleep host; every
+// one is held by the edge, none is refused, and nothing wakes. A plain
+// request wakes the host: every stream opens its leg on the one child and
+// every browser gets the next event. The streams are still not activity:
+// the instance sleeps again under all of them, and they stay open.
+func TestHeldE2EManyStreamsOneHost(t *testing.T) {
+ idle := 3 * time.Second
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ if h.cfg.PerHost != edge.DefaultHeldConfig.PerHost || h.cfg.PerHost < heldLoadStreams {
+ t.Fatalf("PerHost %d: the witness runs the production cap, at least %d", h.cfg.PerHost, heldLoadStreams)
+ }
+ if h.cfg.PerBox < heldLoadStreams {
+ t.Fatalf("PerBox %d on this machine (its memory or open-file limit), want at least %d", h.cfg.PerBox, heldLoadStreams)
+ }
+ bs := make([]*sseBrowser, heldLoadStreams)
+ cs := make([]*sseConn, heldLoadStreams)
+ for i := range bs {
+ bs[i] = newBrowser(t, h.front.URL, heldPath)
+ cs[i] = bs[i].connect()
+ if cs[i].resp.StatusCode != http.StatusOK || cs[i].ended() {
+ t.Fatalf("browser %d: status %d, ended %v body %q, want a held stream", i+1, cs[i].resp.StatusCode, cs[i].ended(), cs[i].body)
+ }
+ }
+ if st := h.e.HeldStreamStats(); st.Held != heldLoadStreams || st.Hosts[e2eHost] != heldLoadStreams || st.OverCap != 0 {
+ t.Fatalf("held-stream stats %+v, want all %d held for %s and none over a cap", st, heldLoadStreams, e2eHost)
+ }
+ if n := len(h.starts()); n != 0 || !h.asleep() {
+ t.Fatalf("%d child starts with only held streams open, want none", n)
+ }
+
+ pid := h.wake()
+ h.appendEvent("e1")
+ for i, b := range bs {
+ waitE2E(t, 30*time.Second, fmt.Sprintf("browser %d's event", i+1), func() bool { return b.eventCount() >= 1 })
+ ev, _, _ := b.snapshot()
+ wantEvents(t, ev, 1)
+ }
+ if legs := h.liveReqs(pid); len(legs) != heldLoadStreams {
+ t.Fatalf("%d legs on the woken child, want one per stream, %d", len(legs), heldLoadStreams)
+ }
+
+ waitE2E(t, 10*idle, "the instance to sleep under the open streams", h.asleep)
+ h.shutdownOf(pid, 10*time.Second)
+ for i, c := range cs {
+ if c.ended() {
+ t.Fatalf("browser %d's stream ended with the instance's sleep", i+1)
+ }
+ }
+ if st := h.e.HeldStreamStats(); st.Held != heldLoadStreams || st.OverCap != 0 {
+ t.Fatalf("held-stream stats after the sleep %+v, want all %d still held", st, heldLoadStreams)
+ }
+ if n := len(h.starts()); n != 1 {
+ t.Fatalf("%d child starts, want 1 (the plain wake)", n)
+ }
+}
+
// Case 4: events 1-2 relayed; the instance sleeps; a plain request wakes it
// and the test appends event 3. The stream resumes on the new process with
// Last-Event-ID 2, and the browser receives event 3 next, with no duplicate.
diff --git a/internal/edge/heldbudget.go b/internal/edge/heldbudget.go
new file mode 100644
index 000000000..def06c4a2
--- /dev/null
+++ b/internal/edge/heldbudget.go
@@ -0,0 +1,64 @@
+package edge
+
+// The held-stream caps (spec 2026-10-28-edge-held-streams-design.md §3.6,
+// rev 4) and the box budget PerBox comes from.
+
+const (
+ // heldPerHost is the most streams one host holds on one edge. Rastrillo's
+ // live hub serves at most 1,000 streams per process (live.Config
+ // MaxStreams), and an app left at systemd's default soft limit of 1,024
+ // open files cannot take many more, so holding more would only queue
+ // legs the app refuses.
+ heldPerHost = 1000
+
+ // heldStreamCost is the most one held stream is taken to cost the edge in
+ // memory. Measured 2026-11-20 over TLS and HTTP/2, one connection per
+ // browser: about 95 KiB while the host sleeps and 232 KiB with its leg
+ // open (seven goroutines and their buffers); rounded up.
+ heldStreamCost = 256 << 10
+
+ // heldMemoryShare: held streams, every one with its leg open, may take
+ // 1/heldMemoryShare of the box's memory.
+ heldMemoryShare = 8
+
+ // heldStreamFiles is the open files one held stream takes: the browser's
+ // connection, and the leg's while the host is awake.
+ heldStreamFiles = 2
+
+ // heldFileReserve is the open files left for everything else the edge
+ // does before held streams may take any.
+ heldFileReserve = 8192
+
+ // heldPerChannel caps the streams held for requests a tunnel or link
+ // channel delivered (fleet boxes, linked deployments), all channels
+ // together. Each keeps one HTTP/2 stream of its channel open for its life,
+ // and a channel serves 250 at once (tunnelclient.DefaultLimits) for every
+ // request the hub sends: with the hub's 128 upgrades (tunnelUpgradeCap)
+ // this leaves 58 for plain requests. A plain request finding none waits
+ // for one, so without this cap one busy page could stall every app on
+ // the box.
+ heldPerChannel = 64
+)
+
+// heldPerBox is the box's cap on held streams: as many as fit in
+// 1/heldMemoryShare of memBytes at heldStreamCost each, never fewer than
+// heldPerHost so that every box can hold one full host, and never more than
+// the open-file limit nofile leaves room for after heldFileReserve. A zero
+// memBytes or nofile means unknown, and that bound is left out.
+//
+// For scale: 1 or 2 GiB of memory gives 1,000 (the floor), 4 GiB about 2,000,
+// 8 GiB about 4,000 and 16 GiB about 8,000.
+func heldPerBox(memBytes, nofile uint64) int {
+ n := uint64(heldPerHost)
+ if m := memBytes / heldMemoryShare / heldStreamCost; m > n {
+ n = m
+ }
+ if nofile > 0 {
+ f := uint64(0)
+ if nofile > heldFileReserve {
+ f = (nofile - heldFileReserve) / heldStreamFiles
+ }
+ n = min(n, f)
+ }
+ return int(min(n, 1<<30))
+}
diff --git a/internal/edge/heldbudget_linux.go b/internal/edge/heldbudget_linux.go
new file mode 100644
index 000000000..3a9441071
--- /dev/null
+++ b/internal/edge/heldbudget_linux.go
@@ -0,0 +1,19 @@
+package edge
+
+import "syscall"
+
+// heldBoxLimits reads the box's memory and this process's open-file limit
+// for heldPerBox, once, when the package starts. The Go runtime has already
+// raised the soft limit to the hard one by then. Either is 0 when it cannot
+// be read.
+func heldBoxLimits() (memBytes, nofile uint64) {
+ var si syscall.Sysinfo_t
+ if syscall.Sysinfo(&si) == nil {
+ memBytes = uint64(si.Totalram) * uint64(si.Unit)
+ }
+ var rl syscall.Rlimit
+ if syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rl) == nil {
+ nofile = rl.Cur
+ }
+ return memBytes, nofile
+}
diff --git a/internal/edge/heldbudget_other.go b/internal/edge/heldbudget_other.go
new file mode 100644
index 000000000..012d7d34e
--- /dev/null
+++ b/internal/edge/heldbudget_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package edge
+
+// heldBoxLimits is unknown off Linux, where no box runs: heldPerBox then
+// gives heldPerHost.
+func heldBoxLimits() (memBytes, nofile uint64) { return 0, 0 }
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go
index 213c229dc..28092def2 100644
--- a/internal/edge/heldstream.go
+++ b/internal/edge/heldstream.go
@@ -28,8 +28,10 @@ import (
// HeldConfig holds the held-stream bounds and timings. It is exported so
// tests in other packages can shorten it (SetHeldConfig).
type HeldConfig struct {
- // PerHost and PerBox cap the streams held at once (§3.6).
- PerHost, PerBox int
+ // PerHost and PerBox cap the streams held at once (§3.6). PerChannel
+ // caps, within PerBox, the streams held for requests a tunnel or link
+ // channel delivered, all channels together.
+ PerHost, PerBox, PerChannel int
// MaxHold recycles a browser connection; Commit is how long the browser
// may wait for a first response; LegHeader bounds a leg's response
// headers; WriteDeadline bounds one downstream write; Tick is the
@@ -43,8 +45,14 @@ type HeldConfig struct {
ShortLegsToClose int
}
-// DefaultHeldConfig is the spec's values.
-var DefaultHeldConfig = HeldConfig{64, 4096, time.Hour, 2 * time.Second, 10 * time.Second, 10 * time.Second, 25 * time.Second, time.Second, 30 * time.Second, 30 * time.Second, 5}
+// DefaultHeldConfig is the spec's values. PerBox is this box's own, from its
+// memory and open-file limit (heldbudget.go).
+var DefaultHeldConfig = HeldConfig{
+ PerHost: heldPerHost, PerBox: heldPerBox(heldBoxLimits()), PerChannel: heldPerChannel,
+ MaxHold: time.Hour, Commit: 2 * time.Second, LegHeader: 10 * time.Second, WriteDeadline: 10 * time.Second, Tick: 25 * time.Second,
+ ReopenSpacing: time.Second, ShortLeg: 30 * time.Second, BackoffCap: 30 * time.Second,
+ ShortLegsToClose: 5,
+}
// SetHeldConfig replaces the held set with an empty one using c. Call it
// before serving: streams held by the old set are not moved.
@@ -82,6 +90,8 @@ type heldSet struct {
mu sync.Mutex
byHost map[string]map[*heldStream]struct{}
total int
+ // channel is how many of total a tunnel or link channel delivered.
+ channel int
// Counters (spec §3.9), under mu.
everHeld bool
resumes int64
@@ -103,6 +113,7 @@ type heldSet struct {
// goroutines send its task.
type heldStream struct {
host string
+ channel bool // a tunnel or link channel delivered it (PerChannel)
wakeC chan struct{} // buffered 1; a full buffer drops the signal
closeC chan struct{} // closed once by closeHost
closeOnce sync.Once
@@ -112,16 +123,19 @@ func newHeldSet(cfg HeldConfig) *heldSet {
return &heldSet{cfg: cfg, byHost: make(map[string]map[*heldStream]struct{})}
}
-// register adds a stream for host, or returns nil over a cap.
-func (s *heldSet) register(host string) *heldStream {
+// register adds a stream for host, or returns nil over a cap. channel says
+// a tunnel or link channel delivered the request: such a stream keeps one of
+// its channel's HTTP/2 streams open for its life, so they have their own cap
+// (§3.6).
+func (s *heldSet) register(host string, channel bool) *heldStream {
s.mu.Lock()
defer s.mu.Unlock()
s.everHeld = true
- if s.total >= s.cfg.PerBox || len(s.byHost[host]) >= s.cfg.PerHost {
+ if s.total >= s.cfg.PerBox || len(s.byHost[host]) >= s.cfg.PerHost || channel && s.channel >= s.cfg.PerChannel {
s.overCap++
return nil
}
- st := &heldStream{host: host, wakeC: make(chan struct{}, 1), closeC: make(chan struct{})}
+ st := &heldStream{host: host, channel: channel, wakeC: make(chan struct{}, 1), closeC: make(chan struct{})}
m := s.byHost[host]
if m == nil {
m = make(map[*heldStream]struct{})
@@ -129,6 +143,9 @@ func (s *heldSet) register(host string) *heldStream {
}
m[st] = struct{}{}
s.total++
+ if channel {
+ s.channel++
+ }
return st
}
@@ -213,6 +230,9 @@ func (s *heldSet) finish(st *heldStream, r heldCloseReason) {
if _, ok := m[st]; ok {
delete(m, st)
s.total--
+ if st.channel {
+ s.channel--
+ }
}
if len(m) == 0 {
delete(s.byHost, st.host)
@@ -318,7 +338,7 @@ func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Rou
if s.beforeRegister != nil {
s.beforeRegister()
}
- st = s.register(rt.Host)
+ st = s.register(rt.Host, fromTunnel(r.Context()) || linkedRequest(r.Context()))
}
if st == nil {
d := DefaultHeldConfig.WriteDeadline
diff --git a/internal/edge/heldstream_test.go b/internal/edge/heldstream_test.go
index 9b575509d..f59c159bd 100644
--- a/internal/edge/heldstream_test.go
+++ b/internal/edge/heldstream_test.go
@@ -28,7 +28,7 @@ const heldTestHost = "shop.example.com"
// their own.
func heldTestConfig() HeldConfig {
return HeldConfig{
- PerHost: 64, PerBox: 4096,
+ PerHost: 64, PerBox: 4096, PerChannel: 64,
MaxHold: 2 * time.Second, Commit: time.Minute, LegHeader: time.Second,
// The brief's 30 ms write deadline is set only by the tests about
// deadlines; elsewhere a starved test process must not turn a slow
@@ -684,12 +684,95 @@ func TestHeldConfigOnNew(t *testing.T) {
if e.held == nil || e.held.cfg != heldTestConfig() {
t.Fatal("SetHeldConfig did not replace the held set")
}
- if DefaultHeldConfig.MaxHold != time.Hour || DefaultHeldConfig.Tick != 25*time.Second || DefaultHeldConfig.PerHost != 64 ||
- DefaultHeldConfig.PerBox != 4096 || DefaultHeldConfig.ShortLegsToClose != 5 {
+ if DefaultHeldConfig.MaxHold != time.Hour || DefaultHeldConfig.Tick != 25*time.Second || DefaultHeldConfig.PerHost != 1000 ||
+ DefaultHeldConfig.PerBox != heldPerBox(heldBoxLimits()) || DefaultHeldConfig.PerChannel != 64 || DefaultHeldConfig.ShortLegsToClose != 5 {
t.Fatalf("DefaultHeldConfig %+v", DefaultHeldConfig)
}
}
+// PerBox is sized from the box (§3.6): an eighth of its memory at 256 KiB a
+// stream, never under PerHost, and never more than its open files allow
+// after the reserve, two a stream. Zero means unknown.
+func TestHeldPerBox(t *testing.T) {
+ const gib = 1 << 30
+ for _, c := range []struct {
+ mem, nofile uint64
+ want int
+ }{
+ {0, 0, 1000}, // nothing known: one full host
+ {1 * gib, 524288, 1000}, // the floor
+ {1900 << 20, 524288, 1000}, // a 2 GiB box's MemTotal: the floor
+ {2 * gib, 524288, 1024}, // memory decides
+ {3 * gib, 524288, 1536}, // memory decides
+ {16 * gib, 524288, 8192}, // memory decides
+ {64 * gib, 0, 32768}, // no file limit known
+ {16 * gib, 10192, 1000}, // files decide: (10192-8192)/2
+ {16 * gib, 9192, 500}, // files decide, below the floor
+ {16 * gib, 8192, 0}, // nothing past the reserve
+ {0, 1024, 0}, // nothing past the reserve
+ {1 << 62, 1 << 62, 1 << 30}, // clamped to an int on every platform
+ } {
+ if got := heldPerBox(c.mem, c.nofile); got != c.want {
+ t.Errorf("heldPerBox(%d, %d) = %d, want %d", c.mem, c.nofile, got, c.want)
+ }
+ }
+}
+
+// The production per-host cap (§3.6): heldPerHost streams for one host, then
+// the over-cap answer; another host still has room until PerBox.
+func TestHeldSetDefaultCaps(t *testing.T) {
+ cfg := DefaultHeldConfig
+ cfg.PerBox = heldPerHost + 1 // this machine's PerBox is not the subject
+ s := newHeldSet(cfg)
+ for i := range heldPerHost {
+ if s.register("a.example.com", false) == nil {
+ t.Fatalf("stream %d refused under the per-host cap", i+1)
+ }
+ }
+ if s.register("a.example.com", false) != nil {
+ t.Fatalf("stream %d admitted over the per-host cap", heldPerHost+1)
+ }
+ if s.register("b.example.com", false) == nil {
+ t.Fatal("another host refused under the box cap")
+ }
+ if s.register("c.example.com", false) != nil {
+ t.Fatal("admitted over the box cap")
+ }
+ if st, _ := s.stats(); st.Held != heldPerHost+1 || st.Hosts["a.example.com"] != heldPerHost || st.OverCap != 2 {
+ t.Fatalf("stats %+v", st)
+ }
+}
+
+// Streams a tunnel or link channel delivered stop at PerChannel, all hosts
+// together, whatever room PerHost and PerBox leave; streams the box's own
+// listener took are not counted against it; a finished channel stream gives
+// its place back.
+func TestHeldSetPerChannel(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.PerChannel = 2
+ s := newHeldSet(cfg)
+ first := s.register("a.example.com", true)
+ if first == nil || s.register("b.example.com", true) == nil {
+ t.Fatal("channel stream refused under PerChannel")
+ }
+ if s.register("c.example.com", true) != nil {
+ t.Fatal("channel stream admitted over PerChannel")
+ }
+ if s.register("c.example.com", false) == nil {
+ t.Fatal("a direct stream was refused by the channel cap")
+ }
+ s.finish(first, heldCloseClientGone)
+ if s.register("c.example.com", true) == nil {
+ t.Fatal("a finished channel stream did not give its place back")
+ }
+ if s.register("d.example.com", true) != nil {
+ t.Fatal("channel stream admitted over PerChannel after the swap")
+ }
+ if st, _ := s.stats(); st.Held != 3 || st.OverCap != 2 {
+ t.Fatalf("stats %+v, want 3 held and 2 over a cap", st)
+ }
+}
+
func TestStripHoldMarker(t *testing.T) {
for _, c := range []struct {
in, out string
diff --git a/internal/edge/tunnel_e2e_test.go b/internal/edge/tunnel_e2e_test.go
index f6fe04f16..0069cce1a 100644
--- a/internal/edge/tunnel_e2e_test.go
+++ b/internal/edge/tunnel_e2e_test.go
@@ -322,6 +322,85 @@ func TestTunnelForwardsHoldMarkerAndSkipsCache(t *testing.T) {
}
}
+// TestTunnelHeldStreamsCappedPerChannel: a held stream the tunnel delivered
+// keeps one of the channel's HTTP/2 streams for its life, so the box holds
+// at most PerChannel of them (edge-held streams spec §3.6) and answers the
+// next with the over-cap retry, through the real hub and tunnel client loop.
+func TestTunnelHeldStreamsCappedPerChannel(t *testing.T) {
+ const host = "shop.example.com"
+ reg := tunnelRoute(t, registry.Route{
+ Host: host, Kind: "instance", Status: "ready", Tunnel: "pi-box", Hibernate: true,
+ })
+ hubEdge, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(hubEdge)
+ defer srv.Close()
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hub := NewTunnelHub(u.Hostname(), map[string]string{"pi-box": "sekrit"})
+ hubEdge.EnableTunnels(hub)
+ if err := hubEdge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+
+ boxReg := openReg(t)
+ if err := boxReg.Upsert(registry.Route{Host: host, Kind: "instance", Addr: "127.0.0.1:1", Status: "ready", App: "web", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ boxEdge, err := New(boxReg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(boxEdge.probers.Stop)
+ cfg := heldTestConfig()
+ cfg.MaxHold = 30 * time.Second
+ cfg.PerChannel = 1
+ boxEdge.SetHeldConfig(cfg)
+ stop := startFakeRemoteHost(t, srv.URL, "pi-box", "sekrit", boxEdge)
+ defer stop()
+ waitForTunnelState(t, hub, "pi-box", "connected", e2eReconnectBound)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ open := func() *http.Response {
+ t.Helper()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/live?carlos_hold=1", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ req.Header.Set("Accept", "text/event-stream")
+ req.Header.Set("Accept-Encoding", "identity")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("held request through tunnel: %v", err)
+ }
+ t.Cleanup(func() { resp.Body.Close() })
+ return resp
+ }
+ first := open()
+ if got, _ := readFor(first.Body, 300*time.Millisecond); first.StatusCode != http.StatusOK || !strings.Contains(got, ": ping\n") {
+ t.Fatalf("first: status %d body %q, want the box's held stream", first.StatusCode, got)
+ }
+ second := open()
+ body, err := io.ReadAll(second.Body)
+ if err != nil || second.StatusCode != http.StatusOK || string(body) != "retry: 30000\n\n" {
+ t.Fatalf("second: status %d body %q err %v, want the over-cap retry", second.StatusCode, body, err)
+ }
+ if st := boxEdge.HeldStreamStats(); st.Held != 1 || st.OverCap != 1 {
+ t.Fatalf("box held-stream stats %+v, want 1 held and 1 over a cap", st)
+ }
+ if n := act.admits.Load(); n != 0 {
+ t.Fatalf("box activator admitted %d legs for an asleep host", n)
+ }
+}
+
// TestTunnelMarkedResponseNeverStored: the storage half of §7's hub cache
// bypass (whole-branch fix P2-4). The box answers a marked request with a
// finite, explicitly cacheable response, which the hub would store for an