EventDispatcher.close() releases a mutex held by a publishing thread
The template’s Discussions and pytest-celery reproduction boxes remain unchecked: I have not posted a discussion or run the reproducer against main through pytest-celery. The standalone reproducer below was run against the current main dispatcher code.
Checklist
- I have verified that the issue exists against the
mainbranch of Celery. - This has already been asked to the [discussions forum](https://github.com/celery/celery/discussions) first.
- I have read the relevant section in the [contribution guide](https://docs.celeryq.dev/en/main/contributing.html#other-bugs) on reporting bugs.
- I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22) for similar or identical bug reports.
- I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22) for existing proposed fixes.
- I have checked the [commit log](https://github.com/celery/celery/commits/main) to find out if the bug was already fixed in the main branch.
- I have included related issues and possible duplicates below.
- I have tried to reproduce the issue with [pytest-celery](https://docs.celeryq.dev/projects/pytest-celery/en/latest/userguide/celery-bug-report.html) and added the reproduction script below.
Mandatory Debugging Information
- I have included
celery reportoutput below. The standalone reproducer has noprojapplication. - I have verified that the issue exists against the
mainbranch of Celery. - I have included the contents of
pip freezebelow. - I have included the versions of external dependencies required to reproduce this bug. No external broker or result backend is required.
Optional Debugging Information
- I have tried reproducing the issue on more than one Python version and/or implementation.
- I have tried reproducing the issue on more than one message broker and/or result backend.
- I have tried reproducing the issue on more than one version of the message broker and/or result backend.
- I have tried reproducing the issue on more than one operating system.
- I have tried reproducing the issue on more than one worker pool.
- I have tried reproducing the issue with autoscaling, retries, ETA/Countdown and rate limits disabled.
- I have tried reproducing the issue after downgrading and/or upgrading Celery and its dependencies.
Related Issues and Possible Duplicates
Related Issues
- [#10273](https://github.com/celery/celery/issues/10273) concerns a different
EventDispatcherproblem after broker reconnection. - [PR #7690](https://github.com/celery/celery/pull/7690) is earlier work concerning Celery locks and deadlocks; it does not address this cross-thread release.
Possible Duplicates
- None found.
Environment & Settings
Celery version: main at commit [57cfb4629bbf919e24ff85f33d1eca038c973f4d](https://github.com/celery/celery/commit/57cfb4629bbf919e24ff85f33d1eca038c973f4d), reporting version 5.6.3.
celery report Output:
software -> celery:5.6.3 (recovery) kombu:5.7.0a1 py:3.12.3
billiard:4.3.0 py-amqp:5.4.0
platform -> system:Linux arch:64bit, ELF
kernel version:6.6.87.2-microsoft-standard-WSL2 imp:CPython
loader -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled
deprecated_settings: NoneThe report shows CLI defaults; the reproducer below explicitly uses memory://.
Steps to Reproduce
Required Dependencies
- Minimal Python Version: reproduced with Python 3.12.3.
- Minimal Celery Version: reproduced against the
maincommit above. - Minimal Kombu Version: reproduced with Kombu 5.7.0a1.
- Minimal Broker Version: uses the in-memory transport.
- Minimal Result Backend Version: N/A.
- Minimal OS and/or Kernel Version: Linux/WSL2 kernel 6.6.87.2.
- Minimal Broker Client Version: N/A.
- Minimal Result Backend Client Version: N/A.
Python Packages
pip freeze Output:
alabaster==1.0.0
amqp==5.4.0
annotated-types==0.8.0
ast_serialize==0.11.2
attrs==26.1.0
azure-core==1.41.0
azure-identity==1.25.3
azure-storage-blob==12.30.1
babel==2.18.0
bandit==1.9.4
billiard==4.3.0
boto3==1.43.104
botocore==1.43.104
bump2version==1.0.1
bumpversion==0.6.0
cachetools==7.2.0
celery==5.6.3
certifi==2026.7.22
cffi==2.1.1
cfgv==3.5.0
charset-normalizer==3.5.1
click==8.5.0
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.0
colorama==0.4.6
coverage==7.16.2
cryptography==50.0.1
debugpy==1.8.22
distlib==0.4.3
dnspython==2.8.0
docker==7.2.0
docutils==0.22.4
filelock==4.0.6
flake8==7.3.0
flake8-docstrings==1.7.0
gevent==26.8.0
google-api-core==2.39.0
google-auth==2.59.0
google-cloud-core==2.7.0
google-cloud-firestore==2.30.0
google-cloud-storage==3.15.0
google-crc32c==1.9.0
google-resumable-media==2.10.2
googleapis-common-protos==1.75.4
greenlet==3.5.6
grpcio==1.84.0
grpcio-status==1.84.0
identify==2.6.20
idna==3.20
imagesize==2.0.1
iniconfig==2.3.0
isodate==0.7.2
Jinja2==3.1.6
jmespath==1.1.0
kombu==5.7.0a1
librt==0.16.0
markdown-it-py==4.2.0
MarkupSafe==3.0.3
mccabe==0.7.0
mdurl==0.1.2
mock==5.2.0
moto==5.2.3
msal==1.39.0
msal-extensions==1.3.1
msgpack==1.2.2
mypy==2.3.1
mypy_extensions==1.1.0
nodeenv==1.11.0
opentelemetry-api==1.45.0
packaging==26.3
pathspec==1.1.1
platformdirs==4.12.1
pluggy==1.6.0
pre_commit==4.6.2
prompt_toolkit==3.0.53
proto-plus==1.28.4
protobuf==7.36.2
psutil==7.2.2
pyasn1==0.6.4
pyasn1_modules==0.4.2
pycodestyle==2.14.0
pycparser==3.0
pycurl==7.48.0
pydantic==2.13.5
pydantic_core==2.46.5
pydocstyle==6.3.0
pyflakes==3.4.0
Pygments==2.21.0
PyJWT==2.15.1
pymongo==4.18.0
pyperclip==1.11.0
pyproject-api==1.11.2
pytest==9.1.1
pytest-celery==1.3.0
pytest-click==1.1.0
pytest-cov==7.1.0
pytest-order==1.5.0
pytest-rerunfailures==16.6.1
pytest-subtests==0.15.0
pytest-timeout==2.4.0
pytest_docker_tools==3.1.10
python-dateutil==2.9.0.post0
python-discovery==1.6.1
python-memcached==1.62
PyYAML==6.0.3
redis==8.1.0
requests==2.34.2
responses==0.26.3
rich==15.0.0
roman-numerals==4.1.0
s3transfer==0.19.2
setuptools==84.0.0
six==1.17.0
snowballstemmer==3.1.1
Sphinx==9.1.0
sphinx-celery==2.1.3
sphinx-click==6.2.0
sphinx-testing==1.0.1
sphinx2rst==1.1.0
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.0
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
SQLAlchemy==2.0.54
stevedore==5.9.1
tenacity==9.1.4
tomli_w==1.2.0
tox==4.64.3
typing-inspection==0.4.4
typing_extensions==4.16.0
tzdata==2026.4
tzlocal==5.4.4
urllib3==1.26.20
vine==5.1.0
virtualenv==21.13.0
wcwidth==0.9.1
Werkzeug==3.1.9
wheel==0.48.0
xmltodict==1.0.4
zope.event==6.2
zope.interface==8.6Other Dependencies
N/A. No external broker, backend or worker process is required.
Minimally Reproducible Test Case
Run this from a checkout of Celery main:
from threading import Event, Thread
from celery import Celery
app = Celery("dispatcher_close_race", broker="memory://")
publish_started = Event()
finish_publish = Event()
close_started = Event()
close_finished = Event()
errors = []
with app.connection_for_write() as connection:
dispatcher = app.events.Dispatcher(
connection, buffer_while_offline=False
)
actual_publish = dispatcher.producer.publish
def blocking_publish(*args, **kwargs):
publish_started.set()
if not finish_publish.wait(5):
raise TimeoutError("publish was not allowed to finish")
return actual_publish(*args, **kwargs)
dispatcher.producer.publish = blocking_publish
def send():
try:
dispatcher.send("task-sent")
except Exception as exc:
errors.append(f"{type(exc).__name__}: {exc}")
def close():
close_started.set()
try:
dispatcher.close()
finally:
close_finished.set()
publisher = Thread(target=send)
closer = Thread(target=close)
publisher.start()
assert publish_started.wait(5)
try:
closer.start()
assert close_started.wait(5)
closed_before_publish = close_finished.wait(0.2)
finally:
finish_publish.set()
publisher.join(5)
closer.join(5)
assert not publisher.is_alive() and not closer.is_alive()
print("close returned before publish finished:", closed_before_publish)
print("publisher errors:", errors)On main, this prints:
close returned before publish finished: True
publisher errors: ['RuntimeError: release unlocked lock']Expected Behavior
close() should wait for an in-flight event publication to leave the dispatcher’s critical section. The publishing thread should finish without a lock error; only then should close() clear the producer and return.
Actual Behavior
EventDispatcher.close() on main calls self.mutex.release() whenever the primitive lock is locked, even when another thread owns the ongoing publication. close() returns and clears producer while that publication is still in progress. When the publishing thread exits with self.mutex:, it raises:
Traceback (most recent call last):
File "<stdin>", line 24, in send
File "upstream/main:celery/events/dispatcher.py", line 197, in send
return self.publish(type, fields, self.producer, blind=blind,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "upstream/main:celery/events/dispatcher.py", line 138, in publish
with self.mutex:
RuntimeError: release unlocked lockThe interleaving was reproduced using the dispatcher source from main at the commit identified above.
Source: celery/celery