Repository navigation
fix(ssh): close the macOS relay's per-terminal pty fd leak - #18534
Conversation
|
Warning Review limit reachedNext included review available in 17 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between f80c1079bda5f54043a5d9495d03e717ae5caea2 and ae51905. 📒 Files selected for processing (1)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 98e77ef and f80c1079bda5f54043a5d9495d03e717ae5caea2. 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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 Resolution Add the required template sections and headings. Include ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
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
f80c107 to
ae51905
Compare
There was a problem hiding this comment.
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 —
applyNodePtyMasterCloexecPatchinssh-relay-deploy.tsstops returningfixedfor non-Linux hosts and only short-circuits Windows (isWindowsRelayPlatform). - Apple-branch cloexec +
low_fdsrewrite — the relay asset adds apty_cloexec(master)call on thepty_posix_spawnpath and rewrites thelow_fdsinit/cleanup (both byte-identical toconfig/patches/[email protected]). - Per-platform build layout and verification —
buildLayout()movesprebuilds/aside on darwin (arming rollback and forcing the node-gyp fall-through) vsbuild/Releaseon Linux; verification splits into/proc/self/fd(Linux, inherited) andlsof(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.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…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

Closes the half of #17915 that #17920 could not have found: macOS relay hosts leak one
/dev/ptmxfd per terminal, and the gate that decides publishability answeredfixedfor them without running anything.Two bugs, one gate
1. The asset patched nothing macOS executes.
FORKPTY_CALL_SITEtargetsdefault:, which sits in the#elsearm ofPtyFork's#if defined(__APPLE__)(pty.cc:378). macOS takespty_posix_spawn.grep -c low_fds config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjsreturned 0.2. The platform gate short-circuited before the script.
applyNodePtyMasterCloexecPatchreturned'fixed'for any non-Linux/Windows host, and'fixed'is what gatespromoteRelayNativeDepsCache. Adarwin-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:In any running process the first
posix_openpt()already returns >= 2, so the loop breaks withcount == 0and the body never runs — and where it does run it closeslow_fds[count], neverlow_fds[0]. Linux takesforkpty()and has nolow_fdsblock 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 (relaypackage.jsonwithallowScripts,npm install --ignore-scripts=false --omit=dev --no-audit --no-fund [email protected] @parcel/[email protected], thefind … -name spawn-helper -exec chmod +xline, the native-deps probe, thennode node-pty-1.1.0-master-cloexec-patch.cjs). One PTY per open/close cycle: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 +fgon a stock build showsR,W,NB, noCX. What actually closes the master in children isPOSIX_SPAWN_CLOEXEC_DEFAULTinpty_posix_spawn's spawn flags, an Apple-only flag closing every fd in the spawned child. That is one option away from gone: settinguid/giddrops libuv back tofork()/exec(), which honors nothing butFD_CLOEXEC. So this also ports the app patch's Apple-branchpty_cloexec(master)call. After: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 nobuild/at all on macOS, so the existingskipped:no-compiled-buildguard would have refused, andnpm rebuildwould no-op (scripts/prebuild.jsexits 0 when the prebuild is present).buildLayout()splits it:build/Releasebuild/Releaseskipped:no-compiled-buildprebuildsbuild/Releaseskipped:no-prebuildMoving
prebuildsaside does double duty on darwin: it arms the rollback and it is what makes node-pty's install script fall through from "prebuild found" tonode-gyp rebuild. Deliberately notnpm_config_build_from_source, which deletes the prebuilds outright and would leave nothing to roll back to.loadNativeModulechecksbuild/Releasebeforeprebuilds, 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 ownlsof, N live ptys must account for exactly N/dev/ptmxrows). Either returnspatched-unverifiedrather 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.gypcorrupted:failed:is not inNODE_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_spawnis inside#if defined(__APPLE__); Linux never compiles it. Re-verified indocker node:22against a real npm install:build/Releasepresent,prebuildsuntouched (node-pty ships no linux prebuild). Thedefault:call site, thepty_cloexecdefinition 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 —
computeRelayNativeDepsCacheKeyhashes each patch artifact's contents (ssh-relay-native-deps-cache.ts:90), andRELAY_NATIVE_DEPS_PATCH_ARTIFACT_PATTERNmatches this asset. Already-published leakydarwin-*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 andgcRelayNativeDepsCachereclaims 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 tcclean;pnpm test src/main/ssh2070 passed / 16 skipped;config/scripts/node-pty-master-cloexec-patch.test.mjs14 passed;pnpm run check:code-quality:changed0 new findings.skipped:no-prebuild, and — inverting the oldnever adds a compile to a macOS relaycase — that a darwin relay now runs the patch and promotes, and that a failed darwin compile does not.Refs #17915
Refs #8362
Note:
static analysisis red for a reason that predates this PRVerify runtime-required localization catalogfails on this branch and on every PR based onmainsincec79e1c097b7("fix(i18n): localize remaining onboarding UI", landed onmaintoday). That commit added 35 keys tosrc/renderer/src/i18n/locales/en.jsonand never regeneratedsrc/renderer/src/i18n/en-runtime-required.json, whose last change is the unrelated #18326. The four keys the gate names arecomponents.onboarding.integrations.capabilities.{browseIssues,managePullRequests,reviewStatus,startWorkspaceFromIssue}— no file in this PR touches i18n or onboarding. The fix is one command onmain,pnpm run sync:localization-runtime-catalog, and is deliberately not bundled into a relay fd-leak PR.verifyis red only because it aggregates that job.All 8
testshards,typecheck,packageandpackage (windows)pass.