Repository navigation
Store FAILURE instead of RETRY when cancelling an acknowledged task - #11136
Conversation
An early-ack task is acknowledged when it starts, so when a cold shutdown cancels it the broker will not redeliver it and nothing runs it again. Request._announce_cancelled() stored RETRY for it anyway, leaving callers waiting on a result that would never arrive. Gate the RETRY announcement on the request not being acknowledged: acknowledged requests now store a terminal FAILURE with WorkerLostError, as the worker-lost path does. Unacknowledged requests (acks_late tasks cancelled on connection loss, whose messages are redelivered) keep storing RETRY. Fixes celery#11079
MehrazRumman
left a comment
There was a problem hiding this comment.
I checked for duplicates first. This is the only PR for #11079: the issue's timeline has no other cross-referenced PR, and a search for _announce_cancelled, cancel_active_requests and "cancelled by Celery" finds no other PR that changes the stored state. The other open cold-shutdown PRs work on different code:
#11065 does edit the same comment in cancel_active_requests() (consumer.py:926-927). Whichever of the two merges second will have a small conflict.
The fix looks right to me. Checked against main (9c2f238) and billiard main:
- Callers. Only two places call
Request.cancel()withemit_retry=True.on_connection_error_after_connectedcoversacks_late and not acknowledgedonly, so it still stores RETRY.cancel_active_requests()covers the early-ack tasks, whichon_accepted()has acknowledged, so they now get FAILURE. Gating onself.acknowledgedinstead ofacks_latealso gives the right answer for an early-ack request whose start hasn't been accepted yet: its message isn't acked, so RETRY still fits. - No second failure from the pool.
terminate_job()setsproc._job_terminated, so billiard reportsTerminated, andon_failure()returns early for it. A child that turns SIGTERM intoSystemExitis also skipped, because_already_cancelledis set. So the worker-lost branch doesn't callmark_as_failurea second time, and a chord header isn't counted twice. - Errbacks and chords. Through
mark_as_failurethey're now released. A RETRY state left them waiting.
One question is inline: the RETRY branch this replaces calls task.on_retry() and sends task_retry, but the new branch only stores the state.
CI hasn't run yet. The workflows on 1741a14 are waiting for maintainer approval (action_required).
The FAILURE branch added for celery#11079 stored the result but fired no hook or signal, unlike the other terminal-FAILURE paths in this file (worker-lost branch of on_failure(), Reject(requeue=False), the hard time-limit path), which all send signals.task_failure. Alerting on task_failure (Sentry and similar) would therefore miss these tasks. Send task_failure like the worker-lost branch does, with the request context pushed onto the request stack, and build the ExceptionInfo the way the hard time-limit path does. on_retry/task_retry still do not apply: the message is already acknowledged, so the task will never run again. Fixes the inline review comment on celery#11136.
This comment was marked as abuse.
This comment was marked as abuse.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #11136 +/- ##
==========================================
+ Coverage 91.32% 91.33% +0.01%
==========================================
Files 153 153
Lines 21823 21841 +18
Branches 2710 2712 +2
==========================================
+ Hits 19929 19948 +19
Misses 1593 1593
+ Partials 301 300 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
ChristianMurphy
left a comment
There was a problem hiding this comment.
Looks good. I ran it at b9004d00f against main (ebf4be58d) and it fixes what I reported in #11079, with no regression that I could find.
A prefork worker on a Redis broker, stopped with SIGQUIT while an early-ack task runs:
| main | This PR | |
|---|---|---|
| The task's state | RETRY, and it stays |
FAILURE (WorkerLostError) |
| Next task in a chain | PENDING, and it stays |
FAILURE |
| Chord body, with the task in the header | PENDING, and it stays |
FAILURE (ChordError) |
link_error on the task |
never runs | runs once |
Task with ignore_result=True |
a RETRY result is stored |
nothing is stored |
task_failure signal |
not sent | sent once |
Under load it holds. Six cold shutdowns with 16 tasks in flight each, on a Redis result backend and again on PostgreSQL 16:
| Per backend | main | This PR |
|---|---|---|
Tasks left in RETRY |
48 | 0 |
Chain tails left PENDING |
24 | 0 |
Chord bodies left PENDING |
12 | 0 |
| Errbacks that ran, of 24 | 0 | 24 |
task_failure sent twice for one task |
0 | 0 |
On PostgreSQL there is one more effect on main: celery.chord_unlock for those 12 chords keeps retrying and never stops (1368 retries before I ended the run). With this PR the queue is empty at the end.
These gave the same result on main and on this PR:
- A late-ack task on SIGQUIT: the message goes back to the queue, and it runs again after a restart.
- A warm shutdown: the task finishes,
SUCCESS. - A task that was prefetched but not started: runs after a restart.
- A late-ack task cancelled on connection loss (
worker_cancel_long_running_tasks_on_connection_loss):RETRY, then it runs again. - The result backend down at the moment of SIGQUIT: the worker still exits in 1.7 s.
- Time for the worker to exit: the same in every case, to within 0.3 s.
The new tests do their job. With celery/worker/request.py put back to main they fail, and each of six bugs I planted in the new branch fails at least one of them. t/unit/worker as tox runs it (python -bb): 819 passed. The existing shutdown smoke tests in t/smoke/tests/test_worker.py pass here too (38 passed, 6 skipped). For that run I removed the apt-get step from the worker image, since my sandbox could not reach the package mirror.
Smaller things that can wait for a follow-up:
- No smoke test covers this.
test_worker_shutdownint/smoke/tests/test_worker.pysetstask_acks_late = True, so itstest_cold_shutdownonly sees the late-ack path. A test for the early-ack path is below. In the Docker smoke setup it fails on main and passes here, on the RabbitMQ and the Redis broker. task_retryis no longer sent for these tasks. That is right, since nothing retries them, and a line in the changelog would help anyone who alerts on it.- The gevent pool is not changed by this: there the state stays
PENDINGon main and here. #11065 and #11134 are open for that pool.
Smoke test for the early-ack cold shutdown
At the end of t/smoke/tests/test_worker.py. On main res.get() times out, since the state stays RETRY.
class test_worker_shutdown_early_ack(SuiteOperations):
def test_cold_shutdown_fails_the_running_task(self, celery_setup: CeleryTestSetup):
queue = celery_setup.worker.worker_queue
worker = celery_setup.worker
res = long_running_task.si(5, verbose=True).set(queue=queue).delay()
worker.assert_log_exists("Starting long running task")
self.kill_worker(worker, WorkerKill.Method.SIGQUIT)
worker.assert_log_exists("worker: Cold shutdown (MainProcess)")
assert_container_exited(worker)
with pytest.raises(celery.exceptions.WorkerLostError):
res.get(timeout=RESULT_TIMEOUT)What I did not run
- RabbitMQ as the broker outside the smoke tests. The tables above used Redis 7 as the broker, with kombu main.
- Smoke tests other than the shutdown ones, and Python versions other than 3.13.
- The threads pool is not affected either way: a cold shutdown there does not cancel the task, and it finishes with
SUCCESSon main and here.
|
@tony1233200 check the smoke test suggestions and improve unit test coverage please. |
Add the early-ack cold shutdown smoke test from review (fails on main, passes here) and a unit test for the failure-info setup raising while announcing a cancelled acknowledged task, taking the patch coverage of the new _announce_cancelled branch to 100%.
tony1233200
left a comment
There was a problem hiding this comment.
Both points addressed, head 145aba3:
- Smoke test: added
test_worker_shutdown_early_ack.test_cold_shutdown_fails_the_running_taskat the end oft/smoke/tests/test_worker.py, as suggested (early-ack path, notask_acks_lateoverride;res.get()expectsWorkerLostError). It collects as two cases (RabbitMQ and Redis brokers). I could not execute it here (no Docker smoke setup in this environment), so it still needs a run in CI / your Docker setup. - Unit test coverage: patch coverage is now 100% (was 94.44%, 1 partial line). The remaining gap was the
if einfo is not Nonecleanup branch in_announce_cancelled()— its false path only runs if building the failure info raises. Addedtest_cancel__acknowledged_failure_info_setup_raises, which makesExceptionInforaise and checks the FAILURE is still stored and the error propagates.
Tests: t/unit/worker/test_request.py + test_consumer.py — 321 passed; flake8 clean on the touched files.
This comment was marked as abuse.
This comment was marked as abuse.
|
thanks |
Fixes #11079
What was wrong
A cold shutdown stores
RETRYfor a running early-ack task it cancels, butnothing ever runs the task again.
Consumer.cancel_active_requests()cancels every active non-acks_laterequest with
emit_retry=True, andRequest._announce_cancelled()thenunconditionally stored
RETRY("cancelled by Celery"). An early-ack messageis acknowledged in
Request.on_accepted()when the task starts, so thebroker will not redeliver it: the stored
RETRYclaims the task will runagain, and a caller waiting on the result waits until its timeout.
This is a regression from #9213 (5.5.0), which made cold shutdown cancel
running tasks; on 5.4.0 the same steps stored
FAILURE. TheRETRYitselfcomes from #6654 (5.1.0), where it was written for
acks_latetaskscancelled on connection loss — their messages are redelivered, so
RETRYfits there and is kept for that case.
What changes
Request._announce_cancelled()now gates the retry announcement on therequest not being acknowledged:
self.acknowledged): store a terminalFAILUREwith
WorkerLostError('cancelled by Celery')viabackend.mark_as_failure(..., store_result=self.store_errors), and donot call
on_retryor send thetask_retrysignal. This matches thereporter's suggested outcome, the pre-5.5 behaviour, and the existing
worker-lost failure path, and
mark_as_failurealso propagates toerrbacks/chords so waiters are released instead of hanging.
RETRYis stored andtask_retryis sent,because the message will be redelivered and the task will run again.
emit_retry=False: unchanged — nothing is stored.Leaving the state at
STARTED(storing nothing) was rejected:on_failurefor a terminated, already-cancelled request returns early, so nothing else
would ever move the task out of
STARTED.cancel_active_requests()itself is unchanged apart from a comment: itstill passes
emit_retry=Truefor non-acks_latetasks, and the requestdecides which state that announcement stores. The connection-loss call site
(
on_connection_error_after_connected,acks_lateand unacknowledgedonly) is untouched.
Reproduction
Unit-level reproduction, following the existing fixtures in
t/unit/worker/test_request.py: build aRequestfor a default(early-ack) task, acknowledge it as
on_accepted()does, settime_start, thencancel(pool, emit_retry=True)ascancel_active_requests()does.Before the fix:
After the fix:
Tests
New tests in
t/unit/worker/test_request.py(fail without the fix, passwith it):
test_cancel__acknowledged_stores_failure_not_retry— acknowledgedrequest: no
mark_as_retry, noon_retry, onemark_as_failurewith aWorkerLostError.test_cancel__unacknowledged_acks_late_stores_retry— unacknowledgedacks_laterequest:RETRYand thetask_retrysignal are unchanged.test_cancel__acknowledged_emit_retry_false_stores_nothing—emit_retry=Falsestores neither state.Results (Python 3.12, kombu 5.7, pytest 9):
t/unit/worker/test_request.py: 183 passedt/unit/worker/test_consumer.py: 136 passedt/unit/worker/test_control.py: 84 passedt/unit/worker/(whole directory): 810 passed, 2 skippedNot tested: a live end-to-end run against a real Redis broker/backend
(the reporter's original scenario); the fix is covered at the unit level
where the wrong state is stored.