Repository navigation
fix: leak of benchmark monitor threads - #4259
Conversation
ScheduledPeriodicTimer._action re-arms a fresh DaemonTimer on every fire without checking the stop flag, so a cancel() that lands between a timer fire and _action is immediately undone — the monitor thread then lives for the rest of the process. This fires on normal job completion, so at scale the leaked threads accumulate until the scheduler starves: on a ~23k-job run throughput decayed monotonically (from ~11 min per 1% early to ~131 min per 1% near the end) and the run stalled, with repeated "Benchmark: unable to collect ... process no longer exists" messages from timers still polling exited PIDs. _action now honors the stop flag; cancel() sets the flag before touching the timer (so a racing _action observes it) and is None-safe; and benchmarked() cancels in a finally so a raising job body cannot leak the monitor.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe benchmark timer now synchronizes scheduling and cancellation, stops polling after process exit, and guarantees monitor cleanup when benchmarked code raises. Regression tests cover cancellation races, stopped-state handling, and exceptional context exits. ChangesBenchmark timer safety
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant benchmarked
participant BenchmarkTimer
participant ScheduledPeriodicTimer
participant DaemonTimer
participant ObservedProcess
benchmarked->>BenchmarkTimer: Start monitor
BenchmarkTimer->>ScheduledPeriodicTimer: Schedule periodic action
ScheduledPeriodicTimer->>ObservedProcess: Check process status
ObservedProcess-->>BenchmarkTimer: Return running state
benchmarked->>BenchmarkTimer: Cancel in finally
BenchmarkTimer->>ScheduledPeriodicTimer: Set stopped and cancel
ScheduledPeriodicTimer->>DaemonTimer: Cancel active timer
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/test_benchmark_leak.py (1)
35-42: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy liftMake the regression tests observe the cleanup guarantees.
- Lines 35-42 only call
_action()after_stoppedis already true, so they do not exercise cancellation after the initial check but before rescheduling.- Lines 45-51 cannot verify “flag first” because
_timerisNone; use a fake timer whosecancel()asserts_stopped.- Lines 54-60 would pass even if
bench_thread.cancel()were removed; inject a fakeBenchmarkTimerand assertcancel()was called.Also applies to: 45-51, 54-60
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_benchmark_leak.py` around lines 35 - 42, Strengthen the regression tests around _action and cancellation: make test_action_is_noop_once_stopped trigger the stop/cancel race after _action’s initial check, use a fake timer in the flag-order test whose cancel() verifies _stopped is already true, and inject a fake BenchmarkTimer in the bench_thread test that records and asserts cancel() was called. Preserve the existing cleanup guarantees and assertions while ensuring each test fails if the corresponding behavior is removed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/snakemake/benchmark.py`:
- Around line 276-280: The _action() rescheduling path remains racy because
cancel() can run after the initial _stopped check. Use the same lock/state
protocol as cancel() to protect the check through cancellation of the current
timer, and perform a second protected _stopped check immediately before creating
and starting the replacement DaemonTimer, preventing rescheduling after
cancellation.
---
Nitpick comments:
In `@tests/test_benchmark_leak.py`:
- Around line 35-42: Strengthen the regression tests around _action and
cancellation: make test_action_is_noop_once_stopped trigger the stop/cancel race
after _action’s initial check, use a fake timer in the flag-order test whose
cancel() verifies _stopped is already true, and inject a fake BenchmarkTimer in
the bench_thread test that records and asserts cancel() was called. Preserve the
existing cleanup guarantees and assertions while ensuring each test fails if the
corresponding behavior is removed.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 354f17c2-8e1c-469e-8205-503d8ac568cd
📒 Files selected for processing (2)
src/snakemake/benchmark.pytests/test_benchmark_leak.py
After the leak fix the monitor is still armed for the whole context, so a process that exits mid-context keeps getting polled every interval (each poll failing with NoSuchProcess) until the context closes. Stop the timer once the observed process is gone. The check runs after the sample so a final measurement is still attempted, and _action honors the resulting stop so it does not re-arm.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tests/test_benchmark_leak.py (2)
56-63: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winAssert that the monitor is actually cancelled.
Checking
record.running_timeonly proves thefinallypath recorded timing; it does not proveBenchmarkTimer.cancel()ran. Spy oncancel()or assert the monitor is stopped after the body raises, since cancellation is the behavior preventing the thread leak.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_benchmark_leak.py` around lines 56 - 63, Update test_benchmarked_cancels_when_body_raises to observe BenchmarkTimer.cancel() directly, using a spy or mock while preserving the ValueError body failure. Assert that cancel() is called after the exception path, rather than relying only on record.running_time.
47-54: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winVerify flag-before-cancel ordering.
With
_timer=None, this test does not prove that_stoppedis set before the underlying timer’scancel()method. Inject a mock timer whosecancel()asserts the flag is already true, and verify it is called.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_benchmark_leak.py` around lines 47 - 54, Update test_cancel_is_none_safe_and_sets_flag_first to inject a mock timer whose cancel() asserts t._stopped is already true; invoke t.cancel(), then verify the mock timer’s cancel method was called while preserving the existing stopped-state assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/test_benchmark_leak.py`:
- Around line 65-78: Update test_work_stops_monitor_once_process_exited to
replace the no-op timer._update_record lambda with a mock, then assert it is
called exactly once after timer.work(). Retain the existing assertion that
timer._stopped is True, verifying the final measurement occurs before stopping.
---
Outside diff comments:
In `@tests/test_benchmark_leak.py`:
- Around line 56-63: Update test_benchmarked_cancels_when_body_raises to observe
BenchmarkTimer.cancel() directly, using a spy or mock while preserving the
ValueError body failure. Assert that cancel() is called after the exception
path, rather than relying only on record.running_time.
- Around line 47-54: Update test_cancel_is_none_safe_and_sets_flag_first to
inject a mock timer whose cancel() asserts t._stopped is already true; invoke
t.cancel(), then verify the mock timer’s cancel method was called while
preserving the existing stopped-state assertion.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7efd5cd7-68a0-4844-a532-7b9cf00310f9
📒 Files selected for processing (2)
src/snakemake/benchmark.pytests/test_benchmark_leak.py
🚧 Files skipped from review as they are similar to previous changes (1)
- src/snakemake/benchmark.py
The stop-flag check and the reschedule in _action() were not atomic with cancel(): a cancel() landing between _action's re-check and starting the next timer could still be undone. Guard the flag with a lock and serialize it with (re)scheduling in start()/_action()/cancel() via a _schedule() helper, so the two can never interleave into a resurrected timer. Strengthen the tests to prove the guarantees rather than just observe state: cancel during the check→reschedule window does not re-arm, cancel() sets the flag before touching the timer, cancel() is None-safe, and benchmarked() cancels the monitor on the exception path.
🤖 I have created a release *beep* *boop* --- ## [9.24.0](v9.23.1...v9.24.0) (2026-07-30) ### Features * allow to combine cases with otherwise in branch function ([#4262](#4262)) ([000ff52](000ff52)) ### Bug Fixes * avoid config hash crash for non-serializable values ([#4241](#4241)) ([1a27746](1a27746)) * compilation error when final line contains an f-string ([#4234](#4234)) ([9c5e7fe](9c5e7fe)) * Group error log formatting ([#4256](#4256)) ([bb6dcde](bb6dcde)) * leak of benchmark monitor threads ([#4259](#4259)) ([d37852e](d37852e)) * no benchmark warning when a process exits before it can be sampled ([#4260](#4260)) ([6738359](6738359)) * persistence starttime unset/defaults ([#4251](#4251)) ([56395c0](56395c0)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please).
ScheduledPeriodicTimer._actionre-arms a freshDaemonTimeron every fire without checking the stop flag, so a cancel() that lands between a timer fire and _action is immediately undone — the monitor thread then lives for the rest of the process. This fires on normal job completion, so at scale the leaked threads accumulate until the scheduler starves: on a ~23k-job run throughput decayed monotonically (from ~11 min per 1% early to ~131 min per 1% near the end) and the run stalled, with repeated "Benchmark: unable to collect ... process no longer exists" messages from timers still polling exited PIDs._actionnow honors the stop flag;cancel()sets the flag before touching the timer (so a racing_actionobserves it) and is None-safe; andbenchmarked()cancels in afinallyso a raising job body cannot leak the monitor.QC
docs/) is updated to reflect the changes or this is not necessary (e.g. if the change does neither modify the language nor the behavior or functionalities of Snakemake).AI-assistance disclosure
I used AI assistance for:
Summary by CodeRabbit