Skip to content

fix: bound preload runtime subscription IPC listeners to O(1) (#6288) - #6564

Merged
nwparker merged 2 commits into
mainfrom
nwparker/fix-6288
Jun 28, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/fix-6288

Conversation

@nwparker

@nwparker nwparker commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

🧑‍🤝‍🧑 Impact & ELI5

1) What's broken today (ELI5). If you use Orca's remote-server mode (connecting Orca to a second computer over the network) and keep it running for a while, Orca slowly eats more and more memory until it gets so bloated it crashes. The reporter saw it with just three projects open. It's worst when the network connection between the two computers is shaky and keeps dropping and reconnecting — every reconnect quietly makes the leak a little bigger. So for remote/SSH users it's a real blocker (the app eventually dies after ~15–30 minutes of flaky connection), while local-only users are basically unaffected.

2) What this PR does (ELI5). Think of Orca's two computers chatting over many phone lines, one per "topic" they're tracking (open tabs, file changes, notifications, etc.). Every time it opened a new line, it also hired a new operator to listen on it — but when a call dropped with an error (instead of hanging up cleanly), it forgot to send that operator home. After lots of dropped calls you'd have a room full of idle operators, each clutching a heavy stack of paperwork they refuse to put down — that's the memory leak. This PR fires all the redundant operators and installs one switchboard operator who routes every call to the right place by its ticket number. So now it cleans up after a dropped connection instead of piling up forgotten listeners forever.

3) Tradeoffs / regressions — honest answer. No regressions — nothing is disabled, no new setup, and no behavior is lost. The message routing is identical to before: a dropped/error connection is still treated as non-terminal (the topic stays subscribed and keeps working across reconnects, exactly as designed), a clean close still tears the subscription down, and unsubscribe still works. The only thing that changed is when the internal listeners are cleaned up — strictly fewer of them, never more — so this is pure cleanup with no feature cost. Two honest caveats, neither a user-facing downside: (a) the fix was validated with unit tests that count the leaked listeners rather than a full two-machine 15–30-minute repro (which is impractical in CI), and (b) a separate, pre-existing quirk — that some remote data can go stale after a terminal error until something else refreshes it — is explicitly left alone here and noted as a future follow-up. This PR neither introduces nor worsens that.


Summary

Fixes #6288 — remote-server memory/CPU usage climbs to the renderer V8 heap ceiling (~3586MB) and crashes (exit 5) when two connected computers run for 15–30 min under remote-runtime connection stress.

Root cause: the preload subscription bridge (src/preload/runtime-environment-subscriptions.ts) attached one IPC listener per subscribe() to the single shared channel runtimeEnvironments:subscriptionEvent, and only detached it on unsubscribe() or a terminal 'close' frame. The 'error' branch never detached. Shared-control subscriptions (session.tabs.subscribe/subscribeAll, runtime.clientEvents.subscribe, files.watch, accounts/notifications.subscribe) are intentionally kept alive across socket reconnects, so while the link flaps the renderer accumulated stale per-subscription listeners — each closure capturing the Zustand store and large session-tab snapshot objects — without bound. That pinned the renderer heap and tripped Node's MaxListenersExceededWarning on the channel.

Fix: replace the per-subscribe listener with one shared dispatcher per renderer (ipc instance) that routes every frame by subscriptionId through a Map. Attached IPC listeners are now O(1) regardless of subscription churn; the map entry is the only per-subscription state, and it is released on 'close' or unsubscribe(). The intended "shared-control subscription survives transparent reconnects" contract is preserved: 'error' frames remain non-terminal (they still reach the live consumer and keep the entry mapped), exactly as before — only the listener no longer leaks.

Screenshots

No visual change. This is a renderer memory leak under remote-runtime stress; the signal is heap/listener retention, not pixels. See the PR comment for before/after listener-count evidence.

Testing

  • pnpm lint (oxlint, scoped to changed files — clean)
  • pnpm typecheck (tsgo -p config/tsconfig.node.json — clean)
  • pnpm test (preload + related runtime suites — 39 passed)
  • pnpm build (not run; no build-affecting change — preload module signature unchanged)
  • Added/updated high-quality regression tests

Added the missing 'error'-path coverage the validation pass flagged, plus a direct leak guard:

  • shares a single channel listener across many subscriptions on one ipc — asserts ipc.on is called exactly once across 25 subscriptions (was 25 listeners before).
  • keeps the subscription mapped on error frames but releases it on unsubscribe — delivers 50 error frames, asserts no detach/leak and that the consumer's unsubscribe() is the single release path.
  • Updated existing response/reject/close tests to the shared-dispatcher model and asserted frames stop reaching released subscriptions.

AI Review Report

Reviewed for correctness, edge cases, cross-platform safety, and elegance.

  • Correctness: confirmed via reading src/main/ipc/runtime-environments.ts, runtime-environment-transport-routing.ts, and the shared-control state machine that every onError is paired with a terminal onClose (so 'close' still releases the entry), and that server ok:false response frames are non-terminal by design (handleSharedControlSubscriptionResponse) — the dispatcher preserves both semantics.
  • Edge cases: subscribe-resolution id-mismatch and reject paths release the map entry; redundant unsubscribe() after 'close' is idempotent; re-entrancy during dispatch is safe (get-then-delete, no map iteration).
  • Cross-platform: confirmed no metaKey/path-separator/shell assumptions; this is the SSH/remote path itself and is provider-agnostic (no GitHub-only naming). The WeakMap keyed on the singleton ipcRenderer means exactly one listener per renderer on macOS/Linux/Windows.
  • Audited renderer fire-and-forget runtimeEnvironments.call/callRuntimeRpc callers for unhandled rejections — all already carry .catch; no change needed there.

Security Audit

No new IPC channels, no command/path/secret handling, no new dependencies. The change is purely internal to the existing preload subscription bridge: it narrows listener lifetime (strictly fewer attached listeners) and routes by the same subscriptionId already used. No input-handling or auth surface changes. IPC payload shape is unchanged. No injection, traversal, eval, or exfiltration risk introduced.

Notes

  • Scope kept minimal: the primary, genuine leak is the preload listener accumulation, fixed comprehensively (O(N)→O(1)). Renderer consumers and call sites were audited and found already rejection-safe.
  • Manual end-to-end heap validation deferred: a full repro needs two paired machines plus a network conditioner flapping the WebSocket for 15–30 min — infeasible in CI/sandbox. The unit tests assert the exact leak signal (attached-listener count) instead.
  • Future suggestions (out of scope): (1) renderer consumers in web-session-tabs-sync.ts and runtime-client-events.ts only console.warn on onError and never re-subscribe, so after a terminal shared-control error the session-tabs/client-events stay stale until an effect dep changes — a correctness (not memory) follow-up could re-subscribe via the existing scheduleRetry path. (2) Optionally bound runtime-rpc-call-queue.ts per-environment queues when an environment is known-unreachable, as a defensive measure during long outages.

Made with Orca 🐋

The preload subscription bridge attached one IPC listener per subscribe()
to the shared 'runtimeEnvironments:subscriptionEvent' channel and only
detached on unsubscribe()/close. The 'error' branch never detached, so
shared-control subscriptions that survive reconnects (session.tabs,
runtime.clientEvents, files.watch) leaked one listener plus its closure
(capturing the Zustand store and session-tab snapshots) per subscription
during connection flapping, pinning the renderer heap toward the V8
ceiling under sustained remote-runtime stress.

Replace the per-subscribe listener with a single shared dispatcher per
ipc instance that routes frames by subscriptionId through a Map. Attached
IPC listeners are now O(1) regardless of subscription churn; the map entry
is the only per-subscription state and is released on close or unsubscribe.

Fixes #6288

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

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@nwparker, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 27 minutes and 25 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b9e8b7cc-d42c-485a-b537-a326d9222edc

📥 Commits

Reviewing files that changed from the base of the PR and between 5712cf9 and 74f778e.

📒 Files selected for processing (2)
  • src/preload/runtime-environment-subscriptions.test.ts
  • src/preload/runtime-environment-subscriptions.ts

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

Copy link
Copy Markdown
Contributor Author

Evidence

Unit tests (the leak signal)

This is a memory leak under remote-runtime connection stress, so the regression signal is attached IPC listener count / retained closures, not pixels. The new tests measure that signal directly.

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts src/preload/runtime-environment-subscriptions.test.ts

 Test Files  1 passed (1)
      Tests  5 passed (5)

Key assertions:

  • shares a single channel listener across many subscriptions on one ipc — expect(ipc.on).toHaveBeenCalledTimes(1) across 25 subscriptions (the old code attached 25 listeners).
  • keeps the subscription mapped on error frames but releases it on unsubscribe — delivers 50 'error' frames; asserts ipc.removeListener is never called mid-flight (errors are non-terminal, contract preserved) and that after unsubscribe() no further frames reach the consumer (closure released).
  • Existing response / subscribe-reject / remote-close tests updated to the shared-dispatcher model; all assert frames stop reaching a released subscription.

Related suites still green (39 passed total): src/main/ipc/runtime-environments.test.ts, src/renderer/src/runtime/runtime-client-events.test.ts, src/renderer/src/hooks/runtime-client-events-sync.test.ts.

Before/after: listener accumulation under churn

Modeling the exact failure mode — subscriptions that error during a flap and are never unsubscribed (shared-control subscriptions, by design):

subscribes=10    OLD attached IPC listeners=10    NEW attached IPC listeners=1
subscribes=100   OLD attached IPC listeners=100   NEW attached IPC listeners=1
subscribes=1000  OLD attached IPC listeners=1000  NEW attached IPC listeners=1
subscribes=5000  OLD attached IPC listeners=5000  NEW attached IPC listeners=1

Old: O(N) listeners, each retaining a closure over the Zustand store + session-tab snapshots → monotonic renderer heap growth toward the 3586MB V8 ceiling and MaxListenersExceededWarning. New: O(1) listener; the only per-subscription state is a Map entry that is freed on 'close'/unsubscribe().

Why the fix is safe (root-cause confirmation)

Read of src/main/ipc/runtime-environment-transport-routing.ts + the shared-control state machine confirms every consumer onError is immediately followed by a terminal onClose (finishSharedControlSubscription(..., notifyClose=true, error) in reconnect/send paths), so the 'close' frame still releases the dispatcher entry. Server ok:false response frames (e.g. runtime.clientEvents during reconnect) remain non-terminal and continue to reach the live consumer — the survives-reconnect contract is unchanged. The fix only stops the listener from leaking.

End-to-end heap validation (deferred, explained)

A faithful repro requires two paired machines plus a network conditioner flapping the WebSocket for 15–30 min; that is infeasible in this sandbox/CI, so it is deferred. The unit tests above assert the precise retained-listener signal that a heap snapshot would otherwise show plateauing instead of growing.

- detach idle shared subscription dispatcher after last release

- release terminal close frames before invoking onClose

- strengthen IPC listener-count and cleanup regression coverage
@nwparker

Copy link
Copy Markdown
Contributor Author

Thanks again! Made a few tweaks but otherwise looks good:

  • detach the shared preload dispatcher when the last subscription releases, so the O(1) listener also has a real idle cleanup path
  • release close frames before onClose runs (so a throwing or re-entrant close callback cannot keep renderer state mapped)
  • strengthened the fake IPC in tests to track actual listener add/remove behavior, plus coverage for binary frames, id mismatch, error churn, close, and last-unsubscribe cleanup
  • checked the new leak guard fails against the old per-subscribe listener path
  • verified with focused preload tests, targeted runtime IPC/shared-control tests, full typecheck/lint, and a dev Electron smoke on CDP

@nwparker
nwparker merged commit 2e59e06 into main Jun 28, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/fix-6288 branch June 28, 2026 23:53
nwparker added a commit that referenced this pull request Jun 29, 2026
… (#6667)

* perf: dedupe relay process-table scans behind a short-TTL cache (#6288)

Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=`
(a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a
shared SSH relay every tracked agent terminal drives it, so concurrent panes
each forked their own `ps` — sustaining up to the per-second inspection cap of
full-table scans for as long as agents are open, pinning idle relay CPU and
amplified by AV process scanning. This is the CPU half of #6288 (PR #6564
covers the memory-leak half).

Memoize the scan behind a single in-flight promise + 500ms TTL shared by the
relay and local main-process call sites. 500ms sits below the active poll's
minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a
snapshot older than it would have scanned itself — same data and freshness,
just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2).

Failures are never cached (in-flight cleared on settle) so a transient `ps`
error retries and the existing best-effort fall-through is preserved. Windows
branches are untouched; no git-provider implications.

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

* test: regression guard for #6288 ps-scan volume (repro + measurement)

Drives the real local foreground-inspection call site under the documented
750ms agent-completion cadence across 6 concurrently-inspecting agent panes
over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=`
full-table scans.

Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection;
the test fails there) and proves the fix (240 inspections -> 40 scans,
0.167/inspection — bounded by poll ticks, not pane count) while every pane
still resolves its foreground agent. Guards against regressing the cache back
to a per-call scan.

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

* docs: clarify 500ms TTL covers cadence floor + tolerated event-driven staleness (#6288)

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

---------

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

Copy link
Copy Markdown
Contributor Author

Cross-link: the CPU half of #6288 just merged in #6667 (06392a4) — a shared short-TTL cache that deduplicates the per-pane full-table ps -axo foreground-inspection scans on the relay (240 → 40 scans in a 6-pane/30s repro). This PR covers the memory half (leaked preload IPC subscription listeners). The two are complementary and don't overlap; #6288 is staying open until this one lands.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#6288) (stablyai#6667)

* perf: dedupe relay process-table scans behind a short-TTL cache (stablyai#6288)

Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=`
(a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a
shared SSH relay every tracked agent terminal drives it, so concurrent panes
each forked their own `ps` — sustaining up to the per-second inspection cap of
full-table scans for as long as agents are open, pinning idle relay CPU and
amplified by AV process scanning. This is the CPU half of stablyai#6288 (PR stablyai#6564
covers the memory-leak half).

Memoize the scan behind a single in-flight promise + 500ms TTL shared by the
relay and local main-process call sites. 500ms sits below the active poll's
minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a
snapshot older than it would have scanned itself — same data and freshness,
just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2).

Failures are never cached (in-flight cleared on settle) so a transient `ps`
error retries and the existing best-effort fall-through is preserved. Windows
branches are untouched; no git-provider implications.

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

* test: regression guard for stablyai#6288 ps-scan volume (repro + measurement)

Drives the real local foreground-inspection call site under the documented
750ms agent-completion cadence across 6 concurrently-inspecting agent panes
over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=`
full-table scans.

Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection;
the test fails there) and proves the fix (240 inspections -> 40 scans,
0.167/inspection — bounded by poll ticks, not pane count) while every pane
still resolves its foreground agent. Guards against regressing the cache back
to a per-call scan.

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

* docs: clarify 500ms TTL covers cadence floor + tolerated event-driven staleness (stablyai#6288)

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.

[Bug]: Orca remote server memory usage and CPU usage are too high

1 participant