Skip to content

fix(events): skip publish when producer is None to stop memory leak after broker reconnect - #10277

Merged
auvipy merged 2 commits into
celery:mainfrom
Song-Junho97:fix/#10273-gevent-memory-leaks
Apr 22, 2026
Merged

auvipy merged 2 commits into
celery:mainfrom
Song-Junho97:fix/#10273-gevent-memory-leaks

Conversation

@Song-Junho97

@Song-Junho97 Song-Junho97 commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #10273. Regression of #5047.

Description

After a broker reconnect the previous EventDispatcher is closed (producer set to None) but
stale timers — notably Heart's heartbeat timer, wired up via on_enabled on the old dispatcher
— keep calling its _publish(). Each call raised an AttributeError: 'NoneType' object has no attribute 'publish' that _publish() caught under buffer_while_offline=True and appended to
_outbound_buffer together with the exception object. The retained exception pinned its
traceback and frame locals, leaking ~6 frame objects and a full AttributeError per failed
publish (~every 2s, the default heartbeat interval).

A long-lived gevent worker accumulated hundreds of MiB of unreclaimable memory after a single
broker blip. Production measurement cited in #10273 (Python 3.14, Celery 5.6.3, gevent pool, 3.8
days after one reconnect):

99,138 AttributeError objects (never GC'd)
99,191 traceback objects (1 per exception)                                                       
594,908 frame objects (~6 per exception)
_outbound_buffer: 99,139 events accumulated                                                      
Process RSS: 677 MiB (started at 192 MiB)                                                        

After a broker reconnect the previous EventDispatcher is closed
(producer set to None) but stale timers — notably Heart —
keep calling its _publish(). The call raised an AttributeError
on None.publish which was caught and appended to
_outbound_buffer together with the exception; the retained
exception pinned its traceback and frame locals, leaking ~6 frames
and a full AttributeError per failed publish (~every 2s). A
long-lived gevent worker accumulated hundreds of MiB of unreclaimable
memory after a single broker blip.

Short-circuit _publish() when producer is None so the no-op
call path raises nothing and does not grow the buffer. Verified
against the reproduction in celery#10273: the linear AE/frame growth is
gone (delta stays constant as wait time increases).

Fixes celery#10273

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

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

Fixes a post-reconnect memory leak in EventDispatcher by preventing publishes when the dispatcher’s producer has been cleared (set to None) on close, avoiding repeated buffering of AttributeError exceptions.

Changes:

  • Add an early return in EventDispatcher._publish() when producer is None.
  • Add a unit test asserting no buffering occurs when attempting to publish with producer=None.
  • Add a contributor entry.

Reviewed changes

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

File Description
celery/events/dispatcher.py Skip _publish() work when producer is None, preventing exception buffering and associated memory retention.
t/unit/events/test_events.py Add regression test coverage for producer-None publish behavior.
CONTRIBUTORS.txt Add contributor attribution.

Comment thread t/unit/events/test_events.py Resolved
Comment thread celery/events/dispatcher.py Resolved
Comment thread celery/events/dispatcher.py Resolved
@codecov

codecov Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.28%. Comparing base (b313b64) to head (80dc00e).
⚠️ Report is 66 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10277   +/-   ##
=======================================
  Coverage   88.28%   88.28%           
=======================================
  Files         153      153           
  Lines       19676    19678    +2     
  Branches     2269     2270    +1     
=======================================
+ Hits        17371    17373    +2     
  Misses       2005     2005           
  Partials      300      300           
Flag Coverage Δ
unittests 88.26% <100.00%> (+<0.01%) ⬆️

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.

can you please cross check the suggestion?

Song-Junho97 added a commit to Song-Junho97/celery that referenced this pull request Apr 22, 2026
…test

Address review feedback on PR celery#10277: the regression test called the
private ``_publish()`` directly, which doesn't guard against future
refactors of how ``send()`` reaches ``_publish()``. Switch to the
public ``send()`` path under the actual bug shape — ``enabled=True``
with ``producer=None`` after a ``close()`` during broker reconnect.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Song-Junho97

Song-Junho97 commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the cross-check ping @auvipy — addressed inline:

  • Comment 1 (public send() path): accepted, test updated in 80dc00e
  • Comment 2 (stop storing exc in _outbound_buffer): deliberately scoped out; happy to fold in or follow up — your call
  • Comment 3 (lifecycle / Heart callback binding): requires broader changes to the bootstep and Heart's eventer rebinding, suggest a separate PR

…test

Address review feedback on PR celery#10277: the regression test called the
private _publish() directly, which doesn't guard against future
refactors of how send() reaches _publish(). Switch to the
public send() path under the actual bug shape — enabled=True
with producer=None after a close() during broker reconnect.

Co-authored-by: JaeHyuckSa <[email protected]>
@Song-Junho97
Song-Junho97 force-pushed the fix/#10273-gevent-memory-leaks branch from 0b8055b to 80dc00e Compare April 22, 2026 07:05
@auvipy auvipy added this to the 5.7.0 milestone Apr 22, 2026
@auvipy
auvipy merged commit acce2ac into celery:main Apr 22, 2026
336 checks passed
@auvipy

auvipy commented Apr 22, 2026

Copy link
Copy Markdown
Member

I will be looking forward for the remaining changes in separate PR

auvipy added a commit that referenced this pull request Apr 23, 2026
…10280)

Follow-up to #10277 addressing the two remaining review comments on
that PR. Both failures are symptoms of the same post-reconnect lifecycle
gap described in #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
  #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 #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 #2: enabled=False in the measurement output confirms
that on_disabled now fires on reconnect.

See: #10273, #10277

Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
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.

EventDispatcher leaks memory via _outbound_buffer after broker reconnection (gevent pool)

3 participants