Skip to content

Fix Timer.ensure_started race on concurrent first use - #11153

Open
TINGyu123644 wants to merge 3 commits into
celery:mainfrom
TINGyu123644:fix/timer-ensure-started-race
Open

TINGyu123644 wants to merge 3 commits into
celery:mainfrom
TINGyu123644:fix/timer-ensure-started-race

Conversation

@TINGyu123644

Copy link
Copy Markdown

Fixes #11151

Problem

Timer.ensure_started() does an unguarded check-then-start:

if not self.running and not self.is_alive():
    if self.on_start:
        self.on_start(self)
    self.start()

self.running is set asynchronously by the new thread inside run(), so two threads that first touch the same shared Timer concurrently (both via _do_enter) can both pass the guard and call Thread.start() twice. The loser gets RuntimeError: thread already started out of task-message handling, and in the worst interleaving two run() loops are bootstrapped over one Schedule. There is a worker-wide shared timer instance, so ETA scheduling from multiple threads can hit this.

Fix

Guard the check-and-start with the existing self.mutex. _do_enter calls ensure_started() before acquiring the mutex, so no caller holds it at that point → no self-deadlock. on_start defaults to None for all timer2.Timer callers in the tree, so no callback re-enters the lock. start() only launches the thread (it does not run the loop inline), so the new thread simply waits on the mutex until the lock is released.

Verification

  • Threaded repro (8-thread barrier, concurrent ensure_started) against the unmodified source: 105/120 trials raised RuntimeError/KeyError; against the patched source: 0/120 trials. No deadlock — every trial's stop() completed.
  • New regression test t/unit/utils/test_timer2.py::test_ensure_started_concurrent_first_use (pure addition, +33/-0): fails before the fix (15/20 rounds) and passes after (0/20).
  • Existing test_ensure_started_not_started semantics unchanged (guarded block still skips start() when running is set).

Diff: celery/utils/timer2.py +8/-4, t/unit/utils/test_timer2.py +33/-0.

AI assistance

This patch and its regression test were prepared with AI assistance (WorkBuddy / Tencent Hunyuan Hy). I have read and understand the change and can defend it.

TINGyu123644 and others added 2 commits November 23, 2026 16:42
Guard the check-then-start in Timer.ensure_started with the existing
self.mutex. Two threads first touching the shared timer could both
pass `if not self.running and not self.is_alive()` (running is set
asynchronously by the new thread in run()) and each call Thread.start(),
raising "thread already started" and potentially booting two run loops.
All non-interactive contexts preserve the original behavior; on_start
(default None for timer2.Timer callers) runs under the same lock.

Fixes celery#11151

Signed-off-by: TINGyu123644 <[email protected]>
@auvipy
auvipy self-requested a review November 23, 2026 09:14
@auvipy auvipy added this to the 5.7.x milestone Nov 23, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.32%. Comparing base (3bb3224) to head (e1ed3db).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11153      +/-   ##
==========================================
- Coverage   91.33%   91.32%   -0.01%     
==========================================
  Files         153      153              
  Lines       21841    21842       +1     
  Branches     2712     2712              
==========================================
  Hits        19948    19948              
  Misses       1593     1593              
- Partials      300      301       +1     
Flag Coverage Δ
unittests 91.31% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

This branch has not been deployed

No deployments
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.

Race in Timer.ensure_started: concurrent first use calls Thread.start() twice

2 participants