Skip to content

Store FAILURE instead of RETRY when cancelling an acknowledged task - #11136

Merged
auvipy merged 5 commits into
celery:mainfrom
tony1233200:fix/11079-cold-shutdown-retry-state
Nov 23, 2026
Merged

auvipy merged 5 commits into
celery:mainfrom
tony1233200:fix/11079-cold-shutdown-retry-state

Conversation

@tony1233200

Copy link
Copy Markdown
Contributor

Fixes #11079

What was wrong

A cold shutdown stores RETRY for a running early-ack task it cancels, but
nothing ever runs the task again.

Consumer.cancel_active_requests() cancels every active non-acks_late
request with emit_retry=True, and Request._announce_cancelled() then
unconditionally stored RETRY ("cancelled by Celery"). An early-ack message
is acknowledged in Request.on_accepted() when the task starts, so the
broker will not redeliver it: the stored RETRY claims the task will run
again, 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. The RETRY itself
comes from #6654 (5.1.0), where it was written for acks_late tasks
cancelled on connection loss — their messages are redelivered, so RETRY
fits there and is kept for that case.

What changes

Request._announce_cancelled() now gates the retry announcement on the
request not being acknowledged:

  • Already acknowledged (self.acknowledged): store a terminal FAILURE
    with WorkerLostError('cancelled by Celery') via
    backend.mark_as_failure(..., store_result=self.store_errors), and do
    not call on_retry or send the task_retry signal. This matches the
    reporter's suggested outcome, the pre-5.5 behaviour, and the existing
    worker-lost failure path, and mark_as_failure also propagates to
    errbacks/chords so waiters are released instead of hanging.
  • Not acknowledged: unchanged — RETRY is stored and task_retry is 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_failure
for 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: it
still passes emit_retry=True for non-acks_late tasks, and the request
decides which state that announcement stores. The connection-loss call site
(on_connection_error_after_connected, acks_late and unacknowledged
only) is untouched.

Reproduction

Unit-level reproduction, following the existing fixtures in
t/unit/worker/test_request.py: build a Request for a default
(early-ack) task, acknowledge it as on_accepted() does, set
time_start, then cancel(pool, emit_retry=True) as
cancel_active_requests() does.

Before the fix:

mark_as_retry calls:   call('<task-id>', Retry(...), request=<Context ...>)
mark_as_failure calls: None
AssertionError: BUG #11079: RETRY stored for an already-acknowledged task

After the fix:

mark_as_retry calls:   None
mark_as_failure calls: call('<task-id>', WorkerLostError('cancelled by Celery'), request=<Context ...>, store_result=True)
1 passed

Tests

New tests in t/unit/worker/test_request.py (fail without the fix, pass
with it):

  • test_cancel__acknowledged_stores_failure_not_retry — acknowledged
    request: no mark_as_retry, no on_retry, one mark_as_failure with a
    WorkerLostError.
  • test_cancel__unacknowledged_acks_late_stores_retry — unacknowledged
    acks_late request: RETRY and the task_retry signal are unchanged.
  • test_cancel__acknowledged_emit_retry_false_stores_nothing —
    emit_retry=False stores neither state.

Results (Python 3.12, kombu 5.7, pytest 9):

  • t/unit/worker/test_request.py: 183 passed
  • t/unit/worker/test_consumer.py: 136 passed
  • t/unit/worker/test_control.py: 84 passed
  • t/unit/worker/ (whole directory): 810 passed, 2 skipped
  • flake8 (setup.cfg config) on the changed files: clean

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

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 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 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:

  • #10491: threads terminate_job
  • #11065: gevent/threads cold shutdown
  • #11134: gevent late-ack

#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() with emit_retry=True. on_connection_error_after_connected covers acks_late and not acknowledged only, so it still stores RETRY. cancel_active_requests() covers the early-ack tasks, which on_accepted() has acknowledged, so they now get FAILURE. Gating on self.acknowledged instead of acks_late also 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() sets proc._job_terminated, so billiard reports Terminated, and on_failure() returns early for it. A child that turns SIGTERM into SystemExit is also skipped, because _already_cancelled is set. So the worker-lost branch doesn't call mark_as_failure a second time, and a chord header isn't counted twice.
  • Errbacks and chords. Through mark_as_failure they'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).

Comment thread celery/worker/request.py Resolved
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.
@tony1233200

This comment was marked as abuse.

@auvipy

auvipy commented Nov 22, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.33%. Comparing base (29b14de) to head (145aba3).

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

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

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_shutdown in t/smoke/tests/test_worker.py sets task_acks_late = True, so its test_cold_shutdown only 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_retry is 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 PENDING on 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 SUCCESS on main and here.

@auvipy

auvipy commented Nov 23, 2026

Copy link
Copy Markdown
Member

@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 tony1233200 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both points addressed, head 145aba3:

  • Smoke test: added test_worker_shutdown_early_ack.test_cold_shutdown_fails_the_running_task at the end of t/smoke/tests/test_worker.py, as suggested (early-ack path, no task_acks_late override; res.get() expects WorkerLostError). 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 None cleanup branch in _announce_cancelled() — its false path only runs if building the failure info raises. Added test_cancel__acknowledged_failure_info_setup_raises, which makes ExceptionInfo raise 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.

@tony1233200

This comment was marked as abuse.

@auvipy

auvipy commented Nov 23, 2026

Copy link
Copy Markdown
Member

thanks

@auvipy
auvipy merged commit 992e9b5 into celery:main Nov 23, 2026
531 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.

Cold shutdown stores RETRY for an early-ack task it cancels, and nothing runs the task again

4 participants