Skip to content

chord_unlock sends the chord body again after a lost worker #11037

Done

Description

@ChristianMurphy
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.
  • 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 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.7.0 (main at 768e476). Also 5.6.3.

celery report Output:
software -> celery:5.7.0 (collider) kombu:5.7.0 py:3.14.6
            billiard:4.3.2 py-amqp:5.4.2
settings -> transport:amqp results:db+postgresql+psycopg2://postgres:********@localhost/celery

broker_url: 'amqp://guest:********@localhost:5672//'
result_backend: 'db+postgresql+psycopg2://postgres:********@localhost/celery'
task_acks_late: True

Steps to Reproduce

Required Dependencies

Minimal versions
  • Minimal Celery Version: 5.6.3 or older
  • Python, kombu, broker, result backend, OS and their clients: N/A or Unknown

Python Packages

pip freeze Output:
celery @ main (768e476)
kombu==5.7.0
psycopg2==2.9.13
redis==8.1.0
SQLAlchemy==2.1.8

Other Dependencies

Services

RabbitMQ 3.13, PostgreSQL 16, Redis 7.4 (counts body runs).

Minimally Reproducible Test Case

tasks.py, run.py, kill_loop.sh and output
# tasks.py
import random
import time

import redis
from celery import Celery

app = Celery("tasks", broker="amqp://guest:guest@localhost//",
             backend="db+postgresql+psycopg2://postgres:pw@localhost/celery")
app.conf.task_acks_late = True
log = redis.Redis(db=8)


@app.task
def part(i):
    time.sleep(random.uniform(0.05, 1))
    return i


@app.task(bind=True)
def body(self, results):
    if not self.request.delivery_info.get("redelivered"):
        log.rpush(f"body:{self.request.id}", repr(results))
    return results
# run.py
import time
from collections import Counter

from celery import chord

from tasks import body, log, part

results = [chord(part.si(i) for i in range(4))(body.s()) for _ in range(60)]
deadline = time.time() + 400
while time.time() < deadline and not all(log.llen(f"body:{r.id}") for r in results):
    time.sleep(5)
time.sleep(20)
print(Counter(f"body sent {log.llen(f'body:{r.id}')}x" for r in results))
# kill_loop.sh
start() {
    celery -A tasks worker -P solo -n "w$1@%h" -l info >> "worker$1.log" 2>&1 &
    eval "pid$1=$!"
}
start 1; start 2
while true; do
    for n in 1 2; do sleep 4; eval "kill -9 \$pid$n"; start $n; done
done
$ ./kill_loop.sh & python run.py
Counter({'body sent 1x': 25, 'body sent 2x': 17, 'body sent 3x': 10, 'body sent 0x': 4, 'body sent 4x': 2, 'body sent 5x': 2})

Expected Behavior

The chord body is sent once, as it is with the Redis result backend.

Actual Behavior

On result backends that join chords with chord_unlock (database, MongoDB, Cassandra...), a lost worker can make the chord body run twice or more. With task_acks_late=True, the worker can be lost after chord_unlock sent its retry or the body, but before its ack. The broker then delivers chord_unlock again. The copy sends the body itself, or starts a second polling chain that sends it later.

Natural trigger, 60 chords per run Result backend Body sent twice or more
Script above, RabbitMQ PostgreSQL 16 (Redis: 0 of 60) 31 and 21 of 60
Solo workers SIGKILLed every 2 to 5 s, Redis broker PostgreSQL / MongoDB 18 of 180 / 2 of 60
prefork workers SIGKILLed, RabbitMQ Cassandra 1 of 60
RabbitMQ restarted every 8 to 15 s, prefork PostgreSQL 1 of 300

Solo workers show it most often: their ack for a finished task can wait while the next prefetched task runs. With broker restarts and solo workers, 2 of 60 chords also ran both the error callback (a copy failed to publish) and the body.

unlock_chord() in celery/app/builtins.py doesn't record that it sent the body. It could claim the dispatch in the result backend first, with a create if absent write (a unique row in SQL, insert_one in MongoDB), and an expiry like the Redis claim from #10998 so a lost worker doesn't lose the body. If a maintainer confirms the bug and this approach, I can write it up as a PR.

Activity

  1. ChristianMurphy commented on Nov 8, 2026

    @ChristianMurphy
    ContributorAuthor

    The other outcome of the same worker loss: without a requeue, the chord is lost instead, with the body PENDING forever and no errback, when the pool child running chord_unlock dies before it publishes its retry. That is the case the #10959 comment describes ("nothing will poll this chord again", celery/app/builtins.py:91), reached through a lost child instead of a refused publish. chord_unlock has ignore_result=True, so after the WorkerLostError the main process acks the message and doesn't store anything. No part return or errback follows.

    On main (768e476) with the database backend (PostgreSQL 16), a Redis broker and prefork:

    chord_unlock's pool child SIGKILLed while it polls Chords left PENDING
    Default settings (early ack) 10 of 10
    task_acks_late=True 5 of 10 (in the other 5 the retry was already published)
    task_acks_late=True, task_reject_on_worker_lost=True 0 of 10
    A random pool child SIGKILLed about every second, chords of 200 headers, early ack 7 of 40, and 6 of 40 with the script below
    The same with task_acks_late=True 6 of 40
    The same with task_reject_on_worker_lost=True too 0 of 40

    In the random runs the other chords mostly failed visibly, because a killed header stores FAILURE and the next poll reports it; only the chords whose chord_unlock run was killed stayed PENDING, every one of them. Each poll of a 200 header chord takes 54 to 137 ms at the median, since deps.ready() reads each header's state until the first one that isn't ready.

    The docs say a killed task is acked on purpose even with acks_late (docs/userguide/tasks.rst:32), Should chord_unlock follow that rule, when losing it loses the chord without a trace? task_reject_on_worker_lost=True avoids it here, but then a requeued chord_unlock and the retry it had already published both poll: 1 of the 10 targeted chords ran its body twice (0 of 40 in the random run). A narrower change would be to fail the chord when a chord_unlock run is lost, as #10959 does for a refused retry. Once a maintainer picks a direction, I'm happy to write it up as a PR.

    Script and output
    # tasks.py
    import time
    
    from celery import Celery
    
    app = Celery("tasks", broker="redis://localhost:6379/0",
                 backend="db+postgresql://postgres:pw@localhost/celery")
    
    
    @app.task
    def part(i):
        time.sleep(0.05)
        return i
    
    
    @app.task
    def total(results):
        return len(results)
    # run.py
    import time
    from collections import Counter
    
    from celery import chord
    
    from tasks import app, part, total
    
    bodies = []
    for i in range(40):
        bodies.append(chord(part.s(j) for j in range(200))(total.s()))
        if i >= 2:
            try:
                bodies[i - 2].get(timeout=60, propagate=False)
            except Exception:
                pass
    time.sleep(30)
    print(Counter(app.AsyncResult(b.id).state for b in bodies))
    $ celery -A tasks worker -P prefork -c 4 -l info & W=$!
    $ # SIGKILL a random pool child about every second
    $ while kill -0 $W; do sleep $(awk 'BEGIN{srand(); print -log(1-rand())}'); kill -9 $(pgrep -P $W | shuf -n 1); done &
    $ python run.py
    Counter({'FAILURE': 34, 'PENDING': 6})
    How the targeted runs were timed

    The worker ran with -c 2 and -l debug, and each chord had one 6 second header, so the other child ran every chord_unlock poll. When the worker logged TaskPool: Apply for celery.chord_unlock, the other child got SIGKILL 16 to 140 ms later. A lost run shows as a chord_unlock id that was applied and never logged retry: or succeeded; every PENDING chord had one.

  2. added this to the 5.7.x milestone on Nov 22, 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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions