Skip to content

Redis backend: chord body can be dispatched twice when a duplicate header task finishes during callback dispatch #10997

Closed

Description

@Namraa310806

Checklist

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 the versions of the external dependencies required to reproduce this bug.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None identified yet.

Environment & Settings

Celery version: 5.7.0rc1 (development version from Git)

Kombu version: 5.7.0b1

Python version: 3.13.15

Billiard version: 4.3.1

Redis Python client: 6.4.0

Operating System: Windows 11 (64-bit)

Python implementation: CPython

Broker used in reproduction: memory://

Result backend used in reproduction: redis://localhost:6390/0

Redis server: Local Redis instance listening on port 6390.

celery report Output:

software -> celery:5.7.0rc1 (collider) kombu:5.7.0b1 py:3.13.15
            billiard:4.3.1 memory:N/A
platform -> system:Windows arch:64bit, WindowsPE
            kernel version:11 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: Not yet determined.
  • Minimal Celery Version: Affected implementation after Count each chord header task only once in the Redis backend #10919; reproduced on 5.7.0rc1 and main.
  • Minimal Kombu Version: 5.7.0b1 (tested environment).
  • Minimal Broker Version: Not applicable to the standalone reproduction (memory:// broker).
  • Minimal Result Backend Version: Redis (exact minimum version not yet determined).
  • Minimal OS and/or Kernel Version: Windows 11 (tested environment).
  • Minimal Broker Client Version: Not applicable to the memory:// broker.
  • Minimal Result Backend Client Version: redis-py 6.4.0.

Python Packages

pip freeze Output:

-e git+https://github.com/Namraa310806/agent-framework.git@beb7d2916d36ab4efc0387936fccaecded88003e#egg=agent_framework_core&subdirectory=python\packages\core
aiohappyeyeballs==2.7.1
aiohttp==3.14.3
aiohttp-retry==2.9.1
aiosignal==1.4.0
amqp==5.4.1
annotated-types==0.8.0
anyio==4.15.1
asgiref==3.12.1
ast_serialize==0.12.1
attrs==26.1.0
azure-core==1.41.0
azure-identity==1.25.3
azure-storage-blob==12.31.0
beautifulsoup4==4.12.2
billiard==4.3.1
black==26.10.1
boto3==1.43.111
botocore==1.43.111
cachetools==7.1.7
catboost==1.2.10
-e git+https://github.com/Namraa310806/celery.git@57cb15ff99ab47a6e72d5a70c5522b8fabb59a57#egg=celery
certifi==2026.7.22
cffi==2.1.1
cfgv==3.5.0
charset-normalizer==3.5.1
click==8.4.2
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
cloudpickle==3.1.2
colorama==0.4.6
contourpy==1.4.0
coverage==7.15.4
cron_descriptor==2.1.0
cryptography==50.0.0
cycler==0.12.1
DateTime==6.0
debugpy==1.8.22
deprecation==2.1.0
distlib==0.4.3
distro==1.9.0
-e git+https://github.com/Namraa310806/django.git@ed52a1f6c1527bce131424e3b8bee57dddad6c57#egg=Django
django-celery-beat==2.5.0
django-cors-headers==4.3.1
django-timezone-field==7.2.2
djangorestframework==3.14.0
djangorestframework-simplejwt==5.3.0
dnspython==2.9.0
docker==7.2.0
easyocr==1.7.2
fastapi==0.115.6
filelock==3.32.3
flake8==7.3.0
fonttools==4.66.0
freezegun==1.5.5
frozenlist==1.8.0
fsspec==2026.7.0
future==1.0.0
gevent==26.9.0
google-api-core==2.42.0
google-auth==2.61.0
google-cloud-core==2.8.0
google-cloud-firestore==2.32.0
google-cloud-storage==3.15.0
google-crc32c==1.9.0
google-resumable-media==2.11.0
googleapis-common-protos==1.75.5
gotrue==2.12.4
graphviz==0.21
greenlet==3.5.6
groq==0.28.0
grpcio==1.84.0
grpcio-status==1.84.0
h11==0.16.0
h2==4.4.1
hpack==4.2.1
httpcore==1.0.9
httptools==0.8.0
httpx==0.27.2
hyperframe==6.1.0
identify==2.6.19
idna==3.19
ImageIO==2.37.4
iniconfig==2.3.0
isodate==0.7.2
isort==9.0.2
Jinja2==3.1.6
jmespath==1.1.0
joblib==1.6.0
kiwisolver==1.5.1
kombu==5.7.0b1
lazy-loader==0.5
librt==0.16.0
lightgbm==4.7.0
MarkupSafe==3.0.3
matplotlib==3.11.2
mccabe==0.7.0
moto==5.2.3
mpmath==1.3.0
msal==1.39.0
msal-extensions==1.3.1
msgpack==1.1.2
msgspec==0.21.1
multidict==6.7.1
mypy==2.3.1
mypy_extensions==1.1.0
narwhals==2.26.0
networkx==3.6.1
ninja==1.13.0
nodeenv==1.10.0
numpy==2.2.2
opencv-python==4.10.0.84
opencv-python-headless==5.0.0.93
opentelemetry-api==1.44.0
opentelemetry-sdk==1.44.0
opentelemetry-semantic-conventions==0.65b0
packaging==26.3
pandas==3.0.6
pathspec==1.1.1
pdf2image==1.17.0
pdfminer.six==20231228
pdfplumber==0.11.4
pillow==11.1.0
platformdirs==4.11.3
plotly==7.1.0
pluggy==1.6.0
postgrest==2.31.0
pre_commit==4.6.2
prompt_toolkit==3.0.53
propcache==0.5.2
proto-plus==1.29.0
protobuf==7.36.2
psutil==7.2.2
psycopg2-binary==2.9.12
pyArango==2.1.1
pyarrow==25.0.1
pyasn1==0.6.4
pyasn1_modules==0.4.2
pyclipper==1.4.0
pycodestyle==2.14.0
pycparser==3.0
pydantic==2.13.5
pydantic-settings==2.7.1
pydantic_core==2.46.5
pyflakes==3.4.0
Pygments==2.20.0
PyJWT==2.13.0
pymongo==4.15.3
pymupdf==1.28.2
pyparsing==3.3.3
pypdfium2==5.13.0
pyproject-api==1.11.0
pyright==1.1.414
pytesseract==0.3.13
pytest==9.1.1
pytest-asyncio==1.4.0
pytest-celery==1.3.0
pytest-click==1.1.0
pytest-cov==7.1.0
pytest-order==1.5.0
pytest-rerunfailures==16.7
pytest-subtests==0.15.0
pytest-timeout==2.4.0
pytest_docker_tools==3.1.10
python-bidi==0.6.11
python-crontab==3.4.0
python-dateutil==2.9.0.post0
python-decouple==3.8
python-discovery==1.5.2
python-dotenv==1.0.1
python-memcached==1.62
python-multipart==0.0.20
pytokens==0.4.1
pytz==2026.3.post1
pywin32==312
PyYAML==6.0.3
RapidFuzz==3.14.6
realtime==2.31.0
redis==6.4.0
regex==2026.9.29
requests==2.34.2
responses==0.26.3
s3transfer==0.19.0
scikit-image==0.26.0
scikit-learn==1.9.1
scipy==1.18.1
setuptools==84.0.0
shapely==2.1.2
six==1.17.0
sniffio==1.3.1
soupsieve==2.9.2
SQLAlchemy==2.1.4
sqlparse==0.6.0
starlette==0.41.3
storage3==2.31.0
StrEnum==0.4.15
supabase==2.31.0
supabase-auth==2.31.0
supabase-functions==2.31.0
supafunc==0.7.0
sympy==1.14.0
tenacity==9.2.1
threadpoolctl==3.7.0
tifffile==2026.8.23
tomli_w==1.2.0
torch==2.14.0
torchvision==0.29.0
tox==4.61.1
tqdm==4.70.1
twilio==9.4.5
typing-inspection==0.4.4
typing_extensions==4.16.0
tzdata==2026.4
tzlocal==5.4.4
urllib3==1.26.20
uv==0.13.5
uvicorn==0.34.0
vine==5.1.0
virtualenv==21.7.4
watchfiles==1.2.0
wcwidth==0.8.2
websockets==15.0.1
Werkzeug==3.1.9
xmltodict==1.0.0
yarl==1.24.5
zope.event==6.2
zope.interface==8.6

Other Dependencies

Details

  • Redis server running locally on port 6390.
  • Redis Python client (redis-py) version 6.4.0.
  • fakeredis[lua] for the unit regression test that executes the actual Lua script.

Minimally Reproducible Test Case

The following standalone reproduction uses a real Redis server and injects a duplicate header completion from inside callback.delay().

This deterministically exercises the window between the original chord completion and chord cleanup.

A Redis server must be running on localhost:6390.

Details

from types import SimpleNamespace as NS
from unittest.mock import patch

from celery import Celery, states
from celery.canvas import signature


app = Celery(
    'x',
    set_as_current=True,
    broker='memory://',
    backend='redis://localhost:6390/0',
)


@app.task(name='body')
def body(r):
    return r


b = app.backend
b.client.flushall()

gid = 'g1'
body_sig = signature('body', app=app)
body_sig.freeze()

n = 3
b.set_chord_size(gid, n)

fired = []


def mk(i):
    return NS(
        id=f't{i}',
        group=gid,
        group_index=i,
        chord=body_sig,
    )


dup_done = [False]


def fake_delay(self, *args, **kwargs):
    fired.append(args)

    if not dup_done[0]:
        dup_done[0] = True

        # Simulate a redelivered copy of header task 0
        # finishing while the chord body is being dispatched.
        b.on_chord_part_return(
            mk(0),
            states.SUCCESS,
            'r0',
        )


with patch.object(type(body_sig), 'delay', fake_delay):
    b.on_chord_part_return(mk(0), states.SUCCESS, 'r0')
    b.on_chord_part_return(mk(1), states.SUCCESS, 'r1')
    b.on_chord_part_return(mk(2), states.SUCCESS, 'r2')


print('callback fired', len(fired), 'times')

Reproduction Results

Actual behavior on unmodified main:

callback fired 2 times

Expected behavior:

callback fired 1 times

The reproduction uses the real Redis result backend and invokes the actual RedisBackend.on_chord_part_return() implementation.

The duplicate completion is injected synchronously while the original callback dispatch is in progress, making the race deterministic without relying on timing or sleeps.

Additional Regression Test

The issue can also be reproduced in the Redis backend unit tests using fakeredis[lua].

The following test exercises the same race through the actual Lua script:

def test_on_chord_part_return__duplicate_part_while_sending_body(self):
    # A copy of a header task, e.g. redelivered after its visibility
    # timeout, can finish while the body of the chord is being sent.
    # It must not send the body a second time.
    with self.chord_context(3) as (tasks, _, callback):
        def finish_copy(*args, **kwargs):
            if callback.delay.call_count == 1:
                self.b.on_chord_part_return(
                    tasks[0].request, states.SUCCESS, 10)

        callback.delay.side_effect = finish_copy
        self.b.on_chord_part_return(tasks[0].request, states.SUCCESS, 10)
        self.b.on_chord_part_return(tasks[1].request, states.SUCCESS, 20)
        self.b.on_chord_part_return(tasks[2].request, states.SUCCESS, 30)
        callback.delay.assert_called_once_with([10, 20, 30])

The test fails against the unmodified implementation and passes with the proposed fix.

Expected Behavior

The Redis result backend should dispatch a chord body only once when all header tasks have completed.

If a duplicate completion of an already-recorded header task arrives while the original completion is processing or dispatching the callback, it should not cause another callback dispatch.

The operation that determines that the chord has completed should atomically claim the chord, preventing subsequent duplicate completions from independently triggering the callback.

Actual Behavior

CHORD_PART_RETURN_LUA already prevents duplicate header task results from being inserted into the chord result structure.

It tracks completed task IDs, ensuring that a header task is counted only once, even if it executes multiple times and returns different results.

However, the script does not atomically claim the chord when the final header task completes.

In RedisBackend.on_chord_part_return(), the chord keys (.j, .t, .s, .d) are deleted in the finally block, after callback dispatch.

For complex headers, this cleanup also occurs after GroupResult.restore() and join_native().

This creates a window in which another copy of an already-completed header task can invoke on_chord_part_return().

Although the Lua script recognizes the task as a duplicate and does not insert its result again, readycount still equals the expected total and the chord size key .s still exists.

Consequently, the Python-side completion condition succeeds again, and the chord body is dispatched a second time.

This can occur with late-acknowledged task redelivery after worker failure or Redis broker visibility-timeout redelivery, provided the duplicate completion arrives during this window.

Impact

The chord body can execute more than once, potentially causing duplicate side effects, including:

  • Duplicate payments or charges.
  • Duplicate emails or notifications.
  • Duplicate database writes.
  • Repeated external API calls.
  • Other non-idempotent operations performed by chord callbacks.

Root Cause

Duplicate result recording and chord completion claiming are currently separate concerns.

The Lua script atomically prevents a header task from being counted more than once, but it does not atomically ensure that only one invocation can claim the completed chord.

As a result, multiple invocations can observe the same completed state before the Python-side cleanup removes the chord keys.

Suggested Fix

The Lua script could atomically claim successful chord completion by deleting the chord size key (.s) in the same execution that determines that all header tasks have completed.

For example, when:

readycount == tonumber(size) + (tonumber(totaldiff) or 0)

the script could delete .s before returning.

The completing invocation can still return the size value read before deletion, allowing the existing Python-side code to calculate the total as it does currently.

Subsequent duplicate completions would then observe that the chord size no longer exists and would not trigger another callback dispatch.

The existing error-handling path already uses deletion of the chord size to prevent subsequent copies of header tasks from failing the chord again.

Applying equivalent protection to successful completion would prevent this duplicate-dispatch race.

This would provide an at-most-once callback dispatch claim. A separate consideration is recovery if a worker crashes after claiming the chord but before publishing the callback.

Activity

  1. auvipy commented on Nov 1, 2026

    @auvipy
    Member

    @ChristianMurphy can you verify?

  2. ChristianMurphy commented on Nov 1, 2026

    @ChristianMurphy
    Contributor

    Confirmed on main (57cb15f) against Redis 7.0. The body is sent twice when the same header task finishes twice, and the second one finishes while the last header result is still sending the body. Here that window was about 1.5 ms, with Redis on the same machine. A remote Redis makes it longer.

    How likely it is depends on how the second run comes about:

    • A header message delivered twice, with both copies running in parallel: likely. On a prefork worker, the body ran twice in 26 of 30 chords when the last header task was delivered twice.
    • A rerun after a lost worker with acks_late, or after a Redis visibility timeout: unlikely. The rerun ends a whole task run later, so it has to finish inside that 1.5 ms window.

    So it's rare unless two copies of a header message run in parallel. When they do, a body that isn't idempotent is likely to run twice.

    I'll review #10998 on the PR. It closes most of this, but I can still get a second body with it.

    What I ran

    Redis 7.0.15 as broker and result backend, Python 3.13, kombu 5.7.0rc1, redis-py 8.1.0.

    Calling on_chord_part_return() directly against Redis, with header task 0 finishing again from inside callback.delay(): main sent the body twice.

    With a worker (-P prefork -c 4), each chord has two header tasks that sleep 0.2 s. One of them publishes a copy of its own message with the same task id, group, index and chord, which models a message delivered twice:

    @app.task(bind=True)
    def part(self, x, dup, seconds):
        if dup:
            self.apply_async((x, False, seconds), task_id=self.request.id,
                             group_id=self.request.group, group_index=self.request.group_index,
                             chord=self.request.chord)
        time.sleep(seconds)
        return x
    Delivered twice Body ran once Body ran twice
    no task (control) 30 0
    the last header task 4 26
    the first header task 5 25

    Time from the chord's last count to the cleanup of its keys, over 300 chords with a Redis broker on localhost: median 1.53 ms, 90th percentile 1.81 ms, max 16.75 ms.

  3. added this to the 5.7.0 milestone on Nov 2, 2026
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