Repository navigation
Pass chord, chain, and errbacks to mark_as_failure on unknown task (#11088) - #11101
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
A moderate active issue remains because the fallback can re-trigger lazy payload decoding on malformed messages, allowing unknown invalid tasks to escape rejection and failure handling.
1 open issue
What changed in this PR
This PR fixes unknown-task failure handling by preserving task metadata from protocol v1/v2 messages when calling backend.mark_as_failure(), enabling chord failures, chain propagation, and errbacks for unregistered tasks.
Changes:
- Extracts task and workflow metadata from message headers and decoded payloads.
- Passes decoded payloads through
create_task_handler()toon_unknown_task(). - Adds unit tests for protocol-specific metadata extraction and backend failure propagation.
| File | Description |
|---|---|
| t/unit/worker/test_consumer.py | Adds tests covering protocol v1/v2 metadata extraction and chord, chain, and errback propagation. |
| celery/worker/consumer/consumer.py | Reconstructs failure request metadata and forwards decoded payloads for backend handling of unknown tasks. |
Review effort: Lite
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #11101 +/- ##
==========================================
+ Coverage 91.32% 91.35% +0.02%
==========================================
Files 153 153
Lines 21842 21889 +47
Branches 2713 2721 +8
==========================================
+ Hits 19948 19997 +49
+ Misses 1593 1590 -3
- Partials 301 302 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
auvipy
left a comment
There was a problem hiding this comment.
can you check if this need additional smoke or integration tests?
|
and why the following error is happening plugin = ep.load() |
|
@ChristianMurphy can you check |
ChristianMurphy
left a comment
There was a problem hiding this comment.
Needs a couple of changes before merge. The fix itself works: I ran it at e7b493f1b against main (a2d470f19), and it does what I asked for in #11088.
One of the new tests fails. test_on_unknown_task_does_not_retry_lazy_payload_decode raises AttributeError: 'MalformedMessage' object has no attribute 'body', because on_unknown_task() logs through dump_body(), which reads message.body. It fails the same way at 62c8b41a6, before the merges of main, and with released kombu 5.7.0. Adding body = b'{' to the fake message makes it pass.
A message for an unknown task with no id still stops the worker. The new except branch is commented as handling malformed headers, but its group = payload.get('group') or (...) line calls .get() on None. I published a protocol 2 message with a task header and no id to a prefork worker on Redis:
| main | This PR | This PR with the two lines below | |
|---|---|---|---|
| Worker | exits, Unrecoverable error: TypeError |
exits, Unrecoverable error: AttributeError |
stays up |
| The message | back on the queue, for the next worker to hit | the same | rejected |
| A known task sent afterwards | not run | not run | runs |
That is long-standing on main, so I would not hold the PR for it by itself. But the PR adds the branch that is meant to handle it, so I'd fix the line while it is open:
group = (payload.get('group') or payload.get('taskset')) if isinstance(payload, dict) else Noneand, before the request is built, reject a message that has no id, since there is nothing to store the failure under (as it stands a protocol 1 body without an id is stored under the id None):
if id_ is None:
return self.on_unknown_message(body, message)What works. A worker without missing.task, 13 workflows around that task, prefork on a Redis broker and backend:
| main | This PR | |
|---|---|---|
| Cases with the wrong outcome | 9 of 13 | 0 of 13 |
| Chain after the unknown task | PENDING |
FAILURE |
| Chord with it in the header, or at the end of a header chain | body PENDING |
body FAILURE |
| Errback on the task, the chain or the chord body (new-style and old-style) | runs 0 times | runs once |
Success callback (link) on the unknown task |
does not run | does not run |
| Worker | stays up | stays up |
The solo, threads and gevent pools and the SQLite database backend give the same picture, and so does result_extended. The worker suites pass as tox runs them (python -bb): 811 here apart from the test above, 808 on main.
@auvipy asked whether this needs more integration or smoke tests. I think it does, and unit tests for two gaps as well.
The integration suite's session worker has no task under a made-up name, so the case needs no new fixtures. This class for t/integration/test_canvas.py passes here in 9 s, and all 4 tests fail with the fix reverted. It waits on each result's own state, because result.get() also raises for a failed parent while the result itself is still pending, which made my first version pass on main.
Integration tests
class test_unregistered_task:
"""A task name the worker does not have fails like any other task."""
MISSING = 't.integration.tasks.not_registered_anywhere'
def missing(self, manager, *args):
return signature(self.MISSING, args=args, app=manager.app)
def await_failure(self, result, timeout=TIMEOUT):
# Not result.get(): that also raises for a failed parent while
# this result is still pending.
deadline = monotonic() + timeout
while result.state != states.FAILURE:
assert monotonic() < deadline, (
f'{result.id} is {result.state}, expected FAILURE')
sleep(0.1)
def test_chain_fails_after_an_unregistered_task(self, manager):
res = chain(self.missing(manager), identity.s()).delay()
self.await_failure(res.parent)
self.await_failure(res)
def test_chord_fails_when_a_header_task_is_unregistered(self, manager):
try:
manager.app.backend.ensure_chords_allowed()
except NotImplementedError as e:
raise pytest.skip(e.args[0])
res = chord([identity.si(1), self.missing(manager)],
identity.s()).delay()
self.await_failure(res)
@pytest.mark.parametrize(
"errback_task", [errback_old_style, errback_new_style, ],
)
def test_errback_is_called_for_an_unregistered_task(
self, errback_task, manager
):
if not manager.app.conf.result_backend.startswith("redis"):
raise pytest.skip("Requires redis result backend.")
redis_connection = get_redis_connection()
sig = self.missing(manager)
sig.link_error(errback_task.s())
expected_redis_key = sig.freeze().id
redis_connection.delete(expected_redis_key)
res = sig.delay()
self.await_failure(res)
await_redis_count(1, redis_key=expected_redis_key)
redis_connection.delete(expected_redis_key)The unit tests miss two things I planted: the task handler passing None in place of the protocol 1 payload, and delivery_info left off the request. All of them still passed. These two tests catch both, and the second covers the message without an id (it needs the two lines above):
Unit tests for test_Consumer_on_unknown_task
def test_task_handler_passes_a_protocol_1_payload_on(self):
# Protocol 1 keeps the chord and errbacks in the decoded body, which
# only the task handler has.
c = self.get_consumer()
c.app.backend.mark_as_failure = Mock()
c.strategies = {}
payload = {
'id': 'task-id-proto1',
'task': 'unregistered.proto1.task',
'chord': {'chord_sig_p1': 'sig'},
'errbacks': [{'errback_sig_p1': 'err'}],
}
message = Mock(name='message')
message.body = b'{}'
message.headers = {}
message.decode.return_value = payload
message.properties = {}
message.delivery_info = {'routing_key': 'celery'}
c.create_task_handler()(message)
request = c.app.backend.mark_as_failure.call_args[1]['request']
assert request.id == 'task-id-proto1'
assert request.chord == {'chord_sig_p1': 'sig'}
assert request.errbacks == [{'errback_sig_p1': 'err'}]
assert request.delivery_info == {'routing_key': 'celery'}
@pytest.mark.parametrize('body', [None, {'task': 'unregistered.task'}])
def test_on_unknown_task_without_an_id_is_rejected(self, body):
# Protocol 2 headers, or a protocol 1 body, with no task id: there
# is nothing to store a failure under, and it must not raise.
c = self.get_consumer()
c.app.backend.mark_as_failure = Mock()
message = Mock(name='message')
message.body = b'[[], {}, {}]'
message.headers = {'task': 'unregistered.task'} if body is None else {}
message.decode.return_value = [[], {}, {}] if body is None else body
message.properties = {}
message.delivery_info = {}
c.on_unknown_task(body, message, KeyError('unregistered.task'))
c.app.backend.mark_as_failure.assert_not_called()
message.reject_log_error.assert_called_once()For the smoke suite I'd suggest the rolling-deploy case from the issue: two workers on one queue, only one of which has the task, and a chain and a chord sent while both are up. I have not written or run that one: I had no Docker here.
Protocol 1, odd messages, overhead, and what I did not run
- Protocol 1 (
task_protocol = 1): errbacks and chords are fixed. A chain after the unknown task staysPENDING, here and on main. A task that raises does the same under protocol 1, so that is how protocol 1 chains behave, not this change. - Bodies that are not valid JSON, a pickle body while only JSON is accepted, a body that is an object or a two-item list, and an empty body: each is rejected and stored as a failure with no chord or chain, on main and here, and the handler does not raise.
- Overhead, per unknown-task message in the consumer: 25 µs for a small body on both trees. The body is now decoded in the main process to read the chord and errbacks, so a 1 MB body takes 2.2 ms where main takes 1.4 ms, and a 20 MB body 44 ms where main takes 28 ms.
- I planted eight other bugs, each dropping one field from the request (
chord,chain,errbacks,group,group_index,id,callbacks,parent_id). Each fails at least one of the PR's tests. - Not run: RabbitMQ, eventlet, the full integration and smoke suites, and Python versions other than 3.13.
ChristianMurphy
left a comment
There was a problem hiding this comment.
Needs one more change before merge, and I'd like a smoke test with it. I ran cd2d8f538 against main (c5742e22c).
Both points from my last review are fixed:
Last head (e7b493f1b) |
Now | |
|---|---|---|
test_on_unknown_task_does_not_retry_lazy_payload_decode |
fails | passes |
A protocol 2 message for an unknown task with no id |
worker exits | rejected, worker stays up, the next task runs |
| The 13 workflows around an unknown task, prefork on Redis | 13 right | 13 right |
The solo, threads and gevent pools, protocol 1, result_extended and the SQLite backend give the same results as before, and the worker stayed up in every run. t/unit/worker as tox runs it (python -bb): 827 passed. The four integration tests pass here on Redis in 9 s and all four fail on main.
A message whose canvas fields have the wrong type now stops the worker. The handler passes chain, chord and errbacks from the message to mark_as_failure() as they are. If one is not what the backend expects, the exception leaves the consumer. I published a protocol 2 message for an unknown task with "chain": ["not-a-signature"] to a prefork worker on Redis:
| main | This PR | This PR with the change below | |
|---|---|---|---|
| Worker | stays up | exits, Unrecoverable error: ValueError |
stays up |
| A known task sent afterwards | runs | not run | runs |
The message is rejected before the failure is stored, so a restarted worker does not meet it again. It still takes a malformed message to stop a worker that main keeps running. In the handler with the in-memory cache backend and nothing mocked, six shapes raise here that do not on main: errbacks as a number, chord as a string, chain as a string or a list of strings, and group as a number or an object. Catching the error around the store keeps the worker up for all six.
Change and unit test
- self.app.backend.mark_as_failure(
- id_, NotRegistered(name), request=request,
- )
+ try:
+ self.app.backend.mark_as_failure(
+ id_, NotRegistered(name), request=request,
+ )
+ except Exception: # pylint: disable=broad-except
+ # The message is already rejected. A canvas field of the
+ # wrong type must not stop the consumer.
+ logger.exception(
+ 'Could not store the failure of unknown task %r (%s)',
+ name, id_)For t/unit/worker/test_consumer.py. Both cases fail here and pass with the change:
@pytest.mark.parametrize('field, value', [
('chain', ['not-a-signature']),
('errbacks', 5),
])
def test_on_unknown_task_survives_malformed_canvas_fields(self, field, value):
# The failure is stored through the real backend here: a field of
# the wrong type must not raise out of the consumer and stop it.
c = self.get_consumer()
embed = {'callbacks': None, 'errbacks': None, 'chain': None, 'chord': None}
embed[field] = value
message = Mock(name='message')
message.body = b'[]'
message.headers = {'id': 'task-id-bad-fields', 'task': 'unregistered.task'}
message.properties = {}
message.delivery_info = {}
message.decode.return_value = [[], {}, embed]
c.on_unknown_task(None, message, KeyError('unregistered.task'))
message.reject_log_error.assert_called_once()A smoke test for the rolling deploy. @auvipy asked about smoke tests. The case to cover is a worker that does not have the task yet, as in a rolling deploy. The test below passes here and fails on main (the last task is PENDING), on the RabbitMQ and the Redis broker.
Smoke test
At the end of t/smoke/tests/test_canvas.py, with from time import monotonic, sleep added to the imports:
class test_unregistered_task:
"""A worker that does not have the task yet, as during a rolling deploy."""
def test_chain_fails_and_the_worker_keeps_working(self, celery_setup: CeleryTestSetup):
queue = celery_setup.worker.worker_queue
missing = signature("t.smoke.tasks.not_deployed_yet", app=celery_setup.app, queue=queue)
res = chain(missing, identity.s().set(queue=queue)).apply_async()
# Not res.get(): it also raises for the failed first task while
# the last one is still pending.
deadline = monotonic() + RESULT_TIMEOUT
while res.state != "FAILURE":
assert monotonic() < deadline, f"the last task is {res.state}, expected FAILURE"
sleep(0.5)
after = identity.si("still up").apply_async(queue=queue)
assert after.get(timeout=RESULT_TIMEOUT) == "still up"For my 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:
on_task_receivednow hands the protocol 1 payload toon_unknown_task. With that line put back toNoneall tests still pass, because the handler decodes the message itself. Either the argument or the second decode can go.- The handler decodes the body in the main process for an unknown task. That costs 30 µs per message against 20 µs on main for a small body, and 53 ms against 33 ms for a 20 MB body. It only happens for unknown tasks.
- A
taskheader that is a list still raises before the handler is reached. That is the same on main.
What I did not run
- RabbitMQ as the broker outside the smoke test, and eventlet.
- The full integration and smoke suites, and Python versions other than 3.13.
|
Also i am fixing the fakeredis failure in another PR |

Description
Fixes #11088
When a worker receives a task name that is not registered, Consumer.on_unknown_task() marks the task as a failure via �ackend.mark_as_failure(). Previously, on_unknown_task() constructed a synthetic Bunch request that hardcoded chord=None, errbacks=None, and omitted chain, group, and group_index.
As a result:
equest.errbacks was None.
Solution
ame,
oot_id, parent_id, group, group_index, chord, chain, errbacks, callbacks, correlation_id,
eply_to, and delivery_info on the
equest passed to �ackend.mark_as_failure().