Skip to content

task_id must not be empty with chain as body of a chord #9773

Closed

Description

@dfm88

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.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • 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 Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None

Environment & Settings

Celery version:
5.5.3

celery report Output:

software -> celery:5.5.3 (immunity) kombu:5.5.4 py:3.11.4
            billiard:4.2.1 py-amqp:5.3.1
platform -> system:Darwin arch:64bit
            kernel version:24.5.0 imp:CPython
loader   -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled

deprecated_settings: None

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: N/A or Unknown
  • Minimal Celery Version: N/A or Unknown
  • Minimal Kombu Version: N/A or Unknown
  • Minimal Broker Version: N/A or Unknown
  • Minimal Result Backend Version: N/A or Unknown
  • 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.3.1
billiard==4.2.1
boto3==1.38.40
botocore==1.38.40
celery==5.5.3
certifi==2025.6.15
charset-normalizer==3.4.2
click==8.2.1
click-didyoumean==0.3.1
click-plugins==1.1.1
click-repl==0.3.0
debugpy==1.8.14
docker==7.1.0
idna==3.10
iniconfig==2.1.0
jmespath==1.0.1
kombu==5.5.4
packaging==25.0
pluggy==1.6.0
prompt_toolkit==3.0.51
psutil==7.0.0
Pygments==2.19.1
pytest==8.4.1
pytest-celery==1.2.0
pytest_docker_tools==3.1.9
python-dateutil==2.9.0.post0
python-memcached==1.62
redis==6.2.0
requests==2.32.4
s3transfer==0.13.0
six==1.17.0
tenacity==9.1.2
tzdata==2025.2
urllib3==1.26.20
vine==5.1.0
wcwidth==0.2.13

Other Dependencies

Details

N/A

Minimally Reproducible Test Case

Details

standalone reproduction scripts using pytest-celery link

Create 3 files named:

  • requirements-pytest-celery.txt
  • bug_task.py
  • test_celery_bug_report.py

With the following content, and then run the below commands in the shell

python -m venv .venv

source .venv/bin/activate

pip install -r requirements-pytest-celery.txt

pytest test_celery_bug_report.py
# requirements-pytest-celery.txt
pytest-celery[all]>=1.2.0
pytest>=7.0.0
# bug_task.py

"""
Bug reproduction tasks for the pytest-celery bug report.

These tasks are used to reproduce the ValueError: task_id must not be empty
that occurs when a group with a failing task is part of a chain.
"""

import time
from celery import shared_task


@shared_task
def add(x, y):
    """Simple addition task with sleep to simulate work"""
    print(f"Adding {x} + {y}")
    time.sleep(1)
    result = x + y
    print(f"Result: {result}")
    return result


@shared_task
def failc():
    """Task that always fails to trigger the bug"""
    print("About to fail...")
    raise ValueError("failc - intentional failure")
# test_celery_bug_report.py

# flake8: noqa
"""
Pytest-Celery Bug Report

This test reproduces the ValueError: task_id must not be empty. Got None instead.
that occurs when a task in a group fails and the group is part of a chain.

To run:
1. Install pytest-celery: pip install -U "pytest-celery[all]"
2. Run: pytest test_celery_bug_report.py

The plugin will automatically:
- Start a Redis Docker container for broker and backend
- Start a Celery worker Docker container
- Run the test and clean up afterward

Docs: https://docs.celeryq.dev/projects/pytest-celery/en/latest/userguide/celery-bug-report.html
"""

from __future__ import annotations

import pytest
import time
from celery import Celery, chain, group
from celery.canvas import Signature
from celery.result import AsyncResult

from pytest_celery import CeleryBackendCluster
from pytest_celery import CeleryBrokerCluster
from pytest_celery import CeleryTestSetup
from pytest_celery import RedisTestBackend
from pytest_celery import RedisTestBroker

###############################################################################
# Redis Broker Setup
###############################################################################

@pytest.fixture
def celery_broker_cluster(celery_redis_broker: RedisTestBroker) -> CeleryBrokerCluster:
    cluster = CeleryBrokerCluster(celery_redis_broker)
    yield cluster
    cluster.teardown()

@pytest.fixture
def default_redis_broker_image() -> str:
    return "redis:latest"

###############################################################################
# Redis Backend Setup
###############################################################################

@pytest.fixture
def celery_backend_cluster(celery_redis_backend: RedisTestBackend) -> CeleryBackendCluster:
    cluster = CeleryBackendCluster(celery_redis_backend)
    yield cluster
    cluster.teardown()

@pytest.fixture
def default_redis_backend_image() -> str:
    return "redis:latest"

###############################################################################
# Worker Configuration
###############################################################################

@pytest.fixture(scope="session")
def default_worker_celery_version() -> str:
    return ""  # Use latest version

@pytest.fixture(scope="session")
def default_worker_celery_log_level() -> str:
    return "INFO"

@pytest.fixture(scope="session")
def default_worker_celery_worker_queue() -> str:
    return "celery"

@pytest.fixture
def default_worker_command(default_worker_command: list[str]) -> list[str]:
    return default_worker_command + [
        "--without-gossip",
        "--without-mingle",
        "--without-heartbeat",
    ]

@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
    app = default_worker_app
    # Configure app for bug reproduction
    app.conf.update(
        task_serializer='json',
        accept_content=['json'],
        result_serializer='json',
        timezone='UTC',
        enable_utc=True,
        task_track_started=True,
        task_always_eager=False,
    )
    return app

###############################################################################
# Custom Tasks for Bug Reproduction
###############################################################################

import bug_tasks

@pytest.fixture
def default_worker_tasks(default_worker_tasks: set) -> set:
    default_worker_tasks.add(bug_tasks)
    return default_worker_tasks

###############################################################################
# Bug Reproduction Test
###############################################################################

def test_group_chain_failure_bug(celery_setup: CeleryTestSetup, caplog: pytest.LogCaptureFixture):
    """
    Reproduces the bug: ValueError: task_id must not be empty. Got None instead.
    
    When a group containing a failing task is part of a chain with additional tasks,
    instead of proper error propagation, a ValueError is raised.
    """
    from bug_tasks import add, failc

    # This chain triggers the bug:
    # - group contains one successful and one failing task
    # - followed by two more tasks in the chain
    mychain = chain(
        group([add.si(15, 7), failc.si()]),
        add.si(9, 7),
        add.si(5, 7)
    )
    
    _ = mychain.apply_async(queue=celery_setup.worker.worker_queue)
    
    time.sleep(10) 
    
    assert (
        "ValueError: task_id must not be empty. Got None instead" not in celery_setup.worker.logs()
    ), "Expected task error, not celery ValueError on task_id being None"

Expected Behavior

I'm encountering a ValueError: task_id must not be empty. Got None instead. when using chords with a specific pattern: a group containing both succeeding and failing tasks, followed by a chain body with multiple tasks.

This issue was previously reported in above discussions, and there was an attempt to fix it, but the issue still persists in the latest version (5.5.3).

The chain should fail with the exception from failc(), allowing proper error handling.

Actual Behavior

The following error occurs:

 -------------- [email protected] v5.5.3 (immunity)
--- ***** ----- 
-- ******* ---- macOS-15.5-arm64-arm-64bit 2025-06-19 23:39:11
- *** --- * --- 
- ** ---------- [config]
- ** ---------- .> app:         celery_failing:0x104befdd0
- ** ---------- .> transport:   redis://localhost:6379//
- ** ---------- .> results:     redis://localhost:6379/
- *** --- * --- .> concurrency: 10 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- 
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery
                

[tasks]
  . tasks.add
  . tasks.failc

[2025-06-19 23:39:11,730: INFO/MainProcess] Connected to redis://localhost:6379//
[2025-06-19 23:39:11,750: INFO/MainProcess] mingle: searching for neighbors
[2025-06-19 23:39:12,789: INFO/MainProcess] mingle: all alone
[2025-06-19 23:39:12,824: INFO/MainProcess] [email protected] ready.
[2025-06-19 23:39:16,731: INFO/MainProcess] Task tasks.add[2069eb9f-b57e-48e4-98d8-595efd5f5922] received
[2025-06-19 23:39:16,735: INFO/MainProcess] Task tasks.failc[f9032a00-4ee6-4430-bf27-eb04f3d66cd7] received
[2025-06-19 23:39:16,748: ERROR/ForkPoolWorker-1] Task tasks.failc[f9032a00-4ee6-4430-bf27-eb04f3d66cd7] raised unexpected: Exception('failc')
Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/app/trace.py", line 453, in trace_task
    R = retval = fun(*args, **kwargs)
                 ^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/app/trace.py", line 736, in __protected_call__
    return self.run(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/tasks.py", line 13, in failc
    raise Exception("failc")
Exception: failc
[2025-06-19 23:39:19,750: ERROR/ForkPoolWorker-8] Chord 'e0e30bbb-f009-455e-9cdd-3bb1df2e6619' raised: ChordError("Dependency f9032a00-4ee6-4430-bf27-eb04f3d66cd7 raised Exception('failc')")
Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in on_chord_part_return
    resl = [unpack(tup, decode) for tup in resl]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in <listcomp>
    resl = [unpack(tup, decode) for tup in resl]
            ^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 439, in _unpack_chord_result
    raise ChordError(f'Dependency {tid} raised {retval!r}')
celery.exceptions.ChordError: Dependency f9032a00-4ee6-4430-bf27-eb04f3d66cd7 raised Exception('failc')
[2025-06-19 23:39:19,755: WARNING/ForkPoolWorker-8] /Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/app/trace.py:662: RuntimeWarning: Exception raised outside body: ValueError('task_id must not be empty. Got None instead.'):
Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in on_chord_part_return
    resl = [unpack(tup, decode) for tup in resl]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in <listcomp>
    resl = [unpack(tup, decode) for tup in resl]
            ^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 439, in _unpack_chord_result
    raise ChordError(f'Dependency {tid} raised {retval!r}')
celery.exceptions.ChordError: Dependency f9032a00-4ee6-4430-bf27-eb04f3d66cd7 raised Exception('failc')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/app/trace.py", line 520, in trace_task
    task.backend.mark_as_done(
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 159, in mark_as_done
    self.on_chord_part_return(request, state, result)
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 554, in on_chord_part_return
    return self.chord_error_from_stack(callback, exc)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 304, in chord_error_from_stack
    return backend.fail_from_current_stack(callback.id, exc=exc)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 311, in fail_from_current_stack
    self.mark_as_failure(task_id, exc, exception_info.traceback)
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 167, in mark_as_failure
    self.store_result(task_id, exc, state,
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 526, in store_result
    self._store_result(task_id, result, state, traceback,
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 975, in _store_result
    current_meta = self._get_task_meta_for(task_id)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 997, in _get_task_meta_for
    meta = self.get(self.get_key_for_task(task_id))
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 871, in get_key_for_task
    raise ValueError(f'task_id must not be empty. Got {task_id} instead.')
ValueError: task_id must not be empty. Got None instead.

  warn(RuntimeWarning(

[2025-06-19 23:39:19,760: ERROR/ForkPoolWorker-8] Task tasks.add[2069eb9f-b57e-48e4-98d8-595efd5f5922] raised unexpected: ValueError('task_id must not be empty. Got None instead.')
Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in on_chord_part_return
    resl = [unpack(tup, decode) for tup in resl]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 533, in <listcomp>
    resl = [unpack(tup, decode) for tup in resl]
            ^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 439, in _unpack_chord_result
    raise ChordError(f'Dependency {tid} raised {retval!r}')
celery.exceptions.ChordError: Dependency f9032a00-4ee6-4430-bf27-eb04f3d66cd7 raised Exception('failc')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/app/trace.py", line 520, in trace_task
    task.backend.mark_as_done(
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 159, in mark_as_done
    self.on_chord_part_return(request, state, result)
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/redis.py", line 554, in on_chord_part_return
    return self.chord_error_from_stack(callback, exc)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 304, in chord_error_from_stack
    return backend.fail_from_current_stack(callback.id, exc=exc)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 311, in fail_from_current_stack
    self.mark_as_failure(task_id, exc, exception_info.traceback)
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 167, in mark_as_failure
    self.store_result(task_id, exc, state,
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 526, in store_result
    self._store_result(task_id, result, state, traceback,
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 975, in _store_result
    current_meta = self._get_task_meta_for(task_id)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 997, in _get_task_meta_for
    meta = self.get(self.get_key_for_task(task_id))
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/diego/Development/my_celery_project/.venv/lib/python3.11/site-packages/celery/backends/base.py", line 871, in get_key_for_task
    raise ValueError(f'task_id must not be empty. Got {task_id} instead.')
ValueError: task_id must not be empty. Got None instead.

Root cause analysis

After debugging with rdb breakpoints, I found that the issue occurs in the chord.run() method in celery/canvas.py. When a chord body is frozen, it's currently using task_id instead of group_id:

# Line ~2261 in celery/canvas.py
bodyres = body.freeze(task_id, root_id=root_id)

The problem is:

  1. task_id can be None or an external chord task ID
  2. When error propagation occurs, it looks for callback.id to handle the error
  3. Since the body was frozen with None or wrong ID, callback.id is None in redis backend file inside on_chord_part_returnmethod
  4. This causes the "task_id must not be empty" error when trying to store the failure

The fix should be to use group_id instead:

bodyres = body.freeze(group_id, root_id=root_id)

This creates the proper semantic relationship between the group and its callback, allowing error handling to work correctly.

I have a working fix and tests ready in the linked pull request.

Activity

  1. added 2 commits that reference this issue on Jun 19, 2025
  2. added 3 commits that reference this issue on Jun 22, 2025
  3. added a commit that references this issue on Jun 24, 2025
  4. added this to the 5.5.4 milestone on Jun 24, 2025
  5. modified the milestones: 5.5.4, 5.6.0 on Jul 13, 2025
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions