Skip to content

fix(process-table): bound collectDescendantsFromIndex against PID-reuse cycles - #20715

Closed
brynnclaw wants to merge 1 commit into
stablyai:mainfrom
brynnclaw:fix/descendant-walk-pid-cycle-guard
Closed

brynnclaw wants to merge 1 commit into
stablyai:mainfrom
brynnclaw:fix/descendant-walk-pid-cycle-guard

Conversation

@brynnclaw

Copy link
Copy Markdown
Contributor

Drafted by Warden (Claude Code) on Brynn's behalf; Brynn reviewed.

ELI5

When Orca lists Windows processes to find what's running in a terminal, it walks the "who is a child of whom" tree. The Windows process list isn't a frozen snapshot, and Windows reuses process IDs aggressively, so once in a while the list says A is B's parent and B is A's parent — a loop. The tree walk had no "already seen this one" check, so it went round that loop forever, piling up objects until the terminal host ran out of memory and died, taking every open terminal with it. This adds the missing "already seen" check.

What Changed

collectDescendantsFromIndex in src/shared/process-table-index.ts now carries a visited set of pids and never pushes a pid it has already queued. That is the only behavioural change. On a well-formed table every pid is unique, so the guard never fires and the existing deepest-last ordering is byte-for-byte unchanged.

Adds src/shared/process-table-index.test.ts.

Why

A process-table capture (Toolhelp32 on Windows, ps on POSIX) is not atomic, and Windows recycles pids quickly. A capture taken during heavy process churn can therefore contain a pid-reuse cycle: a row whose ppid points at one of its own descendants, because that descendant's pid was reused by a newly-spawned ancestor between reads. childrenByPpid then has A -> B and B -> A, and the walk

const stack = (index.childrenByPpid.get(rootPid) ?? []).map((row) => ({ row, depth: 1 }))
while (stack.length > 0) {
  const { row, depth } = stack.pop()!
  descendants.push({ ...row, depth })
  for (const child of index.childrenByPpid.get(row.pid) ?? []) {
    stack.push({ row: child, depth: depth + 1 })   // no visited guard
  }
}

pushes {...row, depth} objects without bound. In the daemon this runs on the Windows foreground-process path (windows-foreground-process-rows.ts, agent-foreground-process.ts) on every pane refresh, so the terminal host's V8 heap climbs from ~200 MB to the 4 GB cap in ~20 s and aborts — killing every terminal session the daemon hosts.

The sibling ppid walk in pty-descendant-termination.ts already guards this exact hazard, with the comment: "ps is not an atomic snapshot. PID reuse can produce duplicate or cyclic-looking rows, which must not hang the Electron main thread." When the shared index machinery was extracted, the descendant walk did not carry that guard. This restores parity.

The approach is the minimal one: a visited set is what the sibling walk uses, it is O(1) per node, and it changes nothing for well-formed tables.

Linked Issue

Fixes #16797

This is a confirmed cause of the silent OOM aborts reported there on Windows. It is independent of the missing-native-addon staging in #19522 — the OOM reproduces on both the native process-tree path and the PowerShell CIM fallback, because both feed the same index into this walk.

Visual Proof

N/A — no UI or interaction change; this is an internal process-table traversal fix.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Deterministic reproduction against the real function (Node 24, --max-old-space-size=128):

  • Before (unguarded): a 4-row table with a 2-node pid-reuse cycle aborts with EXIT=134 (V8 heap OOM) in under 8 s.
  • After (guarded): the same table returns in microseconds; a self-parented row (pid === ppid) and a descendant that reuses the root pid both terminate; and for a normal acyclic tree the output is identical (same rows, same order, same depths) to the original per-call walk.

New tests in src/shared/process-table-index.test.ts cover: acyclic parity with the plain walk, a 2-node cycle, a self-parented row, and root-pid reuse.

Platforms: the trigger is Windows-specific (pid reuse + Toolhelp32/CIM non-atomicity), but the walk is platform-agnostic pure logic and is also on the POSIX foreground path; verified on Node/Windows. I could not run the full pnpm test/typecheck/build locally (partial clone without installed deps) — the new test follows the repo's existing vitest conventions and is syntax-clean; CI should confirm.

AI Disclosure

Investigated and written with Claude Code (Anthropic). Models: Claude Fable 5.1, with a fallback to Claude Opus 4.8 during the infrastructure work. Root cause was confirmed by the deterministic repro above, not inferred. Brynn reviewed before filing.

Review

AI code-review summary against the contribution checklist:

  • Correctness: guard only skips pids already queued; on unique-pid tables it is a no-op, so acyclic output and ordering are unchanged (asserted in the test against the pre-guard walk).
  • Cross-platform: pure JS/TS, no platform APIs; benefits Windows (the trigger) and POSIX (same shared walk).
  • SSH/remote/local: the daemon's foreground path runs on local and relay hosts alike; both fed this walk, so both are covered.
  • Agent/integration compatibility: no protocol, schema, or public-API change; internal function signature unchanged.
  • Performance: one Set<number> and an O(1) membership check per node; the walk stays linear in table size instead of unbounded.
  • UI: none.
  • Security: no new process spawns, file access, or data flow; strictly bounds an existing traversal.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: bounded traversal only. Cross-platform: pure logic, Windows + POSIX. Remote SSH: covered (same daemon path). Mobile: N/A. Backwards compatibility: output unchanged for well-formed tables. Performance: linear, one set allocation.

Author: Brynn Bendixen (X handle not provided).

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — not run locally (partial clone); relying on CI

…se cycles

A process-table capture is not atomic, so PID reuse can produce duplicate or
cyclic-looking ppid links -- a descendant whose pid a later row reuses as an
ancestor. collectDescendantsFromIndex walked children with no visited set, so
such a cycle sent it into an unbounded DFS: it re-pushed the same rows forever,
grew the terminal-host heap to the V8 4 GB cap, and aborted the daemon, killing
every terminal session it hosted (stablyai#16797).

The sibling ppid walk in pty-descendant-termination.ts already guards this exact
case ("PID reuse can produce duplicate or cyclic-looking rows, which must not
hang the Electron main thread"). This brings the shared walk to parity with a
visited set. Well-formed tables have unique pids, so the guard never fires and
the existing deepest-last ordering is unchanged.

Adds process-table-index.test.ts: a 2-node cycle and a self-parented row now
terminate, a descendant that reuses the root pid does not revisit it, and the
acyclic result still matches the plain per-call walk exactly.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

collectDescendantsFromIndex now records visited PIDs, including the root PID, and avoids pushing previously visited children. This preserves depth-first ordering for valid trees and prevents repeated traversal in cyclic or reused-PID process tables. New tests cover ordering, PID-reuse cycles, self-parented rows, and root-PID reuse.

Priority: ⬆️ High

Severity of issue fixed: High

Merge Risk: 🔵 Low · up to 4ca3e

The current traversal behavior is bounded, but its regression test can miss a root-PID reuse failure. Add the exact-result assertion before merge to preserve this safeguard.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: bounding collectDescendantsFromIndex against PID-reuse cycles.
Description check ✅ Passed The description covers the required sections, explains the root cause and solution, links issue #16797, documents testing and platform scope, and marks the visual proof as not applicable. It also stat…
Linked Issues check ✅ Passed Issue #16797 requires prevention of the confirmed unbounded process-tree traversal that can OOM the Windows terminal daemon. collectDescendantsFromIndex now tracks rootPid and each visited PID bef…
Out of Scope Changes check ✅ Passed The pull request changes only collectDescendantsFromIndex and adds focused tests for its traversal behavior. These changes directly support the process-table OOM cause described in issue #16797. No …
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files.

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: Advanced

Run ID: 388cf678-2591-467b-9e1f-10074ff9190d

📥 Commits

Reviewing files that changed from the base of the PR and between 4a02762 and 4ca3e1a.

📒 Files selected for processing (2)
  • src/shared/process-table-index.test.ts
  • src/shared/process-table-index.ts

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

Comment on lines +74 to +75
expect(got.length).toBeLessThanOrEqual(rows.length)
expect(got.some((r) => r.pid === 60)).toBe(true)

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

Assert that the reused root PID is excluded.

The current assertions pass if visited does not start with rootPid. That regression returns PID 50 after PID 60 but still produces a bounded result. Assert the exact PID list, or assert that PID 50 is absent.

Proposed test update
-    expect(got.length).toBeLessThanOrEqual(rows.length)
-    expect(got.some((r) => r.pid === 60)).toBe(true)
+    expect(got.map((r) => r.pid)).toEqual([60])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(got.length).toBeLessThanOrEqual(rows.length)
expect(got.some((r) => r.pid === 60)).toBe(true)
expect(got.map((r) => r.pid)).toEqual([60])

@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 — the guard itself is correct and well pinned by the new tests. One coverage gap worth a follow-up.

Reviewed changes

  • Bound collectDescendantsFromIndex against PID-reuse cycles — a per-call visited set (seeded with rootPid) now gates every push onto the walk stack, so a cyclic or duplicate childrenByPpid link can no longer grow it without bound. On unique-pid tables the guard never fires, so ordering and depths are unchanged; only the guard is new.
  • New src/shared/process-table-index.test.ts — asserts exact acyclic parity against a pre-guard reference walk, plus bounded termination for a 2-node cycle, a self-parented row (pid === ppid), and root-pid reuse. The parity test is an exact toEqual, and the cycle tests would hang/OOM against the pre-fix walk, so the suite genuinely fails with the bug present.

ℹ️ The relay's private descendant walk still has the unguarded loop

collectDescendants in src/relay/pty-shell-utils.ts:182 is a byte-for-byte copy of the pre-fix walk — same stack.map(...) seed, same unconditional stack.push — and it is live on the relay's foreground RPC (pty-handler.ts:2623 and :2831), which is POSIX-only. The PR body says the shared walk is "also on the POSIX foreground path; verified on Node/Windows" and that local and relay hosts "both fed this walk," but the relay does not call collectDescendantsFromIndex; it feeds its own copy the same index. So a pid-reuse cycle still grows that stack without bound on a relay host. This is pre-existing, not a regression, and the Windows daemon target of #16797 is fully covered by this PR — mentioning it only because the stated relay coverage is inaccurate.

Technical details
# Relay foreground walk is not covered by the shared guard

## Affected sites
- `src/relay/pty-shell-utils.ts:182-196` — private `collectDescendants(index, rootPid)` reproduces the pre-guard stack walk exactly.
- `src/relay/pty-shell-utils.ts:223` — the only caller, via `getForegroundProcessNameFromProcessTable`.
- `src/relay/pty-shell-utils.ts:275, 294` → `getRecognizedForegroundDescendant` → `pty-handler.ts:2623, 2831` — live relay foreground path.
- The file already imports `getProcessTableIndex` / `ProcessTableIndex` from the shared module but not `collectDescendantsFromIndex`.

## Required outcome
The relay's POSIX foreground walk must terminate on a cyclic or duplicate `childrenByPpid` link, matching `collectDescendantsFromIndex`, `collectDescendantRows` (`main/providers/agent-foreground-process-remote-evidence.ts:126`), and the ppid walk in `main/pty-descendant-termination.ts:198`.

## Suggested approach (optional)
Delete the private copy and import `collectDescendantsFromIndex` from `../shared/process-table-index` (same signature: `(index, rootPid) => (Row & { depth })[]`). Alternatively add the same `visited`/`pushUnvisited` guard. Either way, a relay-side regression test mirroring the new cycle test would pin it.

## Open questions for the human (optional)
Is the relay-side copy intentionally retained (e.g. a different row contract) or a leftover from the shared-index extraction?

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

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded by merged #22411, which carries the corresponding fix and regression coverage. Thank you for the original contribution. The broader daemon-exit report #16797 remains open; this closes the duplicate traversal proposal only.

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.

[Bug][Windows] orca-terminal-daemon silently exits while window is backgrounded / display off, killing all hosted PTY sessions (claude et al.)

2 participants