Repository navigation
fix(process-table): fail a short ps capture loudly, and stop a resume spending 49 of them - #18166
Conversation
📝 WalkthroughWalkthroughThe structured TUI process identity reader now uses adaptive polling with a 1,000 ms fast-poll window and a 500 ms maximum delay. Tests cover timeout duration, capture counts, and child detection latency. The process-table snapshot module now uses a 32 MB buffer ceiling and rejects truncated or empty captures with explicit errors. Tests cover large tables, buffer overflow, truncation, and empty output. Merge Risk: 🟡 Moderate · up to The change improves process discovery reliability and reduces repeated polling, but the current implementation can still misclassify header-only captures as empty tables and reject complete captures at the exact size limit, causing incorrect process-status results. These bounded correctness issues should be fixed or explicitly accepted before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives detailed ELI5, change rationale, implementation scope, reliability considerations, platform coverage, measurements, and test results. However, it omits the required Linked Issue, Visual Proof or an explicit N/A explanation, Agent skill upstream boundary, and checklist sections. Resolution Add a linked issue using the required Fixes # format. Add the Visual Proof section with N/A and a reason if no visual or interaction change exists. Complete the Agent skill upstream boundary and Checklist sections, and state AI disclosure details when applicable.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 3b1b164c-564a-4149-a89d-0dda174ad31b
📒 Files selected for processing (4)
src/main/runtime/structured-tui-process-identity.test.tssrc/main/runtime/structured-tui-process-identity.tssrc/shared/process-table-snapshot.test.tssrc/shared/process-table-snapshot.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| * evidence and must fail loudly on both views. | ||
| */ | ||
| function assertWholeCapture(stdout: string): string { | ||
| if (Buffer.byteLength(stdout, 'utf-8') >= PS_MAX_BUFFER_BYTES) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Confirm the declared Node runtime accepts stdout exactly equal to maxBuffer.
fd -HI '(\.nvmrc|\.node-version|package\.json|\.tool-versions)$' . -x sh -c \
'echo "--- $1"; sed -n "1,120p" "$1"' sh {}
node <<'NODE'
const { execFile } = require('node:child_process')
const limit = 32 * 1024 * 1024
execFile(
process.execPath,
['-e', `process.stdout.write('x'.repeat(${limit}))`],
{ encoding: 'utf-8', maxBuffer: limit },
(error, stdout) => {
console.log({
node: process.version,
errorCode: error?.code ?? null,
stdoutBytes: Buffer.byteLength(stdout ?? '', 'utf-8')
})
process.exit(error ? 1 : 0)
}
)
NODERepository: stablyai/orca
Length of output: 19858
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- process-table-snapshot.ts relevant definitions and callers'
rg -n -A18 -B12 'PS_MAX_BUFFER_BYTES|assertWholeCapture|ERR_CHILD_PROCESS_STDIO_MAXBUFFER|execFile' src/shared/process-table-snapshot.ts
printf '%s\n' '--- process-table-snapshot.test.ts exact-limit test'
sed -n '535,585p' src/shared/process-table-snapshot.test.tsRepository: stablyai/orca
Length of output: 7210
Do not reject complete captures at the exact buffer limit.
execFile allows stdout whose UTF-8 size equals PS_MAX_BUFFER_BYTES, but assertWholeCapture classifies it as capture_truncated. Remove this size check. Keep the existing ERR_CHILD_PROCESS_STDIO_MAXBUFFER mapping for actual overflow, and add a test for an exact-limit capture.
🧰 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 { execFile as execFileCb } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
process-table-snapshot.ts— 32 MBmaxBuffer+ whole-capture integrity guard. The POSIXpscapture now sets an explicitmaxBuffer(matching the siblingpty-descendant-termination.tsreader) and addsassertWholeCapture, which rejects a capture that reaches the buffer ceiling (capture_truncated) or carries no rows (empty_capture).ERR_CHILD_PROCESS_STDIO_MAXBUFFERis renamed into the same domain vocabulary. This closes the "silently short table" path (lenient parser drops an unparseable tail → false "no agent") at the capture boundary so no future exec wrapper can reopen it.structured-tui-process-identity.ts— adaptive poll backoff. The poll holds the caller's interval for the first 1 s, then doubles per poll to a 500 ms cap, cutting the worst-case capture count per identification from ~49 to ~20. The first-second detection latency is byte-identical; past it, added latency is bounded by one interval.getFreshProcessTableSnapshot()is retained, keeping the "root absent ⇒ root gone" freshness guarantee intact.- Tests — six red-on-
mainregression guards. The busy-host overflow, truncated/empty capture, and buffer-ceiling-rename cases all fail against the pre-change behavior and pass now; the poll-cost case assertscaptures ≤ 20deterministically on a simulated clock.
The verdict vocabulary (live / unverifiable / exited) is untouched and no new synonym was introduced. Lenient-view consumers (agent-foreground-process.ts, pty-shell-utils.ts) already wrap reads in try/catch and degrade to available:false/null on the new rejections; the relay's pty-handler.listProcesses maps an unreadable capture to table_unreadable evidence. Windows is unaffected (its Toolhelp32 reader forks no child). I verified the six tests are meaningful rather than tautological: each would still pass only because the fix landed, and none use a loose >=/truthiness assertion where an exact one belongs.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…me spending 49 of them
The POSIX process-table capture ran `execFile('ps', ...)` with no `maxBuffer`,
inheriting Node's 1MB default. Measured at 1,460 processes the capture is 326KB
with a 5,116-char longest row — ~3x headroom, which a busy host clears.
Two separate defects follow, fixed here:
1. `parseProcessTableRows` drops unparseable lines, so any short capture reads
as a COMPLETE table whose missing processes simply are not running. Verified:
a capture cut at 4KB parses to 59 of 1,463 rows, and an empty capture parses
to `[]`, both with no error — and `resolveAgentForegroundProcessWithAvailability`
then answers `available: true`. That is the `unverifiable` -> `exited` collapse
the execution boundary forbids. The capture now rejects with
`ProcessTableCaptureError` on a ceiling-length or row-less capture, so both the
lenient and strict views fail loudly and callers report unavailable.
2. `maxBuffer` is now an explicit 32MB, matching the sibling reader in
`pty-descendant-termination.ts` and its stated reasoning. Without it a 4,000-
process host fails EVERY capture, degrading the whole subsystem permanently.
Separately, `readStructuredTuiProcessIdentity` polled a fresh whole-machine `ps`
every 50ms for up to 5s. Each capture costs ~0.065 CPU-s, and the 5s ceiling is
only reached when the child never appears — where the tight interval buys
nothing. The interval now holds at 50ms for the first second, then doubles to a
500ms cap. Identification latency is unchanged for any child appearing inside
that window, and the 5s ceiling is unchanged.
31547e1 to
df870fd
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
|
Readiness review (batch G). Merging. Both things I was asked to be strict about check out. The new guards cannot manufacture a false "no agent." I traced every consumer of the capture:
The The fast path is genuinely byte-identical, and the guard proving it is not vacuous. Setting So the 0/200/500/900 ms rows in your table are held by a real assertion. Also confirmed All five claimed regression tests reproduce red on Windows is unaffected as claimed — Rebased onto main; 6,994 tests pass across |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 4cac7dcf-ace1-4f02-8c4a-fe0ca5240e25
📒 Files selected for processing (4)
src/main/runtime/structured-tui-process-identity.test.tssrc/main/runtime/structured-tui-process-identity.tssrc/shared/process-table-snapshot.test.tssrc/shared/process-table-snapshot.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/runtime/structured-tui-process-identity.ts
- src/shared/process-table-snapshot.test.ts
- src/main/runtime/structured-tui-process-identity.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| if (!/\S/.test(stdout)) { | ||
| throw new ProcessTableCaptureError('empty_capture') | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 \
'\.lenient\s*\(\)|ProcessTableCapture|parseProcessTableRows|assertWholeCapture' \
src --glob '*.ts'
rg -n -C 8 \
'empty_capture|header-only|assertWholeCapture' \
src/shared/process-table-snapshot.test.ts src --glob '*.ts'Repository: stablyai/orca
Length of output: 50369
Reject captures with no parseable process rows.
A header-only or otherwise non-matching stdout can pass assertWholeCapture because it contains non-whitespace text. The lenient path then calls parseProcessTableRows and returns [], while only the strict path rejects zero rows. Reject the capture when the lenient parser returns no rows, and add a header-only regression test.
🧰 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 { execFile as execFileCb } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
…wn module (#18246) `src/shared/process-table-snapshot.ts` is 308 code lines against the 300 cap for `**/*.ts`, so `static analysis` is red on `main` and every open PR inherits it. Neither PR that grew the file crossed the cap alone. #18151 took it to 427 raw lines; #18166 added ~35 more. #18166's branch predated #18151, so the head CI linted was 428 raw lines and passed, while the squash onto main is 463 -> 308 code lines. The gate lints the PR head, not the merge result, so nothing linted the sum until it was on main. Pure move, no behaviour change: the generic index machinery (ProcessIdentityRow, ProcessTableIndexOf, buildProcessTableIndex, collectDescendantsFromIndex, lookupProcessTableIndex, getProcessTableIndex and its WeakMap) moves to process-table-index.ts. `ProcessTableIndex` and `scoreForegroundCandidateRow` stay behind because they need `ProcessTableRow`, which keeps the new module free of any import back and so introduces no cycle.
…me spending 49 of them (stablyai#18166) The POSIX process-table capture ran `execFile('ps', ...)` with no `maxBuffer`, inheriting Node's 1MB default. Measured at 1,460 processes the capture is 326KB with a 5,116-char longest row — ~3x headroom, which a busy host clears. Two separate defects follow, fixed here: 1. `parseProcessTableRows` drops unparseable lines, so any short capture reads as a COMPLETE table whose missing processes simply are not running. Verified: a capture cut at 4KB parses to 59 of 1,463 rows, and an empty capture parses to `[]`, both with no error — and `resolveAgentForegroundProcessWithAvailability` then answers `available: true`. That is the `unverifiable` -> `exited` collapse the execution boundary forbids. The capture now rejects with `ProcessTableCaptureError` on a ceiling-length or row-less capture, so both the lenient and strict views fail loudly and callers report unavailable. 2. `maxBuffer` is now an explicit 32MB, matching the sibling reader in `pty-descendant-termination.ts` and its stated reasoning. Without it a 4,000- process host fails EVERY capture, degrading the whole subsystem permanently. Separately, `readStructuredTuiProcessIdentity` polled a fresh whole-machine `ps` every 50ms for up to 5s. Each capture costs ~0.065 CPU-s, and the 5s ceiling is only reached when the child never appears — where the tight interval buys nothing. The interval now holds at 50ms for the first second, then doubles to a 500ms cap. Identification latency is unchanged for any child appearing inside that window, and the 5s ceiling is unchanged.
…wn module (stablyai#18246) `src/shared/process-table-snapshot.ts` is 308 code lines against the 300 cap for `**/*.ts`, so `static analysis` is red on `main` and every open PR inherits it. Neither PR that grew the file crossed the cap alone. stablyai#18151 took it to 427 raw lines; stablyai#18166 added ~35 more. stablyai#18166's branch predated stablyai#18151, so the head CI linted was 428 raw lines and passed, while the squash onto main is 463 -> 308 code lines. The gate lints the PR head, not the merge result, so nothing linted the sum until it was on main. Pure move, no behaviour change: the generic index machinery (ProcessIdentityRow, ProcessTableIndexOf, buildProcessTableIndex, collectDescendantsFromIndex, lookupProcessTableIndex, getProcessTableIndex and its WeakMap) moves to process-table-index.ts. `ProcessTableIndex` and `scoreForegroundCandidateRow` stay behind because they need `ProcessTableRow`, which keeps the new module free of any import back and so introduces no cycle.

ELI5
To answer "is the agent still running in this terminal?", Orca asks the OS for the list of every running program and reads it into a buffer. That buffer had no size set, so it got the default 1 MB — and on my machine the list is already 326 KB. On a busier machine it overflows. When it overflows, Orca does not say "I couldn't read the list"; it quietly acts as if the programs it never read simply are not running. That is how "I can't tell" turns into "nothing is there" — the one conversion the execution-boundary rule forbids.
Separately, resuming an agent terminal reads that entire program list over and over — up to 49 times in five seconds — waiting for the agent's process to show up. The first second of that is doing real work. The remaining four seconds are re-asking a question that has already answered "no" forty times.
What changed
Fix 1 —
src/shared/process-table-snapshot.tsmaxBufferof 32 MB, matching the sibling reader insrc/main/pty-descendant-termination.tsand its stated reasoning ("truncation would silently drop descendants from the snapshot").ProcessTableCaptureError(capture_truncated/empty_capture) instead of being parsed. AERR_CHILD_PROCESS_STDIO_MAXBUFFERrejection is renamed into the same domain vocabulary.Fix 2 —
src/main/runtime/structured-tui-process-identity.tsgetFreshProcessTableSnapshot()is retained — the freshness guarantee is what makes "root absent ⇒ root gone" sound, so it was not weakened to the TTL-cached reader.Correcting the reported premise for Fix 1
The investigation that motivated this said overflow produces "a partial process table presented as a complete one". Measured, that is not what
execFiledoes. PromisifiedexecFilerejects on overflow (ERR_CHILD_PROCESS_STDIO_MAXBUFFER), and every consumer already handles a rejection correctly as unavailable. So the reported false-negative is not reachable through the buffer ceiling today.The real defects are the two adjacent ones, and both are demonstrated by failing tests:
[]with no error.resolveAgentForegroundProcessWithAvailabilitythen answersavailable: trueon that empty table. So the "silently short table" shape is genuinely present — it just needed a non-execFileroute to reach it. This PR closes it at the capture boundary so no future exec wrapper can reopen it.unverifiable.Both are fixed; the verdict vocabulary (
live/unverifiable/exited) is unchanged and no new synonym was introduced.Measurements
All on macOS, 1,460 processes, Orca's exact
PS_ARGS.Output size vs buffer limit
psstdoutpschild)A 4,000-process host with ordinary argv produces ~1.14 MB and fails outright on the old limit; the regression test uses exactly that table.
Captures per identification attempt (Fix 2)
Simulated clock, 55 ms measured capture cost, 5 s ceiling:
CPU saved per resume
Note the corrected worst case is 49 captures, not 100: each capture costs ~55 ms of wall time on top of the 50 ms sleep, so a 5 s window fits ~48 iterations, not 100.
Negative user-facing trade-offs
None.
codex/claudechild in well under that, and the capture itself already imposes a ~105 ms effective granularity, so the first second was never finer-grained than the fix leaves it.tui-idle. There is no interactive surface on this path.PS_ARGS, the 500 ms TTL, and every cadence tier are untouched.unavailable.Reliability contract
process-table.capture-completeness— a process-table snapshot is either whole or unreadable; it is never partially delivered as complete. Andagent-session.foreground-availability— an unreadable capture yieldsavailable: false, never a positive claim about what is running.getProcessTableSnapshot()rejects rather than resolving with a short array; the busy-host table parses to all 4,000 rows. Both fail onmain.src/main/windows/windows-process-table.tssupplies its ownrunPstocreateProcessTableSnapshotReadervia a Toolhelp32 snapshot, forks no child and has no buffer ceiling;readStructuredTuiProcessIdentity'swin32branch usesqueryWindowsProcessRowsFreshand shares only the poll cadence, which changes identically on all three platforms. SSH/relay covered — the relay imports the same shared reader, andpty-handler.listProcessesalready maps a capture failure totable_unreadableevidence.execFilemock that reproduces Node's exact buffering semantics rather than by a genuinely 4,000-process host.Tests
Six new regression tests, all verified red on
main:src/shared/process-table-snapshot.test.tsreads a busy host whose table overflows execFile 1MB default— red: "promise rejected 'stdout maxBuffer length exceeded' instead of resolving"reports a truncated capture as unreadable rather than a silently short table— red: "promise resolved [200 rows] instead of rejecting"names a buffer-ceiling rejection as truncation on both views— redreports an empty capture as unreadable rather than an empty process table— red: "promise resolved [] instead of rejecting"src/main/runtime/structured-tui-process-identity.test.tsdoes not spend a hundred ps captures on an identification that never resolves— red: "expected 49 to be less than or equal to 20"keeps identification latency identical while a child can still plausibly appear— passes both before and after by design: it is the guard proving the fast path did not move.Verification
pnpm tc— cleannpx oxlint <changed files>— cleannpx vitest run --config config/vitest.config.ts src/shared src/main/runtime src/main/providers— 13,478 passed, plus the relay snapshot consumers (pty-shell-utils,pty-handler-inventory-process-evidence) for 13,511 passed total