Skip to content

Keep the first SUCCESS in the Cassandra backend - #10945

Merged
auvipy merged 6 commits into
celery:mainfrom
ZedingZhang:fix-cassandra-preserve-success-10929
Oct 28, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
ZedingZhang:fix-cassandra-preserve-success-10929

Conversation

@ZedingZhang

@ZedingZhang ZedingZhang commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Note: Before submitting this pull request, please review our contributing guidelines.

Description

Refs #10929 (Cassandra only). The MongoDB portion is handled in #10944.

Skip state writes when the newest stored Cassandra row is already SUCCESS, so a redelivered task does not replace it with STARTED, FAILURE, or a different successful result. Inspect the stored status directly without decoding the old result, traceback, or children. Initialize the write connection before reading, including when an earlier reader opened the session, so the result table exists.

Implement forget() by deleting the task's entire partition at cassandra_write_consistency. A task id can then be reused without waiting for cassandra_entry_ttl: storing SUCCESS 'monday', calling AsyncResult.forget(), then storing STARTED and SUCCESS 'tuesday' returns the new result. Forgetting an unknown task is harmless.

Regression tests cover preservation across backend instances, updates before success, undecodable payloads, table initialization, and the public forget/reuse flow. The forget tests also check cache clearing, isolation from other task ids, repeated deletion, custom table names, bound task-id parameters, write consistency, and reuse of an earlier read session. Add a changelog entry and a 5.7 versionchanged note under cassandra_read_consistency.

Validation

  • Python 3.13: pytest -q t/unit/backends t/unit/tasks/test_result.py — 1,204 passed, 11 skipped.
  • Cassandra unit tests — 41 passed; 100% statement and branch coverage for celery/backends/cassandra.py.
  • The 3 new forget regression cases fail with NotImplementedError on the previous PR head and pass with this change.
  • All repository pre-commit hooks pass.
  • Bandit passes for celery/backends/cassandra.py.
  • apicheck, configcheck, and repository-wide Bandit report the same failures on the unchanged PR base 6ef562b and this branch: 4 undocumented modules, 28 undocumented settings, and 49 Bandit findings, respectively. Sphinx successfully parses the new version-change note.

Each attempted store adds a read using cassandra_read_consistency, so writes depend on that read succeeding. Weaker reads can miss a successful row on another replica. The read and insert remain separate operations; concurrent writers can still race. A live Cassandra server was not available for local validation.

AI assistance: prepared with Codex.

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.07%. Comparing base (80c0b0e) to head (7739fd5).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10945   +/-   ##
=======================================
  Coverage   91.07%   91.07%           
=======================================
  Files         153      153           
  Lines       21652    21661    +9     
  Branches     2681     2682    +1     
=======================================
+ Hits        19719    19728    +9     
  Misses       1624     1624           
  Partials      309      309           
Flag Coverage Δ
unittests 91.05% <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 self-requested a review October 25, 2026 03:14
@auvipy auvipy added this to the 5.7.0 milestone Oct 25, 2026
@auvipy

auvipy commented Oct 25, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy would you mind checking this?

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

I checked this out and ran it against main. Since I had no Cassandra server, I used a small in-memory stand-in for the driver that keeps rows per task_id, newest first, like PRIMARY KEY ((task_id), date_done) ... CLUSTERING ORDER BY (date_done DESC). A first worker stores SUCCESS, then a second backend instance writes the states of a redelivered copy:

Redelivered write after SUCCESS(42) main this PR
STARTED stored state becomes STARTED stays SUCCESS(42)
FAILURE becomes FAILURE stays SUCCESS(42)
SUCCESS(99) becomes SUCCESS(99) stays SUCCESS(42)

So the fix does what #10929 asks for Cassandra and matches the key-value backends. The new tests fail on main and pass here, and test_cassandra.py and test_base.py give the same results apart from the new tests.

Suggestion: read only the status, without decoding the row

_get_task_meta_for() decodes result, traceback and children and rebuilds exceptions, only so the status can be compared. Besides the extra work, a row this worker can't decode now makes the write itself fail. A SUCCESS write after a row that does not decode with the current serializer (for example during a serializer change, or after a partially written row) raises DecodeError on this branch and nothing is stored, while main stores it. The status is the first column of the existing SELECT, so it can be checked directly:

        # Create the table before reading, and keep the first SUCCESS result.
        # Only the status is needed, so the stored payload is not decoded.
        row = self._session.execute(self._read_stmt, (task_id,)).one()
        if row is not None and row[0] == states.SUCCESS:
            return

With this, the three cases above give the same result, the undecodable-row case stores SUCCESS again, and all 29 tests in test_cassandra.py pass without changes.

Worth noting in the docs or changelog

  • Every state write now does a read first, so a normal task with task_track_started does 2 reads and 2 writes instead of 2 writes. The description already says this.
  • The read uses cassandra_read_consistency. With a stricter read than write consistency (for example LOCAL_QUORUM reads and LOCAL_ONE writes), a node outage that used to allow result writes now makes them fail at the read. That is probably acceptable, but it is a change in availability users may want to know about.
  • As the description says, the read and the insert are not atomic, so two writers racing on the same task id can still both write.

@ZedingZhang

Copy link
Copy Markdown
Contributor Author

Thanks, @MehrazRumman ! updated the check to inspect the stored status directly without decoding the payload, and added regression tests for undecodable rows.

@ChristianMurphy

Copy link
Copy Markdown
Contributor

Sure

Testing at 677b358 against a real Cassandra 4.1 server (one node).

The crash script from #10929 now keeps the first SUCCESS. Main prints SUCCESS report-3437 -> STARTED -> SUCCESS report-1519, and this branch prints PENDING -> STARTED -> SUCCESS report-6528.

A reused task id now keeps its first SUCCESS forever, though. The Cassandra backend has no _forget, so forget() raises NotImplementedError, and cassandra_entry_ttl is unset by default:

# store SUCCESS 'monday', call forget(), then store STARTED and SUCCESS 'tuesday'
main:        SUCCESS 'tuesday'
this branch: SUCCESS 'monday'

A _forget that deletes the task's partition fixes it. With this added, the script prints SUCCESS 'tuesday':

def _forget(self, task_id):
    self._get_connection(write=True)
    stmt = cassandra.query.SimpleStatement(
        'DELETE FROM {0} WHERE task_id=%s'.format(self.table))
    stmt.consistency_level = self.write_consistency
    self._session.execute(stmt, (task_id,))

Please also add a changelog line, and a versionchanged note under cassandra_read_consistency. A draft of the note is below.

Suggested note under cassandra_read_consistency
.. versionchanged:: 5.7

    Workers also use this level when they store a result: each write
    first reads the newest row of the task and skips the write if that
    row is ``SUCCESS``. A level stricter than
    :setting:`cassandra_write_consistency` can make writes fail while
    nodes are down, and a weaker one, such as ``ONE``, can miss a
    ``SUCCESS`` stored on another replica. The read and the write are
    separate steps. Two runs of the same task that overlap can still
    both write.
The race that remains

When run B pauses between its read and its insert, and run A stores SUCCESS during the pause, the result is FAILURE ValueError('B'), on main and on this branch.

Runs of a race harness, with writers on a barrier and a reader polling, moved in both directions. The read doesn't close the race:

Bad rounds main this branch
Run 1 (200 rounds): SUCCESS changed after a reader saw it 82 45
Run 2 (150 rounds): SUCCESS changed after a reader saw it 54 66
Run 2 (150 rounds): final state not SUCCESS 82 69

Part of it comes from main, not this PR. The primary key is (task_id, date_done), with date_done in milliseconds, so two writes in the same millisecond share a key and the later one replaces the row. In one run on this branch, 36 tasks had no SUCCESS row left.

A one-step check would need a static column and a lightweight transaction (... IF done = null). Cassandra 4.1 accepts it, but every existing table would need ALTER TABLE, and each write would become a Paxos round. That's outside this PR.

Cost and tests

On the one-node server, a store went from 1.2 ms to 2.5 ms (2,000 stores, two runs). The new tests fail on main (8 of 38 in test_cassandra.py). Reading the status through _get_task_meta_for() makes 9 fail, and reading before the table is created makes 23 fail.

@auvipy

auvipy commented Oct 26, 2026

Copy link
Copy Markdown
Member

@ZedingZhang please check the last review comment

@auvipy
auvipy merged commit cb2e588 into celery:main Oct 28, 2026
25 checks passed
@ZedingZhang
ZedingZhang deleted the fix-cassandra-preserve-success-10929 branch October 28, 2026 05:41
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.

4 participants