Skip to content

fix(terminal): verify Windows PTY root identity before taskkill /T /F - #10484

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/fix-win-taskkill-pid-identity
Jul 25, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/fix-win-taskkill-pid-identity

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

The defect (P1)

On Windows, killWithDescendantSweep force-kills a PID and its entire descendant tree guarded only by ownsRoot():

  • src/main/pty-descendant-termination.ts:246-256 (pre-fix) — taskkill /pid <rootPid> /T /F behind deps.ownsRoot?.() ?? true.

Every ownsRoot implementation is JS-state-only:

Site Predicate
src/main/daemon/terminal-session-teardown.ts:63 (plain shell) sessions.get(id) === session && session.isAlive
src/main/daemon/terminal-session-teardown.ts:120 (agent) same
src/main/providers/local-pty-provider.ts:1129 ptyProcesses.get(id) === proc
src/main/providers/local-pty-provider.ts:1137 same
src/main/daemon/session.ts:293 () => this.isAlive

session.isAlive is _state !== 'exited', flipped only in handleSubprocessExit (src/main/daemon/session.ts:170, :522) off node-pty's JS onExit. I confirmed node-pty 1.1.0's ConPTY exit watcher ordering in node_modules/node-pty/src/win/conpty.cc:100-108:

WaitForSingleObject(baton->hShell, INFINITE);
GetExitCodeProcess(baton->hShell, ...);
CloseHandle(baton->hShell);          // <-- last handle closes here
...
tsfn.BlockingCall(exit_event, callback);   // <-- JS only learns here

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 returns true for 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 onExit that ownsRoot() depends on may never arrive at all. Orca sets useConptyDll: true unconditionally on win32 (providers/local-pty-utils.ts:190, daemon/pty-subprocess.ts:518). Under that flag node-pty's _$onProcessExit only records the exit code — the flush/cleanup path is gated behind if (!this._useConptyDll) (windowsPtyAgent.js:221-233) — and exit is emitted solely from the out-socket close handler (windowsTerminal.js:97-99), which waits on the whole pseudoconsole process list. So in the exact #10004 scenario (shell dead, orphaned pnpm/node still attached to the ConPTY), node-pty never emits exit, ownsRoot() stays true indefinitely, 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-await ownsRoot() 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: d152039e9d hardened exactly this class on POSIX in this same release — the absent-root bail at pty-descendant-termination.ts:170-172 and the lstart+pgid identity check at :334-338 before delayed SIGKILL. The Windows tree kill got neither.

The fix

New src/main/windows-pty-root-identity.ts verifies the PID against the OS before taskkill, by walking its ancestry back to the process that spawned it:

Design notes:

  • Ancestry, not creation-time, because it needs no spawn-time baseline — nothing has to be threaded through the provider or daemon session. ConPTY spawns the shell directly from our process (conpty.cc:413 CreateProcessW), so 1 hop; node-pty falls back to winpty below Windows build 18309 (windowsPtyAgent.js:38), which adds a winpty-agent.exe hop, so the walk allows up to 4.
  • The probe reads the table through queryWindowsProcessRowsFresh(), which delegates to the existing reader's getFreshSnapshot(). That already guarantees rows from a scan that starts after the request (src/shared/process-table-snapshot.ts:113-152; the startSequence > requestSequence assertion 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).
  • Fail-open everywhere: rejects, sync throws, and a 3 s deadline on a wedged query all resolve unknown. killRoot() still runs in the finally on every path.
  • Ownership is re-checked after the probe's await, since exit can land while the query is in flight.
  • rootPid === ownerPid classifies foreign, so a corrupt PID can never make Orca taskkill /T /F its own tree.

Verification

Verified here (macOS):

  • New 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.
  • Extended pty-descendant-termination.test.ts — win32 skips taskkill on foreign/absent, kills on own/unknown/probe-throw, re-checks ownership lost during the probe, and never probes when ownership was already lost. All still assert killRoot() runs. Reverting pty-descendant-termination.ts to main fails exactly the three that encode the new behavior (foreign skip, absent skip, mid-probe ownership re-check); the rest are non-regression guards and pass either way, by design.
  • Extended 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 with 32 scans instead of 1.
  • Suites: the touched suites plus 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.json clean; oxlint clean on all touched files; lint:switch-exhaustiveness, check:reliability-gates (48 gates), check:max-lines-ratchet all 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 and wmic probes, and the recycled-PID window. The ConPTY handle-ordering claim is read from vendored node-pty C++ source, not observed. Every Windows-only behavior here is covered by injected fakes; the default probe returns unknown off-win32, so the unit suite exercises the decision logic, not the OS calls.

The one real-Windows signal: the Windows terminal restart regressions job (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's paths: 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 pinned verifyTreeKillTarget in the two pre-existing win32 tests so they stay deterministic if the suite is ever run on a real Windows host.

Residual risk

  • Not atomic, and cannot be. taskkill by PID is inherently racy; the guard narrows the window from "however long the event loop lags" to the gap between the probe returning and taskkill executing. It reduces likelihood, it does not eliminate the race.
  • Fail-open is load-bearing and cuts against the guard. Every unknown path 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.
  • Legacy winpty edge: if winpty-agent.exe dies while its shell lives, the chain dead-ends and classifies foreign, 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.
  • Latency: adds one PowerShell/CIM scan (~hundreds of ms, 3 s ceiling) to Windows agent kills and to immediate plain-shell teardown. Normal non-immediate tab close does not reach this path (local-pty-provider.ts:1131), and app quit does not either (it goes through proc.kill() / forceKillAndDisposeSubprocess). Worktree delete does: worktree-teardown.ts:267 fans out at WORKTREE_TEARDOWN_CONCURRENCY = 32 inside 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".
  • The guard proves subtree membership, not root identity — this class is narrowed, not closed. MAX_ANCESTOR_HOPS = 4 asks "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, a git.exe we spawned — still classifies own and is tree-killed. During teardown Orca is itself the process allocating PIDs (this probe forks PowerShell, the sweep forks taskkill), 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 a git.exe mid-operation remains reachable. Closing it needs actual identity: a Win32_Process.CreationDate baseline (the Windows analogue of the POSIX lstart check already used at pty-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.
  • Likelihood remains unquantified, as in the original report; severity is what motivates the fix.
  • The probe is deadline-unaware. pty-descendant-termination.ts calls verify(rootPid) with no timeout argument, so verifyWindowsTreeKillTarget's existing timeoutMs dep 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.
  • Coalescing trade-off (accepted). A probe that arrives while a scan is already running does not start its own; it waits out the in-flight scan and then shares the next one (process-table-snapshot.ts:125-134). So a second-wave caller pays remaining(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 to unknown (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.
  • Probe budget kept at 3 s, not lowered to match POSIX. Review raised that WINDOWS_ROOT_IDENTITY_TIMEOUT_MS = 3_000 is 3x the analogous POSIX DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 inside a 10 s teardown deadline. Declining: the 1 s budget is sized for ps, 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 returns unknown, 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.

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.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Windows PTY termination now verifies root process identity through fresh process snapshots, ancestry classification, timeout handling, and platform checks before running recursive taskkill. Descendant-sweep tests cover ownership, recycled and absent roots, ambiguous probes, failures, and in-flight identity loss. Windows process-row tests verify concurrent probe deduplication and uncached scans, while E2E workflow path filters include the updated termination modules.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. 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 is concise, specific, and accurately summarizes the main Windows identity verification change.
Description check ✅ Passed The description is mostly complete; it covers summary, testing, review, security, and notes, with screenshots omitted because there is no visual change.
✨ Finishing Touches
📝 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ab6a653c-e2f2-4eb1-bfbb-9d2d5d3209f2

📥 Commits

Reviewing files that changed from the base of the PR and between c468e3f and 324ac66.

📒 Files selected for processing (8)
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/windows-foreground-process-rows.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
  • src/main/windows-pty-root-identity.test.ts
  • src/main/windows-pty-root-identity.ts
  • src/shared/physical-exit-tracker.test.ts
  • src/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.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e903a842-458a-4e74-94db-8385f775293d

📥 Commits

Reviewing files that changed from the base of the PR and between 3f4ebd9 and 81fc04c.

📒 Files selected for processing (1)
  • src/main/windows-pty-root-identity.test.ts

@brennanb2025
brennanb2025 merged commit 2653794 into main Jul 25, 2026
3 checks passed
bbingz added a commit to bbingz/orca that referenced this pull request Aug 5, 2026
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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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