Skip to content

Fix gevent pool acking a late-ack task killed on cold shutdown - #11134

Merged
auvipy merged 8 commits into
celery:mainfrom
tony1233200:fix/11086-gevent-cold-shutdown-ack
Nov 28, 2026
Merged

auvipy merged 8 commits into
celery:mainfrom
tony1233200:fix/11086-gevent-cold-shutdown-ack

Conversation

@tony1233200

@tony1233200 tony1233200 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #11086

Summary

On the gevent pool, a cold shutdown (SIGQUIT / double SIGINT) acknowledged
the message of a late-ack task it interrupted, so the task was lost. On
5.4.0 and on prefork the message goes back to the queue and runs again.
The same fix also covers revoke(terminate=True) on the gevent pool: a
revoked task no longer first emits task-revoked and then gets recorded as
task-succeeded.

Root cause

  1. on_cold_shutdown() calls consumer.cancel_active_requests(), which
    cancels each active request and kills its greenlet
    (TaskPool.terminate_job()).
  2. TaskPool._make_killable_target() in celery/concurrency/gevent.py
    caught the resulting GreenletExit and returned (False, None, None).
  3. That tuple is the success shape produced by trace_task_ret: the pool
    passed it to Request.on_success(), which reads "not failed" and, with
    task_acks_late, calls self.acknowledge(). The interrupted task was
    therefore acked and never redelivered.

Fix

killable_target no longer fabricates a success. A killed greenlet is now
reported as a terminated job — the same failure shape a trace returns and
the same exception prefork reports for a terminated job
(billiard's ApplyResult._set_terminated() delivers a Terminated
ExceptionInfo to Request.on_failure()):

except GreenletExit:
    try:
        raise Terminated('greenlet killed')
    except Terminated:
        return (True, ExceptionInfo(), None)

Request.on_success() sees failed=True and delegates to
Request.on_failure(), whose Terminated branch returns early for a
request the worker itself cancelled (_already_cancelled, set by
Request.cancel() before the greenlet is killed): no ack, no reject, so
the message stays unacknowledged and is redelivered when the connection
closes — matching prefork.

Two alternatives were considered and rejected on evidence (verified
against a real Request with default settings):

  • Re-raising GreenletExit lets celery.concurrency.base.apply_target
    convert it to callback(ExceptionInfo(WorkerLostError)), but the gevent
    pool has a single callback (Request.on_success), which cannot unpack
    an ExceptionInfo and raises TypeError.
  • Delivering WorkerLostError to Request.on_failure() acknowledges
    under the default task_acks_on_failure=True, so the task would still
    be lost unless task_reject_on_worker_lost is enabled.

The diff is confined to celery/concurrency/gevent.py; the adjacent
BlockingSwitchOutError shutdown handling (#11065) is untouched.
The same fix is also applied to celery/concurrency/eventlet.py,
whose _make_killable_target had the identical (False, None, None)
pattern; test_make_killable_target in
t/unit/concurrency/test_eventlet.py is updated the same way as the
gevent one.

Reproduction

Standalone script (real gevent pool, job killed with terminate_job(),
result fed to a real Request with acks_late=True and
_already_cancelled=True):

Before the fix:

callback received: [(False, None, None)]
RESULT: callback got success-shaped value: True
request: on_success -> returned, acknowledged=True, on_ack calls=1
BUG

After the fix:

callback received: [(True, <ExceptionInfo: ExceptionWithTraceback()>, None)]
RESULT: callback got success-shaped value: False
request: on_success -> returned, acknowledged=False, on_ack calls=0
FIXED

Tests

Updated test_make_killable_target and added
test_TaskPool_killed_job in t/unit/concurrency/test_gevent.py:
a real gevent job killed via terminate_job() reports Terminated
(not success), and feeding that result to a cancelled late-ack
Request.on_success() does not acknowledge it. All three new/updated
tests fail on the unpatched code and pass with the fix.

$ pytest t/unit/concurrency/test_gevent.py t/unit/concurrency/test_concurrency.py t/unit/worker/test_request.py -q
229 passed

Per file: test_gevent.py 13 passed, test_concurrency.py 26 passed,
test_request.py 180 passed. The whole t/unit/concurrency/ directory
also passes (121 passed, 1 skipped — eventlet not installed).
flake8 (repo setup.cfg config) is clean on both changed files.

_make_killable_target() caught GreenletExit and returned
(False, None, None), the success shape, so Request.on_success()
acknowledged a task that never finished and the message was lost
(issue celery#11086, regression in 5.5.0).

Report a killed greenlet as a terminated job instead --
(True, ExceptionInfo(Terminated), None) -- so a request cancelled
by the worker itself stays unacknowledged and its message is
redelivered, matching prefork.
@tony1233200

Copy link
Copy Markdown
Contributor Author

Closing to clear the queue: opened 7 days ago with no maintainer reply. The branch is kept, so this can be reopened if there is interest.

@auvipy

auvipy commented Nov 26, 2026

Copy link
Copy Markdown
Member

dude, just unbanned you and you restarted attention seeking drama again? you want to get ban again?

@auvipy auvipy reopened this Nov 26, 2026
@auvipy
auvipy self-requested a review November 26, 2026 17:41
@auvipy

auvipy commented Nov 26, 2026

Copy link
Copy Markdown
Member

@MehrazRumman

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

The fix looks right to me. I traced it through main (a2d470f).

Why main loses the task. terminate_job() calls gevent.kill(greenlet), so GreenletExit is raised inside the task. trace_task doesn't catch it, since it's a BaseException, and killable_target returns (False, None, None). base.apply_target() then calls callback(ret), which is Request.on_success(). With failed=False, that runs task_ready(self, successful=True), then self.acknowledge() for acks_late, then sends task-succeeded. So the message is acked and the task never ran to the end.

Why the new return value is safe. With (True, ExceptionInfo(Terminated), None), on_success() hands the result to on_failure(retval, return_ok=True). Its Terminated branch calls task_ready() and then returns without an ack or a reject when _already_cancelled or _already_revoked is set. That's the same path prefork takes through billiard's _set_terminated(). cancel_active_requests() → Request.cancel() sets _already_cancelled before the kill, so the message stays unacked and is redelivered.

It also fixes revoke(terminate=True) on gevent. Request.terminate() → _announce_revoked() already acks, stores REVOKED and sends task-revoked. On main, the killed greenlet then also went through the success path: task-succeeded was sent after task-revoked, and the request was counted in successful_requests. With this PR, the Terminated branch returns early, because _already_revoked is set. Monitors (Flower, events.State) no longer see a revoked task flip to SUCCESS. It might be worth one line in the description.

Eventlet. celery/concurrency/eventlet.py:168-174 has the same except GreenletExit: return (False, None, None), so it has the same bug. test_eventlet.py mocks the eventlet modules, so a fix there doesn't need eventlet installed. Here is the same change, if you'd like to include it here or in the follow-up you mentioned:

    @staticmethod
    def _make_killable_target(target):
        def killable_target(*args, **kwargs):
            try:
                return target(*args, **kwargs)
            except GreenletExit:
                # Report a killed job as terminated, not as a success (#11086).
                try:
                    raise Terminated('greenlet killed')
                except Terminated:
                    return (True, ExceptionInfo(), None)
        return killable_target

That needs from billiard.einfo import ExceptionInfo and from billiard.exceptions import Terminated at the top of eventlet.py. GreenletExit is already imported there.

Not changed by this PR: if the kill lands while accept_callback is running, before target is called, base.apply_target() reports it as callback(ExceptionInfo(WorkerLostError)). The single gevent callback can't unpack that, as you found. That window is tiny and was there before, so I'd leave it.

The tests are good. The real-gevent test kills a running job through terminate_job(), and the Request test checks the outcome that matters, no ack, instead of the tuple's shape. Unit and smoke jobs were still running on d66ac46 when I looked; lint, Semgrep and CodeQL pass.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.78%. Comparing base (f8dee9d) to head (13a786c).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11134      +/-   ##
==========================================
+ Coverage   91.54%   91.78%   +0.24%     
==========================================
  Files         153      153              
  Lines       22211    22243      +32     
  Branches     2783     2784       +1     
==========================================
+ Hits        20332    20415      +83     
+ Misses       1580     1530      -50     
+ Partials      299      298       -1     
Flag Coverage Δ
unittests 91.76% <100.00%> (+0.24%) ⬆️

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.

@tony1233200

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @MehrazRumman — both points are addressed in the latest push:

  • Eventlet: applied the same fix to celery/concurrency/eventlet.py (_make_killable_target now returns (True, ExceptionInfo(Terminated), None)), with test_make_killable_target updated the same way as the gevent one. No eventlet install is needed for the test (it mocks the modules, as you said). t/unit/concurrency/test_eventlet.py, test_gevent.py, test_concurrency.py, test_request.py: 250 passed (the one failure, test_aaa_blockdetecet, fails identically on the base commit).
  • Description: added the line about revoke(terminate=True) no longer flipping a revoked task to SUCCESS.

The accept_callback window you flagged is left as-is, per your note.

@tony1233200

Copy link
Copy Markdown
Contributor Author

Sorry about that, @auvipy — the "closing to clear the queue" comment was routine queue cleanup on my side (7 days with no reply at the time), not an attempt to draw attention, and I won't do that again. The PR stays open. Thanks for pinging @MehrazRumman — his review is addressed in the latest push (eventlet gets the same fix, see below).

@auvipy auvipy added this to the 5.7.x milestone Nov 28, 2026
@auvipy

auvipy commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

I forbid you multiple times not to do this shit in celery. never ever do this again

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

the unit test coverage needs to be 100% for the patch

Bring celery/concurrency/gevent.py and celery/concurrency/eventlet.py
to 100% unit test coverage for the celery#11086 terminated-job fix:
terminate_job() with an unknown pid and the no-op _terminate hook.
@tony1233200

Copy link
Copy Markdown
Contributor Author

Sorry about that, @auvipy — I won't do it again.

Coverage for the patch is now 100%: celery/concurrency/gevent.py and celery/concurrency/eventlet.py both report 100% (statements and branches) under t/unit/concurrency/test_gevent.py and t/unit/concurrency/test_eventlet.py, measured with pytest --cov (branch coverage on). The new push (a99ed77) adds tests for the remaining paths — terminate_job() with an unknown pid and the no-op _terminate hook. 40 passed; the only failure is the pre-existing test_aaa_blockdetecet, which also fails on unpatched main.

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

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

auvipy and others added 3 commits November 28, 2026 14:29
CI (Python 3.11+) does not install eventlet: requirements/extras/
eventlet.txt gates it to Python < 3.10, so the module-level
pytest.importorskip('eventlet') skipped the whole test file and the
celery#11086 fix in celery/concurrency/eventlet.py got no patch coverage
(codecov/patch 50%).

celery/concurrency/eventlet.py does not import eventlet at module
level, so _make_killable_target() can be exercised without it: move
that test into a plain class and only skip the eventlet-dependent
tests when eventlet is not installed.
@tony1233200

Copy link
Copy Markdown
Contributor Author

@auvipy Those two commits are mine — pushed from my side with my email [email protected] as the author email. GitHub maps that email to my yc25778-droid account, so they show up under that name. Sorry for the confusion.

On the coverage: the eventlet test file was skipped wholesale in CI because eventlet is not installed on Python 3.11+ (requirements/extras/eventlet.txt gates it to Python < 3.10), so the eventlet.py fix never got patch coverage even though the test exists and passes locally — that is why codecov still showed 50% with the 6 eventlet.py lines missing.

Just pushed bd3b7e3: the killable-target test now runs without eventlet installed (celery/concurrency/eventlet.py does not import eventlet at module level), and only the eventlet-dependent tests are skipped when it is missing. Locally the file is at 100% coverage both with and without eventlet installed; codecov/patch should go green once CI runs on the new push.

@auvipy

auvipy commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

also can we upgrade the requirments file? this seems to be now support python 3.14 https://github.com/eventlet/eventlet/blob/master/tox.ini

I opened a new PR I also opened a PR #11172

@auvipy
auvipy merged commit 93b5ba0 into celery:main Nov 28, 2026
536 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.

gevent: a cold shutdown acknowledges a late-ack task it interrupts, and the task is lost (regression in 5.5.0)

4 participants