Repository navigation
fix(terminal): verify Windows PTY root identity before taskkill /T /F - #10484
Conversation
killWithDescendantSweep guarded its Windows tree kill with ownsRoot() alone, which is JS state only. node-pty's ConPTY exit watcher closes the last shell handle before it queues the JS exit callback, so Windows can recycle the PID while the session map still looks live — force-killing an unrelated process and its whole descendant tree. Walk the recycled PID's ancestry back to this process before taskkill: skip the sweep when the root is gone or resolves to a stranger, and keep the sweep when identity is unknown so #10004 orphan cleanup still runs. Also gate the local provider's ownsRoot on observed physical exit.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughWindows PTY termination now verifies root process identity through fresh process snapshots, ancestry classification, timeout handling, and platform checks before running recursive 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ab6a653c-e2f2-4eb1-bfbb-9d2d5d3209f2
📒 Files selected for processing (8)
src/main/providers/local-pty-provider.tssrc/main/providers/windows-foreground-process-rows.tssrc/main/pty-descendant-termination.test.tssrc/main/pty-descendant-termination.tssrc/main/windows-pty-root-identity.test.tssrc/main/windows-pty-root-identity.tssrc/shared/physical-exit-tracker.test.tssrc/shared/physical-exit-tracker.ts
…gate Review fixes on the PID-identity guard. The probe read the process table through a new uncached export, bypassing the reader that worktree teardown depends on: worktree-teardown.ts fans out 32-wide inside a 10s deadline, so a delete forked 32 powershell cold-starts (the churn windows-foreground-process-rows.ts:25-32 warns about, #6288/#6667). getFreshSnapshot() already guarantees a scan that starts after the request -- the exact property the bypass existed for -- and coalesces concurrent callers, so use it. Measured on the new test: 32 scans -> 1. The PhysicalExitTracker.hasExited gate could never fire. markExited() is only reached at local-pty-provider.ts:985/:1431, and both are followed synchronously by clearPtyState(), which deletes the ptyProcesses entry -- so ownsRoot's map check is already false whenever hasExited is true. Reverting it broke no test. Drop it and the shared getter it added; the identity probe already covers every ownsRoot caller from inside killWithDescendantSweep. Also point the Windows terminal-restart E2E job at the files that own this behavior, so a change to the new Windows-only module runs the one job that executes on a real Windows host.
The probe checks subtree membership, not root identity: a recycle that lands on another Orca descendant (another pane's shell, an agent CLI, a git.exe we spawned) still reads `own`, and that is not remote during teardown when Orca is itself allocating pids. It bounds the blast radius rather than closing the class. Say so at the type and at classifyWindowsTreeKillTarget, and name what a real close would need (a CreationDate baseline -- the analogue of the POSIX lstart check already used here -- or an inherited handle / Job Object). Also note why our own pid must classify `foreign`.
…reader The Windows root-identity probe now reads through getFreshSnapshot, so an edit to that module changes Windows teardown behavior without touching any path the job already watches.
…bypass The existing volume guard covers queryWindowsProcessRowsFresh directly, but the identity-probe cases all inject readRows, so nothing exercised the DEFAULT reader wiring -- a bypass reintroduced inside windows-pty-root-identity would have gone unnoticed. Drive verifyWindowsTreeKillTarget 32-wide through the real reader and assert one scan. Verified it fails at 32 when the bypass is put back.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e903a842-458a-4e74-94db-8385f775293d
📒 Files selected for processing (1)
src/main/windows-pty-root-identity.test.ts
Drop redundant Windows root-identity plumbing already covered by upstream stablyai#10484/stablyai#10674, document Job Object as the primary reaper with identity-gated taskkill as fallback, guard Apple/OpenBSD spawn helpers to avoid unused-function -Werror noise, and regenerate the node-pty patch so it applies cleanly to 1.1.0.
…stablyai#10484) * fix(terminal): verify Windows PTY root identity before taskkill /T /F killWithDescendantSweep guarded its Windows tree kill with ownsRoot() alone, which is JS state only. node-pty's ConPTY exit watcher closes the last shell handle before it queues the JS exit callback, so Windows can recycle the PID while the session map still looks live — force-killing an unrelated process and its whole descendant tree. Walk the recycled PID's ancestry back to this process before taskkill: skip the sweep when the root is gone or resolves to a stranger, and keep the sweep when identity is unknown so stablyai#10004 orphan cleanup still runs. Also gate the local provider's ownsRoot on observed physical exit. * fix(terminal): dedupe the Windows root-identity scan, drop dead exit gate Review fixes on the PID-identity guard. The probe read the process table through a new uncached export, bypassing the reader that worktree teardown depends on: worktree-teardown.ts fans out 32-wide inside a 10s deadline, so a delete forked 32 powershell cold-starts (the churn windows-foreground-process-rows.ts:25-32 warns about, stablyai#6288/stablyai#6667). getFreshSnapshot() already guarantees a scan that starts after the request -- the exact property the bypass existed for -- and coalesces concurrent callers, so use it. Measured on the new test: 32 scans -> 1. The PhysicalExitTracker.hasExited gate could never fire. markExited() is only reached at local-pty-provider.ts:985/:1431, and both are followed synchronously by clearPtyState(), which deletes the ptyProcesses entry -- so ownsRoot's map check is already false whenever hasExited is true. Reverting it broke no test. Drop it and the shared getter it added; the identity probe already covers every ownsRoot caller from inside killWithDescendantSweep. Also point the Windows terminal-restart E2E job at the files that own this behavior, so a change to the new Windows-only module runs the one job that executes on a real Windows host. * docs(terminal): state what the Windows root probe actually proves The probe checks subtree membership, not root identity: a recycle that lands on another Orca descendant (another pane's shell, an agent CLI, a git.exe we spawned) still reads `own`, and that is not remote during teardown when Orca is itself allocating pids. It bounds the blast radius rather than closing the class. Say so at the type and at classifyWindowsTreeKillTarget, and name what a real close would need (a CreationDate baseline -- the analogue of the POSIX lstart check already used here -- or an inherited handle / Job Object). Also note why our own pid must classify `foreign`. * ci(windows): trigger the terminal-restart E2E on the shared snapshot reader The Windows root-identity probe now reads through getFreshSnapshot, so an edit to that module changes Windows teardown behavior without touching any path the job already watches. * test(terminal): guard the teardown probe against a reintroduced scan bypass The existing volume guard covers queryWindowsProcessRowsFresh directly, but the identity-probe cases all inject readRows, so nothing exercised the DEFAULT reader wiring -- a bypass reintroduced inside windows-pty-root-identity would have gone unnoticed. Drive verifyWindowsTreeKillTarget 32-wide through the real reader and assert one scan. Verified it fails at 32 when the bypass is put back.
The defect (P1)
On Windows,
killWithDescendantSweepforce-kills a PID and its entire descendant tree guarded only byownsRoot():src/main/pty-descendant-termination.ts:246-256(pre-fix) —taskkill /pid <rootPid> /T /Fbehinddeps.ownsRoot?.() ?? true.Every
ownsRootimplementation is JS-state-only:src/main/daemon/terminal-session-teardown.ts:63(plain shell)sessions.get(id) === session && session.isAlivesrc/main/daemon/terminal-session-teardown.ts:120(agent)src/main/providers/local-pty-provider.ts:1129ptyProcesses.get(id) === procsrc/main/providers/local-pty-provider.ts:1137src/main/daemon/session.ts:293() => this.isAlivesession.isAliveis_state !== 'exited', flipped only inhandleSubprocessExit(src/main/daemon/session.ts:170,:522) off node-pty's JSonExit. I confirmed node-pty 1.1.0's ConPTY exit watcher ordering innode_modules/node-pty/src/win/conpty.cc:100-108:Windows only guarantees a PID is not recycled while a handle to the process object stays open. That handle closes in native code before JS is notified, so in the gap
ownsRoot()still returnstruefor a PID Windows may already have reassigned. With a busy event loop (cold-restore replay, large PTY writes) that gap widens from sub-millisecond to seconds.node-pty says the same thing in its own Windows kill path (
lib/windowsPtyAgent.js:163-165): "Process IDs can be reused as soon as all handles to them are dropped."Worse, the JS
onExitthatownsRoot()depends on may never arrive at all. Orca setsuseConptyDll: trueunconditionally on win32 (providers/local-pty-utils.ts:190,daemon/pty-subprocess.ts:518). Under that flag node-pty's_$onProcessExitonly records the exit code — the flush/cleanup path is gated behindif (!this._useConptyDll)(windowsPtyAgent.js:221-233) — andexitis emitted solely from the out-socketclosehandler (windowsTerminal.js:97-99), which waits on the whole pseudoconsole process list. So in the exact #10004 scenario (shell dead, orphanedpnpm/nodestill attached to the ConPTY), node-pty never emits exit,ownsRoot()staystrueindefinitely, and the pre-fix code force-killed a long-since-recyclable PID. The window is not sub-millisecond in the case that matters — it is unbounded.A corollary worth stating: the post-
awaitownsRoot()re-check is therefore near-useless in that same scenario. The CIM classification is doing essentially all of the work.Scenario: a Windows shell exits on its own; the user deletes the worktree seconds later; the daemon event loop is saturated; Windows reassigns the PID; teardown
taskkill /T /Fs an unrelated process and its whole descendant tree.This is a gap, not an inherent race:
d152039e9dhardened exactly this class on POSIX in this same release — the absent-root bail atpty-descendant-termination.ts:170-172and thelstart+pgididentity check at:334-338before delayedSIGKILL. The Windows tree kill got neither.The fix
New
src/main/windows-pty-root-identity.tsverifies the PID against the OS beforetaskkill, by walking its ancestry back to the process that spawned it:own→ ancestry reaches us; sweep proceeds.absent→ PID gone; skip (taskkillwould no-op anyway).foreign→ PID resolves to a process we did not start; skip the tree kill.unknown→ no usable evidence (probe unavailable/rejected/timed out, ambiguous duplicate rows, inconsistent cyclic table); sweep still proceeds, so Windows: agent PTY child processes orphaned on terminal stop/close, blocking worktree removal (Failed to physically stop every PTY) #10004/fix(win): taskkill agent PTY descendant trees on stop #10100 orphan cleanup is not regressed.Design notes:
conpty.cc:413CreateProcessW), so 1 hop; node-pty falls back to winpty below Windows build 18309 (windowsPtyAgent.js:38), which adds awinpty-agent.exehop, so the walk allows up to 4.queryWindowsProcessRowsFresh(), which delegates to the existing reader'sgetFreshSnapshot(). That already guarantees rows from a scan that starts after the request (src/shared/process-table-snapshot.ts:113-152; thestartSequence > requestSequenceassertion at:138-141), so it can never answer from a cached row that predates the very recycle it is meant to detect — while still coalescing concurrent callers, which matters because teardown fans out (see Latency below).unknown.killRoot()still runs in thefinallyon every path.await, since exit can land while the query is in flight.rootPid === ownerPidclassifiesforeign, so a corrupt PID can never make Orcataskkill /T /Fits own tree.Verification
Verified here (macOS):
src/main/windows-pty-root-identity.test.ts— 20 cases: ConPTY direct child, winpty agent hop, recycled stranger, absent root, orphan whose parent also exited, over-depth chain, self-pid, invalid pids, duplicate rows, cyclic table; and for the async probe: own/foreign classification, both-probes-unavailable, reject, sync throw, wedged-query deadline, off-platform skip.pty-descendant-termination.test.ts— win32 skipstaskkillonforeign/absent, kills onown/unknown/probe-throw, re-checks ownership lost during the probe, and never probes when ownership was already lost. All still assertkillRoot()runs. Revertingpty-descendant-termination.tstomainfails exactly the three that encode the new behavior (foreignskip,absentskip, mid-probe ownership re-check); the rest are non-regression guards and pass either way, by design.windows-foreground-process-rows.test.ts— a 32-wide burst of identity probes collapses to one PowerShell scan, and the probe never answers from the TTL cache. Swapping the coalesced read back for an uncached one fails the first with32scans instead of1.local-pty-provider,src/main/daemon,src/shared,windows-process-tree-kill,subprocess-tree-termination,agent-foreground-process,pty-shell-utils— 4519 passed / 11 skipped, 0 failures.tsc --noEmit -p config/tsconfig.node.jsonclean;oxlintclean on all touched files;lint:switch-exhaustiveness,check:reliability-gates(48 gates),check:max-lines-ratchetall pass (no new suppressions).The race itself is static-only — I cannot reproduce it on this macOS host, and it is not deterministically reproducible on demand anywhere. Not executed by me: the real
taskkill /T /F, the real PowerShell/CIM andwmicprobes, and the recycled-PID window. The ConPTY handle-ordering claim is read from vendorednode-ptyC++ source, not observed. Every Windows-only behavior here is covered by injected fakes; the default probe returnsunknownoff-win32, so the unit suite exercises the decision logic, not the OS calls.The one real-Windows signal: the
Windows terminal restart regressionsjob (windows-terminal-restart-e2e.yml,windows-2022, real Electron + real ConPTY) passes on this branch. That proves the new probe does not wedge or slow Windows terminal teardown to failure; it does not exercise the recycle race. This PR adds the files that own this behavior to that job'spaths:filter, which previously would not have triggered it for a change confined to the identity module. Note the separate Windows vitest job (computer-e2e.yml:83) runs a fixed narrow file list that excludes these suites — I pinnedverifyTreeKillTargetin the two pre-existing win32 tests so they stay deterministic if the suite is ever run on a real Windows host.Residual risk
taskkillby PID is inherently racy; the guard narrows the window from "however long the event loop lags" to the gap between the probe returning andtaskkillexecuting. It reduces likelihood, it does not eliminate the race.unknownpath still sweeps. So under the conditions that most widen the race — a saturated machine — a slow or wedged probe is also most likely to hit the 3 s deadline and fall through to the old behavior. This is a deliberate trade (orphan cleanup regressions are certain, PID recycles are rare) but it means the guard is best-effort, not a barrier.winpty-agent.exedies while its shell lives, the chain dead-ends and classifiesforeign, so the tree kill is skipped and orphans could again hold the worktree cwd (the Windows: agent PTY child processes orphaned on terminal stop/close, blocking worktree removal (Failed to physically stop every PTY) #10004 symptom) on Windows builds < 18309.killRoot()still runs. Deliberate: an orphan-holds-cwd failure is recoverable, killing a stranger's process tree is not.local-pty-provider.ts:1131), and app quit does not either (it goes throughproc.kill()/forceKillAndDisposeSubprocess). Worktree delete does:worktree-teardown.ts:267fans out atWORKTREE_TEARDOWN_CONCURRENCY = 32inside a 10 s deadline, which is why the probe shares the coalescing reader rather than bypassing it — otherwise one delete would fork 32 PowerShell cold-starts and could push teardown past that deadline into "Failed to physically stop every PTY".MAX_ANCESTOR_HOPS = 4asks "is Orca an ancestor within 4 hops", so a recycle landing on any other Orca descendant — another pane's shell (depth 1), an agent CLI (depth 2), an MCP child, agit.exewe spawned — still classifiesownand is tree-killed. During teardown Orca is itself the process allocating PIDs (this probe forks PowerShell, the sweep forkstaskkill), so that is not a corner case. Blast radius drops from "any process on the machine" to "our own <=4-deep subtree", which is a real improvement, but killing another pane's shell/agent/MCP tree or agit.exemid-operation remains reachable. Closing it needs actual identity: aWin32_Process.CreationDatebaseline (the Windows analogue of the POSIXlstartcheck already used atpty-descendant-termination.ts:302-310), or an inherited handle / Job Object on the root, which makes PID reuse impossible by OS contract rather than merely unlikely. Left as follow-up — both need a spawn-time baseline threaded through the provider and daemon, which is beyond this fix.pty-descendant-termination.tscallsverify(rootPid)with no timeout argument, soverifyWindowsTreeKillTarget's existingtimeoutMsdep is not forwarded and a caller with its own budget cannot shrink the 3 s ceiling to fit. Left alone deliberately: with the probe now coalesced, a worktree delete costs ~1 scan rather than 32, so no current caller is close to its budget, and adding a knob nobody passes would be speculative. Worth doing if another deadline-bound caller appears.process-table-snapshot.ts:125-134). So a second-wave caller paysremaining(prior scan) + own scan. At a ~400 ms scan that is ~800 ms worst case; on a loaded box with ~1.5 s scans it approaches the 3 s deadline and would degrade tounknown(i.e. pre-guard behavior) where an uncached probe might have answered. Accepted, because the uncached path's own worst case is 6 s (3 s PowerShell + 3 s wmic) and N independent forks make timeouts more likely under load, not less — a single shared scan is the more reliable option precisely when the machine is busy. Secondary: a shared scan failure is correlated across joined callers, where independent probes could have differed.WINDOWS_ROOT_IDENTITY_TIMEOUT_MS = 3_000is 3x the analogous POSIXDESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000inside a 10 s teardown deadline. Declining: the 1 s budget is sized forps, which this repo's own comment (windows-foreground-process-rows.ts:26-32) puts at 10-40x lighter than a PowerShell cold start — matching the number would not match the cost. More importantly the failure direction is wrong: a probe that times out returnsunknown, which sweeps anyway, so a tighter budget makes the guard fail open precisely on the slow machines where the race window is widest. Coalescing already cut a worktree delete from up to 32 scans to ~1-2, which is where the deadline pressure actually came from. Revisit with real Windows timings rather than by analogy.