Skip to content

Compress daemon and terminal WebSockets for peers on another machine - #7881

Merged
ymichael merged 3 commits into
mainfrom
bb/6748-daemon-compression-thr_6xtgkb7avh
Nov 20, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/6748-daemon-compression-thr_6xtgkb7avh

Conversation

@ymichael

@ymichael ymichael commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 Compress realtime WebSocket pushes with permessage-deflate #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 Keep small daemon messages ahead of bulk data; stream file chunks as binary #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

ymichael and others added 3 commits November 19, 2026 16:43
/internal/ws and /ws/terminals/:id always declined permessage-deflate, so
terminal output (base64 inside JSON) and daemon RPC traffic crossed LAN,
Tailscale and other direct routes at full size. They now negotiate the same
level-1, 1 KB-threshold compression as the browser /ws when the peer is not
on this machine: a non-loopback address, or a request forwarded by a proxy
(X-Forwarded-For / Forwarded). Same-machine peers stay uncompressed.

- The server compresses daemon frames and terminal output when negotiated.
- Daemons offer level-1 compression and send host.read_file_chunk replies
  uncompressed: deflating file bytes cut fast-link downloads from ~120 to
  ~31 MB/s.
- No protocol bump: compression is negotiated per connection, older daemons
  already offer it, and older servers decline it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mpression

Daemons shipped before this change offer permessage-deflate with ws defaults,
so against this server they compress every frame at level 6, file chunks
included. Measured on an unconstrained link, 30 MB downloads through such a
daemon ran at ~31-40 MB/s instead of ~120 MB/s. The bump makes enrolled
daemons update to the level-1, file-chunks-uncompressed sender.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 22efcfa into main Nov 20, 2026
53 checks passed
@ymichael
ymichael deleted the bb/6748-daemon-compression-thr_6xtgkb7avh branch November 20, 2026 18:05
ymichael added a commit that referenced this pull request Nov 20, 2026
…binary (#7874)

## 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

- **Daemon send order** (`apps/host-daemon/src/session-send-queue.ts`,
`server-connection.ts`). Terminal output and `host.read_file_chunk`
replies 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.
- **Bulk send window** (`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:
- it grows while ack round trips of full-size (≥ 32 KiB) frames stay
near the lowest seen in the last 10–20 s;
  - it shrinks while its own bulk keeps > ~144 KiB and > 10 ms queued.
- The window, not `bufferedAmount`, bounds what sits in kernel and
network buffers ahead of a reply.
  - The server's sequencer acknowledges every 32 KiB instead of 256 KiB.
  - Draining is driven by ws write callbacks instead of a 10 ms poll.
- **Binary file chunks.** `host.read_file_chunk` returns raw bytes:
- The sequencer frame becomes a binary WS message: a 4-byte header
length, the usual JSON frame, then the bytes. It is retained and
replayed like text frames. The contract codec
(`encodeHostDaemonDaemonWsMessage` / `decodeHostDaemonDaemonWsMessage`)
moves `result.content` into and out of the binary part.
  - Chunks are 64 KiB (`HOST_FILE_CHUNK_MAX_BYTES`).
- `createFileStreamResponse` keeps up to 16 daemon reads in flight and
still delivers in order. A failed chunk aborts the reads still in
flight.
- **Compression (#7881) rule.** The daemon's ws `send` compresses text
frames only, so binary chunk frames are never deflated. This replaces
#7881's `sendUncompressed` path and keeps its behaviour: file bytes
cross uncompressed, everything else as before.
- **Wire change:** `HOST_DAEMON_PROTOCOL_VERSION` 275 → 276. Changed:
the chunk result type, the binary frames, and the ack cadence.
- **Docs:** `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.
- Two full stacks ran side by side: origin/main `81b1f612632` (includes
#7881 and #7883) and this branch. Each ran an isolated `start:worktree`
server bound to `0.0.0.0`, with its own client daemon reaching it
through the shaper at the LAN address. The route is non-loopback, so
#7881 compression is on in both stacks.
- Runs were interleaved main/branch with the order alternating per
round.
- Cells are median/p95 in ms; "·" separates the two rounds; n is samples
per round.
- "Download" streams a 16 MiB (relay) or 64 MiB file in a loop.
"Terminal flood" is `head -c 1M /dev/urandom | base64` in a loop. "Text
flood" `cat`s 400 TypeScript files in a loop (compresses ~3×).

Relay, 45 ms / 3.6 MB/s:

| | origin/main | this PR |
|---|---|---|
| RPC during download | 414/422 · 414/424 (n=45, 45) | **97/102 ·
96/101** (n=136, 137) |
| echo during download | 413/423 · 413/423 | **94/100 · 94/100** |
| RPC during terminal flood | 248/271 · 252/271 (n=69, 67) | **89/106 ·
89/96** (n=142, 143) |
| echo during terminal flood | 247/273 · 251/270 | **89/105 · 88/95** |
| RPC during text flood | 107/119 · 107/120 (n=127, 129) | **59/68 ·
61/87** (n=181, 176) |
| file download MB/s | 2.13 · 2.13 | **3.29 · 3.29** |
| first byte of a download | 519 · 529 ms | **133 · 130 ms** |
| terminal flood MB/s | 3.43 · 3.43 | 3.45 · 3.43 |
| text flood MB/s | 7.68 · 7.84 | 7.61 · 7.66 |
| idle RPC / echo (n=100) | 55/59 · 56/59 / 53/55 · 53/55 | 56/59 ·
55/58 / 53/56 · 53/55 |

Far relay, 120 ms / 3.6 MB/s:

| | origin/main | this PR |
|---|---|---|
| RPC during download | 490/503 · 493/506 (n=39, 39) | **171/181 ·
170/183** (n=92, 93) |
| RPC during terminal flood | 251/272 · 249/271 (n=70, 69) | **159/170 ·
159/172** (n=97, 97) |
| file download MB/s | 1.83 · 1.81 | **2.49 · 3.18** |
| first byte | 664 · 671 ms | **286 · 290 ms** |
| terminal flood MB/s | 3.39 · 3.36 | 3.39 · 3.39 |

LAN emulation, 3 ms / 25 MB/s:

| | origin/main | this PR |
|---|---|---|
| RPC during download | 25/30 · 25/32 (n=265, 264) | **15/19 · 16/21**
(n=305, 302) |
| RPC during terminal flood | 34/44 · 34/43 (n=239, 239) | **18/21 ·
18/21** (n=294, 293) |
| file download MB/s | 14.66 · 12.85 | **19.78 · 19.77** |
| terminal flood MB/s | 22.20 · 22.06 | 22.02 · 22.00 |

Unshaped LAN address (~loopback speed):

| | origin/main | this PR |
|---|---|---|
| RPC during download | 6.0/10.0 · 5.6/9.3 (n=351, 354) | 4.9/7.8 ·
4.9/8.0 (n=364, 364) |
| RPC during terminal flood | 21/24 · 20/24 (n=286, 286) | **5.5/7.4 ·
5.3/7.2** (n=359, 360) |
| RPC during text flood | 14/20 · 11/17 (n=314, 327) | 11/14 · 11/14
(n=327, 330) |
| file download MB/s | 124 · 121 | **290 · 276** |
| terminal flood MB/s | 33.5 · 33.4 | 33.3 · 33.0 |

**Known cost.** On the relay, text-heavy output that competes with
interactive traffic moves a little slower:
- 7.90/7.87 → 5.95/6.77 MB/s while the RPC and echo probes run alongside
it.
- On its own the text flood is at parity (7.68/7.84 vs 7.61/7.66).
- The window counts uncompressed bytes, so with ~3× compression it
treats ~48 KB of real queue as its 144 KiB limit and backs off early.
- In exchange, replies during that flood take 59–61 ms instead of 107
ms.

**Why an adaptive window.** Measured, not assumed:
- Send order plus a 64 KiB high-water mark alone did not help terminal
floods: the 1 MiB window moved into kernel buffers.
- A fixed 256 KiB unacknowledged limit halved far-relay terminal
throughput.
- The adaptive window's queue band was tuned on current main with
compression on:
- 32/96 KiB kept far-relay replies at ~135 ms, but cost ~12% far-relay
throughput (3.0 vs 3.4 MB/s).
  - 64/192 KiB reached parity but raised relay replies to ~106 ms.
- 48/144 KiB (shipped) reaches parity on every profile, with relay
replies at ~89 ms.

**Tests:**
- Send ordering under load: replies and echo go ahead of queued bulk;
per-terminal order holds, including the exit; terminals take turns; bulk
waits for and resumes on server acknowledgement.
- File chunk replies go out as binary frames and other replies as text.
- Against a real compressing `ws` server, 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.
- Sequencer binary frames, and the codec rejecting bytes on other
messages.
- Daemon file stream: reads ahead in order; a failed chunk aborts the
reads still in flight.

**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.
- After the final band change: `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:
- Through the branch daemon on the 45 ms LAN-address route, a Claude
Code turn with an uploaded attachment returned its token and ran a
command in the client host's workspace.
- 16 MiB and byte-range downloads through the branch daemon matched
`shasum` of the source.
- The proxy tally confirmed compression on both stacks (0.44 wire bytes
per decoded terminal byte).

Refs #6748

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant