Skip to content

Fix chord_unlock redelivery dispatching the chord body twice - #11135

Merged
auvipy merged 9 commits into
celery:mainfrom
tony1233200:fix/11037-chord-unlock-redelivery
Nov 25, 2026
Merged

auvipy merged 9 commits into
celery:mainfrom
tony1233200:fix/11037-chord-unlock-redelivery

Conversation

@tony1233200

Copy link
Copy Markdown
Contributor

Fixes #11037

Summary

On result backends that finish chords with the fallback chord_unlock
polling task (database, MongoDB, Cassandra, filesystem, …), a lost worker
could make the chord body run two or more times. unlock_chord recorded
nothing about having dispatched the body, so with task_acks_late=True a
worker lost after dispatching the body (or its retry) but before acking
caused the broker to redeliver chord_unlock, and the copy dispatched the
body again — or started a second polling chain that dispatched it later.
The issue reports 31 and 21 of 60 chords duplicated on PostgreSQL, while
the Redis backend is unaffected because its dispatch is claimed atomically
in on_chord_part_return (#10919/#10998).

This change claims the terminal step of chord_unlock in the result
backend, before the body is dispatched or the chord is failed, using only
storage primitives every result backend already has.

How it works

New generic API on celery.backends.base.Backend (no per-backend code,
no schema changes):

  • The claim is an ordinary result stored under a synthetic id,
    chord-unlock-claim-<group_id>, so it works on any backend that can
    store a result and expires like any other result (result_expires /
    backend cleanup) — mirroring the expiring done marker of the Redis
    backend instead of leaking a permanent key per chord.
  • try_claim_chord_unlock(group_id) returns (status, token):
    • claimed — the caller owns the claim. The claim is first stored as a
      lease: state STARTED, a unique token and the claim time.
    • dispatched — a previous run already finished this chord; the
      caller must neither dispatch the body nor fail the chord again.
    • in_progress — another live worker holds a fresh lease;
      chord_unlock retries itself with its normal polling interval and
      re-checks, instead of dispatching concurrently.
  • After dispatching the body (or failing the chord via
    chord_error_from_stack), the owner calls
    mark_chord_unlock_dispatched(), which replaces the lease with a
    SUCCESS marker. The key/value, database, MongoDB and Cassandra
    backends already refuse to overwrite a SUCCESS result with a later
    one, which is what makes the marker stick.
  • The claim is taken after the header has been joined, never while
    polling: the not-ready retry chain is unchanged, and no claim is taken
    on the deps.ready()/retry-exhaustion paths.
  • fallback_chord_unlock() calls reset_chord_unlock_claim() when a
    new chord run is launched, so reapplying a frozen chord under the same
    group id (a new run) still dispatches its body; only copies of the
    same run's chord_unlock are deduplicated.
  • Everything fails open: a backend that cannot store or read the claim
    at all (e.g. the disabled backend), a failed marker write, or a
    backend without the claim API leaves the previous at-least-once
    behaviour in place rather than losing the body.
  • The Redis backend and the key/value on_chord_part_return counter
    path are untouched: Redis keeps its atomic Lua claim, and
    apply_chord implementations that don't go through
    fallback_chord_unlock never see the new claim.

Crash recovery: if a worker is lost after taking the lease but before
storing the SUCCESS marker, its lease (60 s,
Backend.chord_unlock_claim_lease) is treated as abandoned once stale.
A redelivered copy first polls while the lease is fresh, then takes it
over and finishes the chord, so the body is delayed, not lost.

Boundaries / remaining races (honest assessment)

  • The claim is a check-and-set built from separate reads and writes,
    because the generic backend interface has no atomic
    create-if-absent operation that works across SQL, MongoDB, Cassandra
    and key/value stores. It fully closes the reported sequential
    redelivery case: a copy that starts after the first run stored its
    lease/marker always sees it.
  • Two copies running at exactly the same moment can still both
    claim if their lease writes interleave before either re-reads (the
    token re-read after writing the lease narrows, but does not
    eliminate, this window). Closing it completely would need
    per-backend atomic primitives (a unique-row insert in SQL,
    insert_one in MongoDB, SET NX in key/value stores) and is left
    as follow-up work.
  • Lease staleness is judged with the wall clock stored in the claim,
    so workers with badly skewed clocks can take over a lease early or
    late; the lease only covers the publish/fail step, which follows the
    join immediately.
  • If publishing the body takes longer than the lease (very long broker
    publish-retry budgets), a polling copy may take over while the owner
    is still publishing and dispatch a second time. This is the same
    trade-off the Redis claim documents for unbounded joins.
  • The retry-exhaustion path in chord_unlock (where the retry itself
    cannot be scheduled) still fails the chord without claiming, as
    before; it never dispatches the body.

Reproduction

Unit-level reproduction (cache+memory backend, ready header, the same
chord_unlock arguments executed twice to simulate broker redelivery
after a lost worker):

Before this change:

after first chord_unlock:  body dispatched 1x
after redelivered chord_unlock: body dispatched 2x total
BUG REPRODUCED: body dispatched more than once

After this change:

after first chord_unlock:  body dispatched 1x
after redelivered chord_unlock: body dispatched 1x total
OK: body dispatched exactly once

The claim cycle was also exercised directly against the real database
backend (SQLite, same DatabaseBackend code path as PostgreSQL):
first claim claimed, second claim while the lease is fresh
in_progress, after marking dispatched dispatched, after reset
claimed again, and a stale lease is taken over.

Tests

New tests:

  • t/unit/tasks/test_chord.py (test_unlock_chord_task):
    • redelivery after dispatch does not dispatch the body again;
    • redelivery after a join failure does not fail the chord again;
    • polling while not ready does not claim, and the same chain still
      dispatches once the header is ready;
    • a copy that finds another worker's fresh claim retries instead of
      dispatching;
    • a copy that finds an abandoned (stale) claim takes over and
      dispatches.
  • t/unit/backends/test_base.py (test_chord_unlock_claim):
    first claim wins, fresh lease blocks, dispatched marker blocks,
    stale lease takeover, reset, fallback_chord_unlock resetting the
    claim for a new run, and fail-open behaviour on a backend without
    result storage.
  • test_unlock_chord_task._chord_context now uses a fresh group id per
    invocation: real chord runs always get a fresh group id, and with
    dispatch recorded against it, reusing one id across tests would look
    like a redelivery of an already finished chord.

Results (Python 3.12, kombu 5.7, pytest 9):

  • t/unit/tasks/test_chord.py, t/unit/app/test_builtins.py,
    t/unit/backends/test_base.py, t/unit/tasks/test_result.py:
    386 passed, 1 skipped.
  • t/unit/tasks/ + t/unit/app/test_builtins.py:
    1317 passed, 1 skipped, 1 xfailed.
  • t/unit/backends/ + t/unit/tasks/test_result.py:
    982 passed, 65 skipped, 1 failed —
    test_mongodb.py::test_MongoBackend::test_regression_worker_startup_info
    fails only because the test environment runs as root with pickle
    accepted (SecurityError from celery/platforms.py); it passes with
    C_FORCE_ROOT=1 and is unrelated to this change.
  • t/unit/backends/test_database.py (with SQLAlchemy installed):
    116 passed.
  • flake8 (repo setup.cfg config) on all changed files: clean.

…11037)

unlock_chord recorded nothing about having finished a chord, so
with task_acks_late a worker lost after dispatching the body but
before acking made the broker redeliver chord_unlock, and the copy
dispatched the body again on backends using the fallback polling
path (database, MongoDB, Cassandra, ...).

Claim the terminal step of chord_unlock in the result backend
before dispatching the body or failing the chord. The claim is a
plain result stored under a synthetic id: a STARTED lease with a
token and timestamp, replaced by a SUCCESS marker once the chord
is finished, which the existing backends refuse to overwrite. A
redelivered copy that finds the marker skips, a copy that finds a
fresh lease polls again, and a copy that finds an abandoned lease
takes over so the body is not lost with the lost worker.
@auvipy
auvipy self-requested a review November 22, 2026 13:46
@auvipy

auvipy commented Nov 22, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy can you check

@auvipy auvipy added this to the 5.7.x milestone Nov 22, 2026

@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 two changes before merge. I ran it at 521dc45f0 against main (ebf4be58d) on RabbitMQ 4.0 with a PostgreSQL 16 result backend.

It does stop the duplicates I reported in #11037. The script from the issue, with two workers killed in turn every 4 s and task_acks_late on:

main This PR
PostgreSQL: chords whose body was sent twice or more 29 of 180 0 of 280
Filesystem backend: the same 7 of 40 0 of 40
Chords whose body never ran, in the runs where I tracked it 0 of 80 0 of 80
No kills, 30 chords: each body sent once yes, 40 s yes, 36 s

1. A chord with a failed header task now leaves the body PENDING and it never changes. No worker loss is needed. Ten chords with one header task that raises, one worker, no kills:

main This PR
Body state FAILURE (ChordError), 10 of 10 PENDING, 10 of 10
celery.chord_unlock succeeds fails with AttributeError: 'NoneType' object has no attribute 'tb_frame', 10 of 10
link_error on the body runs once runs once

chord_error_from_stack() ends in fail_from_current_stack(), which reads sys.exc_info(). On main it is called inside the except block of the join. Here the call moved below the claim, where no exception is being handled, so the traceback is None and it crashes before mark_as_failure() stores the body's result. The unit tests miss it because _chord_context replaces fail_from_current_stack with a mock. A test that runs the real method and a four-line fix are below. With the fix the body is FAILURE (ChordError) 10 of 10 again.

2. The claim is not atomic, and it can be. The description says two copies at the same moment can both claim. I measured how often: two processes calling try_claim_chord_unlock() for one group at the same moment both got claimed in 119 of 300 tries on PostgreSQL, 278 of 300 on SQLite, 96 of 300 on the filesystem backend and 105 of 300 on Redis. Through a worker, with two copies of chord_unlock placed together, the body ran twice for 1 of 30 chords (30 of 30 on main). The kill loop above did not hit it, so it is rare in that script, but a backend that answers "who claimed" with a read after a write will give two winners under load. Each backend has a primitive that decides it in one step: task_id is unique in the database backend's table, so an insert can only succeed once; the filesystem can create the file exclusively; Redis has SET NX; MongoDB has a unique _id. Taking over a stale lease needs the same care, as a compare-and-set on the token. I'd like the database backend done here, since it is the one in the issue, with the generic read-then-write kept as the fallback for the others.

Smaller things:

  • A worker killed while it holds the claim delays the body by the lease. With a worker killed between the claim and the dispatch, the body ran 61.5 s later, against 1.3 s on main. I think that trade is right, and it should be in the docs next to chord_unlock_claim_lease, which today can only be changed by subclassing the backend.
  • Each chord leaves one more result, chord-unlock-claim-<group_id>, until results expire: one extra row per chord in celery_taskmeta, or one extra file. The docs could say so, for anyone who counts or cleans that table.
  • The claim adds backend calls per chord: 47 ms on PostgreSQL, 16 ms on SQLite, 1.2 ms on Redis, 0.3 ms on the filesystem. The 30-chord run without kills took the same time on both.
  • The token re-read and the fail-open around the claim in unlock_chord have no test: with either removed, all tests pass. Tests for both are below.
Fix and test for point 1
         try:
             if join_error is not None:
-                app.backend.chord_error_from_stack(callback=callback, exc=join_error)
+                try:
+                    raise join_error
+                except Exception:  # pylint: disable=broad-except
+                    app.backend.chord_error_from_stack(callback=callback, exc=join_error)
             else:

In test_unlock_chord_task (t/unit/tasks/test_chord.py). It fails on this PR and passes on main and with the fix:

    def test_unlock_ready_failed_stores_the_failure_on_the_body(self):
        # The other tests replace fail_from_current_stack with a mock.  This
        # one runs the real method, which needs an exception being handled.
        class Failed(TSR):
            is_ready = True
            value = [2, KeyError('foo'), 8, 6]

        def setup(callback):
            del self.app.backend.fail_from_current_stack

        with self._chord_context(Failed, setup) as (cb, retry, _):
            cb.type.apply_async.assert_not_called()
            meta = self.app.backend.get_task_meta(cb.id)
            assert meta['status'] == 'FAILURE'
            assert isinstance(meta['result'], ChordError)

An integration test on a backend that uses chord_unlock would catch it as well: a chord with a failing header task, asserting the body ends in FAILURE.

Two more unit tests

Both pass on this PR. Each fails when the code it covers is removed.

Next to the other claim tests in t/unit/backends/test_base.py:

    def test_claim_lost_to_a_copy_that_wrote_after_ours(self):
        # Another copy stores its claim between our write and our
        # re-read: we must not finish the chord as well.
        gid = uuid()
        store_result = self.b.store_result

        def store_then_be_overwritten(task_id, result, state, **kwargs):
            store_result(task_id, result, state, **kwargs)
            store_result(task_id, dict(result, token='other-copy'), state)

        with patch.object(self.b, 'store_result', store_then_be_overwritten):
            status, token = self.b.try_claim_chord_unlock(gid)
        assert status == 'in_progress'
        assert token is None

In test_unlock_chord_task:

    def test_unlock_dispatches_body_when_the_claim_raises(self):
        # A backend that cannot answer the claim must not lose the body.
        class AlwaysReady(TSR):
            is_ready = True
            value = [2, 4, 8, 6]

        with patch.object(self.app.backend, 'try_claim_chord_unlock',
                          side_effect=RuntimeError('backend down')):
            with self._chord_context(AlwaysReady) as (cb, retry, _):
                cb.type.apply_async.assert_called_once()
                assert not retry.call_count
Other runs
  • A redelivered copy that starts after the dispatch: the body ran 2 to 4 times on main, once here.
  • A chord with a failing header task under the kill loop: link_error ran twice or more for 11 of 60 chords on main, 0 of 60 here.
  • The new unit tests: 10 fail with the change reverted, and 5 of 7 bugs I planted are caught. The other two are the untested paths above.
  • t/unit/tasks, t/unit/backends and t/unit/app/test_builtins.py: the same 4 failures on main and here, none in code this PR touches.
  • A signature that is frozen and applied twice still runs its body twice, on main and here. That is outside this PR.
What I did not run
  • MongoDB, Cassandra, or any backend other than PostgreSQL, SQLite, the filesystem and Redis.
  • The prefork pool under the kill loop long enough to say anything: my run there finished in 30 s with 8 kills and no duplicate on either side.
  • Python versions other than 3.13.

- Re-raise the join error inside an except block before calling
  chord_error_from_stack(), so fail_from_current_stack() sees a real
  traceback instead of crashing on None and leaving the body PENDING.
- DatabaseBackend.try_claim_chord_unlock(): insert the claim row
  against the unique task_id, so exactly one copy wins; a stale-lease
  takeover is decided under a row lock (compare-and-set on the token).
  The generic read-then-write stays the fallback for other backends.
- Document the lease-delay trade-off and the extra stored result next
  to chord_unlock_claim_lease.
- Tests: failing-header failure is stored on the body; dispatching
  continues when the claim raises; a copy that wrote after ours loses;
  database claim lifecycle, lost-insert race and stale takeover.
@tony1233200

This comment was marked as abuse.

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.42520% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.39%. Comparing base (992e9b5) to head (b3fbc27).
⚠️ Report is 12 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
celery/backends/database/__init__.py 96.15% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11135      +/-   ##
==========================================
+ Coverage   91.33%   91.39%   +0.06%     
==========================================
  Files         153      153              
  Lines       21841    22020     +179     
  Branches     2712     2738      +26     
==========================================
+ Hits        19948    20126     +178     
+ Misses       1593     1591       -2     
- Partials      300      303       +3     
Flag Coverage Δ
unittests 91.38% <98.42%> (+0.06%) ⬆️

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.

@tony1233200 tony1233200 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough review and the reproduction numbers — all addressed in the latest push (head 06b8f02, which also merges main and picks up the pre-commit fixes):

1. Failed header task leaving the body PENDING — fixed. unlock_chord now re-raises join_error inside the except block before calling chord_error_from_stack(), so fail_from_current_stack() sees a real traceback. Your test test_unlock_ready_failed_stores_the_failure_on_the_body is added verbatim in t/unit/tasks/test_chord.py (it runs the real method, not the mock).

2. Atomic claim — DatabaseBackend.try_claim_chord_unlock() now inserts the claim row against the unique task_id, so exactly one copy wins; a stale-lease takeover is decided under a row lock as a compare-and-set on the token. The generic read-then-write stays as the fallback for the other backends. Both of your tests are added: test_claim_lost_to_a_copy_that_wrote_after_ours in t/unit/backends/test_base.py and test_unlock_dispatches_body_when_the_claim_raises in t/unit/tasks/test_chord.py.

Smaller things — the lease-delay trade-off (a worker killed while holding the claim delays the body by the lease) and the extra chord-unlock-claim-<group_id> result are both documented next to chord_unlock_claim_lease in celery/backends/base.py.

Tests: t/unit/tasks/test_chord.py, t/unit/backends/test_base.py and t/unit/backends/test_database.py — 366 passed on the pushed head.

@auvipy auvipy left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also improve the patch test coverage, specially unit test to 100% @tony1233200

Cover the fail-open and malformed-lease paths in the generic and
database claim implementations, and the retry-scheduling failure
path in chord_unlock.

Also fix try_claim_chord_unlock checking 'task is None':
_query_task returns [] for a missing row, so the vanished-row
re-insert was unreachable; check truthiness instead, like
_store_result does.

@tony1233200 tony1233200 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Patch test coverage is now 100% (was 78.4% per codecov, 27 lines missing), head 5a413c5:

  • celery/backends/base.py: malformed claimed_at treated as abandoned, non-dict lease payload treated as abandoned, store failure fails open, second read seeing dispatched, silent marker-write failure.
  • celery/backends/database/__init__.py: vanished-row re-insert (both winning and losing again), unexpected storage error fails open, malformed claimed_at / non-dict payload in the locked decision.
  • celery/app/builtins.py: chord_unlock retry that cannot be scheduled leaves the chord to the worker holding the claim.

Covering the database paths also exposed a real bug: try_claim_chord_unlock checked task is None after _query_task, but that method returns [] for a missing row, so the vanished-row re-insert was unreachable (it fell through to the fail-open handler with a spurious warning). Fixed to a truthiness check, as _store_result does, and the new tests cover the path for real.

Tests: t/unit/tasks/test_chord.py, t/unit/backends/test_base.py, t/unit/backends/test_database.py, t/unit/app/test_builtins.py — 392 passed; flake8 clean on the touched files.

@tony1233200

This comment was marked as abuse.

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Looks good, with two small changes. I ran 5a413c59a against main (29b14de6d) on RabbitMQ 4.0 and PostgreSQL 16, including the kill loop you asked about.

Both points from my last review are fixed:

Last head (521dc45f0) Now
Chord with a failing header task: body state PENDING, 10 of 10 FAILURE (ChordError), 10 of 10
Two claims at the same moment, both win: PostgreSQL 119 of 300 0 of 300
The same on SQLite 278 of 300 0 of 300
Two copies of chord_unlock placed together: body ran twice 1 of 30 chords 0 of 30
Two copies taking over one abandoned lease, both win: PostgreSQL 4 of 200 0 of 200

The kill loop from #11037 on PostgreSQL, two workers killed in turn every 4 s:

main This PR
Chords whose body was sent twice or more 9 of 40 0 of 120
Chords whose body never ran 0 0

With a failing header task under the same kill loop, link_error ran once for each of 30 chords. The worker logs of the last run have no "finishing the chord without a claim" warning, so the claim did not fall back there.

Two things I'd like before merge:

1. The takeover is not atomic on SQLite. Two copies taking over the same abandoned lease both got claimed in 133 of 200 tries on SQLite, against 0 of 200 on PostgreSQL. SELECT ... FOR UPDATE is what makes the lease check and the write one step, and SQLite ignores it. It takes a killed worker and two copies at the same moment, so it is rare, but a conditional UPDATE on the stored lease closes it on every database and no longer depends on the lock. With the change below I get 0 of 200 on SQLite and on PostgreSQL, and the unit tests pass.

2. No test checks that a takeover stores the new token. If the takeover returns claimed without writing the row, all 392 tests pass, and the next copy takes the lease as well. The test below fails with that bug and passes here.

Smaller things that can wait for a follow-up:

  • chord_unlock_claim_lease is documented in a code comment only. A setting, or a line in the chord docs, would let people find the 60 s delay without reading base.py.
  • The other backends that use chord_unlock still claim with a read after a write. On the filesystem backend two claims at the same moment both won in 94 of 300 tries. An exclusive file create would settle it there.
  • The row-lock path has no test that could fail, since the unit tests run on SQLite. With the conditional UPDATE that stops mattering.
Change for point 1

In _decide_chord_unlock_claim() in celery/backends/database/__init__.py:

-        self._update_result(
-            task,
-            {'token': token, 'claimed_at': time.time()},
-            states.STARTED,
-        )
-        flag_modified(task, 'status')
+        # A conditional UPDATE on the stored lease: only one copy can
+        # replace it, also on databases without row locks (SQLite).
+        taken = session.query(self.task_cls).filter(
+            self.task_cls.id == task.id,
+            self.task_cls.status == states.STARTED,
+            self.task_cls.result == task.result,
+        ).update({
+            'result': ensure_bytes(self.encode(
+                {'token': token, 'claimed_at': time.time()})),
+            'date_done': datetime.now(timezone.utc),
+        }, synchronize_session=False)
         session.commit()
-        return 'claimed', token
+        if taken == 1:
+            return 'claimed', token
+        return 'in_progress', None
Test for point 2

In test_DatabaseBackend_chord_unlock_claim (t/unit/backends/test_database.py):

    def test_takeover_stores_the_new_claim(self):
        # After a takeover the claim row must hold the new token and a
        # fresh lease, so the next copy waits instead of taking it too.
        import time

        gid = uuid()
        claim_id = self.b._chord_unlock_claim_id(gid)
        self.b.store_result(
            claim_id,
            {'token': 'lost-worker', 'claimed_at': time.time() - 3600},
            states.STARTED,
        )
        status, token = self.b.try_claim_chord_unlock(gid)
        assert status == 'claimed'
        assert self.b.get_task_meta(claim_id, cache=False)['result']['token'] == token
        assert self.b.try_claim_chord_unlock(gid) == ('in_progress', None)
Other checks
  • t/unit/tasks/test_chord.py, t/unit/backends/test_base.py, t/unit/backends/test_database.py and t/unit/app/test_builtins.py as tox runs them (python -bb): 392 passed. flake8 is clean on the touched files.
  • Of six bugs I planted in the new code, the tests catch four. The two they miss are the ones above: the takeover that does not store its token, and the row lock removed.
  • A worker killed between the claim and the dispatch: the body still runs once, after the lease.
  • The claim adds about 22 ms of backend calls per chord on PostgreSQL and 8 ms on SQLite.
What I did not run
  • MySQL, or any database other than PostgreSQL 16 and SQLite.
  • MongoDB and Cassandra.
  • Python versions other than 3.13.

Take over an abandoned chord_unlock lease with a conditional UPDATE
on the stored lease instead of a row-locked read-then-write: SQLite
ignores SELECT ... FOR UPDATE, so two copies taking over the same
abandoned lease could both win (133 of 200 in review testing). The
conditional UPDATE closes it on every database, and the new
test_takeover_stores_the_new_claim pins that the takeover actually
stores the new token (it fails if the takeover returns 'claimed'
without writing the row).
@tony1233200

This comment was marked as abuse.

@auvipy

auvipy commented Nov 23, 2026

Copy link
Copy Markdown
Member

The follow-ups (documenting chord_unlock_claim_lease, the filesystem backend's read-after-write claim) are left for a separate PR, as you suggested.

documentation should be included 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.

Thanks, both changes check out at b0793b4ce: two copies taking over one abandoned lease on SQLite both claimed in 0 of 200 tries (133 before), and the four unit test files pass (393).

One thing for the docs @auvipy asked to have here. The claim makes a second dispatch rare and late, but one window stays open on every backend: a worker killed after it sends the body and before it stores the marker. The lease it leaves expires, and a redelivered chord_unlock then sends the body again. I placed that case on PostgreSQL with the lease shortened to 4 s, and the body ran a second time 4.5 s after the first. With the default lease that is about 60 s later.

No claim can close it, since the send and the marker are two steps, and storing the marker first would lose the body instead. So I think the behaviour is right as it is. The docs could say it in one line next to chord_unlock_claim_lease: the body is sent at least once, and a worker lost between the send and the marker can send it a second time after the lease, so chord bodies should still be idempotent under task_acks_late.

@tony1233200

This comment was marked as abuse.

@auvipy
auvipy merged commit 9cb646b into celery:main Nov 25, 2026
531 checks passed
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.

chord_unlock sends the chord body again after a lost worker

3 participants