Skip to content

perf(ssh): bound relay bulk-stream backlog so PTY echo is not head-of-line blocked - #7601

Merged
Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/ssh-typing-performance
Jul 7, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/ssh-typing-performance

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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.

  1. Relay-side head-of-line blocking (primary). The fs.readFileStream pump wrote every 256KB chunk (~340KB framed) into the relay's stdout as fast as local disk reads completed, ignoring write()'s backpressure signal. A file preview queued the entire remaining file ahead of any pty.data echo emitted mid-stream.
  2. Main-process decode cost (secondary). FrameDecoder.feed() rebuilt its buffer with Buffer.concat per ~32KB TCP chunk — O(n²) memcpy (~80MB per 10MB stream) on the Electron main thread, delaying pty:write dispatch and echo delivery.

Fix

  • Bulk lane — RelayDispatcher.notifyBulk(): per-client serialized sends that honor write() === false and wait for the sink's drain; stream chunks target only the requesting client. Interactive pty.data frames 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.
  • Credit flow control — client requests flowControl: 'ack' and sends fs.streamAck per 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.
  • FrameDecoder rewrite (both mirrored protocol files): chunk-list buffering; each frame is assembled exactly once.
  • Cross-version safety: old client + new relay → no flowControl param → legacy pump (still drain-bounded, transparent). New client + old relay → fs.streamAck is an unknown notification, silently ignored. STREAM_CHUNK_SIZE intentionally 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):

Metric Before After
Echo latency mid-stream 2081 / 2974 / 3951 ms 139 / 113 / 126 ms (~20x)
Bytes queued ahead of the echo frame 4.5–5.0 MB (whole remaining file) 273–298 KB (~1 framed chunk)
FrameDecoder feed, 13.3MB in 32KB slices median 78ms (worst 384ms) median 33ms (worst 42ms)

Docker SSH e2e (ORCA_E2E_SSH_DOCKER=1 pnpm run test:e2e:ssh-docker-perf, all 3 pass):

  • Quiet typing (existing test): median 3.8ms / worst 7.0ms — no regression.
  • New busy-relay test (two 8MB remote file-read loops + git.status churn; 158 error-free bulk reads during measurement): median 169ms / worst 181ms vs 500/2000ms budgets.

Reliability proof

  • Invariant: interactive PTY input/echo frames must not queue behind an unbounded bulk backlog on the shared SSH channel; remote file streams must remain byte-identical, cancellable, and leak-free.
  • Material impact: closes the "SSH typing is seconds-slow while previews/git refresh run" class; the deterministic byte-bound test makes the flood shape hard to reintroduce.
  • Product change type: perf hardening + protocol addition (backward/forward compatible) + regression gates.
  • Performance risk inventory: touches SSH PTY output/echo path, file streaming, relay event loop, main-process frame decode. Does NOT touch typing/focus/switch/resume/resize/render store paths; no listSessions()/provider fanout added anywhere (verified: input path unchanged; daemon listSessions() remains metadata-only).
  • No-regression evidence: deterministic count/byte tests (bytes-ahead-of-echo bound, ack-window park/resume counts, cancel-while-parked handle release, no-Buffer.concat-in-feed guard); 1201 tests across src/relay + src/main/ssh pass incl. 12MB stream round-trip; full typecheck + lint clean; quiet-typing e2e unchanged.
  • Correctness evidence: stream content equality on all paths (congested, ack-paced, legacy no-ack), per-chunk length/count/byte invariants unchanged, cancel/stale/detach release the pump and file handle.
  • Provider/platform coverage: SSH relay covered (unit + integration + Docker e2e, POSIX). Windows relay sinks use the same Node stream semantics — covered by code reasoning, no Windows-specific path touched. Local/daemon/WSL/mobile PTY paths unaffected (no shared code changed). macOS/Linux e2e covered; Windows accepted gap (no Docker SSH e2e there).
  • Residual gaps (documented in 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 outbound fs.writeFile frames can delay keystrokes client→relay; pty.ackData output flow control remains unenforced (PTY floods are paced by the relay's existing 8ms batch scheduler).
  • Known trade-off: bulk stream throughput is now RTT-coupled (~1MB per round-trip ≈ 10MB/s at 100ms RTT). Tunable via STREAM_ACK_WINDOW_CHUNKS; an adaptive window can recover throughput later without giving back the latency win.
  • Rollback/demotion rule: if field reports show file previews meaningfully slower on high-RTT links, raise the window (or gate ack pacing) before reverting the bulk lane — the two mechanisms are independent.

Tests

  • npx vitest run src/relay src/main/ssh — 1201 passed, 1 skipped
  • pnpm run typecheck — clean
  • ORCA_E2E_SSH_DOCKER=1 pnpm run test:e2e:ssh-docker-perf — 3 passed (includes new busy-relay scenario)

Made with Orca 🐋

…-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]>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d8d1e557-14b3-47b8-9c83-b1f0a6e27872

📥 Commits

Reviewing files that changed from the base of the PR and between 68ee5b5 and d48d737.

📒 Files selected for processing (1)
  • src/main/providers/ssh-filesystem-provider-stream.test.ts

📝 Walkthrough

Walkthrough

Changes

This PR adds backpressure-aware bulk dispatch in the relay, ack-based pacing for streamed file reads, and a chunk-queue rewrite of FrameDecoder to avoid repeated buffering copies. Relay stdout and socket sinks now expose drain callbacks to the dispatcher. Stream registry state tracks acknowledgements and wakeups. Tests cover dispatcher backpressure, frame decoding, stream pacing, an integration scenario for PTY echo versus file streaming, and a Docker relay latency perf case. A reference doc records the symptom, changes, tests, and remaining gaps.

Sequence Diagram(s)

See diagrams embedded in the hidden review stack artifact above.

Compact metadata

  • Type: Feature/performance fix
  • Scope: SSH relay protocol, dispatcher, filesystem streaming, documentation, tests
  • Breaking changes: Public signatures changed for RelayDispatcher constructor, setWrite, attachClient, sendFrame/writeFrame return types, and readRelayFileStreamMetadata

Related issues: None referenced
Related PRs: 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
A rabbit typed while files streamed by,
No longer stuck in queues piled high,
Chunks now wait for credit's nod,
The decoder skips the copy-slog,
Drain waiters wake, the bulk lane clears,
Fast keystrokes echo, calming fears. 🐇⌨️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is on-topic but misses required template sections like Screenshots, AI Review Report, Security Audit, and Notes, and the cross-platform review is incomplete. Add the missing template sections, include screenshots or 'No visual change', and explicitly document the AI review, security audit, testing, and macOS/Linux/Windows coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main SSH relay backlog fix and PTY head-of-line blocking improvement.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/relay/relay.ts (1)

712-740: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Wrap sock.write in try/catch, mirroring the stdout sink.

The stdout sink (Lines 393-402) wraps process.stdout.write in try/catch specifically to catch a synchronous throw and mark the sink dead. The socket sink here calls sock.write(data) unguarded. If it throws (e.g. after an unexpected .end()), it would propagate out of the dispatcher's write path uncaught — and since process.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

📥 Commits

Reviewing files that changed from the base of the PR and between 99ae2dc and 68ee5b5.

📒 Files selected for processing (14)
  • docs/reference/ssh-typing-latency-under-relay-load.md
  • src/main/ssh/relay-protocol.test.ts
  • src/main/ssh/relay-protocol.ts
  • src/main/ssh/ssh-filesystem-stream-reader.ts
  • src/relay/dispatcher.test.ts
  • src/relay/dispatcher.ts
  • src/relay/fs-handler-file-read.ts
  • src/relay/fs-handler-stream.test.ts
  • src/relay/fs-handler.ts
  • src/relay/fs-stream-pty-echo-backpressure.integration.test.ts
  • src/relay/fs-stream-registry.ts
  • src/relay/protocol.ts
  • src/relay/relay.ts
  • tests/e2e/ssh-docker-relay-perf.spec.ts

@Jinwoo-H
Jinwoo-H merged commit 9bed9bb into main Jul 7, 2026
1 check passed
@Jinwoo-H
Jinwoo-H deleted the Jinwoo-H/ssh-typing-performance branch July 7, 2026 00:10
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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