Repository navigation
Add task-ignored event for tasks raising Ignore - #11164
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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.
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
ignoreddropped fromTask._fields(soas_dict()loses it), and nothing checks that a latetask-startedleaves 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.ignoredSmoke 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
Ignoreon a solo worker with-Etook 12.3 s here and 12.3 s on main (three runs each). Without-Eno event is sent. t/unit/worker/test_request.py,t/unit/events,t/unit/tasks/test_tasks.pyandt/unit/tasks/test_canvas.pyas tox runs them (python -bb): all pass. flake8 is clean on the touched files.- A chain or chord with a task that raises
Ignorestops 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.Stateand Flower 2.2.0.
|
Thanks for the thorough review, @ChristianMurphy — and for verifying the fix against real brokers. I've pushed the changes you asked for:
The smoke tests need a live broker, so those rest on CI. Please let me know if anything else needs adjusting. |
ege-arhan
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Looks good to me. I traced it against main:
trace_taskturnsIgnoreinto(failed=1, ExceptionInfo), so the new branch inRequest.on_failurereally runs in the worker. The event goes out before the ack, which is the same orderreject()uses fortask-rejected.IGNOREDisn't inPRECEDENCE, so it gets theNoneslot. That ranks aboveSTARTED/RECEIVED, which means a latetask-startedcan't pull the task back. Yourtest_task_ignored_is_kept_and_exportedcovers this.- Making
Replaceda subclass ofIgnorekeeps the existingexcept 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 forself.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.
|
Thanks for the careful look, @ege-arhan — the repro is clear and the point is fair: I left it out of 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 |
|
Agreed, leaving The test pinning the current behaviour ( |
ChristianMurphy
left a comment
There was a problem hiding this comment.
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.pyandt/unit/app/test_exceptions.pyas 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 raisesIgnore, still end asIGNORED.
What I did not run
- The existing
test_replace::test_sanitysmoke 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.
|
Thank you for the approval and for re-running it on both brokers, @ChristianMurphy. The last items are in:
@ege-arhan — added the pinning test as well: |
|
Pinning test and the Agree on |
Fixes #11093.
A task that raises
Ignoresends no event aftertask-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 oftask-rejectedforReject(#4222).Changes:
celery/worker/request.py:Request.on_failurenow emitstask-ignoredfrom theIgnorebranch before acknowledging, mirroring howRequest.reject()emitstask-rejected. The payload is just the taskuuid, as in the issue discussion.celery/events/state.py: maptask-ignoredtostates.IGNOREDinTASK_EVENT_TO_STATEand record the event timestamp on theTaskobject (ignoredfield), mirroringrejected, so monitors built oncelery.events.Statepick the state up automatically.task-ignoredsection in the monitoring guide, aftertask-rejected.test_on_failure_Ignore_sends_task_ignored_event(worker request) andtest_task_ignored_event_sets_ignored_state(events state), both mirroring the existingtask-rejectedtests.Tests (run locally on Windows 11, Python 3.13.14, against upstream/main de28509):
1 failed, 16 passedfor the worker request tests (send('task-ignored', ...)not called) and1 failedfor the events state test (Taskhas no attributeignored).pytest t/unit/worker/test_request.py -k Ignore— 17 passed;pytest t/unit/events/test_state.py -k ignored— 1 passed; full filest/unit/worker/test_request.py t/unit/events/test_state.py— 233 passed, 1 skipped, no regressions. The existingtest_on_failure_Ignore_acknowledgesstill passes — acknowledge behaviour is unchanged. Fullt/unit/eventsalso passes (104 passed, 2 skipped).One deliberate non-change, flagged for reviewers: like
REJECTED,IGNOREDis not added toREADY_STATES, soState.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.