Skip to content

Race: LimitedSet.purge reads heap[0] while a concurrent pop empties it (IndexError) #11141

Open

Description

@ashitpatel

Checklist

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required to reproduce this bug (see pip freeze; no broker involved).

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None

Environment & Settings

Celery version: 5.7.0 (main @ a2d470f)

celery report Output:

software -> celery:5.7.0 (collider) kombu:5.7.0 py:3.14.6
            billiard:4.3.2 memory:N/A
platform -> system:Darwin arch:64bit, Mach-O
            kernel version:24.5.0 imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:memory results:disabled

Steps to Reproduce

LimitedSet.purge (celery/utils/collections.py) peeks at the heap without holding any lock, while other threads add/pop concurrently:

if self.expires:
    while len(self._data) > self.minlen >= 0:
        entry = self._heap[0]   # <-- concurrent pop can empty the heap first

A pop landing between the length check and the index raises IndexError: list index out of range out of purge. LimitedSet backs worker-global structures (e.g. revoked tasks) touched from multiple threads, and none of its methods take a lock.

Reproducer (stress with adders and purger/poppers; uses only celery.utils.collections):

import threading, time
from celery.utils.collections import LimitedSet

s = LimitedSet(maxlen=50, expires=0.05, minlen=0)
stop = threading.Event()
errs = []

def adder():
    i = 0
    while not stop.is_set():
        s.add(f'k{i}')
        i += 1

def purger():
    while not stop.is_set():
        try:
            s.purge()
            if s._data:
                s.pop()
        except IndexError as e:
            errs.append(repr(e))
            return

ts = [threading.Thread(target=adder) for _ in range(2)] + \
     [threading.Thread(target=purger) for _ in range(2)]
[t.start() for t in ts]
time.sleep(8)
stop.set()
[t.join(10) for t in ts]
assert not errs, errs

Fails within seconds: IndexError: list index out of range.

Suggested direction: lock around the check-and-index in purge (and audit the other unlocked heap/data compound ops in the class).

Required Dependencies

  • Minimal Python Version: 3.14 (tested); race is a code-shape issue, not version-specific
  • Minimal Celery Version: 5.7.0 / main @ a2d470f
  • Minimal Kombu Version: N/A (celery-only code path)
  • Minimal Broker Version: N/A (no broker involved; memory:// used only for celery report)
  • Minimal Result Backend Version: N/A
  • Minimal OS and/or Kernel Version: N/A (Darwin 24.5.0 tested)
  • Minimal Broker Client Version: N/A
  • Minimal Result Backend Client Version: N/A

Python Packages

pip freeze Output:

amqp==5.4.2
billiard==4.3.2
-e git+https://github.com/celery/celery.git@a2d470f198444db889608537a5792216b447429e#egg=celery
click==8.5.1
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
-e git+https://github.com/celery/kombu.git@4cadf8b9606f4023f75e7281447a320809834d12#egg=kombu
prompt_toolkit==3.0.53
python-dateutil==4.0.0
typing_extensions==4.16.0
tzdata==2026.6
tzlocal==5.4.5
vine==5.1.0
wcwidth==0.9.4

Activity

  1. FullStraing commented on Nov 21, 2026

    @FullStraing

    I reproduced this on current main (a2d470f): the reproducer in the issue raises IndexError from purge() at celery/utils/collections.py (entry = self._heap[0]) within seconds, both from the purger threads and via add() -> purge().

    I have a fix ready: guard LimitedSet's mutating methods (add/update/discard/clear/purge/pop, plus as_dict and iteration) with a threading.RLock on the instance, via a small @_synchronized decorator — the lock is re-entrant since the methods call each other (add calls purge, purge calls pop). I also added a regression test running the issue's threaded reproducer, which fails on main and passes with the fix; the full t/unit/utils/test_collections.py suite (98 tests) passes and flake8 is clean. This fix was prepared with AI assistance, and I verified it as described above.

    Before opening a PR (per the repo's PR template, AI-based PRs should ask first): is this approach welcome, and could a maintainer confirm the issue? Happy to adjust the approach (e.g. a narrower fix) if you'd prefer.

  2. ashitpatel commented on Nov 21, 2026

    @ashitpatel
    Author

    Thanks for verifying and putting together a fix! Supporting evidence for the broad approach: I found a second race in the same class (clear() emptying the heap while add() stores to _data, stranding a live item off it), so guarding all the mutators looks right to me rather than just the purge path.

  3. auvipy commented on Nov 22, 2026

    @auvipy
    Member

    @FullStraing you can come with a PR

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