Skip to content

fix: leak of benchmark monitor threads - #4259

Merged
johanneskoester merged 4 commits into
snakemake:mainfrom
bkeepers:fix-benchmark-monitor-thread-leak
Jul 28, 2026
Merged

johanneskoester merged 4 commits into
snakemake:mainfrom
bkeepers:fix-benchmark-monitor-thread-leak

Conversation

@bkeepers

@bkeepers bkeepers commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

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.

QC

  • The PR contains a test case for the changes or the changes are already covered by an existing test case.
  • The documentation (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).
  • I, as a human being, have checked each line of code in this pull request

AI-assistance disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Summary by CodeRabbit

  • Bug Fixes
    • Reworked periodic benchmarking timer handling to prevent cancellation/rescheduling races and avoid unintended re-arming.
    • Improved shutdown behavior so monitoring stops when the process exits and no monitor is left running after failures.
    • Made cancellation more robust by safely handling cases where the underlying timer is not yet available.
  • Tests
    • Added regression coverage for timer cancellation/re-arming race conditions and for ensuring monitor cleanup even when the benchmark body raises.

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.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d3422c4-569c-4ebd-bdb6-aa8d1c8ddd3d

📥 Commits

Reviewing files that changed from the base of the PR and between 1944fd4 and e389cf8.

📒 Files selected for processing (1)
  • tests/test_benchmark_leak.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_benchmark_leak.py

📝 Walkthrough

Walkthrough

The 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.

Changes

Benchmark timer safety

Layer / File(s) Summary
Timer cancellation race handling
src/snakemake/benchmark.py, tests/test_benchmark_leak.py
ScheduledPeriodicTimer prevents work or re-arming after cancellation, sets _stopped before cancelling the underlying timer, and adds regression coverage for these states.
Benchmark exception cleanup
src/snakemake/benchmark.py, tests/test_benchmark_leak.py
BenchmarkTimer stops polling after process exit, while benchmarked() cancels its monitor and computes running_time when the wrapped body raises.

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
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 72.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main fix: benchmark monitor thread leaks.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/test_benchmark_leak.py (1)

35-42: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy lift

Make the regression tests observe the cleanup guarantees.

  • Lines 35-42 only call _action() after _stopped is already true, so they do not exercise cancellation after the initial check but before rescheduling.
  • Lines 45-51 cannot verify “flag first” because _timer is None; use a fake timer whose cancel() asserts _stopped.
  • Lines 54-60 would pass even if bench_thread.cancel() were removed; inject a fake BenchmarkTimer and assert cancel() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a27746 and 448d1fb.

📒 Files selected for processing (2)
  • src/snakemake/benchmark.py
  • tests/test_benchmark_leak.py

Comment thread src/snakemake/benchmark.py Resolved
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Assert that the monitor is actually cancelled.

Checking record.running_time only proves the finally path recorded timing; it does not prove BenchmarkTimer.cancel() ran. Spy on cancel() 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 win

Verify flag-before-cancel ordering.

With _timer=None, this test does not prove that _stopped is set before the underlying timer’s cancel() method. Inject a mock timer whose cancel() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 448d1fb and 7f43be8.

📒 Files selected for processing (2)
  • src/snakemake/benchmark.py
  • tests/test_benchmark_leak.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/snakemake/benchmark.py

Comment thread tests/test_benchmark_leak.py Resolved
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.

@johanneskoester johanneskoester left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot!!

@johanneskoester
johanneskoester enabled auto-merge (squash) July 28, 2026 10:53
@johanneskoester
johanneskoester merged commit d37852e into snakemake:main Jul 28, 2026
83 of 87 checks passed
johanneskoester pushed a commit that referenced this pull request Jul 30, 2026
🤖 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).
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.

2 participants