Skip to content

fix(relay): stop detached tools on immediate terminal close - #20645

Merged
nwparker merged 2 commits into
mainfrom
nwparker/omp-relay-close-lifecycle
Sep 18, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/omp-relay-close-lifecycle

Conversation

@nwparker

@nwparker nwparker commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​518 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​518
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​57 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​54

Immediate relay terminal close can leave an OMP external tool running after its shell and OMP exit. With OMP 18.1.18 configured for bash, ! /bin/sleep 120 survives the production relay shutdown on source base 93c370246388, reparented to PID 1. The zsh control exits cleanly because OMP uses a different tool execution path.

The relay now reuses the existing guarded descendant sweep before immediate POSIX root termination. ELI5: closing the terminal also stops the tools its programs started, even when those tools created their own process group. Concurrent closes join the same operation; attachment and agent adoption are refused during close, with ownership retained until physical exit. Attachment also rechecks its exact owner after awaiting source publication.

Related to #9530 and complements local/daemon PR #20642. This fixes reproduced detached-tool leakage; the original foreground-OMP-survives report remains unproven. Every immediate POSIX close includes still-parented intentionally detached jobs. Graceful shutdown, disconnect/keep-alive, fatal teardown and dispose policy are unchanged. Windows retains its force-kill path and gains the pending-attachment fence.

Validation:

  • Actual installed OMP with disposable homes and real native PTYs: bash fails before and passes after; zsh baseline control passes. Production relay spawn/data/shutdown handlers run through an in-process dispatcher. This is macOS backend evidence, not a live SSH connection or rendered client test.
  • Broad relay suite: 174 files / 1,707 tests passed, four skipped before the final two review regressions. Final close/source-publication/attach suite: 48 tests passed, including both new races. Node typecheck and changed-code quality checked.
  • Nine focused close cases cover concurrent close, attachment, retained claims, cached create replay, natural exit, signal retry, Windows behavior, and graceful shutdown. Mock-PTY suites isolate descendant cleanup so fake PIDs cannot reach host signals.
  • Independent review approved the corrected candidate, with 102 focused tests passed (overlapping the parent suite). Review found and drove regressions for close completing during checkpoint attachment and close overlapping initial agent-claim promotion.

Reliability invariant: terminal-session.explicit-close-retirement. Host ownership persists through physical exit; the execution host captures descendants before killing the root. The incumbent bounded capture uses a one-second timeout / 32-MiB cap and one delayed identity recheck after two seconds when needed; captures coalesce and no recurring polling is added. The existing experimental gate's relay/descendant suites and opt-in real-PTY probe exercise the change.

No wire fields, opcodes, or capabilities change. Pending refusal has no proven-exited marker and is not evidence of process death. Folder workspaces and git worktrees use the same PTY ownership. Older clients receive an ordinary attach failure during termination.

Reproduction and limitations: tests/tools/omp-relay-close-lifecycle.md. No Linux/Windows/WSL runtime, live SSH/mobile, mixed-version clients, or rendered UI proof is claimed. Already-reparented children and incumbent same-second PID identity ambiguity remain limitations. Process reports/transcripts stay local.

Exact-head independent approval: a34fab2e9ebdec345930a072b02ececfc1f9e53c. Combined local OMP integration 0bbf95921ed7 passes 125 focused relay/descendant tests, node types, delta quality and the actual OMP bash-mode cleanup probe. Integration branch is local only.

Review findings — read before merging

1. This changes ordinary tab-close semantics, not only the OMP path (needs sign-off)

immediate: true is the normal renderer tab close — src/main/ipc/pty/ipc/renderer-kill.ts:85 and src/main/ipc/pty/runtime/kill.ts:286 — not a path reserved for agent tooling. Both this PR and #20642 gate the descendant sweep on immediate, so on POSIX every tab close now SIGTERMs the shell's still-parented descendant tree and SIGKILLs identity-verified survivors after DESCENDANT_KILL_GRACE_MS.

The delta against the previous behaviour is precise: forceKillPosixPtyProcessGroups signalled process groups attached to the pty's tty. A tool that detached from the controlling terminal but remained a ppid child of the shell was in neither measurement and survived a tab close. It now dies. That is the intended fix for detached agent tooling — and it also catches a user's own terminal-detached long-running job, with no gate and no setting.

This is a product decision shipped under a bug-fix title and wants explicit sign-off, not a code review.

2. Added latency, measured

The sweep runs a whole-host ps -axo pid=,ppid=,pgid=,lstart= before signalling the root, which is what src/main/pty/posix-pty-process-groups.ts:34-35 deliberately avoided. Measured on a host with 1963 process rows: 60.8 / 62.0 / 63.6 / 64.8 / 69.1 ms, against a ~20 ms bare-ps spawn floor — so roughly 40-50 ms added per immediate close, coalesced across same-turn bursts by createProcessTableSnapshotReader. DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 is a bound, not a typical cost. Minor, but not nothing on a worktree-removal path that closes many PTYs.

3. Open residual: evidence-unit mismatch on the SSH orphan sweep

src/main/ssh/ssh-orphan-relay-pty-sweep.ts:146 issues pty.shutdown { immediate: true } gated by the idle predicate in src/shared/ssh-relay-pty-ownership-proof.ts:150-156. That predicate was calibrated to killpg — tty process groups and the shell's own pgid. A terminal-detached ppid child is invisible to both measurements, yet it is exactly what this PR now kills.

docs/reference/ssh-execution-boundary.md requires evidence to be measured in the unit the destructive action operates on. This does not fire on an absence of evidence, so it is not a rule-2 violation, but the proof and the action are in different units. The cheapest fix is a wire-safe optional pty.shutdown.sweepDescendants?: boolean that the orphan sweep leaves unset until the idle predicate measures ppid descendants. Unresolved — needs the owner's decision.

4. Open residual: duplicated test mock

src/relay/mock-descendant-sweep.ts and #20642's src/main/daemon/mock-descendant-sweep.ts are 8 lines each and differ only in a comment and the relative import path. Left as-is deliberately: consolidating means churn across two PRs for a test-only mock. Worth folding into one *.test-mock.ts if either file grows.

5. Windows parity is narrower than the title implies

closeImmediately short-circuits to requestForceKill on win32, so the relay never enters the sweep's Windows branch and the terminateOwnedTree dep passed alongside it is unreachable — it exists to satisfy src/main/pty-descendant-termination-job-coverage.test.ts. Daemon and local Windows immediate close job-kill the tree; relay Windows immediate close still only closes the ConPTY. Pre-existing gap, not introduced here.

Boundary audit — clean

Every kill this PR adds was traced against docs/reference/ssh-execution-boundary.md:

  • readProcessTableBeforeDeadline returns null on ps error or timeout → captureDescendantSnapshot returns null → sweep skipped, root-only kill.
  • Absent or duplicate root → collectDescendantRows returns { rootPgid: null, descendants: [] } and bails (pty-descendant-termination.ts:192-194).
  • The delayed SIGKILL requires a fresh table, matching startedAt, matching pgid, an unambiguous capture second, and non-duplicate rows.
  • An empty enumeration is treated as "no descendants" → leak, never kill.

Nothing fires on an absence of evidence, and no verdict word outside live / unverifiable / exited is introduced.

Verification

24 test files, 265 passed, 1 skipped. Mutation-verified: reverting src/relay/pty-handler.ts alone fails 8 tests in pty-handler-immediate-descendants.test.ts — no inert assertions in the new file. Changed-code quality gate clean on a current-main merge.

Merge constraint: this and #20642 land together or neither. They are two genuinely distinct sites — different processes on different hosts — implementing one policy, already sharing the algorithm through killWithDescendantSweep. Landing one alone leaves local and remote terminals behaving differently on close. Land #20642 first (it consolidates the local branch and lowers the ratchet floor 5→4), then this.

@nwparker
nwparker marked this pull request as ready for review September 14, 2026 16:00
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d1377398-0167-4828-9722-eaca91baa8fa

📥 Commits

Reviewing files that changed from the base of the PR and between a34fab2 and 78e08a9.

📒 Files selected for processing (1)
  • tests/tools/omp-relay-close-lifecycle.test.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/tools/omp-relay-close-lifecycle.test.mjs

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


📝 Walkthrough

Walkthrough

The PTY handler now tracks in-flight immediate closes and rejects spawn or attach operations while a PTY terminates. POSIX immediate shutdown uses descendant sweeping, while Windows uses force kill. Tests add shared sweep mocking and cover close, retry, ownership, platform, and recovery cases. A new opt-in integration probe checks cleanup of real OMP child processes.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 78e08

An immediate close can leave OMP child processes running when the PTY root exits during snapshot capture. This cleanup race should be fixed before merge.

🚥 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 1 functions across 23 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main change: stopping detached tools during immediate relay terminal close.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, linked issues, testing, platform limitations, risks, and merge constraint. It does not use the exact N/A wording fo…
  • 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 97a82ccf-d01c-40bb-acde-30a303b8188f

📥 Commits

Reviewing files that changed from the base of the PR and between e53f155 and a34fab2.

📒 Files selected for processing (24)
  • src/relay/mock-descendant-sweep.ts
  • src/relay/pty-handler-attach-replay.test.ts
  • src/relay/pty-handler-dispose-lifecycle.test.ts
  • src/relay/pty-handler-grace-timer.test.ts
  • src/relay/pty-handler-immediate-descendants.test.ts
  • src/relay/pty-handler-inventory-process-evidence.test.ts
  • src/relay/pty-handler-output-drain-differential.test.ts
  • src/relay/pty-handler-output-streaming.test.ts
  • src/relay/pty-handler-ownership-attestation.test.ts
  • src/relay/pty-handler-resize-stale-pty.test.ts
  • src/relay/pty-handler-retired-pane-surface.test.ts
  • src/relay/pty-handler-revive.test.ts
  • src/relay/pty-handler-shell-resolution.test.ts
  • src/relay/pty-handler-shutdown-signals.test.ts
  • src/relay/pty-handler-source-publication.test.ts
  • src/relay/pty-handler-spawn-admission.test.ts
  • src/relay/pty-handler-spawn-cwd.test.ts
  • src/relay/pty-handler-spawn-environment.test.ts
  • src/relay/pty-handler-startup-command-delivery.test.ts
  • src/relay/pty-handler-windows-child-process-evidence.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-daemon-fatal-reap.test.ts
  • tests/tools/omp-relay-close-lifecycle.md
  • tests/tools/omp-relay-close-lifecycle.test.mjs

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

Comment thread src/relay/pty-handler.ts
this.requestForceKill(managed)
}
},
{ ownsRoot, terminateOwnedTree: () => terminatePtyJob(managed.pty) }

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 | 🏗️ Heavy lift

Keep descendant termination authorized after the root exits.

onExit removes and disposes managed. This makes ownsRoot() false. killWithDescendantSweep checks this predicate before it calls terminateDescendantSnapshot.

If the root exits while snapshot capture is pending, the helper skips every captured descendant. An OMP child can then survive immediate close.

Use an operation-scoped guard for descendant termination. Use the map and disposal check only for the root kill. Extend the root-exit race test to verify descendant termination.

@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 — mergeable as-is. Two informational notes and one scope question below, none blocking.

Reviewed changes

This PR routes the relay's POSIX immediate close (pty.shutdown { immediate: true }) through the existing guarded killWithDescendantSweep before force-killing the root, turns that close into one shared ManagedPty.immediateClose operation, and fences attach/adopt/create-replay while it is pending.

  • Immediate close now sweeps descendants — closeImmediately (src/relay/pty-handler.ts:2308) snapshots the root's ppid tree via killWithDescendantSweep (:2317) before requestForceKill, so a still-parented but intentionally detached tool (the OMP ! /bin/sleep case) is signalled before it reparents to PID 1.
  • Close is a single fenced operation — immediateClose coalesces concurrent closes (:2309); assertPtyNotClosing rejects attach (:2077, :2120), cached create replay (:1690) and post-ensure adoption (:1805) while set; ownsRoot gates both the sweep and the root signal, and the dirty-map re-check at :2117 closes the source-checkpoint await window.
  • Windows and graceful paths unchanged — win32 keeps the direct force-kill (:2314); immediate: false keeps requestGracefulKill (:2298); dispose/fatal teardown untouched.
  • Test/mock plumbing — new src/relay/mock-descendant-sweep.ts neuters the sweep for mock PTYs (pid === process.pid), added to ~18 relay suites; new src/relay/pty-handler-immediate-descendants.test.ts; opt-in real-PTY probe tests/tools/omp-relay-close-lifecycle.{md,test.mjs}.

I verified the concurrency mechanics directly: immediateClose is assigned before close() reaches its first suspension point, the finally uses an identity guard so it can't clobber a newer close, the root signal is unchanged (still the forceKillPosixPtyProcessGroups group SIGKILL) and is now gated rather than unconditional, and every new assertion fails with the bug present. No blocking defects.

ℹ️ Plain (non-agent) POSIX relay shells now sweep descendants, unlike the local/daemon path

Every immediate POSIX relay close runs killWithDescendantSweep, but the sibling local-provider contract restricts the POSIX sweep to agent-owned PTYs (src/main/providers/local-pty-termination.ts:178-197); a plain shell there only gets signalRoot(). The practical delta for a plain shell is a still-parented, setsid/nohup-detached background job: it survives tab close locally but is now killed on a relay/SSH host. The PR body acknowledges sweeping intentionally-detached jobs, so this may be intended — but the cross-provider divergence is worth confirming, or gating the relay sweep on agent ownership to match.

Technical details
# Plain-shell sweep divergence

## Affected sites
- `src/relay/pty-handler.ts:2317-2325` — unconditional POSIX sweep on immediate close
- `src/main/providers/local-pty-termination.ts:178-197` — local path sweeps only when `ptyAgentSessionIds.has(id)`

## Required outcome
- Either confirm the relay is intentionally more aggressive for plain shells, or match the local-provider contract.

## Open questions for the human
- Is relay parity with the local/daemon provider a goal, or is "closing a remote tab stops everything it started" the intended relay contract?

ℹ️ New relay regression suite is not registered in a reliability gate

The new src/relay/pty-handler-immediate-descendants.test.ts (and the opt-in probe) appear in no gate's testFiles/commands, even though the close-retirement gate (config/reliability-gates.jsonc:7788-7817) and the relay watcher-isolation gate (:17388-17450) list the other src/relay/pty-handler-*.test.ts files. The tests still run in PR CI, but the gate oracle the PR body cites won't execute them, so the invariant's stated coverage is broader than what CI-protected gates actually run.

Technical details
# Gate registration gap

## Affected sites
- `src/relay/pty-handler-immediate-descendants.test.ts` — not in any gate testFiles
- `tests/tools/omp-relay-close-lifecycle.test.mjs` — opt-in probe, not registered
- `config/reliability-gates.jsonc:7788` (`terminal-session.explicit-close-retirement`) and `:17388` (`runtime-files.watcher-process-isolation`)

## Required outcome
- Add the new relay suite (and note the opt-in probe) to the relevant gate so its `oracle`/`coverageNotes` describe what actually runs.

ℹ️ Sweep widens the pre-existing recycled-PID window on POSIX

ownsRoot is JS bookkeeping only, and POSIX killWithDescendantSweep has no OS root-identity probe (Windows does: src/main/pty-descendant-termination.ts:293-306). When a shell exits without node-pty delivering onExit, the old immediate path signalled only the root's tty groups; it can now ppid-walk and SIGTERM a recycled PID's tree. Low-probability and acknowledged as an incumbent identity limitation, but the blast radius is larger than before — worth carrying as a known gap.

Technical details
# Recycled-PID blast radius

## Affected sites
- `src/relay/pty-handler.ts:2312` — `ownsRoot` is map membership + `disposed`, not liveness
- `src/main/pty-descendant-termination.ts:314-323` — POSIX sweep trusts the root pid parsed from the table

## Required outcome
- Not required for this PR; record as a known gap or gate the sweep on `isProcessAlive`/`reapPtyProvenExited` before starting.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Risk-reduction review at 78e08a9215cf509a0d8a3ffeae659c0750086a5e: Hold — known race.

Actual native OMP happy-path cleanup passes; adversarial production killWithDescendantSweep reproduction fails: captured child receives no termination after root exits. Process-query test assertions strengthened.

Remaining user-facing consequence: Detached tools may survive closing the relay terminal. A naive guard relaxation risks signaling reused PIDs; needs identity-safe correction.

The follow-up is independently reviewed. Focused local checks passed; CI for this new commit must be assessed separately from the previously green head.

@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 incremental re-review covers the single commit landed since the prior pullfrog review (a34fab2e9e): a test-only hardening of the opt-in OMP relay close probe.

  • Probe rejects failed process queries — rows() in tests/tools/omp-relay-close-lifecycle.test.mjs:91 now asserts the ps invocation did not time out, was not signalled, wrote no stderr, and returned 0/1 (with empty stdout on 1) before its output is consumed, so a failed query can no longer pass as "all owned PIDs gone" against the after === '' expectation. The assertions match ProcessResult in src/shared/child-process/run-process.ts.

The production change (closeImmediately descendant sweep + close fence) is unchanged from the prior review, and the tightened assertions are capable of failing on a broken ps query — the gap they close is real.

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

@nwparker
nwparker merged commit 8c6ae79 into main Sep 18, 2026
34 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 18, 2026
…ing gate (#21362)

#20642 and #20645 added src/main/daemon/mock-descendant-sweep.ts and
src/relay/mock-descendant-sweep.ts: test-only side-effect modules whose whole body is
one vi.mock, imported by 60 suites so mock PTY PIDs never reach the host process table.
Their CI ran before the anti-slop gate landed, so main now fails
`oxlint --config config/oxlint-anti-slop.json` on every PR's merge ref.

File-scoped exemption, like the others in this config, because the root lint scan does
not load the plugin and an inline directive would read back as unused.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…#20645)

* fix(relay): sweep detached tools on immediate terminal close

* test(relay): reject failed process cleanup queries
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…ing gate (stablyai#21362)

stablyai#20642 and stablyai#20645 added src/main/daemon/mock-descendant-sweep.ts and
src/relay/mock-descendant-sweep.ts: test-only side-effect modules whose whole body is
one vi.mock, imported by 60 suites so mock PTY PIDs never reach the host process table.
Their CI ran before the anti-slop gate landed, so main now fails
`oxlint --config config/oxlint-anti-slop.json` on every PR's merge ref.

File-scoped exemption, like the others in this config, because the root lint scan does
not load the plugin and an inline directive would read back as unused.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
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