Skip to content

Cancel only per-connection timer entries on broker reconnect instead of clearing the worker timer (#10888) - #10901

Merged
auvipy merged 7 commits into
celery:mainfrom
MehrazRumman:fix/asynloop-cancel-own-timer-entries
Oct 22, 2026
Merged

auvipy merged 7 commits into
celery:mainfrom
MehrazRumman:fix/asynloop-cancel-own-timer-entries

Conversation

@MehrazRumman

@MehrazRumman MehrazRumman commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Note: Before submitting this pull request, please review our contributing
guidelines
.

Description

Fixes #10888. Supersedes #10890. Related: #10218, #10892.

Problem

#10218 made asynloop call hub.timer.clear() when the event loop exits on a connection error, to drop stale periodic entries such as the transport's maybe_restore_messages. hub.timer is the worker-wide timer, though. Clearing it also removes the soft/hard time limits of tasks that keep running across the reconnect. Nothing registers those again, so a hung task is never killed after a broker connection drop. This affects 5.6.3 and the 5.7 pre-releases.

Fix

Cancel only the timer entries that belong to the connection that failed, and keep everything else on the timer.

  • Consumer.start() records the timer entries that exist before each connection attempt (timer_entries_before_start).
  • asynloop takes the entries added between that point and the start of the loop: the transport's periodic timers registered in Consumer.connect(), AMQP and event heartbeats, and the register_with_event_loop callbacks (including the pool's and autoscaler's, which asynloop registers again on every call). On a connection error it cancels only those, with timer.cancel(), instead of clearing the timer.
  • Entries added after the loop starts are kept. The same goes for entries that existed before the connection attempt. This covers time limits of running tasks, ETA and rate-limit entries, and timers registered once at worker start.
  • If asynloop is called without that record, it falls back to a snapshot taken when it starts.
  • AsynPool._create_timelimit_handlers now keeps its existing _tref_for_id mapping when the pool registers with the event loop again. A task that was running across the reconnect can then still cancel its time-limit entry when it finishes.
  • Graceful shutdown, WorkerShutdown and WorkerTerminate behave as before: nothing is cancelled.

Differences from #10890 / #10892

Tests

  • asynloop timer tests now use a real kombu.asynchronous.timer.Timer and cover:
    • per-connection entries are cancelled
    • entries don't pile up across reconnects
    • entries registered while connecting are cancelled
    • entries that existed before, or were added while running, survive
    • nothing is cancelled on graceful, worker or terminate shutdown
    • the original error is still raised when cleanup fails
  • Consumer: the timer entries are recorded before blueprint.start().
  • AsynPool: time-limit trefs survive registering with the event loop again.
  • The reproduction script from 5.7 regression: broker reconnect clears the shared worker timer, silently dropping soft/hard time limits of running tasks #10888 now fires the hard time limit after the reconnect.

asynloop cleared the shared worker timer on a connection error, which
also dropped the soft/hard time limits of tasks still running in the
pool; nothing registered them again, so hung tasks were never killed.

Record the timer entries before the consumer connects and cancel only
the entries added while connecting and starting the loop. Keep the
AsynPool tref mapping across re-registration so running tasks can
still cancel their time-limit entries.

Fixes celery#10888
@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.69%. Comparing base (75ca8cc) to head (1b442ba).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10901      +/-   ##
==========================================
+ Coverage   90.65%   90.69%   +0.03%     
==========================================
  Files         153      153              
  Lines       21477    21502      +25     
  Branches     2638     2644       +6     
==========================================
+ Hits        19471    19502      +31     
+ Misses       1694     1686       -8     
- Partials      312      314       +2     
Flag Coverage Δ
unittests 90.67% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@auvipy auvipy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this change covered by existing smoke or integration tests already?

@auvipy

auvipy commented Oct 20, 2026

Copy link
Copy Markdown
Member

@Kavin-Nithil would you mind reviewing this fix?

@Kavin-Nithil Kavin-Nithil left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was done well

  • The root cause is fixed. Only the entries added for the current connection are cancelled, instead of hub.timer.clear() wiping the shared worker timer. Hard time limits of running tasks now survive a reconnect, and #10218's protection against stale maybe_restore_messages entries still holds.
  • Good catch on _tref_for_id. Re-registering used to replace the WeakValueDictionary. Jobs started before the reconnect kept writing to the old dictionary, so the new on_timeout_cancel couldn't cancel their limits after they finished. Keeping the same dictionary fixes this, and test_create_timelimit_handlers_keeps_trefs_on_reregister covers it.
  • The snapshot is in the right place. Taking it in Consumer.start() before blueprint.start() means the entries the transport registers in connect() and events.py are counted as per-connection, which a snapshot inside asynloop would miss.
  • The tests are much stronger. They now use a real kombu Timer and check entry.canceled, instead of mock assertions on clear(). They cover repeated reconnects, existing entries and entries added while the loop runs, graceful shutdown, WorkerShutdown/WorkerTerminate, failing cancel/reset, and workers without a hub.
  • The comments are clear. The separate try blocks around reset and cancel are kept, and the comments explain why the timer must not be cleared.

What to note

  1. Errors before asynloop's try block leak entries. Entries are only cancelled in asynloop's except. If blueprint.start() fails after connect() but before the loop (Events, Mingle, Gossip, Tasks, Control), nothing is cancelled. The same happens if consumer.consume(), obj.on_ready() or did_start_ok() raises, since they run after registered_timer_entries is computed but before the try. On the next attempt those entries are in the "before" snapshot, so they are never cancelled. A flapping broker would pile up dead-connection entries, which is the #10218 symptom again. Previously the next clear() would have removed them. Could the cancel live next to the snapshot, in Consumer.start()'s except recoverable_errors branch before blueprint.restart()? A test for this path would help too.

  2. One failed cancel skips the rest. The try/except wraps the whole for loop, so if one hub.timer.cancel(entry) raises, the remaining entries stay live. Could the try go around each cancel? test_hub_timer_cancel_error_still_reraises_original currently asserts cancel is called exactly once, so it would need updating.

  3. The on_close comment is now out of date. In consumer.py on_close, the comment still says asynloop's hub.reset()/hub.timer.clear() clears the timer. That is no longer true.

MehrazRumman and others added 2 commits October 21, 2026 23:15
Address review feedback on celery#10901:

- If the connection fails after the transport registered its timer
  entries but before asynloop records them (a later bootstep, or
  consume()/on_ready()/did_start_ok() before the loop's try block),
  Consumer.start() now cancels every entry added since it started
  connecting. Otherwise those entries become part of the next attempt's
  snapshot and are never cancelled, so a flapping broker would pile them
  up again. Once asynloop has recorded its entries, only those are
  cancelled, so entries added while the loop ran (e.g. task time limits)
  are kept.
- Cancel each entry in its own try block, so one entry that fails to
  cancel no longer leaves the rest live.
- Update the Consumer.on_close() comment, which still said asynloop
  clears the timer.
@MehrazRumman

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews. I pushed 789ce40 to address them.

@Kavin-Nithil

  1. Entries registered before the loop's try block. asynloop now records the entries it registered on the consumer (timer_entries_registered). Consumer.start() cancels the failed connection's entries in its except recoverable_errors branch, right before blueprint.restart():

    • If asynloop recorded its entries, only those are cancelled, so entries added while the loop was running (e.g. task time limits) are kept.
    • If the connection failed before that (a later bootstep, or consume() / on_ready() / did_start_ok() before the try), it cancels everything added since the snapshot. The event loop wasn't running yet, so nothing else could have added entries in between.

    New tests cover both cases, plus resetting the record before each attempt.

  2. One failed cancel skipping the rest. Each entry is now cancelled in its own try (_cancel_timer_entries). test_hub_timer_cancel_error_does_not_skip_other_entries makes the first cancel fail and checks that the other entry is still cancelled.

  3. on_close comment. Updated. It no longer says asynloop clears the timer.

@auvipy: on smoke/integration coverage, nothing existing covers this combination:

  • t/smoke/tests/failover/test_broker_failover.py kills and reconnects the broker, but without a task running.
  • t/smoke/tests/test_worker.py::test_child_is_replaced_after_hard_time_limit covers the hard time limit, but without a reconnect.

The regression only shows when both happen together: a task running past its time limit while the broker connection drops and comes back. For now it is covered by the unit tests, which use a real kombu Timer, and by the reproduction script from #10888. I can add a smoke test in failover/ that starts a long task with a hard time limit, kills and restarts the broker, and checks the child is still killed, if you'd like that in this PR.

Locally: t/unit/worker and t/unit/concurrency pass (900 passed, 3 skipped), the 5 new tests fail without the change, and flake8/isort are clean.

@auvipy
auvipy merged commit 5138433 into celery:main Oct 22, 2026
22 of 23 checks passed
@MehrazRumman
MehrazRumman deleted the fix/asynloop-cancel-own-timer-entries branch October 22, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants