Skip to content

fix(pty): invalidate the descriptor when node-pty gives up the handle - #17930

Merged
nwparker merged 44 commits into
fix/relay-cpu-and-stale-pty-lifecyclefrom
fix/pty-fd-ownership-root-cause
Sep 2, 2026
Merged

nwparker merged 44 commits into
fix/relay-cpu-and-stale-pty-lifecyclefrom
fix/pty-fd-ownership-root-cause

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 56 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2387 $\color{#cf222e}{\Huge{\mathbf{−}}}$​465 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1922
Prod 710 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​93535 $\color{#cf222e}{\Huge{\mathbf{−}}}$​66940 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​26595

Stacked on #17832 (merged in as a base, since it is not in #17914) and #17914. Retarget to main once those land.

#17832 handles a resize ioctl on a dead fd by probing isProcessAlive, retrying and classifying. That machinery exists because node-pty splits fd ownership — and it cannot see the dangerous case.

The hazard the probe cannot detect

_close() (node_modules/node-pty/lib/terminal.js:169-175) sets _readable/_writable false but never nulls this._fd, and none of the three fd-addressed surfaces consults anything. libuv has already closed the descriptor, so the number is free for the kernel to reissue.

This is not a rare race — it is immediate and deterministic. In a Linux container, every retired master and the next live pty got fd 17. Measured with the guards reverted:

FAIL cannot resize a live pty handed the retired descriptor number:
     '50 200' !== '24 80'
FAIL does not name a live pty foreground process off the retired descriptor:
     'sleep' !== '/bin/sh'

'50 200' !== '24 80' is the whole argument: resizing an exited handle silently resized an unrelated live pane — and it did not throw. So isProcessAlive, the retry and the classification never fire. Probe-retry-classify is structurally blind to the case that actually corrupts state; it only ever caught the benign EBADF.

The second failure is the same hole in the process getter: tcgetpgrp on a reused descriptor reported another pane's foreground process for a pty that had already exited.

The fix

Extend the patch we already carry (config/patches/[email protected], which #17914 also extends):

  • _close() sets this._fd = -1 in the same block that gives up the handle.
  • resize() and the process getter guard on that sentinel — resize() returns early leaving cols/rows at the last size actually applied; process returns this._file.
  • CustomWriteStream is the third surface, and _fd = -1 does not reach it: it is constructed with its own plain-number copy of the fd (lib/unixTerminal.js:97). Its dispose() only cleared a pending immediate, and it was called from destroy() alone — the EIO/EOF read-error path and the socket 'close' path both reach _close() without it. So dispose() now retires the copy and drops _writeQueue, write()/_processWriteQueue() guard on it, and _close() calls dispose(). (Terminal._close() already shadows terminal.write with a no-op, so the live surface here is the residual queue and the in-flight fs.write that re-enter the stream after the close, not the public write.)

Spliced in place so the rest of the file — including all of #17914's FD_CLOEXEC, .symver and binding.gyp work — is byte-identical. Authored against a pristine reverse-applied copy, git apply --check clean, lockfile patch-hash updated.

That is the ownership model a mature multiplexer uses: close the master and set the fd to -1 in one block, then guard on it.

What this does and does not buy — it narrows the window, it does not close it

An earlier revision of this description claimed a stale fd becomes "unreachable by construction". That is not what the change delivers, and the difference decides whether the relay's fallback can be dropped. It cannot, for two reasons:

  • The guard is set after the fd is already free. libuv closes the descriptor synchronously inside uv_close, before the JS 'close' event fires (handle.rst:149-150), and _close() runs on that event. So the reuse window opens ahead of any JS sentinel. The patch turns an unbounded exposure — every resize for the rest of the entry's life — into a one-tick one. That is the whole win, and it is a real one.
  • On relay hosts the patch is not applied at all, by design. build-relay.mjs keeps node-pty external and the remote installs it with npm install [email protected], i.e. pristine JS. assertNodePtyPatchApplied in build-orcad-prebuilds.mjs only greps the two glibc markers (--no-as-needed,-l:libutil.so.1, .symver openpty,openpty@) — it never checks the JS hunks, and it guards the native prebuild, not the relay. No variant of the new test runs there either.

So #17832's machinery does not collapse:

  • reapPtyProvenExited and its isProcessAlive retirement stay. That was never ioctl safety — it is what stops a dead entry holding activePtyCount above zero ([Bug]: Remote relay busy-loops at ~95% CPU after 'ioctl(2) failed, EBADF' — host looks connected but every new terminal exits instantly #12423). Only ESRCH from the owning host is evidence of exited.
  • The re-probe in the catch stays too. An earlier revision of this PR deleted it. It covers a different part of the window from the JS guard, plus the entire relay case; it is a process.kill(pid, 0) on a path already inside an exception handler, so it costs nothing. Restored.
  • Both existing resize tests pinned liveness with a constant mockReturnValue(true|false), which is exactly why deleting the re-probe passed CI invisibly. A new case uses mockReturnValueOnce(true).mockReturnValueOnce(false) — alive at the pre-probe, gone by the time the ioctl throws — and fails without the restored lines.

Deliberately not done: using _fd < 0 as a liveness signal. A retired master says the handle is gone, not that the process exited — the pgrp can outlive it. Per ssh-execution-boundary.md that is unverifiable, so retirement stays on ESRCH alone.

Verification

Test Files  177 passed (177)    # src/relay/ + src/main/pty/ + build-orcad-prebuilds
     Tests  1823 passed | 7 skipped (1830)

pnpm tc clean; check:code-quality:changed 0 new findings across 16 files.

Negative checks, both run against a real patched install: reverting the _close() → dispose() hook fails retires the write stream fd on _close(), not only on destroy() (expected 16 to be -1), and re-deleting the relay re-probe fails the new race case (expected 1 to be +0).

Of the five new tests, 4 and 5 carry the regression weight — test 3 passes unpatched (with no reuse, tcgetpgrp on a closed fd simply fails and falls back), so it is a contract assertion rather than a guard. Stating that so the suite is not read as stronger than it is.

Two notes for maintainers

  • The patch now carries its first upstream reference. microsoft/node-pty#220 named this exact mechanism in 2018 ("fd number got reattached to something else") and was closed 2025-12-19 as COMPLETED after only improving the error message; Windows has guards (windowsPtyAgent.ts:185-189), Unix does not; #827 is still open showing the guarded path crashing callers. Tracked as node-pty local fork: 1079 lines across 12 files with no upstream references or maintenance record #18109.
  • The Linux-gated tests now run under vitest inside node:24-bookworm against a source-built patched node-pty, not as a transcribed standalone script: 7 passed, 8 consecutive runs, no flake. Reverting the _close() → dispose() hook in that same container fails the write case with expected 'leak\r\n' not to contain 'leak', so it is load-bearing on the platform that matters. They still skip on macOS/Windows — which is how the first version of the write case shipped a broken sibling: it killed its live pty without awaiting the exit, Linux hands out the lowest free descriptor, and the next case's reuse premise came up short by exactly one (expected 22 to be 23). Fixed by awaiting the exit; the premise assertion is unchanged, since it compares two observed descriptors and relaxing it would let both reuse cases pass vacuously.
  • Unrelated and pre-existing on the base branch: this worktree's node-pty prebuild shipped a non-executable spawn-helper, which breaks real pty spawning on macOS. Worth a separate look.

Refs #12423

brennanb2025 and others added 30 commits August 31, 2026 23:27
…mages (#17801)

* fix(native-chat): keep the attachments on a Claude turn that pasted images

A Claude turn carrying pasted images reached native chat with no images at all —
no thumbnails on mobile, and not even an attachment chip on desktop. Nothing
showed that the message had any.

Both carriers were being dropped:

- Claude records the paths in a companion turn marked `isMeta`, holding one
  `[Image: source: <path>]` text block per image. The decoder treats an `isMeta`
  user row as injected, filters it down to tool-result blocks, and returns null
  when none remain — so the whole row went away.
- The prompt row's own `image` blocks are `{source: {type: 'base64'}}`, which
  carry no url or path, so `imageRefBlock` drops them too.

With the companion gone, `isImageSourceUserTurn` could never fire and the fold in
`normalizeImageTranscriptMessages` was unreachable on the Claude path.

Surveying every transcript under `~/.claude/projects`: 238 of 241 image-source
rows are `isMeta`, across every versioned release (2.1.220 through 2.1.237); the
3 that are not carry no version field at all. 38 of those rows hold more than one
content block, which also defeated the single-block rule in
`isImageSourceUserTurn`.

Let image-source text survive the injected-turn filter, and recognize a turn
whose blocks are *all* markers rather than only a lone one. An ordinary injected
turn (a skill preamble, a compact summary) is still dropped, and a turn that
mixes prose with a marker is still not an image-source turn.

Carrying the paths keeps the payload small; decoding the base64 instead would put
hundreds of KB per image on the wire to mobile.

* fix(native-chat): preserve image companion ordering

* fix(native-chat): keep image companions turn-local

---------

Co-authored-by: Merge Sim <sim@local>
…ession (#17813)

A frame the classifier declines (status-chrome, suppressed-benign, stream-into-item)
is deliberately not journaled. #17720 turned that null translation into
`{accepted: false, reason: 'untranslated'}`, which is not `backpressure`, so the
notification retry queue treated it as unreplayable and escalated through fail() ->
forceCloseUnexpected -> connection.close(). The app-server latched `closing` and the
create path's next model/list rejected with "codex app-server connection is closed
(model/list)".

The provider emits `remoteControl/status/changed` right after initialize, so every
structured Codex session died on its first chrome frame. Admit the null translation
instead, before any bookkeeping or publish.

Also restore the error-frame exemption from the generic row cap, dropped by the same
PR: the cap now runs after the classification check, so a noisy turn can no longer
reduce provider errors to a suppression count. The test that pinned the capped
behavior is inverted to assert the exemption.

Co-authored-by: Merge Sim <sim@local>
(cherry picked from commit be954c3663409116f34ba08658876262733b3f67)
(cherry picked from commit a4a9c4da19d6967eceb8025dd01480a56261039f)
Documents the pre-existing render-time refs the split relocated onto changed
lines, and drops a ref assignment the split added that the monolith never had.
…bef (#17835)

Delivery callbacks and telemetry belong to the completed send operation, not to the
picker instance that launched it. Remove early returns that skipped delivery
acknowledgment and success toast when the popover was already closed.
…ide it (#17783)

* fix(mobile-native-chat): retire an image echo glued with the send beside it

A message sent with images could render two or three times over, with the copy
carrying the photos sorting below the reply that answered it — and it never
cleared.

A send issued while the agent is mid-turn is glued onto the agent's input line
with any send adjacent to it, so the pair lands as one transcript row whose text
is the concatenation. Every retirement path then declined the pair:

- The image matcher wanted the whole row to equal the echo's text, so a glued
  row never bound. That also stranded the local preview: the phone's photo never
  reached the authoritative row.
- The exact-count path skips image echoes by design.
- The glue path excluded image echoes too, which made one a *barrier* — splitting
  the run so the text-only send beside it was left alone, and a lone match is
  rejected as an ordinary landing.

So neither echo could ever retire, and the unmatched image echo fell through to
the trailing bucket, which is what put it below the reply.

Match a glued row in the image matcher, and let an image echo take part in the
glue pass once its preview has been rebound. It stays a barrier while unbound,
so the existing guarantee is kept: an image echo never retires before its local
preview reaches the transcript row, or the photo would disappear.

* fix(mobile-chat): require image provenance for glued prefix matches

---------

Co-authored-by: Merge Sim <sim@local>
The split's dependency list no longer trips the rule, so the directive is dead
and the changed-code quality gate rejects it.
(cherry picked from commit bc5f8a5ac5b8e8ad3fc59250795842e663bad0ee)
… defects

#8362: node-pty leaves the forkpty()/posix_openpt() master without FD_CLOEXEC,
so on Linux every later child of the process -- both later pty children and
plain child_process spawns -- inherits it and keeps the /dev/pts device alive.
Measured on Linux with stock node-pty 1.1.0: master fd flags 0404002
(cloexec=false), and 17 -> /dev/pts/ptmx present in both a later pty child's
/proc/self/fd and a later child_process child's. Extend the existing node-pty
patch with pty_cloexec() on both PtyFork spawn paths; after the patch the flags
read 02404002 (cloexec=true) and neither child sees the master. This covers the
app and terminal daemon only -- the SSH relay installs node-pty from npm on the
remote host, so it stays exposed (see the report).

#8414: the inspection queue's fire-and-forget `.finally()` chain re-raised a
rejecting inspection as a renderer-global unhandledrejection, which an
unreachable runtime produced on every cadence tick.

#9194: `tab_not_found` is the host's definitive "no such tab", but the close
path cleared the close intent for it exactly like a dropped connection, so a
host that keeps republishing the dead surface re-materialized the pane the user
just closed. Keep that intent and drop its TTL. Also route the banner's
"Remote terminal was closed." line through translate() so it stops mixing
English into a localized banner.
node-pty hands the master to libuv, which closes it on EIO/EOF, but `_close()`
never invalidated `_fd` and neither `resize()` nor the `process` getter consulted
anything. A late ioctl therefore addressed whatever the kernel had since reissued
that number to. On Linux the very next pty gets it: resizing an exited handle
silently resized an unrelated live pane, with no error for #17832's
probe-retry-classify to observe.

Retire `_fd` in the same block that gives up the master and guard both fd-addressed
syscalls on it, so a stale handle is unreachable by construction. The relay's resize
keeps the isProcessAlive-proven retirement — still the only evidence of `exited` —
and drops the re-probe-and-classify arm the ioctl no longer needs.

Windows is unaffected: WindowsTerminal.resize goes through the conpty agent and
reads no fd.
@greptile-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

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

@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 run reviewed the head commit da79630, the substantive delta of this stacked PR (the 766-file base..head diff is stack noise from fix/relay-cpu-and-stale-pty-lifecycle; retarget to main after #17832/#17914 land).

  • node-pty fd retirement — _close() now sets _fd = -1 in the same block that gives up the handle, and resize() / the process getter guard on that sentinel. A stale handle becomes unreachable by construction instead of EBADF-or-worse; resize() preserves the last applied geometry and the process getter falls back to the spawn file.
  • Relay resize simplification — src/relay/pty-handler.ts drops the re-probe-and-classify in the resize catch (structurally blind — it only ever caught benign EBADF) while keeping the top-of-function reapPtyProvenExited retirement, which remains the only ESRCH-backed evidence of exited.
  • Regression tests — src/main/pty/node-pty-master-fd-retirement.test.ts plus updates to src/relay/pty-handler-resize-stale-pty.test.ts. The Linux-gated fd-reuse tests premise-check masterFd(live) === spawnFd so they fail loudly rather than pass for the wrong reason if the kernel stops reissuing the number.

Verified against the patched sources: the _fd = -1 write is inert on Windows (WindowsTerminal writes _fd once and never reads it back; resize goes through the conpty agent, process returns _name), the patch hash in pnpm-lock.yaml matches sha256sum of the patch file, and no production code reads node-pty's .fd. Tests 1/2/4/5 fail pre-patch; test 3 is a contract assertion that passes unpatched, which the PR body discloses honestly.

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

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Review finding: the entire production behavior change is three deleted lines, and no test can observe the deletion.

First, the diff size is misleading. GitHub reports 766 files / +99,220 −67,529 against baseRefOid db9e642e, which is correct — the inflation is #17914's content plus 39 commits of main (merge-base(17914, main) is 39 commits ahead of merge-base(17832, main)), replayed by the merge. node_modules is not checked in (git ls-files node_modules = 0).

True sizes:

scope files +/-
stack vs its main merge-base 23 +1057 / −47
this commit alone (da79630c) 5 +189 / −24
hand-written (excl. patch + lockfile) 3 +145 / −20
src/relay/pty-handler.ts 1 +13 / −16 (net −3)

Of those 16 deleted lines 3 are executable — the if (this.reapPtyProvenExited(managed)) { return } guard in the resize catch. Of the 13 added, 1 is executable (a reworded process.stderr.write template). The other 12/12 are comment. 132 of the 145 hand-written lines are the new test.

So the production change is: delete a fallback, relocate the guard into the vendored patch.


Why that combination is the concern.

Two of the three patch-loss scenarios fail loudly, and credit where due: a version bump hits ERR_PNPM_UNUSED_PATCH (pnpm-workspace.yaml:44 keys on the exact string [email protected]), and a patch that fails to apply fails the install. The new node-pty-master-fd-retirement.test.ts genuinely asserts expect(masterFd(term)).toBe(-1) against a real spawned pty on Linux CI, so an edited-out JS hunk is caught there.

The uncovered case is the one that matters most: on relay hosts the patch never applies by design. No variant of that test runs there, assertNodePtyPatchApplied in build-orcad-prebuilds.mjs only greps the two glibc markers (--no-as-needed,-l:libutil.so.1, .symver openpty,openpty@) and not the JS hunks, and nothing in CI runs it anyway. There, behavior degrades silently to the original throw — with the fallback now deleted.

And no test distinguishes the two versions. Both tests in pty-handler-resize-stale-pty.test.ts pin liveness with a constant vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(true|false). Covering the deleted path needs mockReturnValueOnce(true).mockReturnValueOnce(false) — alive at the pre-probe, dead by the time the ioctl throws — which is precisely the race the re-probe existed for, and it is absent from the file. That is why the deletion passes CI invisibly.

Suggested resolution — cheap: keep the vendored patch, keep the new test, and put the three lines back. The re-probe is a process.kill(pid, 0) on a path already inside an exception handler; it costs nothing, and the fix does not require its removal.

Patch-attribution note (clean): #17832 touches the patch not at all; #17914 adds src/unix/pty.cc (+56/−5); this PR modifies lib/unixTerminal.js and adds a lib/terminal.js section, verified against the upstream 1.1.0 tarball as landing inside _close. The wider maintenance concern about the 1,079-line fork is filed separately as #18109 and is not a defect in this PR.

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: an upstream mechanism detail that bears on the deleted fallback.

libuv closes the fd synchronously inside uv_close, before the JS 'close' event fires (docs/src/handle.rst:149-150). node-pty's _close() runs on that JS event.

So the this._fd = -1 assignment added by this patch hunk lands after the fd has already been released to the OS. The reuse window opens before the guard is set — the patch narrows it substantially but cannot close it.

That strengthens the case for keeping the three-line catch-path re-probe rather than deleting it: the guard and the fallback cover different parts of the window, so they aren't redundant. The process.kill(pid, 0) re-probe is precisely what catches "the fd was already recycled before _close() ran," which is the residual case the patch cannot reach.

Upstream status, for the record: microsoft/node-pty#220 is the issue for this behavior — closed 2025-12-19 as COMPLETED but unfixed on Unix. Maintainer jerch named "fd number got reattached to something else" in 2018; the only action was PR #285 improving the error string ("This is good enough for now"). Windows has guards (windowsPtyAgent.ts:185-189); Unix does not. #827 remains open showing the guarded path still crashing uncatching callers.

Worth citing in the patch itself — the fork currently carries no upstream references at all (filed as #18109).

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Addendum — the third fd surface, and why it's worse than the one being fixed.

The PR's headline claim, "a stale fd becomes unreachable by construction," is not true. There are three fd-addressed surfaces in unixTerminal.js; this PR guards two.

CustomWriteStream (:285-318) is constructed with its own plain-number copy of the fd (:101), so Terminal._fd = -1 does not touch it. Its dispose() (:291) only clears a pending immediate — it does not invalidate the fd, drain _writeQueue, or cancel an in-flight fs.write.

And the reachability is the problem: dispose() is called only from destroy() (:219-229). The EIO/EOF read-error path (:111) and the socket 'close' path (:143) both reach _close() without it — and EIO/EOF is the exact path this PR's own commit message cites.

Reachable in Orca: pty-handler.ts:2070-2078 guards pty.write on !managed.disposed, but disposed is set by reapExitedPty, which only runs when something probes. Between shell exit and reap, write() is live on a retired handle.

That is a data write landing on a reissued descriptor — a user's keystrokes delivered into an unrelated live pane. Strictly worse than the resize this PR fixes, on the path it names.

Compounding it: libuv closes the fd synchronously inside uv_close, before the JS 'close' event fires (handle.rst:149-150), and _close() runs on that event. So the reuse window opens before any JS-side guard can run — which is also why the three-line catch-path re-probe removed from pty-handler.ts was not redundant with the patch: they cover different parts of the window.

To lift the hold: one more hunk — invalidate CustomWriteStream's fd and drain its queue from _close(), not just destroy(). Or, if that's out of scope, replace the "unreachable by construction" claim in the body with what the patch actually delivers. The 29 lines as written are correct and net-positive; it's the completeness assertion that isn't earned.

Credit where it's due, verified independently: the fd-reuse premise is real (master fds: [3,5,7] -> close 3 -> next master fd 3, deterministic on Linux); the new tests are genuine node-pty tests and are not in unit-tests.yml's exclude list, so the describeOnLinux fd-reuse cases really do run in the ubuntu shards; the glibc floor gate (verify-linux-glibc-floor.cjs) hard-throws rather than skipping and passed; and CI is green across native-smoke (ubuntu-22.04), (windows-latest), mac-native-owner-smoke, package, and package (windows).

Unrelated but confirmed while auditing: build-orcad-prebuilds.mjs:183-187 guards on process.platform !== 'win32' and throws spawn-helper missing, while binding.gyp:85-98 declares that target only under ['OS=="mac"'] — so no Linux prebuild slot can be produced and the guard should be === 'darwin'. Not this PR's problem, but it is why Linux relay hosts build node-pty from source, which is the path this patch flows through.

…re-probe

Two gaps in the fd-retirement change.

`CustomWriteStream` is the third fd-addressed surface and takes its own plain-number
copy of the master at spawn, so `Terminal._fd = -1` never reaches it. Its `dispose()`
only cleared a pending immediate, and it was called from `destroy()` alone — the
EIO/EOF read-error path and the socket `'close'` path both reach `_close()` without
it. A residual `_writeQueue` and an in-flight `fs.write` therefore kept addressing
the number after libuv gave it up. Retire the copy and drop the queue in `dispose()`,
and call it from `_close()`.

Restore the relay's catch-block re-probe. It was never redundant with the patch:
libuv closes the fd synchronously inside `uv_close`, before the JS `'close'` that
runs `_close()`, so the reuse window opens ahead of any JS guard; and a relay host
installs node-pty from npm, where the patch is not applied at all. The re-probe is a
`process.kill(pid, 0)` on a path already inside an exception handler.

Both existing resize tests pinned liveness with a constant mock, which is why the
deletion passed CI invisibly; the new case is alive at the pre-probe and gone by the
time the ioctl throws.

Also adds the patch's first upstream reference: microsoft/node-pty#220 named this
mechanism in 2018 and was closed 2025-12-19 as completed after only improving the
error message; #827 is still open. Tracked as #18109.
@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my earlier addendum. I wrote that between shell exit and reap, write() is live on a retired handle and would deliver "a user's keystrokes into an unrelated live pane." That overstated it — Terminal._close() already shadows this.write with a no-op, so the public pty.write() path is not live after _close().

The surface that genuinely still reached the fd is narrower: the residual _writeQueue plus an in-flight fs.write re-entering the stream, since CustomWriteStream holds its own plain-number copy of the fd and its dispose() was reachable only from destroy().

Still a real cross-pane write on a reissued descriptor, still worth fixing — but via the queue, not the public write path. The fix as pushed is written to the accurate claim.

Everything else in the addendum stands: dispose() was reachable only from destroy(), the EIO/EOF (:111) and socket-'close' (:143) paths reach _close() without it, and libuv closing the fd inside uv_close before the JS 'close' event means no JS-side guard can close the window entirely — which is why the three-line catch-path re-probe was never redundant with the patch.

Independently confirmed while fixing: build-relay.mjs keeps node-pty external and the remote installs it with npm install [email protected] — pristine JS. The patch genuinely never applies on a relay host, so the deleted fallback was the only protection there.

@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 run reviewed the delta since the prior Pullfrog review: commit 8f46541 ("retire the write stream's fd copy too, and keep the resize re-probe"), touching 5 files.

  • Write-stream fd retirement — CustomWriteStream holds its own plain-number copy of the master fd, so retiring Terminal._fd = -1 alone still left the residual _writeQueue and an in-flight fs.write addressing a kernel-reused descriptor. The patch now has dispose() retire the stream's own _fd and drop the queue, guards write() and _processWriteQueue() on the -1 sentinel, and has _close() call dispose() (guarded on if (this._writeStream), so it stays inert on Windows and UnixTerminal.open() handles).
  • Relay resize re-probe restored — da79630 had dropped the re-probe in the resize catch; this commit restores it. It covers the one-tick window between libuv closing the fd and node-pty's JS _close() observing it, plus the relay host (which installs node-pty from npm, unpatched). The reapPtyProvenExited ESRCH-only retirement at the top of resize() is unchanged.
  • Regression tests — a retires the write stream fd on _close(), not only on destroy() case, a Linux-gated cannot write into a live pty handed the retired descriptor number case (premise-guarded on fd reuse), and a relay race case using mockReturnValueOnce(true).mockReturnValueOnce(false) to prove the restored re-probe retires an entry whose pid vanishes between the pre-probe and the ioctl failure.

Verified against the actual patched sources: the dispose() retirement is idempotent under the destroy() → _close() → dispose() double call, the patch hash in pnpm-lock.yaml (e262847f…) matches sha256sum, and the three new tests fail against the unpatched behavior (fd stays the spawn number / write still enqueues / entry stays live without the re-probe).

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

The new Linux write case killed its live pty without awaiting the exit, so that
master was still open when the next case spawned. Linux hands out the lowest
free descriptor, so the retired pty got N+1 while the leaked N closed during the
400ms settle -- and `does not name a live pty foreground process off the retired
descriptor` then saw its live pty take N, failing its own reuse premise by
exactly one (`expected 22 to be 23` on CI, reproduced as 19/20 in a container).

Test isolation, not a Linux behavior difference: with the descriptor released
the case passes 8/8. Await the exit like the resize case above already does, and
switch the payload command to `sleep 1` -- the line discipline echoes a leaked
write back on its own, so nothing has to read it. Note the constraint on the
block so the next case does not repeat it.

The premise assertion stays as it is. It compares two observed descriptors, not
a hardcoded number; relaxing it to "differs from the retired one" would let both
reuse cases pass vacuously on a kernel that never reissues, which is the whole
thing they exist to demonstrate.

Verified with vitest under node:24-bookworm against a source-built patched
node-pty: 7 passed, 8 runs, no flake. Negative check in the same container --
reverting the `_close()` -> `dispose()` hook fails the case with
`expected 'leak\r\n' not to contain 'leak'`, so the rewritten assertion is still
load-bearing.

@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 run reviewed the delta since the prior Pullfrog review: commit e818172 ("test(pty): release the live pty before the next fd-reuse case"), a single-file test change.

  • Test-ordering fix for the fd-reuse write case — the cannot write into a live pty handed the retired descriptor number case now spawns sleep 1 as its live pty and awaits live.onExit() instead of a fixed 300 ms sleep. Awaiting the exit releases the live pty's descriptor before the next case runs, which previously leaked the descriptor into the next case's masterFd(live) === spawnFd premise as an off-by-one that flaked on node 24 on Linux.
  • Observation moved from read+printf to line-discipline echo — the leak is now observed via the tty echo of the leaked leak\r rather than a shell round-trip, so no reader is required for the leak to be observable. The PR body's negative check (expected 'leak\r\n' not to contain 'leak') still fails pre-patch, so the case remains a genuine regression guard.

No production code changed in this delta.

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

@nwparker
nwparker merged commit ccd3b8d into fix/relay-cpu-and-stale-pty-lifecycle Sep 2, 2026
38 checks passed
nwparker added a commit that referenced this pull request Sep 2, 2026
…#17930)

Carried forward from PR #17930, which merged into this branch. Rebased onto
current main; main's newer node-pty-fd-leak test is kept as-is.
nwparker added a commit that referenced this pull request Sep 2, 2026
…ll scan storms (#17832)

* fix(relay): stop three CPU growth terms in a long-running remote session

pty.resize gated only on `managed.disposed`, which is bookkeeping rather than
liveness. A shell that exits without node-pty's `onExit` leaves an undisposed
entry holding a closed master fd, and UnixTerminal.resize has no fd guard, so
the ioctl threw `ioctl(2) failed, EBADF` into the dispatcher's generic
parse-error catch. Nothing retired the entry, so it stayed advertised and kept
activePtyCount above zero -- which is what stops a relay with an unlimited
grace from reaching its idle-no-ptys exit (#12423). Probe liveness with the
same helper attach/listProcesses use, retire a provably dead pid, and contain
an ioctl failure over a live-or-unverifiable process.

processHasChildren forked `pgrep -P` per pane per inspection poll, uncached.
procps-ng opens six procfs files per process to resolve one ppid, so each call
cost O(host process count). Answer from the TTL-cached `ps` table the same RPC
already captured for the foreground lookup (#13537).

The remote AI Vault scanner had no parse cache at all, so every forced rescan
re-read and re-parsed the whole transcript corpus, including files untouched
for a month. Give it the mtime+size keyed memo the local scanner has (#13753).

* fix(pty): invalidate the descriptor when node-pty gives up the handle (#17930)

Carried forward from PR #17930, which merged into this branch. Rebased onto
current main; main's newer node-pty-fd-leak test is kept as-is.

* fix(ai-vault): refresh codex titles on the remote parse-cache reuse path

The remote cache keys on the transcript's (mtime, size, host), but codex
titles live in $CODEX_HOME/session_index.jsonl and are written after the
rollout — so a cache hit froze the fallback title forever. Mirrors the
local scanner's existing reuse-path refresh via a shared core.

* fix(relay): publish the exit a reap performs, and rescan for close decisions

Two review findings on the CPU work.

reapExitedPty told only the relay-internal exit listener, so a retirement left
the client's pane mounted against a session the relay had already forgotten --
the next attach answered `PTY "<id>" not found` with nothing before it to
explain why. Pre-existing on three probe paths; resize made it user-triggered.
Publish the same pending-exit the natural onExit path publishes, carrying -1
("gone, status unrecoverable"), and skip it when onExit already reported the
real code.

processHasChildren now answers from a 500ms TTL-cached table. That is right for
pty.inspectProcess, which every tracked pane polls, but pty.hasChildProcesses
gates the window-close confirmation and workspace cleanup's idle evidence --
one destructive decision per answer, where a child started inside the window
would be killed unasked. Give that RPC a fresh scan; pgrep used to.

* fix(relay): publish a reap's exit only on proven-exited evidence

The publication is a verdict the client acts on by retiring the pane, so it
must not be reachable from the disposed-record sweep, which retires off our own
bookkeeping rather than the host's process table. Only ESRCH earns it.

* fix(i18n): restore the activity-options key the rebase dropped

* fix(i18n): union en.json with main so the rebase cannot drop keys
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ll scan storms (stablyai#17832)

* fix(relay): stop three CPU growth terms in a long-running remote session

pty.resize gated only on `managed.disposed`, which is bookkeeping rather than
liveness. A shell that exits without node-pty's `onExit` leaves an undisposed
entry holding a closed master fd, and UnixTerminal.resize has no fd guard, so
the ioctl threw `ioctl(2) failed, EBADF` into the dispatcher's generic
parse-error catch. Nothing retired the entry, so it stayed advertised and kept
activePtyCount above zero -- which is what stops a relay with an unlimited
grace from reaching its idle-no-ptys exit (stablyai#12423). Probe liveness with the
same helper attach/listProcesses use, retire a provably dead pid, and contain
an ioctl failure over a live-or-unverifiable process.

processHasChildren forked `pgrep -P` per pane per inspection poll, uncached.
procps-ng opens six procfs files per process to resolve one ppid, so each call
cost O(host process count). Answer from the TTL-cached `ps` table the same RPC
already captured for the foreground lookup (stablyai#13537).

The remote AI Vault scanner had no parse cache at all, so every forced rescan
re-read and re-parsed the whole transcript corpus, including files untouched
for a month. Give it the mtime+size keyed memo the local scanner has (stablyai#13753).

* fix(pty): invalidate the descriptor when node-pty gives up the handle (stablyai#17930)

Carried forward from PR stablyai#17930, which merged into this branch. Rebased onto
current main; main's newer node-pty-fd-leak test is kept as-is.

* fix(ai-vault): refresh codex titles on the remote parse-cache reuse path

The remote cache keys on the transcript's (mtime, size, host), but codex
titles live in $CODEX_HOME/session_index.jsonl and are written after the
rollout — so a cache hit froze the fallback title forever. Mirrors the
local scanner's existing reuse-path refresh via a shared core.

* fix(relay): publish the exit a reap performs, and rescan for close decisions

Two review findings on the CPU work.

reapExitedPty told only the relay-internal exit listener, so a retirement left
the client's pane mounted against a session the relay had already forgotten --
the next attach answered `PTY "<id>" not found` with nothing before it to
explain why. Pre-existing on three probe paths; resize made it user-triggered.
Publish the same pending-exit the natural onExit path publishes, carrying -1
("gone, status unrecoverable"), and skip it when onExit already reported the
real code.

processHasChildren now answers from a 500ms TTL-cached table. That is right for
pty.inspectProcess, which every tracked pane polls, but pty.hasChildProcesses
gates the window-close confirmation and workspace cleanup's idle evidence --
one destructive decision per answer, where a child started inside the window
would be killed unasked. Give that RPC a fresh scan; pgrep used to.

* fix(relay): publish a reap's exit only on proven-exited evidence

The publication is a verdict the client acts on by retiring the pane, so it
must not be reachable from the disposed-record sweep, which retires off our own
bookkeeping rather than the host's process table. Only ESRCH earns it.

* fix(i18n): restore the activity-options key the rebase dropped

* fix(i18n): union en.json with main so the rebase cannot drop keys
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.

3 participants