Skip to content

fix(relay): reap owned PTYs when the daemon dies on an uncaught exception (STA-5697) - #16894

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta5697-crash-reap
Aug 30, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta5697-crash-reap

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​272 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​272
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​43 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​43

In plain terms

You have terminals open on a remote machine over SSH. Orca runs a small helper program on that machine to look after them.

If that helper hit an unexpected error, it quit — and left your terminal programs running. Orca could no longer see or control them, but they were still there: still running, still holding your project folder open, still using the machine. You'd have no way to notice except that things gradually got slower and messier.

This makes the helper shut your terminals down on its way out, instead of walking away and leaving them behind.

What you'll notice: nothing, when things are working. That's the point — after a crash, the leftovers you never knew about simply aren't there any more.

How the three PRs fit together

The original report (STA-5698) was: after the remote helper restarts, Orca might start your AI agent a second time while the first one is still running — two agents editing the same files at once.

That needs two ingredients:

  1. Leftover programs that survive the helper's death — otherwise there's no first agent left to collide with.
  2. Orca being unable to tell whether a remembered terminal name still means the same terminal — otherwise it wouldn't get confused in the first place.

These three PRs remove both ingredients rather than trying to detect the collision afterwards:

Removes Covers
#16894 ingredient 1 the helper crashing on an error
#16895 ingredient 1 the helper being force-killed, running out of memory, or losing power — Windows only, where the OS doesn't clean up for us
#16901 ingredient 2 terminal names that restart from 1 and get reused

Each stands alone and they can land in any order.

Why not just detect the collision? That was the first attempt (#16843, now closed). It tried to work out "has the helper been replaced?" by comparing how long it had been running against when Orca last saw the terminal. It couldn't tell a helper restart apart from the whole machine having rebooted — and after a reboot nothing survives, so there's nothing to protect against. It would have refused to restore your agent in a case that was completely safe. A live reproduction also failed to produce the collision at all on Linux: killing the helper took the agent down with it in 0.3 seconds.

So: prevent the leftovers, fix the names, and the problem doesn't arise instead of being guessed at.


Fixes STA-5697.

The bug

src/relay/relay-daemon.ts installs an uncaughtException handler that logs, cleans up the socket, and calls process.exit(1). It never disposes the PTYs the relay owns — even though the teardown already exists and is used on every other exit path (PtyHandler.dispose() → disposePtys()).

So a relay that crashes leaves every shell it owned behind.

Why it matters, measured

On Windows it orphans. On build 26200, after taskkill /F of a process owning a ConPTY, the shell died but a descendant survived. Windows has no SIGHUP-on-master-close semantics, and the per-PTY job is deliberately not kill-on-close (its comment explains why: with that flag, typing exit in a pane also reaped whatever the user had backgrounded).

On Linux it usually doesn't — closing the pty master delivers SIGHUP and the shell and its agent die, measured at 0.3s in a live SSH repro. But the crash path must not depend on that being true for every shell, every agent, and every platform.

The fix

A bounded, synchronous, best-effort reap on the fatal path before process.exit(1).

  • Synchronous by necessity. The handler runs in an already-broken process, so dispose() — which is async and waits for physical exit — is the wrong tool. This uses the existing synchronous primitives instead.
  • The handler stays where it is, installed before RelayRuntimeServices is constructed so an exception during construction is still caught. A mutable holder is set once the runtime exists; the reap is a no-op until then.
  • Wrapped in try/catch so a failure to reap can never prevent the exit.
  • unhandledRejection deliberately unchanged. It logs and does not exit, so the process keeps running and its PTYs must keep running with it.

One correction to the original design

The task described reusing killPtyProcess(pty, 'SIGKILL'), whose win32 branch calls pty.kill(). That is not sufficient: pty.kill() does not terminate the non-kill-on-close per-PTY job, so the descendants that actually orphan on Windows would have survived. The implementation uses terminatePtyJob first — which is exact, because job membership is the kernel's answer rather than a pid walk — and falls back to the POSIX group kill path only when that is unavailable.

Tests

src/relay/relay-daemon-fatal-reap.test.ts asserts the derived behaviour: that the owned PTYs are actually killed on the fatal path. It was confirmed red before the production change (expected the Windows job kills, received []) and green after.

Verification

pnpm tc, npx oxlint on the changed files, the new test file, and pnpm oxfmt all pass. Integrated with the sibling Windows PR, pnpm build:relay succeeds and the relay suite shows no new failures — the two that fail (pty-handler-spawn-environment, pty-handler-startup-command-delivery) fail identically on origin/main.

Relationship to the other relay PRs

This removes the orphan on paths that run a handler. Its sibling covers deaths that run nothing at all (taskkill /F, OOM) by putting the relay in a kill-on-close job. They are independent and can land in either order.

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: da52a63a-c664-437c-9b32-d08110a10ac8

📥 Commits

Reviewing files that changed from the base of the PR and between 94e7586 and 8b892bb.

📒 Files selected for processing (3)
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon-fatal-reap.test.ts
  • src/relay/relay-daemon.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon.ts

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


📝 Walkthrough

Walkthrough

The relay daemon stores its runtime PtyHandler and force-kills managed PTYs during uncaught-exception cleanup. Windows PTYs use terminatePtyJob; fallback killing remains available when job termination does not succeed. Cleanup processes all PTYs and rethrows the first error. New tests cover Windows and POSIX cleanup, socket cleanup, failure logging, and exit status 1.

Merge Risk: ⚪ Minimal · up to 8b892

The change synchronously cleans up relay-owned terminals when the daemon exits from an uncaught exception while preserving socket cleanup and exit behavior. No actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 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 and concisely describes the main change: reaping relay-owned PTYs after an uncaught exception.
Description check ✅ Passed The description is detailed and on-topic. It explains the problem, fix, rationale, linked issue, testing, platform behavior, and relationship to related changes. Some template sections and checklist i…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and on-topic. It explains the problem, fix, rationale, linked issue, testing, platform behavior, and relationship to related changes. Some template sections and checklist items are not explicitly completed, but the required information is mostly present.

  • 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 commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review — PR #16894

Reviewed at head 2950f4f805, rebased onto current main (83320bff9e). Rebases cleanly; pnpm tc clean; oxlint clean on all changed files; git diff --check clean. Full src/relay suite: 2 failures (pty-handler-spawn-environment, pty-handler-startup-command-delivery) — I confirmed both fail identically on origin/main, so no regression from this PR.

The core claim holds

I traced the uncaughtException path end to end. The reap is genuinely synchronous and genuinely runs before the exit: forceKillAllPtyProcesses() → terminatePtyJob() / requestForceKill() → killPtyProcess() are all synchronous, and the call sits ahead of both socketOwnership.cleanup() and process.exit(1). No async hop races the exit. The correction described in the PR body — using terminatePtyJob rather than pty.kill() on win32 — is the right call for the reason given.

Ablation

Hunk Ablated Result
daemon handler wiring (fatalPtyHandler?.forceKillAllPtyProcesses()) removed RED — expected [] to deeply equal [[11,101],[22,202]]
win32 terminatePtyJob branch removed RED — same assertion
trailing if (hasError) { throw firstError } removed GREEN — unpinned

Full pre-fix tree (both prod files reverted, test kept) is RED, matching the PR body's claim.

Findings (all P2)

  1. throw firstError is unpinned, and the error it throws is discarded. Ablating it leaves the suite green. Its only consumer is the daemon's catch {}, which is empty — so a reap failure is captured, rethrown, and silently dropped. On a crash path that is exactly where diagnostics matter. Either relayLogLine it in the catch, or delete the firstError/hasError bookkeeping as dead weight. Logging is the better half of that choice.

  2. "Bounded" is per-call, not in aggregate. On POSIX, requestForceKill → killPtyProcess → forceKillPosixPtyProcessGroups runs up to two execFileSync('ps', …) calls per PTY, each with a 1s timeout. With MAX_RELAY_PTY_SESSIONS = 50 the worst case is ~100s of synchronous blocking inside uncaughtException before the socket is cleaned and the process exits. A wedged or heavily loaded host is precisely when a crash happens. Worth either a total time budget across the loop, or skipping the ps sweep on the fatal path entirely — the measured POSIX behaviour (master close → SIGHUP, 0.3s) already covers it, and the PR body already argues the POSIX case is the one that does not need this.

  3. Ordering: cleanup after reap. socketOwnership.cleanup() runs after the reap, so any blocking in (2) also delays socket cleanup. cleanup() is cheap and synchronous; running it first lets a reconnecting client see the truth sooner without weakening the reap.

  4. No POSIX coverage. The test pins process.platform = 'win32' throughout, so the entire POSIX branch of forceKillAllPtyProcesses is untested. Given the PR's own framing (Windows orphans, POSIX usually does not), a POSIX case asserting the group-kill path fires would be cheap and would pin finding (2)'s behaviour if you bound it.

Not affected

  • Wire compatibility — no RPC params, stream frames, opcodes, or published host content change. Crash-path teardown only.
  • Verdict vocabulary — no new live/unverifiable/exited producer; nothing coerces a failed query into a verdict.
  • Import ratchet — no new node:child_process import; no allowlist or baseline edited.

Composition with #16895

The two merge cleanly and compose correctly: #16895's process-wide kill-on-close job nests the per-PTY jobs, which is the documented and intended relationship, and it does not change what this PR's reap observes. See my comment on #16895 for a shared-failure-mode note that applies to both.

…able

The fatal reap had no POSIX coverage at all -- every case forced win32 -- and
the daemon discarded the rethrown reap error in an empty catch, so a reap that
failed on a remote host left no trace in the only log a crash produces.

Collapse the job-terminated branch onto the forceKillSent flag it already sets:
the flag is what suppresses the redundant signal, so the separate "continue"
was a second expression of one intent, and the two could only be caught
together -- reverting either one alone left the suite green.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta5697-crash-reap branch from 2950f4f to 8b892bb Compare August 28, 2026 15:13
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review — patched, recommend merge with #16895

Rebased onto current main (94e7586665) and re-verified; the previous green was against a stale base. New head 8b892bb0a9.

Confirmed from the earlier round

  • The reap genuinely fires before exit. The chain is synchronous end to end: forceKillAllPtyProcesses → requestForceKill → killPtyProcess → forceKillPosixPtyProcessGroups → process.kill(-pgid). Nothing is deferred to a tick that process.exit(1) would cancel.
  • throw firstError ablated GREEN and the daemon's empty catch {} discarded it, so a failed reap left no trace in the only log a crashed remote daemon produces. Fixed.
  • Zero POSIX coverage — beforeEach forced win32 for the single test. Fixed.

New finding: two arms that could only be caught together

managed.forceKillSent = true and the continue beneath it were individually unpinned and mutually masking — reverting either alone left the suite green, because the flag makes requestForceKill early-return and the continue skips it. Only reverting both went red. They were two expressions of one intent, so the fix is structural: keep the flag (which is what actually suppresses the redundant signal, here and in any later dispose) and drop the continue.

Gate-level ablation, each arm reverted ALONE

Arm Before After
win32 + terminatePtyJob guard RED RED
forceKillSent marking GREEN — unpinned RED
continue short-circuit GREEN — unpinned (collapsed away)
requestForceKill fallback RED RED
per-PTY try/catch RED RED
trailing throw firstError GREEN — unpinned RED
daemon call site RED RED
daemon catch / failure log RED RED
fatalPtyHandler assignment RED RED

Every arm is now individually pinned (8/8).

Red-before-green

The new failure-log test fails against the pre-fix tree — AssertionError: expected '[relay] Uncaught exception: relay cra…' to contain '[relay] Fatal PTY reap failed: SIGKIL…' — and passes after. The new POSIX test is a coverage test for behaviour this PR already introduced but never exercised; it goes red when the call site, the fallback, or the handler assignment is reverted.

Gates

pnpm tc clean · oxlint clean · git diff --check clean · full src/relay/ suite 148 files / 1523 tests green · formatted with oxfmt on changed files only.

Still open — not fixed here, flagging for a decision

The reap is bounded per call, not in aggregate. MAX_RELAY_PTY_SESSIONS is 50, and each POSIX force-kill can make two execFileSync('ps') calls at a 1s timeout (posix-pty-process-groups.ts:19-36). Worst case is ~100s of fully blocking work inside the uncaughtException handler, and socketOwnership.cleanup() runs after it. From scratch I would not fork ps in a fatal handler at all: the root pgid is known at spawn time, so the crash path could do cheap killpg syscalls and skip the scan whose only job is to catch groups that setpgid'd away. That is a design change beyond this PR's scope, so I have left it — but it is the part that is least like what we would write from scratch.

Also worth noting: requestForceKill early-returns when gracefulKillSent is set on win32, so a PTY mid-graceful-kill is not force-reaped on crash. #16895's job object makes that moot on Windows; it remains a gap on POSIX.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Addendum — the Windows job branch is dead on SSH remotes, so the POSIX path I added coverage for is the one that runs

Follow-up to my review above; verified independently.

terminatePtyJob depends on terminateJob / listJobProcessIds, which are added only by Orca's local pnpm patch (config/patches/[email protected]:786-787, wired via patchedDependencies in package.json:323). The relay installs node-pty on the remote from the registry (ssh-relay-deploy.ts:989-1012), and the only remote-side node-pty patch is JS-only (it rewrites lib/conpty_console_list_agent.js, never the native addon). Against the published tarball, strings on both shipped conpty.node prebuilds returns 0 occurrences of either symbol.

So on an SSH remote, nativeLoader() returns null, terminatePtyJob returns unavailable, and the loop falls through to requestForceKill. That is the module's documented contract working correctly — unavailable must never be read as success — so nothing here is broken. But two consequences are worth stating plainly:

  1. The portable POSIX path is the one that actually reaps on remotes, which is precisely the path that had zero coverage before this review. That makes the added POSIX test more load-bearing than it first appears, not less.
  2. The ~100s blocking-ps concern I raised is therefore the live path, not a corner case. On a Linux/macOS remote every PTY goes through forceKillPosixPtyProcessGroups, so the aggregate execFileSync('ps') cost inside the uncaughtException handler is what a real crash on a real remote will pay.

A one-line comment at the terminatePtyJob call site noting that it is expected to degrade on remotes would save the next reader the same investigation. I have not added it — happy to if you want it.

This does not change my recommendation: the patch stands, CI is green at 8b892bb0a9, and the aggregate-bound question remains the one design item I would want resolved before treating the crash path as finished.

@brennanb2025
brennanb2025 merged commit ba5f334 into main Aug 30, 2026
28 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tion (STA-5697) (stablyai#16894)

* fix(relay): reap PTY jobs on fatal exit (STA-5697)

* test(relay): cover the POSIX fatal reap and make a failed reap observable

The fatal reap had no POSIX coverage at all -- every case forced win32 -- and
the daemon discarded the rethrown reap error in an empty catch, so a reap that
failed on a remote host left no trace in the only log a crash produces.

Collapse the job-terminated branch onto the forceKillSent flag it already sets:
the flag is what suppresses the redundant signal, so the separate "continue"
was a second expression of one intent, and the two could only be caught
together -- reverting either one alone left the suite green.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant