Skip to content

Complete a chord once on the cache, DynamoDB and GCS backends - #11072

Merged
auvipy merged 21 commits into
celery:mainfrom
ChristianMurphy:fix/chord-count-each-header-once
Nov 28, 2026
Merged

auvipy merged 21 commits into
celery:mainfrom
ChristianMurphy:fix/chord-count-each-header-once

Conversation

@ChristianMurphy

@ChristianMurphy ChristianMurphy commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Note: Before submitting this pull request, please review our contributing
guidelines
& Anti AI spamming Guidelines. Before opening an AI based PR make sure you asked
in the discussion forum or in the related open issues first.

Description

Fixes #11036.

On the cache, DynamoDB and GCS result backends, a chord now completes once, after every header task stored its result, even when the broker delivers a header task again. A duplicate header no longer fails the chord with a join timeout, and a copy that returns after the chord completed no longer runs the body's errbacks. The trade-off is one more backend round trip per header part (6 instead of 5), and in exchange a header result that was lost, such as one memcached evicted, fails the chord at once with an error naming it, instead of leaving the chord waiting.

Most of the diff is tests: code +189/−8, tests +579/−1, docs +52. The tests show that:

  • a duplicate header, a copy after completion, a worker killed between a header's result and its count, and two parts completing together still give one body and no errback, on all three backends, also in a seeded random model of 50 to 300 chords per backend;
  • a lost or expired header result, a group that expired (KeyValueStoreBackend: assumes chord's group result exists #1094), and a header task with ignore_result=True each fail the chord visibly, once;
  • a header task that hasn't returned yet keeps the chord waiting, and a part run by a worker without this change still counts;
  • each backend adds a key only when it's missing and sets its expiry, and a write its client sent again still counts as its own.

How it works:

  • Every run of a header task counts, as on main.
  • Once the count is at the chord size, it reads the header results, and if all are there, the one run that adds the chord's done key completes the chord.
  • Each header task also adds a key when it returns, so a missing result whose header returned is known to be lost. The results are read once more before the chord fails, since a header can store its result and its key between the two reads.
  • A header task that ignores its result fails the chord as soon as it returns, since the chord can't complete without it. A failure it stored with store_errors_even_if_ignored is reported as on main.
  • The keys are written with memcached add, a DynamoDB PutItem with attribute_not_exists or Firestore create(), and kept twice as long as the header results, which on DynamoDB and GCS includes their own ttl_seconds and gcs_ttl. Backends without the new _add_chord_key() keep main's behavior.

Risks:

  • The part that completes the chord deletes the header tasks' keys in one batch. The chord's own key lives twice as long as the header results, and with no expiry configured (DynamoDB without ttl_seconds) it is never removed. The keys of a chord that never completes stay until they expire.
  • During a rolling upgrade, a header task run by a worker without this change doesn't write a key, so a lost result of that task keeps the chord waiting. If a duplicate pushes the counter past the size before an old worker completes the chord, a new worker may complete it too, and the body runs twice. If a duplicate runs on a new worker and the last header then returns on an old one, neither completes the chord, and it stays PENDING, where main fails it after the join timeout. None of these can happen once every worker is upgraded, and the docs now say to upgrade a chord's workers together or let running chords finish first.
  • A worker killed between the done key and the body publish loses the body, as on main.

DynamoDB and GCS ran only against moto and in-memory fakes in the unit tests, and the chord integration tests ran against DynamoDB Local, an emulator. CI doesn't run the cache or DynamoDB integration environments, so I ran the chord tests of test_canvas.py there locally: they fail the same way on main and here (9 on memcached, 12 on DynamoDB Local). I didn't run the smoke tests.

#11052 also changes on_chord_part_return(), to skip restoring the group on every part. Both change the same lines, but they combine cleanly: whichever merges second needs a short rebase, which I'm happy to do.

A Hypothesis version of the model test found nothing in 25,000 runs. Want it in place of the seeded one? It would add Hypothesis as a test dependency, so I left it out.

Worker runs on memcached, main against this branch

Redis 7.4 broker, memcached 1.6.45, prefork, task_acks_late=True, worker_prefetch_multiplier=1, visibility_timeout=2, kombu main. A and B are the scripts from #11036: A runs 5 chords of 2 headers that sleep 4 s on the first delivery, B runs 3 chords of a 3 s and a 12 s header. The lost-result run deletes one header result before the last header returns. The kill run SIGKILLs a whole worker right before a header counts, with task_reject_on_worker_lost=True and a second worker that gets the task again.

main (1a48583) this branch
A: errbacks for 10 late copies 10 in each of 3 runs 0 in each of 7 runs
B: chords failed by the join timeout 3 of 3 in each of 3 runs 0 of 3 in each of 7 runs
A lost header result ChordError from the join timeout after 5 s ChordError naming the result after 2 s
A header task with ignore_result=True ChordError from the join timeout after 3.5 s ChordError naming the task at once
Worker killed before the count: chords completed 3 of 3 10 of 10

In B the body ran more than once on this branch. That's the broker delivering the body message itself again while it waited behind the 12 s headers. The chord sent it once: memcached saw one incr per header run and one body publish.

A pool process killed after its header stored SUCCESS leaves the chord PENDING on main and here alike (#11038), and so does a worker killed with early ack, which loses the message.

Cost, main against this branch

memcached on localhost, on_chord_part_return() with the body publish stubbed, round trips counted in the client and bytes from memcached stats, for chords of 4 / 100 / 1,000 headers:

main this branch
a header part 5 round trips 6 round trips, about 140 more bytes sent
the part that completes the chord 9 / 105 / 1,005 round trips 12 / 108 / 1,008, and the header results read a second time (2.4 / 55 / 549 KB instead of 1.4 / 31 / 307 KB)
a duplicate that brings the count to the size early waits result_chord_join_timeout, then fails the chord 6 round trips, reads the header results
a copy after completion 1 round trip, then the errbacks 3 round trips
keys left after the chord, until they expire none one per header task and one per chord

On DynamoDB and GCS, counting the calls the code makes, a header part makes 2 calls on main and 3 here. Completing a chord adds one PutItem or Firestore create() and one read per header result, because the DynamoDB backend reads results one GetItem at a time. Broker traffic is the same: 1,000 lpush for 200 chords of 4 on both.

Time a part return blocks, with Toxiproxy adding latency to each memcached request (p50 of 120 chords of 4), measured before the key for each header task, which adds one round trip to each part:

Added latency 0 ms 1 ms 5 ms
a header part, main 0.6 ms 8.2 ms 30.0 ms
a header part, this branch 0.5 ms 8.3 ms 29.9 ms
the completing part, main 1.1 ms 15.2 ms 54.5 ms
the completing part, this branch 1.3 ms 18.4 ms 66.2 ms
mark_as_failure() in the worker's main process, completing part, main 1.5 ms 18.7 ms 66.5 ms
same, this branch 1.8 ms 22.1 ms 78.5 ms

The failure paths (WorkerLostError, time limits, revokes) run mark_as_failure() in the worker's main process. These calls block the event loop there, on main too. The solo pool runs every part return in the main process, and gevent and eventlet yield on the socket I/O. Result backends are synchronous, so I don't see a way to block less without an async client.

Other designs I compared

I built the first five on memcached and ran each through the worker runs, the kill run and the cost measurement.

  • Skipping a header task's later runs with a per-part add before the count. It fixed both bugs, but a worker killed between the add and the count left the part recorded and uncounted, and the copy the broker delivered again skipped it: the chord stayed PENDING in 3 of 3 kill runs, which main completes.
  • Marking that record "pending" until the run counted, so a copy that finds another run's pending record counts anyway. It completed the kill runs, but costs two more writes per part, and a copy inside the other run's sub-millisecond gap counts twice.
  • Per-part records as the source of truth, with the same done key. It completed the kill runs too, but during a rolling upgrade a part counted by an old worker has no record, so it needs the results as a fallback anyway. This PR reads the results first.
  • Keeping the group result and counter until they expire. Late copies only log Chord counter incremented too many times, but it doesn't fix the duplicate before completion (B failed 3 of 3).
  • Checking whether the body already stored a state before failing the chord. The errbacks still ran 5, 7 and 5 times out of 10, because the body is often still queued when a late copy returns.
  • Skipping the group restore on each part. Clients haven't sent chord_size since 5.1 (start chord header tasks as soon as possible #6576), so this needs the size stored at apply time, which is what Fix KV backends restoring the whole group on every chord part return #11052 does.
  • Sending add and incr in one round trip. pymemcache can't pipeline different commands, and the meta protocol isn't in its public API.
  • One atomic structure per backend, such as a DynamoDB string set updated with a condition or a memcached cas loop. The value grows with every part, so a 1,000 header chord uses about 7 times the DynamoDB write units, and parts finishing together retry their cas.

For a lost header result, these failed it without the key for each header task:

Lost result B: chords failed Cost
Join anyway when the count equals the size ChordError after 5 s 3 of 3 none
Record when a result was first missing, and join on a later part return waits: no part returns later 0 of 3 none
Join when a missing header has no stored state ChordError after 5 s 3 of 3, or 0 of 3 with task_track_started=True none
One delayed check task after result_chord_expires ChordError after result_chord_expires 0 of 3 a new built-in task, and 58 to 67 redeliveries of its long countdown per run
A key for each header task that returns (this PR) ChordError naming the result after 2 s 0 of 3 one round trip and one key per header part
Interleavings
  • Killed between a header's result and its count: the copy the broker delivers again counts it.
  • Killed between a header's key and its count: the copy counts it, and its own key write finds the key there.
  • When parts bring the count to the size together, both read the results, and the one that adds the done key completes the chord. The other returns.
  • A duplicate brings the count to the size while a header still runs: that header has no result and no key, so the chord waits for it.
  • A header's result is lost: its key is still there, so the chord fails once, naming the result. The key lives twice as long as the result, so a backlog that outlasts the results still fails the chord instead of waiting.
  • A copy that returns after completion finds the group gone and the done key there, so it returns. The done key also lives twice as long as the results.
  • A write whose reply was lost and that the client sent again: the key stores this run's token, so it counts as this run's write.
Tests

t/unit/backends/test_chord_parts.py runs each test on the memory and memcached cache backends, DynamoDB and GCS:

  • A header task that returns twice before the chord completes: fails on main (join timeout).
  • A copy that returns after completion: fails on main (errback).
  • A header task killed between its result and its count, then delivered again: passes on main, fails on the earlier per-part add.
  • A group that expired fails the chord once: fails on main (once per run).
  • A header task that ignores its result fails the chord once: fails on main (after the join timeout) and on the version before the check (the chord waits).
  • A lost header result fails the chord once, while a header that hasn't returned keeps it waiting: fails before the key for each header task (the chord waits).
  • A header result that expired during a long chord fails it (memcached): fails while the keys expired with the results.
  • A header that uses one task id at two positions. _add_chord_key() counting a write the client sent again. A part run by a worker without this change.
  • The seeded random model: fails on main.

Per backend: the exact add, PutItem and create() calls, their expiry (twice the results' lifetime, including ttl_seconds and gcs_ttl, and at most 30 days on memcached), and DynamoDB errors other than a failed condition.

Integration on memcached: a duplicate before completion, and a late copy after a chord the worker ran. Both fail on main.

38 of 39 mutations of the new lines make a test fail. The one left returns True after a header that ignores its result already failed the chord, which only adds the count's round trips.

With acks_late, the broker can deliver a chord header task again, and
each run counts the part with incr. A run that returns before the chord
completes can make the count reach the chord size while another header
task still runs, so the join times out and fails the chord. A run that
returns after the chord completed finds the group result deleted and
calls the body's errbacks, although the chord succeeded.

Right before counting, record the part with memcached's add, keyed by
task id and header index as the Redis backend does, and return if
another run recorded it. The record lives as long as the header
results, so it outlives the chord: a run that finds the group deleted
checks it too, and only fails the chord for a part that was never
counted, as when the group expired.

The record holds a random token, so that an add that pymemcache's
RetryingClient sent again still counts. It's removed when incr fails or
a time limit interrupts it, so that a later run can count the part.

Backends that can't add a key atomically keep counting every run.
The DynamoDB backend counts chord parts with the same incr-based code as
the cache backend, so a header task that the broker delivers again is
counted twice too. Record each part with a conditional PutItem, which
only stores an item that isn't there yet. The item expires like the
results when the table has a TTL. If the condition fails, compare the
stored token, so that a put that botocore sent again still counts.
The GCS backend counts chord parts in Firestore with its own copy of the
incr-based code, so a header task that the broker delivers again is
counted twice. Once enough copies return after the chord completed, the
counter reaches the chord size again, the group result is gone, and the
body's errbacks run.

Record each part by creating a Firestore document, which fails when the
document exists, and return if another run created it. The document
expires a day later, like the chord counter.
The per-part record added earlier in this branch is written before the
count. A worker killed between the two leaves the part recorded but not
counted, and the copy that the broker delivers again then skips it, so
the chord never completes. On main that copy counts.

Count every run again, as main does, and treat the counter as a hint:
when it reaches the chord size, check that every header task stored a
ready result, and let the one run that adds the chord's done key
complete the chord. A copy that pushes the count to the size early
finds a result missing and returns; the missing part checks again when
it returns. A copy that returns after the chord completed finds the
group deleted and the done key, and returns. A group that expired still
fails the chord, once.

Without the per-part record, a header part costs the same backend round
trips as on main. Completing the chord costs one more read of the header
results and one add.

The chord tests move to one module that runs them on the memory and
memcached cache backends, DynamoDB and GCS.
Under python -bb, str() on a bytes key raises a BytesWarning. Decode
the key instead. The existing DynamoDB get() and set() still format
bytes keys with str(), so the shared chord tests ignore that warning for
DynamoDB.
Return from the completing branch when a result is missing or another
run completed the chord, instead of folding the check into its
condition. The flow then reads like main's, and matches the shape that
celery#11052 gives this code, so whichever change lands second rebases with
context-only conflicts.
The chord now completes only once every header result is stored, so a
header task with ignore_result=True kept it waiting. On main the join
timed out after result_chord_join_timeout instead. Fail the chord as
soon as such a part returns, with a ChordError that names the task. The
chord's done key makes this happen once, however many parts ignore
their results or return twice.
The chord waits while a header result is missing, since a duplicate can
bring the count to the size before another header task returned. A
result that memcached evicted, or that expired, then kept the chord
waiting forever, where main failed the join visibly.

Record each header task that returns, with a key that lives as long as
the header results. When the count reaches the size and every header
with a missing result has its record, the result was lost: fail the
chord, once, with a ChordError naming the missing results. A header
with no record yet is still running, so the chord keeps waiting.

The record costs one more round trip per header part. It only marks a
part as returned: every run still counts, the done key still decides
who completes the chord, and the results are still what it joins. A
part counted by a worker without this change has no record, so a lost
result in a mixed fleet still waits, as before.
A header's key and its result got the same lifetime, and the done key
too. Main refreshes the counter, the group and each part's own result as
header tasks return, but nothing refreshes these keys. When a backlog
stretched a chord past that lifetime, an early header's result and key
expired together, so the chord waited for a result that was gone instead
of failing, and a copy delivered after the done key expired ran the
errback for a chord that had succeeded.

Keep both keys for twice the header results' lifetime: still no
expiry when the results have none, and at most memcached's 30 day limit
for relative expiry times on the cache backend.
DynamoDB results expire through ttl_seconds and GCS results through
gcs_ttl, which can be longer than result_expires. Keep the chord keys
for twice the longer of the chord's result lifetime and that TTL, so a
header's key still outlives its result there.
The completion check read the header results, then the keys of the
missing ones. A header that stored its result and its key between the
two reads looked lost, and the chord failed although every result was
stored. A header stores its result before its key, so read the missing
results once more when every key is there.
@codecov

codecov Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.45763% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.49%. Comparing base (14115f0) to head (6007a82).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
celery/backends/base.py 96.15% 2 Missing ⚠️
celery/backends/gcs.py 96.55% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11072      +/-   ##
==========================================
+ Coverage   91.43%   91.49%   +0.06%     
==========================================
  Files         153      153              
  Lines       22061    22176     +115     
  Branches     2749     2772      +23     
==========================================
+ Hits        20172    20291     +119     
+ Misses       1588     1584       -4     
  Partials      301      301              
Flag Coverage Δ
unittests 91.48% <97.45%> (+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.

While workers with and without the change share a chord, a header task
delivered twice can leave the chord pending or run its body twice.
@auvipy
auvipy self-requested a review November 11, 2026 02:59
@auvipy auvipy added this to the 5.7.x milestone Nov 11, 2026

@MehrazRumman MehrazRumman 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.

Read b0b99fb, the code and the docs. The tests I only skimmed. I didn't run anything, so this is from reading the code.

The approach holds up in the interleavings I traced:

  • _missing_results() goes through _mget_to_results(), which keeps only ready states. A header that is STARTED with task_track_started=True still counts as missing, and has no part key, so a duplicate that brings the count to the size waits for it instead of joining early.
  • A header stores its result before on_chord_part_return() adds its part key. With the second read, a header that returns between the two reads doesn't fail the chord.
  • Completing and failing both go through the one .done claim. Once a chord failed because a result was lost, a later part can't complete it, and a copy after completion stops at the claim in the deps is None branch, before it writes a part key.
  • _chord_keys_exist() handles both the dict that mget() returns on the cache backend and the list it returns elsewhere.

All 523 checks pass on b0b99fb.

Two points inline: one changes the error a failed header reports, and one is about the new keys never going away in some configurations.

Comment thread celery/backends/base.py Resolved
Comment thread celery/backends/dynamodb.py Resolved
ChristianMurphy and others added 3 commits November 11, 2026 13:40
A header task with ignore_result and store_errors_even_if_ignored stores
its failure. The chord then failed with 'ignores its result' in place of
that failure. Only a header with nothing stored fails the chord early.
Without an expiry, as on DynamoDB with no ttl_seconds or with
result_expires unset, nothing removed the key each header task adds.
The part that completes the chord now deletes them in one batch. The
chord's own key stays: it stops a copy of a header task that returns
later.
@ChristianMurphy

Copy link
Copy Markdown
Contributor Author

I ran the DynamoDB path against AWS Emulator 1.0.322. The earlier DynamoDB runs used fakes.

A chord of 3 headers, each delivered twice main (9c2f238) this PR (2d401ed)
Body Ran once Ran once
Errback Called 3 times after the body, in 4 of 4 runs Not called, in 4 of 4 runs

Chords of 1, 30 and 200 headers and a chord with a failing header ended the same way on both. After a 30-header chord the table held the 31 results and 1 item for the chord, so the batch delete of the header keys works there.

Setup of the runs
  • Redis broker with visibility_timeout=2 and task_acks_late. Each header sleeps 4 s on its first delivery, so it is delivered and run a second time.
  • The backend creates its own table, with read=500&write=500. With the default of 1 write unit the emulator throttles the writes, on main and here alike.
  • The errback on main reports GroupResult ... no longer exists.
  • kombu main (445027e), Python 3.14, prefork with 4 processes.

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

is it ready?

@ChristianMurphy

Copy link
Copy Markdown
Contributor Author

It's ready

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

can this be included in celery v5.7.1?

@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.

isnt the PR going to change API surface in public? or not

Comment thread celery/backends/cache.py Resolved
Comment thread celery/backends/cache.py Resolved
@ChristianMurphy

Copy link
Copy Markdown
Contributor Author

isnt the PR going to change API surface in public? or not

It doesn't remove or rename any public name. It adds one on a backend: the class flag implements_add, which defaults to False, so third-party backends behave as before. Every other new backend method is private.

can this be included in celery v5.7.1?

I think so. It is a bug fix for #11036 and doesn't add a setting. For people on the cache, DynamoDB and GCS backends the docs notes say what changes:

  • Workers that share a chord should be upgraded together, or running chords left to finish first.
  • On GCS the service account also needs read access to the Firestore collection.
  • Each header task makes one more backend round trip (6, was 5).

I've changed the three docs notes to versionchanged:: 5.7.1.

@auvipy

auvipy commented Nov 28, 2026

Copy link
Copy Markdown
Member

OK

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 errback runs for a chord that succeeded when a header task is redelivered (memcached backend)

3 participants