Skip to content

Restore a KV-store chord's group only on the part that completes it - #11176

Open
binnguyenx wants to merge 4 commits into
celery:mainfrom
binnguyenx:fix-11045-chord-restore
Open

binnguyenx wants to merge 4 commits into
celery:mainfrom
binnguyenx:fix-11045-chord-restore

Conversation

@binnguyenx

Copy link
Copy Markdown

Description

Fixes #11045

What was wrong. On backends that count chords with incr (cache/memcached, DynamoDB), BaseKeyValueStoreBackend.on_chord_part_return restored the whole GroupResult on every header task. It needed the group to learn the chord size, because request.chord["chord_size"] hasn't been set since #6576. With the default result_cache_max=-1, every restore decodes all N results, so a chord of N tasks does O(N²) work.

What changes.

  • _chord.run puts the header size in the body as chord_size, using _descend (the count Redis already passes to set_chord_size). Headers built from a generator are left without it, so they stay lazy (group and chord: subtasks are not executed until entire generator is consumed #3021).
  • On backends with implements_add, a part whose request has the size checks the chord's done key, records its part key, counts, and returns if the count is below the size. Only the part that reaches the size restores the group, and then it follows the existing Complete a chord once on the cache, DynamoDB and GCS backends #11072 completion path unchanged. The done key is the same one Complete a chord once on the cache, DynamoDB and GCS backends #11072 keeps to stop a header task that returns after completion. Without the restore, it does that job before the count, on a counter that has already been deleted.
  • A request without the size (a generator header, or a message from an earlier version), or a backend without implements_add, keeps the old order: restore, record, count.
  • The done key is stored as a str, like the part keys, so every backend reads it back with mget(). On memcached a str key and a bytes key are the same key, and DynamoDB already stored it as a str.
  • GCS already reads chord_size, so it benefits from the canvas change without other edits.

How it was tested.

  • With an in-process worker, memory:// broker and cache+memory:// backend, GroupResult.restore() runs once per chord instead of 5/10/20/40 times for headers of those sizes.
  • New unit tests in test_base.py, test_cache.py and test_chord.py. The 4 that target the fix fail on main's code and pass with it. test_cache.py::test_chord_restores_its_group_once applies a chord through _chord.run and checks that the body is published once, with the right results.
  • test_chord_parts.py now runs every scenario with and without chord_size on memory, pymemcache, DynamoDB (moto) and GCS. That includes the random chords with redelivered, killed and concurrent parts.
  • I undid each behaviour-changing line one at a time, and each undo makes at least one test fail.
  • Full t/unit passes. flake8 and isort are clean.

Not tested. I didn't run integration or smoke tests. Redis, the backend CI runs integration with, overrides on_chord_part_return and isn't affected by this change.

A separate bug, not fixed here. In #11045 I said this change also fixes a hang with headers like chain(a.si(), group(b.si(), c.si())). That was true before #11072, but on current main that chord still hangs, with or without this PR. The chain's entry in the stored group is a GroupResult, and _complete_chord_once reports its id as a missing result, because no task result is stored under it. I can open an issue for it if that's useful.

🤖 Generated with Claude Code

BaseKeyValueStoreBackend.on_chord_part_return restored the whole group on
every header task to learn the chord size, because nothing set
request.chord["chord_size"] since celery#6576. With result_cache_max=-1 each
restore decodes all N results, so a chord of N tasks did O(N^2) work.

_chord.run now stores the header size (_descend, the count Redis already
uses) in the body. On backends with implements_add, a part with that size
records its part key and counts, and only the part whose count reaches
the size restores the group. The done key, kept after the chord
completes, stops a later copy of a header task before it counts, as the
restored group did. A body without the size (a generator header, kept
lazy for celery#3021, or a message from an earlier version) and a backend
without implements_add keep the order they had.

The done key is now stored as a str, like the part keys, so every backend
reads it back with mget().

Fixes celery#11045

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@auvipy
auvipy self-requested a review November 29, 2026 05:16
@auvipy auvipy added this to the 5.7.x milestone Nov 29, 2026
@auvipy

auvipy commented Nov 29, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy please check

@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.83%. Comparing base (07ec498) to head (163706e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11176   +/-   ##
=======================================
  Coverage   91.82%   91.83%           
=======================================
  Files         153      153           
  Lines       22308    22332   +24     
  Branches     2796     2803    +7     
=======================================
+ Hits        20484    20508   +24     
  Misses       1529     1529           
  Partials      295      295           
Flag Coverage Δ
unittests 91.81% <100.00%> (+<0.01%) ⬆️

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.

@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 one thing before merge: a test with a memcached server. The change itself held up in everything I ran.

I ran 163706e64 against main (07ec498c4) with memcached 1.6 as the result backend and a Redis broker.

main This PR
GroupResult.restore() calls for a chord of 5 headers 5 1
Read from memcached per chord of 40 headers with 1 KB results 249 KiB 158 KiB
The same for 200 headers 2,991 KiB 788 KiB
memcached commands per chord of 200 headers 1,002 gets, 404 sets 1,003 gets, 404 sets

The saving is in bytes, not in round trips: the read of the group is replaced by a read of the done key. Wall time for three chords of 200 headers was the same, 0.56 s.

These gave the same result on main and here:

  • Nine kinds of chord: simple, one header, group | body, a generator header, a chain in the header, a nested group, a nested chord, a failing header, 40 headers.
  • A new publisher with an old worker, and an old publisher with a new worker, complete a chord of 200 headers.
  • A pool process killed after its header was counted, or after the part return finished: the body ran once on main and here, no errback.

The test. The new tests use cache+memory:// or mocks. The integration tests for this backend are in t/integration/test_cache_backend.py, and one there would keep the restore count from growing back. The test below fails on main (5 restores) and passed here in 2 of 2 runs.

The hang you describe at the end comes from #11072 (mine), not from this PR. On memcached a chord whose header chain ends in a group completed in 20 of 20 runs before #11072, and it is PENDING in 20 of 20 on main and here. test_chord_expires in the same integration file fails since #11072 as well, on main and here.

Integration test

At the end of t/integration/test_cache_backend.py, with from unittest.mock import patch added to the imports:

@memcached
def test_chord_restores_its_group_once(manager):
    # Only the header task that completes the chord restores the group
    # (#11045). Before, every header task did.
    backend = manager.app.backend
    group_id = uuid()
    headers = [AsyncResult(uuid()) for _ in range(5)]
    body = tsum.s()
    body.freeze()
    body['chord_size'] = len(headers)
    backend.apply_chord((group_id, headers), body)
    with patch.object(GroupResult, 'restore',
                      wraps=GroupResult.restore) as restore:
        for index, header in enumerate(headers):
            backend.mark_as_done(header.id, index, request=Context(
                id=header.id, group=group_id, group_index=index, chord=body))
    assert AsyncResult(body.id).get(timeout=10) == 10
    assert restore.call_count == 1
Other checks
  • The tests the description names fail on main's source, and each of seven bugs I planted in the change fails at least one test.
  • t/unit/backends (base, cache, chord parts, DynamoDB, GCS), t/unit/tasks/test_chord.py and t/unit/tasks/test_canvas.py as tox runs them (python -bb): the same three tests fail on main and here, none in this change. flake8 and isort are clean.
What I did not run
  • DynamoDB and GCS servers. Their unit tests ran.
  • Pools other than prefork, and Python versions other than 3.13.

Adds an integration test, suggested in review, that runs a chord of
five headers on the memcached result backend and checks that
GroupResult.restore() is called once, by the part that completes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@binnguyenx

Copy link
Copy Markdown
Author

@ChristianMurphy Thanks for testing this so thoroughly. I added your integration test as test_chord_restores_its_group_once at the end of t/integration/test_cache_backend.py (51ff295), unchanged apart from the patch import.

I couldn't run it against a memcached server on my machine, so I've only checked that it lints and collects. Your 2-of-2 runs are the only memcached runs so far.

Thanks also for tracing the chain-ending-in-a-group hang and test_chord_expires to #11072. I'll leave both out of this PR.

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

Looks good now. I ran the new test at 51ff29586 against memcached 1.6 with a Redis broker: it passed 3 of 3 runs, and it fails on main.

test_chord_expires in the same file still fails there, on main as well. That one comes from #11072 and not from this PR.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KV-store chords restore the whole group on every header task (O(N²))

3 participants