Skip to content

fix(cassandra): do not report a committed PutItem or UpdateItem as failed - #1401

Open
eliseong wants to merge 1 commit into
mainfrom
eliseong-cassandra-lwt-idempotent-2026-11-19
Open

eliseong wants to merge 1 commit into
mainfrom
eliseong-cassandra-lwt-idempotent-2026-11-19

Conversation

@eliseong

Copy link
Copy Markdown
Collaborator

What

A single-row write through occ_write (PutItem and UpdateItem) mapped a lost driver answer to an internal error even when the lightweight transaction had committed. A client that retried the error then applied a non-idempotent update a second time, so a concurrent list_append of fifty calls could leave fifty-one entries.

On a lost answer (an Io, Timeout, WriteTimeout or WriteFailure), the write now reads the row back at serial consistency and decides from its own full image:

  • stored item_data equals this write's exact image: the write committed, so the call succeeds;
  • the fence is intact (an existing row still at the fenced version, or a create whose row is still absent): the write did not land, so the OCC loop retries it like a lost race;
  • otherwise (the version moved on and this image is not stored): the outcome cannot be told from a committed write that a later writer overwrote, so the call returns an internal error and never re-runs the body, applying it at most once.

When the retry budget is spent on a single-row write, the call returns a transient error (503) rather than an internal error, so a caller backs off instead of re-applying. The unknown-outcome classifier moves from the backup catalog into cassandra_util so the write path and the catalog share it.

Why

tests/test_concurrency.py::TestConcurrentListAppend::test_concurrent_list_append saw 51 entries for 50 calls. The reported precedent is #342 (MongoDB: an ADD applied twice when a committed write was reported as InternalServerError). The same principle applies here: a committed write must not surface as a retryable or internal error, and an unknown outcome must apply the body at most once and never re-run it.

Refs #893

Testing done

  • Live Cassandra (4.1, single node): the concurrent list_append of fifty, nine runs, finished with fifty entries and no duplicate writer every run; the original head left duplicates. The internal errors that remain under contention are retried to success with no double-apply.
  • A frame proxy that forwards the write so Cassandra commits, then drops the answer and closes the connection: with a normal connection pool the write returns success and the item holds the write once. On the original head the same case returned a retryable error for a committed write.
  • cargo +1.97.0 fmt --check: clean. cargo +1.97.0 clippy -p extenddb-storage-cassandra --all-targets -- -D warnings: clean. cargo +1.97.0 test -p extenddb-storage-cassandra --lib: 178 passed.

Scope

This change covers occ_write, which serves PutItem and UpdateItem. It does not change DeleteItem or the conditional PutItem path (put_item_if_not_exists); those have the same class of error-after-commit and are worth separate issues. It does not make contention return 200; it returns a retryable error that a client retries to success, which is a narrower goal than serializing contention to success.

Open item for the reviewer

The "did not land, so retry" branch is safe because a serial read runs a full Paxos round that forecloses an in-flight minority-accepted write. On a single node this is trivially correct, so the single-node reproduction above cannot exercise it. It should be confirmed on a cluster with a replication factor above one before this is relied on there.

One case is left unresolved by design, matching #342: a write that committed and was then overwritten within the lost-answer window cannot be told from one that never committed, so the call returns an internal error. A client that retries that internal error can still double-apply. Closing that fully needs a per-request idempotency record, which is a larger change.

Checklist

  • I have read CONTRIBUTING.md
  • All tests pass (cargo test --workspace)
  • Code is formatted (cargo fmt --check)
  • Clippy is clean (cargo clippy -- -W clippy::pedantic)
  • I have added or updated tests for new functionality
  • I have updated documentation if behavior changed
  • Breaking changes are noted below (if any)
  • If this changes the wire protocol, Storage trait, auth model, on-disk
    format, or public CLI surface, an RFC has been accepted or is linked
    below. Otherwise, an ADR captures the decision (link below).

Notes on the checklist: I ran the Cassandra crate's lib tests and clippy with -D warnings (the setting CI uses), and the behavior under a lost answer was verified live against a real node, since exercising it needs a dropped answer that a committed test cannot produce without a fault hook in the write path. The full cargo test --workspace runs in CI. This changes the error a single-row write returns on a lost answer; it does not change the wire protocol, trait, auth model, on-disk format, or CLI.

ADR / RFC: n/a.


By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.

…iled

A single-row write through occ_write (PutItem, UpdateItem) mapped a lost driver
answer to an internal error even when the LWT had committed. A client that
retried the error then applied a non-idempotent update a second time: a
concurrent list_append of fifty calls could leave fifty-one entries.

On a lost answer (an Io, Timeout, WriteTimeout or WriteFailure) the write reads
the row back at serial consistency and decides from its own full image. If the
stored item_data is this write's exact image, the write committed and the call
succeeds. If the fence is intact (an existing row still at the fenced version,
or a create whose row is still absent) the write did not land, so the OCC loop
retries it like a lost race. Otherwise the outcome cannot be told from a
committed write that a later writer overwrote, so the call returns an internal
error and never re-runs the body, applying it at most once. When the retry
budget is spent on a single-row write, the call returns a transient error
(503), not an internal error, so a caller backs off.

The unknown-outcome classifier moves from the backup catalog into
cassandra_util so the write path and the catalog share it.

Refs #893

@demohan demohan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The case this targets is fixed at a02a71d: with a fault hook in occ_write on a single cassandra:4.1 node, a write that commits and loses its answer now answers 200 and is applied once, where the merge-base answered 500 and a retrying client applied it twice; the PutItem and UpdateItem answers with ALL_NEW, UPDATED_OLD, ALL_OLD and a condition match the service's single-writer answers in us-east-1. With 50, 200 and 400 concurrent writers on one key, over one and two servers, list_append, ADD, PutItem with ALL_OLD and a conditional claim give the same items, one GSI row per key and 1 INSERT plus N-1 MODIFY records, as main and the service. fmt, clippy, the 178 lib tests and the 1.91.1 check are clean, CI passes, and the branch merges with main at 222d80a, where clippy with test-hooks, 192 lib tests and the 1.94.0 check pass.

The commit check decides from the stored image and the stored version, and both readings can be wrong (below), so a write that did not commit can now answer 200 and one that did can be applied again. The title also claims more than the change covers: a committed write still answers 500 when the GSI or stream batch after it fails (update_item.rs:636-642, measured with an injected failure: the item committed with no GSI row and no stream record, and with SDK retries l=[b1,b1]), when the version advanced (the 500 drops its GSI and stream effects, [g1,g2,g1] with retries), and on TTL-enabled tables, which this does not change; and PutItem's spent retry budget still answers TransactionConflictException (put_get_item.rs:208-211), not the 503 the body names for single-row writes. docs/adr/0020-cassandra-occ-update-item.md:39 still says timeouts are not retried. DeleteItem, put_item_if_not_exists, BatchWriteItem, TransactWriteItems and PartiQL keep main's mapping of a lost answer to an internal error.

I will approve once a matching image alone is not taken as this write's commit, an unchanged version alone is not taken as proof it did not land, the title or the change covers the post-commit failures, and a test holds the commit check.

let stored_item: Option<String> = row
.as_ref()
.and_then(|r| r.get_by_name("item_data").ok().flatten());
if stored_item.as_deref() != Some(item_json_str) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A stored image equal to this write's is taken as its commit without checking the version. When A's lightweight write never ran and B then stored the same image, A answers 200 too: two ADD counter 1 calls both answer 200 and leave the counter at 1, the same on an absent item, and two writes with ConditionExpression counter = 0 both answer 200; with the merge-base mapping and a client retrying three times the same cases end at counter 2, counter 2 and ConditionalCheckFailedException for A, twice each. Two PutItems of one image also give two INSERT records, where the service gives one. Requiring the stored version to equal this attempt's next_version (line 376) as well would close it.

// existing row still at the fenced version, or a create
// whose row is still absent) the write provably did not
// land, so retry it like a lost race.
let never_applied = if item_existed {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An unchanged version, or an absent row for a create, does not prove the write did not land. When the statement reaches the node after this read, an unconditional list_append on a new item answers 200 with l=[a1,a1] (the service gives [a1]), and a conditional create answers ConditionalCheckFailedException while the item holds this request's own value, with no GSI row or stream record. When the write committed and a DeleteItem removed it before this read, the deleter's ALL_OLD returns the writer's image, the item comes back, and the stream shows REMOVE then INSERT with no INSERT before. Main applies twice on every lost answer, so this is not a regression. On Io, WriteTimeout or WriteFailure, sending the same fenced write again and deciding from its answer would hold; only the driver's Timeout, raised when no pool connection is free, means it was never sent.

}
// shortcut: the version advanced and our image is not
// stored, so a committed-then-overwritten write cannot
// be told from one that never committed. Fail honestly

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test holds this branch: forcing it to "not stored" still passes all 178 lib tests. test_hooks.rs already has ProgressWriteFault::{Landed, Lost}, and CI runs it in direct_integration, so a test that loses the answer after the commit, and one where it never ran, would keep both readings. Optional on the same lines: last.unwrap() at 491, and the read-back sleeps of up to 1.55 s with no bound against the request deadline.

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I read the change against main 92155f3. On a single-node Cassandra 4.1 with password authentication, as in CI, the crate's 178 lib tests passed at this head. The catalog test that uses the moved classifier passed 3 of 3 runs. No test reaches the new read-back or the 503 at line 271.

For #893, the read-back after a lost answer works as the description says. The write reads its row at LOCAL_SERIAL, decides from the stored row, and does not run the update body again. demohan's three comments of 28 November have no answer yet, and I agree with all three. I do not repeat them here.

These changes are needed before it merges:

  1. Line 497, from demohan's first comment: also require the stored version to equal next_version. Without it, two ADD calls from one base can both answer 200 and store one increment. My inline comment there names a case that the version check leaves open.

  2. A test of the read-back, as demohan asks at line 515. One table-driven test can cover the four outcomes:

    • The write committed: 200, with one write stored.
    • The fence is intact: retry.
    • The version advanced: 500.
    • Another writer stored the same image: the case of line 497.

    ProgressWriteFault and lose_next_maintenance_insert_answer in test_hooks.rs show the shape of the hook, and CI runs direct_integration with test-hooks.

  3. The 503 at line 271. It changes the answer for a spent retry budget, which is the subject of #878, and it changes UpdateItem only. The inline comment there has the detail.

  4. The documents. On Cassandra, a committed write whose answer was lost now answers 200, where main answers 500 InternalServerError. docs/versioning.md lists each such change under Behavior Changes by Release in docs/manuals/07-upgrade-manual.md, so this needs an entry under a ### v1.2.0: heading. If the 503 stays, the entry names it too. Lines 38-39 of docs/adr/0020-cassandra-occ-update-item.md say that UpdateItem retries only a clean lost race and passes a Cassandra timeout to the caller. After this change it reads the row back and can retry, so those lines need the new rule.

#1531 (navareamol, opened 30 November) changes the retry windows of the same loop for #878. The two PRs conflict in one hunk, the constants at the top of update_item.rs. The #1531 description gives the resolution: keep occ_window_ms and COMMIT_CHECK_PROBES, and drop OCC_BASE_DELAY_MS and OCC_EXP_CAP. The two fix different defects, so neither duplicates the other. Please name #1531 in the description. I found no other open or recent PR that changes this read-back.

The inline comment in cassandra_util.rs is about wording.

let stored_item: Option<String> = row
.as_ref()
.and_then(|r| r.get_by_name("item_data").ok().flatten());
if stored_item.as_deref() != Some(item_json_str) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with demohan's comment here. The version check closes the case of two writers that store different versions. One case stays open: two writers from one base that compute the same next_version. next_row_version_at returns max(previous + 1, now). Two writers get the same value when both read the clock in the same microsecond. They also get it when the stored version is ahead of both clocks, so that both take previous + 1. A token of the request in the LWT would tell those two apart. If you leave that case open, please say so in the comment.

// single-item write with TransactionConflictException only while a
// transaction holds the item, so answer a retryable 503 that the SDKs
// retry rather than a 400 the application sees.
Err(StorageError::Transient(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hunk changes the answer for a spent retry budget from 400 TransactionConflictException to 503 ServiceUnavailable. The description says that it replaces an internal error, but main answers 400 here. That answer is the subject of #878, and #1531 fixes #878 with the 400 kept. This PR fixes #893, so a change of this answer belongs with #878.

The UpdateItem API reference gives TransactionConflictException only for an item that a transaction holds. On #1531, LJMart11 measured that DynamoDB answered no error to 1,000 contended ADD calls with SDK retries off. The SDKs retry a 503 and not a 400, so 503 fits this state better than 400.

The change covers UpdateItem only, but the description says "a single-row write". PutItem (put_get_item.rs:208-211) and DeleteItem (delete_item.rs:110-113) still answer 400 when their attempts are spent. Two more paths end at this line:

  • A TTL claim lost on the last attempt (line 202). It now answers 503, and docs/differences-from-dynamodb.md:81 still says TransactionConflictException.
  • A last attempt that loses to a transaction that prepared the row after occ_read. DynamoDB answers TransactionConflictException while a transaction holds the item, so the comment at lines 265-266 does not hold for this path.

crates/storage/src/error.rs:44-50 and the comment at tests/test_stream_write_contention.py:349-352 also give the old answer.

Please drop this hunk and raise the code on #878 for the three writes together. If you keep it here, extend it to PutItem and DeleteItem, answer TransactionConflictException for the prepared row, and update the texts.

/// have reached a replica before the answer was lost. A write timeout or
/// failure on a lightweight transaction is the Paxos round not completing
/// within the coordinator's view; the proposal may still commit. A caller
/// that gets this must read the row (at `Stmt::SerialRead`) to learn whether

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other caller, backup_catalog::conditional_write, does not read the row. It answers WriteOutcome::Unknown and leaves the decision to its own caller. "must read the row" could say "reads the row (at Stmt::SerialRead) or reports the outcome as unknown". In backup_catalog.rs, outcome_unknown is now a wrapper of this function with a copy of this doc comment. A call to this function at line 243 removes both.

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.

3 participants