Skip to content

fix(canvas): link errbacks to nested chords in a frozen chord header - #10784

Open
subham-hq wants to merge 10 commits into
celery:mainfrom
subham-hq:fix/chord-nested-errback-after-freeze
Open

subham-hq wants to merge 10 commits into
celery:mainfrom
subham-hq:fix/chord-nested-errback-after-freeze

Conversation

@subham-hq

Copy link
Copy Markdown
Contributor

Fixes #10783

Description

chord.link_error() handles chords nested in its header as a special case (#9580). With the default task_allow_error_cb_on_chord_header=False, it links the errback to the nested chord so that a failure in the inner chord's header reaches it. The special case stops working once the chord is frozen:

inner = chord([add.si(1), fail.si()], tsum.s())
outer = chord([inner, add.si(3, 3)], tsum.s())

outer.on_error(eb.s()).apply_async()                         # eb called once
chain(add.si(0, 0), outer).on_error(eb.s()).apply_async()    # eb never called

freeze() replaces the header list with a group. A group is a dict subclass, so maybe_list(self.tasks) returns it as a single item and isinstance(task, chord) never matches. _chain.prepare_steps() freezes each step before linking the chain's errbacks to it, so every chain(...).on_error() / link_error= with such a chord is affected. Calling freeze() before link_error() on a chord directly has the same effect. When the inner header fails, no errback is called, and the chord does not complete either (as designed, see test_nested_chord_header_link_error), so the failure goes unnoticed.

Fix

  • Look at the tasks of the group (getattr(self.tasks, 'tasks', self.tasks)), as stamp() and __length_hint__() already do.
  • Run the special case only when task_allow_error_cb_on_chord_header is False, which is the configuration Bugfix: Chord with a chord in header doesn't invoke error callback on inner chord header failure (default config) #9580 targeted. When it is True, the first loop already links every header task, nested chords included. The special case linked the nested chord's body a second time, so the errback ran twice for one failure. Without this change, the first fix would have spread that duplicate to chains.
  • chord.set_immutable() iterated self.tasks the same way and raised AttributeError: 'str' object has no attribute 'set_immutable' after freeze(), because iterating the group yields its dict keys. It now uses the same unwrapping.

Before / after: errbacks called when the inner chord's header fails

Output of the reproduction script in #10783 (in-process worker, memory:// broker, cache+memory:// backend):

task_allow_error_cb_on_chord_header Standalone nested chord chain(add, nested chord).on_error(eb)
False (default) ['ChordError'] → ['ChordError'] [] → ['ChordError']
True ['ChordError', 'ChordError', 'ValueError'] → ['ChordError', 'ValueError'] ['ChordError', 'ValueError'] → ['ChordError', 'ValueError']
Before After
chord.freeze(); chord.set_immutable(True) AttributeError header tasks marked immutable, body unchanged

After the change each failure is reported exactly once, and frozen and unfrozen chords produce the same errback wiring under both settings.

Tests

  • test_link_error_on_nested_chord[unfrozen|frozen|chain] (default setting): the nested chord's body gets the errback. The chain case goes through prepare_steps(), like a real chain. frozen and chain fail on main.
  • test_link_error_on_nested_chord_with_header_errbacks[unfrozen|frozen|chain] (True): the nested chord's body gets the errback exactly once. unfrozen fails on main (duplicate). frozen and chain pass on main and check that behavior there is unchanged.
  • test_set_immutable_after_freeze: fails on main with AttributeError.

The full t/unit suite passes except for failures that also occur on unmodified main in my environment (root user, no broker). flake8, isort and codespell are clean.

Added an entry under Unreleased in Changelog.rst.

subham-hq and others added 3 commits October 3, 2026 17:48
chord.link_error() handles chords nested in its header as a special case
(celery#9580): with the default task_allow_error_cb_on_chord_header=False, it
links the errback to the nested chord so that a failure in the inner
chord's header reaches it. The loop iterated maybe_list(self.tasks).
freeze() replaces the header list with a group, a dict subclass, which
maybe_list() returns as a single item, so no nested chord was found.

_chain.prepare_steps() freezes each step before linking the chain's
errbacks to it, so every chain(..., chord).on_error(eb) or
link_error=eb whose chord has a nested chord in its header was affected.
When the inner chord's header fails, no errback is called. The chord
does not complete either, as designed, so the failure goes unnoticed.

Look at the tasks of the group, as stamp() and __length_hint__() do.
Also run this special case only when task_allow_error_cb_on_chord_header
is False: when it is True, the loop above already links every header
task, nested chords included, and the special case linked the nested
chord's body a second time, so the errback ran twice for one failure.

chord.set_immutable() iterated self.tasks the same way and raised
AttributeError ('str' object has no attribute 'set_immutable') after
freeze(), because iterating the group yields its dict keys.
Also move the entry next to the related chord countdown/eta entry, so
that it does not conflict with other entries added at the end.
@auvipy
auvipy requested review from Nusnus and auvipy and removed request for Nusnus and auvipy October 3, 2026 18:21
@auvipy auvipy added this to the 5.7.x milestone Oct 4, 2026
@auvipy
auvipy self-requested a review October 8, 2026 03:43
The changelog is written at release time, and 5.7.0rc1 rewrote
Changelog.rst, so the entry only causes conflicts. Leave it out of this
change, as asked in review.
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.38%. Comparing base (c0b177e) to head (a2b2470).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10784      +/-   ##
==========================================
+ Coverage   91.35%   91.38%   +0.02%     
==========================================
  Files         153      153              
  Lines       21896    21907      +11     
  Branches     2722     2723       +1     
==========================================
+ Hits        20004    20020      +16     
+ Misses       1590     1586       -4     
+ Partials      302      301       -1     
Flag Coverage Δ
unittests 91.36% <100.00%> (+0.02%) ⬆️

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.

@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy this looks good to me. what do you think?

@auvipy

auvipy commented Nov 24, 2026

Copy link
Copy Markdown
Member

the unit test coverage reduced to 60 % only. please also improve the unit test coverage

@subham-hq

Copy link
Copy Markdown
Contributor Author

Following up from #10783, I verified with Redis that apply_async(link_error=...) now calls the errback once when the inner chord’s header fails, and the outer body stays PENDING.

@subham-hq

Copy link
Copy Markdown
Contributor Author

@auvipy I found two regressions in follow-up testing. If the inner chord’s body fails, the errback can run twice. Passing link_error also makes generator-backed headers consume more tasks before publishing the first one. I’ll address both here in a moment.

Forward header-failure errbacks during dispatch to preserve lazy chord headers.
@subham-hq

Copy link
Copy Markdown
Contributor Author

@auvipy Both follow-up regressions are fixed in 0d00702. A failure in the inner chord’s body now calls the errback once, and generator-backed headers publish incrementally again. I also verified that the original inner-header failure still calls the errback once and leaves the outer body PENDING.

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

Needs a change before merge. I ran 0d0070277, with today's two commits, against main (c0b177ede) with a worker on Redis 7, and again on PostgreSQL 16 with RabbitMQ 4.0. The results differ by backend.

An inner chord in the header of an outer chord, the inner header fails, default settings. Errback calls:

Redis, main Redis, this PR PostgreSQL, main PostgreSQL, this PR
outer.on_error(eb) 1 1 2 2
freeze(), then link_error(eb) 0 1 1 2
chain(task, outer).on_error(eb) 0 1 1 2
chain(task, outer).apply_async(link_error=eb) 0 1 1 2
Three levels of chords, in a chain 0 1 1 3
outer.apply_async(link_error=eb) 0 1 1 2
The outer body PENDING, never ends the same FAILURE FAILURE

On a database backend this adds a second errback call for one failure, and today's "avoid duplicate nested chord errbacks" commit does not change that. I got the same numbers at a9f36a5d1 and at 0d0070277. There the outer chord already fails when the inner one does, and its body's errback runs. Linking the errback to the inner chord as well calls it once per level. So "each failure is reported once" holds on Redis only, and it holds there because the outer chord never ends.

I think the cause is one step earlier. On Redis nothing tells the outer chord that the inner chord failed: chord_error_from_stack() stores the failure of the inner body, but the inner body is a header task of the outer chord and its part is never counted. The special case in link_error() makes up for that by linking the errback to the inner chord. With the lines below on main the outer chord ends in FAILURE on Redis as it does on PostgreSQL, and with the special case removed as well the errback runs once in every row above, on both backends. That includes outer.apply_async(link_error=eb), which I raised on #10783, without passing the errback down into the header (_chord_header_errbacks).

With the lines below, and the special case removed Redis PostgreSQL
Errback calls, each of the six rows above 1 1
The outer body FAILURE FAILURE

It changes what Redis does: an outer chord that waited forever now fails. I think that is the right outcome, and it needs a maintainer's yes, @auvipy. t/unit/tasks, t/unit/backends and t/unit/app/test_builtins.py give the same results with it as on main.

The lines, in chord_error_from_stack() in celery/backends/base.py

After backend._fail_chain(callback.options.get("chain"), exc):

        outer = callback.options.get("chord")
        if outer:
            # The body is itself a header task of another chord (a chord
            # nested in a chord header): count its failure there, so the
            # outer chord ends instead of waiting for it forever.
            part = _create_fake_task_request(
                task_id=callback_id, task_name=callback.task, chord=outer,
                group=callback.options.get("group_id"),
                group_index=callback.options.get("group_index"),
            )
            backend.on_chord_part_return(part, states.FAILURE, exc)

The set_immutable() fix is right and stands on its own: it raises AttributeError after freeze() on main and works here.

Smaller things:

  • With task_allow_error_cb_on_chord_header on, this PR removes a duplicate call for outer.on_error(eb) (3 calls to 2 on Redis, 4 to 3 on PostgreSQL). That part is an improvement on both backends.
  • The new unit tests check which signature holds the errback. A test that runs the chord and counts the calls would have shown the difference between backends. test_nested_chord_header_link_error in t/integration/test_canvas.py, which today's commit extends, runs on Redis only.
What I did not run
  • Any result backend other than Redis and PostgreSQL.
  • The integration and smoke suites, and Python versions other than 3.13.

@subham-hq

Copy link
Copy Markdown
Contributor Author

@ChristianMurphy On it, just a moment.

Report a failed inner body as a completed outer header part and let the outer chord run its own errback. Cover the result and errback count on native and polling backends.
@subham-hq

Copy link
Copy Markdown
Contributor Author

Thanks for the cross-backend repro, @ChristianMurphy. I pushed a2b2470. A failed inner chord body now counts as a failed part of the outer header. I removed the nested errback forwarding and kept the set_immutable() fix.

With default settings, all six cases from your review now reach FAILURE and call the outer errback once on Redis 7 and PostgreSQL 16 with RabbitMQ 4.0. They also passed on Memcached, along with an additional case where the inner chord has a group body.

@auvipy, could you confirm that changing the Redis result from PENDING to FAILURE is the behavior you want 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.

Needs one more change before merge, and a merge of main. Re-tested a2b24701f against main (bffee14b2). The six cases from my last review now end FAILURE with one errback call on Redis, PostgreSQL and memcached.

An inner chord whose body is a group with a chain in it loses its errback. The chain has no chord option, only its last task does, so _return_failed_chord_part() returns without counting it.

inner = chord([add.s(1, 1), boom.s()], group(chain(body.s(), add.s(1)), body.s()))
chord([inner, add.s(2, 2)], body.s()).on_error(eb.s()).apply_async()
Redis 7.4, 3 of 3 runs Errback calls Outer body
main 2 PENDING
This PR 0 PENDING
This PR, with the change below 1 FAILURE
The change I tried in _return_failed_chord_part()
    from celery.canvas import _chain

    # A chain in a group body keeps the enclosing chord on its last task.
    while isinstance(callback, _chain) and callback.tasks and "chord" not in callback.options:
        callback = maybe_signature(callback.tasks[-1], app=backend.app)

It goes above options = callback.options. It has no unit test yet.

The branch conflicts with main in celery/backends/gcs.py and t/unit/backends/test_gcs.py, after #11072.

The description also still describes the first approach.

What I ran
  • Celery at a2b24701f and main at bffee14b2, with kombu main (9cd1cef8), Python 3.13, prefork with 2 processes.
  • The six cases, 3 of 3 runs each: Redis 7.4, PostgreSQL 16 with RabbitMQ 4.3, and memcached 1.6 with a Redis broker. Each ends FAILURE with one errback call and no result left PENDING.
  • The chord above on memcached gives the same counts as on Redis. On PostgreSQL it ends FAILURE with one call.
  • 31 more nested chords per backend, main against this PR. No other one is worse than main.
  • The new unit tests: 12 of 12 pass, and 7 of them fail on main's source.
  • Not run: DynamoDB, GCS and MongoDB, pools other than prefork, and the smoke suite.

@auvipy

auvipy commented Nov 29, 2026

Copy link
Copy Markdown
Member

also the merge conflicts

This branch has not been deployed

No deployments
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.

chain(..., chord).on_error() never calls the errback when the chord's header contains a nested chord

3 participants