Skip to content

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

Open

Description

@subham-hq

Checklist

  • I have verified that the issue exists against the main branch of Celery.
  • This has already been asked to the discussions forum first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).
  • I have tried to reproduce the issue with pytest-celery and added the reproduction script below.

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one message broker and/or
    result backend.

    Not with a live broker. Reproduced with the in-memory broker and backend; the failing code path is in celery/canvas.py and does not depend on them.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None

Environment & Settings

Celery version: 5.7.0a1, main @ 508c112

celery report Output:

software -> celery:5.7.0a1 (recovery) kombu:5.7.0a1 py:3.11.15
            billiard:4.3.0 memory:N/A
platform -> system:Linux arch:64bit, ELF
            kernel version:6.18.44-fc-v64 imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:memory results:cache+memory://

broker_url: 'memory://:********@localhost//'
result_backend: 'cache+memory://'
deprecated_settings: None

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: N/A or Unknown
  • Minimal Celery Version: N/A or Unknown (reproduced on main @ 508c112)
  • Minimal Kombu Version: N/A or Unknown
  • Minimal Broker Version: N/A (in-memory broker)
  • Minimal Result Backend Version: N/A (cache+memory://)
  • Minimal OS and/or Kernel Version: N/A or Unknown
  • Minimal Broker Client Version: N/A or Unknown
  • Minimal Result Backend Client Version: N/A or Unknown

Python Packages

pip freeze Output:

amqp==5.4.0
billiard==4.3.0
celery @ main (508c112)
click==8.5.0
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.0
kombu==5.7.0a1
python-dateutil==2.9.0.post0
tzdata==2026.5
tzlocal==5.4.4
vine==5.1.0

Other Dependencies

Details

N/A

Minimally Reproducible Test Case

Details

import time

from celery import Celery, chain, chord
from celery.contrib.testing.worker import start_worker

app = Celery('repro', broker='memory://', backend='cache+memory://')
calls = []


@app.task
def add(x, y=0):
    return x + y


@app.task
def tsum(xs):
    return sum(xs)


@app.task
def fail(*args):
    raise ValueError('boom')


@app.task
def on_error(request, exc, traceback):
    calls.append(type(exc).__name__)


def nested_chord():
    inner = chord([add.si(1), fail.si()], tsum.s())
    return chord([inner, add.si(3, 3)], tsum.s())


def errback_calls(canvas):
    calls.clear()
    canvas.on_error(on_error.s()).apply_async()
    time.sleep(3)
    return sorted(calls)


with start_worker(app, pool='solo', perform_ping_check=False, loglevel='CRITICAL'):
    for setting in (False, True):
        app.conf.task_allow_error_cb_on_chord_header = setting
        print(f'task_allow_error_cb_on_chord_header={setting}')
        print('  standalone chord:         ', errback_calls(nested_chord()))
        print('  chain ending in the chord:', errback_calls(chain(add.si(0, 0), nested_chord())))

# chord.set_immutable() after freeze()
c = chord([add.s(1), add.s(2)], tsum.s())
c.freeze()
try:
    c.set_immutable(True)
except AttributeError as exc:
    print('set_immutable after freeze:', repr(exc))

Expected Behavior

The errback is called once for each failure, whether the chord is applied on its own or as a step of a chain:

task_allow_error_cb_on_chord_header=False
  standalone chord:          ['ChordError']
  chain ending in the chord: ['ChordError']
task_allow_error_cb_on_chord_header=True
  standalone chord:          ['ChordError', 'ValueError']
  chain ending in the chord: ['ChordError', 'ValueError']

chord.set_immutable(True) after freeze() marks the header tasks immutable.

Actual Behavior

task_allow_error_cb_on_chord_header=False
  standalone chord:          ['ChordError']
  chain ending in the chord: []
task_allow_error_cb_on_chord_header=True
  standalone chord:          ['ChordError', 'ChordError', 'ValueError']
  chain ending in the chord: ['ChordError', 'ValueError']
set_immutable after freeze: AttributeError("'str' object has no attribute 'set_immutable'")
  1. With the default setting, the errback is never called when the chord is a step of a chain. The chord does not complete either (as designed, see test_nested_chord_header_link_error), so the failure goes unnoticed. chord.link_error() links the errback to chords nested in the header in a special case added in Bugfix: Chord with a chord in header doesn't invoke error callback on inner chord header failure (default config) #9580. That special case iterates 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 is found. _chain.prepare_steps() freezes each step before linking the chain's errbacks to it, so every chain with on_error() / link_error and such a chord is affected. Calling freeze() before link_error() on a chord directly has the same effect.
  2. With task_allow_error_cb_on_chord_header=True, the errback runs twice for the inner chord's failure. The first loop in link_error() already links every header task, nested chords included. The special case then links the nested chord's body a second time.
  3. chord.set_immutable() raises AttributeError after freeze(). It iterates self.tasks, which yields the group's dict keys.

Activity

  1. added a commit that references this issue on Oct 3, 2026
  2. ChristianMurphy commented on Nov 12, 2026

    @ChristianMurphy
    Contributor

    The errback is also missed on a second path, chord.apply_async(link_error=...), which is new in 5.7.0 with #10778. From reading #10784 it doesn't cover that path. I'd fix it there too, by linking the errback to a chord in the header as link_error() does. @subham-hq, does that fit your PR?

    Main (9c2f238), outer = chord([chord([add, boom], tsum), add], tsum) Errback calls Outer body
    outer.on_error(eb.si()).apply_async() 1 PENDING
    outer.apply_async(link_error=eb.si()) 0 PENDING
    A chord without the nested chord, apply_async(link_error=eb.si()) 1 FAILURE

    Each row is 3 of 3 runs. On 5.5.3 the call raises TypeError.

    Cause and script

    chord.link_error() links the errback to a chord in the header (celery/canvas.py:2744). apply_async() goes through _add_body_callbacks() instead, which gives link_error to the body only (canvas.py:2594). #10784 changes link_error() and leaves _add_body_callbacks() as it is. I read its diff and didn't run it.

    The outer chord doesn't complete by design, so the errback is the only signal a caller gets.

    # tasks.py
    import redis
    from celery import Celery
    
    app = Celery("tasks", broker="redis://localhost:6379/0",
                 backend="redis://localhost:6379/1")
    calls = redis.Redis(db=2)
    
    
    @app.task
    def add(x, y=0):
        return x + y
    
    
    @app.task
    def tsum(numbers):
        return sum(numbers)
    
    
    @app.task
    def boom():
        raise ValueError("boom")
    
    
    @app.task
    def eb(*args):
        calls.incr("errback")
    # run.py
    import os
    import sys
    import time
    
    from celery import chord
    
    from tasks import add, app, boom, calls, eb, tsum
    
    calls.delete("errback")
    inner = chord([add.s(1), boom.s()], tsum.s())
    outer = chord([inner, add.s(10)], tsum.s())
    if "on_error" in sys.argv:
        res = outer.on_error(eb.si()).apply_async()
    else:
        res = outer.apply_async(link_error=eb.si())
    time.sleep(6)
    state = app.backend.get_task_meta(res.id)["status"]
    print("errback calls:", int(calls.get("errback") or 0), "| outer body:", state,
          flush=True)
    os._exit(0)                         # skips the result cleanup at exit, which is noisy for a pending result
    $ celery -A tasks worker -c 2 -l warning
    $ python run.py on_error
    errback calls: 1 | outer body: PENDING
    $ python run.py
    errback calls: 0 | outer body: PENDING
  3. added this to the 5.7.x milestone on Nov 24, 2026
  4. auvipy commented on Nov 24, 2026

    @auvipy
    Member

    @subham-hq did you check?

  5. subham-hq commented on Nov 24, 2026

    @subham-hq
    ContributorAuthor

    @auvipy Sorry for the slow reply. I got caught up with work. I reproduced Christian’s apply_async(link_error=...) case with Redis and pushed the fix and regression test to #10784. The errback now runs exactly once when the inner chord’s header fails, and the outer body stays PENDING, matching .on_error(). Thanks for catching this, @ChristianMurphy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions