Skip to content

fix(crash-reporting): record Orca-initiated tree kills so a killed renderer is decidable - #18367

Merged
nwparker merged 4 commits into
mainfrom
nwparker/crash-self-tree-kill-breadcrumb
Sep 3, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/crash-self-tree-kill-breadcrumb

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​598 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​591
Prod 20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​540 $\color{#cf222e}{\Huge{\mathbf{−}}}$​84 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​456

What

Cluster G2-killed: 20 field crash reports whose renderer died with reason=killed exitCode=1 and no minidump. Affected versions 1.4.194 (10 reports) and 1.4.195 (10 reports). OS split: 15 win32 (10.0.19045 / 22631 / 26100 / 26200, x64), 3 darwin (25.6.0 arm64), 2 linux (6.8 x64 and arm64).

The cluster is undecidable as recorded. A taskkill /T /F that Orca itself issues and an external kill of the same renderer produce byte-identical crash reports — same reason, same exitCode, same crashAttribution, same siblingProcessDeathCount. Nothing Orca persists today distinguishes "something killed us" from "we killed ourselves".

Two changes.

1. A real guard (behaviour change). classifyWindowsTreeKillTarget (src/main/windows-pty-root-identity.ts:40-90) decides whether a pid may be force-killed by walking its ancestry back to the killing process's own pid and returning own when the chain reaches us. Orca's renderer, GPU process and network-service utility are all direct children of Electron main, so from Electron main that walk hits parent === ownerPid on hop 0 (windows-pty-root-identity.ts:79-81) and returns own — handing PTY teardown a licence to taskkill /T /F Orca's own UI. That is the Chromium half of known limit #10680, documented in the classifier's own doc comment. Both the classifier (windows-pty-root-identity.ts:55-57) and the taskkill choke point (src/main/windows-process-tree-kill.ts:26-28) now refuse any pid Electron is currently accounting for in app.getAppMetrics(), via a shared gate admitSelfInitiatedTreeKill (src/main/own-chromium-tree-kill-guard.ts:26-40). The gate is shared because the codex and claude account-login teardowns run their own taskkill /T /F with different lifetimes, so a check inside the tree-kill helper alone would have covered one of three families.

Reachable from killWithDescendantSweep (src/main/pty-descendant-termination.ts:274-280, site: 'pty-descendant-sweep') and from src/main/codex/codex-structured-turn-processes.ts:61 (site: 'codex-turn-added-roots') — the two sites the investigation named as suspects for G2.

2. Instrumentation that makes the next round decidable. The gated force-kill choke points record a durable, coalesced self_tree_kill breadcrumb (src/main/crash-reporting/self-initiated-tree-kill-log.ts), and process_gone reports carry three new detail keys (src/main/crash-reporting/process-gone-recorder.ts:254):

  • selfInitiatedTreeKillCount — pid-addressed taskkills only, i.e. kills that could land on a recycled pid that is now our renderer.
  • selfInitiatedGroupKillCount — PTY process-group / Job Object sweeps, which are structurally incapable of taking a Chromium process with them.
  • selfInitiatedKills — win-taskkill-tree/pty-descendant-sweep/pid21688 -121ms, pid-addressed entries sorted first so truncation never drops the discriminating ones.

selfInitiatedTreeKillCount is not a clean binary discriminator, and an earlier version of this body called it one. It has a routine base rate: every aborted or timed-out runProcess on Windows records scope win-taskkill-tree, including ordinary cancelled git. The selfInitiatedKills site string is what separates a pty-descendant-sweep from a git-command-tree-kill; the count alone does not.

A refused kill records self_tree_kill_refused_own_chromium. That crumb is falsifiable on purpose: if it ever appears in a field bundle, Orca was demonstrably about to kill its own renderer.

This PR does not claim to fix the 20 reports. G2 is at least four fingerprints sharing one symptom (~15 Windows killed/1, 3 POSIX SIGKILL under memory pressure, 2 duplicate reports of one macOS V8 Proxy Resolver SIGKILL, 1 install-dir ACL crash). It ships one guard that every pid-addressed taskkill /pid <pid> /t /f reachable from Electron main now asks — including the git command-runner abort, the codex app-server deadline kill, the notebook and precheck timeouts and the shared runProcess choke point — plus a ratchet (src/main/main-process-tree-kill-gate.test.ts) that fails on a new ungated one. (not in this merge — see the box; that is #18459.) What merged is the guard wired into three families: terminateWindowsProcessTree and the two account-login teardowns. Six other pid-addressed taskkill families in Electron main remain ungated on main, so a main-issued kill can still land on a pid Electron is accounting for. It does not make the shape impossible anywhere else: on the CLI, relay and daemon hosts the same seam admits every kill because there is no Chromium pid set to consult, and a recycle onto a non-Chromium Orca descendant still classifies own (Follow-up 2).

Fix evidence

Everything below was re-run from scratch on 2026-09-03, on macOS, after the merge, at both revisions. Merge-base for both experiments is 76836b30ea6.

A. The merged artifact (2d0c627ba08) — this is what is on main

Red without the production change. All new modules and all test files kept; only the 15 pre-existing production files reverted to the merge-base:

$ git checkout 76836b30ea6 -- <15 pre-existing production .ts files>
$ ./node_modules/.bin/vitest run \
    src/main/crash-reporting/self-initiated-tree-kill-log.test.ts \
    src/main/own-chromium-tree-kill-guard.test.ts \
    src/shared/child-process/process-tree-termination.test.ts \
    src/main/pty/posix-pty-process-groups.test.ts \
    src/main/windows/windows-pty-job.test.ts \
    src/main/codex/codex-app-server-process-teardown.test.ts \
    src/main/rate-limits/codex-probe-termination.test.ts

 Test Files  7 failed (7)
      Tests  14 failed | 47 passed (61)

First failure verbatim — this is the discriminator test, and without the production change the field simply does not exist:

 FAIL  src/main/crash-reporting/self-initiated-tree-kill-log.test.ts > self-initiated tree kill breadcrumb > separates an Orca-issued tree kill from an external kill of the same shape
TypeError: .toMatch() expects to receive a string, but got undefined
 ❯ src/main/crash-reporting/self-initiated-tree-kill-log.test.ts:103:43
    101|     const externallyKilled = await recordKilledRenderer()
    102|
    103|     expect(selfKilled.selfInitiatedKills).toMatch(
       |                                           ^
    104|       /^win-taskkill-tree\/pty-descendant-sweep\/pid4242 [+-]\d+ms$/
    105|

Green with it, plus the broad sweep, typechecks and lint at the merged head:

$ git checkout 2d0c627ba08 -- <same 15 files>   # git status clean
$ ./node_modules/.bin/vitest run <same 7 test files>
 Test Files  7 passed (7)
      Tests  61 passed (61)

$ ./node_modules/.bin/vitest run src/main/crash-reporting src/main/own-chromium-tree-kill-guard.test.ts \
    src/main/windows-pty-root-identity.test.ts src/main/pty src/main/windows src/main/codex \
    src/main/rate-limits src/main/claude-accounts src/main/codex-accounts src/main/text-generation \
    src/shared/child-process src/main/pty-descendant-termination.test.ts
 Test Files  299 passed | 5 skipped (304)
      Tests  3048 passed | 48 skipped (3096)

$ tsc -p config/tsconfig.node.json --noEmit    exit=0
$ tsc -p config/tsconfig.tc.web.json --noEmit  exit=0
$ tsc -p config/tsconfig.tc.cli.json --noEmit  exit=0
$ oxlint src                                   exit=0

B. The branch tip (9db1b4ce6ef) — NOT merged, and superseded by #18459

Kept here only because the branch still points at it. It adds an eighth test file (the ratchet) and touches 20 rather than 15 pre-existing production files:

$ git checkout 76836b30ea6 -- <20 pre-existing production .ts files>
 20 files changed, 84 insertions(+), 200 deletions(-)
$ vitest run <8 test files, adding src/main/main-process-tree-kill-gate.test.ts>
 Test Files  8 failed (8)
      Tests  17 failed | 51 passed (68)

$ git checkout HEAD -- src/   # git status clean
$ vitest run <same 8 test files>
 Test Files  8 passed (8)
      Tests  68 passed (68)

$ vitest run <same broad sweep>
 Test Files  300 passed | 5 skipped (305)
      Tests  3055 passed | 48 skipped (3103)

$ tsc x3   exit=0,0,0        $ oxlint src   exit=0

This tip is stale and must not be merged as-is. It still carries the round-4 eviction defect. Probe re-run at the tip today — 32 routine git-command-tree-kill entries saturate the 32-slot ring, then a win-pty-job teardown 10ms before the death:

PROBE_RESULT {"selfInitiatedTreeKillCount":32,
  "selfInitiatedKills":"win-taskkill-tree/git-command-tree-kill/pid100 -3000ms, ... (+29 more)"}
AssertionError: expected undefined to be 1     # selfInitiatedGroupKillCount

The entry recorded 10ms before the crash is spliced out by the entry itself; pid 7777 never appears. #18459 (9bac44ee970) fixes this by excluding the just-recorded entry from eviction candidacy.

process-gone-recorder.ts and claude-command-process.ts both hit the 300-line cap during development. No max-lines suppression was added: the recorder change was collapsed to one import + one spread, and terminateClaudeProcess was moved to its own module (claude-login-process-termination.ts).

Live reproduction on real Windows 11 / Electron 43.4.1 — captured against an earlier revision, NOT re-run at the merged head

Read this first. The three arms below were captured at f05863a. Three commits landed in this merge since (8e6a107, 1796073, 2d0c627) and they changed exactly what these arms print: the list key is now selfInitiatedKills (not selfInitiatedTreeKills), every entry carries a <scope>/ prefix, and the count is split into selfInitiatedTreeKillCount / selfInitiatedGroupKillCount. The Windows host was unreachable when the round-3 findings were closed (ssh awin → connection timed out) and has not been reachable since, so no Windows execution has covered the merged code. Treat the arms as evidence for the two claims that do not depend on the output format — A vs B are indistinguishable in every recorded field, and the refusal prevents the crash entirely — and treat the merged format as pinned by unit tests instead.

Disclosure: main2.js is a JS transliteration of three shipped functions (readOrcaChromiumProcessPids, recordSelfInitiatedTreeKill + selfInitiatedTreeKillDetails, terminateWindowsProcessTree), md5 3f8b05c0953102c627608e24635dbe7e verified identical on both machines. It is not the shipped TypeScript, and it models a single-Electron-process topology, not the standalone daemon.

Arm A — Orca kills its own renderer, guard off. Breadcrumb present:

{"ev":"ready","mode":"self","guard":false,"mainPid":13112,"rendererPid":21688,
 "metrics":[["Browser",13112,null],["GPU",9124,"GPU"],["Utility",21620,"network.mojom.NetworkService"],["Tab",21688,null]]}
{"ev":"breadcrumb","name":"self_tree_kill","pid":21688,"site":"pty-descendant-sweep","scope":"win-taskkill-tree"}
{"ev":"render-process-gone","reason":"killed","exitCode":1,"crashAttribution":"none",
 "siblingProcessDeathCount":0,"siblingProcessDeaths":"",
 "selfInitiatedTreeKillCount":1,"selfInitiatedTreeKills":"pty-descendant-sweep/pid21688 -121ms"}

(Stale key and format, per the banner above. On main that last line reads "selfInitiatedTreeKillCount":1,"selfInitiatedKills":"win-taskkill-tree/pty-descendant-sweep/pid21688 -121ms".)

Arm B — external taskkill of the same renderer from a second shell. Breadcrumb absent:

(second terminal) $ taskkill //PID 22260 //T //F
SUCCESS: The process with PID 22260 (child process of PID 20016) has been terminated.

{"ev":"ready","mode":"external","guard":false,"mainPid":20016,"rendererPid":22260,
 "metrics":[["Browser",20016,null],["GPU",13440,"GPU"],["Utility",23720,"network.mojom.NetworkService"],["Tab",22260,null]]}
{"ev":"render-process-gone","reason":"killed","exitCode":1,"crashAttribution":"none",
 "siblingProcessDeathCount":0,"siblingProcessDeaths":""}

reason, exitCode, crashAttribution, siblingProcessDeathCount and siblingProcessDeaths are identical across A and B. The self-kill list is the only field that differs. Both match field report 1.4.194_449351d6 (killed / exit 1 / win32 10.0.19045 / no siblings / app survived / minidumpStatus: absent).

Arm C — same self-kill with the guard on. Kill refused, no crash at all:

{"ev":"ready","mode":"self","guard":true,"mainPid":2524,"rendererPid":10408,
 "metrics":[["Browser",2524,null],["GPU",2448,"GPU"],["Utility",19608,"network.mojom.NetworkService"],["Tab",10408,null]]}
{"ev":"breadcrumb","name":"self_tree_kill_refused_own_chromium","pid":10408,"site":"pty-descendant-sweep","scope":"win-taskkill-tree"}
{"ev":"timeout_exit","rendererAlive":true}

No render-process-gone was ever emitted.

Explicitly NOT proven

  • That Orca caused any of the 20 field reports. Nobody has that evidence. This PR creates part of the field that would produce it.
  • That the guard eliminates the shape everywhere. Arm C proves it for kills issued from terminateWindowsProcessTree in Electron main. Six other pid-addressed taskkill families in main are ungated on main. In the standalone daemon readOrcaChromiumProcessPids() is empty and the gate always admits; there the shape is blocked one layer earlier by the ancestry walk, locked in as a falsifiable test pair in own-chromium-tree-kill-guard.test.ts — but not exercised by the Windows arms.
  • That anything shipped has run on Windows. The arms predate three merged commits and were produced by a JS transliteration; the Windows host has been unreachable since round 3. Everything reproducible on macOS was re-run today at both revisions; the Windows arms were not.
  • app.getAppMetrics() cost per force-kill. Unbenchmarked. See Trade-off 2.

ELI5

Orca sometimes needs to forcefully kill a group of background processes — a terminal's shell, an agent CLI and everything they started. On Windows it does that by process ID. The check that decides "is this ID safe to kill?" asked "does this process belong to me?", and Orca's own window — the thing you're looking at — technically does belong to Orca. So under the wrong timing, the cleanup routine could be handed permission to kill Orca's own UI.

To a user that looks like the window suddenly going blank or the app appearing to die for no reason. And here's the frustrating part: when that happens, the crash report Orca sends back looks exactly the same as one where an antivirus, a system update, or the user's own task manager killed it. Twenty of these came in from the field and there was no way to tell which was which.

This change does two things. It teaches one of the main cleanup routines that Orca's own window is never a valid thing to kill. And it makes Orca write a short note to itself when it kills something — "I killed process 21688, from the terminal cleanup, 121ms before this crash" — so future reports answer the question directly. It is a partial fix: several other cleanup routines still don't ask that safety question, and in one place a refused kill now means the thing Orca meant to stop keeps running.

Merge Risk

MEDIUM as merged, and it merged without a clean review round. The guard, instrumentation and all five extractions are individually clean and well tested. What raises the risk is what did not land and one thing that did:

  • Fixed — the win32 reaped-pid skip no longer flips the termination barrier. The hasExited(child) short-circuit correctly avoids taskkill /t /f on a pid Windows may have reissued (Windows PTY teardown: ancestry own is not true root identity (PID recycle into Orca tree) #10680), but it resolved true — verified tree termination. A taskkill against a reaped pid already resolved false, and run-process.ts turns true into barrierTerminationVerified + terminationReporter.report(), which releases the git admission grant on root exit instead of on close. It now resolves false. Failure it prevents: a git fetch root exits while git-remote-https.exe still holds the inherited pipes, and the next git command is admitted against a repo that descendant is still writing.
  • Cleared: self-initiated-tree-kill-log is bounded (32-entry ring plus a 128-key LRU coalesce map — no session-lifetime growth); the Claude login extraction and both Codex teardown extractions are faithful moves preserving pid resolution, the 5s ladder, the finish() double-guard, the ESRCH contract and every fallback.
  • Open on main — the guard is not a choke point. Six pid-addressed taskkill families in Electron main are ungated: the git command-runner abort, the notebook and precheck timeouts, the codex app-server deadline kill, the runProcess choke point and the ephemeral-VM recipe kill. A main-issued kill from any of those can still land on a pid Electron is accounting for, and leaves no breadcrumb.
  • Open on main — a refusal silently leaks the commit-message agent. Trade-off 9. This is a new failure mode this PR introduced.
  • Open on main — the ring can evict the discriminating entry. Plain FIFO; 32 routine win-pty-job teardowns from a window-close burst push out the one win-taskkill-tree entry that explains the death, leaving a detail byte-identical to the external-kill arm.
  • Open on main — the coverage doc misdescribes the uninstrumented sites. self-initiated-tree-kill-log.ts still says the notebook, precheck, browser-route and ephemeral-VM kills are process.kill(-pid) group calls. On Windows all four take the pid-addressed taskkill arm, and the git command-runner and codex app-server paths are missing from the list entirely. The next investigator reading selfInitiatedTreeKillCount: 0 is pointed the wrong way by the module whose only job is telling them how to read it.
  • P2 — synchronous app.getAppMetrics() per kill and again per verify, fanned out over every added root in codex-structured-turn-processes.ts:61.

Trade-offs

  1. A real refusal, so a real risk of a missed kill. terminateWindowsProcessTree and classifyWindowsTreeKillTarget return early / foreign for any pid in app.getAppMetrics(). If a PTY root pid were ever legitimately equal to one of our Chromium pids, that tree is left running. No current caller can produce that — the callers are PTY shells, codex CLI roots, git children and the source-control agent, none of which is an Electron child of ours. A recycled pid landing on a live Chromium pid is exactly the case we want refused. The claim that a refusal is always harmless is false as merged — see 9.

  2. app.getAppMetrics() is now called once per force-kill. A synchronous in-process read of browser-side state (~4-30 processes), not an OS process-table enumeration. codex-structured-turn-processes fans out over every added root, so a turn teardown makes N of these calls, and windows-pty-root-identity.ts:150 plus terminateWindowsProcessTree means two calls per Windows PTY close. This is unbenchmarked — flagged rather than hidden. It is deliberately uncached: a TTL cache would let a recycled pid slip past the refusal, which is the whole point of the guard.

  3. Diagnostic breadcrumbs cost ring slots and a disk flush. The crash breadcrumb ring is 30 entries with FIFO eviction, and a durable crumb forces a synchronous sink flush. The first revision wrote uncoalesced crumbs from routine teardown and reviewers reproduced 12 terminal closes × 3 process groups completely evicting the ring — including this PR's own refusal crumb. As merged they go through recordCoalescedDurableCrashBreadcrumb (5s window for pid-addressed taskkills, 60s for routine group/job teardown), so a burst costs one slot and one flush. A regression test replays that exact 12×3 reproduction.

  4. The self-kill ring itself can evict the discriminating entry. Separate from 3: selfInitiatedKills is a 32-slot plain-FIFO ring on main. A Windows window-close burst is 30+ win-pty-job group kills, which can push out the win-taskkill-tree entry that would explain the death. When that happens the detail comes back byte-identical to the external-kill arm — the exact undecidability this PR exists to remove, in the exact scenario the field reports come from. Scope-aware eviction is in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459 (and its first attempt there was itself defective; see Adversarial review round 4).

  5. selfInitiatedTreeKillCount = 0 does not mean "not us". The ring is per-process and its only reader lives in Electron main, so kills issued from the daemon, relay or CLI record into a ring nothing reads. What remains uninstrumented is only the POSIX process.kill(-pid, …) group arms… (not in this merge.) As merged, six pid-addressed taskkill families in Electron main are also uninstrumented — the git command-runner abort, the notebook and precheck timeouts, the codex app-server deadline kill, the runProcess choke point and the ephemeral-VM recipe kill. Worse, the module's own coverage doc still describes four of them as POSIX group kills, so the doc actively misleads. Absence is evidence, not proof — and on main it is weak evidence.

  6. selfInitiatedTreeKillCount has a routine base rate. Every aborted or timed-out runProcess on Windows records scope win-taskkill-tree, including ordinary cancelled git; killSpawnedCommandTree alone has 14 call sites. A nonzero count is not by itself suspicious. Read the selfInitiatedKills site string.

  7. Relay bundle growth. src/relay/pty-handler.ts imports forceKillPosixPtyProcessGroups and terminatePtyJob, so the relay now pulls in crash-breadcrumb-store + observability/tracer. pnpm build:relay succeeds for all six platform targets plus both WSL relays (exit 0). In the relay there is no active sink, so startSpan/flushActiveSink are no-ops and only the bounded in-memory ring is touched.

  8. No newly-swallowed errors, and no remote wire change. Breadcrumb calls were deliberately moved outside the try blocks whose catch is the ESRCH contract (posix-pty-process-groups, codex teardown, claude POSIX branch, windows-pty-job), so a throw from the diagnostic path can never be reported as a failed kill. Crash-report details are local-only and the new keys are additive optional fields inside an existing details bag; an older client reading a newer bundle ignores them. forceKillPosixPtyProcessGroups and terminatePtyJob run on the execution host, so the crumb is recorded wherever the kill was actually issued. Folder workspaces are unaffected; nothing here touches git or worktree state.

  9. NEW USER-FACING COST, shipped: a refused kill silently leaks the commit-message agent. killSourceControlAgentProcess (source-control-local-process.ts:33) has no child.kill() fallback on its win32 arm, and since this merge terminateWindowsProcessTree returns Promise.resolve() on refusal. So if the guard ever refuses that pid, the caller marks the process closed and the agent's tree keeps running against the repo. Who it affects: Windows users generating commit messages / source-control text locally. How likely: only when the agent's pid collides with a live Chromium pid, i.e. the pid-recycling case the guard exists for — rare, but the same rarity this whole PR treats as real enough to justify the guard. Fixed in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459 (9bac44ee970), not on main. This trade-off did not exist before this PR; the refusal created it.

  10. Test-visible API churn. WindowsTreeKiller gained an optional deps param carrying site; a handful of existing test assertions were updated to expect it.

Adversarial review

Six rounds. It never converged clean, and it merged anyway. No round signed
off. Rounds 4-6 ran after the merge, against main plus the branch tip, and
rounds 4 and 5 each found a defect in the previous round's remediation. The
items marked "in #18459" below are open work in an unmerged, unreviewed-clean
PR
— they are not resolved, and nothing here should be read as if they were.

Round 1 — three blocking findings, all accepted and fixed (commit 8e6a107):

  • Breadcrumb flood. Uncoalesced durable crumbs from two routine teardown paths; the reviewer reproduced 12 terminal closes × 3 process groups evicting the whole 30-slot ring, including this PR's own refusal crumb, plus a writeSync per killed group. Fixed by routing through recordCoalescedDurableCrashBreadcrumb, with the reviewer's exact reproduction locked in as a test.
  • Undifferentiated count. posix-process-group and win-pty-job scopes cannot reach a Chromium process but were counted with the same weight as win-taskkill-tree, and scope was missing from the persisted string. Fixed: scope is now in every entry and the count is split.
  • Recording gaps and a false comment. The shipped comment claiming a "single taskkill choke point" was contradicted by two other main-process taskkill sites. Fixed: comment gone, all three families share admitSelfInitiatedTreeKill, and the runProcess choke point is instrumented via a setProcessTreeKillObserver seam.

Round 2 — four blocking findings; three accepted, one rebutted in part (commit 1796073):

  • "The guard is a no-op in the daemon that issues the pty-descendant-sweep taskkill." REBUTTED IN PART, and here is why. The mechanism is correct — the standalone daemon never calls setAppEnvironment, so the Chromium pid set is empty there. But it is not a live hazard: the daemon reaches that taskkill only through classifyWindowsTreeKillTarget, whose ancestry walk terminates at the killing process's pid. Orca's Chromium processes descend from Electron main, a sibling of the daemon, so from a daemon ownerPid the walk dead-ends and returns foreign. The reviewer's probe passed ownerPid: 1000 with the renderer as a direct child — that is the Electron-main topology, where the AppEnvironment is installed and the guard does fire. Rather than leave that as prose it is a falsifiable test pair in own-chromium-tree-kill-guard.test.ts and is documented in orca-chromium-process-pids.ts. Residual risk of the rebuttal: the argument rests on process topology, not on a runtime assertion; if a future change ever made a Chromium process a descendant of the daemon, the guard would be silently absent there. The finding did expose one genuine hole, fixed: signalProcessTree's taskkillTree is a fourth pid-addressed family running in daemon/relay/CLI; its win32 branch now refuses a reaped child and falls back to killRoot.
  • Module doc overstated coverage. Accepted, rewritten — but round 3 then found the rewrite itself wrong, and that is still open on main (see round 3).
  • The three out-of-main instrumentation sites were untested. Accepted. Added coverage for the runProcess seam on both branches plus the reaped-child refusal, the group sweep recording only groups it actually signalled, and the Job Object recording only on terminated.
  • The Windows evidence validates a single-process model. Accepted and disclosed — Arm C's claim holds for main-issued kills only.
  • Non-blocking taken: the breadcrumb call moved out of the native terminateJob try.
  • Non-blocking declined: codex-accounts/service.ts records before the spawn, because a refusal must prevent the spawn — the crumb means "we were about to kill this pid". Date.now() over performance.now() was kept and the reviewer agreed: offsets are computed against goneAt = Date.now().

Round 3 — four blocking findings; ONE closed, THREE still open on main. The remediation for the first three lives in 9db1b4ce6ef, which is not an ancestor of main. They are not closed; they are moved to #18459, which is open.

  • "The guard is not a choke point, so the headline claim is false." OPEN ON main. Six pid-addressed taskkill /pid families in main are ungated. Verified today on origin/main: zero admit*TreeKill references in all six, and no ratchet test. Work sits in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459.
  • "The coverage doc misdescribes the uninstrumented sites." OPEN ON main. git show origin/main:src/main/crash-reporting/self-initiated-tree-kill-log.ts still says "Never instrumented: the direct process.kill(-pid) calls in the browser routes, notebooks, automation prechecks and ephemeral-VM recipes" — four Windows pid-addressed taskkills misclassified as POSIX group kills, and the git command-runner and codex app-server paths absent. Residual risk: the interpretive doc for the discriminator is wrong in the direction that produces false exoneration. Affects whoever triages the next G2 bundle.
  • "32 routine win-pty-job teardowns evict the discriminating entry from the FIFO ring." OPEN ON main (Trade-off 4). The fix in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459 was itself defective — round 4 below.
  • "The real-Windows Arm A/B/C evidence no longer matches the code." ACCEPTED AS A DISCLOSED LIMITATION. Not closable: the Windows host was and remains unreachable (ssh awin → connection timed out). The evidence section carries a banner naming which commits changed the key and format and stating that no Windows execution covers the merged code; "Explicitly NOT proven" repeats it. Format is pinned by unit assertions instead. Residual risk: nothing that shipped has ever executed on Windows, and this is a Windows-targeted change. That is the single largest untested surface here, and it affects every Windows user.

Round 4 — three blocking findings, all against the post-merge state. This is the round that discovered the merge/commit mismatch.

  • "The PR is already merged, at 2d0c627ba08, one commit before the content the body claimed." ACCEPTED. 9db1b4ce6ef was committed 87 minutes after the merge and is not an ancestor of main. The body's headline and its three "FIXED in 9db1b4c" entries were false of the shipped artifact. Fixed by rewriting this body (the box at the top) — and re-verified again today.
  • "The round-3 eviction fix creates a new false clean, strictly worse than what shipped." ACCEPTED. With the ring already holding 32 pid-addressed entries, the only non-pid-addressed element is the group kill just pushed at the tail, so the eviction rule splices itself. Reproduced at the branch tip today (probe output in Fix evidence B): selfInitiatedGroupKillCount undefined, pid absent. Fixed in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459 9bac44ee970 by excluding the just-recorded entry from candidacy. Note this is not a main problem — main never got the round-3 fix — but it is why the branch tip must not be merged as-is.
  • "Five of the six newly gated sites return on refusal with no direct-child fallback." ACCEPTED. spawned-command-tree-kill.ts, ipc/notebook.ts, precheck-runner.ts, ephemeral-vm-recipe-process.ts and codex-app-server-session.ts all returned before their child.kill() path, while claude-login-process-termination.ts did it correctly — proving inconsistency, not design. A refusal would have converted a diagnostics feature into a silent process leak. Fixed in fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459 (8fc8aa22646), which adds the root kill to every refusal path.
  • Non-blocking, accepted as known: the ratchet is a string-containment check, not a call-graph check — an unused import satisfies it, and spawn(TASKKILL_BIN, args) evades its regex. Accurate today, brittle tomorrow. Also accepted: admitProcessTreeKill reaches the POSIX arm of signalProcessTree, so the unbenchmarked getAppMetrics() call is not Windows-only (Trade-off 2).
  • Round 4 independently re-ran the whole verification set and confirmed the tests are genuine, not theatre: 17 red at merge-base, green at the tip, tsc ×3 and oxlint clean.

Round 5 — one restated blocking finding and one novel one.

Round 6 — final round, no clean sign-off. It re-probed the round-4 eviction defect rather than raising a new class of finding, and I have not been able to reproduce a round-6 blocking item that is not already listed above. Rather than infer one, the honest summary is the banner at the top of this section: six rounds, none clean, with the round-3 and round-5 items still live on main.

Still open and disclosed rather than closed, across all six rounds: nothing shipped has run on Windows (round 3); the guard is not a choke point on main and the coverage doc misdescribes what it misses (round 3); the FIFO ring can evict the discriminating entry (round 3); a refused source-control kill leaks its tree on main (round 5); app.getAppMetrics() is unbenchmarked (Trade-off 2); the daemon/relay rings are written but unread (Trade-off 5, Follow-up 3); the guard closes only the Chromium half of #10680 (Follow-up 2); and the durable span trail keeps the first pid of a coalesced same-site burst, which the shipped module comment ("The newest pid still rides the emitted crumb") does not qualify.

Follow-ups

These are follow-ups for work that was never in scope here. Anything a review round blocked on is listed as open in Adversarial review above, not laundered into this list.

  1. Land fix(crash-reporting): make the own-Chromium gate a real choke point, and stop a refusal leaking the root #18459, or revert its parts into a reviewed change. It carries the round-3 choke point, the ratchet, the scope-aware eviction, the round-4 refusal-fallback fix and the round-5 source-control leak fix. It is OPEN and has not had a clean round either. Until it lands, Trade-offs 4, 5 and 9 describe shipped behaviour.
  2. Get a Windows host and run the arms against shipped code. Blocked since round 3 on host reachability. This is the largest untested surface.
  3. Benchmark app.getAppMetrics() on the force-kill path. Measure under a codex turn teardown that fans out over N added roots. If material, the fix is not a TTL cache (that would let a recycled pid past the refusal) but hoisting one read per teardown batch.
  4. Close the non-Chromium half of Windows PTY teardown: ancestry own is not true root identity (PID recycle into Orca tree) #10680. A recycle that lands on another Orca descendant — another pane's shell, an agent CLI, a git.exe we spawned — still classifies own. Closing it needs real identity: a Win32_Process.CreationDate baseline, an inherited handle, or a Job Object.
  5. Make the daemon and relay breadcrumb rings readable. Today forceKillPosixPtyProcessGroups, terminatePtyJob and signalProcessTree record into a per-process ring no reader exists for outside Electron main. Either forward those crumbs to main, or attach the daemon's ring to the bundle.
  6. Re-file the G2 cluster. At least four distinct fingerprints (Windows killed/1; POSIX SIGKILL under memory pressure → G4-oom; a duplicated macOS V8 Proxy Resolver SIGKILL; one 0x80000003 install-dir ACL crash → G1). Splitting it is a prerequisite for reading the new field correctly.
  7. Rewrite crashAttribution to self-initiated-tree-kill when a pid-addressed kill matches the dead renderer. Not shipped because the dead process's pid is not available at the recorder — render-process-gone does not carry it — so the match would have to be inferred from the pre-gone metrics sample.

…d the rest

G2 is 20 field reports that share only a symptom. It is at least four
fingerprints: ~15 Windows `reason=killed exitCode=1`, 3 POSIX SIGKILL under
memory pressure (G4-oom), 2 duplicate reports of one macOS V8 Proxy Resolver
SIGKILL, and 1 `0x80000003` install-dir ACL crash (G1; #17740 ships in
v1.4.196 only, not 1.4.195). Nothing here claims to fix all of them.

Two changes:

1. Behaviour. `classifyWindowsTreeKillTarget` returns `own` for any direct
   child of the main process — which our renderer, GPU and network-service
   utility all are — so PTY teardown could `taskkill /T /F` Orca's own UI
   (#10680). Both that classifier and `terminateWindowsProcessTree` now refuse
   any pid Electron is currently accounting for in `getAppMetrics()`.

2. Diagnosis. An Orca-issued kill and an external one are byte-identical in
   every field the crash report records today, so the cluster is undecidable.
   Every main-process force-kill choke point now records a durable
   `self_tree_kill` breadcrumb, and `process_gone` reports carry
   `selfInitiatedTreeKills` naming the pid and its offset from the death.
   A refused kill records `self_tree_kill_refused_own_chromium`, which is
   falsifiable: if it ever shows up in the field, we were the killer.
…scriminator

Round-1 review remediation. Three blocking findings, all accepted.

1. Breadcrumb flood (accepted). recordSelfInitiatedTreeKill wrote an
   uncoalesced durable crumb from two routine teardown paths, and the
   reviewer reproduced 12 terminal closes x 3 process groups completely
   evicting the 30-slot ring — including this PR's own refusal crumb — plus a
   forced writeSync per killed group. It now uses the existing
   recordCoalescedDurableCrashBreadcrumb (5s window for pid-addressed
   taskkills, 60s for routine group/job teardown), so a burst costs one ring
   slot and one flush. The refusal crumb is coalesced per victim pid, so a
   retry loop cannot flood while a distinct pid always gets its own crumb.
   Regression test replays the reviewer's exact 12x3 reproduction and asserts
   the refusal crumb and a pre-existing gpu_process_crashed both survive.

2. Undifferentiated count (accepted). posix-process-group and win-pty-job are
   structurally incapable of reaching a Chromium process, and scope was absent
   from the persisted string. Scope is now in every entry
   (`<scope>/<site>/pid<N> +Nms`), and the count is split:
   selfInitiatedTreeKillCount now counts only pid-addressed taskkills — the
   kills that can land on a recycled pid that is now our renderer — with
   pty-scoped sweeps in selfInitiatedGroupKillCount. The list is renamed
   selfInitiatedKills because it carries both, and sorts pid-addressed kills
   first so truncation never drops the discriminating ones for teardown noise.
   The reviewer's repro (routine macOS terminal close + unrelated exit-133
   crash) now yields selfInitiatedTreeKillCount undefined.

3. Recording gaps and a false comment (accepted). New
   admitSelfInitiatedTreeKill gate: it refuses own-Chromium pids and records
   the rest, and all three main-process taskkill families now go through it —
   terminateWindowsProcessTree plus codex-accounts/service.ts and
   claude-accounts (which keep their own spawn lifetimes). The false "single
   taskkill choke point" comment is gone. The runProcess choke point the
   investigation asked for is instrumented via a
   setProcessTreeKillObserver seam in src/shared/child-process — shared code
   runs in the CLI and relay so it cannot import the main breadcrumb store —
   registered in main preflight. The codex app-server POSIX group teardowns
   and the claude POSIX branch record too. The module doc no longer claims
   absence is discriminating: it enumerates what is instrumented and names the
   direct process.kill(-pid) sites that are not.

Non-blocking, also fixed:
- Breadcrumb calls moved out of the try blocks whose catch is the ESRCH
  contract (posix-pty-process-groups, codex teardown, claude POSIX), so a
  throw from the diagnostic path can never be reported as a failed kill.
- Detail truncation now bounds the first entry too, matching its comment.
- own-chromium-tree-kill-refusal.test.ts renamed to
  own-chromium-tree-kill-guard.test.ts, colocated with the module it tests.

Not changed, with reasons:
- Date.now() vs performance.now(): kept. Offsets are computed against
  goneAt = Date.now() in process-gone-recorder; a monotonic clock here would
  make the offsets meaningless. The reviewer verified this and agreed it is
  not a defect.
- app.getAppMetrics() per force-kill remains unbenchmarked. It reads
  in-process browser state rather than enumerating the OS process table, and a
  TTL cache would let a recycled pid slip past the refusal, so it stays
  uncached.
- The ~15 remaining direct process.kill(-pid) sites (browser routes,
  notebooks, automation prechecks, ephemeral VM recipes) are not instrumented.
  Rather than claim coverage this PR does not have, the module doc names them.

claude-command-process.ts crossed the 300-line cap, so terminateClaudeProcess
moved to claude-login-process-termination.ts. No max-lines suppression added.
…logy

Round-2 review findings on the own-Chromium tree-kill guard.

BLOCKING 1 — "the own-Chromium refusal is a no-op in the process that issues
the pty-descendant-sweep taskkill". Correct on the mechanism, wrong on the
consequence; REBUTTED in part and documented in full.

Confirmed: the only non-test `setAppEnvironment` installs are
main-process-preflight.ts:177 (Electron) and orcad-entry.ts:84 (Node, whose
`getAppMetrics()` is `[]`); daemon-init-fresh-import.ts is a test harness. So
in the standalone daemon `readOrcaChromiumProcessPids()` is empty and
`admitSelfInitiatedTreeKill` always admits.

But that is not a live hazard. `killWithDescendantSweep` reaches
`terminateWindowsProcessTree` only when `verifyWindowsTreeKillTarget` returns
`own`, and that walks ancestry back to `deps.ownerPid ?? process.pid` — the
KILLING process's pid. In the daemon that is the daemon's pid. Orca's Chromium
processes are children of Electron main, a sibling of the daemon, so their
chain never reaches it: hop 0 lands on main, and within MAX_ANCESTOR_HOPS the
walk dead-ends and returns `foreign`. The reviewer's probe passes
`ownerPid: 1000` with the renderer as a direct child of 1000 — that is the
Electron-main topology, where the AppEnvironment IS installed and the guard DOES
fire, not the daemon's. On an orcad/SSH host there is no Chromium on the box at
all, so `[]` is accurate rather than degraded.

Locked in as tests rather than prose (own-chromium-tree-kill-guard.test.ts):
a renderer classifies `foreign` from a daemon ownerPid with an empty pid set,
and `own` from main's ownerPid with an empty set — the falsifiable pair showing
the pid set is load-bearing in main and nowhere else. Documented the host
coverage in orca-chromium-process-pids.ts and own-chromium-tree-kill-guard.ts.

One genuine hole the finding exposes: `signalProcessTree`'s `taskkillTree` is a
fourth pid-addressed taskkill family (non-blocking item 2), it runs in the
daemon/relay/CLI where the guard cannot run, and it guarded only on
`!child.pid`. Reusing the predicate the codex login teardown already uses, the
win32 branch now refuses a reaped child and falls back to `killRoot` — the same
shape as the existing `!child.pid` branch. That closes the reaped-then-recycled
pid path in every host.

BLOCKING 2 — module doc overstates coverage. Rewritten: the ring is per-process
and its only reader lives in Electron main, so a count on a `render-process-gone`
covers main-issued kills only. Sites are now split into main-only, main-and-
other-hosts (runProcess choke point, POSIX PTY group sweep, Windows Job Object —
which record into a ring nothing reads when they run in the daemon or relay),
and never-instrumented, with the note that a daemon/relay omission is a
diagnostics gap, not a missed suspect, per the topology argument above.

BLOCKING 3 — the three out-of-main instrumentation sites were untested. Added
regression coverage: the runProcess seam on both branches plus the reaped-child
refusal (process-tree-termination.test.ts), the group sweep recording only
groups it actually signalled and skipping an ESRCH group
(posix-pty-process-groups.test.ts), and the Job Object recording the shell pid
only on `terminated` (windows-pty-job.test.ts). Verified red: reverting the
three production files to origin/main fails 7 of the new tests.

BLOCKING 4 — the Windows evidence validates a single-process model. Accepted.
The main2.js arms exercise `pty-descendant-sweep` inside one Electron process;
that models the in-process/degraded daemon and the local PTY provider, not the
standalone daemon. Arm C's "the 449351d6 shape is not producible with the guard"
holds for main-issued kills only. In the daemon the shape is blocked one layer
earlier, by the ancestry check, which the arms do not exercise.

NON-BLOCKING taken: `recordSelfInitiatedTreeKill` moved outside the native
`terminateJob` try in windows-pty-job.ts, so a diagnostics throw can no longer
downgrade a real termination to `unavailable` and escalate callers to a broader
kill; covered by a test. The "all three families" parenthetical is gone with the
doc rewrite. `pnpm build:relay` run: exit 0, all seven targets built.

NON-BLOCKING declined: codex-accounts/service.ts records before the spawn
because a refusal must prevent the spawn — the crumb means "we were about to
kill this pid", which is the artifact worth having; the existing comment already
says so. `app.getAppMetrics()` perf is unbenchmarked and unchanged by this round.

Verification: pnpm tc clean; oxlint clean on touched paths;
check:code-quality:changed 0 new findings; oxfmt applied. 730 tests pass across
shared/child-process, main/crash-reporting, main/pty, main/windows and the guard
and descendant-sweep suites. The 4 failures in providers/git/codex-integration
reproduce on HEAD without these changes.
@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds process-tree kill observation and crash-report details for Orca-issued terminations. It prevents Windows tree kills from targeting Electron-owned Chromium processes. It propagates site metadata through Codex, PTY, rate-limit, and source-control termination paths. It records successful POSIX process-group and Windows PTY Job Object terminations. Claude login termination moves to a dedicated module with guarded Windows handling and consistent callback completion. Tests cover the new logging, admission, metadata, and termination behavior.

Merge Risk: 🟠 High · up to 2d0c6

The change improves termination safety and diagnostics, but unresolved races can still kill an unrelated Windows process tree, including Chromium processes, and failed termination attempts may be reported as successful Orca-issued kills. These issues should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 41 functions across 27 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed context, scope, rationale, testing evidence, limitations, and follow-ups. However, it omits required template sections and information, including a Linked Issue, Visu… Add every required template section. Provide the issue reference after Fixes #; add before/after visual evidence or write N/A with a brief reason; complete the Testing checklist and list tested platforms; complete AI Disclosure as appli…
✅ Passed checks (3 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 identifies the main change: recording Orca-initiated tree kills for crash-report attribution. It is concise and specific.
Full details: Description check

Explanation

The description provides detailed context, scope, rationale, testing evidence, limitations, and follow-ups. However, it omits required template sections and information, including a Linked Issue, Visual Proof or an exact N/A statement, the Testing checklist, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the final Checklist.

Resolution

Add every required template section. Provide the issue reference after Fixes #; add before/after visual evidence or write N/A with a brief reason; complete the Testing checklist and list tested platforms; complete AI Disclosure as applicable; complete Review, Agent skill upstream boundary, Notes, and the final Checklist. Retain the existing technical details as supporting content under the matching headings.

  • 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: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: da8f802f-5a43-444e-887c-e8304b5f8ac5

📥 Commits

Reviewing files that changed from the base of the PR and between d5803bd and 1796073.

📒 Files selected for processing (27)
  • src/main/claude-accounts/claude-command-process.ts
  • src/main/claude-accounts/claude-login-process-termination.ts
  • src/main/codex-accounts/service.ts
  • src/main/codex/codex-app-server-process-teardown.test.ts
  • src/main/codex/codex-app-server-process-teardown.ts
  • src/main/codex/codex-structured-turn-processes.ts
  • src/main/crash-reporting/process-gone-recorder.ts
  • src/main/crash-reporting/self-initiated-tree-kill-log.test.ts
  • src/main/crash-reporting/self-initiated-tree-kill-log.ts
  • src/main/orca-chromium-process-pids.ts
  • src/main/own-chromium-tree-kill-guard.test.ts
  • src/main/own-chromium-tree-kill-guard.ts
  • src/main/pty-descendant-termination.ts
  • src/main/pty/posix-pty-process-groups.test.ts
  • src/main/pty/posix-pty-process-groups.ts
  • src/main/rate-limits/codex-probe-termination.test.ts
  • src/main/rate-limits/codex-probe-termination.ts
  • src/main/startup/main-process-preflight.ts
  • src/main/text-generation/commit-message-text-generation-test-harness.ts
  • src/main/text-generation/source-control-local-process.ts
  • src/main/windows-process-tree-kill.ts
  • src/main/windows-pty-root-identity.ts
  • src/main/windows/windows-pty-job.test.ts
  • src/main/windows/windows-pty-job.ts
  • src/shared/child-process/process-tree-kill-observer.ts
  • src/shared/child-process/process-tree-termination.test.ts
  • src/shared/child-process/process-tree-termination.ts

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

Comment on lines +139 to +143
recordSelfInitiatedTreeKill({
pid: snapshot.rootPgid,
site: 'codex-app-server-teardown',
scope: 'posix-process-group'
})

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 | ⚡ Quick win

Propagate snapshot group-signal failure before recording success.

In terminatePosixTree, the default signalGroup suppresses every process.kill error. The caller then records self_tree_kill and returns true. A non-ESRCH failure can leave group members running while teardown reports success. Preserve ESRCH as an already-gone result, but return failure for other errors and record only when process.kill succeeds.

Comment on lines +33 to +34
} catch {
return new Set()

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 | ⚡ Quick win

Fail closed when Chromium metrics cannot be read.

When getAppMetrics() throws, both PID checks can return an empty set. The Windows ancestry classifier can then mark an Electron renderer as own, and the PTY sweep can invoke taskkill /T /F on it. Return a distinct unavailable result and reject PID-addressed tree kills for that result. Keep the empty-set result for hosts without AppEnvironment.

Comment on lines +30 to +35
}): boolean {
// Why: no PTY root, codex root or git child is ever one of our own Chromium
// processes, so a pid that is means the caller is about to kill a renderer,
// the GPU or the browser itself (#10680).
if (readOrcaChromiumProcessPids().has(target.pid)) {
recordRefusedOwnChromiumTreeKill(target)

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Record accepted kills only after taskkill succeeds. admitSelfInitiatedTreeKill records before its three guarded callers run taskkill; timeout, startup error, or nonzero exit therefore leaves a false entry in the five-second attribution window. A later Chromium render-process-gone event can then be marked as Orca-initiated. Keep refusal recording in the guard, and call recordSelfInitiatedTreeKill only from each caller’s confirmed-success path.

// Why: no PTY root, codex root or git child is ever one of our own Chromium
// processes, so a pid that is means the caller is about to kill a renderer,
// the GPU or the browser itself (#10680).
if (readOrcaChromiumProcessPids().has(target.pid)) {

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

Bind tree termination to a stable process identity.

readOrcaChromiumProcessPids() checks only a PID snapshot. If the target exits after this check and Windows reuses the PID for Chromium, the later taskkill /T /F can terminate the new Chromium tree. Use an identity-bound primitive for the guarded callers, such as the existing PTY Job Object path or a retained process identity from spawn; a PID or process-table check alone cannot close this check-to-use window.

resolve(false)
return
}
notifyProcessTreeKill({ pid: rootPid, site: 'run-process-tree', scope: 'win-taskkill-tree' })

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Emit win-taskkill-tree only after taskkill succeeds.

taskkillTree records the kill before completion. Error, nonzero close, and timeout paths call killRoot through finish(true) after the record exists. Notify only when a code === 0 close wins settlement. Add regression coverage for each failure path.

🧰 Tools
🪛 ast-grep (0.45.2)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn as nodeSpawn, type ChildProcess } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

@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 — one minor inconsistency worth a look.

Reviewed changes

  • Own-Chromium tree-kill guard — new readOrcaChromiumProcessPids() / admitSelfInitiatedTreeKill() refuse any pid Electron is currently accounting for, at both classifyWindowsTreeKillTarget and every main-process taskkill /T /F family.
  • Discriminating breadcrumbs — every force-kill choke point records a coalesced durable self_tree_kill crumb, and process-gone now carries selfInitiatedTreeKillCount / selfInitiatedGroupKillCount / selfInitiatedKills.
  • Shared runProcess seam — a setProcessTreeKillObserver seam lets main record signalProcessTree kills; its win32 branch now refuses a reaped (recyclable) pid and falls back to killRoot.

I verified the load-bearing claims independently: goneAt and ring timestamps are both Date.now(); off-main readOrcaChromiumProcessPids() is empty (daemon/orcad install Node environments with getAppMetrics: () => [], only main-process-preflight installs the Electron-backed one); and the new imports pull no electron into the relay (main-process-lifecycle-identity touches only node:crypto, and the pids reader only shared/app-environment). The verify-then-admit double gate plus killWithDescendantSweep's finally { killRoot() } make the refusal safe. The remaining open items (getAppMetrics() cost, unread daemon/relay rings, uninstrumented process.kill(-pid) sites) are disclosed rather than hidden, and none is a regression on main.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

}
})
signalGroup(snapshot.rootPgid, 'SIGKILL')
recordSelfInitiatedTreeKill({

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.

terminatePosixTree records a group kill even when signalGroup hit ESRCH, because the default signalGroup swallows the exception and the breadcrumb call sits unconditionally below it. forceKillPosixPtyProcessGroups deliberately avoids this (its test is literally does not claim a group that was already gone), so this path slightly over-counts selfInitiatedGroupKillCount. Only the non-discriminating group count is affected, but recording only after a successful signal would match the sibling module's contract.

…ination barrier

The win32 hasExited short-circuit correctly avoids taskkill on a pid Windows
may have reissued, but it resolved `true` — verified tree termination. A
taskkill against a reaped pid already resolved `false`, and run-process turns
`true` into barrierTerminationVerified + terminationReporter.report(), which
releases the git admission grant on root exit instead of on `close`. That
admits the next git command while a descendant holding the inherited pipes is
still writing the repo. Resolve `false` so the skip changes only which process
we refuse to signal, not what the barrier claims.

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

Run ID: 742d5b62-5d5a-4bfc-a37b-bfb48023b5d0

📥 Commits

Reviewing files that changed from the base of the PR and between 1796073 and 2d0c627.

📒 Files selected for processing (2)
  • src/shared/child-process/process-tree-termination.test.ts
  • src/shared/child-process/process-tree-termination.ts

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

Comment on lines +36 to +38
if (hasExited(child)) {
killRoot(child, signal)
return Promise.resolve(false)

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

🔎 Supported by static analysis

🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 21303


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
cat -n src/shared/child-process/process-tree-termination.ts
printf '%s\n' '--- directly bound symbols and callers ---'
rg -n -C 3 'hasExited|killRoot|taskkill|notifyProcessTreeKill|terminateProcessTree|process-tree-termination' src test tests 2>/dev/null || true
printf '%s\n' '--- candidate related files ---'
fd -i 'process.*(tree|kill)|child.*process|job' src test tests 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- imports and call sites of signalProcessTree/forceTerminateProcessTree ---'
rg -n -C 4 'signalProcessTree|forceTerminateProcessTree' src tests/e2e --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- Windows identity-gated path ---'
sed -n '235,305p' src/main/pty-descendant-termination.ts
printf '%s\n' '--- process identity implementation ---'
rg -n -C 5 'verifyWindowsTreeKillTarget|WindowsTreeKillTarget|ownsRoot|classifyWindowsTreeKillTarget' src/main src/shared --glob '*.ts'
printf '%s\n' '--- focused tests for the shared termination module ---'
fd -i 'process-tree-termination.*test|child-process.*test' src tests | sort

Repository: stablyai/orca

Length of output: 50369


Bind Windows termination to the original process identity

If child exits after hasExited(child) and before nodeSpawn starts taskkill, Windows may reuse child.pid. taskkill /pid /t /f can then terminate the replacement tree, including Orca Chromium processes. A second exit check is not sufficient. Use a process handle or Job Object, and add a Windows regression test for this interleaving.

🧰 Tools
🪛 ast-grep (0.45.2)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn as nodeSpawn, type ChildProcess } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

@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 in this delta. The reaped-pid false restore is correct and closes the PR body's own "blocking as written" item. I'm holding approval only because the one thread from the prior review is unchanged and still open.

Reviewed changes

  • Restored false from the reaped-pid win32 short-circuit — signalProcessTree's hasExited branch now returns Promise.resolve(false) instead of true, so skipping the taskkill spawn against a reaped, recyclable pid no longer reports verified termination and no longer releases the git admission grant on root exit instead of on close. This matches the pre-PR behavior (a taskkill against a reaped pid already resolved non-zero → false).
  • Updated the discriminator test — the reaped-child case now asserts resolves.toBe(false) with no taskkill spawn, aligning the test with the corrected semantics.

The open thread from review 5098706320 (codex-app-server-process-teardown.ts:139 — the unconditional group-kill breadcrumb over-counting selfInitiatedGroupKillCount when the default signalGroup swallows ESRCH) is untouched by this commit and still applies.

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

@nwparker
nwparker merged commit 7b530f1 into main Sep 3, 2026
28 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…nderer is decidable (stablyai#18367)

* fix(windows): refuse tree-kills of Orca's own Chromium pids and record the rest

G2 is 20 field reports that share only a symptom. It is at least four
fingerprints: ~15 Windows `reason=killed exitCode=1`, 3 POSIX SIGKILL under
memory pressure (G4-oom), 2 duplicate reports of one macOS V8 Proxy Resolver
SIGKILL, and 1 `0x80000003` install-dir ACL crash (G1; stablyai#17740 ships in
v1.4.196 only, not 1.4.195). Nothing here claims to fix all of them.

Two changes:

1. Behaviour. `classifyWindowsTreeKillTarget` returns `own` for any direct
   child of the main process — which our renderer, GPU and network-service
   utility all are — so PTY teardown could `taskkill /T /F` Orca's own UI
   (stablyai#10680). Both that classifier and `terminateWindowsProcessTree` now refuse
   any pid Electron is currently accounting for in `getAppMetrics()`.

2. Diagnosis. An Orca-issued kill and an external one are byte-identical in
   every field the crash report records today, so the cluster is undecidable.
   Every main-process force-kill choke point now records a durable
   `self_tree_kill` breadcrumb, and `process_gone` reports carry
   `selfInitiatedTreeKills` naming the pid and its offset from the death.
   A refused kill records `self_tree_kill_refused_own_chromium`, which is
   falsifiable: if it ever shows up in the field, we were the killer.

* fix(crash-reporting): coalesce self-kill breadcrumbs and scope the discriminator

Round-1 review remediation. Three blocking findings, all accepted.

1. Breadcrumb flood (accepted). recordSelfInitiatedTreeKill wrote an
   uncoalesced durable crumb from two routine teardown paths, and the
   reviewer reproduced 12 terminal closes x 3 process groups completely
   evicting the 30-slot ring — including this PR's own refusal crumb — plus a
   forced writeSync per killed group. It now uses the existing
   recordCoalescedDurableCrashBreadcrumb (5s window for pid-addressed
   taskkills, 60s for routine group/job teardown), so a burst costs one ring
   slot and one flush. The refusal crumb is coalesced per victim pid, so a
   retry loop cannot flood while a distinct pid always gets its own crumb.
   Regression test replays the reviewer's exact 12x3 reproduction and asserts
   the refusal crumb and a pre-existing gpu_process_crashed both survive.

2. Undifferentiated count (accepted). posix-process-group and win-pty-job are
   structurally incapable of reaching a Chromium process, and scope was absent
   from the persisted string. Scope is now in every entry
   (`<scope>/<site>/pid<N> +Nms`), and the count is split:
   selfInitiatedTreeKillCount now counts only pid-addressed taskkills — the
   kills that can land on a recycled pid that is now our renderer — with
   pty-scoped sweeps in selfInitiatedGroupKillCount. The list is renamed
   selfInitiatedKills because it carries both, and sorts pid-addressed kills
   first so truncation never drops the discriminating ones for teardown noise.
   The reviewer's repro (routine macOS terminal close + unrelated exit-133
   crash) now yields selfInitiatedTreeKillCount undefined.

3. Recording gaps and a false comment (accepted). New
   admitSelfInitiatedTreeKill gate: it refuses own-Chromium pids and records
   the rest, and all three main-process taskkill families now go through it —
   terminateWindowsProcessTree plus codex-accounts/service.ts and
   claude-accounts (which keep their own spawn lifetimes). The false "single
   taskkill choke point" comment is gone. The runProcess choke point the
   investigation asked for is instrumented via a
   setProcessTreeKillObserver seam in src/shared/child-process — shared code
   runs in the CLI and relay so it cannot import the main breadcrumb store —
   registered in main preflight. The codex app-server POSIX group teardowns
   and the claude POSIX branch record too. The module doc no longer claims
   absence is discriminating: it enumerates what is instrumented and names the
   direct process.kill(-pid) sites that are not.

Non-blocking, also fixed:
- Breadcrumb calls moved out of the try blocks whose catch is the ESRCH
  contract (posix-pty-process-groups, codex teardown, claude POSIX), so a
  throw from the diagnostic path can never be reported as a failed kill.
- Detail truncation now bounds the first entry too, matching its comment.
- own-chromium-tree-kill-refusal.test.ts renamed to
  own-chromium-tree-kill-guard.test.ts, colocated with the module it tests.

Not changed, with reasons:
- Date.now() vs performance.now(): kept. Offsets are computed against
  goneAt = Date.now() in process-gone-recorder; a monotonic clock here would
  make the offsets meaningless. The reviewer verified this and agreed it is
  not a defect.
- app.getAppMetrics() per force-kill remains unbenchmarked. It reads
  in-process browser state rather than enumerating the OS process table, and a
  TTL cache would let a recycled pid slip past the refusal, so it stays
  uncached.
- The ~15 remaining direct process.kill(-pid) sites (browser routes,
  notebooks, automation prechecks, ephemeral VM recipes) are not instrumented.
  Rather than claim coverage this PR does not have, the module doc names them.

claude-command-process.ts crossed the 300-line cap, so terminateClaudeProcess
moved to claude-login-process-termination.ts. No max-lines suppression added.

* fix(crash-reporting): scope the self-kill guard to its real host topology

Round-2 review findings on the own-Chromium tree-kill guard.

BLOCKING 1 — "the own-Chromium refusal is a no-op in the process that issues
the pty-descendant-sweep taskkill". Correct on the mechanism, wrong on the
consequence; REBUTTED in part and documented in full.

Confirmed: the only non-test `setAppEnvironment` installs are
main-process-preflight.ts:177 (Electron) and orcad-entry.ts:84 (Node, whose
`getAppMetrics()` is `[]`); daemon-init-fresh-import.ts is a test harness. So
in the standalone daemon `readOrcaChromiumProcessPids()` is empty and
`admitSelfInitiatedTreeKill` always admits.

But that is not a live hazard. `killWithDescendantSweep` reaches
`terminateWindowsProcessTree` only when `verifyWindowsTreeKillTarget` returns
`own`, and that walks ancestry back to `deps.ownerPid ?? process.pid` — the
KILLING process's pid. In the daemon that is the daemon's pid. Orca's Chromium
processes are children of Electron main, a sibling of the daemon, so their
chain never reaches it: hop 0 lands on main, and within MAX_ANCESTOR_HOPS the
walk dead-ends and returns `foreign`. The reviewer's probe passes
`ownerPid: 1000` with the renderer as a direct child of 1000 — that is the
Electron-main topology, where the AppEnvironment IS installed and the guard DOES
fire, not the daemon's. On an orcad/SSH host there is no Chromium on the box at
all, so `[]` is accurate rather than degraded.

Locked in as tests rather than prose (own-chromium-tree-kill-guard.test.ts):
a renderer classifies `foreign` from a daemon ownerPid with an empty pid set,
and `own` from main's ownerPid with an empty set — the falsifiable pair showing
the pid set is load-bearing in main and nowhere else. Documented the host
coverage in orca-chromium-process-pids.ts and own-chromium-tree-kill-guard.ts.

One genuine hole the finding exposes: `signalProcessTree`'s `taskkillTree` is a
fourth pid-addressed taskkill family (non-blocking item 2), it runs in the
daemon/relay/CLI where the guard cannot run, and it guarded only on
`!child.pid`. Reusing the predicate the codex login teardown already uses, the
win32 branch now refuses a reaped child and falls back to `killRoot` — the same
shape as the existing `!child.pid` branch. That closes the reaped-then-recycled
pid path in every host.

BLOCKING 2 — module doc overstates coverage. Rewritten: the ring is per-process
and its only reader lives in Electron main, so a count on a `render-process-gone`
covers main-issued kills only. Sites are now split into main-only, main-and-
other-hosts (runProcess choke point, POSIX PTY group sweep, Windows Job Object —
which record into a ring nothing reads when they run in the daemon or relay),
and never-instrumented, with the note that a daemon/relay omission is a
diagnostics gap, not a missed suspect, per the topology argument above.

BLOCKING 3 — the three out-of-main instrumentation sites were untested. Added
regression coverage: the runProcess seam on both branches plus the reaped-child
refusal (process-tree-termination.test.ts), the group sweep recording only
groups it actually signalled and skipping an ESRCH group
(posix-pty-process-groups.test.ts), and the Job Object recording the shell pid
only on `terminated` (windows-pty-job.test.ts). Verified red: reverting the
three production files to origin/main fails 7 of the new tests.

BLOCKING 4 — the Windows evidence validates a single-process model. Accepted.
The main2.js arms exercise `pty-descendant-sweep` inside one Electron process;
that models the in-process/degraded daemon and the local PTY provider, not the
standalone daemon. Arm C's "the 449351d6 shape is not producible with the guard"
holds for main-issued kills only. In the daemon the shape is blocked one layer
earlier, by the ancestry check, which the arms do not exercise.

NON-BLOCKING taken: `recordSelfInitiatedTreeKill` moved outside the native
`terminateJob` try in windows-pty-job.ts, so a diagnostics throw can no longer
downgrade a real termination to `unavailable` and escalate callers to a broader
kill; covered by a test. The "all three families" parenthetical is gone with the
doc rewrite. `pnpm build:relay` run: exit 0, all seven targets built.

NON-BLOCKING declined: codex-accounts/service.ts records before the spawn
because a refusal must prevent the spawn — the crumb means "we were about to
kill this pid", which is the artifact worth having; the existing comment already
says so. `app.getAppMetrics()` perf is unbenchmarked and unchanged by this round.

Verification: pnpm tc clean; oxlint clean on touched paths;
check:code-quality:changed 0 new findings; oxfmt applied. 730 tests pass across
shared/child-process, main/crash-reporting, main/pty, main/windows and the guard
and descendant-sweep suites. The 4 failures in providers/git/codex-integration
reproduce on HEAD without these changes.

* fix(crash-reporting): keep the reaped-pid skip from flipping the termination barrier

The win32 hasExited short-circuit correctly avoids taskkill on a pid Windows
may have reissued, but it resolved `true` — verified tree termination. A
taskkill against a reaped pid already resolved `false`, and run-process turns
`true` into barrierTerminationVerified + terminationReporter.report(), which
releases the git admission grant on root exit instead of on `close`. That
admits the next git command while a descendant holding the inherited pipes is
still writing the repo. Resolve `false` so the skip changes only which process
we refuse to signal, not what the barrier claims.
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