Repository navigation
perf(ssh): bound relay bulk-stream backlog so PTY echo is not head-of-line blocked - #7601
Conversation
…-line blocked Root cause of SSH typing latency under load: all relay JSON-RPC traffic shares one ordered SSH channel, and the fs.readFileStream pump wrote every 256KB chunk (~340KB framed) into the relay's stdout as fast as local disk reads completed, ignoring write() backpressure. A file preview queued the entire remaining file ahead of any pty.data echo emitted mid-stream — measured 4.5-5.0MB ahead of one echo, 2.1-4.0s of echo latency on a simulated 2.5MB/s link. A quiet shell has no bulk traffic, which is why quiet repros felt snappy. Secondary: FrameDecoder rebuilt its buffer with Buffer.concat per TCP chunk (O(n^2) memcpy on the Electron main thread). Fix: - RelayDispatcher.notifyBulk(): per-client serialized bulk lane that honors the sink's write()===false and waits for drain; stream chunks target only the requesting client. Interactive pty.data frames still write directly, so an echo jumps ahead of not-yet-admitted chunks. - fs.streamAck credit window (4 chunks ~1MB): the client declares flowControl:'ack' and acks each processed chunk; the pump parks at the window and wakes on ack/cancel/detach/dispose plus a 1s stall recheck. Old client or old relay degrades to the legacy unpaced pump. - FrameDecoder chunk-list buffering in both mirrored protocol files: each frame is assembled exactly once. After: 113-139ms echo latency (was 2081-3951ms), 273-298KB queued ahead of the echo (was 4.5-5.0MB) on the same simulated link; decoder feed of 13.3MB in 32KB slices median 33ms (was 78ms, worst 384ms). Docker SSH e2e: quiet typing median 3.8ms unchanged; new busy-relay test (two 8MB read loops + git churn) median 169ms / worst 181ms vs 500/2000ms budgets. STREAM_CHUNK_SIZE is intentionally unchanged: both sides bake it into chunk offset math, so changing it breaks cross-version streams. Co-authored-by: Orca <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughChangesThis PR adds backpressure-aware bulk dispatch in the relay, ack-based pacing for streamed file reads, and a chunk-queue rewrite of Sequence Diagram(s)See diagrams embedded in the hidden review stack artifact above. Compact metadata
Related issues: None referenced Suggested labels: performance, relay, ssh, backpressure, streaming Suggested reviewers: Reviewers familiar with the relay dispatcher, SSH filesystem streaming, and protocol framing code Poem 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/relay/relay.ts (1)
712-740: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winWrap
sock.writein try/catch, mirroring the stdout sink.The stdout sink (Lines 393-402) wraps
process.stdout.writein try/catch specifically to catch a synchronous throw and mark the sink dead. The socket sink here callssock.write(data)unguarded. If it throws (e.g. after an unexpected.end()), it would propagate out of the dispatcher's write path uncaught — and sinceprocess.on('uncaughtException')exits the whole process (Line 360-364), one client's socket fault could kill the entire relay, not just that client.🛡️ Proposed fix
const clientId = dispatcher.attachClient( (data) => { - if (!sock.destroyed) { - return sock.write(data) - } - return undefined + if (sock.destroyed) { + return undefined + } + try { + return sock.write(data) + } catch { + sock.destroy() + return undefined + } },
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 9ee5ea45-3d72-4982-a6de-c770a6f86752
📒 Files selected for processing (14)
docs/reference/ssh-typing-latency-under-relay-load.mdsrc/main/ssh/relay-protocol.test.tssrc/main/ssh/relay-protocol.tssrc/main/ssh/ssh-filesystem-stream-reader.tssrc/relay/dispatcher.test.tssrc/relay/dispatcher.tssrc/relay/fs-handler-file-read.tssrc/relay/fs-handler-stream.test.tssrc/relay/fs-handler.tssrc/relay/fs-stream-pty-echo-backpressure.integration.test.tssrc/relay/fs-stream-registry.tssrc/relay/protocol.tssrc/relay/relay.tstests/e2e/ssh-docker-relay-perf.spec.ts
Co-authored-by: Orca <[email protected]>
…-line blocked (stablyai#7601) Co-authored-by: Orca <[email protected]>
Problem
SSH-host terminal typing becomes extremely slow (seconds per echoed keystroke) while other SSH work is active — file previews, source-control refresh, search. A quiet SSH shell stays snappy, which made reports look unreproducible.
Root cause
All relay JSON-RPC traffic — PTY echo, file streams, git, search — shares one ordered SSH channel.
fs.readFileStreampump wrote every 256KB chunk (~340KB framed) into the relay's stdout as fast as local disk reads completed, ignoringwrite()'s backpressure signal. A file preview queued the entire remaining file ahead of anypty.dataecho emitted mid-stream.FrameDecoder.feed()rebuilt its buffer withBuffer.concatper ~32KB TCP chunk — O(n²) memcpy (~80MB per 10MB stream) on the Electron main thread, delayingpty:writedispatch and echo delivery.Fix
RelayDispatcher.notifyBulk(): per-client serialized sends that honorwrite() === falseand wait for the sink's drain; stream chunks target only the requesting client. Interactivepty.dataframes still write directly, so an echo jumps ahead of every not-yet-admitted chunk. All sink-death paths (EPIPE, stdin end, detach, dispose) flush parked waiters so a pump can never hang on a dead pipe.flowControl: 'ack'and sendsfs.streamAckper processed chunk; the relay parks the pump at 4 unacked chunks (~1MB) and wakes on ack/cancel/detach/dispose plus a 1s stall recheck. This also yields the relay event loop between chunks so incoming keystrokes are handled promptly.flowControlparam → legacy pump (still drain-bounded, transparent). New client + old relay →fs.streamAckis an unknown notification, silently ignored.STREAM_CHUNK_SIZEintentionally unchanged — both sides bake it into offset math; changing it corrupts cross-version streams.Benchmarks
In-process, simulated 2.5MB/s link, keystroke sent mid-4MB-preview (3 runs each, HEAD vs this branch):
Docker SSH e2e (
ORCA_E2E_SSH_DOCKER=1 pnpm run test:e2e:ssh-docker-perf, all 3 pass):Reliability proof
listSessions()/provider fanout added anywhere (verified: input path unchanged; daemonlistSessions()remains metadata-only).Buffer.concat-in-feed guard); 1201 tests acrosssrc/relay+src/main/sshpass incl. 12MB stream round-trip; full typecheck + lint clean; quiet-typing e2e unchanged.docs/reference/ssh-typing-latency-under-relay-load.md): large single-frame git responses (up to ~13MB) can still delay an echo by their own transfer time (needs response chunking); large outboundfs.writeFileframes can delay keystrokes client→relay;pty.ackDataoutput flow control remains unenforced (PTY floods are paced by the relay's existing 8ms batch scheduler).STREAM_ACK_WINDOW_CHUNKS; an adaptive window can recover throughput later without giving back the latency win.Tests
npx vitest run src/relay src/main/ssh— 1201 passed, 1 skippedpnpm run typecheck— cleanORCA_E2E_SSH_DOCKER=1 pnpm run test:e2e:ssh-docker-perf— 3 passed (includes new busy-relay scenario)Made with Orca 🐋