Skip to content

5.7 regression: broker reconnect clears the shared worker timer, silently dropping soft/hard time limits of running tasks #10888

Closed

Description

@Kavin-Nithil

Checklist

  • I have verified that the issue exists against the main branch 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 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.

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

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)
        raise

hub.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 with hub.call_later only once, when the job is sent to a child process. Nothing re-arms them after the consumer restarts.
  • The prefork verify_process_alive timers, plus any timers that custom bootsteps register on worker.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_limit as a safety net.

Suggested fix

Either of these would work. I'm happy to send a PR.

  1. 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.
  2. Re-arm pool time limits on re-registration. In AsynPool.register_with_event_loop, for every job in self._cache that 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

  1. auvipy commented on Oct 18, 2026

    @auvipy
    Member

    so it is also reproduces on celery v5.7.0rc1 too?

  2. Kavin-Nithil commented on Oct 18, 2026

    @Kavin-Nithil
    ContributorAuthor

    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):

    Celery hub.timer.clear() in asynloop Hard time limit fires after reconnect
    5.6.2 (kombu 5.6.2) no yes
    5.6.3 yes (backport a989e8c of #10218) no
    5.7.0rc1 (kombu 5.7.0rc1) yes (c38600d) no
    main @ 0731c05 yes no

    On 5.7.0rc1:

    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
    

    On 5.6.2, before the change:

    timer entries before reconnect: 1
    asynloop raised: connection reset by broker -> consumer will reconnect
    timer entries after reconnect: 1
    hard time limit fired? ['HARD TIMEOUT -> kill child']
    

    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_messages entries #10218 was fixing) instead of clearing the shared worker timer. I'd add a regression test that pool time-limit entries survive an asynloop connection error, so the #10205 fix keeps working. Does that approach sound good to you?

  3. auvipy commented on Oct 18, 2026

    @auvipy
    Member

    PR welcome

  4. added this to the 5.7.0 milestone on Oct 18, 2026
  5. auvipy commented on Oct 22, 2026

    @auvipy
    Member

    @MehrazRumman is this fix also fix this #7844 ? can you verify?

  6. MehrazRumman commented on Oct 22, 2026

    @MehrazRumman
    Contributor

    @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:

    I checked it with the bootstep from #7844: worker.timer.call_repeatedly(...) registered at worker start, then a real Consumer.start() where asynloop hits a connection error, on_close() runs and the consumer reconnects:

    worker bootstep timer after the reconnect
    75ca8cc (just before #10901) removed from the timer, never fires again
    5138433 (#10901) still on the timer, keeps firing

    To answer the question in #7844: using worker.timer from 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.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions