Skip to content

perf(pty): cap the unsent main→renderer PTY backlog (Win/Linux GB-scale leak) - #7630

Merged
nwparker merged 2 commits into
mainfrom
nwparker/leak-pty-backlog-cap
Jul 7, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/leak-pty-backlog-cap

Conversation

@nwparker

@nwparker nwparker commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Description

The per-pty pendingData string in src/main/ipc/pty.ts — the main process's unsent main→renderer output queue — had no size cap. The existing 512 KB/pty and 8 MB-total caps bound only sent-but-unacked bytes (rendererInFlightCharsByPty); the queued-but-unsent backlog grows freely:

  • onData appends every PTY chunk via appendPendingPtyData (plain string concat, no cap).
  • flushPendingData is ACK-gated by canSendPtyDataToRenderer; when gated it just continues (does not drain).
  • There is no PTY-read pause, so ingestion never stops.

So the only thing bounding pendingData is the renderer sending pty:ackData. On Windows/Linux the main renderer is background-throttled — createMainWindow.ts:307 calls setBackgroundThrottling(false) only inside if (process.platform === 'darwin'), and Chromium freezes hidden pages after ~5 min. So a backgrounded Orca window with an active or verbose background agent stops ACKing → in-flight pins at 8 MB → the flush gates → pendingData grows at raw PTY throughput → MB→GB in the main process. macOS is unaffected (throttling disabled there).

This is triggered by the extremely common act of backgrounding/minimizing the app while a background agent or build keeps printing.

Fix

Cap the per-pty backlog to the most-recent PENDING_DATA_MAX_CHARS (2 MB, matching the daemon pendingOutput and renderer scheduler caps, both 2 MB), advancing startSeq by the dropped-char count (the identical arithmetic flushPendingData already uses when it slices), and set a droppedBacklog flag on the next payload.

The renderer's dataCallback sees the flag and calls the existing markHiddenOutputRestoreNeeded() — the same recovery the renderer's own 2 MB scheduler overflow already uses. On hidden→visible it rebuilds the dropped span from the main headless-emulator snapshot, so no output is lost within the pane's scrollback depth. The flag threads through the same layers as the existing background/seq fields: main payload → preload types → dispatcher PtyDataMeta → one-line renderer trigger.

Why this loses zero user-visible output: the leak scenario is intrinsically the hidden renderer path. Every PTY byte is independently fed to the runtime headless emulator (which owns the pane's real scrollback) regardless of renderer state, and the renderer already snapshot-reconciles on un-hide. Background agents keep writing full-speed into that buffer — only the redundant main→renderer delivery copy is trimmed, so agent throughput is unaffected (a PTY-pause fix would have stalled background agents; this does not).

Evidence (red → green)

Two new tests in pty.test.ts drive a daemon pty that emits 5 MB while the renderer never ACKs:

  • WITHOUT the cap: AssertionError: expected undefined to be true — droppedBacklog is never set. Leak reproduced (backlog would grow unbounded).
  • WITH the fix: the first emitted chunk carries droppedBacklog: true exactly once, and total delivered chars stay bounded. A second test asserts ordinary small output never sets the flag (no common-case regression). ✅

Verification:

  • pty.test.ts — 217 tests green (2 new)
  • pty-connection.test.ts (331) + hidden-output-restore + dispatcher suites green
  • oxlint clean, tsgo node and web typecheck clean

Platform note

The leak and the fix are Windows/Linux-only (macOS is throttling-exempt via setBackgroundThrottling(false)), so this is not reproducible at runtime on macOS (can't /electron-verify on a Mac). Evidence is the code trace + unit/integration tests. Worth a manual Win/Linux soak (background the app with a chatty background agent, watch main-process RSS) before/after.

ELI5

When you hide Orca on Windows/Linux, the app's window "falls asleep" and stops saying "got it" to the part of the program feeding it terminal text. That feeder kept stuffing everything into a bag with no bottom — a busy background robot could fill it with gigabytes until the app ran out of memory. Now the bag has a 2 MB limit: when it's full we keep only the newest text and leave a note ("you missed some"). When you look at the window again, it rebuilds the missing part from a complete copy the app kept elsewhere — so you still see everything, and memory stays bounded.

Trade-offs / regression risk: none in normal use

  • The cap only engages when pendingData exceeds 2 MB, which only happens when the renderer isn't ACKing (throttled/frozen) — never in normal foreground operation, where the renderer ACKs fast and the backlog stays tiny. The "small output" test locks this in.
  • When it does engage, the dropped span is recovered from the main headless snapshot on un-hide (no scrollback loss within depth).
  • Background-agent throughput is unchanged.

Context

Second of two massive-scale leaks found this pass. The first — the native-chat transcript read-cache retaining full transcripts (GB-scale) — is #7625.

Made with Orca 🐋

The per-pty `pendingData` string in ipc/pty.ts (main's unsent
main→renderer output queue) had no size cap. The 512 KB/pty + 8 MB
in-flight caps bound only SENT-but-unacked bytes; `onData` appends to
`pendingData` unconditionally and `flushPendingData` merely `continue`s
(no drain) while ack-gated. On Windows/Linux the main renderer is
background-throttled — `setBackgroundThrottling(false)` is set only for
`process.platform === 'darwin'` — and Chromium freezes hidden pages
after ~5 min, so a backgrounded Orca with an active/verbose agent stops
ACKing: in-flight pins at 8 MB, the flush gates, and `pendingData` grows
at raw PTY throughput → MB→GB in the main process. macOS is unaffected.

Fix: cap the backlog to the most-recent PENDING_DATA_MAX_CHARS (2 MB,
matching the daemon pendingOutput and renderer scheduler caps),
advancing startSeq by the dropped-char count (the same arithmetic
flushPendingData uses when slicing), and set a `droppedBacklog` flag on
the next payload. The renderer's dataCallback sees the flag and calls
the existing markHiddenOutputRestoreNeeded(), so on hidden→visible it
rebuilds the dropped span from the main headless snapshot — no output is
lost within scrollback depth. Background agents keep writing full-speed
into the runtime buffer; only the redundant delivery copy is trimmed.
The flag threads through the same layers as the existing `background`
field: main payload → preload types → dispatcher PtyDataMeta → renderer.

Tests (red→green): a daemon pty emits 5 MB while the renderer never
ACKs. Without the cap the flag is never set (fail); with it the first
emitted chunk carries droppedBacklog exactly once and delivery stays
bounded. Ordinary small output never sets the flag.

Note: leak + fix are Win/Linux-only (macOS is throttling-exempt), so not
reproducible at runtime on macOS; evidence is the code trace + tests.
@coderabbitai

coderabbitai Bot commented Jul 7, 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: cb61d051-9350-4050-a6d5-39497aa4841b

📥 Commits

Reviewing files that changed from the base of the PR and between ae68e9a and 5a88f93.

📒 Files selected for processing (1)
  • src/main/ipc/pty.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/ipc/pty.test.ts

📝 Walkthrough

Walkthrough

This PR adds a cap on per-PTY unsent backlog in the main process and introduces a droppedBacklog flag when trimming occurs. That flag is carried through PTY payloads, preload and renderer IPC metadata, and renderer connection handling. When the renderer receives the flag, it marks hidden output restore as needed. Tests cover capped backlog behavior and normal output without the flag.

Related issues: None provided.
Related PRs: None provided.
Suggested labels: area: pty, area: renderer, area: ipc
Suggested reviewers: None provided.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits required template sections for Screenshots, AI Review Report, and Security Audit. Add the missing sections, including 'No visual change' for screenshots, an AI review summary with cross-platform checks, and a brief security audit.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: capping the unsent PTY backlog to fix a Windows/Linux leak.
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.

@nwparker

nwparker commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Adversarial review complete — shipping.

  • Traced all four send paths (batch flush, ack-gated re-queue, interactive fast-path, exit flush): the droppedBacklog flag rides exactly one outgoing payload and is retained while gated; startSeq trim arithmetic matches the slice math flushPendingData already uses.
  • Renderer seq handling only special-cases backwards seq (session revival), so the forward jump from a trim is a benign high-water update; snapshot reconciliation stays consistent.
  • Recovery gate is identical to the existing renderer 2 MB scheduler-overflow path (onBackgroundBacklogDropped), including immediate self-heal when the pane is foreground — recovery parity holds.
  • Red→green independently re-proven: reverting only pty.ts fails the new backlog test on the droppedBacklog assertion.
  • Two independent delegated review rounds returned clean; one test-comment reword landed (the totalChars < 3MB assertion is a sanity bound gated by the pre-existing in-flight caps, not the cap proof — the flag assertion is the discriminator).
  • Electron smoke on macOS: 240 pty:data events / 1.49 MB streamed, droppedBacklog never set, full seq 1 200000 burst rendered to the exact tail, terminal interactive throughout — common path unaffected.
  • 562 affected tests green, all three typecheck configs clean, perf hot-path cost is one O(1) length compare per append.

Leak engagement path is Win/Linux background-throttle only (not runtime-reproducible on macOS); a Win/Linux RSS soak with a chatty background agent remains worthwhile post-merge.

@nwparker
nwparker merged commit f057c9d into main Jul 7, 2026
2 checks passed
Jinwoo-H added a commit that referenced this pull request Jul 7, 2026
46 commits from main. Conflict resolutions (branch structure wins, main
semantics grafted):

- pending-backlog cap (#7630): main's capPendingPtyData/droppedBacklog
  2MB tail-trim EXCISED — this branch's droppedOutput sentinel mechanism
  (O(1) drop + query salvage + settings-scaled cap + restore marker)
  already bounds the unsent backlog and strictly supersedes it; carrying
  both would race two cap policies over one buffer. Kept main's
  makePtyDataPayload helper and exit-time pending flush (adapted to the
  sentinel). Main's duplicate never-ACK cap test removed (covered by the
  existing sentinel cap tests); its reload-gate tests kept with the
  runtime mock extended.
- replay guard (#7661): main's blind REPLAY_GUARD_RELEASE_FALLBACK_MS
  release dropped — this branch's probe-certified stall release covers
  the same cold-restore reattach lockout without the auto-reply leak a
  timed release can cause in agent TUIs. Main's three regression tests
  KEPT, adapted to probe timing (explicit stallCheckMs).
- hidden-pressure scenario: kept this branch's STRICT 1500ms restore
  budget (the background keep-tail global budget earns it; main relaxed
  to 4s for CI drain overhead) + grafted main's timer-drift gate const.
- ssh-docker-relay-perf: kept this branch's ACK-stalled background PTY
  test AND grafted main's new file-streams+git-churn test (4 tests).
- preload/renderer: droppedBacklog threading excised with the mechanism;
  main's unrelated changes (ssh importConfig reAdopt, etc.) kept.

Gates: typecheck clean; ipc+daemon+terminal-pane+pane-manager suites
4,396 passed / 14 skipped.

Co-authored-by: Orca <[email protected]>
brennanb2025 added a commit that referenced this pull request Jul 9, 2026
#7630 landed the same 2MB cap + droppedBacklog restore flag this branch
introduced independently — adopt its mechanism wholesale (constants, flag
naming, renderer threading, cap tests). This branch keeps what #7630 does not
cover: releasing the queue + in-flight ACK budget on teardown paths that skip
sendPtyExitToRenderer (SSH connection drop, synthetic-kill dedup), and dropping
renderer delivery for output arriving inside the synthetic-kill window.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…le leak) (stablyai#7630)

* perf(pty): cap the unsent main→renderer PTY backlog (Win/Linux GB leak)

The per-pty `pendingData` string in ipc/pty.ts (main's unsent
main→renderer output queue) had no size cap. The 512 KB/pty + 8 MB
in-flight caps bound only SENT-but-unacked bytes; `onData` appends to
`pendingData` unconditionally and `flushPendingData` merely `continue`s
(no drain) while ack-gated. On Windows/Linux the main renderer is
background-throttled — `setBackgroundThrottling(false)` is set only for
`process.platform === 'darwin'` — and Chromium freezes hidden pages
after ~5 min, so a backgrounded Orca with an active/verbose agent stops
ACKing: in-flight pins at 8 MB, the flush gates, and `pendingData` grows
at raw PTY throughput → MB→GB in the main process. macOS is unaffected.

Fix: cap the backlog to the most-recent PENDING_DATA_MAX_CHARS (2 MB,
matching the daemon pendingOutput and renderer scheduler caps),
advancing startSeq by the dropped-char count (the same arithmetic
flushPendingData uses when slicing), and set a `droppedBacklog` flag on
the next payload. The renderer's dataCallback sees the flag and calls
the existing markHiddenOutputRestoreNeeded(), so on hidden→visible it
rebuilds the dropped span from the main headless snapshot — no output is
lost within scrollback depth. Background agents keep writing full-speed
into the runtime buffer; only the redundant delivery copy is trimmed.
The flag threads through the same layers as the existing `background`
field: main payload → preload types → dispatcher PtyDataMeta → renderer.

Tests (red→green): a daemon pty emits 5 MB while the renderer never
ACKs. Without the cap the flag is never set (fail); with it the first
emitted chunk carries droppedBacklog exactly once and delivery stays
bounded. Ordinary small output never sets the flag.

Note: leak + fix are Win/Linux-only (macOS is throttling-exempt), so not
reproducible at runtime on macOS; evidence is the code trace + tests.

* test(pty): clarify that the sent-total assertion is a sanity bound, not the cap proof

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[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