Repository navigation
fix(relay): stop detached tools on immediate terminal close - #20645
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 97a82ccf-d01c-40bb-acde-30a303b8188f
📒 Files selected for processing (24)
src/relay/mock-descendant-sweep.tssrc/relay/pty-handler-attach-replay.test.tssrc/relay/pty-handler-dispose-lifecycle.test.tssrc/relay/pty-handler-grace-timer.test.tssrc/relay/pty-handler-immediate-descendants.test.tssrc/relay/pty-handler-inventory-process-evidence.test.tssrc/relay/pty-handler-output-drain-differential.test.tssrc/relay/pty-handler-output-streaming.test.tssrc/relay/pty-handler-ownership-attestation.test.tssrc/relay/pty-handler-resize-stale-pty.test.tssrc/relay/pty-handler-retired-pane-surface.test.tssrc/relay/pty-handler-revive.test.tssrc/relay/pty-handler-shell-resolution.test.tssrc/relay/pty-handler-shutdown-signals.test.tssrc/relay/pty-handler-source-publication.test.tssrc/relay/pty-handler-spawn-admission.test.tssrc/relay/pty-handler-spawn-cwd.test.tssrc/relay/pty-handler-spawn-environment.test.tssrc/relay/pty-handler-startup-command-delivery.test.tssrc/relay/pty-handler-windows-child-process-evidence.test.tssrc/relay/pty-handler.tssrc/relay/relay-daemon-fatal-reap.test.tstests/tools/omp-relay-close-lifecycle.mdtests/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.
| this.requestForceKill(managed) | ||
| } | ||
| }, | ||
| { ownsRoot, terminateOwnedTree: () => terminatePtyJob(managed.pty) } |
There was a problem hiding this comment.
🩺 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.
There was a problem hiding this comment.
ℹ️ 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 viakillWithDescendantSweep(:2317) beforerequestForceKill, so a still-parented but intentionally detached tool (the OMP! /bin/sleepcase) is signalled before it reparents to PID 1. - Close is a single fenced operation —
immediateClosecoalesces concurrent closes (:2309);assertPtyNotClosingrejects attach (:2077,:2120), cached create replay (:1690) and post-ensureadoption (:1805) while set;ownsRootgates both the sweep and the root signal, and the dirty-map re-check at:2117closes the source-checkpoint await window. - Windows and graceful paths unchanged — win32 keeps the direct force-kill (
:2314);immediate: falsekeepsrequestGracefulKill(:2298); dispose/fatal teardown untouched. - Test/mock plumbing — new
src/relay/mock-descendant-sweep.tsneuters the sweep for mock PTYs (pid === process.pid), added to ~18 relay suites; newsrc/relay/pty-handler-immediate-descendants.test.ts; opt-in real-PTY probetests/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.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Risk-reduction review at 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. |
There was a problem hiding this comment.
✅ 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()intests/tools/omp-relay-close-lifecycle.test.mjs:91now asserts thepsinvocation did not time out, was not signalled, wrote no stderr, and returned0/1(with empty stdout on1) before its output is consumed, so a failed query can no longer pass as "all owned PIDs gone" against theafter === ''expectation. The assertions matchProcessResultinsrc/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.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…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
…#20645) * fix(relay): sweep detached tools on immediate terminal close * test(relay): reject failed process cleanup queries
…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

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 120survives the production relay shutdown on source base93c370246388, 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:
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 integration0bbf95921ed7passes 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: trueis the normal renderer tab close —src/main/ipc/pty/ipc/renderer-kill.ts:85andsrc/main/ipc/pty/runtime/kill.ts:286— not a path reserved for agent tooling. Both this PR and #20642 gate the descendant sweep onimmediate, so on POSIX every tab close now SIGTERMs the shell's still-parented descendant tree and SIGKILLs identity-verified survivors afterDESCENDANT_KILL_GRACE_MS.The delta against the previous behaviour is precise:
forceKillPosixPtyProcessGroupssignalled 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 whatsrc/main/pty/posix-pty-process-groups.ts:34-35deliberately 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-psspawn floor — so roughly 40-50 ms added per immediate close, coalesced across same-turn bursts bycreateProcessTableSnapshotReader.DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000is 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:146issuespty.shutdown { immediate: true }gated by the idle predicate insrc/shared/ssh-relay-pty-ownership-proof.ts:150-156. That predicate was calibrated tokillpg— 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.mdrequires 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 optionalpty.shutdown.sweepDescendants?: booleanthat 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.tsand #20642'ssrc/main/daemon/mock-descendant-sweep.tsare 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.tsif either file grows.5. Windows parity is narrower than the title implies
closeImmediatelyshort-circuits torequestForceKillon win32, so the relay never enters the sweep's Windows branch and theterminateOwnedTreedep passed alongside it is unreachable — it exists to satisfysrc/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:readProcessTableBeforeDeadlinereturnsnullon ps error or timeout →captureDescendantSnapshotreturnsnull→ sweep skipped, root-only kill.collectDescendantRowsreturns{ rootPgid: null, descendants: [] }and bails (pty-descendant-termination.ts:192-194).startedAt, matchingpgid, an unambiguous capture second, and non-duplicate rows.Nothing fires on an absence of evidence, and no verdict word outside
live/unverifiable/exitedis introduced.Verification
24 test files, 265 passed, 1 skipped. Mutation-verified: reverting
src/relay/pty-handler.tsalone fails 8 tests inpty-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.