Repository navigation
fix: bound preload runtime subscription IPC listeners to O(1) (#6288) - #6564
Conversation
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]>
|
Warning Review limit reached
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 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 configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
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 |
EvidenceUnit 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. Key assertions:
Related suites still green (39 passed total): Before/after: listener accumulation under churnModeling the exact failure mode — subscriptions that error during a flap and are never unsubscribed (shared-control subscriptions, by design): 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 Why the fix is safe (root-cause confirmation)Read of 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
|
Thanks again! Made a few tweaks but otherwise looks good:
|
… (#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]>
|
Cross-link: the CPU half of #6288 just merged in #6667 ( |
…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]>
🧑🤝🧑 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 persubscribe()to the single shared channelruntimeEnvironments:subscriptionEvent, and only detached it onunsubscribe()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'sMaxListenersExceededWarningon the channel.Fix: replace the per-subscribe listener with one shared dispatcher per renderer (
ipcinstance) that routes every frame bysubscriptionIdthrough aMap. 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'orunsubscribe(). 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 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— assertsipc.onis 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'sunsubscribe()is the single release path.AI Review Report
Reviewed for correctness, edge cases, cross-platform safety, and elegance.
src/main/ipc/runtime-environments.ts,runtime-environment-transport-routing.ts, and the shared-control state machine that everyonErroris paired with a terminalonClose(so'close'still releases the entry), and that serverok:falseresponse frames are non-terminal by design (handleSharedControlSubscriptionResponse) — the dispatcher preserves both semantics.unsubscribe()after'close'is idempotent; re-entrancy during dispatch is safe (get-then-delete, no map iteration).metaKey/path-separator/shell assumptions; this is the SSH/remote path itself and is provider-agnostic (no GitHub-only naming). TheWeakMapkeyed on the singletonipcRenderermeans exactly one listener per renderer on macOS/Linux/Windows.runtimeEnvironments.call/callRuntimeRpccallers 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
subscriptionIdalready used. No input-handling or auth surface changes. IPC payload shape is unchanged. No injection, traversal, eval, or exfiltration risk introduced.Notes
web-session-tabs-sync.tsandruntime-client-events.tsonlyconsole.warnononErrorand 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 existingscheduleRetrypath. (2) Optionally boundruntime-rpc-call-queue.tsper-environment queues when an environment is known-unreachable, as a defensive measure during long outages.Made with Orca 🐋