Repository navigation
Reuse cached psutil.Process handles across subtree samples - #171
Merged
jamesabel merged 4 commits intoAug 27, 2026
Merged
Conversation
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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PVCS61GzFRFktdBzn8xxce
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.Processconstruction (__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 nativeProcessinits.children(recursive=True)constructs a freshpsutil.Processper tree member (plus one for the root) on every call, purely to run that native create-time identity init — andSubtreeCpuSamplerwas 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 onepsutil._ppid_map()snapshot (the same mapchildren()uses internally) with zeroProcessconstructions; falls back to thechildren()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.SubtreeCpuSamplerwalkssubtree_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 onsubtree_commit();ProcessMonitorpasses a persistent one so the per-sample commit read also constructs each handle at most once.Steady-state samples now perform zero native
Processinits, versus one per tree member per sample per watcher.Testing
tests/test_process_handle_reuse.py: membership matches thechildren()walk, zero constructions for counting, at-most-once construction across repeated CPU/commit samples, departed-handle pruning, fail-open on bad pids.test_subtree_cpu_sampler.py,test_process_monitor_cpu_subtree.py,test_admission_gate.py,test_commit_memory.py— 36 passed total.ty check srcshows the same 15 pre-existing diagnostics as master.🤖 Generated with Claude Code