Skip to content

perf: dedupe relay process-table scans behind a short-TTL cache (#6288) - #6667

Merged
nwparker merged 3 commits into
mainfrom
nwparker/fix-6288-relay-ps-scan
Jun 29, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/fix-6288-relay-ps-scan

Conversation

@nwparker

@nwparker nwparker commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

🧑‍🤝‍🧑 Impact & ELI5

What's slow today (ELI5). To label each terminal with the agent running in it (e.g. "codex", "gemini"), Orca peeks at the system's process list. The cheap way would be to ask "what's running under this terminal?" — but the code instead photographs the entire machine's process table and then sifts it down to the one terminal. Every open agent terminal does this on a ~0.75–2s loop. On a shared remote/SSH server with a few projects open, that's a stream of full-table ps scans running forever, and antivirus scans each one — so the server's CPU stays elevated even when nothing is happening. This is the CPU half of #6288; the existing PR #6564 fixes the memory-leak half (leaked IPC listeners on flaky reconnects). They're complementary.

What this PR does (ELI5). When many terminals want that photo at nearly the same moment, take one photo and hand the same copy to all of them, and keep it for half a second before taking a fresh one. Same picture, same freshness for any single terminal — just not re-shot N times per tick.

What was happening

Agent foreground-process inspection runs a full system process-table scan:

ps -axo pid=,ppid=,stat=,command=

then filters to one pid's subtree in JS. It's called per-pane on a 750ms (active) / 2000ms (idle) cadence by the agent-completion coordinator, and keeps running for any pane with agent evidence — even when the pane is hidden (shouldRunCadenceInspection returns true while hasAgentRunEvidence || lastForegroundAgent !== null). With multiple agent terminals across a few projects on one relay, the daemon sustains repeated full-table scans indefinitely, each forked independently with no caching or batching. The same scan exists on the local main-process path (agent-foreground-process.ts), but it's acutely felt on the shared relay daemon.

  • Relay scan: src/relay/pty-shell-utils.ts → getRecognizedForegroundDescendant
  • Local scan: src/main/providers/agent-foreground-process.ts → resolveAgentForegroundProcess
  • Driver/cadence: src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts (ACTIVE_POLL_INTERVAL_MS = 750, IDLE_POLL_INTERVAL_MS = 2000); global cap MAX_INSPECTION_STARTS_PER_SECOND = 8 in agent-process-inspection-queue.ts

Reproduction + measured evidence

Added a deterministic repro/regression test, src/main/providers/agent-foreground-process-ps-scan-volume.test.ts, that drives the real call site (resolveAgentForegroundProcess) under the documented 750ms cadence across 6 concurrently-inspecting agent panes over a 30-second window (40 ticks → 240 inspections) and counts actual ps -axo spawns. A real ps returns the whole system, so the fixture contains every pane's process tree; each pane must still resolve its own foreground agent.

ps -axo full-table scans scans / inspection every pane resolves codex?
Before (main) 240 1.000 ✅
After (this branch) 40 0.167 ✅

≈83% fewer full-table scans (6×). Scan volume is now bounded by poll ticks, not by pane count — adding panes no longer multiplies ps spawns. The test fails on main (ps_scans == inspections) and passes here, so it locks in the win. Measured by overlaying main's pre-cache call site and re-running the identical harness:

[before, main]   inspections=240 ps_scans=240 scans_per_inspection=1.000
[after,  branch] inspections=240 ps_scans=40  scans_per_inspection=0.167

(ps here is mocked to count spawns deterministically — the cost being removed is the spawn itself, which on a real shared relay is also scanned by AV per the issue. The count is the proxy for that CPU.)

The fix

A shared getProcessTableSnapshot() (src/shared/process-table-snapshot.ts) memoizes the scan behind a single in-flight promise + a 500ms TTL, used by both call sites.

  • Why 500ms: below the active poll's minimum inter-poll gap (~675ms = 750ms − 10% jitter), so a single pane never reuses a snapshot older than it would otherwise have scanned itself. Freshness per pane is equal-or-better; a burst of panes polling in the same window collapses from up to ~8 scans/sec down to ~1–2/sec.
  • Capture time is stamped after the scan returns, so a slow ps can't hand back a snapshot that's already past its TTL.
  • Failures are never cached (in-flight is cleared on settle), so a transient ps timeout/error retries on the next call and the existing best-effort fall-through (node-pty's process name) is preserved — terminal identity never breaks PTY operation.
  • Per-process singleton: the relay and local main processes each dedupe their own scans (each relay is its own process).

This deletes redundant work rather than adding more caching layers; no behavior change (same ps data, same fall-through, same Windows branches — Windows uses PowerShell/WMIC, untouched). No git-provider implications (process inspection, not source control).

Scope vs #6564 / #5075

Testing

  • New src/main/providers/agent-foreground-process-ps-scan-volume.test.ts — the repro/regression guard above (before 240 → after 40 scans).
  • New src/shared/process-table-snapshot.test.ts (5 cases): concurrent calls collapse to one scan; cached reuse within TTL; rescan after TTL; capture-time stamped post-scan; failures not cached + retried.
  • Existing agent-foreground-process.test.ts and pty-shell-utils.test.ts updated with a test-only cache reset in beforeEach (the module cache otherwise carries one mocked-ps case into the next within the TTL).
  • pnpm run typecheck ✅ · oxlint ✅ · oxfmt ✅ · 37 tests pass across the four files.

Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=`
(a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a
shared SSH relay every tracked agent terminal drives it, so concurrent panes
each forked their own `ps` — sustaining up to the per-second inspection cap of
full-table scans for as long as agents are open, pinning idle relay CPU and
amplified by AV process scanning. This is the CPU half of #6288 (PR #6564
covers the memory-leak half).

Memoize the scan behind a single in-flight promise + 500ms TTL shared by the
relay and local main-process call sites. 500ms sits below the active poll's
minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a
snapshot older than it would have scanned itself — same data and freshness,
just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2).

Failures are never cached (in-flight cleared on settle) so a transient `ps`
error retries and the existing best-effort fall-through is preserved. Windows
branches are untouched; no git-provider implications.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new shared module, src/shared/process-table-snapshot.ts, adds createProcessTableSnapshotReader with TTL caching and in-flight request deduplication. It exports getProcessTableSnapshot() and resetProcessTableSnapshotForTests(). agent-foreground-process.ts and pty-shell-utils.ts now read process data through the shared helper. Tests were added for the snapshot reader and for concurrent foreground-process resolution scan volume.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely off-template and omits required Summary, Screenshots, AI Review Report, Security Audit, and Notes sections. Reformat it to the repository template and add the missing sections, including testing checklist items and a cross-platform review summary.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title captures the performance fix and short-TTL deduping, though it understates that the cache is shared beyond relay scans.
Linked Issues check ✅ Passed The change directly addresses #6288 by deduping process-table scans behind a shared TTL cache, reducing repeated CPU-heavy ps invocations.
Out of Scope Changes check ✅ Passed The shared snapshot helper, main-process integration, and regression tests all support the stated performance fix and are in scope.
✨ 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.

nwparker and others added 2 commits June 28, 2026 17:13
Drives the real local foreground-inspection call site under the documented
750ms agent-completion cadence across 6 concurrently-inspecting agent panes
over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=`
full-table scans.

Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection;
the test fails there) and proves the fix (240 inspections -> 40 scans,
0.167/inspection — bounded by poll ticks, not pane count) while every pane
still resolves its foreground agent. Guards against regressing the cache back
to a per-call scan.

Co-authored-by: Orca <[email protected]>

@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

Run ID: 88ab0f5f-bfd7-4700-9883-57680e9ec8ca

📥 Commits

Reviewing files that changed from the base of the PR and between 8c51ab1 and 8b261c6.

📒 Files selected for processing (7)
  • src/main/providers/agent-foreground-process-ps-scan-volume.test.ts
  • src/main/providers/agent-foreground-process.test.ts
  • src/main/providers/agent-foreground-process.ts
  • src/relay/pty-shell-utils.test.ts
  • src/relay/pty-shell-utils.ts
  • src/shared/process-table-snapshot.test.ts
  • src/shared/process-table-snapshot.ts

Comment on lines +86 to +91
const totalInspections = PANE_COUNT * TICKS
// Pre-fix this equals totalInspections (one scan per inspection). With the
// shared cache, concurrent panes within a tick share one scan and the 500ms
// TTL forces a fresh scan each new 750ms tick -> ~one scan per tick.
expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
expect(psScanCount.value).toBeLessThan(totalInspections / 2)

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

Make the scan-count assertion prove per-tick refresh.

psScanCount.value === 1 still satisfies both expectations here, so a reader that never expires its cache across the full 30-second window would pass this regression. Add a lower bound near TICKS so this test actually fails when the default reader stops rescanning once per 750ms tick.

Proposed fix
-    expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
+    expect(psScanCount.value).toBeGreaterThanOrEqual(TICKS - 1)
+    expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
     expect(psScanCount.value).toBeLessThan(totalInspections / 2)
📝 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
const totalInspections = PANE_COUNT * TICKS
// Pre-fix this equals totalInspections (one scan per inspection). With the
// shared cache, concurrent panes within a tick share one scan and the 500ms
// TTL forces a fresh scan each new 750ms tick -> ~one scan per tick.
expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
expect(psScanCount.value).toBeLessThan(totalInspections / 2)
const totalInspections = PANE_COUNT * TICKS
// Pre-fix this equals totalInspections (one scan per inspection). With the
// shared cache, concurrent panes within a tick share one scan and the 500ms
// TTL forces a fresh scan each new 750ms tick -> ~one scan per tick.
expect(psScanCount.value).toBeGreaterThanOrEqual(TICKS - 1)
expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
expect(psScanCount.value).toBeLessThan(totalInspections / 2)

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

🧹 Nitpick comments (1)
src/shared/process-table-snapshot.ts (1)

13-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the inline rationale comment.

The rationale is helpful, but this is well beyond the guideline’s “one or two lines” limit. Please keep the non-obvious reason inline and move the extra cadence math/context to the PR, design doc, or test names.

✂️ Suggested trim
-// Why: 500ms is below the active cadence poll's minimum inter-poll gap (~675ms
-// = 750ms less jitter), so a cadence-driven pane never reuses a snapshot older
-// than it would have scanned itself; a burst of panes polling in the same
-// window collapses from up to 8 scans/sec down to ~2/sec. The faster
-// event-driven follow-up inspections (e.g. the pending-title confirmation,
-// which can re-fire <500ms apart) intentionally accept a <=500ms-stale table:
-// they only confirm the same agent still owns the pane, and process-exit is
-// debounced across repeated samples, so a near-instant cached scan answers
-// identically to a fresh fork.
+// Why: 500ms stays below the poll cadence floor, so panes do not reuse a
+// snapshot older than they would have observed from their own `ps` scan.

As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason".

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: eed4682b-92cf-4140-99d4-547158862a8b

📥 Commits

Reviewing files that changed from the base of the PR and between 8b261c6 and d08f6e2.

📒 Files selected for processing (1)
  • src/shared/process-table-snapshot.ts

@nwparker
nwparker merged commit 06392a4 into main Jun 29, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/fix-6288-relay-ps-scan branch June 29, 2026 00:28
nwparker added a commit that referenced this pull request Jun 29, 2026
…6693)

A terminal pane that has ever run an agent keeps polling the OS process
table for completion detection even while HIDDEN. The cadence (750ms
active / 2000ms idle) did not depend on visibility, so a backgrounded
pane forked a `ps`-scan every ~750ms purely to keep the process-exit
backstop alive — wasting idle CPU, especially on shared SSH relays.

Follow-up to #6288 / PR #6667 (merged), which deduped scans WITHIN a
poll tick via a 500ms-TTL snapshot cache. This attacks the orthogonal
axis: the number of ticks a hidden pane runs.

Hidden panes now poll at a 3s cadence (HIDDEN_POLL_INTERVAL_MS). This is
safe because the process poll is only a BACKSTOP: the primary completion
signals — Orca-managed agent hooks (observeHookStatus, push via IPC) and
xterm title changes (observeTitle) — are event-driven and fire
regardless of poll cadence or visibility. Only a non-hooked agent with
no recognizable completion title relies solely on the poll; for that
case worst-case hidden completion-notification latency rises to ~2x3s
(~6s, repeat-idle-sample) from ~2x750ms.

Visible-pane cadence is unchanged (750ms). Becoming visible re-arms the
slow hidden timer at full cadence immediately, so switching back to a
throttled pane is not sluggish (scheduleNextPoll previously no-oped while
any timer was pending).

Measured inspection calls over 60s: hidden 78->20 (-74%); visible 78->78.

Co-authored-by: Orca <[email protected]>
nwparker added a commit that referenced this pull request Jul 5, 2026
#7384)

* perf(windows): dedupe per-pane process-table scans in agent inspection

Windows agent foreground-process inspection forks a whole-process-table
PowerShell/CIM scan per pane on the same 750ms/2000ms cadence the POSIX path
uses. The POSIX side routes through getProcessTableSnapshot (500ms TTL + single
in-flight, #6288/#6667), collapsing N concurrent panes to ~2 scans/sec. The
Windows path (queryWindowsProcessDescendants) had no such dedup: K concurrent
agent panes forked K powershell.exe cold-starts, each enumerating the ENTIRE
process table then filtering per-pid in JS — ~10-40x heavier than `ps` (a
powershell cold start is ~150-400ms CPU + tens of MB RSS). The degraded/local
PTY provider path calls it with no per-pane throttle at all. This is the
Windows analogue of the idle-CPU churn #6288 fixed for POSIX.

Generalize the existing createProcessTableSnapshotReader factory to be generic
over its scan result (default T = string, so the POSIX path and its test are
byte-identical) and add a Windows singleton reader that caches parsed
WindowsProcessRow[]. queryWindowsProcessDescendants now reads the shared
snapshot and runs its own descendant walk; runWindowsProcessRows throws on total
enumeration failure so the miss is not cached and the prior null-fallback
contract (callers fall through to node-pty's name) is preserved.

Windows scan-volume regression test (mirrors the POSIX #6288 guard) drives
PANE_COUNT concurrent panes over the cadence window and asserts powershell.exe
spawns are bounded by ticks, not pane count, while every pane still resolves its
descendant. Reverting the dedup fails both cases. POSIX snapshot + volume tests
unchanged and green; node/web/cli typecheck clean.

Co-authored-by: Orca <[email protected]>

* test: reset windows process-rows snapshot between agent-foreground cases

The new module-level Windows rows reader caches for 500ms with real
Date.now(), so one case's mocked process table was served to the next
case's assertions (7 CI failures in agent-foreground-process.test.ts).
Mirror the suite's existing POSIX resetProcessTableSnapshotForTests()
with the Windows reset in beforeEach.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
nwparker added a commit that referenced this pull request Jul 6, 2026
…#7518)

getProcessTableSnapshot deduped the ps fork (#6288/#6667) but cached only the
raw stdout string on POSIX, so every concurrent agent pane re-ran parsePsRows
over the identical output within each 500ms TTL window — O(M*P) redundant
tokenization + row allocation. The Windows reader already caches parsed rows;
this makes the POSIX default reader do the same by parsing inside the deduped
scan and returning ProcessTableRow[]. Collapses the duplicate parsePsRows in
the main and relay foreground resolvers into one shared parseProcessTableRows.

Co-authored-by: Orca <[email protected]>
brennanb2025 added a commit that referenced this pull request Jul 25, 2026
…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.
brennanb2025 added a commit that referenced this pull request Jul 25, 2026
…#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 #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, #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.

* 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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#6288) (stablyai#6667)

* perf: dedupe relay process-table scans behind a short-TTL cache (stablyai#6288)

Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=`
(a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a
shared SSH relay every tracked agent terminal drives it, so concurrent panes
each forked their own `ps` — sustaining up to the per-second inspection cap of
full-table scans for as long as agents are open, pinning idle relay CPU and
amplified by AV process scanning. This is the CPU half of stablyai#6288 (PR stablyai#6564
covers the memory-leak half).

Memoize the scan behind a single in-flight promise + 500ms TTL shared by the
relay and local main-process call sites. 500ms sits below the active poll's
minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a
snapshot older than it would have scanned itself — same data and freshness,
just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2).

Failures are never cached (in-flight cleared on settle) so a transient `ps`
error retries and the existing best-effort fall-through is preserved. Windows
branches are untouched; no git-provider implications.

Co-authored-by: Orca <[email protected]>

* test: regression guard for stablyai#6288 ps-scan volume (repro + measurement)

Drives the real local foreground-inspection call site under the documented
750ms agent-completion cadence across 6 concurrently-inspecting agent panes
over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=`
full-table scans.

Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection;
the test fails there) and proves the fix (240 inspections -> 40 scans,
0.167/inspection — bounded by poll ticks, not pane count) while every pane
still resolves its foreground agent. Guards against regressing the cache back
to a per-call scan.

Co-authored-by: Orca <[email protected]>

* docs: clarify 500ms TTL covers cadence floor + tolerated event-driven staleness (stablyai#6288)

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#6693)

A terminal pane that has ever run an agent keeps polling the OS process
table for completion detection even while HIDDEN. The cadence (750ms
active / 2000ms idle) did not depend on visibility, so a backgrounded
pane forked a `ps`-scan every ~750ms purely to keep the process-exit
backstop alive — wasting idle CPU, especially on shared SSH relays.

Follow-up to stablyai#6288 / PR stablyai#6667 (merged), which deduped scans WITHIN a
poll tick via a 500ms-TTL snapshot cache. This attacks the orthogonal
axis: the number of ticks a hidden pane runs.

Hidden panes now poll at a 3s cadence (HIDDEN_POLL_INTERVAL_MS). This is
safe because the process poll is only a BACKSTOP: the primary completion
signals — Orca-managed agent hooks (observeHookStatus, push via IPC) and
xterm title changes (observeTitle) — are event-driven and fire
regardless of poll cadence or visibility. Only a non-hooked agent with
no recognizable completion title relies solely on the poll; for that
case worst-case hidden completion-notification latency rises to ~2x3s
(~6s, repeat-idle-sample) from ~2x750ms.

Visible-pane cadence is unchanged (750ms). Becoming visible re-arms the
slow hidden timer at full cadence immediately, so switching back to a
throttled pane is not sluggish (scheduleNextPoll previously no-oped while
any timer was pending).

Measured inspection calls over 60s: hidden 78->20 (-74%); visible 78->78.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#7384)

* perf(windows): dedupe per-pane process-table scans in agent inspection

Windows agent foreground-process inspection forks a whole-process-table
PowerShell/CIM scan per pane on the same 750ms/2000ms cadence the POSIX path
uses. The POSIX side routes through getProcessTableSnapshot (500ms TTL + single
in-flight, stablyai#6288/stablyai#6667), collapsing N concurrent panes to ~2 scans/sec. The
Windows path (queryWindowsProcessDescendants) had no such dedup: K concurrent
agent panes forked K powershell.exe cold-starts, each enumerating the ENTIRE
process table then filtering per-pid in JS — ~10-40x heavier than `ps` (a
powershell cold start is ~150-400ms CPU + tens of MB RSS). The degraded/local
PTY provider path calls it with no per-pane throttle at all. This is the
Windows analogue of the idle-CPU churn stablyai#6288 fixed for POSIX.

Generalize the existing createProcessTableSnapshotReader factory to be generic
over its scan result (default T = string, so the POSIX path and its test are
byte-identical) and add a Windows singleton reader that caches parsed
WindowsProcessRow[]. queryWindowsProcessDescendants now reads the shared
snapshot and runs its own descendant walk; runWindowsProcessRows throws on total
enumeration failure so the miss is not cached and the prior null-fallback
contract (callers fall through to node-pty's name) is preserved.

Windows scan-volume regression test (mirrors the POSIX stablyai#6288 guard) drives
PANE_COUNT concurrent panes over the cadence window and asserts powershell.exe
spawns are bounded by ticks, not pane count, while every pane still resolves its
descendant. Reverting the dedup fails both cases. POSIX snapshot + volume tests
unchanged and green; node/web/cli typecheck clean.

Co-authored-by: Orca <[email protected]>

* test: reset windows process-rows snapshot between agent-foreground cases

The new module-level Windows rows reader caches for 500ms with real
Date.now(), so one case's mocked process table was served to the next
case's assertions (7 CI failures in agent-foreground-process.test.ts).
Mirror the suite's existing POSIX resetProcessTableSnapshotForTests()
with the Windows reset in beforeEach.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#7518)

getProcessTableSnapshot deduped the ps fork (stablyai#6288/stablyai#6667) but cached only the
raw stdout string on POSIX, so every concurrent agent pane re-ran parsePsRows
over the identical output within each 500ms TTL window — O(M*P) redundant
tokenization + row allocation. The Windows reader already caches parsed rows;
this makes the POSIX default reader do the same by parsing inside the deduped
scan and returning ProcessTableRow[]. Collapses the duplicate parsePsRows in
the main and relay foreground resolvers into one shared parseProcessTableRows.

Co-authored-by: Orca <[email protected]>
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.

[Bug]: Orca remote server memory usage and CPU usage are too high

1 participant