Skip to content

perf(terminal): stop forking ps on every poll of an anchored agent pane - #35257

Closed
thefrikidude wants to merge 1 commit into
stablyai:mainfrom
thefrikidude:fix/daemon-ps-polling
Closed

thefrikidude wants to merge 1 commit into
stablyai:mainfrom
thefrikidude:fix/daemon-ps-polling

Conversation

@thefrikidude

Copy link
Copy Markdown
Contributor

ELI5

When an agent runs in a terminal pane that you can see, Orca checks about every second whether the agent is still there. To check, it started the ps program each time. On a Mac, each ps start makes the system security service (syspolicyd) do work, so with a few agent panes open that service burned CPU all day. Now Orca asks the kernel two cheap questions instead, and runs ps only once every 10 seconds. With 4 agent panes, ps runs go from 81 to 9 per minute when the agents wait, and from 149 to 24 per minute when they are busy.

Author: @thefrikidude

What Changed

  • Before: a visible agent pane polls inspectProcess every 750 ms. For an anchored agent the terminal host used the "cheap tier". That tier still forked ps -axo pid=,ppid=,pgid=,tpgid=,stat=,lstart= to rebuild the pane fingerprint. The snapshot cache lasts 500 ms, so almost every poll window forked. While the agent ran tools, its subprocesses changed the fingerprint on each poll. Each poll then escalated to the full ps … command= capture.
  • After: between captures, the host keeps the anchor while two facts hold. Neither needs a fork:
    1. node-pty still names the same foreground process (tcgetpgrp + sysctl). The cheap tier already checked this before it forked.
    2. The leader of the anchored foreground group is still alive (process.kill(pid, 0)). EPERM counts as alive.
  • What still forces a capture at once:
    • Agent exit: the leader is gone.
    • Ctrl-Z, or a tool that takes the terminal: node-pty names another process.
    • A restart: the old leader is gone.
  • The fingerprint still runs. It is rebuilt once per shared 10 s window, so anything the kernel checks cannot see is still caught at the next window. Examples are a stopped agent that keeps the terminal, or a reused PID. The window is aligned to the clock, so all panes of a host share one capture.
  • Wrappers keep the old behavior. The shortcut applies only when the foreground leader is itself a recognized agent (claude, codex, …). A wrapper (node, bash -c …) can outlive the agent inside it, so those panes still read the table on every poll, as before.
  • Mechanism:
    • pane-fingerprint-revalidation.ts holds the rule.
    • paneFingerprintForegroundGroup() reads the group from the fingerprint that buildPaneProcessFingerprint() already writes.
    • Anchors record the window in which they were last verified. A new anchor from a full capture counts as verified.
    • The daemon (terminal-host-process-inspection.ts) and the local provider (local-pty-foreground-inspection.ts) both use the helper.
  • What the poll returns is unchanged: the cheap tier's answer ({ foregroundProcess, hasChildProcesses: true }, no evidence). Full captures, evidence, unanchored panes, Windows and remote panes are untouched.

Why

The issue measured about 10 forks per second per terminal host, mostly ps. The commenters showed why that is expensive on macOS: /bin/ps is setuid, so syspolicyd assesses every exec and never caches the result.

I reproduced the cause on a dev build. Idle shells and hidden panes fork little. The rate comes from visible agent panes, which poll every 750 ms.

Options I considered:

  • Read the process table natively (libproc/sysctl), as the issue suggests. This removes ps entirely, but it needs a new native addon in the signed terminal host bundle. It would also need exact ps parity for command=/tdev=; for example, only setuid ps can read the arguments of a sudo pane. That is a much larger and riskier change. This PR does not rule it out, and it removes most of the forks now.
  • A longer snapshot cache: this would also delay noticing agent exit and Ctrl-Z. Here those are still caught at the next poll.

Linked Issue

Fixes #31783

I saw that @Jinwoo-H said on the issue they are looking into it. If this overlaps with work in progress, I am happy to close or reduce this PR.

Visual Proof

N/A: there is no UI change. The proof is the measurements below.

ps forks by one terminal host in 60 s (dev build on macOS). A logging ps shim sits first on the daemon's PATH, and I replay the visible-pane poll for 4 panes every 750 ms. The panes run a compiled fake agent named claude:

4 agent panes main this PR
idle (waiting for input) 81 (79 cheap captures) 9 (7 cheap)
busy (forks a child every 300 ms, like tools) 149 (76 full command= + 71 cheap) 24 (11 full + 11 cheap)

The 2 remaining ps -axo pid=,ppid=,pgid=,lstart= calls per minute come from a separate periodic check and are the same before and after.

Detection in the real app after the change (one poll every 150 ms):

Event Seen as
Ctrl-Z first poll after it (205 ms): foreground leaves claude
fg next poll: claude again, then back to the no-fork path
agent killed first poll (52 ms): full capture. The existing exit-settle logic then clears claude as before.
agent restarted with the same name first poll: full capture, re-anchored on the new process

Testing

  • Real app (macOS, dev build): the tables above, both measured with the same script against main and against this branch.

  • New tests:

    • pane-fingerprint-revalidation.test.ts (10):
      • one read per window
      • a fresh anchor needs no read in its window
      • leader exit reads at once
      • wrappers (node, bash, unknown) read on every poll
      • a change the kernel cannot see is caught at the next window
      • an unverified anchor reads first
      • a failed read rejects
      • EPERM is alive, ESRCH is gone
    • Daemon integration, darwin + linux (8):
      • no fork until the next window, then one cheap fork
      • leader exit escalates inside the window
      • a node-pty name change escalates with no fork
      • a child under the agent is caught at the next window
    • Local provider (1), and fingerprint group parsing (3).
    • All existing cheap-tier tests pass unchanged. They model an npm node wrapper, so they also pin the "wrappers keep the old behavior" rule.
  • Mutation checks: I broke each of 9 safeguards in turn, and a test failed each time:

    • the window check
    • the wrapper check
    • the liveness check
    • marking after a match
    • marking on a mismatch
    • EPERM handling
    • the group parse
    • marking a new daemon anchor
    • marking a new local anchor
  • Suites: the daemon, providers and pty suites pass: 4,256 tests.

  • Gate: pnpm check:changed: 20 of 20 checks pass (format, lint, casts, flaky-test ratchet, typecheck, affected tests).

  • Not tested: Linux and Windows hosts on real hardware. Windows does not reach this path. Linux runs the same code with /proc-backed ps, and the daemon tests cover it.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Written with Claude (Opus 5.5) via Claude Code. I reviewed the diff, ran the measurements, and checked detection in the real app.

Author: X @thefrikidude

Review

AI review summary:

  • Correctness:
    • The cheap tier's answer is unchanged.
    • Agent exit, Ctrl-Z, a tool in front and a restart are caught at the next poll, as before.
    • Changes only the fingerprint can see are caught within ≤10 s instead of ≤0.75 s. These are a stopped agent that keeps the terminal, PID reuse, or a zombie leader.
    • Wrapper-led panes are unchanged.
  • Cross-platform: POSIX only. Windows returns before this path in both callers. kill(pid, 0) works the same on macOS and Linux.
  • SSH/remote: remote panes do not use the cheap tier. Mixed versions are fine: a newer host answers the same RPC with the same shape.
  • Performance: about 6 to 9 times fewer ps forks for agent panes. Each spared fork is one syspolicyd assessment of the terminal host bundle on macOS.
  • Security: none. kill uses signal 0, which only checks that the PID exists.
  • Mobile, folder workspaces: no change.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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) — check:changed and the daemon, providers and pty suites pass locally; the full test run and build are left to CI

🤖 Generated with Claude Code

A visible agent pane asks the terminal host every 750 ms whether its
agent is still in front. For an anchored agent the host answered from a
cheap tier that still forked `ps -axo ...` to rebuild the pane's process
fingerprint, and the 500 ms snapshot cache meant a new fork for almost
every poll window. While the agent ran tools, the fingerprint changed on
every poll and each poll escalated to the full `ps ... command=` capture.
On macOS every one of those forks goes through syspolicyd, which is the
load reported in stablyai#31783.

Between captures the host now trusts two kernel facts that need no fork:
node-pty still names the same process in the foreground (the cheap tier
already checked this), and that process, the leader of the anchored
foreground group, is still alive (`kill(pid, 0)`). Exit, Ctrl-Z, a tool
taking the terminal, and a restart each break one of them. The
fingerprint itself is still rebuilt once per shared 10 s window, so
anything subtler is caught at the next window, and all panes share that
one capture. The shortcut only applies when the foreground leader is a
recognized agent; a wrapper such as `node` or `bash` can outlive the
agent inside it, so those panes keep reading the table on every poll.

The local (non-daemon) provider uses the same helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thefrikidude

Copy link
Copy Markdown
Contributor Author

Could a maintainer approve the CI workflow runs for this PR? They're waiting on approval. Thanks!

@coderabbitai

coderabbitai Bot commented Oct 28, 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: d3ff158e-b326-4d07-ac7a-9056d407d651
Commits

Reviewing files that changed from the base of the PR and between 92a754a and 4c8bc0c.

Files selected for processing: 10
  • src/main/daemon/terminal-host-process-inspection-cheap-tier.test.ts
  • src/main/daemon/terminal-host-process-inspection.ts
  • src/main/daemon/terminal-host-steady-state-anchor.ts
  • src/main/providers/local-pty-foreground-inspection-cheap-tier.test.ts
  • src/main/providers/local-pty-foreground-inspection.ts
  • src/main/providers/local-pty-provider-state.ts
  • src/main/providers/pane-fingerprint-revalidation.test.ts
  • src/main/providers/pane-fingerprint-revalidation.ts
  • src/main/providers/posix-pane-foreground-fingerprint.test.ts
  • src/main/providers/posix-pane-foreground-fingerprint.ts

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

Walkthrough

The change adds a shared 10-second pane fingerprint revalidation window. A verified fingerprint can be reused when a recognized agent leads a live foreground process group. In other cases, inspection reads process rows and rebuilds the fingerprint. Daemon and local PTY foreground inspection now use this logic. Tests cover reuse, recapture, process liveness, fingerprint changes, and inspection escalation.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Low · up to 4c8bc

Agent information can briefly remain stale after a process change near a window boundary. The impact is bounded and does not block merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 61.54% 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: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main performance change: avoiding repeated ps forks for anchored agent panes.
Description check Passed The description is complete and closely follows the repository template. It explains the user impact, implementation, rationale, linked issue, testing, measurements, limitations, cross-platform consid…
Linked Issues check Passed Issue #31783 asks to reduce repeated process launches and ps scans. The PR adds paneFingerprintStillMatches with a shared 10-second revalidation window. It reuses an anchored fingerprint when the …
Out of Scope Changes check Passed The changes stay within issue #31783. They add the revalidation helper, foreground-group parsing, anchor state, daemon and local-provider integration, and tests for the reduced capture behavior and it…
Full details: Description check

Explanation

The description is complete and closely follows the repository template. It explains the user impact, implementation, rationale, linked issue, testing, measurements, limitations, cross-platform considerations, and checklist status. The unchecked full test and build items are explicitly documented as deferred to CI.

Full details: Linked Issues check

Explanation

Issue #31783 asks to reduce repeated process launches and ps scans. The PR adds paneFingerprintStillMatches with a shared 10-second revalidation window. It reuses an anchored fingerprint when the recognized agent remains the foreground process and its process-group leader is alive. It captures immediately when liveness or foreground checks fail. The daemon and local provider use this helper. Wrapper-led panes retain the prior capture behavior. The PR also adds unit, daemon, local-provider, and fingerprint parsing tests. The reported checks and test suites provide supporting evidence for the implementation.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #31783. They add the revalidation helper, foreground-group parsing, anchor state, daemon and local-provider integration, and tests for the reduced capture behavior and its safety conditions. These changes directly support lower ps launch frequency. No unrelated product behavior or work for stale terminal hosts in #23372 is introduced.

Full details: Docstring Coverage

Explanation

Docstring coverage is 61.54% 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 13 functions across 10 files.

Resolution

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

  • 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

Copy link
Copy Markdown
Contributor

Thanks @thefrikidude — your measurements here directly shaped the fix. #31783 is now resolved by #35987, which reads the macOS process table in-process via libproc (the native route you described), so the daemon no longer forks ps on these polls at all. Closing as superseded by #35987.

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]: Terminal daemon spawns full-table ps scans ~1,000/min on macOS, keeping syspolicyd/EDR busy around the clock

2 participants