Skip to content

fix(ssh): close the macOS relay's per-terminal pty fd leak - #18534

Merged
nwparker merged 1 commit into
mainfrom
worktree-agent-a9a33d6402fa288b9
Sep 3, 2026
Merged

nwparker merged 1 commit into
mainfrom
worktree-agent-a9a33d6402fa288b9

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​156 $\color{#cf222e}{\Huge{\mathbf{−}}}$​37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​119
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​187 $\color{#cf222e}{\Huge{\mathbf{−}}}$​52 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​135

Closes the half of #17915 that #17920 could not have found: macOS relay hosts leak one /dev/ptmx fd per terminal, and the gate that decides publishability answered fixed for them without running anything.

Two bugs, one gate

1. The asset patched nothing macOS executes. FORKPTY_CALL_SITE targets default:, which sits in the #else arm of PtyFork's #if defined(__APPLE__) (pty.cc:378). macOS takes pty_posix_spawn. grep -c low_fds config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs returned 0.

2. The platform gate short-circuited before the script. applyNodePtyMasterCloexecPatch returned 'fixed' for any non-Linux/Windows host, and 'fixed' is what gates promoteRelayNativeDepsCache. A darwin-arm64-<hash> entry was therefore published to ~/.orca-remote/native/ as non-leaking, so every later host on that machine links a tree that leaks an fd per terminal.

The leak itself is in stock pty_posix_spawn, which opens up to three throwaway ptys to push the real master off fds 0-2 and never closes them:

for (; count > 0; count--) {
  close(low_fds[count]);
}

In any running process the first posix_openpt() already returns >= 2, so the loop breaks with count == 0 and the body never runs — and where it does run it closes low_fds[count], never low_fds[0]. Linux takes forkpty() and has no low_fds block at all, which is why Linux and Docker testing could never surface this.

Measured on real darwin-arm64 hardware

A relay-shaped directory running installNativeDeps' own commands (relay package.json with allowScripts, npm install --ignore-scripts=false --omit=dev --no-audit --no-fund [email protected] @parcel/[email protected], the find … -name spawn-helper -exec chmod +x line, the native-deps probe, then node node-pty-1.1.0-master-cloexec-patch.cjs). One PTY per open/close cycle:

== native deps probe ==      ORCA-NPTY-PROBE-OK
== BEFORE ==
cycle:ptmx  1:1  2:2  3:3  4:4  5:5  6:6  7:7  8:8  9:9  10:10
after 3s settle: ptmx=10
== cloexec patch ==          ORCA-NPTY-CLOEXEC:patched
== AFTER ==
cycle:ptmx  1:0  2:0  3:0  4:0  5:0  6:0  7:0  8:0  9:0  10:0
after 3s settle: ptmx=0

Flat where it grew +1 per cycle, and 0 retained rather than 10. Total patch + compile time: 8.5s. Second run: already-patched.

The SSH transport itself was not exercised on a Mac — Remote Login is off on the machine available to me and enabling it needs a password I do not have. What is reproduced is the entire host-side half, which is all the SSH channel carries: the command in, the ORCA-NPTY-CLOEXEC: status line out.

Correcting a false comment, with the measurement

The asset claimed "macOS re-opens the tty through uv_tty_init's cloexec dup." Measured false — lsof +fg on a stock build shows R,W,NB, no CX. What actually closes the master in children is POSIX_SPAWN_CLOEXEC_DEFAULT in pty_posix_spawn's spawn flags, an Apple-only flag closing every fd in the spawned child. That is one option away from gone: setting uid/gid drops libuv back to fork()/exec(), which honors nothing but FD_CLOEXEC. So this also ports the app patch's Apple-branch pty_cloexec(master) call. After:

node  39744  nwparker  12u  CHR  R,W,NB;CX  15,161  0t0  605  /dev/ptmx

Both new C hunks are byte-identical to config/patches/[email protected], so the desktop and the relay compile the same cleanup.

macOS needs a different build layout, not a wider gate

Flipping the gate alone would have done nothing. node-pty 1.1.0 ships prebuilds/darwin-{x64,arm64} and no build/ at all on macOS, so the existing skipped:no-compiled-build guard would have refused, and npm rebuild would no-op (scripts/prebuild.js exits 0 when the prebuild is present).

buildLayout() splits it:

fallback moved aside compile writes guard
linux build/Release build/Release skipped:no-compiled-build
darwin prebuilds build/Release skipped:no-prebuild

Moving prebuilds aside does double duty on darwin: it arms the rollback and it is what makes node-pty's install script fall through from "prebuild found" to node-gyp rebuild. Deliberately not npm_config_build_from_source, which deletes the prebuilds outright and would leave nothing to roll back to. loadNativeModule checks build/Release before prebuilds, so the compiled artifact wins; on success the prebuild is discarded, matching Linux, so no unpatched binary survives in a tree that gets published.

Verification is per-platform too, because the leaks differ in kind: Linux's is inheritance (a later plain child's /proc/self/fd), macOS's is self-held (this process's own lsof, N live ptys must account for exactly N /dev/ptmx rows). Either returns patched-unverified rather than failing when the host cannot show its fds.

Failure behaviour, verified on the same Mac

macOS has no toolchain guarantee, so a failed compile is the common case, not the rare one. With binding.gyp corrupted:

STATUS: failed:npm rebuild node-pty exited 1: gyp ERR! ...
source reverted:      true      prebuilds restored:  true
build/Release removed:true      backup discarded:    true
skip marker written:  true      node-pty still loads: yes
SECOND ATTEMPT:       skipped:earlier-attempt-failed

failed: is not in NODE_PTY_CLOEXEC_FIXED_STATUSES, so the rolled-back tree is not published — which matters more on darwin than on Linux, because the rollback restores a working prebuild and the tree therefore probes loadable while still leaking. #17920's promotion gate is exactly what catches that.

Linux is unaffected

pty_posix_spawn is inside #if defined(__APPLE__); Linux never compiles it. Re-verified in docker node:22 against a real npm install:

BEFORE  later child sees ptmx: true
patch   ORCA-NPTY-CLOEXEC:patched
AFTER   later child sees ptmx: false
2nd run ORCA-NPTY-CLOEXEC:already-patched

build/Release present, prebuilds untouched (node-pty ships no linux prebuild). The default: call site, the pty_cloexec definition and the forward declaration are unchanged; the only Linux-visible change is the verify script's token (INHERITED → LEAKED, shared with the darwin script), same verdict logic.

Cache keys

The key changes with the patch bytes — computeRelayNativeDepsCacheKey hashes each patch artifact's contents (ssh-relay-native-deps-cache.ts:90), and RELAY_NATIVE_DEPS_PATCH_ARTIFACT_PATTERN matches this asset. Already-published leaky darwin-* entries are therefore naturally orphaned: a patched build mints a new key and can never link the old one. No eviction is needed — once their relay dirs are GC'd they are unreferenced and gcRelayNativeDepsCache reclaims them under its existing tombstone protocol. Same for the relay directory itself, which is content-hashed over the manifest the asset is part of.

Cost

macOS pays a first compile, where Linux pays a second on a path that already compiles. Measured 8.5s end to end on darwin-arm64, once per relay directory ever, bounded by the skip marker, behind the probe that already proved node-pty loadable. That is the price of the only fix there is: the bug is in the source the prebuild was built from.

Verification

  • pnpm tc clean; pnpm test src/main/ssh 2070 passed / 16 skipped; config/scripts/node-pty-master-cloexec-patch.test.mjs 14 passed; pnpm run check:code-quality:changed 0 new findings.
  • New specs: the Apple-branch rewrite (anchors + the stock loop's absence), the darwin prebuild layout, darwin rollback, skipped:no-prebuild, and — inverting the old never adds a compile to a macOS relay case — that a darwin relay now runs the patch and promotes, and that a failed darwin compile does not.

Refs #17915
Refs #8362


Note: static analysis is red for a reason that predates this PR

Verify runtime-required localization catalog fails on this branch and on every PR based on main since c79e1c097b7 ("fix(i18n): localize remaining onboarding UI", landed on main today). That commit added 35 keys to src/renderer/src/i18n/locales/en.json and never regenerated src/renderer/src/i18n/en-runtime-required.json, whose last change is the unrelated #18326. The four keys the gate names are components.onboarding.integrations.capabilities.{browseIssues,managePullRequests,reviewStatus,startWorkspaceFromIssue} — no file in this PR touches i18n or onboarding. The fix is one command on main, pnpm run sync:localization-runtime-catalog, and is deliberately not bundled into a relay fd-leak PR. verify is red only because it aggregates that job.

All 8 test shards, typecheck, package and package (windows) pass.

@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

Next included review available in 17 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: a98250d1-0896-473b-a65a-acbc7c16fbd9

📥 Commits

Reviewing files that changed from the base of the PR and between f80c1079bda5f54043a5d9495d03e717ae5caea2 and ae51905.

📒 Files selected for processing (1)
  • src/main/ssh/ssh-relay-pty-master-cloexec-install.test.ts

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 89908041-bdb4-47b1-b0d5-842a3b1ccc47

📥 Commits

Reviewing files that changed from the base of the PR and between 98e77ef and f80c1079bda5f54043a5d9495d03e717ae5caea2.

📒 Files selected for processing (4)
  • config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs
  • config/scripts/node-pty-master-cloexec-patch.test.mjs
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-pty-master-cloexec-install.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The node-pty relay patch now handles fd leaks on Linux and macOS. It adds macOS source rewriting, platform-specific verification, and artifact rollback. Relay deployment applies the patch on both Unix platforms and skips unsupported Windows paths. Tests cover macOS rebuilds, rollback, missing prebuilds, unsupported platforms, source rewriting, and cache promotion.

Merge Risk: ⚪ Minimal · up to f80c1

This change applies and verifies the node-pty file-descriptor leak fix on macOS while retaining rollback behavior for failed rebuilds. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed context, implementation rationale, linked issues, platform coverage, measurements, and test results. However, it does not follow the required template structure and o… Add the required template sections and headings. Include N/A with a brief reason under Visual Proof because this is not a UI change, complete the checklist, and address Review, Agent skill upstream boundary, Notes, and AI Disclosure as ap…
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely identifies the primary change: fixing the macOS relay per-terminal pty file-descriptor leak.
Full details: Description check

Explanation

The description provides detailed context, implementation rationale, linked issues, platform coverage, measurements, and test results. However, it does not follow the required template structure and omits required items such as the Visual Proof section with N/A and a reason, the checklist, and explicit review and boundary sections.

Resolution

Add the required template sections and headings. Include N/A with a brief reason under Visual Proof because this is not a UI change, complete the checklist, and address Review, Agent skill upstream boundary, Notes, and AI Disclosure as applicable.

✨ Finishing Touches 💡 1
📝 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.

The relay asset from #17920 only rewrote the forkpty `default:` call site, which
sits in the `#else` arm of PtyFork's `#if defined(__APPLE__)`. macOS takes
`pty_posix_spawn`, so the asset had never patched anything a Mac executes -- and
`applyNodePtyMasterCloexecPatch` returned 'fixed' for any non-Linux host without
running the script at all, which is what publishes a tree to the shared
native-deps cache.

Stock `pty_posix_spawn` opens up to three throwaway ptys to push the real master
off fds 0-2 and never closes them: the cleanup loop is `for (; count > 0;
count--)`, but the first `posix_openpt()` in a running process already returns
>= 2, so it breaks with `count == 0` and the body never runs -- and where it does
run it closes `low_fds[count]`, never `low_fds[0]`. One orphaned /dev/ptmx fd per
terminal, for the life of the relay.

Ports the `low_fds` fix and the Apple-branch `pty_cloexec(master)` call from the
app's `config/patches/[email protected]`, byte-identical, and runs the gate on
darwin. macOS needs a different build layout than Linux: it has no `build/` at
all, so the fallback moved aside is `prebuilds/darwin-<arch>` -- which is also
what makes node-pty's install script fall through from "prebuild found" to
node-gyp -- and the compile writes a `build/Release` the loader checks first.
Verification is per-platform too: Linux's leak is inheritance (/proc), macOS's is
self-held (lsof).

Also corrects the asset's claim that "macOS re-opens the tty through uv_tty_init's
cloexec dup". Measured false: FD_CLOEXEC is not set on the master. What protects
it is POSIX_SPAWN_CLOEXEC_DEFAULT, one option away from gone since uid/gid drops
libuv back to fork()/exec() -- so the master is now marked there too.

Measured on darwin-arm64, one PTY per open/close cycle in a relay-shaped dir
running the relay's own commands:

  before  cycle:ptmx  1:1 2:2 3:3 ... 10:10   (10 after a settle)
  after   cycle:ptmx  1:0 2:0 3:0 ... 10:0    (0 after a settle)

Linux re-verified in docker node:22: inherited before, isolated after,
`already-patched` on the second run.

Refs #17915
Refs #8362
@nwparker
nwparker force-pushed the worktree-agent-a9a33d6402fa288b9 branch from f80c107 to ae51905 Compare September 3, 2026 22:39

@pullfrog pullfrog 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.

Important

The relay still leaks one pty fd per terminal on macOS: pty_posix_spawn's slave. The low_fds throwaway is closed, but the parent process's slave fd is not — and the darwin verify script can't see it, so a still-leaking tree reports ISOLATED and is published.

Reviewed changes

  • Gate now reaches macOS — applyNodePtyMasterCloexecPatch in ssh-relay-deploy.ts stops returning fixed for non-Linux hosts and only short-circuits Windows (isWindowsRelayPlatform).
  • Apple-branch cloexec + low_fds rewrite — the relay asset adds a pty_cloexec(master) call on the pty_posix_spawn path and rewrites the low_fds init/cleanup (both byte-identical to config/patches/[email protected]).
  • Per-platform build layout and verification — buildLayout() moves prebuilds/ aside on darwin (arming rollback and forcing the node-gyp fall-through) vs build/Release on Linux; verification splits into /proc/self/fd (Linux, inherited) and lsof (darwin, self-held).

⚠️ The slave fd still leaks per terminal on macOS, and the verify script cannot see it

The stated goal is "close the macOS relay's per-terminal pty fd leak", but the patch only closes one of the two fds pty_posix_spawn opens in the relay process. slave = open(slave_pty_name, O_RDWR | O_NOCTTY) (fixture config/scripts/__fixtures__/node-pty-1.1.0-unix-pty.cc:725) is dup2'd into the child and closed in the child by posix_spawn_file_actions_addclose, but the parent's copy is never closed on the success path — one /dev/ttysXXX fd leaks per terminal for the life of the relay. The app's pnpm patch already fixes this (close(slave) in the done: block of config/patches/[email protected]), so the claim that "the desktop and the relay compile the same cleanup" (.cjs:137, PR body) is inaccurate: the relay's REPLACEMENTS array stops at low_fds.

Worse, the darwin verifier is blind to it: VERIFY_SELF_FDS_SCRIPT filters lsof output for /dev/ptmx only, and low_fds fds are /dev/ptmx while the slave is /dev/ttysXXX. After the low_fds fix, 3 spawns hold 3 masters (/dev/ptmx) plus 3 leaked slaves (/dev/ttysXXX); the check sees exactly 3 /dev/ptmx rows and reports ISOLATED, so a tree that still leaks one fd per terminal is published to the shared cache.

Technical details
# Close the parent's slave fd on the macOS path

## Affected sites
- config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs:160-167 — `REPLACEMENTS` has no `close(slave)` hunk; the forkpty `DEFINITION`/`FORKPTY_CALL_SITE` only mark the master cloexec.
- config/scripts/__fixtures__/node-pty-1.1.0-unix-pty.cc:725 — `slave = open(...)`; never closed in the parent on success (only `low_fds` at :781-783).
- config/patches/node-[email protected] — app's `done:` block closes `slave` (`close(slave)`), which the relay omits.
- config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs:290 — `VERIFY_SELF_FDS_SCRIPT` filters `line.includes('/dev/ptmx')`, so slave (`/dev/ttysXXX`) leaks are invisible.

## Required outcome
- The relay's patched `pty_posix_spawn` closes the parent's `slave` fd on the success path (and ideally error paths), matching the app's patched `done:` block.
- Verification on darwin accounts for the slave fd, or the parity claim is scoped honestly to `low_fds` only.

## Open questions for the human
- Is `close(slave)` deliberately out of scope for the relay patch, or an omission? If out of scope, the PR title/body ("per-terminal pty fd leak") and the "same cleanup" comment should be narrowed to the `/dev/ptmx` throwaway only.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

ℹ️ No new issues in this delta.

Reviewed changes — since the prior review (f80c107), this push corrects a single stale comment reference in ssh-relay-pty-master-cloexec-install.test.ts: the "does not publish a tree the patch refused to touch" spec now names skipped:unsupported-platform instead of the removed skipped:not-linux, matching the gate rename in the main commit. Comment-only; no behavioral surface.

The [!IMPORTANT] finding from the prior review (the parent's slave fd still leaks per terminal on macOS and is invisible to VERIFY_SELF_FDS_SCRIPT) is not touched by this delta and remains open.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 04ae622 into main Sep 3, 2026
29 of 31 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…18534)

The relay asset from stablyai#17920 only rewrote the forkpty `default:` call site, which
sits in the `#else` arm of PtyFork's `#if defined(__APPLE__)`. macOS takes
`pty_posix_spawn`, so the asset had never patched anything a Mac executes -- and
`applyNodePtyMasterCloexecPatch` returned 'fixed' for any non-Linux host without
running the script at all, which is what publishes a tree to the shared
native-deps cache.

Stock `pty_posix_spawn` opens up to three throwaway ptys to push the real master
off fds 0-2 and never closes them: the cleanup loop is `for (; count > 0;
count--)`, but the first `posix_openpt()` in a running process already returns
>= 2, so it breaks with `count == 0` and the body never runs -- and where it does
run it closes `low_fds[count]`, never `low_fds[0]`. One orphaned /dev/ptmx fd per
terminal, for the life of the relay.

Ports the `low_fds` fix and the Apple-branch `pty_cloexec(master)` call from the
app's `config/patches/[email protected]`, byte-identical, and runs the gate on
darwin. macOS needs a different build layout than Linux: it has no `build/` at
all, so the fallback moved aside is `prebuilds/darwin-<arch>` -- which is also
what makes node-pty's install script fall through from "prebuild found" to
node-gyp -- and the compile writes a `build/Release` the loader checks first.
Verification is per-platform too: Linux's leak is inheritance (/proc), macOS's is
self-held (lsof).

Also corrects the asset's claim that "macOS re-opens the tty through uv_tty_init's
cloexec dup". Measured false: FD_CLOEXEC is not set on the master. What protects
it is POSIX_SPAWN_CLOEXEC_DEFAULT, one option away from gone since uid/gid drops
libuv back to fork()/exec() -- so the master is now marked there too.

Measured on darwin-arm64, one PTY per open/close cycle in a relay-shaped dir
running the relay's own commands:

  before  cycle:ptmx  1:1 2:2 3:3 ... 10:10   (10 after a settle)
  after   cycle:ptmx  1:0 2:0 3:0 ... 10:0    (0 after a settle)

Linux re-verified in docker node:22: inherited before, isolated after,
`already-patched` on the second run.

Refs stablyai#17915
Refs stablyai#8362
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