Skip to content

fix(gevent): cancel underlying Entry and pending greenlets in Timer - #11015

Merged
auvipy merged 8 commits into
celery:mainfrom
IsaacsonMango:fix/gevent-timer-cancel-entry
Nov 19, 2026
Merged

auvipy merged 8 commits into
celery:mainfrom
IsaacsonMango:fix/gevent-timer-cancel-entry

Conversation

@IsaacsonMango

@IsaacsonMango IsaacsonMango commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix celery.concurrency.gevent.Timer so that cancelling a timer handle (or clearing the timer queue) marks the underlying kombu.asynchronous.timer.Entry as cancelled and skips executing any already-queued greenlet for that Entry.

Fixes #11028 (also related to #10273 / #10280).

Root Cause

When a repeating timer is scheduled via Timer.call_repeatedly() (such as Heart.start() in celery/worker/heartbeat.py or Gossip.register_timer() in celery/worker/consumer/gossip.py):

  1. kombu.asynchronous.timer.Timer.call_repeatedly wraps the target in an Entry (tref) and reschedules the same Entry in its finally block (if not tref.canceled: self.enter_after(...)).
  2. celery.concurrency.gevent.Timer._enter returns the first spawned _Greenlet (g) rather than Entry, and schedules spawn_later(secs, entry) directly without checking entry.canceled.
  3. Previously, _Greenlet.cancel was aliased to Greenlet.kill. Once the first timer tick finished, calling timer.cancel(tref) or tref.cancel() only killed the already-completed first greenlet while leaving entry.canceled == False, so the queued next iteration ran entry() and continued rescheduling indefinitely.
  4. Similarly, Timer.clear() called queue.pop().kill() without marking g.entry.cancel(), allowing an active call_repeatedly callback interrupted mid-execution to reschedule itself in its finally block.

Changes

  • Guard spawn_later execution with Timer._apply_entry(entry) (if not entry.canceled: entry()), as suggested by @MehrazRumman.
  • Override _Greenlet.cancel to call self.entry.cancel() before self.kill(*args, **kwargs).
  • Update Timer.clear() to mark g.entry.cancel() for all queued greenlets before the queue.pop().kill() loop.
  • Add unit and real-gevent regression tests in t/unit/concurrency/test_gevent.py (all 9 real-gevent regression cases fail on main and pass with this change; smoke tests requiring Docker were not run locally).

@auvipy auvipy added this to the 5.7.x milestone Nov 4, 2026
@auvipy
auvipy self-requested a review November 4, 2026 14:20
@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.26%. Comparing base (71b0d90) to head (a6af187).
⚠️ Report is 1 commits behind head on main.

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           
Flag Coverage Δ
unittests 91.25% <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.

did you follow the contribution guideline and anti AI spamming guideline before opening this PR?

@IsaacsonMango

IsaacsonMango commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

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 celery -P gevent workers today (5.6.2 with Redis) where old Heart timers kept firing every 2s after broker reconnects. When I checked main, I saw #10273 / #10280 fixed the EventDispatcher side, but gevent.Timer still wasn't marking entry.canceled = True after the first greenlet exited, so I sent this PR directly.

Should I open a bug report issue with our reproduction script first, or is it okay to keep this open?

@MehrazRumman MehrazRumman 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.

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

Comment thread celery/concurrency/gevent.py Resolved
Comment thread celery/concurrency/gevent.py Resolved
@IsaacsonMango

Copy link
Copy Markdown
Contributor Author

@auvipy @MehrazRumman I've updated the PR using @MehrazRumman's _apply_entry fix, opened #11028 with the repro, and linked it in the description. All checks are green now, so please let me know if anything else is needed.

@auvipy

auvipy commented Nov 19, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy please have a look while you have time

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Looks good. I ran it at 75e268cc6 against main (971b0ef4b) and did not find a regression.

It fixes the leak end to end. A gevent worker on Redis with events on, with every broker connection cut 20 times:

After 20 reconnects main This PR
Heartbeat timers firing 9.6 a second 0.5 a second
Entries in the worker's timer queue 42 2
Heart objects still alive 22 2

On main each reconnect leaves one more Heart timer firing. With this PR the count stays where it started. The interval is the default 2 s, so 0.5 a second is one timer.

At the timer level I ran 25 scenarios on gevent 26.9.0 and 25.4.1, with the same results on both:

main This PR
Scenarios where a cancelled repeating timer keeps firing 12 0
Stop and start 20 times, as Heart does: ticks in the next 0.5 s 488 0
Re-arm 50 times, as Gossip does: timers still ticking 50 1
300 random sequences of schedule, cancel and clear: left a timer firing or queued 36 0

The new tests do their job. With celery/concurrency/gevent.py put back to main, 11 of 21 fail. I planted four bugs and each fails at least 2 tests: no check before running the entry, cancel() not marking the entry, clear() not marking entries, and cancel() not killing the pending greenlet. The real-gevent tests passed 20 times in a row.

Smaller things that can wait for a follow-up:

  • The description still lists the first design. It could say what the code does now, with the _apply_entry check.
  • The eventlet timer has the same bug. @MehrazRumman expected that from reading; I ran the same 25 scenarios on eventlet 0.41.3 and it fails the same ones as gevent on main. It is outside this PR.
  • cancel() still kills a callback that is in the middle of a timer's first run, which the timer other pools use (celery.utils.timer2) does not do. That is long-standing and the same on main. Details below, with a variant I tried.
cancel() and a callback that is already running
timer2 (thread) gevent, main and this PR
cancel() from outside while the first run is in its callback the callback finishes the callback is killed where it is
A callback cancels its own timer on its first run, then does more work the rest runs cut off at the cancel() call
The callback takes 0.2 s to clean up: how long cancel() takes 0.00 s 0.20 s

From the second run on, gevent behaves like timer2, because the handle is the first greenlet and that one is finished.

I tried a variant where cancel() marks the entry and kills the greenlet only if its callback has not started. It gives the timer2 column in all three rows, passes the other 22 scenarios the same as this PR, and gave the same results in the worker runs below. I'm not asking for it here.

Worker runs for regressions (gevent, Redis 7.0.15, kombu main)

Each gave the same result on main and on this PR:

  • 5 tasks with countdown=10 and no connection loss: each ran once, at 10.0 s.
  • 4 tasks with countdown=6, 2 revoked after 1 s: the revoked ones did not run, the others did.
  • 15 tasks at rate_limit='5/s': all ran once, the last about 4 s after the first.
  • Warm shutdown idle (2.6 s) and with a 3 s task running (4.2 s, the task finished), and a cold shutdown by SIGQUIT (0.7 s).
  • A task sent after the reconnects ran, in every run.

t/unit/concurrency, t/unit/worker and t/unit/events as tox runs them (python -bb): 1043 passed.

What I did not run
  • RabbitMQ, or any broker other than Redis.
  • eventlet in a worker. The eventlet result above is from the timer scenarios only.
  • The Docker smoke tests, and Python versions other than 3.13.

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.

gevent Timer.cancel() fails to stop recurring callbacks after the first tick

4 participants