Repository navigation
Description
Checklist
- I have verified that the issue exists against the
mainbranch of Celery. - This has already been asked to the discussions forum first.
- I have read the relevant section in the
contribution guide
on reporting bugs. - I have checked the issues list
for similar or identical bug reports. - I have checked the pull requests list
for existing proposed fixes. - I have checked the commit log
to find out if the bug was already fixed in the main branch. - I have included all related issues and possible duplicate issues
in this issue (If there are none, check this box anyway). - I have tried to reproduce the issue with pytest-celery and added the reproduction script below.
Mandatory Debugging Information
- I have included the output of
celery -A proj reportin the issue. - I have verified that the issue exists against the
mainbranch of Celery. - I have included the contents of
pip freezein the issue. - I have included all the versions of all the external dependencies required
to reproduce this bug.
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 workers pool.
- I have tried reproducing the issue with autoscaling, retries,
ETA/Countdown & 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
- Celery worker stops consuming Redis tasks after broker connection reset (Connection reset by peer) and does not recover automatically #10205 — worker stops consuming after broker connection reset (the problem fix: clear the timer while catch the exception #10218 fixed)
- fix: clear the timer while catch the exception #10218 — PR that added
hub.timer.clear()toasynloop's exception path (first released in v5.7.0a1) - Timers registered in worker boot are getting cancelled on consumer close #7844 — user timers cancelled when the consumer closes (older code path, same class of problem)
Possible Duplicates
- None
Environment & Settings
Celery version: 5.7.0rc1 (collider). The affected code is also in v5.7.0a1 and v5.7.0b1; 5.6.x is not affected.
Edit: I said 5.6.x wasn't affected, but #10218 was backported, so 5.6.3 is affected as well. 5.6.2 is the last good release.
celery report Output:
software -> celery:5.7.0rc1 (collider) kombu:5.7.0rc1 py:3.12.13
billiard:4.3.1 py-amqp:5.4.1
platform -> system:Linux arch:64bit, ELF
kernel version:6.8.0-138-generic imp:CPython
loader -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled
deprecated_settings: None
Steps to Reproduce
Required Dependencies
- Minimal Python Version: 3.12.13 (tested)
- Minimal Celery Version: 5.7.0a1
- Minimal Kombu Version: 5.7.0rc1 (tested)
- Minimal Broker Version: any (Redis / RabbitMQ). Triggered by any connection error caught by
asynloop - Minimal Result Backend Version: N/A
- Minimal OS and/or Kernel Version: Linux 6.8 (tested)
- Minimal Broker Client Version: N/A
- Minimal Result Backend Client Version: N/A
Python Packages
pip freeze Output:
-e git+https://github.com/celery/celery@0731c053b#egg=celery # 5.7.0rc1
amqp==5.4.1
billiard==4.3.1
click==8.5.0
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
kombu==5.7.0rc1
packaging==26.3
prompt-toolkit==3.0.53
python-dateutil==2.9.0.post0
six==1.17.0
tzdata==2026.4
tzlocal==5.4.4
vine==5.1.0
wcwidth==0.9.2
Other Dependencies
Details
N/A
Minimally Reproducible Test Case
This uses the real kombu Hub/Timer, the real AsynPool time-limit handlers and the real asynloop hitting a broker connection error. Only the pool object and the connection are mocked.
Details
import socket
import time
from unittest.mock import Mock
from kombu.asynchronous import Hub
from kombu.asynchronous.timer import Timer
from celery import bootsteps
from celery.concurrency.asynpool import AsynPool
from celery.worker.loops import asynloop
hub = Hub(Timer())
# AsynPool's own time-limit machinery, bound to a stub pool object
fired = []
pool = Mock(spec=AsynPool)
pool._cache = {'job-1': Mock(name='ApplyResult')}
pool.on_hard_timeout = lambda r: fired.append('HARD TIMEOUT -> kill child')
pool._on_hard_timeout = lambda job: AsynPool._on_hard_timeout(pool, job)
pool._on_soft_timeout = lambda *a: AsynPool._on_soft_timeout(pool, *a)
AsynPool._create_timelimit_handlers(pool, hub)
pool.on_timeout_set(Mock(_job='job-1'), None, 0.05) # hard time limit = 50ms
print('timer entries before reconnect:', len(hub.timer.queue))
# Consumer event loop hits a broker connection error
obj = Mock(restart_count=1, event_dispatcher=None, connection=Mock())
conn = Mock(connection_errors=(socket.error,))
conn.get_heartbeat_interval.return_value = 0
conn.transport.driver_type = 'redis'
def broken_loop():
raise socket.error('connection reset by broker')
yield
hub.create_loop = broken_loop
try:
asynloop(obj, conn, Mock(), Mock(state=bootsteps.RUN), hub,
Mock(prev=1, value=1), None, None)
except socket.error as exc:
print('asynloop raised:', exc, '-> consumer will reconnect')
print('timer entries after reconnect:', len(hub.timer.queue))
time.sleep(0.1)
for _ in range(3): # drive the timer as the restarted event loop would
hub.fire_timers(propagate=(Exception,))
print('hard time limit fired?', fired or 'NO - task can run forever')Expected Behavior
A task that is still executing in a pool child when the broker connection drops keeps its soft_time_limit / time_limit. By default worker_cancel_long_running_tasks_on_connection_loss=False, so such tasks deliberately keep running across the reconnect.
If you remove the asynloop(...) call from the script above, the hard limit fires as expected:
timer entries before reconnect: 1
hard time limit fired? ['HARD TIMEOUT -> kill child']
Actual Behavior
timer entries before reconnect: 1
asynloop raised: connection reset by broker -> consumer will reconnect
timer entries after reconnect: 0
hard time limit fired? NO - task can run forever
Root cause
celery/worker/loops.py (asynloop, exception path, added by #10218):
try:
hub.timer.clear()
except Exception as exc: # pylint: disable=broad-except
logger.exception(
'Error clearing hub timer after event loop: %r', exc)
raisehub.timer is the worker-wide timer (WorkController.timer). It is shared with:
AsynPool's per-job time limits (celery/concurrency/asynpool.py,_create_timelimit_handlers/on_timeout_set). These timers are armed withhub.call_lateronly once, when the job is sent to a child process. Nothing re-arms them after the consumer restarts.- The prefork
verify_process_alivetimers, plus any timers that custom bootsteps register onworker.timer.
The comment above the call says "Timers are re-registered by register_with_event_loop". That is true for the consumer/transport timers that #10218 targeted (e.g. maybe_restore_messages), but not for the pool's per-job timers.
Impact
- Every task that is running when a broker connection error occurs (Redis restart, RabbitMQ failover, network blip, heartbeat miss) silently loses both its soft and hard time limit.
- Hung tasks are never killed. They hold pool slots indefinitely, and a few reconnects can starve the worker.
- It is a silent regression in the 5.7 pre-releases. Nothing is logged, and users rely on
time_limitas a safety net.
Suggested fix
Either of these would work. I'm happy to send a PR.
- Cancel only the consumer's own timers instead of clearing the shared timer. Record the timer entries created during
consumer.register_with_event_loop/connection.transport.register_with_event_loop(the entries fix: clear the timer while catch the exception #10218 was concerned with) and cancel just those on the error path. - Re-arm pool time limits on re-registration. In
AsynPool.register_with_event_loop, for every job inself._cachethat has been accepted, re-arm the soft and hard timers with the remaining time (limit - (now - job._time_accepted)).
Add a regression test asserting that pool time-limit entries survive asynloop raising a connection error.
Activity
auvipy commentedon Oct 18, 2026
so it is also reproduces on celery v5.7.0rc1 too?
Kavin-Nithil commentedon Oct 18, 2026
Yes, it reproduces on v5.7.0rc1. I re-ran the repro from the issue against the released packages from PyPI, each in a clean virtualenv (Python 3.12.13):
hub.timer.clear()inasynloopmain@ 0731c05On 5.7.0rc1:
On 5.6.2, before the change:
One correction to my original report: I said 5.6.x wasn't affected, but #10218 was backported, so 5.6.3 is affected as well. 5.6.2 is the last good release.
I'd be happy to open a PR before 5.7.0 final. My plan is to cancel only the timer entries the consumer/transport registers (the
maybe_restore_messagesentries #10218 was fixing) instead of clearing the shared worker timer. I'd add a regression test that pool time-limit entries survive anasynloopconnection error, so the #10205 fix keeps working. Does that approach sound good to you?auvipy commentedon Oct 18, 2026
PR welcome
Cancel only per-connection timer entries on broker reconnect instead …
auvipy commentedon Oct 22, 2026
@MehrazRumman is this fix also fix this #7844 ? can you verify?
MehrazRumman commentedon Oct 22, 2026
@auvipy Yes. #7844 is the same problem for timers that a worker bootstep registers on
worker.timer, and #10901 fixes it on main.How it went:
Consumer.on_close(), which calledself.timer.clear()on every reconnect. Since the consumer and the worker share the same timer when the event loop is used, that wiped timers registered at worker start. Fix: Broker heartbeats not sent during graceful shutdown #9986 removed that call, so 5.6.1 and 5.6.2 were not affected.hub.timer.clear()inasynloop's error path. That's in 5.6.3 and the 5.7 pre-releases (5.7.0a1 to 5.7.0rc1).Consumer.start()begins connecting, so anything registered at worker start is kept.I checked it with the bootstep from #7844:
worker.timer.call_repeatedly(...)registered at worker start, then a realConsumer.start()whereasynloophits a connection error,on_close()runs and the consumer reconnects:To answer the question in #7844: using
worker.timerfrom a worker bootstep is right. It is the same timer the consumer uses with the event loop, and a reconnect no longer removes entries registered on it before the consumer starts. #7844 can be closed once #10901 is in a release.