Repository navigation
Fix chord_unlock redelivery dispatching the chord body twice - #11135
Conversation
…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.
|
@ChristianMurphy can you check |
ChristianMurphy
left a comment
There was a problem hiding this comment.
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 incelery_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_chordhave 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 NoneIn 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_countOther 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_errorran 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/backendsandt/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.
This comment was marked as abuse.
This comment was marked as abuse.
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
tony1233200
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Patch test coverage is now 100% (was 78.4% per codecov, 27 lines missing), head 5a413c5:
celery/backends/base.py: malformedclaimed_attreated as abandoned, non-dict lease payload treated as abandoned, store failure fails open, second read seeingdispatched, silent marker-write failure.celery/backends/database/__init__.py: vanished-row re-insert (both winning and losing again), unexpected storage error fails open, malformedclaimed_at/ non-dict payload in the locked decision.celery/app/builtins.py:chord_unlockretry 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.
This comment was marked as abuse.
This comment was marked as abuse.
|
Looks good, with two small changes. I ran Both points from my last review are fixed:
The kill loop from #11037 on PostgreSQL, two workers killed in turn every 4 s:
With a failing header task under the same kill loop, 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 2. No test checks that a takeover stores the new token. If the takeover returns Smaller things that can wait for a follow-up:
Change for point 1In - 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', NoneTest for point 2In 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
What I did not run
|
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).
This comment was marked as abuse.
This comment was marked as abuse.
documentation should be included here |
ChristianMurphy
left a comment
There was a problem hiding this comment.
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.
Fixes #11037
Summary
On result backends that finish chords with the fallback
chord_unlockpolling task (database, MongoDB, Cassandra, filesystem, …), a lost worker
could make the chord body run two or more times.
unlock_chordrecordednothing about having dispatched the body, so with
task_acks_late=Trueaworker lost after dispatching the body (or its retry) but before acking
caused the broker to redeliver
chord_unlock, and the copy dispatched thebody 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_unlockin the resultbackend, 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):
chord-unlock-claim-<group_id>, so it works on any backend that canstore a result and expires like any other result (
result_expires/backend cleanup) — mirroring the expiring
donemarker of the Redisbackend 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 alease: state
STARTED, a unique token and the claim time.dispatched— a previous run already finished this chord; thecaller must neither dispatch the body nor fail the chord again.
in_progress— another live worker holds a fresh lease;chord_unlockretries itself with its normal polling interval andre-checks, instead of dispatching concurrently.
chord_error_from_stack), the owner callsmark_chord_unlock_dispatched(), which replaces the lease with aSUCCESSmarker. The key/value, database, MongoDB and Cassandrabackends already refuse to overwrite a
SUCCESSresult with a laterone, which is what makes the marker stick.
polling: the not-ready retry chain is unchanged, and no claim is taken
on the
deps.ready()/retry-exhaustion paths.fallback_chord_unlock()callsreset_chord_unlock_claim()when anew 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_unlockare deduplicated.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.
on_chord_part_returncounterpath are untouched: Redis keeps its atomic Lua claim, and
apply_chordimplementations that don't go throughfallback_chord_unlocknever see the new claim.Crash recovery: if a worker is lost after taking the lease but before
storing the
SUCCESSmarker, 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)
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.
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_onein MongoDB,SET NXin key/value stores) and is leftas follow-up work.
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.
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.
chord_unlock(where the retry itselfcannot 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_unlockarguments executed twice to simulate broker redeliveryafter a lost worker):
Before this change:
After this change:
The claim cycle was also exercised directly against the real database
backend (SQLite, same
DatabaseBackendcode path as PostgreSQL):first claim
claimed, second claim while the lease is freshin_progress, after marking dispatcheddispatched, after resetclaimedagain, and a stale lease is taken over.Tests
New tests:
t/unit/tasks/test_chord.py(test_unlock_chord_task):dispatches once the header is ready;
dispatching;
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_unlockresetting theclaim for a new run, and fail-open behaviour on a backend without
result storage.
test_unlock_chord_task._chord_contextnow uses a fresh group id perinvocation: 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_infofails only because the test environment runs as root with pickle
accepted (
SecurityErrorfromcelery/platforms.py); it passes withC_FORCE_ROOT=1and is unrelated to this change.t/unit/backends/test_database.py(with SQLAlchemy installed):116 passed.
setup.cfgconfig) on all changed files: clean.