Repository navigation
fix(ssh): close the pty master fd leak on relay hosts too - #17920
Conversation
There was a problem hiding this comment.
ℹ️ No critical issues — one minor observability nit inline.
Reviewed changes
This PR re-applies the app's pnpm pty_cloexec fix to the relay's stock npm copy of [email protected], so Linux relay hosts stop leaking the pty master fd into every later child.
- New relay patch asset —
config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjssha256-keys the publishedpty.cc, applies the forkptyFD_CLOEXECcall,npm rebuilds, verifies in a child process, and rolls back + writes a one-shot skip marker on any failure. - Delivery wiring — the asset is registered in
RELAY_ARTIFACTS(shipped to all platforms so its bytes change the relay content hash) and copied bybuild-relay.mjs. - Install-path hook —
applyNodePtyMasterCloexecPatchinssh-relay-deploy.tsruns only on Linux after node-pty is proven loadable, and is non-fatal on error. - Tests — a 10-case byte-exact patch/rollback suite plus a 4-case install-path suite; the app's existing native-deps tests gain the new exec slot.
I read the full diff, traced the install/repair flow, confirmed the relay patch is a faithful Linux subset of the app's pnpm patch (binding.gyp/.symver glibc pins correctly omitted since the relay compiles on the target host), and ran the new suites plus tc:node — all green.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Delivery-mechanism note (from independent recon)Recording why this ships as a relay asset rather than relying on the pnpm patch, since it is non-obvious and a future change could silently undo it. pnpm patches do not cross the SSH boundary. Stock tarball, and So a pnpm-patch-only cloexec fix would have been silently ineffective on relay hosts — precisely where the 193 leaked master fds were measured. This PR adds One cost worth a maintainer's eye before mergeThe artifact list feeds the relay content hash, and the hash selects the immutable remote directory. Adding a Linux relay asset changes That lands on top of the user report behind this sweep ("relays … taking several minutes to connect"), and #17891 exists because an unanswered deps probe was read as "all deps missing" and looped an 8-minute rebuild to the 900s cap. Worth confirming before merge that the one-time rebuild is cleanly one-per-host and does not interact with a retry path. There is a standing TODO for the durable answer at |
Correction to my previous comment, plus two concrete findingsMy cost framing above was wrong. I said adding a Linux relay asset "forces a fresh install dir and a full native-deps reinstall on every host." That is true but not attributable to this PR — it is the status quo for any relay change. The marginal cost actually attributable to this PR is the second compile: the Finding 1 — the timeout budget does not have room for this (worth acting on before merge)
export const NATIVE_DEPS_COMMAND_TIMEOUT_MS = 240_000
const NATIVE_DEPS_REPAIR_BUDGET_MS = 2 * NATIVE_DEPS_COMMAND_TIMEOUT_MS // 480s
export const RELAY_DEPLOY_TIMEOUT_MS = NATIVE_DEPS_REPAIR_BUDGET_MS + 7 * 60_000 // 900sThe 7-minute slack is explicitly sized for the separately bounded chmod/probe/diagnostic/finalize commands around install + rebuild — not for another compile. This branch gives the cloexec command the full Suggest either a tighter timeout on the cloexec step or a bump to Finding 2 — sequencing: #17891 should land before or with thisThe #17891 defect is still live on main. This PR's guards are good on the paths they cover — Linux-only, gated behind The one gap: Verdict: with #17891's probe fix, this is cleanly one rebuild per relay directory. Without it, this adds a compile to a path that already has a known runaway. Not a blocker: #1693#1693 is a TODO comment, not code — no relay prebuild pipeline exists, so there is nothing to sequence behind. This branch is already forward-compatible with it (the |
Merge blocker found: this makes
|
Correction to the evidence framing — the fix is still right, the headline number was notI have been citing "193 leaked pty master fds on a Linux host in a 9,10,11…20 pattern" as the production evidence for this PR. Adversarial review shows that framing is impossible as stated, and the correction matters for how the fix gets validated. A single process cannot produce a repeating fd run. fd numbers are unique within one process table, so a set containing Independently confirmed by a hard cap: And the repo's own probe agrees — This still supports the CLOEXEC hypothesis — more precisely than beforefork/exec preserves fd numbers, so every child shows the parent's numbers. Two shapes fit 193:
So the evidence supports the branch's hypothesis. It does not support "193 distinct leaked PTYs," and nobody should validate this fix against that number. Three things reviewers should know
Two gaps in the fix itself, unchanged by the above
The underlying fix is real: Linux takes |
Validation procedure — read this before verifying the fix on a live hostFollow-up to the evidence correction above. There is a way to misread the result: Expect the census to drop to ~0 while the relay's own fd table is unchanged. The leak is inherited copies in children, not extra masters in the relay. So the discriminator is a before/after run of that same probe on the same host — the probe cannot tell an inherited master from one a process opened itself, and a nested pty-creating program in a remote terminal would look identical in a single sample. Also confirmed: Linux is the correct and only target. One amplifier, and two adjacent leaks that are not this bugAmplifier (same bug, worth knowing): Two genuine competing leaks, both bounded by
Both are separate defects from this PR's scope. Filing them is worthwhile; folding them in here is not. |
Correction: the prerequisite is #17907, not #17891I recorded the ordering constraint as #17891 → #17920. That is wrong. Audit found this PR's own catch block names the real dependency:
That repair path is introduced by #17907 ( Corrected constraint: #17891 → #17907 → #17920. That matters specifically because this PR's failure mode is an interrupted rebuild: it adds a 240s remote node-gyp compile, and a connection dropped mid-compile leaves node-pty unloadable with the skip marker unwritten. Landing it without #17907 means the recovery it assumes does not exist. Also confirmed from the same audit, and worth stating plainly on this PR: |
Live production measurement on a real Linux host — the fd numbers are diagnosticMeasured on the reporter's Ubuntu box ( The inheritance signature, shown directlyTwo different processes holding the same fd numbers: fd numbers are unique within a process, so identical numbers across two processes can only come from fork inheritance. And the later-spawned child holds two more of the run than the earlier one — the triangular growth shape predicted from the CLOEXEC hypothesis: child k inherits the k masters open at its spawn instant. This is not merely consistent with the hypothesis; it is close to diagnostic of it. It also confirms the corrected framingThe relay processes themselves hold 0–21 masters each — nowhere near a limit, and legitimately so, one per live terminal. The 355 is entirely duplicates in children: So the user-visible harm is the one the patch header names: a child holding a dup keeps Validation note for whoever verifies this fix: expect the census to drop toward ~0 while the relay's own fd count is unchanged. A flat relay fd table is the expected outcome, not evidence the fix failed. Relay accumulation, separately23 live relay processes across 11 install directories with 33 sockets, oldest 10 days. That is item C — "SSH perf degrades over time" — measured rather than inferred, and it is the blast radius of the Cross-posted to #17821. |
A deterministic reproduction exists — use it to validate this fix#17940's 1 + 2 + 3 + 4 + 5 = 15. Exactly the triangular-growth signature: child k inherits the k masters open at its spawn instant. This is the same shape as the live openclaw measurement (355 masters; identical fd numbers appearing across separate processes) — but reproducible on demand rather than observed after ten days of drift. And it isolates where the leak comes from. Across five reconnects the count stays flat at 21: So it accumulates on spawn, not on reconnect. That narrows validation considerably. Concrete validation procedureWith this patch applied, in that spec:
I flagged earlier that a flat relay fd table is the expected outcome and not evidence of failure — this spec makes that concrete, because it reports both numbers separately. Worth adding the assertion to that spec once this lands, so the fix is guarded rather than merely measured. Today the spec records |
be86269 to
092b44f
Compare
|
Too many files changed for review (1246 files, 100 file limit). |
d69897a to
5037245
Compare
There was a problem hiding this comment.
Important
A failed patch still gets promoted to the shared cache, re-opening the leak machine-wide.
Reviewed changes
This delta makes the relay cloexec patch coexist with the shared native-deps cache: the patch now runs before promotion, so a published entry is already patched.
- Reordered patch before promotion —
installNativeDepsnow appliesapplyNodePtyMasterCloexecPatchbeforepromoteRelayNativeDepsCache, both gated onprobe.available. - Documented the immutability interaction — added doc comments in
ssh-relay-deploy.tsandssh-relay-native-deps-cache.tsexplaining the ordering and why a linked entry never reaches the patch. - Pinned ordering and key in tests — new specs assert patch-before-promote, that a linked entry is never patched, and that the patch asset's bytes enter the cache key.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
94b211f to
ab097ec
Compare
The app gets the FD_CLOEXEC patch through pnpm patchedDependencies (#17914); the relay installs stock node-pty from npm, where no pnpm patch reaches. Linux is where that matters -- it is the only relay platform that takes forkpty()'s no-atomic-O_CLOEXEC path, and it is also the only one that already compiles node-pty at install time, so the fix costs a second compile rather than a first. Ships the patch as a relay asset applied like the existing Windows console-list one, and rebuilds only after the probe has proven node-pty loadable. The rebuild is non-fatal by construction: the working build is moved aside first and moved back on any failure, a failed attempt drops a skip marker so the compile is attempted at most once per relay directory, and the caller swallows the whole step. macOS and Windows relays never run it. Measured on node:22 with a relay-style npm install: before, the master is cloexec=false and shows up as `26 -> /dev/pts/ptmx` in both a later pty child and a later child_process child; after, cloexec=true and neither child sees it. Closes #17915.
…ixtures These sequences are positional, so the new Linux-only patch exec swallowed the READY slot and every install/repair case timed out waiting for the relay.
ab097ec to
411fda4
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This delta closes the prior [!IMPORTANT] — the deploy now refuses to publish a native-deps tree whose cloexec patch did not take, instead of promoting it into the shared cache under a key that hashes the patch's bytes.
- Patch outcome returned instead of discarded —
applyNodePtyMasterCloexecPatchnow yields'fixed' | 'unfixed', mapped from an allowlist (patched,patched-unverified,already-patched,skipped:not-linux) rather than afailed:denylist, so the mixedskipped:family resolves correctly. - Promotion gated on the outcome —
promoteRelayNativeDepsCacheruns only when the outcome is'fixed'; otherwise the tree stays private and logs[ssh-relay][NPTY-CLOEXEC-UNSHARED]atconsole.warn, which also surfaces the previously info-only failure case. - Tests pin the refusal — new specs assert a
failed:and askipped:earlier-attempt-failedtree are not published, whilepatched-unverified(rebuilt from patched source, isolation check unobservable) still is.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change adds a Linux-only node-pty 1.1.0 source patch that sets Merge Risk: 🟡 Moderate · up to If patch installation fails while restoring the existing native build, the relay can fail to record the attempt or return the expected deployment status, leaving the deployment path in an ambiguous state. This bounded rollback risk should be fixed before merging. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and covers the change, motivation, linked issue, before-and-after behavior, failure handling, testing, and platform scope. It does not use the repository template headings or include the checklist and AI disclosure fields, but the required technical information is mostly present. Full details: Linked Issues checkExplanation The PR satisfies issue
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 9c8bbe66-cf63-4205-9a87-11668dcae34b
📒 Files selected for processing (15)
config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjsconfig/scripts/__fixtures__/node-pty-1.1.0-unix-pty.ccconfig/scripts/build-relay.mjsconfig/scripts/node-pty-master-cloexec-patch.test.mjssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-native-deps-cache-deploy.test.tssrc/main/ssh/ssh-relay-native-deps-cache.tssrc/main/ssh/ssh-relay-native-deps-install-fixture.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/main/ssh/ssh-relay-native-deps-probe-verdict.test.tssrc/main/ssh/ssh-relay-node-pty-spawn-repair.test.tssrc/main/ssh/ssh-relay-pty-master-cloexec-install.test.tssrc/main/ssh/ssh-relay-sftp-namespace-install.test.tssrc/shared/relay-artifacts.tssrc/shared/relay-optional-artifacts.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| rmSync(backupDir, { recursive: true, force: true }) | ||
| return verdict === 'isolated' ? 'patched' : 'patched-unverified' | ||
| } catch (err) { | ||
| rollback(relayDir, releaseDir, backupDir) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
rollback can throw and break the documented never-throws contract.
The header comment at Line 244 states this function never throws, and the caller runs on the connect path. rollback calls rmSync, mkdirSync, and renameSync without protection. If any of them fails (for example EACCES or EBUSY on the release directory), the error propagates out of the catch block. The skip marker is then never written, and the status line at Line 305 never prints, so the deploy side receives no ORCA-NPTY-CLOEXEC: token at all.
Contain the rollback failure and still record the attempt.
🛡️ Proposed fix
} catch (err) {
- rollback(relayDir, releaseDir, backupDir)
+ try {
+ rollback(relayDir, releaseDir, backupDir)
+ } catch (rollbackErr) {
+ // Why: the caller is on the connect path; a failed restore must still report a status.
+ err.message = `${err.message} (rollback failed: ${rollbackErr.message})`
+ }
// Bounded on purpose: one compile attempt per relay directory, never a retry loop.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| rollback(relayDir, releaseDir, backupDir) | |
| try { | |
| rollback(relayDir, releaseDir, backupDir) | |
| } catch (rollbackErr) { | |
| // Why: the caller is on the connect path; a failed restore must still report a status. | |
| err.message = `${err.message} (rollback failed: ${rollbackErr.message})` | |
| } |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This delta tightens the observability gap left open on the prior run: the patch status is now surfaced at console.warn the moment it resolves, not only on the shared-cache path.
- Unfixed status warned directly —
applyNodePtyMasterCloexecPatchemits[ssh-relay][NPTY-CLOEXEC-UNFIXED]atconsole.warnfor any status outside the fixed allowlist (failed:, refusals,no-status), before returning'unfixed', so a host that stays leaky is greppable regardless of whether it has a cache to publish to. - Test pins the warn — the refusal spec now asserts the
NPTY-CLOEXEC-UNFIXEDwarning appears, closing the earlier "info-level only" nit completely. - The base was retargeted from
fix/pty-master-fd-cloexectomain; the removed hunks in the range-diff are the merged #17914 content dropping out, not this PR's work.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…thing covered Test-only. No production code. ## The freeze repro was rotted in three ways, not one #16764 tracks four stale call sites. There were three separate problems: 1. **Stale call sites** — `execInTerminal` gained a `ptyId` and `splitActiveTerminalPane` gained a direction. (`startDockerSshRelayTarget`'s missing `testInfo` was the third; #18257 has since landed it on main.) 2. **It connected before session restore settled**, so the seeded tab never bound to a remote PTY and the terminal sat on "Connecting…" forever. 3. **It could never have passed, even once.** It waited for a one-shot `READY:` line through a 4000-char terminal window while its own 2 KB-every-8 ms flood buries that line within ~16 ms. Readiness is now keyed on the repeating `BG:` flood marker, which is strictly stronger — it proves the pane is streaming rather than merely started. It now runs end to end and prints a measurement instead of dying on a call site: ``` [freeze-repro R2] hiddenFloodMaxLagMs 2.1 bulkOpenMaxLagMs 41.5 interactionProbeMs 53.6 softFreeze false hardFreeze false ``` **It is still not CI-gateable, and the exclusion comment now says so.** The same spec on the same commit measured `bulkOpen 2575.6ms / interaction 3464.2ms` on a GitHub ubuntu runner against a 2500 ms soft budget — a ~60x spread on the number the budget reads, with the relay still streaming. That is the budget failing, not the product. The earlier draft of this comment claimed "repaired and passing", which was true only of the host it was measured on; gating this needs a host-relative oracle, not a bigger constant. ## New: a half-open link is judged, not wedged The fixture image has no `iptables` and the container has no `NET_ADMIN`, so `docker pause` is used instead — a harder case, because the container's TCP stack keeps ACKing: no FIN, no RST, and the socket looks perfectly healthy. Only an application-level probe can detect it. ``` [half-open] {"verdict":"reconnecting","verdictMs":25135,"budgetMs":90000} ``` Nothing in the suite covered the failure mode behind the "SSH hangs until I restart Orca" reports. ## New: resource accumulation measured on the remote host 6 terminals, then 5 reconnect cycles, counted on the container itself: ``` open: pts 1->6 (exactly 1/terminal), relay fds 25->30 (exactly 1/terminal) reconnect: pts flat at 6, relay procs flat at 1, node procs flat at 3 ``` `leakedMasterFdCount` is now **asserted**, not merely recorded. It counts PTY master fds held by non-relay processes: without `FD_CLOEXEC` a master is inherited by every later child, so terminal k adds k of them — the triangular signature measured as 15 across 5 terminals before the fix. #17914 patched the app and daemon and #17920 shipped the same patch to the relay host, and both are now on main, so the correct value is 0 and the probe holds it there: ``` baseline leakedMasterFdCount 0 6 terminals leakedMasterFdCount 0 (holders: only relay.js, n=6) reconnects leakedMasterFdCount 0 across all 5 cycles ``` Any growth here means the relay's node-pty rebuild did not take on that host, which is exactly what a remote-host probe exists to catch — and it is the half of #17914's claim that no unit test can reach. ## Routing Both new probes are claimed by `run-ssh-docker-e2e.mjs` (a Docker-gated spec no runner names self-skips everywhere and still reports green) **and** by the `ssh-terminal-source` route in `pr-e2e-source-routing.mjs`, so they run when the relay and SSH code they guard changes rather than only on a scheduled lane.
…thing covered (#17940) Test-only. No production code. ## The freeze repro was rotted in three ways, not one #16764 tracks four stale call sites. There were three separate problems: 1. **Stale call sites** — `execInTerminal` gained a `ptyId` and `splitActiveTerminalPane` gained a direction. (`startDockerSshRelayTarget`'s missing `testInfo` was the third; #18257 has since landed it on main.) 2. **It connected before session restore settled**, so the seeded tab never bound to a remote PTY and the terminal sat on "Connecting…" forever. 3. **It could never have passed, even once.** It waited for a one-shot `READY:` line through a 4000-char terminal window while its own 2 KB-every-8 ms flood buries that line within ~16 ms. Readiness is now keyed on the repeating `BG:` flood marker, which is strictly stronger — it proves the pane is streaming rather than merely started. It now runs end to end and prints a measurement instead of dying on a call site: ``` [freeze-repro R2] hiddenFloodMaxLagMs 2.1 bulkOpenMaxLagMs 41.5 interactionProbeMs 53.6 softFreeze false hardFreeze false ``` **It is still not CI-gateable, and the exclusion comment now says so.** The same spec on the same commit measured `bulkOpen 2575.6ms / interaction 3464.2ms` on a GitHub ubuntu runner against a 2500 ms soft budget — a ~60x spread on the number the budget reads, with the relay still streaming. That is the budget failing, not the product. The earlier draft of this comment claimed "repaired and passing", which was true only of the host it was measured on; gating this needs a host-relative oracle, not a bigger constant. ## New: a half-open link is judged, not wedged The fixture image has no `iptables` and the container has no `NET_ADMIN`, so `docker pause` is used instead — a harder case, because the container's TCP stack keeps ACKing: no FIN, no RST, and the socket looks perfectly healthy. Only an application-level probe can detect it. ``` [half-open] {"verdict":"reconnecting","verdictMs":25135,"budgetMs":90000} ``` Nothing in the suite covered the failure mode behind the "SSH hangs until I restart Orca" reports. ## New: resource accumulation measured on the remote host 6 terminals, then 5 reconnect cycles, counted on the container itself: ``` open: pts 1->6 (exactly 1/terminal), relay fds 25->30 (exactly 1/terminal) reconnect: pts flat at 6, relay procs flat at 1, node procs flat at 3 ``` `leakedMasterFdCount` is now **asserted**, not merely recorded. It counts PTY master fds held by non-relay processes: without `FD_CLOEXEC` a master is inherited by every later child, so terminal k adds k of them — the triangular signature measured as 15 across 5 terminals before the fix. #17914 patched the app and daemon and #17920 shipped the same patch to the relay host, and both are now on main, so the correct value is 0 and the probe holds it there: ``` baseline leakedMasterFdCount 0 6 terminals leakedMasterFdCount 0 (holders: only relay.js, n=6) reconnects leakedMasterFdCount 0 across all 5 cycles ``` Any growth here means the relay's node-pty rebuild did not take on that host, which is exactly what a remote-host probe exists to catch — and it is the half of #17914's claim that no unit test can reach. ## Routing Both new probes are claimed by `run-ssh-docker-e2e.mjs` (a Docker-gated spec no runner names self-skips everywhere and still reports green) **and** by the `ssh-terminal-source` route in `pr-e2e-source-routing.mjs`, so they run when the relay and SSH code they guard changes rather than only on a scheduled lane.
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
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
…7920) * fix(ssh): close the pty master fd leak on Linux relay hosts The app gets the FD_CLOEXEC patch through pnpm patchedDependencies (stablyai#17914); the relay installs stock node-pty from npm, where no pnpm patch reaches. Linux is where that matters -- it is the only relay platform that takes forkpty()'s no-atomic-O_CLOEXEC path, and it is also the only one that already compiles node-pty at install time, so the fix costs a second compile rather than a first. Ships the patch as a relay asset applied like the existing Windows console-list one, and rebuilds only after the probe has proven node-pty loadable. The rebuild is non-fatal by construction: the working build is moved aside first and moved back on any failure, a failed attempt drops a skip marker so the compile is attempted at most once per relay directory, and the caller swallows the whole step. macOS and Windows relays never run it. Measured on node:22 with a relay-style npm install: before, the master is cloexec=false and shows up as `26 -> /dev/pts/ptmx` in both a later pty child and a later child_process child; after, cloexec=true and neither child sees it. Closes stablyai#17915. * test(ssh): feed the cloexec patch exec to the hand-rolled namespace fixtures These sequences are positional, so the new Linux-only patch exec swallowed the READY slot and every install/repair case timed out waiting for the relay. * fix(ssh): patch the pty master before publishing the shared native-deps tree * fix(ssh): refuse to publish a native-deps tree whose cloexec patch did not take
…thing covered (stablyai#17940) Test-only. No production code. ## The freeze repro was rotted in three ways, not one stablyai#16764 tracks four stale call sites. There were three separate problems: 1. **Stale call sites** — `execInTerminal` gained a `ptyId` and `splitActiveTerminalPane` gained a direction. (`startDockerSshRelayTarget`'s missing `testInfo` was the third; stablyai#18257 has since landed it on main.) 2. **It connected before session restore settled**, so the seeded tab never bound to a remote PTY and the terminal sat on "Connecting…" forever. 3. **It could never have passed, even once.** It waited for a one-shot `READY:` line through a 4000-char terminal window while its own 2 KB-every-8 ms flood buries that line within ~16 ms. Readiness is now keyed on the repeating `BG:` flood marker, which is strictly stronger — it proves the pane is streaming rather than merely started. It now runs end to end and prints a measurement instead of dying on a call site: ``` [freeze-repro R2] hiddenFloodMaxLagMs 2.1 bulkOpenMaxLagMs 41.5 interactionProbeMs 53.6 softFreeze false hardFreeze false ``` **It is still not CI-gateable, and the exclusion comment now says so.** The same spec on the same commit measured `bulkOpen 2575.6ms / interaction 3464.2ms` on a GitHub ubuntu runner against a 2500 ms soft budget — a ~60x spread on the number the budget reads, with the relay still streaming. That is the budget failing, not the product. The earlier draft of this comment claimed "repaired and passing", which was true only of the host it was measured on; gating this needs a host-relative oracle, not a bigger constant. ## New: a half-open link is judged, not wedged The fixture image has no `iptables` and the container has no `NET_ADMIN`, so `docker pause` is used instead — a harder case, because the container's TCP stack keeps ACKing: no FIN, no RST, and the socket looks perfectly healthy. Only an application-level probe can detect it. ``` [half-open] {"verdict":"reconnecting","verdictMs":25135,"budgetMs":90000} ``` Nothing in the suite covered the failure mode behind the "SSH hangs until I restart Orca" reports. ## New: resource accumulation measured on the remote host 6 terminals, then 5 reconnect cycles, counted on the container itself: ``` open: pts 1->6 (exactly 1/terminal), relay fds 25->30 (exactly 1/terminal) reconnect: pts flat at 6, relay procs flat at 1, node procs flat at 3 ``` `leakedMasterFdCount` is now **asserted**, not merely recorded. It counts PTY master fds held by non-relay processes: without `FD_CLOEXEC` a master is inherited by every later child, so terminal k adds k of them — the triangular signature measured as 15 across 5 terminals before the fix. stablyai#17914 patched the app and daemon and stablyai#17920 shipped the same patch to the relay host, and both are now on main, so the correct value is 0 and the probe holds it there: ``` baseline leakedMasterFdCount 0 6 terminals leakedMasterFdCount 0 (holders: only relay.js, n=6) reconnects leakedMasterFdCount 0 across all 5 cycles ``` Any growth here means the relay's node-pty rebuild did not take on that host, which is exactly what a remote-host probe exists to catch — and it is the half of stablyai#17914's claim that no unit test can reach. ## Routing Both new probes are claimed by `run-ssh-docker-e2e.mjs` (a Docker-gated spec no runner names self-skips everywhere and still reports green) **and** by the `ssh-terminal-source` route in `pr-e2e-source-routing.mjs`, so they run when the relay and SSH code they guard changes rather than only on a scheduled lane.
…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 #17915 — the half of #8362 that #17914 left open, which is the half that matters, because the leak is Linux-only and relay hosts are overwhelmingly Linux.
Option 2 is dead, and it was measured rather than argued
Bumping the relay pin to
[email protected]does not fix the bug. Upstream'spty_close_inherited_fds()is called atpty.cc:473, insidecase 0:of the forkpty switch — in the pty child, just beforeexecvp. The parent's master is never marked. Measured onnode:22:So a beta bump fixes the pty-child half and leaves the
child_processhalf — every git helper, probe and agent CLI — still holding dead terminals open. That kills the option before its beta status, its desync from the app's pinned 1.1.0, or the coverage test asserting they match (relay-native-dependency-coverage.test.ts:93) even come up.Option 1 is far cheaper than #17915 assumed
I was worried this adds a node-gyp compile to the most failure-prone path in SSH. It does not, because
[email protected]ships no Linux prebuild — onlydarwin-{x64,arm64}andwin32-{x64,arm64}. Every Linux relay install already runsnode-gyp rebuild; that is whyinstallNativeDepshas a toolchain probe and a node-pty-less fallback in the first place.So this adds a second compile to a path that already compiles, on the only platform that leaks. Measured: initial install 19-23s, patch + rebuild 5s, second run 0s (
already-patched). macOS and Windows relays are excluded entirely — they use prebuilds and do not leak, so forcing a rebuild there would add a first compile to fix nothing.Failure behaviour — the property that mattered most
The remote script refuses unless: platform is Linux; no skip marker exists; node-pty is exactly 1.1.0 and
src/unix/pty.cchashes to the published sha; and there is an existingbuild/Release/pty.nodeto fall back on. It then renames the working build aside, patches, rebuilds (200s cap, inside the caller's 240s), and verifies in a child process — a bad build can abort on require — that a plainchild_processchild's/proc/self/fdhas noptmx.On any failure — non-zero npm, timeout, npm missing, addon will not load, or still leaking — it deletes the partial build, reverts
pty.ccto the published bytes, renames the backup back, writes a skip marker, and printsORCA-NPTY-CLOEXEC:failed:<reason>. It never throws, and the TS caller swallows the command entirely. Verified in-container with a corruptedbinding.gyp:If
/proccannot answer it returnspatched-unverifiedand keeps the build — an unobservable flag is not evidence the rebuild was wrong. If the SSH channel dies mid-rebuild, node-pty fails the existing probe, the existing repair path reinstalls from already-patched source, and the next run reaps the stranded backup. One compile attempt per relay directory, ever — no backoff loop.Before / after (docker,
node:22, relay-stylenpm install)Does a relay host stop accumulating
/dev/ptsdevices? Yes, once it lands on a relay directory built with this asset. Two honest carve-outs: a relay process already running keeps itsdlopen'd unpatched binary until it restarts, and a host whose compile fails stays leaky-but-working.Reuse, not a parallel mechanism
Delivery follows the existing precedent exactly —
config/relay-assets/*.cjs, declared inRELAY_ARTIFACTS, copied bybuild-relay.mjs, uploaded and probed throughrelayArtifactFilenames. Shipping the asset on all platforms is deliberate: its bytes enter the relay content hash, which is what moves an upgrading host onto a fresh directory whose install can apply it. Execution is Linux-gated.Application is one call at the end of
installNativeDeps, reached only afterprobeInstalledNativeDepsproves node-pty loadable — so it runs only on a freshly created directory or a locked repair. A relay already serving PTYs haspty.nodemapped, so replacing the file underneath it does not touch the running process.Verification
10 relay/deploy test files: 136 passed, 7 skipped.
pnpm tc:nodeclean.check:code-quality:changed: 0 new findings.New:
node-pty-master-cloexec-patch.test.mjs(10 cases — anchors, round-trip revert, version/source refusal, rollback on failed compile, rollback on a still-leaking build, the one-attempt bound, platform gate, no-build guard, stranded-backup reaping) against a byte-exact vendoredpty.ccfixture; andssh-relay-pty-master-cloexec-install.test.ts(runs on Linux after a healthy probe, skipped on darwin, skipped when node-pty is unloadable, connect still succeeds when the command rejects).Fixes #17915
Refs #8362