Skip to content

Reuse cached psutil.Process handles across subtree samples - #171

Merged
jamesabel merged 4 commits into
jamesabel:masterfrom
jabelnocimed:reuse-cached-psutil-handles
Aug 27, 2026
Merged

jamesabel merged 4 commits into
jamesabel:masterfrom
jabelnocimed:reuse-cached-psutil-handles

Conversation

@jabelnocimed

Copy link
Copy Markdown
Contributor

Why

A native access-violation crash during garbage collection (Windows, Python 3.14.2, psutil 7.2.2) was observed in the GUI process during a run with heavy process churn. The faulthandler stack shows the crash inside psutil.Process construction (__init__ → _init → _get_ident → create_time) while the thread was garbage-collecting. It matches a family of unresolved Python-3.14 GC crashes (e.g. pytest-dev/pytest#14500) rather than a fixed upstream bug, so the practical mitigation is fewer native Process inits.

children(recursive=True) constructs a fresh psutil.Process per tree member (plus one for the root) on every call, purely to run that native create-time identity init — and SubtreeCpuSampler was then discarding those objects in favor of its handle cache. Every sampler walk re-ran the crash-implicated native init for the whole subtree.

What changed

  • commit_memory.subtree_pids() — subtree membership from one psutil._ppid_map() snapshot (the same map children() uses internally) with zero Process constructions; falls back to the children() walk if the private helper disappears.
  • subtree_process_count() (admission gate + stall watchdog, GUI process — the crash domain) is now membership-only: no constructions at all.
  • SubtreeCpuSampler walks subtree_pids() and constructs a handle only at first sight of a pid, keeping psutil's create-time pid-reuse guard; handles for departed pids are dropped so the cache stays bounded.
  • ProcessHandleCache + optional parameter on subtree_commit(); ProcessMonitor passes a persistent one so the per-sample commit read also constructs each handle at most once.

Steady-state samples now perform zero native Process inits, versus one per tree member per sample per watcher.

Testing

  • New tests/test_process_handle_reuse.py: membership matches the children() walk, zero constructions for counting, at-most-once construction across repeated CPU/commit samples, departed-handle pruning, fail-open on bad pids.
  • Existing coverage over the blast radius passes: test_subtree_cpu_sampler.py, test_process_monitor_cpu_subtree.py, test_admission_gate.py, test_commit_memory.py — 36 passed total.
  • Ruff clean; ty check src shows the same 15 pre-existing diagnostics as master.

🤖 Generated with Claude Code

jabelnocimed and others added 3 commits August 27, 2026 09:22
Constructing a psutil.Process runs a native init (a create_time identity
read); a native access-violation crash during garbage collection
(Windows, Python 3.14.2, psutil 7.2.2) was observed with exactly those
construction frames on the stack, in the GUI process, during a run with
heavy process churn. children(recursive=True) constructs a fresh handle
per tree member on every call, so every sampler walk re-ran that native
init for the whole subtree.

- commit_memory.subtree_pids(): subtree membership from one pid->ppid
  snapshot (psutil._ppid_map, the same map children() uses internally)
  with zero Process constructions; falls back to the children() walk if
  the private helper disappears.
- subtree_process_count() (admission gate, stall watchdog) is now
  membership-only: no constructions at all.
- SubtreeCpuSampler walks subtree_pids() and constructs a handle only at
  first sight of a pid, keeping psutil's create_time pid-reuse guard;
  handles for departed pids are dropped so the cache stays bounded.
- subtree_commit() takes an optional ProcessHandleCache; ProcessMonitor
  passes a persistent one so the per-sample commit read also constructs
  each handle at most once.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…rds in the snapshot walk

Review fixes for the blocking findings on jamesabel#171. The PR replaced children(recursive=True)
with a pid->ppid snapshot walk and persistent handles, but dropped the identity checks
psutil performed on the way: cpu_percent()/memory_info() on a cached handle never detect
pid reuse, so a recycled pid was read through the dead process's handle (a bogus
cross-process CPU delta -- a new worker inheriting a finished one's pid looked idle to the
stall watchdog from its first tick), and subtree_pids() had neither the in-time guard nor
the gone-since-snapshot skip, adopting recycled-pid orphans into counts and commit sums.

- subtree_members(): the walk now reads each member's create_time through psutil's
  platform layer (one native call, no psutil.Process constructed) and applies psutil's
  own guards -- skip a member gone since the snapshot, exclude a member (and its subtree)
  older than the root. subtree_pids() is its key list.
- ProcessHandleCache.get(pid, create_time)/holds(): a handle is served only for the
  identity it was constructed for; a mismatch drops it and constructs a fresh one. The
  creation times come from the membership walk, so pid reuse costs no extra native reads
  and steady state still constructs zero handles.
- SubtreeCpuSampler: keeps its handles in a ProcessHandleCache (drops _procs/_ctimes);
  a recycled root re-primes (None) instead of yielding a reading; empty membership
  (root gone mid-sample / tree unreadable) is None, never a partial root-only total.
- subtree_commit(): one-shot reads use a throwaway cache (single code path).
- Tests: identity-change reconstruction, recycled-root re-prime, root-vanishes -> None,
  recycled-pid orphan exclusion.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVCS61GzFRFktdBzn8xxce
Two Linux-only assumptions in tests/test_process_handle_reuse.py (the PR's fork CI runs
were never approved, so its tests had not run on Linux before):

- The spawned tree's root now wait()s on its child instead of sleeping beside it. On POSIX
  an unreaped killed child lingers as a zombie that is still the root's child in the
  pid->ppid map (psutil's children() keeps zombies too), so the "departed descendant is
  dropped" test could never see it leave.
- The recycled-pid orphan test used os.getppid() as the "older" process, but /proc
  creation times have clock-tick resolution on Linux, so a parent that spawns the test
  process immediately can share its timestamp -- and equal is in-time (psutil's rule as
  well). It now picks a process strictly older than the test process.

Verified on Windows (.venv) and Linux (WSL Ubuntu, Python 3.12, psutil 7.2.2).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVCS61GzFRFktdBzn8xxce
@codecov-commenter

codecov-commenter commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.34188% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.72%. Comparing base (967aba2) to head (54399ca).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
src/pytest_fly/pytest_runner/commit_memory.py 83.75% 13 Missing ⚠️
src/pytest_fly/pytest_runner/process_monitor.py 72.97% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #171      +/-   ##
==========================================
- Coverage   85.80%   85.72%   -0.09%     
==========================================
  Files          74       74              
  Lines        6270     6359      +89     
==========================================
+ Hits         5380     5451      +71     
- Misses        890      908      +18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVCS61GzFRFktdBzn8xxce
@jamesabel
jamesabel merged commit f5a1136 into jamesabel:master Aug 27, 2026
3 checks passed
jamesabel added a commit that referenced this pull request Aug 27, 2026
…d watchdog cache, one walk per tick — v0.10.4 (#172)

The remaining (non-blocking) findings from the #171 review:

- _refresh_descendant_snapshot (GUI process, every poll) built its (pid, create_time)
  snapshot via subtree_processes(), constructing a psutil.Process per descendant per tick --
  the exact pattern the handle-reuse work removed elsewhere. It now reads subtree_members(),
  which yields those pairs from one snapshot with zero constructions. subtree_processes()'s
  docstring no longer claims a tree-kill caller it never had; it is the snapshot fallback.
- SubtreeCpuSampler.retain(root_pids): the stall watchdog's run-lifetime sampler only evicted
  inside sample(), so every finished module's root bundle (root handle, members, descendant
  handles) leaked until the runner was discarded. The watchdog now retains only the RUNNING
  pids each tick.
- AccessDenied on cpu_percent()/memory_info() no longer drops the handle (it is not an
  identity failure); a live-but-protected helper was being re-constructed every tick, in
  both the monitor child and the GUI-process watchdog. NoSuchProcess still drops.
- ProcessMonitor takes one subtree_members() walk per tick and hands it to both the CPU
  sampler and the commit read (sample()/subtree_commit() accept a precomputed members dict)
  instead of two full-system snapshots per tick that could disagree within one sample.
- Losing psutil's private _ppid_map now logs a one-shot warning instead of silently
  degrading to the handle-constructing walk.
- Tests: the handle-reuse module's tree teardown uses the production terminate_process_tree
  instead of a third copy of the kill helper; one test per change above.

Version 0.10.4.


Claude-Session: https://claude.ai/code/session_01PVCS61GzFRFktdBzn8xxce

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
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.

3 participants