Skip to content

fix(events): stop leaking exceptions and cancel stale Heart timers - #10280

Merged
auvipy merged 2 commits into
celery:mainfrom
Song-Junho97:fix/events-dispatcher-buffer-and-lifecycle
Apr 23, 2026
Merged

auvipy merged 2 commits into
celery:mainfrom
Song-Junho97:fix/events-dispatcher-buffer-and-lifecycle

Conversation

@Song-Junho97

Copy link
Copy Markdown
Contributor

Description

Follow-up to #10277 addressing the two remaining review comments on that PR. Both changes target root causes of the memory leak reported in #10273 — the previous PR only closed the immediate symptom via an early return in
_publish().

1. EventDispatcher._outbound_buffer no longer retains the exception object.

_publish() used to buffer (event, routing_key, exc) when a publish failed under buffer_while_offline. The retained exception pinned its traceback and ~6 local frames per failure — for any long-lived dispatcher hitting
repeated publish errors (network blips, broker pauses, etc.) this was the real source of the memory leak. flush() already discards the exception via _, so the entry is now (event, routing_key) and flush() unpacking
is updated accordingly. extend_buffer() is shape-agnostic so no change is needed there.

2. Events._close() now calls dispatcher.disable() instead of dispatcher.close().

close() only nulls the producer; it does not fire on_disabled. Heart registers its timer-cancel callback on on_disabled, so under the old code the stale heartbeat tref kept firing against a dead dispatcher after
every broker reconnect. disable() invokes the callback chain (enabled = False → close() → callbacks) while still performing the producer cleanup, so the stale heartbeat is cancelled at its source rather than merely
becoming a no-op publish. dispatcher.close() has no external callers outside this module, so there is no compatibility impact.

Added regression tests:

  • test_buffered_entries_do_not_retain_exception — asserts _outbound_buffer entries are 2-tuples with no exception reference.
  • test_flush_replays_buffered_entries_after_tuple_shape_change — guards flush() unpack against regressions.
  • test_close_connection__heart_shutdown (existing) updated to assert disable() is called on the dispatcher.

Verified against the reproduction in #10273 (RabbitMQ paused 20 s to force reconnect, gc.get_objects() delta measured after):

Wait Delta Dispatcher #2 state
30 s AE=+1 frames=+5 enabled=False
90 s AE=+1 frames=+5 enabled=False

The delta is constant regardless of wait time — no linear growth. The residual +1/+5 comes from an unrelated AMQP heartbeat path (celery/worker/loops.py:40 tick() → kombu.connection.Connection.heartbeat_check()) firing
once during the reconnection transition; that is a distinct issue outside the scope of #10273. Dispatcher #2: enabled=False in the measurement output confirms on_disabled now fires on reconnect — previously enabled
stayed True because close() never flipped it.

See: #10273, #10277

Follow-up to celery#10277 addressing the two remaining review comments on
that PR. Both failures are symptoms of the same post-reconnect lifecycle
gap described in celery#10273.

* _outbound_buffer no longer retains the exception object

  _publish() used to buffer (event, routing_key, exc) when a
  publish failed under buffer_while_offline. The exception pinned
  its traceback and ~6 local frames per failure, which — for any
  long-lived dispatcher that hits repeated publish errors (network
  blips, broker pauses, etc.) — was the real memory leak reported in
  celery#10273. flush() already discarded the exception via _ so the
  entry is now 2-tuple only. extend_buffer is shape-agnostic.

* Events._close() now calls dispatcher.disable() instead of
  dispatcher.close()

  close() only nulls the producer; it does not fire on_disabled.
  Heart registers its timer-cancel callback on on_disabled, so
  under the old code the stale heartbeat tref kept firing against a
  dead dispatcher after every broker reconnect. disable() invokes
  the callback chain while still performing the producer cleanup, so
  the stale heartbeat is cancelled at the source rather than merely
  becoming a no-op publish.

Tests
-----
* test_buffered_entries_do_not_retain_exception — asserts the
  buffer entry is 2-tuple with no exception reference.
* test_flush_replays_buffered_entries_after_tuple_shape_change —
  guards the flush() unpack against regressions.
* Updated test_close_connection__heart_shutdown to assert
  disable() is called on the dispatcher.

Verified against the reproduction in celery#10273: the residual
AE=+1 frames=+5 is constant (30 s and 90 s waits produce the same
deltas) and originates from the unrelated AMQP heartbeat path in
celery/worker/loops.py — the EventDispatcher-driven leak is gone.
Dispatcher celery#2: enabled=False in the measurement output confirms
that on_disabled now fires on reconnect.

See: celery#10273, celery#10277

Co-authored-by: JaeHyuckSa <[email protected]>
@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.28%. Comparing base (7db0d78) to head (2bfc168).
⚠️ Report is 64 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10280   +/-   ##
=======================================
  Coverage   88.28%   88.28%           
=======================================
  Files         153      153           
  Lines       19678    19678           
  Branches     2270     2270           
=======================================
  Hits        17373    17373           
  Misses       2005     2005           
  Partials      300      300           
Flag Coverage Δ
unittests 88.26% <100.00%> (ø)

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 added this to the 5.7.0 milestone Apr 23, 2026

Copilot AI 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.

Pull request overview

This PR follows up on #10277 to eliminate the root causes of the _outbound_buffer-related memory leak in EventDispatcher and to ensure heartbeat timers are properly cancelled when an event dispatcher is shut down during reconnects.

Changes:

  • Stop retaining exception objects in EventDispatcher._outbound_buffer by buffering only (event, routing_key).
  • Update EventDispatcher.flush() to replay buffered entries using the new 2-tuple shape.
  • Ensure worker event dispatcher shutdown triggers on_disabled callbacks (for heartbeat timer cancellation) by calling dispatcher.disable() instead of dispatcher.close(), plus add/adjust unit tests.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
celery/events/dispatcher.py Changes buffering to avoid retaining exception objects; updates flush unpacking accordingly.
celery/worker/consumer/events.py Uses dispatcher.disable() during close to fire on_disabled callbacks (e.g., Heart timer cancellation).
t/unit/events/test_events.py Adds regression tests for buffer tuple shape and flush replay after the shape change.
t/unit/worker/test_worker.py Updates existing shutdown test to assert disable() is called on the dispatcher.

@auvipy
auvipy merged commit 8b4b29c into celery:main Apr 23, 2026
336 checks passed
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.

3 participants