Skip to content

fix(ssh): close the pty master fd leak on relay hosts too - #17920

Merged
nwparker merged 4 commits into
mainfrom
fix/relay-pty-master-fd-cloexec
Sep 2, 2026
Merged

nwparker merged 4 commits into
mainfrom
fix/relay-pty-master-fd-cloexec

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1398 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1398
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​467 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​466

Stacked on #17914. Review that first; retarget to main once it merges.

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's pty_close_inherited_fds() is called at pty.cc:473, inside case 0: of the forkpty switch — in the pty child, just before execvp. The parent's master is never marked. Measured on node:22:

node-pty 1.2.0-beta.4 master fd=26 flags=00404002 cloexec=false
later PTY child ptmx rows:            none
later child_process child ptmx rows:  26 -> /dev/pts/ptmx

So a beta bump fixes the pty-child half and leaves the child_process half — 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 — only darwin-{x64,arm64} and win32-{x64,arm64}. Every Linux relay install already runs node-gyp rebuild; that is why installNativeDeps has 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.cc hashes to the published sha; and there is an existing build/Release/pty.node to 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 plain child_process child's /proc/self/fd has no ptmx.

On any failure — non-zero npm, timeout, npm missing, addon will not load, or still leaking — it deletes the partial build, reverts pty.cc to the published bytes, renames the backup back, writes a skip marker, and prints ORCA-NPTY-CLOEXEC:failed:<reason>. It never throws, and the TS caller swallows the command entirely. Verified in-container with a corrupted binding.gyp:

status head:        failed:npm rebuild node-pty exited 1: ...gyp ERR! not ok
node-pty still loads: true
pty.cc sha:         5e1005d6...  (the published bytes)
build/Release:      pty.node
second attempt:     skipped:earlier-attempt-failed

If /proc cannot answer it returns patched-unverified and 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-style npm install)

BEFORE  master fd=26 flags=00404002  cloexec=false
        later PTY child ptmx:            26 -> /dev/pts/ptmx
        later child_process child ptmx:  26 -> /dev/pts/ptmx
AFTER   master fd=26 flags=002404002 cloexec=true
        later PTY child ptmx:            none
        later child_process child ptmx:  none

Does a relay host stop accumulating /dev/pts devices? Yes, once it lands on a relay directory built with this asset. Two honest carve-outs: a relay process already running keeps its dlopen'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 in RELAY_ARTIFACTS, copied by build-relay.mjs, uploaded and probed through relayArtifactFilenames. 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 after probeInstalledNativeDeps proves node-pty loadable — so it runs only on a freshly created directory or a locked repair. A relay already serving PTYs has pty.node mapped, so replacing the file underneath it does not touch the running process.

Verification

10 relay/deploy test files: 136 passed, 7 skipped. pnpm tc:node clean. 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 vendored pty.cc fixture; and ssh-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

@nwparker nwparker closed this Sep 1, 2026
@nwparker nwparker reopened this Sep 1, 2026

@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 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.cjs sha256-keys the published pty.cc, applies the forkpty FD_CLOEXEC call, 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 by build-relay.mjs.
  • Install-path hook — applyNodePtyMasterCloexecPatch in ssh-relay-deploy.ts runs 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.

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

Comment thread src/main/ssh/ssh-relay-deploy.ts Resolved
@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

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. installNativeDeps runs a stock npm install on the remote host (ssh-relay-deploy.ts:1008-1013):

npm install --ignore-scripts=false --omit=dev --no-audit --no-fund [email protected] @parcel/[email protected]

Stock tarball, and config/patches/[email protected] is registered in pnpm-workspace.yaml (pnpm 12), which the remote never reads. The codebase already states this at ssh-relay-deploy.ts:1252-1255, for the Windows fallback: "pnpm patches do not cross the SSH boundary; apply the version-checked fallback to the remote npm package."

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 config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs and wires it through relay-artifacts + build-relay.mjs, mirroring the existing Windows console-list-agent precedent (SHA-verified, version-checked, atomic swap, re-asserted after write).

One cost worth a maintainer's eye before merge

The artifact list feeds the relay content hash, and the hash selects the immutable remote directory. Adding a Linux relay asset changes fullVersion for every host, forcing a fresh ~/.orca-remote/relay-<hash>/ and a full native-deps reinstall — which on Linux is a node-gyp source compile, since there is no prebuild.

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 ssh-relay-deploy.ts:949-950 — #1693, ship per-platform tarballs with node-pty prebuilt from CI. Landing that first would make this rebuild moot; it is a sequencing question, not a blocker on the correctness of this fix.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment, plus two concrete findings

My 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. build-relay.mjs:198-212 hashes the artifact manifest into .version as ${RELAY_VERSION}+${contentHash}, so any edit to any artifact, including a JS-only relay change, yields a new hash, a new empty dir, and a fresh npm install [email protected] — a node-gyp source compile on Linux.

The marginal cost actually attributable to this PR is the second compile: the npm rebuild --ignore-scripts=false node-pty inside the .cjs. That matches the commit message's own claim ("costs a second compile rather than a first"), and it is the honest number to weigh against the "several minutes to connect" report.

Finding 1 — the timeout budget does not have room for this (worth acting on before merge)

ssh-relay-deploy-timing.ts:

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  // 900s

The 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 NATIVE_DEPS_COMMAND_TIMEOUT_MS, so worst-case native-deps wall time becomes 240 (install) + 240 (conditional rebuild) + 240 (cloexec) = 720s inside a 900s outer bound, with the cloexec step alone consuming 57% of slack reserved for small commands.

Suggest either a tighter timeout on the cloexec step or a bump to RELAY_DEPLOY_TIMEOUT_MS. 900s is exactly the cap #17891 was filed against.

Finding 2 — sequencing: #17891 should land before or with this

The #17891 defect is still live on main. probeRequiredNativeDeps (ssh-relay-deploy.ts:762-765) returns all deps missing when the probe cannot be answered, and missingNativeDepsFromProbe:728-730 does the same when the marker line is absent. That missing becomes resetDeps at :859 → rm -rf node_modules/node-pty → full recompile. An unanswered probe still triggers a destructive rebuild today.

This PR's guards are good on the paths they cover — Linux-only, gated behind probe.available (the diff returns early in the !probe.available branch so it never runs on a broken install), backup moved aside and restored, caller swallows everything, skipped:no-compiled-build when a prebuild exists.

The one gap: SKIP_MARKER_FILENAME is written only inside the rebuild catch, so a connection that dies mid-compile never writes it and the next reconnect retries the compile. The .cjs does self-heal the stranded backup, so it is not corrupting — but on a flaky host this is repeated 240s compiles rather than one.

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 skipped:no-compiled-build path). Do not hold this fix for it.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merge blocker found: this makes NATIVE_DEPS_REPAIR_BUDGET_MS's own comment false

Independent audit, and it corrects my earlier comment on this PR — I said main was already at 720s of 900s. That was wrong.

ssh-relay-deploy-timing.ts on main:

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  // 900s

Main's worst path is 480s, not 720s. There are three NATIVE_DEPS_COMMAND_TIMEOUT_MS call sites but they are not all reachable in one run — installNativeDeps has two mutually exclusive worst paths:

  • Path A (Linux toolchain missing): install 240 → installNativeDepsWithoutNodePty 240 → early return (the code comments on that return explicitly skipping the probe below).
  • Path B (install succeeds, probe says unloadable): install 240 → rebuildNativeDeps 240.

Both are 2 × 240 = 480s, exactly what NATIVE_DEPS_REPAIR_BUDGET_MS encodes, leaving 420s of headroom for chmod/probe/diagnostic/finalize, the SFTP upload, and launch.

This PR is what creates the 720s path. It appends applyNodePtyMasterCloexecPatch at the tail of installNativeDeps on the success path with the full timeoutMs: NATIVE_DEPS_COMMAND_TIMEOUT_MS, so Path B becomes 240 + 240 + 240 = 720s inside a 900s hard cap, leaving 180s for everything else.

And it is not a cheap command: node-pty-1.1.0-master-cloexec-patch.cjs runs a real node-gyp compile (REBUILD_TIMEOUT_MS = 200000, its header noting it "costs a second compile rather than a first one"). That third slot is the second-most-expensive command in the deploy.

The concrete problem: ssh-relay-deploy-timing.ts is byte-identical between main and this branch — NATIVE_DEPS_REPAIR_BUDGET_MS still says 2 *. Its comment ("Keep the outer bound above that valid worst path") becomes false the moment this lands, and RELAY_DEPLOY_TIMEOUT_MS is a hard abort at ssh-relay-deploy.ts:154 that throws Relay deployment timed out after 900s.

Failure mode: a Linux host on Path B — npm install succeeds but require() of a native addon fails, which is exactly the case the repair path exists for — spends 720s, leaving 180s for the SFTP bundle upload, resolveRemoteInstallState, two chmods, two probe round trips, and launchRelay's poll. On a slow or contended host that overruns and the whole deploy aborts.

Suggested fix before merge: make the budget honest rather than implicit — NATIVE_DEPS_REPAIR_BUDGET_MS = 3 * NATIVE_DEPS_COMMAND_TIMEOUT_MS (raising the outer bound to 1140s), or give the cloexec step its own shorter timeout, since its internal rebuild is already capped at 200s and does not need the full 240.

Either is fine; leaving the constant's comment false is not.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Correction to the evidence framing — the fix is still right, the headline number was not

I 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 9,10,…,20, 9,10,…,20, … is by construction a census across multiple processes. A genuine single-process leak under lowest-available-fd allocation is monotonic and never reuses numbers (9,10,…,201).

Independently confirmed by a hard cap: src/relay/pty-handler.ts:1515 refuses spawn at MAX_RELAY_PTY_SESSIONS = 50. 193 masters in one relay process is impossible.

And the repo's own probe agrees — tests/e2e/ssh-docker-resource-accumulation.spec.ts:47-59 (COUNT_LEAKED_MASTER_FDS) walks every /proc/<pid>, skips anything whose cmdline matches *relay.js*, counts ptmx symlinks and sums. It measures duplicates in children, by design.

This still supports the CLOEXEC hypothesis — more precisely than before

fork/exec preserves fd numbers, so every child shows the parent's numbers. Two shapes fit 193:

  • ~16 processes × 12 masters (9..20) = 192, or
  • triangular growth, where child k inherits the k masters open at its spawn time: runs of 9, 9,10, 9,10,11, … summing 1..19 = 190 — which fits "ascending runs from a low base" better still.

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

  1. The probe cannot distinguish an inherited master from one the process opened itself. A nested pty-creating program in a remote terminal (a multiplexer, an agent CLI, sshd) would also show low ascending ptmx fds. The clean discriminator is a before/after run with the patch applied — the count should go to ~0.
  2. A real amplifier is counted as a leak holder: src/relay/ai-vault-service-spawn.ts:11 uses fork() on ai-vault-service-entry.js, whose cmdline does not match *relay.js*, so the probe counts it. It is long-lived and inherits every master open at its spawn time.
  3. I could not locate the raw 193 measurement in the repo — no report file, no log. Note that 193 also appears as a line count in git show 1901c40cccd --stat. Probably coincidence, but worth confirming the two were not conflated before the number is quoted again.

Two gaps in the fix itself, unchanged by the above

  • applyNodePtyMasterCloexecPatch (ssh-relay-deploy.ts:1123-1163) runs only from installNativeDeps — fresh dir or locked repair. It relies entirely on the new artifact changing the relay manifest hash (src/shared/relay-artifacts.ts:54) to move existing hosts onto a new directory. If that assumption is wrong, already-deployed relays stay unpatched.
  • Failure is silent by design: the skip marker means at most one compile attempt per relay dir, and the caller only console.warns. A host that cannot rebuild stays leaky forever, with no surfaced signal.

The underlying fix is real: Linux takes forkpty(), which has no atomic O_CLOEXEC; node's own fds get it via libuv, so the master genuinely is the outlier, and a long-lived child pins the /dev/pts device after the relay closes its master. The new tests assert the observable via fdinfo flags: carrying O_CLOEXEC (0o2000000), which is a valid check.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Validation procedure — read this before verifying the fix on a live host

Follow-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. tests/e2e/ssh-docker-resource-accumulation.spec.ts:47-59 (COUNT_LEAKED_MASTER_FDS) deliberately excludes *relay.js* and sums ptmx symlinks across every other /proc/<pid>. A flat relay fd count after the patch is the expected outcome, not evidence the fix failed.

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. PtyFork takes forkpty() on Linux (no atomic O_CLOEXEC) and pty_posix_spawn on macOS — fixture config/scripts/__fixtures__/node-pty-1.1.0-unix-pty.cc:399 and :371.

One amplifier, and two adjacent leaks that are not this bug

Amplifier (same bug, worth knowing): src/relay/ai-vault-service-spawn.ts:11 fork()s ai-vault-service-entry.js, whose cmdline does not match *relay.js*. The census counts it as a leak holder, and it is long-lived and inherits every master open at its spawn time — so it inflates the number while being a real instance of the same inheritance problem.

Two genuine competing leaks, both bounded by MAX_RELAY_PTY_SESSIONS = 50 and neither able to produce the observed pattern — recording so they are not lost:

  1. An orphaned term if anything throws between pty.spawn (src/relay/pty-handler.ts:1816) and wireAndStore (:1901) — notably sourcePublication?.activate at :1898.
  2. An agentSessionOwners.ensure() rejection after the spawn callback has already stored the pty (:1645-1660), leaving it ownerless.

Both are separate defects from this PR's scope. Filing them is worthwhile; folding them in here is not.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Correction: the prerequisite is #17907, not #17891

I recorded the ordering constraint as #17891 → #17920. That is wrong. Audit found this PR's own catch block names the real dependency:

"An interrupted rebuild leaves node-pty unloadable, which the existing repair path reinstalls."

That repair path is introduced by #17907 (ssh-relay-node-pty-repair.ts, setTerminalUnavailableRecovery). #17891 only supplies diagnosis plus the structured TerminalUnavailableCause — it does not provide the reinstall this PR relies on to recover from its own interrupted rebuild.

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: relay-artifacts.ts gains node-pty-1.1.0-master-cloexec-patch.cjs with the comment "Its presence is what moves a host to a fresh relay directory" — so shipping this forces a cold reinstall on every host on first connect. Combined with the 720s/900s worst-path budget noted above, that is a deliberate product decision, not an incidental cost. See #18009 for why the install model makes that expensive in the first place.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Live production measurement on a real Linux host — the fd numbers are diagnostic

Measured on the reporter's Ubuntu box (Linux 7.0.0-28-generic x86_64, 8 cores) using the same census shape as tests/e2e/ssh-docker-resource-accumulation.spec.ts (walk /proc, exclude *relay.js*, count ptmx symlinks):

LEAKED_MASTER_FDS_TOTAL = 355
relay_dirs   = 11
relay_procs  = 23
sockets      = 33
oldest relay dir: 2026-08-23   (10 days)

The inheritance signature, shown directly

Two different processes holding the same fd numbers:

pid=985426  bash                              → 151, 27, 30,31,32,33,34,35,36,37,38,39
pid=63138   claude --dangerously-skip-…       → 151, 27, 30,31,32,33,34,35,36,37

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 framing

The 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:

pid=63138   claude   n=10    ← a user's agent pinning 10 pty devices
pid=985426  bash     n=12
pid=377363  git diff n=6
pid=377364  pager    n=6     ← a git pager holding 6 masters
pid=444290  bash     n=11

So the user-visible harm is the one the patch header names: a child holding a dup keeps /dev/pts/N alive after the relay closes its master, so the shell never receives EOF/SIGHUP — terminals that will not die. Not fd exhaustion in the relay.

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, separately

23 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 --connect-failure socket unlink that #17821 removes (unlinking does not close a listener the incumbent holds, so the old relay keeps running with its PTYs while a replacement binds the same path).

Cross-posted to #17821.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

A deterministic reproduction exists — use it to validate this fix

#17940's ssh-docker-resource-accumulation.spec.ts reproduces this leak in a container in 25 seconds. I ran it against a branch carrying this sweep's fixes:

baseline    : leakedMasterFdCount = 0
5 terminals : leakedMasterFdCount = 15

master-fd holders:
  937  n=1   /bin/bash --rcfile …/shell-ready/bash/rcfile
  1058 n=2   /bin/bash …
  1180 n=3   /bin/bash …
  1306 n=4   /bin/bash …
  1438 n=5   /bin/bash …
  310  n=6   node relay.js --detached …

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:

reconnects: [21, 21, 21, 21, 21]

So it accumulates on spawn, not on reconnect. That narrows validation considerably.

Concrete validation procedure

With this patch applied, in that spec:

  • leakedMasterFdCount should drop to ~0 (only the relay's own n=6 for its live PTYs)
  • relayFdCount should be unchanged at 30

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 leakedMasterFdCount without bounding it (its assertions are on pts devices, relay fds and relay processes) — correct for main, but it leaves the most diagnostic number unguarded.

@nwparker
nwparker force-pushed the fix/relay-pty-master-fd-cloexec branch from be86269 to 092b44f Compare September 2, 2026 08:27
@greptile-apps

greptile-apps Bot commented Sep 2, 2026

Copy link
Copy Markdown

Too many files changed for review (1246 files, 100 file limit).

@nwparker
nwparker force-pushed the fix/pty-master-fd-cloexec branch from d69897a to 5037245 Compare September 2, 2026 08:29

@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

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 — installNativeDeps now applies applyNodePtyMasterCloexecPatch before promoteRelayNativeDepsCache, both gated on probe.available.
  • Documented the immutability interaction — added doc comments in ssh-relay-deploy.ts and ssh-relay-native-deps-cache.ts explaining 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.

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

Comment thread src/main/ssh/ssh-relay-deploy.ts Resolved
@nwparker
nwparker force-pushed the fix/relay-pty-master-fd-cloexec branch 2 times, most recently from 94b211f to ab097ec Compare September 2, 2026 09:24
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.
@nwparker
nwparker changed the base branch from fix/pty-master-fd-cloexec to main September 2, 2026 09:28
@nwparker
nwparker force-pushed the fix/relay-pty-master-fd-cloexec branch from ab097ec to 411fda4 Compare September 2, 2026 09:28

@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 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 — applyNodePtyMasterCloexecPatch now yields 'fixed' | 'unfixed', mapped from an allowlist (patched, patched-unverified, already-patched, skipped:not-linux) rather than a failed: denylist, so the mixed skipped: family resolves correctly.
  • Promotion gated on the outcome — promoteRelayNativeDepsCache runs only when the outcome is 'fixed'; otherwise the tree stays private and logs [ssh-relay][NPTY-CLOEXEC-UNSHARED] at console.warn, which also surfaces the previously info-only failure case.
  • Tests pin the refusal — new specs assert a failed: and a skipped:earlier-attempt-failed tree are not published, while patched-unverified (rebuilt from patched source, isolation check unobservable) still is.

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

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a Linux-only node-pty 1.1.0 source patch that sets FD_CLOEXEC on the PTY master, rebuilds the native addon, and verifies descriptor isolation. The patch asset is copied into relay builds and included in artifact hashing. Native dependency deployment runs the patch before shared-cache promotion and accepts only fixed outcomes. Tests cover source rewriting, rebuild and rollback states, platform behavior, cache gating, artifact inclusion, and updated remote command response sequences.

Merge Risk: 🟡 Moderate · up to 411fd

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.73% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: fixing the PTY master file-descriptor leak on SSH relay hosts.
Description check ✅ Passed 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 …
Linked Issues check ✅ Passed The PR satisfies issue #17915 by shipping a relay asset for the npm-installed node-pty 1.1.0 copy, applying the parent-side FD_CLOEXEC fix on Linux, rebuilding and verifying the addon, and preventing …
Out of Scope Changes check ✅ Passed The changes remain within scope. The asset, build integration, deployment workflow, cache handling, fixtures, and tests directly support the Linux SSH relay PTY master leak fix.
Full details: Description check

Explanation

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 check

Explanation

The PR satisfies issue #17915 by shipping a relay asset for the npm-installed node-pty 1.1.0 copy, applying the parent-side FD_CLOEXEC fix on Linux, rebuilding and verifying the addon, and preventing failed or unverifiable builds from being promoted.

  • Fix all pre-merge checks with AI
✨ 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.

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9c8bbe66-cf63-4205-9a87-11668dcae34b

📥 Commits

Reviewing files that changed from the base of the PR and between 8197268 and 411fda4.

📒 Files selected for processing (15)
  • config/relay-assets/node-pty-1.1.0-master-cloexec-patch.cjs
  • config/scripts/__fixtures__/node-pty-1.1.0-unix-pty.cc
  • config/scripts/build-relay.mjs
  • config/scripts/node-pty-master-cloexec-patch.test.mjs
  • src/main/ssh/ssh-relay-deploy.ts
  • src/main/ssh/ssh-relay-native-deps-cache-deploy.test.ts
  • src/main/ssh/ssh-relay-native-deps-cache.ts
  • src/main/ssh/ssh-relay-native-deps-install-fixture.ts
  • src/main/ssh/ssh-relay-native-deps-install.test.ts
  • src/main/ssh/ssh-relay-native-deps-probe-verdict.test.ts
  • src/main/ssh/ssh-relay-node-pty-spawn-repair.test.ts
  • src/main/ssh/ssh-relay-pty-master-cloexec-install.test.ts
  • src/main/ssh/ssh-relay-sftp-namespace-install.test.ts
  • src/shared/relay-artifacts.ts
  • src/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)

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.

🩺 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.

Suggested change
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})`
}

@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 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 — applyNodePtyMasterCloexecPatch emits [ssh-relay][NPTY-CLOEXEC-UNFIXED] at console.warn for 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-UNFIXED warning appears, closing the earlier "info-level only" nit completely.
  • The base was retargeted from fix/pty-master-fd-cloexec to main; the removed hunks in the range-diff are the merged #17914 content dropping out, not this PR's work.

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

@nwparker
nwparker merged commit aa3ae6f into main Sep 2, 2026
31 checks passed
nwparker added a commit that referenced this pull request Sep 2, 2026
…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.
nwparker added a commit that referenced this pull request Sep 2, 2026
…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.
nwparker added a commit that referenced this pull request Sep 3, 2026
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 added a commit that referenced this pull request Sep 3, 2026
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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

The pty master fd leak is still open on SSH relay hosts (npm-installed node-pty misses our patch)

1 participant