Skip to content

fix(computer-use): reap detached macOS helper processes on every teardown path - #14494

Closed
JuuuuHong wants to merge 1 commit into
stablyai:mainfrom
JuuuuHong:fix/computer-use-helper-process-reaping
Closed

JuuuuHong wants to merge 1 commit into
stablyai:mainfrom
JuuuuHong:fix/computer-use-helper-process-reaping

Conversation

@JuuuuHong

Copy link
Copy Markdown
Contributor

Fixes #9141.

Summary

On macOS, computer-use leaks helper processes until the machine runs out of memory. #9141 reports ~200 orca-computer-use-macos processes in 3 hours and 40-50 GB of memory, ending in the "system has run out of application memory" dialog and forced restarts.

I hit this on my own machine on 2026-07-16, a day before #9141 was filed — free memory down to ~80 MB, no new app would launch, and dozens of orca-computer-use-macos processes sitting in state T.

After this change every abandoned helper is reclaimed, so the process count stays flat instead of growing with each request. #9141 asks for helpers to be pooled or registered with RunningBoard/jetsam; this takes a third option — reclaiming abandoned helpers at the source — which removes the unbounded growth without changing how helpers are spawned or authorized.

Root cause. The helper is spawned detached and no handle escapes the spawn function:

const provider = spawn(helperExecutablePath, [...], { detached: true, stdio: 'ignore' })
provider.unref()

startMacOSNativeProviderSocket() returned only socket fields, so the sole way to stop a running helper was a socket message — and terminate only lands if the helper is still reading its socket, which a wedged helper by definition is not. Every path that abandoned a socket (request timeout, socket close, transport error, write failure, app quit) dropped it and left the process running; detached: true means it also survives Orca quitting. The next request then spawns a fresh helper with no reclamation of the previous generation. That is the unbounded growth, and it is consistent with #9141's observed rate of roughly one new helper per 54 seconds against the 60s REQUEST_TIMEOUT_MS.

The pre-existing catch in the transport already did provider.kill('SIGTERM'), so startup failures — including superseded startups, whose throw lands in that same catch — were handled. The gap was every path after a successful connect.

Fix. New macos-native-provider-process-reaping.ts:

  • reapMacOSProviderProcess(provider) — SIGTERM, then SIGKILL after a 2s grace if the process has not exited.
  • Signals go to the ChildProcess handle, not a raw pid. Node no-ops once the child has exited, so a recycled pid can never be signalled.
  • A WeakSet makes reaping exactly-once per process, so overlapping teardown paths cannot stack duplicate signals or timers.
  • MacOSProviderProcessOwner holds the current generation; adopt() reaps the outgoing one, so no generation can be dropped even if its teardown path did not run.

Wiring:

  • The transport takes the owner and adopts the helper immediately after spawn, not after connect. Adopting on connect left a window up to HELPER_CONNECT_TIMEOUT_MS (10s) where nothing held the handle: a quit during startup reaped nothing and the connect continuation never ran, stranding the helper.
  • cleanupSocketDirectory() became releaseHelperGeneration(), reaping the process alongside the socket directory. All four client-side abandon paths already called it, so all four now reclaim the process.
  • handleTransportError and invalidateActiveSocketAfterWriteFailure had identical bodies apart from the error they reject with, so they are merged into invalidateActiveSocket; the file ends up three lines shorter. This also keeps it under the 300-line max-lines cap the added wiring would otherwise have crossed. Happy to split the merge into its own PR if you'd rather review it separately.
  • The helper handle is no longer returned from the transport, since ownership now transfers at spawn.

Four files under src/main/computer/, +249 / −30.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Six regressions in macos-native-provider-client.test.ts:

  1. A helper that ignores terminate gets SIGTERM, then SIGKILL after the grace period.
  2. A helper that exits after SIGTERM is not SIGKILLed.
  3. The previous generation is reaped before a replacement starts, and the replacement is left alone.
  4. A helper whose socket closes on its own — a bare close with no preceding error — is reaped. This is the path most likely to run in the wild.
  5. A helper that already exited before teardown is not signalled, covering the recycled-pid guard.
  6. A superseded startup reaps its helper exactly once.

With the reaping call stubbed to a no-op, five of the six fail, along with three existing tests covering the transport's catch branch. Case 5 asserts that no signal is sent, so it holds either way by construction — it pins the recycled-pid guard rather than the reaping.

src/main/computer is 16 files / 97 tests, all passing. On the full suite I see 52,133 pass and 6 fail, none under src/main/computer. The same 6 fail on a clean upstream/main checkout, so they are not from this change, and they look environment-specific here: 1 in automation-schedules is my non-English locale ('일요일s' vs 'Sundays'; passes under LC_ALL=en_US.UTF-8), 4 in codex-fetcher-pty-settle pick up real Codex state on this machine instead of session: null, and 1 is the #13767 shell-ready repro. I'd expect all 6 green in CI — happy to re-run if CI disagrees.

The reclamation logic is covered directly by the six tests above. What I could not do is reproduce the T-state wedge on demand, since a dev-built helper gets a different code identity and therefore a fresh TCC row.

AI Review Report

Reviewed with an AI coding agent across three passes — general correctness, process lifetime and concurrency, and test adequacy — with each finding checked by hand against the diff before it was applied.

What it flagged and what changed as a result:

  • Helper owned too late. Ownership transferred after connect, leaving a ~10s window where a quit during startup stranded the helper. Moved adopt() to immediately after spawn.
  • Generation could be dropped. adopt() overwrote the previous handle without reaping it, so a teardown path that did not run meant a lost helper. adopt() now reaps the outgoing generation.
  • Duplicate reaping. An early draft reaped the superseded-startup branch explicitly, but that throw is caught by the same function's catch, which already reaps — two SIGTERMs, two timers, two listeners. Removed, and a WeakSet now makes reaping exactly-once regardless of overlapping paths.
  • Untested teardown path. handleSocketClose on the active socket — a helper dying and taking its socket down with a bare close — had no coverage. Added as test 4, plus tests 5 and 6.
  • Rejected suggestion. Replacing the typeof checks in hasProviderExited() with !== null was proposed for idiomatic style; it would read the test doubles' undefined as "already exited" and silently skip reaping, so the typeof form was kept and the reason recorded in a comment.

Cross-platform compatibility was explicitly checked for macOS, Linux, and Windows. Every changed file is under the darwin-gated native-provider path; Linux and Windows go through DesktopScriptProviderClient, and provider selection in computer-provider-lifecycle.ts is unchanged. No keyboard shortcuts, accelerators, or user-facing labels are touched, so there are no CmdOrCtrl or ⌘/Ctrl+ concerns. Paths are built with path.join via the existing macos-native-provider-paths helpers; none were added or changed. No shell is invoked — spawn is called with an argv array and no shell: true. The Electron-specific surface touched is process teardown ordering in the computer-use sidecar, which exists only on the macOS native path.

Security Audit

  • Command execution: no new command or executable is invoked. The existing spawn call is unchanged, still argv-array form with no shell: true, so no argument-injection surface is added. The change only sends signals to a process this code already owned.
  • Signal targeting: signals go to the ChildProcess handle rather than a numeric pid. Node treats the handle as inert once the child has exited, which removes the recycled-pid hazard that process.kill(pid) would introduce — this is a reduction in risk, not an addition. Process-group signalling (kill(-pid)) was deliberately not used, since it would reopen that hazard.
  • Path handling: no new path construction. Socket directory creation, chmod 0o700, and cleanup are untouched apart from being called from a renamed method.
  • Auth and secrets: socket token generation, the 0o600 token file, and its removal after connect are unchanged. No token is logged, and no new value is written to disk.
  • IPC: no new IPC surface. No change to REQUIRED_MACOS_PROVIDER_PROTOCOL_VERSION, the wire format, capability negotiation, or peer authorization.
  • Dependencies: none added or updated.
  • Follow-up: the pre-existing isCurrent guard on the transport's catch can leave provider.token in tmpdir() when a startup is superseded. It is a 0o600 file inside a 0o700 directory, so exposure is limited, but it should be cleaned up — noted below rather than fixed here to keep this PR single-topic.

Notes

Platform-specific behavior. macOS only. Windows and Linux are untouched.

Behavior changes worth flagging:

  • A healthy helper is now usually stopped by SIGTERM rather than by its own terminate handling. shutdown() writes terminate, then signals synchronously; the write only reaches the kernel buffer, so the signal typically wins. This is deliberate: sidecar-entry.ts calls process.exit(0) immediately after shutdownProviders() on the SIGTERM path, so a deferred grace period would never execute there. The terminate write is kept ahead of the signal so a helper that reads it promptly still exits on its own terms.
  • That path depends on the helper not installing a SIGTERM handler. It currently does not — there is no signal() / sigaction / DispatchSourceSignal anywhere in native/computer-use-macos/Sources/. Happy to add a note on the Swift side so a future handler doesn't silently regress this.
  • On the beforeExit path the SIGKILL escalation cannot fire, since the timer is unref()d and the loop is already draining. That path relies on SIGTERM alone, which is sufficient given the point above.
  • Already-stranded helpers and their temp directories are not swept. This stops new leaks; existing ones still need a restart.

Out of scope, happy to file separately: a cap on concurrent helpers, an orphan sweep at startup, process-group teardown, and the provider.token cleanup noted above.

Relation to prior work. #11425 and #11441 covered this gap; #11481 rolled them back with the wider process-boundary effort. This is not a re-land of that effort. No supervisor protocol, no main-process ownership, no peer-PID authorization, and no change to the Swift helper. Helper ownership stays in the computer-use sidecar where it is today, and the client-side change extends cleanupSocketDirectory() — a function every teardown path already called.

Possible lead on the wedge itself, not part of this PR: the helper shells out with unbounded waits in two places — openBundle() runs /usr/bin/open -b <bundleId> and processField() runs /bin/ps, both with waitUntilExit() and no deadline (main.swift:1189, main.swift:3813). A LaunchServices stall there would wedge the helper exactly the way #9141 describes. I can open a separate issue for it.

#9141 is assigned to @OrcaWin. If that work is already underway I'm happy to hand this over — otherwise the issue has had no activity since it was filed and this is contained enough to land on its own.

…down path

The macOS helper is spawned detached and its ChildProcess handle never left
startMacOSNativeProviderSocket(), so the only way to stop a running helper was
a `terminate` socket message — which a wedged helper never reads. Every path
that abandoned a socket left the process alive, and the next request spawned a
replacement, growing without bound (stablyai#9141: ~200 helpers in 3h, 40-50GB).

Thread the handle back to an owner adopted at spawn time and reap it (SIGTERM,
then SIGKILL after a grace period) on every teardown path. Signals target the
ChildProcess handle rather than a pid so a recycled pid can never be hit, and a
WeakSet makes reaping exactly-once across overlapping paths.
@coderabbitai

coderabbitai Bot commented Aug 14, 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 Plus

Run ID: 88374d64-ff34-45c1-95b9-0451f5b5baa6

📥 Commits

Reviewing files that changed from the base of the PR and between a6a6443 and 3d7cba8.

📒 Files selected for processing (4)
  • src/main/computer/macos-native-provider-client.test.ts
  • src/main/computer/macos-native-provider-client.ts
  • src/main/computer/macos-native-provider-process-reaping.ts
  • src/main/computer/macos-native-provider-transport.ts

📝 Walkthrough

Walkthrough

The macOS provider client now owns helper-process lifecycle through MacOSProviderProcessOwner. Provider cleanup reaps processes with immediate SIGTERM and delayed SIGKILL escalation. Socket startup adopts helpers and reaps them on connection failure or supersession. Client shutdown, socket closure, transport errors, and write failures release helper generations. Tests cover process exit, escalation timing, replacement, socket closure, already-exited providers, and superseded startups.

Merge Risk: ⚪ Minimal · up to 3d7cb

This localized macOS process-lifecycle change is merge-ready after normal checks and review, with no actionable merge-blocking risk remaining.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: reaping detached macOS helper processes during teardown.
Description check ✅ Passed The description covers the problem, fix, linked issue, testing, security, scope, and lack of visual change, with only minor template-heading differences.
Linked Issues check ✅ Passed The PR reclaims detached helpers on all identified teardown paths, addressing the unbounded process and memory growth reported in [#9141].
Out of Scope Changes check ✅ Passed The changes remain focused on macOS helper-process ownership, reaping, teardown wiring, and regression tests related to [#9141].
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

@AmethystLiang
AmethystLiang requested a review from OrcaWin August 14, 2026 16:51
@nwparker nwparker removed the P1 label Aug 19, 2026
nwparker added a commit that referenced this pull request Sep 16, 2026
…0926)

Reclaim detached macOS computer-use helpers on abandoned requests and transports. Keep ownership from spawn, escalate SIGTERM to SIGKILL, force pending reaps when the sidecar exits, and clean each failed startup's private socket directory.

Based on #14494 by @JuuuuHong. Preserve the original helper ownership/reaping design and regression tests while retaining the upstream line-buffer optimization and adding real-process teardown and resource-bound tests.

Fixes #9141.

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

Copy link
Copy Markdown
Contributor

Merged through #20926 (07c7606), which ports this implementation and regression coverage to current main. @JuuuuHong is credited for the original diagnosis and implementation in the PR description and the squash commit’s Co-authored-by trailer.

The merged version retains the newer upstream line buffer and adds synchronous cleanup of pending reaps when the sidecar exits, failed-startup directory cleanup, and real-process regressions. All CI checks passed. Closing this PR as superseded by the merged replacement. Thank you for the original work.

@nwparker nwparker closed this Sep 16, 2026
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…ablyai#20926)

Reclaim detached macOS computer-use helpers on abandoned requests and transports. Keep ownership from spawn, escalate SIGTERM to SIGKILL, force pending reaps when the sidecar exits, and clean each failed startup's private socket directory.

Based on stablyai#14494 by @JuuuuHong. Preserve the original helper ownership/reaping design and regression tests while retaining the upstream line-buffer optimization and adding real-process teardown and resource-bound tests.

Fixes stablyai#9141.

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

computer-use spawns ~200 unmanaged helper processes/3h, causing 40-50GB+ memory usage and forced restarts

4 participants