Skip to content

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

Open

Description

@ashitpatel

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

celery/utils/timer2.py:110-114:

def ensure_started(self) -> None:
    if not self.running and not self.is_alive():
        if self.on_start:
            self.on_start(self)
        self.start()

The check-then-start is unguarded. When two threads first touch the same Timer concurrently (both go through _do_enter → ensure_started, the only caller), both can pass the guard — running is set asynchronously by the new thread in run() — and both call self.start() on the same Thread object.

Repro

import threading
from celery.utils.timer2 import Timer

fails = 0
for trial in range(200):
    t = Timer(max_interval=10.0)
    bar = threading.Barrier(8)
    errs = []
    def w():
        try:
            bar.wait(timeout=30)
            t.ensure_started()
        except Exception as e:
            errs.append(repr(e))
    ths = [threading.Thread(target=w) for _ in range(8)]
    [th.start() for th in ths]
    [th.join() for th in ths]
    if errs:
        fails += 1
    t.stop()
print('trials with errors:', fails)

Result on CPython 3.14 (GIL build), main @ 9a1371c: 117/200 trials raise, a mix of:

  • RuntimeError: threads can only be started once in the losing caller, and
  • KeyError in threading __bootstrap_inner / _limbo noise plus two live run() loops over the one unsynchronized Schedule when both start() calls slip through.

Why it matters

There is one worker-wide shared instance (celery/worker/components.py:38, w.timer = _Timer(...)), and the task-message path schedules ETA callbacks on the shared consumer timer (celery/worker/strategy.py:120, call_at = consumer.timer.call_at → _do_enter → ensure_started). Any two threads first touching ETA scheduling at once (threads pool, embedded/app use of a shared Timer) can hit this: the loser gets RuntimeError out of task-message handling, and in the worst interleaving the timer thread itself is double-bootstrapped.

Suggested fix

Guard the check-and-start with the existing mutex — no current caller holds it at that point (_do_enter calls ensure_started() before acquiring self.mutex):

def ensure_started(self) -> None:
    with self.mutex:
        if not self.running and not self.is_alive():
            if self.on_start:
                self.on_start(self)
            self.start()

Found via formal modeling (TLA+ model of the check/start interleaving, model-checked and statically confirmed against the source with specfence) plus the threaded repro above.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions