Repository navigation
fix(gevent): cancel underlying Entry and pending greenlets in Timer - #11015
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #11015 +/- ##
=======================================
Coverage 91.26% 91.26%
=======================================
Files 153 153
Lines 21790 21798 +8
Branches 2702 2704 +2
=======================================
+ Hits 19887 19895 +8
Misses 1603 1603
Partials 300 300
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
auvipy
left a comment
There was a problem hiding this comment.
did you follow the contribution guideline and anti AI spamming guideline before opening this PR?
|
Sorry, my bad. I didn't read #10932 before opening this and skipped creating an issue first. We tracked down a 14GB memory leak on our production Should I open a bug report issue with our reproduction script first, or is it okay to keep this open? |
MehrazRumman
left a comment
There was a problem hiding this comment.
I reproduced the bug on main with gevent 26.9.0, using the script below. It has no code from this PR. A call_repeatedly(0.05, ...) timer ticks three times, then gets cancelled the way Heart.stop() and Gossip cancel theirs:
| Cancel path | Ticks in the next 0.3 s on main |
|---|---|
timer.cancel(tref) |
6, with tref.entry.canceled still False |
tref.cancel() |
5 |
So the timer keeps running after it is cancelled, and the cause is the one the description gives: cancel() kills the first greenlet, which has already finished, and the Entry is never marked as cancelled.
The fix could be much smaller, inline. The script below also runs that smaller version. Separately, eventlet's Timer looks like it has the same shape: _entry_exit() only cancels the Entry when the greenlet was killed, and cancel(tref) on a finished first greenlet does nothing. I couldn't run it because eventlet isn't installed here, so that's from reading the code.
On your question to auvipy: Agents.md asks for an issue and a maintainer's go-ahead before a PR. The script below could serve as the reproduction in that issue.
Reproduction on main
from gevent import monkey; monkey.patch_all()
import gevent
from celery.concurrency.gevent import Timer
t = Timer()
ticks = []
tref = t.call_repeatedly(0.05, lambda: ticks.append(1))
gevent.sleep(0.18) # a few ticks, so tref, the first greenlet, has finished
before = len(ticks)
t.cancel(tref) # what Heart.stop() does
gevent.sleep(0.3)
print(len(ticks) - before, tref.entry.canceled) # main: 6 False|
@auvipy @MehrazRumman I've updated the PR using @MehrazRumman's |
|
@ChristianMurphy please have a look while you have time |
|
Looks good. I ran it at It fixes the leak end to end. A gevent worker on Redis with events on, with every broker connection cut 20 times:
On main each reconnect leaves one more At the timer level I ran 25 scenarios on gevent 26.9.0 and 25.4.1, with the same results on both:
The new tests do their job. With Smaller things that can wait for a follow-up:
cancel() and a callback that is already running
From the second run on, gevent behaves like I tried a variant where Worker runs for regressions (gevent, Redis 7.0.15, kombu main)Each gave the same result on main and on this PR:
What I did not run
|
Summary
Fix
celery.concurrency.gevent.Timerso that cancelling a timer handle (or clearing the timer queue) marks the underlyingkombu.asynchronous.timer.Entryas cancelled and skips executing any already-queued greenlet for thatEntry.Fixes #11028 (also related to #10273 / #10280).
Root Cause
When a repeating timer is scheduled via
Timer.call_repeatedly()(such asHeart.start()incelery/worker/heartbeat.pyorGossip.register_timer()incelery/worker/consumer/gossip.py):kombu.asynchronous.timer.Timer.call_repeatedlywraps the target in anEntry(tref) and reschedules the sameEntryin itsfinallyblock (if not tref.canceled: self.enter_after(...)).celery.concurrency.gevent.Timer._enterreturns the first spawned_Greenlet(g) rather thanEntry, and schedulesspawn_later(secs, entry)directly without checkingentry.canceled._Greenlet.cancelwas aliased toGreenlet.kill. Once the first timer tick finished, callingtimer.cancel(tref)ortref.cancel()only killed the already-completed first greenlet while leavingentry.canceled == False, so the queued next iteration ranentry()and continued rescheduling indefinitely.Timer.clear()calledqueue.pop().kill()without markingg.entry.cancel(), allowing an activecall_repeatedlycallback interrupted mid-execution to reschedule itself in itsfinallyblock.Changes
spawn_laterexecution withTimer._apply_entry(entry)(if not entry.canceled: entry()), as suggested by @MehrazRumman._Greenlet.cancelto callself.entry.cancel()beforeself.kill(*args, **kwargs).Timer.clear()to markg.entry.cancel()for all queued greenlets before thequeue.pop().kill()loop.t/unit/concurrency/test_gevent.py(all 9 real-gevent regression cases fail onmainand pass with this change; smoke tests requiring Docker were not run locally).