Skip to content

Add task-ignored event for tasks raising Ignore - #11164

Merged
auvipy merged 13 commits into
celery:mainfrom
purnendu-rai:fix-11093-task-ignored
Nov 28, 2026
Merged

auvipy merged 13 commits into
celery:mainfrom
purnendu-rai:fix-11093-task-ignored

Conversation

@purnendu-rai

Copy link
Copy Markdown
Contributor

Fixes #11093.

A task that raises Ignore sends no event after task-started, so Flower and other event monitors show it as STARTED for as long as they keep it — even though the result backend has moved on. This implements option 1 from the issue thread (thanks @ChristianMurphy for the report and the root-cause analysis): a new terminal event, task-ignored, following the precedent of task-rejected for Reject (#4222).

Changes:

  • celery/worker/request.py: Request.on_failure now emits task-ignored from the Ignore branch before acknowledging, mirroring how Request.reject() emits task-rejected. The payload is just the task uuid, as in the issue discussion.
  • celery/events/state.py: map task-ignored to states.IGNORED in TASK_EVENT_TO_STATE and record the event timestamp on the Task object (ignored field), mirroring rejected, so monitors built on celery.events.State pick the state up automatically.
  • Docs: a task-ignored section in the monitoring guide, after task-rejected.
  • Tests: test_on_failure_Ignore_sends_task_ignored_event (worker request) and test_task_ignored_event_sets_ignored_state (events state), both mirroring the existing task-rejected tests.

Tests (run locally on Windows 11, Python 3.13.14, against upstream/main de28509):

  • Before this change, the two new tests fail: 1 failed, 16 passed for the worker request tests (send('task-ignored', ...) not called) and 1 failed for the events state test (Task has no attribute ignored).
  • With this change: pytest t/unit/worker/test_request.py -k Ignore — 17 passed; pytest t/unit/events/test_state.py -k ignored — 1 passed; full files t/unit/worker/test_request.py t/unit/events/test_state.py — 233 passed, 1 skipped, no regressions. The existing test_on_failure_Ignore_acknowledges still passes — acknowledge behaviour is unchanged. Full t/unit/events also passes (104 passed, 2 skipped).

One deliberate non-change, flagged for reviewers: like REJECTED, IGNORED is not added to READY_STATES, so State.clear_tasks(ready=True) keeps ignored tasks in memory like rejected ones. Happy to change that here if you prefer ignored tasks to be treated as ready for cleanup.

@auvipy
auvipy self-requested a review November 26, 2026 14:18
@auvipy auvipy added this to the 5.7.x milestone Nov 26, 2026
@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.80%. Comparing base (5aaeb86) to head (4772c6a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11164   +/-   ##
=======================================
  Coverage   91.80%   91.80%           
=======================================
  Files         153      153           
  Lines       22288    22291    +3     
  Branches     2792     2793    +1     
=======================================
+ Hits        20462    20465    +3     
  Misses       1530     1530           
  Partials      296      296           
Flag Coverage Δ
unittests 91.79% <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.

Thanks for picking this up. It fixes what I reported in #11093, and it needs two things before merge: a fix for self.replace(), which now shows as IGNORED while its replacement is still running, and the tests below.

I ran 494f8d0f9 against main (14115f05e) with a monitor built on app.events.State, on Redis 7 and RabbitMQ 4.0. The head is now 873234e34, which adds only the merge of main. The unit tests pass on that merge.

The reported case is fixed on the prefork, threads, solo and gevent pools, with early and late ack:

Task Monitor on main Monitor on this PR
Raises Ignore STARTED, and it stays IGNORED
Stores SUCCESS itself, then raises Ignore STARTED, and it stays IGNORED
Retries once, then raises Ignore STARTED, and it stays IGNORED

1. self.replace() raises Ignore too. The replaced task gets task-ignored while it is still in progress. The replacement keeps the task id. Its task-received and task-started cannot move the monitor back, because IGNORED ranks above both in states.PRECEDENCE. With a replacement that sleeps 4 s:

main This PR
Monitor state while the replacement runs STARTED IGNORED
Monitor state at the end SUCCESS SUCCESS

It is the same for a replacement that is a chain or a group, for a replaced task inside a chain, and for a replaced chord header task. Flower 2.2.0 lists the replaced task as IGNORED for those 4 s too. With a long replacement, a dashboard would list running work as ignored.

One way to fix it is below: replace() raises a subclass of Ignore, and the worker doesn't send task-ignored for it. With that change the monitor shows STARTED and then SUCCESS again in all the replace cases, a plain Ignore still ends as IGNORED, and the unit tests pass.

2. The tests need to cover it before merge.

  • The unit tests catch five of the seven bugs I planted. They miss ignored dropped from Task._fields (so as_dict() loses it), and nothing checks that a late task-started leaves the state alone. One test for both is below.
  • The tests don't run a worker, which is why the replace case got through. A smoke test for both cases is below. On main the first fails, on this PR the second fails, and with the fix both pass, on the Redis and the RabbitMQ broker.

On your question: I'd leave IGNORED out of READY_STATES, as you did. It matches REJECTED, and clear_tasks(ready=True) keeps these tasks on main already.

One smaller thing: the docs entry could have .. versionadded::, and "without being executed to completion" reads as if the task did not run. Something like "the worker acknowledged the message and did not store a state for it" is closer.

Fix for the replace case, with its unit test
--- a/celery/exceptions.py
+++ b/celery/exceptions.py
@@ -74,7 +74,7 @@
     # Task semi-predicates
-    'TaskPredicate', 'Ignore', 'Reject', 'Retry',
+    'TaskPredicate', 'Ignore', 'Replaced', 'Reject', 'Retry',
@@ -197,6 +197,10 @@ class Ignore(TaskPredicate):
     """A task can raise this to ignore doing state updates."""
 
 
+class Replaced(Ignore):
+    """The task was replaced by another one that keeps its id."""
+
+
 class Reject(TaskPredicate):
--- a/celery/app/task.py
+++ b/celery/app/task.py
@@ -1359,7 +1359,7 @@ class Task:
             sig.delay()
-            raise Ignore('Replaced by new task')
+            raise Replaced('Replaced by new task')
--- a/celery/worker/request.py
+++ b/celery/worker/request.py
@@ -763,7 +763,10 @@ class Request:
         elif isinstance(exc, Ignore):
-            self.send_event('task-ignored')
+            if not isinstance(exc, Replaced):
+                # A replaced task continues under the same id: its
+                # replacement sends the last event.
+                self.send_event('task-ignored')
             return self.acknowledge()

The imports in task.py and request.py change to match. In t/unit/worker/test_request.py:

    def test_on_failure_Replaced_sends_no_task_ignored_event(self):
        # A replaced task continues under the same id, so a monitor must
        # not see it as ignored while the replacement runs.
        einfo = None
        try:
            raise Replaced()
        except Replaced:
            einfo = ExceptionInfo(internal=True)
        assert einfo is not None
        req = self.get_request(self.add.s(2, 2))
        req.on_failure(einfo)
        req.eventer.send.assert_not_called()
        req.on_ack.assert_called_with(req_logger, req.connection_errors)
Unit test for the late event and the exported field

In test_State (t/unit/events/test_state.py):

    def test_task_ignored_is_kept_and_exported(self):
        # A task-started that arrives late must not move the task back,
        # and the timestamp is part of what a monitor exports.
        state = State()
        tid = uuid()
        for type_, clock in (('task-received', 1), ('task-started', 2),
                             ('task-ignored', 3), ('task-started', 2)):
            state.event({
                'type': type_, 'uuid': tid, 'hostname': 'h', 'clock': clock,
                'timestamp': float(clock), 'local_received': float(clock),
            })
        task = state.tasks[tid]
        assert task.state == states.IGNORED
        assert task.as_dict()['ignored'] == task.ignored
Smoke test

A task for t/smoke/tasks.py:

@shared_task
def ignores():
    raise Ignore()

At the end of t/smoke/tests/test_tasks.py, with ignores, sleeping and monotonic added to its imports:

class test_task_ignored_event:
    @pytest.fixture
    def default_worker_app(self, default_worker_app: Celery) -> Celery:
        app = default_worker_app
        app.conf.worker_send_task_events = True
        return app

    def watch(self, celery_setup: CeleryTestSetup, sig, until: str):
        """Run ``sig`` and follow its events, as a monitor would, up to ``until``."""
        app = celery_setup.app
        state = app.events.State()
        seen = []
        sent = []
        deadline = monotonic() + RESULT_TIMEOUT

        def on_event(event):
            state.event(event)
            if sent and event.get("uuid") == sent[0].id:
                seen.append(event["type"])
            # Worker heartbeats keep this handler running, so the
            # deadline ends the capture when ``until`` never comes.
            if until in seen or monotonic() > deadline:
                receiver.should_stop = True

        def on_consume_ready(*args, **kwargs):
            sent.append(sig.apply_async(queue=celery_setup.worker.worker_queue))

        with app.connection() as connection:
            receiver = app.events.Receiver(connection, handlers={"*": on_event})
            receiver.on_consume_ready = on_consume_ready
            receiver.capture(wakeup=False)
        return state.tasks[sent[0].id], seen

    def test_ignored_task_ends_as_ignored(self, celery_setup: CeleryTestSetup):
        task, seen = self.watch(celery_setup, ignores.si(), "task-ignored")
        assert seen[-1:] == ["task-ignored"]
        assert task.state == "IGNORED"

    def test_replaced_task_is_not_shown_as_ignored(self, celery_setup: CeleryTestSetup):
        # The replacement sleeps so that every event of the replaced
        # task is in before the last one.
        replace_with = signature(sleeping, args=(2,), queue=celery_setup.worker.worker_queue)
        task, seen = self.watch(celery_setup, replace_with_task.si(replace_with), "task-succeeded")
        assert seen[-1:] == ["task-succeeded"]
        assert "task-ignored" not in seen
        assert task.state == "SUCCESS"
Other checks
  • Cost: 3000 tasks that raise Ignore on a solo worker with -E took 12.3 s here and 12.3 s on main (three runs each). Without -E no event is sent.
  • t/unit/worker/test_request.py, t/unit/events, t/unit/tasks/test_tasks.py and t/unit/tasks/test_canvas.py as tox runs them (python -bb): all pass. flake8 is clean on the touched files.
  • A chain or chord with a task that raises Ignore stops there on main and here. Only the monitor state differs.
What I did not run
  • The eventlet pool, and Python versions other than 3.13.
  • Brokers other than Redis 7 and RabbitMQ 4.0.
  • Monitors other than app.events.State and Flower 2.2.0.

@purnendu-rai

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @ChristianMurphy — and for verifying the fix against real brokers.

I've pushed the changes you asked for:

  • Replaced is now a subclass of Ignore raised by Task.replace(), and Request.on_failure no longer emits task-ignored for it, so a replaced task is not shown as IGNORED while its replacement runs.
  • Added your two unit tests (test_on_failure_Replaced_sends_no_task_ignored_event and test_task_ignored_is_kept_and_exported) and the smoke test (ignores task plus the test_task_ignored_event class) covering both cases against a live worker.
  • Docs: added .. versionadded:: 5.7 to the task-ignored entry and reworded it as you suggested.

The smoke tests need a live broker, so those rest on CI. Please let me know if anything else needs adjusting.

@ege-arhan ege-arhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The new event only half-lands: task-ignored maps to IGNORED (celery/events/state.py:76), but IGNORED is in neither READY_STATES nor UNREADY_STATES (celery/states.py:144-145). Monitors decide "done" from READY_STATES, so after this event the task is terminal but still counted as running. Task.ready is False and State.clear_tasks(ready=True) never drops it, so Flower-style monitors accumulate ignored tasks forever — which is the same symptom #11093 describes, just with a nicer state name.

Repro on the PR head, no worker needed:

from celery.events.state import State
s = State()
u = dict(uuid="t1", hostname="h", name="proj.add", args="()", kwargs="{}")
for t, c in (("task-received", 1), ("task-started", 2), ("task-ignored", 3)):
    s.event(dict(type=t, clock=c, timestamp=float(c), local_received=float(c), **u))
task = s.tasks["t1"]
print(task.state, task.ready)        # IGNORED False
s.clear_tasks(ready=True)
print(list(s.tasks))                 # ['t1']

Task.ready (celery/events/state.py:379-380) and _clear_tasks (:460) both read states.READY_STATES, so the ignored task is treated exactly as if it were still STARTED, except it no longer even matches UNREADY_STATES for anything that filters on that set.

The tests you added stop at assert task.state == "IGNORED", which is why this doesn't show up in CI. Adding IGNORED to READY_STATES makes ready True and clear_tasks drop it here; if that set is too broad a change, _clear_tasks and ready need an explicit IGNORED case instead. Either way one of the new tests should assert task.ready (or run clear_tasks) so the terminal behaviour is covered and not just the string.

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

Looks good to me. I traced it against main:

  • trace_task turns Ignore into (failed=1, ExceptionInfo), so the new branch in Request.on_failure really runs in the worker. The event goes out before the ack, which is the same order reject() uses for task-rejected.
  • IGNORED isn't in PRECEDENCE, so it gets the None slot. That ranks above STARTED/RECEIVED, which means a late task-started can't pull the task back. Your test_task_ignored_is_kept_and_exported covers this.
  • Making Replaced a subclass of Ignore keeps the existing except Ignore / isinstance(exc, Ignore) handling working (autoretry.py:39, trace.py:141, trace.py:572), and it's a clean way to skip the event for self.replace().

On READY_STATES, I'm fine with following the REJECTED precedent here. Changing what counts as "ready" affects clear_tasks and every monitor's notion of "done", so I'd do it as its own change.

@purnendu-rai

Copy link
Copy Markdown
Contributor Author

Thanks for the careful look, @ege-arhan — the repro is clear and the point is fair: IGNORED is in neither set today.

I left it out of READY_STATES deliberately, following the REJECTED precedent: task-rejected has the same shape, and clear_tasks(ready=True) keeps rejected tasks on main too. Changing what counts as "ready" affects clear_tasks and every monitor's notion of "done", so it seemed safer as its own change rather than bundled into this fix — @MehrazRumman made the same point above.

Happy to add a test pinning down the current terminal behaviour if you'd like, or to follow the maintainers' call if they'd rather have IGNORED in READY_STATES here.

@ege-arhan

Copy link
Copy Markdown

Agreed, leaving IGNORED out of READY_STATES here is consistent with REJECTED, and changing what monitors count as "done" belongs in its own change.

The test pinning the current behaviour (task.ready is False after task-ignored) is worth adding for the same reason: if someone later adds IGNORED to READY_STATES, the diff shows up as an assertion change instead of a silent behaviour swap. IGNORED is also missing from ALL_STATES in celery/states.py, which that test would not catch. Your call on both.

@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 now. I reran 44a7932a5 on Redis 7 and RabbitMQ 4.0, and the replace case is fixed.

Last head (494f8d0f9) Now
Replaced task, while a 4 s replacement runs IGNORED STARTED
The same with a chain or group as the replacement, inside a chain, and as a chord header task IGNORED STARTED
Task that raises Ignore IGNORED IGNORED

That holds on the prefork, threads, solo and gevent pools, and with late ack. The new smoke tests pass here on both brokers, and the unit tests now catch seven of the eight bugs I planted.

One last test before merge, and it is one word. If replace() went back to raising a plain Ignore, every unit test still passes, because the existing tests use pytest.raises(Ignore) and a subclass matches. Only the smoke test would catch it. In test_replace (t/unit/tasks/test_tasks.py), with Replaced added to the imports:

         self.mytask.request.id = sentinel.request_id
-        with pytest.raises(Ignore):
+        with pytest.raises(Replaced):
             self.mytask.replace(sig1)

With that change the test fails on that bug and passes here.

On READY_STATES, I agree with @MehrazRumman and the author: leave it for its own change. Ignored tasks do not pile up without limit either. State is a bounded cache, and after 25,000 ignored tasks a default State held 10,000.

The docs say versionadded:: 5.7. 5.7.0 is already out, so 5.7.1 may be the right number.

Other checks
  • t/unit/worker/test_request.py, t/unit/events, t/unit/tasks/test_tasks.py, t/unit/tasks/test_canvas.py and t/unit/app/test_exceptions.py as tox runs them (python -bb): 893 passed. flake8 is clean on the touched files.
  • A task that stores its own state and then raises Ignore, and one that retries and then raises Ignore, still end as IGNORED.
What I did not run
  • The existing test_replace::test_sanity smoke test. Its second worker image does not build in my sandbox, on main either.
  • Flower on this head, the eventlet pool, and Python versions other than 3.13.

@purnendu-rai

Copy link
Copy Markdown
Contributor Author

Thank you for the approval and for re-running it on both brokers, @ChristianMurphy. The last items are in:

  • test_replace now expects Replaced (with the import added), so a plain Ignore from replace() would fail that unit test too.
  • Docs: the task-ignored entry now says .. versionadded:: 5.7.1.

@ege-arhan — added the pinning test as well: test_task_ignored_is_not_ready asserts the state is IGNORED while ready stays False. On ALL_STATES: REJECTED is missing from it too, so I left that file alone — adding both feels like a separate consistency change for the maintainers to call.

@ege-arhan

Copy link
Copy Markdown

Pinning test and the Replaced/test_replace update look right to me.

Agree on ALL_STATES — REJECTED missing there too makes it a separate consistency fix, not part of this one. Nothing else from my side.

Comment thread docs/userguide/monitoring.rst Resolved
@purnendu-rai

Copy link
Copy Markdown
Contributor Author

@auvipy Addressed in 66903eb — docs-only change adding the Replaced note under the task-ignored entry, on top of your merge of main. Could you please re-review when you get a chance? Thanks!

@auvipy
auvipy merged commit bffee14 into celery:main Nov 28, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A task that raises Ignore shows as STARTED in event monitors

5 participants