Skip to content

native: scan the process table once per tick, not once per pane - #134

Merged
chaodu-agent merged 6 commits into
mainfrom
perf/procs-scan-once-per-tick
Nov 19, 2026
Merged

chaodu-agent merged 6 commits into
mainfrom
perf/procs-scan-once-per-tick

Conversation

@chaodu-agent

@chaodu-agent chaodu-agent commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #3

On Linux, the holder scans the process table once per 250 ms tick for all of its panes, instead of once per pane. Each scan is also cheaper: /proc/<pid>/stat is read into a reused buffer and parsed from bytes, and the child and process-group indexes are built once per snapshot. macOS behaviour is unchanged.

Measured head

The numbers below were measured at commit a10d7c5, the commit that introduced the shared scan. They were not re-measured on later commits. Commits 05f27b0, aeb7fc2 and 4f56bc1 changed the degraded-scan path and its tests, and 84ffce4 changed the age check and the docs. fcc8434 changed only test gating.

Numbers

Linux build host: Intel N100, 4 cores, 8 panes, 302 processes in the namespace. Idle holder, 300 s, ps -o %cpu,rss every 15 s (cumulative %cpu).

%cpu mean %cpu range Peak RSS
base (main 0d62828) 14.9 14.2 to 15.5 4432 KiB
a10d7c5 1.86 1.8 to 1.9 5296 KiB (samples 4148 to 5296 KiB)

The base and this branch ran at the same time by accident (two tool calls overlapped), so each one loaded the other. Treat the pair as a rough comparison, not a controlled one.

The "well under 1 percent" target is not met. One scan per 250 ms tick sets a floor of about 1.8 percent on this host. Going lower needs a back-off when quiet (recommendation 3 in the measurement notes, not in this PR).

Base figure versus the recorded baseline. The baseline record gives 18.05 % mean for the same base commit, 0d62828. That run was measured alone, with 342 processes in the namespace, 19 of them unrelated openab-shepherd hold processes from another job. The pair above ran with 302 processes. Scaling 18.05 by 302/342 gives about 15.9 %, near the 14.9 % measured here. About one point of the gap is not explained by the records, and it was not re-measured. Compare this branch against 14.9 %, because it comes from the same concurrent pair as the 1.86 % figure. The 18.05 % figure comes from a different table size and is not comparable.

Peak RSS. The base peaked at 4432 KiB and this branch at 5296 KiB, a difference of +864 KiB (about +20 %) in the same concurrent pair. The isolated baseline recorded 4576 KiB for the same base commit, so against it the increase is +720 KiB. The likely cause is the retained snapshot plus the child and peer indexes built over the whole process table. Those parts were not measured separately.

Front restart, 8 full panes, wall time from SIGUSR2 until the new front's CPU is quiet, 3 runs:

run 1 run 2 run 3
base 0.51 s 0.68 s 0.80 s
a10d7c5 0.51 s 0.68 s 0.56 s

Runs 1 and 2 match between the two rows at the reported 0.01 s resolution. The measurement record does not say whether the two rows came from separate harness invocations, so that match is not explained. The isolated baseline gave 0.53, 0.70 and 0.69 s. The restart was not re-measured on the later commits.

Degraded scans

A /proc listing that fails, a read that fails (for example, out of file descriptors), or a stat line that cannot be parsed marks the scan incomplete. An incomplete scan is not cached and prunes no member: a member is dropped only when its pid shows another start time, or when a complete scan no longer lists it. A zombie or exited process is still treated as gone. While a read keeps failing, no scan is kept, so each pane's look takes its own scan, as it did before the shared scan. The tests use real failures: a missing listing, and a stat path that cannot be read.

Detection window

On Linux, a descendant that detaches is seen within about 500 ms in the nominal case (250 ms snapshot age plus a 250 ms look interval), and at most about 700 ms provided each scan finishes within the 250 ms age limit. The snapshot age is read after the shared lock is taken, so a reader that waited for another pane's scan judges the snapshot when it uses it. A longer scan adds its own time. On macOS the bound is about 450 ms. The ADR, the operations guide, the README and the CHANGELOG state these bounds.

Processes whose command name is not valid UTF-8 are now trackable, so they are found and, on remove_pane or shutdown, signalled. The CHANGELOG records this.

Stop path

soft_stop, await_tree_gone and release take a fresh scan, and signals still re-read the pid and its start time before sending. Only the periodic look may use a snapshot up to 250 ms old.

Tests

Commands, run on the head of this PR: cargo fmt --check, cargo clippy --locked --all-targets -- -D warnings, and cargo test --locked --no-fail-fast.

  • macOS build host (Apple Silicon): 1019 passed, 0 failed, 6 ignored.
  • Linux build host: 1042 passed, 0 failed, 6 ignored. This includes the Linux-only scan tests, which read /proc.

eight_panes_share_one_scan_per_tick asserts the exact scan count that the one-scan-per-window rule predicts. eight_pollers_take_exactly_one_scan_per_window pins six scans in 1.5 s. a_snapshot_is_reused_until_the_age_limit_and_no_longer pins the 250 ms age limit.

Not in this PR

Recommendation 3 (back-off when quiet) and recommendation 4 (/proc children lookup) remain options. Readers that wait on the shared lock rescan one after another when a scan is incomplete or takes longer than 250 ms, and each holds its pane's tree lock meanwhile. Reusing an incomplete snapshot would be a cache change, so that stays a follow-up. The CPU cost of teardown, when stop paths scan the whole table, is not measured.

Linux: every pane's reader read /proc/<pid>/stat of every process in the
PID namespace about 2.5 times a second (8 panes, 275 processes: 18% of a
core on an Intel N100). Two changes, finding the same members:

1. A cheaper scan. Each stat is read into a reused buffer and parsed in
   place (bytes, no String, no Vec of fields); the children and the
   group/session indexes are built once per snapshot instead of filtering
   the whole map per call.
2. One snapshot per tick. A holder-wide procs::Shared hands every pane's
   periodic look the same scan if it began less than 250 ms ago and not
   before the pane was spawned. The stop paths (soft_stop,
   await_tree_gone, release) still take their own fresh Tree::refresh,
   and signals still re-read the pid's start time. Lock order: a pane's
   tree, then Shared's lock, which is a leaf. macOS keeps its per-question
   kernel calls (Shared is a no-op there).

One difference in what is found: a process whose command name is not
valid UTF-8 was invisible to the old read_to_string-based parser (so it
was never in a tree and never signalled); the byte parser sees it.

Docs: operations.md says the periodic look may use a 250 ms old read.

Verified (Linux x86_64 build host, no cargo on the laptop):
- cargo fmt --check, clippy --all-targets -D warnings: clean.
- cargo test, whole suite, 2 runs at the final tree: 981 lib + all
  integration tests pass, 0 failed (3 more runs before the last
  test-only fixture fix, same). No existing assertion was edited.
- New tests: parser on a comm with spaces/parentheses, 100 KB comm, non
  UTF-8 comm, zombie, cut lines, a real zombie and a pid that vanished
  between readdir and read; fixture tree finds exactly its 4 members via
  refresh and refresh_shared; age limit and not_before; 8 trees share one
  scan; 8 panes cost <= 14 scans in 1.5 s; stop kills a child the shared
  snapshot missed.
- Equivalence: while the old text parser and BFS were kept as a test
  oracle, the new snapshot matched it (start, children, peers on the
  fixture, start of every common process, same member set); the oracle is
  deleted in this commit and the fixture tests assert explicit members.
- Mutation check: soft_stop/await_tree_gone/release switched to
  refresh_shared makes a_stop_scans_afresh_and_ends_a_child_the_shared_
  snapshot_missed fail ("outlived kill: the stop used a stale snapshot");
  reverted.
- 50 runs of the process, stop and contract tests with 4 busy loops: 50/50.
- Idle holder, 8 panes, 300 s, ps %cpu: base 15.2 (18.05 earlier run),
  new 1.8. Front restart, 8 full panes, 6 runs each: wall to quiet
  0.55-0.74 s new, 0.51-0.68 s base (not changed; neither reproduces the
  3.1-3.9 s of the report).
- macOS not built here (data volume has under 5 GiB free): hosted CI.
macOS clippy -D warnings flagged them as dead code (their only callers are Linux-only tests).
Checked: cargo fmt --check and clippy --all-targets -D warnings clean on a Linux x86_64 host and on macOS; native::host tests pass on both.
A /proc scan that cannot list the directory or read a process (for example
when file descriptors run out) is now marked incomplete. The shared snapshot
does not cache an incomplete scan, and Tree::apply keeps each member it
cannot check instead of pruning it. A member whose pid shows another start
time is still dropped.

Items addressed:
- (a) Degraded scans: Snapshot::build/take track completeness; Shared::snapshot_at
  caches only complete scans; Tree::apply prunes only on a complete snapshot.
  Tests: a_degraded_snapshot_prunes_no_pane_member, a_degraded_snapshot_is_not_cached.
- (b) Scan count: eight_pollers_take_exactly_one_scan_per_window asserts exactly six
  scans in 1.5 s for eight 250 ms pollers on a supplied clock, and
  a_snapshot_is_reused_until_the_age_limit_and_no_longer pins the 250 ms limit.
  The real-PTY eight_panes_share_one_scan_per_tick now asserts 2 to 7 scans,
  because panes started together cluster on the 200 ms reader wake and gave 3.
- (c) Docs: adr/native-core.md and operations.md state the Linux window as 500 ms
  nominal and at most about 700 ms (macOS about 450 ms), including the owner-decision paragraph.
- (d) CHANGELOG: latency change, and processes whose command name is not UTF-8 are now tracked.
- (f) Removed the unused Default impl for Shared, documented that the Linux snapshot
  ignores leader and tty (parameters kept: the signature is shared with macOS),
  and corrected the parse_stat and read_loop comments.

Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings;
cargo test --locked):
- macOS build host: 1019 passed, 0 failed, 6 ignored (12 test binaries)
- Linux build host: 1039 passed, 0 failed, 6 ignored (12 test binaries)

Refs #3
@chaodu-agent

Copy link
Copy Markdown
Collaborator Author

Important

CHANGES REQUESTED ⚠️ - The shared snapshot design is sound and the stop path stays fresh, but the README is stale, the real-PTY scan test is timing-sensitive, and two fail-safe edges need tightening.

What This PR Does

On Linux, every native pane reader used to scan all of /proc on its own 250 ms tick, so idle CPU grew with panes x processes (14.9% for 8 panes on the measured host). This PR makes the holder take one /proc scan per 250 ms window and share it across all panes, which brings the same workload to about 1.86% idle CPU. macOS behaviour is unchanged.

How It Works

  • procs::Shared keeps the last complete Snapshot (stat per pid, plus children and peers indexes built once). Tree::refresh_shared reuses it when it began at or after the pane's born instant and is less than SNAPSHOT_MAX_AGE (250 ms) old; otherwise it takes a fresh scan under the Shared lock.
  • Only the reader's periodic look (local.rs:710) uses the shared snapshot. soft_stop, await_tree_gone and release (local.rs:569,582,605) still call Tree::refresh, which always scans afresh.
  • Reader::read parses /proc/<pid>/stat from bytes into a reused buffer. ENOENT/ESRCH map to Gone (skipped); any other error maps to Failed, which marks the snapshot incomplete. An incomplete snapshot is not cached and never prunes a member; a member whose start time changed is still dropped.
  • Byte parsing (last ) via rposition) also fixes processes with non-UTF-8 command names, which previously escaped the tree and were not signalled on stop.
  • Cost: on Linux with 2 or more panes, a detached descendant is seen within about 500 ms nominal and at most about 700 ms (was about 250 ms nominal). Peak RSS rose from 4432 KiB to 5296 KiB.

Findings

# Severity Finding Location
1 🟡 README still states the old 250 ms Linux detection window README.md:81, README.md:223
2 🟡 eight_panes_share_one_scan_per_tick asserts a wall-clock 2..=7 range that depends on scheduling and on scans being complete src/native/host/tests_scan.rs:72-84
3 🟡 A stat that is read but fails to parse is treated as Gone, so a complete snapshot can prune a live member src/native/host/procs.rs:343
4 🟡 Readers that queue on the Shared lock rescan one after another when the snapshot is incomplete or the scan takes longer than 250 ms, while each holds its pane's tree lock src/native/host/procs.rs:504-520
5 🟡 Operations docs do not state that snapshot memory scales with the system process count, or that sustained degraded scans let a tree grow without pruning; CHANGELOG quotes CPU figures from an uncontrolled run docs/operations.md, CHANGELOG.md:9-10
6 🟢 Stop paths never use the shared snapshot, and a test pins it src/native/host/local.rs:569,582,605
7 🟢 Gone vs Failed split keeps high pid churn from disabling the cache or pruning src/native/host/procs.rs:336-348
8 🟢 Deterministic snapshot_at seam with exact 249 ms / 250 ms boundary and one-scan-per-window tests src/native/host/procs.rs:910-960
Finding Details

🟡 F1: README describes the obsolete detection window

The CHANGELOG, ADR and docs/operations.md were updated to the new bound (about 500 ms nominal, about 700 ms max on Linux; about 450 ms on macOS), but README.md was not touched. Line 81 still says the table is read "about every 250 ms, so a process that fully detaches faster than that is missed", and line 223 still says "within the 250 ms". Operators reading the README get a cleanup bound that no longer holds.

Requested change: update both README passages to the Linux nominal/max figures and the macOS figure, or drop the timing from the README and link to the Known limits in docs/operations.md.

🟡 F2: The real-PTY scan-count test is timing-sensitive

The test sleeps 700 ms, then 1.5 s, and asserts (2..=7).contains(&taken). The lower bound depends on the runner keeping the reader threads scheduled; a loaded CI runner can produce fewer looks without any bug. The upper bound assumes every scan is complete: an incomplete scan is not cached, so a transient EMFILE makes every poll rescan and can exceed 7. The PR notes that panes started together gave 3 scans in one run, which shows the result depends on the 200 ms wake grid.

The exact invariant is already pinned by the supplied-clock test eight_pollers_take_exactly_one_scan_per_window.

Requested change: keep the supplied-clock test as the invariant. For the real-PTY test, assert only what proves sharing without a wall-clock floor (for example taken >= 1 and well below the unshared count of about 48), or start the readers on a barrier and count looks instead of elapsed time.

🟡 F3: Parse failure should not count as "gone"

Reader::read returns parse_stat(&self.buf).map_or(StatRead::Gone, StatRead::Stat). When the file was opened and read but the content does not parse, the process is treated as exited. In a complete snapshot, Tree::apply then drops that member, and a later stop will not signal it. Every other uncertain case in this PR fails safe by keeping the member; this one fails open.

Requested change: map a parse failure to StatRead::Failed, so the snapshot is marked incomplete and the member is kept, and add a test for it next to the existing malformed-line tests.

🟡 F4: Queued readers can serialize full rescans

snapshot_at holds last while it runs take(). When the result is incomplete it is not stored, so every reader queued behind it takes its own full scan, one at a time, each while holding its pane's tree lock. The same happens when one scan takes 250 ms or more: began is the scan start, so the snapshot is already too old for the next waiter. Total CPU stays at the base level (N scans per tick), but readers stop draining their terminals for N scan durations, and a stop on a pane waits on that pane's tree lock behind other panes' scans. Both cases happen when the host is already under pressure.

Requested change: let a reader that waited for the lock accept the scan that finished while it waited. An incomplete snapshot can safely be reused for the rest of that window, because apply never prunes on it. Alternatively, run take() outside the critical section and re-check before storing.

🟡 F5: Document the memory and degraded-scan behaviour, and qualify the numbers

  • The retained snapshot and its indexes cover every process on the system, not just pane descendants. Memory therefore scales with the host's process count: +864 KiB at 302 processes, more on a large shared host. docs/operations.md should say so.
  • Under sustained degraded scans, no member is ever pruned, so a tree only grows until a complete scan succeeds. Signals still re-read the start time, so this cannot kill a wrong process, but the behaviour should be stated next to the existing fail-safe description.
  • The PR description says the base and branch runs overlapped on the same host and loaded each other. The CHANGELOG quotes "about 14.9 % to about 1.9 %" without that caveat. Either re-measure in isolation or mark the figures as approximate from a shared-host run.

🟢 F6: Stop paths stay fresh

All three stop call sites use Tree::refresh, and the test asserting host.scans() is unchanged after a kill pins that invariant. The documented lock order (tree then Shared, with Shared as a leaf that stop paths never take) has no reachable cycle.

🟢 F7: Degraded-scan semantics are correct

Only errors other than ENOENT/ESRCH mark a snapshot incomplete, so a pid that exits between readdir and read is skipped without disabling the cache. Children are indexed by the child's ppid, so children of an unreadable parent are still found. A changed start time still drops a member even in a degraded scan.

🟢 F8: Deterministic tests

The supplied-clock seam in snapshot_at pins the reuse boundary (249 ms reused, 250 ms rescanned), the one-scan-per-window rate for eight pollers, the born cutoff, and both degraded-scan cases. The byte parser has tests for malformed lines, zombies, a 100 KB adversarial comm and non-UTF-8 names.

Baseline Check
  • PR opened: 2026-11-17
  • Reviewed head: 05f27b0559e4856238aa11d353be27472ba9c76b
  • Base branch: main (not stacked); merge-base 0d62828e8e6928a53527382d821a9b1875b0cc99
  • Diff: 7 files, +910 / -51, 3 commits
  • Main already has: per-pane /proc scans every 250 ms (TREE_POLL), the descendant tree with start-time checks, and fresh scans on stop
  • Net-new value: one shared Linux scan per 250 ms window, a cheaper byte-level /proc/<pid>/stat reader, degraded-scan handling, tracking of non-UTF-8 command names, and updated ADR/operations/CHANGELOG text
  • CI at review time: test (ubuntu-latest), test (macos-latest) and docker build all pass
Points Raised and Resolved During Review
  • Last ) in comm: verified. procs.rs:296 uses rposition(|&b| b == b')') on bytes.
  • try_lock skipping a tick extends the window without bound: not an issue. The try_lock is on the pane's own tree and fails only while a stop holds it; that stop runs a fresh Tree::refresh itself.
  • Pid exiting between readdir and read marks the snapshot incomplete: not an issue. ENOENT/ESRCH map to Gone and are skipped (F7).
  • < vs <= at the age limit, and clock source: pinned by test at exactly 250 ms; prod uses Instant::now() for both born and now.
  • 700 ms worst case: consistent with up to about 450 ms between looks (200 ms poll wake plus the 250 ms next_tree) plus up to 250 ms snapshot age. With one pane the cache always expires between looks, so the extra latency only applies with two or more panes.
What's Good (🟢)
  • The dangerous direction is consistently fail-safe: an uncertain member is kept rather than dropped, and every signal re-reads the start time first.
  • The born cutoff prevents a pane from using a snapshot taken before its leader existed, which could otherwise map a stale group id onto foreign processes.
  • The docs state the latency trade-off and the unmet sub-1% target plainly.
  • cfg(all(test, target_os = "linux")) gating on test hooks is consistent, and macOS keeps a no-op Shared.

5️⃣ Three Reasons We Might Not Need This PR

  1. The target is still not met. Idle CPU stays at about 1.86% because the holder still scans the whole table four times a second. Back-off when quiet (recommendation 3) attacks the floor directly and might make sharing less important.
  2. The benefit depends on pane count. With one pane nothing changes except about 800 lines of new machinery and a third tree semantic ("absent from an incomplete scan, keep"). If most Linux hosts run one or two panes, the added memory and complexity may not pay back.
  3. Cleanup latency gets worse. The window in which a fast-detaching descendant escapes grows from about 250 ms to up to about 700 ms. If prompt cleanup matters more than idle CPU, a Linux PR_SET_CHILD_SUBREAPER supervisor (already the ADR's follow-up) would be a better investment.

Suggestions, not blocking: the non-UTF-8 command-name fix is independent of the sharing design and could be split out, so it survives if the perf change is ever reverted. Making stop paths structurally unable to reach Shared (for example a stop-only wrapper) would protect the fresh-scan invariant from a future refresh / refresh_shared mix-up.

… the window

A /proc stat line that cannot be parsed is now a failed read, so the snapshot
is incomplete and keeps the member. Before, it was read as an exited process,
and a complete snapshot could drop a live member. A zombie or exited process is
still treated as gone.

Items addressed (from the bot review on the previous head):
- Unparseable stat line: parse_stat returns Result; an error maps to
  StatRead::Failed. Test: an_unparseable_line_is_a_failed_read_not_a_gone_process.
- README: the periodic-look and fast-escape passages state the Linux nominal
  and worst-case bounds and the macOS bound.
- docs/operations.md: the snapshot memory grows with the host process count,
  and a degraded scan keeps every member it cannot check.
- Real-PTY scan count: the test asserts 1 to 7 scans in 1.5 s (at most one per
  250 ms window). The exact count stays in eight_pollers_take_exactly_one_scan_per_window.
- CHANGELOG: removed the uncontrolled CPU figures.
- Not changed: readers queue on the shared lock when a scan is incomplete or
  takes longer than 250 ms. Reusing an incomplete snapshot would reverse the
  approved degraded-scan rule, so this is recorded as a follow-up.

Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings;
cargo test --locked):
- macOS build host: 1019 passed, 0 failed, 6 ignored (12 test binaries)
- Linux build host: 1040 passed, 0 failed, 6 ignored (12 test binaries)

Refs #3
Fixes for the second council pass on aeb7fc2.

- Degraded scans: Snapshot::take reads through take_in(root). Two new
  Linux tests make a real failure: a listing that cannot be read, and a
  stat path that cannot be read (EISDIR). Both leave the snapshot
  incomplete, and both prune no pane member.
- Exact scan count: eight_panes_share_one_scan_per_tick replays every
  look the real pane readers made against the rule of one scan per
  250 ms window (a literal, so changing SNAPSHOT_MAX_AGE fails it), and
  asserts the scan count that rule predicts for those looks. The 700 ms
  sleep before counting is gone, so the pane-creation burst is measured.
- Linux bound: docs/adr/native-core.md, docs/operations.md, README.md and
  CHANGELOG.md state the about 700 ms worst case with its condition: each
  scan must finish within the 250 ms age limit. A longer scan, or a wait
  on the shared lock, adds its own time. The nominal figure is 500 ms.
  The bare "nominal" wording is replaced with the stated bound.
- Shared::snapshot doc comment: an incomplete scan does not replace an
  older complete one, so a reader may still reuse that older one.
- CHANGELOG: a process whose command name is not valid UTF-8 is now
  trackable, so it is found and signalled on stop.
- Left unchanged: the leader and tty parameters of the Linux
  Snapshot::take. The signature is shared with macOS, where both are used.

Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings;
cargo test --locked --no-fail-fast):
- macOS build host: 1019 passed, 0 failed, 6 ignored.
- Linux build host: 1042 passed, 0 failed, 6 ignored.

Refs #3
…ed cost

Refs #3

Addressed from the pass-3 review of 4f56bc1:

- Snapshot age (procs.rs, Linux Shared): the clock is read after the shared
  lock is taken, in reuse_or_take, so a reader that waited for another pane's
  scan judges the snapshot when it uses it. snapshot_at, the supplied-clock
  seam, is now test-only. Without this gate the lib build fails under
  -D warnings on Linux.
- Docs (docs/operations.md, docs/adr/native-core.md): the memory sentence
  gives the measured values, about 720 KiB more than the isolated base run and
  about 864 KiB more than the concurrent base run, at 302 processes. The
  degraded-scan rule now states its cost: while a read keeps failing, no scan
  is kept, so each pane's look takes its own scan.
- Formatting (README.md, CHANGELOG.md, docs/operations.md, src/native/host/
  local.rs): over-long lines rewrapped; a dangling line fragment in README.md
  removed.

Unchanged: the test that replays the scan window (eight_panes_share_one_scan_
per_tick) keeps its complete-scan assumption, which holds on a healthy /proc.

Tests, run on the head of this commit:
- macOS build host (Apple Silicon): cargo fmt --check, cargo clippy --locked
  --all-targets -- -D warnings, cargo test --locked --no-fail-fast. Result:
  1019 passed, 0 failed, 6 ignored.
- Linux build host (x86_64): the same three commands. Result: 1042 passed,
  0 failed, 6 ignored, including the Linux-only tests that read /proc.
@chaodu-agent
chaodu-agent merged commit 1f1f902 into main Nov 19, 2026
4 of 5 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