Skip to content

perf(terminal): bound the in-process macOS process table's blocking calls and ps fallbacks (#31783) - #36282

Merged
nwparker merged 11 commits into
mainfrom
fix/libproc-followups-31783
Oct 30, 2026
Merged

nwparker merged 11 commits into
mainfrom
fix/libproc-followups-31783

Conversation

@nwparker

@nwparker nwparker commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​872 $\color{#cf222e}{\Huge{\mathbf{−}}}$​25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​847
Prod 24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​899 $\color{#cf222e}{\Huge{\mathbf{−}}}$​247 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​652

Follow-up to #35987 (in-process libproc/sysctl process table for #31783), from its post-merge deep reviews. The diagnosis by @thefrikidude in #35257 informed the original change.

  • cwd/executable path off the event loop: readProcessCwd/readProcessPath run on a libuv worker, at most two outstanding, 250ms each, then fall back to lsof -b. lsof keeps one live child per pid. Shell readiness uses runProcess, which gives up on an unkillable lsof. A dead NFS/SMB/FUSE mount no longer freezes the daemon.
  • Worker-thread safe: node-pty's mac target builds with NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS, so terminating a worker mid-read no longer aborts the process.
  • Unreadable argv: prints (comm) like ps. A withheld foreground makes evidence and foreground resolution unverifiable (argv_unreadable). An unreadable shell, such as a root su, blocks launch typing.
  • Argv recovery:
    • setuid ps runs only for other users' processes (rows carry the euid), or for a selected terminal's foreground after exec su.
    • Recovery is coalesced per process and runs on its own fork budget.
    • Recovered argv is reused for at most 1.5s per pid/start/comm, timed from when its ps started. Evidence is aged by its oldest recovered argv, in whole milliseconds.
    • Only a real ps answer is remembered, and a failure waits 5s.
  • Remote write guard (defence in depth):
    • Live evidence naming the launched agent proves it if the capture began no more than one 500ms snapshot TTL before the read was asked. Up to two TTLs, a fresh foreground read through confirmForegroundProcess decides instead (agent, shell, or unknown).
    • Evidence that saw an agent row but couldn't fence it (two rows of one group, tmux, a missing start time) is completed only by that fresh read, never by the tracker's 1s display cache. The read must name the launched agent. For an ambiguous group it may also be node for an npm-installed agent, as older relays report npm Codex.
    • Every other unverifiable reason refuses, including unknown ones.
    • The evidence builder names same-agent rows directly (npm Codex, Gemini relaunching itself).
  • Fair, prioritised fork budget: while the reader is down (breaker open, a rejecting addon that backs off 1–30s, or a held naming pass), ps runs through one budget: a burst of 4, then 1/s. Interactive and fresh reads go first, then display polls, FIFO per invocation. A ps started before a request never answers it. Signalling paths keep their own full-timeout ps.
  • Old addon: a perf(terminal): read the macOS process table in process instead of forking setuid ps #35987 pty.node keeps the in-process table, with lsof for cwd/path and a one-time warning.

Measured:

  • Busy pane: 24 → 0 ps/min.
  • Root su pane, 13 pollers: 30 ps/min. Fresh-read p50 51ms; strict evidence age p50 752ms, max 1,508ms.
  • 13 pollers with the reader down: 1,040 → about 64 ps/min, with every stream served.
  • Launch-paste reads during a 20-stream poll storm: 12 of 12 served.
  • Naming hold: 400 → 63 ps/min.
  • Capture ages with 13 pollers: max 528ms; 0 of 767 over the 1s bound.
  • Parity: 1,837 rows matched /bin/ps. A timer-driven worker-terminate smoke test survives.

Reachability: since the SSH provider was removed (#27499), the remote (host.remote) write-guard path has no production caller. The registry dispatches only local providers, and paired runtimes evaluate guards locally. The local daemon answers confirmForegroundProcess. For a provider without it, the production controller returns null, which reads as unknown and fails safe. The remote-guard hardening above is defence in depth for any future remote provider.

Remaining legacy path: a controller that can't read the foreground fresh, or a remote host that sends no foreground evidence, still uses the possibly cached foreground name.

No daemon protocol bump: the wire format is unchanged. Linux and Windows are untouched.

Review: adversarially reviewed over 10 rounds by an Opus sub-agent and Codex (gpt-6.1-sol, xhigh), plus deep post-merge TCC reviews of #35987. Both final verdicts were MERGE. TCC verdict: no TCC risk. The only filesystem-touching path lookup was replaced with (comm).

Follow-up: the relay evidence builder could dedupe same-agent rows for older relays too.

…lls and ps fallbacks (#31783)

Follow-up to #35987 from its post-merge reviews.

- cwd and executable path: node-pty's readProcessCwd/readProcessPath now run
  PROC_PIDVNODEPATHINFO and proc_pidpath on a libuv worker (the synchronous
  exports are gone, so an older pty.node falls back to ps/lsof). JS caps them at
  two outstanding lookups and 250ms; a wedged mount or a full cap answers from
  lsof -b, which never stats, so a dead NFS/SMB/FUSE mount cannot freeze the
  daemon's event loop or take the whole pool.
- Unreadable argv prints "(comm)", as ps does, instead of a proc_pidpath lookup
  under Orca's credentials on the table worker.
- The table exports each row's euid. Argv recovery runs setuid ps only for
  another user's processes, never for our own mid-exec or exiting ones (or
  SIDL/exiting rows), which ps cannot read either: a pane looping short
  commands forked ps on ~15% of full reads, now none.
- Recovery is coalesced per process across concurrent readers and a failed
  recovery waits 5s before costing another ps. The cache keys on comm and start
  time.
- Full-table and shell-foreground captures, which feed strict evidence with
  the capture's age, take only argv ps read after their request; display
  readers keep the 30s cache.
- While the reader is down (stalled-pool breaker open, or a rejecting addon,
  which now backs off 1s..30s), runPsInProcess runs /bin/ps itself through one
  shared budget: identical invocations share a run, a burst of 4 forks then one
  a second, and a run spawned before a request never answers it. Descendant
  teardown and foreground-group signalling keep their own full-timeout ps
  (callerRunsPs). 13 pollers at 750ms: 1,040 ps/min before, 63 after.

No daemon protocol bump: the wire format is unchanged, and each daemon loads
JS and pty.node from the same runtime copy.
…closed and share one fair fork budget (#31783)

Review follow-ups to the previous commit.

- Native: every libproc AsyncWorker derives from OrcaPromiseWorker, which skips
  JS completion once an env cleanup hook marks the env closing and swallows a
  Napi::Error thrown mid-teardown. Terminating a worker_thread with cwd or table
  reads in flight aborted the process; 200 terminates each now survive.
- (comm) in a terminal's foreground group (argv neither reader recovered, e.g.
  a root `su`) judges 'unknown', never 'agent', so the launch line is not typed
  into it.
- Fresh argv only for getFreshSnapshot captures; the 500ms TTL readers keep the
  30s cache. Argv recovery runs through its own fork budget (2, then one per
  2s). Root `su` pane, 13 pollers at 750ms: TTL 79 -> 2 ps/min, fresh 158 -> 31.
- The fork budget serves invocations in FIFO turns, grouping each one's waiters
  onto one run. 13 streams: served 80,42,1,1,2,0x8 -> 10-12 each.
- Forced subprocess captures (a held naming pass) go through the fallback
  budget: 5 readers, 400 direct ps/min -> 63, 395 of 400 captures served.
- A failed recovery is retried 5s after ps gave up, not after it started.
- Tests pin Orca's euid instead of reading the runner's and assuming root is 0.
- process-cwd keeps one lsof per pid until it exits, so a dead mount no longer
  leaks one per poll; shell readiness reads the exe path through runProcess,
  which gives up on an lsof that ignores SIGTERM.
- A #35987 pty.node (table reader, no async path reads) keeps the in-process
  table; cwd/path use lsof, with a one-time warning.
- captureProcessTable moves to process-table-ps-capture.ts.
…gv for at most 2s (#31783)

Round-2 review follow-ups.

- Worker teardown: drop OrcaPromiseWorker and its env flag (Node drains the
  pool before cleanup hooks, so it never fired). node-pty's mac pty target now
  builds with NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS, which covers both the
  call-in and completion paths. The smoke test now calls the reads from a
  timer while terminating: the previous build aborted 2 of 3 runs, this one
  survives 3/3 x 100. pty.cc is back to the first follow-up's exact content.
- A foreground process whose argv ps withheld (`(comm)`: another user's,
  exiting, or a recovery the budget skipped) makes the batch resolver, and so
  host-stamped evidence, `argv_unreadable`/unverifiable rather than live with no
  agent; agent-foreground resolution reports it unavailable.
- judgeTerminalForeground fails closed only for an unreadable shell (`(bash)`
  from a root `su`), not our own exiting `(git)`.
- Recovered argv is reused for at most 2s per identity (pid, start, comm) for
  every reader (the next commit ages evidence by it), and
  fresh reads no longer queue behind the recovery budget. Root `su` pane, 13
  fresh pollers: p50 2,989ms -> 53ms, 31 -> 26 ps/min (TTL reader 1 -> 26).
- The fork budgets serve interactive and fresh readers before display polls
  (cheap and TTL snapshot captures), FIFO within each. 20 display streams plus
  a 3s launch-paste read every 5s: 0/12 -> 12/12 served, polls 4-7 each.
- On a selected terminal, the foreground group's argv is recovered even with no
  process of ours left (`exec su`); the root login is not.
- Budgeted captures keep the 32 MiB output ceiling.
Round-3 review follow-ups.

- Recovered argv carried no read time, so a capture reusing it (cached, or a
  recovery still in flight) stamped its own capture time over argv up to 2s
  older, and the remote write guard could take a same-comm re-exec for the
  agent. Rows now carry when ps read their recovered argv; runPsInProcess
  reports the oldest through onArgvReadAt, and the snapshot reader stamps
  capturedAtMs at that input, so capturedAgeMs is the age of the oldest input
  and consumers' own freshness checks (the write guard's 500ms) decide. A
  recovery begun more than 2s before a reader asked no longer answers it, and
  an older recovery finishing late cannot replace a newer one.
- resolveSpawnFileForegroundFromRows reports a withheld `(node)` foreground
  unavailable.
- One budget queue entry per invocation: an interactive request promotes a
  queued poll's, a poll joins an interactive one.
- parseShellForegroundRows gets its JSDoc back.
…nteger, under-2s argv ages (#31783)

Round-4 review follow-ups.

- When the relay's evidence declines a write (stale, unverifiable, another
  agent), its foreground name may still prove the shell but no longer proves
  the agent: that name can be the tracker's 1s display cache, e.g. `claude`
  cached just before Claude exited to a root shell under su. Relays that send
  no evidence keep the name as before.
- Snapshot ages round up to whole milliseconds; the wire rejects fractions
  from the monotonic-to-wall conversion.
- Recovered argv is reused for at most 1.5s, so reuse plus the 500ms snapshot
  cache stays under the 2s freshness gate; reuse ages from when that ps
  spawned, not from the wait for its fork token, and only an answer is
  remembered (a timed-out or withheld run proves nothing). Fork budget
  unchanged. Root su pane, 13 pollers: 30 ps/min; fresh p50 51ms; strict
  evidence age p50 752ms, max 1,508ms.
…fiable evidence (#31783)

The previous commit refused the name fallback whenever the relay sent any
evidence, so `unverifiable` evidence for structural reasons also blocked
writes: npm Codex (node codex.js spawning native codex) and Gemini (relaunching
itself) put two agent rows in the foreground group (ambiguous_foreground_group),
and remote tmux reads multiplexer_boundary. On SSH POSIX hosts that dropped
launch prompts and failed worker briefs, conversation send/cancel and
automations with agent_not_in_foreground.

The name now cannot authorize only when the evidence saw the group (`live`:
stale, or no agent in it, as in the cached-`claude`-over-root-shell repro) or
withheld a foreground argv (`argv_unreadable`, possibly a root `su` shell).
Other unverifiable reasons keep the name fallback, as before this branch.
…idence (#31783)

The SSH name fallback still let a stale or cached name authorize a write under
any unverifiable reason but argv_unreadable: ps EAGAIN (process_table_unreadable)
after the tracker cached `claude` over a root bash, anchor_missing,
tty_boundary (`sudo -i` with use_pty, a root shell on a new pty), or a 1.5s-old
ambiguous capture.

- The name now completes evidence only when it is fresh (within the guard's
  500ms bound), its reason is one that saw an agent row
  (ambiguous_foreground_group, multiplexer_boundary,
  candidate_start_time_missing), and the name is the launched agent. Every other
  reason, including ones this build does not know, reads unknown. Relays that
  send no evidence keep the name, for mixed versions.
- The relay's evidence names one agent that holds two rows of the group (npm
  Codex: node codex.js spawning native codex; Gemini relaunching itself), so a
  new relay proves them live even when its name is `node`. Two different agents
  stay ambiguous. No wire change.
… relays' npm Codex (#31783)

- Name completion compared the capture's start with the read's start, so a
  slow response made old evidence look fresh: a capture 1,500ms old arriving
  after 1,100ms passed. It now uses the host-reported capturedAgeMs against
  the 500ms bound, which latency cannot shrink. Live evidence keeps its
  capture-start rule.
- Relays before same-agent dedupe report npm Codex (node wrapper plus native
  binary) as ambiguous_foreground_group and name it `node`. For that reason
  only, `node` now completes the evidence when the launched agent is
  npm-installed per the node entrypoint tables; other agents and reasons stay
  fail-closed.
…31783)

The 500ms bound refused ~9.5% of tmux name completions on a host with 13
pollers (cached snapshot up to one 500ms TTL old plus ~30ms capture, max
528ms), and a refusal drops the launch prompt or throws with no retry. The
bound is now 2 x PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS (1s), still on the
host-reported age: 0 of 767 reads exceed it, the delayed 1,500ms repro still
refuses, and the cached-name hazard (the tracker's ~1s display cache) is no
wider.
…display cache (#31783)

With the 1s bound, a capture at 0-528ms, `codex` cached at 100ms, Codex
exiting at 101ms and the guard at 999ms still let the cached name authorize a
write over the bash that replaced it.

- Name completion (structural reasons, host age within 2x the snapshot TTL)
  now asks confirmForegroundProcess, which reads the foreground now (a fresh
  scan, or node-pty's raw process name) rather than the tracker's 1s display
  cache; a null answer reads unknown. No new wire surface: the local daemon answers
  confirmForegroundProcess, paired runtimes evaluate guards locally, and the
  production controller returns null (read as unknown, failing safe) when a
  provider lacks it. Controllers without the method, and relays sending no
  evidence, keep the cached name as the legacy path.
- Live evidence also accepts a host-reported age within 2x the TTL, so a real
  agent behind a 500-528ms cached snapshot on a fast link is no longer
  refused; a capture begun after the read was asked still counts, and
  5,000ms-old evidence still refuses.
… a fresh read (#31783)

Accepting live evidence up to 2x the TTL reopened the window the previous
commit closed for name completion: a capture at 0-528ms, the agent exiting at
~529ms, and at 999ms `live claude` still read as agent over a bash.

Live evidence begun no more than one TTL before the read was asked (so any
host age within one TTL, however long ps took) still answers alone. Between
that and 2x the TTL, confirmForegroundProcess reads the foreground now: the
launched agent proves it, a shell reads shell, anything else unknown.
Controllers without that read fall through and refuse, as before.

Reachability: the remote (host.remote) write-guard path has no production
caller since the SSH provider's removal (#27499); the registry dispatches only
local providers and paired runtimes evaluate guards locally. This is defence
in depth for any future remote provider.
@coderabbitai

coderabbitai Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 33672115-6854-41b3-adda-b885e27274c0
Commits

Reviewing files that changed from the base of the PR and between 6361640 and 14aa261.

Files ignored due to path filters: 1
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing: 36
  • config/patches/[email protected]
  • config/process-host-direct-import-baseline.txt
  • src/main/daemon/pty-subprocess/spawn-file-foreground-process.ts
  • src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts
  • src/main/daemon/terminal-descendant-shutdown-libproc.test.ts
  • src/main/providers/agent-foreground-process-batch.ts
  • src/main/providers/agent-foreground-process-remote-evidence.test.ts
  • src/main/providers/agent-foreground-process-remote-evidence.ts
  • src/main/providers/agent-foreground-process.ts
  • src/main/providers/process-cwd.test.ts
  • src/main/providers/process-cwd.ts
  • src/main/pty-descendant-fresh-table.ts
  • src/main/pty-descendant-termination-libproc.test.ts
  • src/main/pty/posix-pty-foreground-group-libproc.test.ts
  • src/main/pty/posix-pty-foreground-group.ts
  • src/main/runtime/launched-agent-foreground.test.ts
  • src/main/runtime/launched-agent-foreground.ts
  • src/main/runtime/terminal-foreground-group.test.ts
  • src/main/runtime/terminal-foreground-group.ts
  • src/shared/agent-process-recognition.ts
  • src/shared/cheap-process-table-snapshot-reader.ts
  • src/shared/darwin-terminal-naming-single-flight.test.ts
  • src/shared/libproc-addon-worker-teardown.test.ts
  • src/shared/libproc-addon.ts
  • src/shared/libproc-argv-completion.ts
  • src/shared/libproc-native-reads.ts
  • src/shared/libproc-process-table.test.ts
  • src/shared/libproc-process-table.ts
  • src/shared/libproc-ps-fallback.test.ts
  • src/shared/libproc-ps-fallback.ts
  • src/shared/libproc-ps-format.ts
  • src/shared/process-table-ps-capture.ts
  • src/shared/process-table-snapshot-reader.ts
  • src/shared/process-table-snapshot.test.ts
  • src/shared/process-table-snapshot.ts
  • src/shared/shell-process-readiness.ts

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

Walkthrough

The change adds asynchronous macOS process-table and path reads, shared budgeted ps fallbacks, and deadline-aware argv recovery. It updates process-table capture timing and foreground-process classification, including handling for unreadable argv and remote evidence. Cwd and executable-path lookups now use asynchronous native reads with lsof fallbacks.

Priority: Normal

Merge Risk: Minimal · up to 14aa2

This change moves macOS process-table, cwd and executable-path reads off the event loop. It also bounds the ps fallbacks and makes unreadable argv unverifiable, so write guards fail closed. No concrete merge-blocking defect was found in the supplied context.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Description check Warning The description provides detailed technical context, rationale, measurements, and review notes, but it does not follow the required template. It omits the required headings and checklist items, lacks … Reformat the description using all required template sections. Add an actual linked issue with a Fixes # reference, state Visual Proof as N/A with a reason if applicable, document automated and manual testing with platforms and commands, co…
Docstring Coverage Warning Docstring coverage is 48.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: bounding blocking macOS process-table calls and ps fallbacks.
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.
Full details: Description check

Explanation

The description provides detailed technical context, rationale, measurements, and review notes, but it does not follow the required template. It omits the required headings and checklist items, lacks a proper Linked Issue entry using Fixes #, and does not state visual proof as N/A or clearly document testing platforms and commands.

Resolution

Reformat the description using all required template sections. Add an actual linked issue with a Fixes # reference, state Visual Proof as N/A with a reason if applicable, document automated and manual testing with platforms and commands, complete the AI Disclosure and Agent skill upstream boundary sections, and complete the checklist.

Full details: Docstring Coverage

Explanation

Docstring coverage is 48.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 41 functions across 34 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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
nwparker merged commit 756d623 into main Oct 30, 2026
87 checks passed
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