Skip to content

mongodb backend: keep the first SUCCESS instead of overwriting it - #10944

Merged
auvipy merged 6 commits into
celery:mainfrom
aniketatgithub:fix-10929-mongodb-cassandra-success
Oct 26, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
aniketatgithub:fix-10929-mongodb-cassandra-success

Conversation

@aniketatgithub

@aniketatgithub aniketatgithub commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Refs #10929

The MongoDB backend stored every result with an unconditional replace_one, so when a task ran a second time (redelivery after the worker was killed past the visibility timeout, as in the report) the second run overwrote the first run's SUCCESS, and later updates could replace it too.

BaseKeyValueStoreBackend already ignores any write once a SUCCESS is stored, and #10920 applies the same rule to the database backend. This does the same for MongoDB: _store_result puts the status check in the replace_one filter (status is not SUCCESS), so the check and the write happen in one step. When the stored document is already a SUCCESS the filter does not match and the upsert raises DuplicateKeyError, which is ignored, with one retry for a document inserted by a concurrent run.

Cassandra has the same bug, but this PR does not cover it: its write path goes through the session/table-creation lifecycle in _get_connection, and a pre-read there needs more care than a straight port of this change.

Tests: test_store_result_after_success_is_ignored, test_store_result_retries_duplicate_key and test_store_result_keeps_first_success cover the filter, the retry and keeping the first SUCCESS. They fail on the old read-then-write logic and pass with this change. The mongodb unit test file shows no new failures against the unmodified tree. A Changelog.rst entry under Unreleased notes that writes after a SUCCESS are now ignored.

@auvipy
auvipy self-requested a review October 24, 2026 12:05
@ChristianMurphy

Copy link
Copy Markdown
Contributor

I tested this against MongoDB 7.0 with pymongo 4.18.

It fixes the case from #10929. With the crash script from the issue, main prints SUCCESS report-8068 -> STARTED -> SUCCESS report-6183, and this branch prints PENDING -> STARTED -> SUCCESS report-4668. The new test fails on main and passes here.

The read and the write can still race.

_store_result now reads the document and then writes it, in two separate steps. If two runs of the same task overlap, one run can read the document right before the other writes SUCCESS, and then write over it. Runs overlap when the broker sends a task again while it's still running, such as after a visibility timeout. #10920 added a row lock to the database backend for the same reason.

I ran two writer processes in parallel, 200 rounds per test. Each number is how many rounds went wrong:

main this PR status in the filter
SUCCESS changed after a reader saw it 167 92 0
STARTED seen after SUCCESS 13 12 0
New task: STARTED written over a SUCCESS 43 48 0

Suggested fix: put the status check in the replace_one filter.

MongoDB checks the filter and writes the document in one step. If the stored document already has SUCCESS, the filter doesn't match, and the upsert raises DuplicateKeyError. The code can ignore that error. The same error also comes up when another run inserts the document at that moment. That case needs one retry:

query = {'_id': task_id, 'status': {'$ne': states.SUCCESS}}
for _ in range(2):
    try:
        self.collection.replace_one(query, meta, upsert=True)
        break
    except DuplicateKeyError:
        # The document has a SUCCESS, or another run just inserted it.
        pass
    except InvalidDocument as exc:
        raise EncodeError(exc) from exc

DuplicateKeyError is in pymongo.errors, next to InvalidDocument. With this change, all three counts were 0, and the crash script still stopped at the first SUCCESS. Without the retry, 17 of 200 new tasks lost their SUCCESS. It's also faster, because it drops the extra read: 0.84 ms per store, against 1.3 ms for this PR and 0.74 ms on main.

The new unit test checks that replace_one isn't called, so it would need to change. It could check the filter and the retry instead.

Put the status check in the replace_one filter so the check and the write happen in one step, and ignore DuplicateKeyError from an upsert against an existing SUCCESS, with one retry for a document inserted by a concurrent run.

Signed-off-by: Aniket <[email protected]>
@aniketatgithub

Copy link
Copy Markdown
Contributor Author

Thanks for testing this against a real MongoDB and for the detailed race numbers. I have pushed a commit that puts the status check in the replace_one filter and ignores DuplicateKeyError, with one retry for a document inserted by a concurrent run, and updated the tests to check the filter and the retry.

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Re-tested ed9a3cb against MongoDB 7. The race is gone:

150 rounds, two writers at once main 8002d05 (read, then write) ed9a3cb
A later run replaced the first SUCCESS 150 0 0
A reader saw STARTED after SUCCESS 86 0 0
A new task lost its SUCCESS 49 54 0

I think it's ready once the PR text is updated. It still says _store_result "reads the stored document first", and the squash commit may use that text.

A line under "Unreleased" in Changelog.rst would also help. Writes after a SUCCESS are now ignored. That includes AbortableAsyncResult.abort() on a finished task, and a task id you reuse, until forget() clears it.

Retry and mutation checks

With range(2) changed to range(1), a new task lost its SUCCESS in 21 of 150 rounds. Removing each part of the fix fails at least one test in t/unit/backends/test_mongodb.py:

Part removed Tests that fail
status in the filter test_store_result_after_success_is_ignored, test_store_result_keeps_first_success
The retry test_store_result_after_success_is_ignored, test_store_result_retries_duplicate_key
except DuplicateKeyError all three new tests
break test_store_result

@aniketatgithub

Copy link
Copy Markdown
Contributor Author

Thanks for re-testing against a real MongoDB and for the mutation checks. I have updated the PR text to describe the filter based write, and added a Changelog entry under Unreleased noting that writes after a SUCCESS are ignored, including abort on a finished task and reusing a task id until forget() clears it.

@codecov

codecov Bot commented Oct 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.04%. Comparing base (54f5a21) to head (48e9df3).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10944   +/-   ##
=======================================
  Coverage   91.04%   91.04%           
=======================================
  Files         153      153           
  Lines       21586    21591    +5     
  Branches     2661     2662    +1     
=======================================
+ Hits        19653    19658    +5     
  Misses       1624     1624           
  Partials      309      309           
Flag Coverage Δ
unittests 91.02% <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.

@auvipy
auvipy merged commit 6ef562b into celery:main Oct 26, 2026
505 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.

3 participants