Repository navigation
Keep small daemon messages ahead of bulk data; stream file chunks as binary - #7874
Merged
ymichael merged 1 commit intoNov 20, 2026
Conversation
This was referenced Nov 20, 2026
ymichael
added a commit
that referenced
this pull request
Nov 20, 2026
#7883) ## Human comments ## What was wrong The daemon sent every terminal's output over the shared session WebSocket, whether or not a client was attached. Output was paced only when a visible browser that acknowledges output was attached: the server turned `terminal.flow-control` on only for such a client. With no client attached, nothing pushed back on the PTY. The server dropped output nobody was watching (`hasTerminalClients` is false), but it had already crossed the link. On a slow route a flooding terminal filled the daemon's 32 MiB send queue (`TERMINAL_SOCKET_MAX_QUEUE_BYTES` in `server-connection.ts`). The daemon then abandoned its session with `terminal-backpressure`, reconnected, and overflowed again about 0.6 s later. The terminal kept flooding across reconnects, so this never ended. Every RPC, terminal and agent turn on that host failed. The same unpaced path applied to attached clients that were hidden, stalled, or did not send acks. Found by the #6748 transport work. ## What changed **The server subscribes to terminal output** (`apps/server/src/services/terminals/terminal-output-flow-control.ts`, `terminal-session-lifecycle.ts`). - Just before it attaches a client, the server sends `terminal.stream` with `enabled: true`. It also sends it before catching clients up after a daemon reconnect. - It sends `enabled: false` when the last client detaches or its attach fails. - Every client counts as a subscriber, including clients that do not send acks. - Output from a daemon session other than the one being streamed is ignored. **The daemon keeps unsubscribed output local** (`apps/host-daemon/src/terminals/terminal-manager.ts`). - Output from a terminal that is not streamed goes only into the existing scrollback ring (4 MiB / 10k chunks per terminal). - Clients get that output from the attach replay, which already happened on every attach. Nothing is sent before a client attaches. - The PTY is not paused, so background processes such as dev servers keep running. - A dropped daemon session stops every stream (`releaseOutputStreams`). **A streamed terminal is always paced by acks.** - The existing 1 MiB unacknowledged window, which pauses the PTY, now applies to every streamed terminal. - When no visible, acknowledging client paces the terminal (hidden, stalled, or no acks), the server acknowledges output as it receives it. The PTY then runs at link rate instead of filling the queue. - A paused PTY whose process has exited is resumed, but streaming continues, so a watching client still gets the final output. - Closing a terminal no longer drops pacing. The exit poll already resumes a paused PTY once its process dies. **Wire change:** `terminal.flow-control` is replaced by `terminal.stream` (same fields, new meaning: when disabled, the daemon does not send output). `HOST_DAEMON_PROTOCOL_VERSION` 272 → 273. **Docs:** "Terminal Output Streaming" in `docs/debugging-and-qa.md`. **Interaction with #7874.** #7874 rewrites the daemon send path (per-stream queues, adaptive window), and it keeps a session-wide queue limit that drops the session. This PR does not touch `server-connection.ts`. It changes what terminal output enters that path: nothing for terminals without a client, and at most a 1 MiB window per streamed terminal. The two compose. #7874 gets RPCs ahead of the bounded terminal windows; this PR keeps those windows bounded. Both bump the protocol to 273, so whichever lands second needs 274. ## How you verified **Live repro.** Ran an isolated `start:worktree` server and a second enrolled daemon behind the #6748 shaping proxy (45 ms RTT, 3.6 MB/s, 512 KiB queue). A script created 16 host-path terminals running `while :; do head -c 1048576 /dev/urandom | base64; done` without attaching to them, probed `paths/exist` every 250 ms, then attached one flooding terminal and ran keystroke echo on a `cat` terminal. origin/main (9f4c156): the daemon overflowed before the second terminal opened. Terminal create returned `502 host_disconnected`, every RPC returned 502, and the loop continued until the daemon was stopped. One terminal was enough. Daemon log: ``` 1795142862290 Connected to server {'sessionId': 'hses_xgjz87jcm3'} 1795142899046 Terminal websocket output queue exceeded its limit {'pendingBytes': 33481827} 1795142899046 Disconnected from server {'reason': 'terminal-backpressure'} 1795142899381 Connected to server {'sessionId': 'hses_2qmg5bkksu'} 1795142899707 Terminal websocket output queue exceeded its limit {'pendingBytes': 33488130} 1795142899707 Disconnected from server {'reason': 'terminal-backpressure'} 1795142900095 Connected to server {'sessionId': 'hses_kpyh8hfqka'} ... (16 overflows in ~11 s) ``` This branch: 0 overflows and 0 disconnects (one connect at daemon start). ``` {"phase":"baseline-rpc-ms","samples":[57.8,52.2,52,51.9,52.6,52.3,54.1,57.4]} {"phase":"created","terminals":16} {"phase":"rpc-during-flood","n":102,"failures":[],"medianMs":51.4,"p95Ms":52.6,"maxMs":52.7} {"phase":"terminal-statuses","statuses":{"running":16}} {"phase":"attach-flooding-terminal","attached":{"replayStartSeq":8291,"nextSeq":8300},"bytesIn3s":8403996,"gaps":0} {"phase":"interactive-echo-ms-during-flood","samples":[53.7,48.9,54.5,53,47.9,56.2,54.2,48.8,47.9,48]} ``` - The shaper tally confirms that no `terminal.output` crossed the link until a client attached. - The attached flood then streamed at link rate (8.4 MB in 3 s) with no sequence gaps. The attach replay held the 512 KiB tail. **Unpaced clients:** 8 flooding terminals, 4 attached without acks and 4 hidden, for 25 s. 68 MB was delivered at link rate, with 0 RPC failures and 0 disconnects. RPC latency was median 782 ms here: RPCs wait behind 8 × 1 MiB of bounded terminal windows. That is the head-of-line blocking #7874 removes. On origin/main this path sends unpaced, the same way as the unattached flood. **Agent turn and UI**, with the 16 unattached floods running on the shaped host: - A thread on that host provisioned and completed a Codex turn in ~4 s. - In the web app's terminal panel (headless Chromium), typed commands echoed. `seq 1 200000; echo BURST-DONE` rendered to the end. - After a page reload, the re-attached terminal showed the scrollback tail ending at `BURST-DONE`. - CLI `terminal run`, `create`/`send`/`wait`/`resize`/`output`/`close` passed on that host. **Tests:** - `terminal-manager.test.ts`, "keeps a flood bounded in scrollback without sending it until the server streams the terminal": 16 MiB of output without a stream sends no `terminal.output`, never pauses the PTY, and replays a ≤ 4 MiB tail ending at the latest output. Output after `terminal.stream` is sent live. With the daemon's "no stream, no send" guard removed, this test and the release test fail. - Also new or updated: an exited paused PTY still delivers its tail; a closing paced terminal delivers its final output; releasing the session stops streaming and pacing. - `terminal-output-flow-control.test.ts`: the stream is enabled only while a client is subscribed; pacing by the fastest visible client; receipt acks when no client paces; receipt acks for a stalled client until it catches up; re-binding to a reconnected daemon session while ignoring the old one. - `public-terminals.test.ts`: `terminal.stream` precedes `terminal.attach` for browser attaches and reconnect catch-up; a non-acking browser gets receipt acks. - `pnpm exec turbo run typecheck lint lint:type-aware test --filter=@bb/host-daemon --filter=@bb/server --filter=@bb/host-daemon-contract`: all green (host-daemon 887, server 4343, contract 92 tests). > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 20, 2026
…7881) ## Human comments ## What was wrong `/internal/ws` (host daemons) and `/ws/terminals/:id` always declined `permessage-deflate` (`declineWebSocketCompression`). #6209 compressed only the browser `/ws`. So terminal output (base64 inside JSON, 1.4× the decoded bytes) and daemon RPC traffic crossed LAN, Tailscale and other direct routes at full size. On a 3.6 MB/s link a text-heavy terminal topped out at ~2.4 MB/s and buried replies behind it. Measured in the #6748 transport report: level-1 deflate brings terminal text to ~33% of its wire bytes. ## What changed - **Server** (`apps/server/src/ws/compression.ts`, `server.ts`): - Terminal and daemon sockets reuse #6209's mechanism: level 1, 1 KB threshold. - They decline compression only when the peer is on this machine: a loopback address with no `X-Forwarded-For`/`Forwarded` header (`declineSameMachineWebSocketCompression`). Requests forwarded by a local proxy such as Tailscale Serve count as remote. - `DaemonChannel` and the terminal send path now pass `compress: true`. hono's ws adapter otherwise sends uncompressed even when compression was negotiated. - **Daemon** (`apps/host-daemon/src/websocket-constructor.ts`, `server-connection*.ts`): - Daemons offer level-1 compression above 1 KB, like the server. - `host.read_file_chunk` replies go out uncompressed through a new `sendUncompressed`. partysocket's `send` drops ws options, so this writes to the underlying ws directly. - Deflating file bytes made fast-link downloads 4× slower (~120 → ~31 MB/s on the first build of this PR) and saved little on media. - **Protocol bump to 274.** Compression is negotiated per connection by the WebSocket handshake, and shipped daemons already offer `permessage-deflate` (the `ws` default) and handle it. But with `ws` defaults they compress every frame at level 6, file chunks included: against this server, 30 MB downloads through a pre-PR daemon on an unconstrained link ran at ~31 MB/s (random) / ~40 MB/s (text) instead of ~120 MB/s. The bump makes enrolled daemons update to the level-1 sender that leaves file chunks uncompressed. - Older servers keep declining. - **Docs:** the compression paragraph in `docs/configuration.md`. - **Not covered: bb connect.** The connect relay re-frames WebSocket messages; its tunnel client opens the origin socket with `perMessageDeflate: false`. Event POST bodies (HTTP) are also unchanged. ## How you verified **Numbers.** I used the #6748 harness on one M4 Mac, with an origin/main `base` stack and this branch. Each isolated `start:worktree` server was bound to `0.0.0.0`. Each client daemon reached its server through the shaping proxy at the machine's LAN address (non-loopback, so compression applies). Runs were interleaved base/branch with the order alternating per round. - Cells are median/p95 in ms; "·" separates the two rounds. - Text flood = `find apps/server/src -name '*.ts' | head -400 | xargs cat` in a loop. - The measuring client (the browser's role) talked to the server over loopback, so these rows compress only the daemon leg. | route | metric | origin/main | this PR | |---|---|---|---| | relay 45 ms / 3.6 MB/s | text flood MB/s | 1.99 · 2.41 | **7.80 · 7.81** | | | RPC during text flood | 211/344 · 226/373 (n=83, 62) | **101/378 · 109/120** (n=113, 126) | | | file download MB/s | 2.19 · 2.14 | 2.13 · 2.14 | | | idle RPC / echo (n=100) | 51/55 · 51/52 / 50/54 · 49/50 | 51/57 · 51/52 / 51/64 · 49/50 | | far relay 120 ms / 3.6 MB/s | text flood MB/s | 2.39 · 2.40 | **4.33 · 4.35** | | | RPC during text flood | 247/379 · 247/374 (n=58, 58) | **125/191 · 125/186** (n=106, 107) | | LAN emulation 3 ms / 25 MB/s | text flood MB/s | 16.69 · 16.78 | **47.94 · 46.65** | | | RPC during text flood | 41/50 · 41/51 (n=219, 218) | **16/21 · 15/19** (n=304, 308) | | | file download MB/s | 13.40 · 13.22 | 13.35 · 13.21 | | unshaped LAN address | file download MB/s | 129.0 · 123.7 | 121.3 · 127.8 | | | text flood MB/s | 47.4 · 49.2 | 45.1 · 49.0 | | | RPC during text flood | 4.7/6.6 · 4.4/6.2 (n=366, 368) | 14/19 · 15/19 (n=312, 307) | Wire bytes on the daemon leg for the same text flood (proxy tally): 1.42 bytes per decoded terminal byte on main vs 0.44 here (3.2× fewer). **Cost.** - **Latency on an unconstrained fast link.** During a sustained ~50 MB/s text flood, a reply on the same socket waits ~15 ms instead of ~5 ms. Deflate and inflate run in order per socket, and main lets up to 1 MiB of terminal output queue ahead of a reply. With #7874 applied (local merge, same runs), that goes to ~11.5 ms. The relay text flood keeps 7.7 MB/s, and replies during it take 58/66 ms instead of 209/363 ms. - **CPU.** 16 concurrent text-flooding terminals, browser client and daemon both on the LAN address (so the browser terminal sockets are compressed too), 20 s per run: | link | | origin/main | this PR | |---|---|---|---| | unshaped | terminal output | 65.7 · 61.8 MB/s | 49.7 · 49.4 MB/s | | | server CPU | 104% · 103%; 16 · 17 ms per MB | 152% · 151%; 30 · 31 ms per MB | | | daemon CPU | 96% · 93%; 15 · 15 ms per MB | 130% · 130%; 26 · 26 ms per MB | | 25 MB/s | terminal output | 17.2 · 17.2 MB/s | **49.2 · 49.4 MB/s** | | | server CPU | 33% · 31%; 19 · 18 ms per MB | 151% · 151%; 31 · 31 ms per MB | - Compression roughly doubles server CPU per terminal megabyte (~16 → ~31 ms/MB, about 1.5 cores at 16 saturated terminals). - On a link that is not the bottleneck it lowers peak aggregate terminal throughput by ~22%. On a 25 MB/s link it delivers 2.9× the output. - Same-machine sockets are unaffected. **Tests:** - `websocket-compression.test.ts`: a forwarded or remote peer gets compressed daemon and terminal sockets. A 400-entry daemon message crosses in < 1/4 of its bytes; this fails without the `compress: true` send flag. Loopback peers still decline. The same-machine rule is covered for IPv4, IPv6, IPv4-mapped and forwarded cases. - `server-connection-support.test.ts`: against a real compressing `ws` server, a normal send compresses (< 1/4) and `sendUncompressed` does not. - `server-connection.test.ts`: `host.read_file_chunk` replies take the uncompressed path; other replies do not. **Commands:** - `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`: 11/11. - `pnpm exec turbo run test --filter=@bb/server --filter=@bb/host-daemon`: server 4344 passed, host-daemon 885 passed. These ran before the uncompressed-chunk change; I reran the affected daemon files after it (`server-connection*.test.ts`, `websocket-constructor.test.ts`, `app.test.ts`). **Live check.** I used an isolated instance with a second daemon on the LAN address behind the 45 ms / 3.6 MB/s shaper, and the app loaded from the LAN address in a browser: - A Claude Code turn with an uploaded attachment returned its token and ran a command in the client host's workspace. - A file preview opened. - A terminal printed `bb6748-42`, `19999`, `20000` for `echo bb6748-$((6*7)) && seq 1 20000 | tail -2`. **Interaction with #7874.** The two PRs merge with conflicts in the daemon send path; they are independent but touch the same lines. Whichever lands second should keep #7874's binary chunk frames out of compression. In the local merge I measured, the rule "compress text frames only" in the ws `send` override replaces `sendUncompressed`. Refs #6748 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/6748-daemon-socket-fairness-binary-chunks-compre-thr_6xtgkb7avh
branch
from
November 20, 2026 19:52
be2855f to
51c5b54
Compare
…binary The daemon's session WebSocket carried RPC replies, keystroke echo, heartbeats and events in the same FIFO as 1.4 MB file-chunk frames and up to 1 MiB of terminal output per streamed terminal, so a small message waited for all of it: on a 45 ms / 3.6 MB/s relay link replies took ~400 ms during a download. - Daemon send queue: terminal output and file-chunk replies queue per terminal or per RPC and take turns; everything else, and stream messages under 4 KiB with nothing queued, goes straight out. - Bulk is written only while ws buffers <= 64 KiB and the unacknowledged bulk fits an adaptive send window (64 KiB-4 MiB, Vegas-style on ack round trips of full frames). The server now acknowledges every 32 KiB. - host.read_file_chunk returns raw bytes in a binary frame (no base64), 64 KiB per RPC, with the server keeping 16 reads in flight. - The daemon compresses text frames only; binary chunk frames go out uncompressed, replacing sendUncompressed. - HOST_DAEMON_PROTOCOL_VERSION 276. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/6748-daemon-socket-fairness-binary-chunks-compre-thr_6xtgkb7avh
branch
from
November 20, 2026 20:45
51c5b54 to
c5cadc6
Compare
ymichael
deleted the
bb/6748-daemon-socket-fairness-binary-chunks-compre-thr_6xtgkb7avh
branch
November 20, 2026 21:46
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Everything a daemon sends to the server shares one session WebSocket, and the daemon wrote it in arrival order. A file download sent each 1 MiB chunk as one ~1.4 MB base64-in-JSON frame. A streamed terminal can have up to 1 MiB of unacknowledged output in flight (#7883), and the daemon handed it to the socket until 1 MiB sat in its buffer; more sat below that in kernel and network buffers. A small RPC reply, keystroke echo, heartbeat or event behind that data waited for it to drain. On current main, with #7881's compression and #7883's paced streaming, replies on a 45 ms / 3.6 MB/s relay link take ~414 ms during a download and ~250 ms during a terminal flood (55 ms idle). File transfer was also slow because it ran one 1 MiB RPC at a time and paid 1.34× in base64. Measured in the #6748 transport report.
What changed
apps/host-daemon/src/session-send-queue.ts,server-connection.ts). Terminal output andhost.read_file_chunkreplies are bulk. They queue per terminal or per chunk RPC, and the queues take turns. Everything else goes straight out: RPC replies, heartbeats, events, and stream messages under 4 KiB whose stream has nothing queued (keystroke echo). A terminal's exit, error and replay messages stay behind its own queued output.apps/host-daemon/src/stream-send-window.ts). Bulk is written only while the ws buffer holds ≤ 64 KiB and the bulk the server has not acknowledged fits a window. The window adapts between 64 KiB and 4 MiB, ±64 KiB per round trip, Vegas-style:bufferedAmount, bounds what sits in kernel and network buffers ahead of a reply.host.read_file_chunkreturns raw bytes:encodeHostDaemonDaemonWsMessage/decodeHostDaemonDaemonWsMessage) movesresult.contentinto and out of the binary part.HOST_FILE_CHUNK_MAX_BYTES).createFileStreamResponsekeeps up to 16 daemon reads in flight and still delivers in order. A failed chunk aborts the reads still in flight.sendcompresses text frames only, so binary chunk frames are never deflated. This replaces Compress daemon and terminal WebSockets for peers on another machine #7881'ssendUncompressedpath and keeps its behaviour: file bytes cross uncompressed, everything else as before.HOST_DAEMON_PROTOCOL_VERSION275 → 276. Changed: the chunk result type, the binary frames, and the ack cadence.docs/debugging-and-qa.md(chunk transfer and send order).Not changed: the server → daemon direction still writes in order. Its bulk (attachments, plugin artifacts) goes over separate HTTP requests.
How you verified
Numbers. I used the #6748 measurement harness and its shaping proxy (FIFO bottleneck, 512 KB queue) on one M4 Mac, at host load ~2.
81b1f612632(includes Compress daemon and terminal WebSockets for peers on another machine #7881 and Stream terminal output to the server only while a client is subscribed #7883) and this branch. Each ran an isolatedstart:worktreeserver bound to0.0.0.0, with its own client daemon reaching it through the shaper at the LAN address. The route is non-loopback, so Compress daemon and terminal WebSockets for peers on another machine #7881 compression is on in both stacks.head -c 1M /dev/urandom | base64in a loop. "Text flood"cats 400 TypeScript files in a loop (compresses ~3×).Relay, 45 ms / 3.6 MB/s:
Far relay, 120 ms / 3.6 MB/s:
LAN emulation, 3 ms / 25 MB/s:
Unshaped LAN address (~loopback speed):
Known cost. On the relay, text-heavy output that competes with interactive traffic moves a little slower:
Why an adaptive window. Measured, not assumed:
Tests:
wsserver, text frames are compressed and binary frames are not.StreamSendWindow: grows at base delay; settles near path capacity; backs off when delay jumps; ignores small-frame round trips.Commands:
pnpm exec turbo run typecheck lint --filter='...[origin/main]': 144/144.pnpm exec turbo run test --filter=@bb/host-daemon-contract --filter=@bb/host-daemon --filter=@bb/server: contract 94, daemon 896, server 4368 passed.turbo run typecheck lint test --filter=@bb/host-daemon: 8/8.Live check. On the earlier revision of this branch I ran an isolated instance with a second daemon behind the 45 ms shaper: an agent turn with an attachment, a file preview, and a terminal in the app. On this rebase:
shasumof the source.Refs #6748
🤖 Generated with Claude Code