Skip to content

fix(mongodb): retry an unconditional PutItem that conflicts on a GSI table - #487

Open
LeeroyHannigan wants to merge 60 commits into
mainfrom
fix/mongodb-putitem-gsi-conflict
Open

LeeroyHannigan wants to merge 60 commits into
mainfrom
fix/mongodb-putitem-gsi-conflict

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changes since the last review

Before that, since c85e24e:

  • 10363a1 merges main (a417b2f), without conflicts.
  • eaa83a5: a BatchExecuteStatement statement that reaches the contention deadline or the attempt budget answers {"Error": {"Code": "TransactionConflict", "Message": "Transaction is ongoing for the item"}}. Before, it answered ValidationError with the 503 text. eaa83a5 also left TableName out of the entry, and f5c22b6 puts it back.
  • 6350dca: the comment above the floor of tests/test_put_item_gsi_contention.py and its assertion message say what the floor bounds: at least 1,814 of the 2,016 puts commit. The comment names the four live tests that hold the attempt budget.
  • 3e85e2f: BatchWriteItem and BatchExecuteStatement read the start of the request clock with web_time::Instant::now, and request_clock holds a web_time::Instant. std::time::Instant::now panics in the WebAssembly build, and the clippy step that main's wasm workflow gained in feat(wasm): [Add WebAssembly browser support for ExtendDB #1009 refused it. Native builds run the same code, because web_time re-exports std::time there.

What

Stacked on #431 (fix/mongodb-upsert-duplicate-key): this branch merges #431's branch and should merge after it.

On MongoDB, a contended single-item write now has two bounds, and both answer an error the SDKs retry:

  • The contention loops get their own budget of 1,000 attempts, CONTENTION_RETRY_ATTEMPTS: PutItem, DeleteItem, UpdateItem, TransactWriteItems, the GSI backfill and the key repair transaction. Every other loop keeps main's TRANSIENT_RETRY_ATTEMPTS of 50. These are the backup and restore transactions, the in-place retry of commitTransaction, and the create-race give-up of an unconditional PutItem and of UpdateItem's native upsert.
  • The four request loops stop after CONTENTION_DEADLINE, 10 seconds from the start of the request. The loop reads the deadline before each attempt after the first, so every request tries its write at least once. The GSI backfill and the key repair pass run in the background and take no deadline.

What each bound answers:

  • PutItem, DeleteItem and UpdateItem answer 503 ServiceUnavailable on either bound. A spent budget goes through main's write_conflict::retry_budget_exhausted ("PutItem: could not commit in 1000 attempts: ..."). The deadline goes through contention_deadline_exhausted beside it ("PutItem: could not commit in 10 seconds: ...").
  • TransactWriteItems answers TransactionCanceledException with a TransactionConflict reason per item on either bound.

BatchWriteItem runs main's handler inside a request clock scope (extenddb_storage::request_clock), so the requests of one batch share one deadline. After the deadline, each later contended request of the batch makes one attempt. Main's handler then returns the requests that could not commit in UnprocessedItems, or answers 503 when it applied none of them.

BatchExecuteStatement runs inside a request clock scope too, so the statements of one batch share one deadline. A statement that reaches either bound answers the per-statement error TransactionConflict with the message "Transaction is ongoing for the item". The entry also names the statement's table. demohan measured that entry. On 2026-11-25, concurrent TransactWriteItems calls kept touching one item. An UPDATE of that item got the error in 21 of 60 and 22 of 60 batches, each HTTP 200. In the review of 2026-11-26, all 184 conflict entries of two UPDATE runs and three DELETE runs named the table. The API reference also gives TableName as the table of a failed statement.

The engine answers every transient storage fault with the same 503, a lost connection among them. Each of these faults gets this entry in a batch too. On Cassandra, a statement whose item a transaction holds reaches the engine as TransactionConflictException and gets the same entry. A unit test covers that mapping, and no test ran it on a Cassandra server.

Why

Refs #426. The issue stays open after this branch merges. Unconditional puts on one key of a GSI table can still answer 503 where the service answers 200. With client retries off, 32 writers sent 30 PutItem each on one key. The service answered 960 of 960 with 200 in two runs on 2026-11-20. This branch answered 957 and 960 of 960 with 200 on a host at a load average of 32 to 36.

The message of db082ab, a commit of this branch, ends with a line that closes #426. That commit is on the remote branch and stays as it is. This PR merges as a squash, and the squash message leaves that line out, so #426 stays open.

On MongoDB a put on a table with an index writes the item and its index entries in one transaction. MongoDB aborts the loser of a same-document conflict at once instead of queueing it. So of N writers on one key, one commits per round and the rest retry. A writer needs on the order of N attempts. A share of the puts spent the budget of 50 attempts.

Measured against DynamoDB in us-east-1 with client retries off, on tables with a string hash key, a GSI and a stream, on 2026-10-23 and 2026-10-24:

shape calls outcome
32 writers putting one key of a GSI table 2,016 2,016 answered 200, the index held the final item's entry and no other
64 threads x 30 PutItem on one key 1,920 1,920 answered 200, 2.5 s
16 writers x 10 TransactWriteItems (one Put) on one key 160 53 answered 200, 107 answered 400 TransactionCanceledException with reason TransactionConflict

The service sheds none of the single-item load at any writer count measured. It sheds concurrent transactions on one key, with the same TransactionConflict reason that this branch answers.

The attempt budget bounds attempts but not the time a caller waits. One run had 256 writers on one key, with 1,000 attempts and no deadline. Of its 5,120 calls, 89 were still waiting when the client's 120 s read timeout fired. The deadline caps that wait.

Measured before the merge with main, with the budget and deadline each row names, on MongoDB 7.0 as a single-node replica set. Client retries were off, and all writers put one key of a fresh GSI table, 20 puts each. The host was shared, at load averages of 5.0 to 22.3, and how many calls this backend sheds depends on that load.

writers budget and deadline answers p99 longest call
64 50 attempts, no deadline 337 of 1,280 answered 200, 943 answered 503 7,070 ms 7,322 ms
64 1,000 attempts, no deadline 1,280 of 1,280 answered 200 18,397 ms 27,995 ms
64 1,000 attempts and the deadline 1,280 of 1,280 answered 200 7,864 ms 9,740 ms
256 50 attempts, no deadline 298 of 5,120 answered 200, 4,822 answered 503 12,192 ms 12,427 ms
256 1,000 attempts, no deadline 4,644 of 5,120 answered 200, 387 shed, 89 hit the client's 120 s read timeout 120,098 ms 120,103 ms
256 1,000 attempts and the deadline 1,262 of 5,120 answered 200, 3,858 shed, none hit the timeout 10,662 ms 11,658 ms

The bounds cost CPU on the MongoDB server, because the losers of a hot key retry for up to 10 s. The measurement ran 64 and then 256 writers on one key for 20 s. The host had 16 cores, at a load average of 18 to 21. mongod used a median of 132 and 128 percent CPU. It ran 1,666 and 1,811 transactions a second, of which 98.7 and 99.6 percent aborted.

The service answered 1,920 calls from 64 writers on one key in 2.5 s, about 770 a second. In the runs above this backend committed 2.4 to 38.9 puts a second. That gap comes from MongoDB aborting the loser of a same-document conflict instead of queueing it, and this branch does not change it. This branch changes which answer a losing write gets and how long it waits.

Merged with main

Main #475 already gives up a spent PutItem budget as Transient and returns deferred BatchWriteItem requests in UnprocessedItems. This branch now uses main's batch handler and main's give-up message, and drops its own copies. Main counts the capacity of the applied requests only. The service also counted an unprocessed request in the measurement this branch made on 2026-11-03, and #996 tracks that difference. Main #671 points six backup and restore loops at TRANSIENT_RETRY_ATTEMPTS. So this branch gives the contention loops a constant of their own instead of raising that one.

Overlaps with other PRs

This branch contains #431's head. No other PR changes the contention loops, request_clock or batch_execute_statement. #529 changes the last arm of StatementError::from_error, beside the TransactionConflict arm of this branch. It gives throttling and server errors their own codes and leaves ServiceUnavailable at ValidationError. So the two changes do not duplicate each other. #781 and #708 also change crates/engine/src/partiql/common.rs, and a merge of either with this branch adds no conflict.

The branch merges with main without conflict. On 4 December 2026, git merge-tree compared b5af797 and main with each of the 213 other open PRs. For #550, #853 and #1127 it used their merges of main at 1e2ebdd (3d882d0, 6d3d448 and 059c6ca). The branch conflicts with these open PRs in the files named, where they do not conflict with main. After one of them lands, the other takes a merge of it:

Testing done

  • Storage live tests, cargo +1.97.0 test -p extenddb-storage-mongodb --lib -- --ignored --test-threads=1 data_engine::live_tests::, against a MongoDB 7.0.45 single-node replica set on this host, at 86d02ba: 26 passed, 0 failed, in 36.27 s. The tests cover:
    • 32 writers putting one key on the transaction path, all committing. The test sets a 600 s deadline, so the attempt budget is the one bound they can reach
    • a contended PutItem, DeleteItem and UpdateItem that each reach a 2 s test deadline and answer the deadline give-up
    • a contended TransactWriteItems that reaches the deadline and answers TransactionCanceledException with a TransactionConflict reason per operation, with neither operation applied
    • a put that spends its 1,000 attempts under a 600 s deadline and answers main's budget give-up
    • a held put inside a request clock scope that started past the deadline, which gives up after one attempt
    • a free put in the same scope, which commits
    • fix(mongodb): retry an unconditional PutItem that loses the create race #431's create-race tests
  • With CONTENTION_RETRY_ATTEMPTS set to 50 at eaa83a5, four of the five contention live tests failed. The four are the 32-writer test (42 of 256 puts failed), the two deadline tests and the budget test. The request clock scope test passed.
  • Library tests at 86d02ba ran with the replica set in EXTENDDB_TEST_MONGODB_URI. cargo +1.97.0 test -p extenddb-engine -p extenddb-storage --tests: extenddb-engine 981 passed, plus 1 integration test, and extenddb-storage 292 passed. cargo +1.97.0 test -p extenddb-storage-mongodb --lib: 201 passed, with 91 live tests ignored. The unit tests cover the deadline helpers, the two give-up messages, the request clock and the per-statement TransactionConflict entry.
  • With the crates/engine/src/partiql/common.rs of a24d811 back in place, which leaves TableName out, a_write_that_lost_to_contention_answers_transaction_conflict fails on the missing TableName. With f5c22b6 it passes.
  • The Python wire tests, which CI runs too, on this host against a MongoDB server built from 86d02ba:
    • tests/test_put_item_gsi_contention.py: 32 writers put one key 2,016 times. Every call must answer 200 or 503 ServiceUnavailable with the message "Service is temporarily unavailable". At least nine in ten of the puts, 1,814 of 2,016, must commit. The floor bounds how many puts the server sheds and does not hold the attempt budget, which the four live tests above hold. This head shed 1 of the 2,016 puts, at a load average of 17 to 24. On 2026-11-24 a server built from main's production files (44cd436) failed the test. It shed 431 and 444 of the 2,016 puts in two runs, at a load average of 17 to 19.
    • tests/test_mongodb_batch_write_contention.py (3 tests): the server returns a held item in a batch as unprocessed, and the rest of the batch is not resent. A batch with two held requests answers within one deadline, and so does a BatchExecuteStatement of three held UPDATEs. Each of the three statements answers the TransactionConflict entry above with the table's name, and the test checks the entries by equality. The batch of statements answered in 10.04 s. At 6350dca the test failed on a server built with the old mapping, and with the Code changed to XControlCode.
    • tests/test_concurrency.py (7 tests), tests/test_put_item_create_race.py (9) and tests/test_stream_write_contention.py (5), which this branch also changes: all 21 passed.
  • cargo +1.97.0 fmt --all -- --check: no changes. Both clippy commands of .github/workflows/clippy.yml on the three crates this branch touches: no warnings. The clippy step of .github/workflows/wasm.yml: no warnings. cargo +1.94.0 check --locked --all-targets on the same crates: passes. cargo test -p extenddb-wasm-adapter --lib --test parity: 4 passed. cargo test -p extenddb-storage-postgres --test doc_version_literals: 3 passed. pytest --collect-only collects 7,305 tests in tests/ and 820 in tests/python, with no error.
  • cargo +1.97.0 clippy with -W clippy::pedantic on the three crates reports no warning on a line this branch adds.
  • Cargo.lock does not change, so the license notice checks do not apply.

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

ADR / RFC: RFC-206, section "Write conflict handling", which this branch rewrites. The RFC is a draft.

Breaking changes

On an existing MongoDB deployment, a contended single-item write now waits for up to 10 seconds, plus the attempt already running, before it answers 503. Before, 50 attempts ended it. The server sheds fewer writes on a hot key. A BatchExecuteStatement statement that loses to contention, or that meets a fault the engine answers 503, now answers TransactionConflict on every backend. The entry names the table as before. Before, it answered ValidationError. The upgrade manual describes both changes. Its entry is "v1.2.0: on MongoDB, a contended write retries for up to 10 seconds, and a BatchExecuteStatement statement that loses answers TransactionConflict".


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.

Amazon DynamoDB applies concurrent PutItem calls on one key one after
another. A call without a condition succeeds, the last writer's item is
stored, and with ReturnValues ALL_OLD each call returns the item it
replaced. Measured on 2026-10-21 against the service in us-east-1 with
client retries off: 32 writers x 63 rounds of racing unconditional puts
on a new key per round answered 2,016 of 2,016 with 200 on hash, GSI and
stream tables; 32 writers on one key for 63 rounds answered 2,016 of
2,016 on GSI and stream tables; one key with half the writers sending
PutItem and half DeleteItem answered 22,400 puts and 22,400 deletes with
200 and no error (seven runs of 64 writers x 100 operations on a hash
table, three runs of 32 x 200 on a GSI table); 32 writers racing PutItem
against DeleteItem, UpdateItem and BatchWriteItem on one key answered
every call with 200; and 64 writers with one putter per three deleters on
one key answered 960 puts and 2,880 deletes with 200. In every cell the
ALL_OLD images, the final item, the index and the stream records formed
one serial history. tests/test_put_item_create_race.py runs against the
service as well as against ExtendDB and checks the race on 8 clients.

On MongoDB, two puts that create the same item could each find no
document and each insert it. The second insert fails with a duplicate-key
error (E11000), which findAndModify reports as a command error. The data
collection has two unique indexes: _id_, and one on the key fields (pk,
plus the sort key field on a table with a sort key). MongoDB retries such
an upsert itself only when the filter is an equality on the fields of the
index that raised the error. The put filters on pk and, on a table with a
sort key, the sort key field, and every measured duplicate-key error names
_id_, so the server does not retry it. The sessionless path (no condition,
no index, no stream) returned the error as an internal error (HTTP 500),
and the transaction path (a table with an index or a stream) classified it
as fatal, which also returned an internal error. On a 16-core host the
race test failed 2 or 3 of its 9 cases per run, each failure a racing put
answering InternalServerError; 32 writers creating a new key per round
got 3 InternalServerError responses in 2,016 puts; and one-key put and
delete churn from 8 and 32 threads got 66 and 45 in 2,016 puts.

Both paths now retry the put under the transient retry budget of 50
attempts with the same backoff the write-conflict retry uses. The next
attempt finds the item the other put created, replaces it and returns it
as the old image, so the ALL_OLD images form one chain; if a delete
removed that item first, the next attempt inserts. On the transaction
path the index update and the stream record take that item as the old
image too. A put whose 50 attempts all lost the create race returns the
internal error the PostgreSQL backend returns when its own retries of
this race run out, with the attempt count in the message.
is_duplicate_key now recognizes the command form as well as the write
form that insert_one returns.

The MongoDB xfail marker on the plain-table race tests is removed.
devtools/run-mongodb-tests exports EXTENDDB_TEST_MONGODB_URI, and two
storage crate tests use it, on the sessionless path and on the
transaction path each: one forces every attempt to lose the race with a
document that holds the item's _id under another pk and checks the
give-up error after 50 attempts and that the document is unchanged; the
other replaces or deletes that document 100 ms after the put starts and
checks that the put succeeds, returns the other put's item or no old
image, and stores its own item. Without the URI the tests print a SKIP
line; with EXTENDDB_TEST_MONGODB_CONTAINER set and no URI they fail. The
scratch databases are dropped when a test fails.

Verified against MongoDB 7.0 as a single-node replica set. The race test
passes 9 of 9 cases in each of 16 runs. The same cells as the service
measurement answered every unconditional PutItem, DeleteItem and
BatchWriteItem with 200 and no invariant violation; one-key put and
delete churn answered 44,800 puts and 44,800 deletes with 200 (ten runs
of 16 x 400 and four of 64 x 100) while 4,663 puts lost a create race
and succeeded on a later attempt. With the backoff removed from the
sessionless retry the lost-race-then-success test fails after 50 attempts;
with a cap of 5 lost races put back on either path, with the transaction
give-up error disabled, or with the transaction arm giving up at the first
lost race, the storage crate tests fail; with the sessionless retry
disabled the race test fails its 3 plain-table cases. One-key contention
on GSI and stream tables still answers TransactionConflictException for
some puts (issue 426), unchanged here.

Closes #356
…table

Amazon DynamoDB applies concurrent PutItem calls on one key one after
another and answers each with 200; with a global secondary index the index
holds the final item's entry only. Measured on 2026-10-23 against the
service in us-east-1 with client retries off: 32 writers putting one key of
a table with a GSI, 2,016 puts, 2,016 answered 200, and the index held the
entry of the final item and no other.

On MongoDB a put on a table with an index writes the item and its index
entries in one transaction. MongoDB aborts the loser of a same-document
conflict at once instead of queueing it, so of N writers on one key one
commits per round and the rest start over, and a writer needs on the order
of N attempts, more under the connection pool's queueing. The retry budget
of 50 attempts ran out for a share of the puts, and the put answered the
400 TransactionConflictException main reserves for a single-item write that
could not serialize against concurrent activity.

The budget is now 1,000 attempts for every write path in data_engine.rs.
The backoff is random, so a writer can lose many rounds in a row, and the
chance of losing every attempt falls off exponentially with the budget:
400 attempts left one put in 2,016 without a commit on a host at a load
average of 30 and 20 of 1,984 with 64 writers. backoff_sleep is capped at
12.8 ms, so 1,000 attempts bound a write at about 6.4 s of backoff plus
the attempts' own round trips before it gives up; measured against a
transaction another session holds open, a put returns after 10.5 s. A
PutItem that runs out of attempts returns StorageError::Transient, which
the engine answers as HTTP 503 ServiceUnavailable. The service answers a
PutItem with TransactionConflictException only while a TransactWriteItems
holds the item, which this backend cannot tell apart from a race against
other puts; the DynamoDB error-handling documentation lists
ServiceUnavailable (HTTP 503) as "OK to retry? Yes", and the SDK retry
modes retry a 503 on their own, whereas a 400 is handed to the application.

Measured on MongoDB 7.0 (single-node replica set, client never retries),
32 writers putting one key of a GSI table, 2,016 puts: main (9d13202)
answered 303 of 2,016 with 400 TransactionConflictException; c3f8bc8 (#431) answered 322 of 2,016 with 400 TransactionConflictException; this branch
answered 2,016 with 200 in each of 3 runs of the wire test, and the index held
the final item's entry only. tests/test_put_item_gsi_contention.py runs
this shape and fails on main and on c3f8bc8. Two storage crate tests run
against the replica set named by EXTENDDB_TEST_MONGODB_URI: 32 writers
putting one key on the transaction path all commit, and a put whose every
attempt conflicts with a transaction another session holds open gives up
with the transient error after 1,000 attempts, in 10.5 s, leaving the
held item unchanged.

Fixes #426
…gets

TRANSIENT_RETRY_ATTEMPTS sized three different loops, and raising it to
1,000 for hot-key contention raised all three. Two of them are not
contention loops and no measurement in this branch says anything about
running them 1,000 times:

commit_write_transaction retries commitTransaction in place after an
UnknownTransactionCommitResult. The label means the commit's outcome is
unknown, the commit is idempotent and the body must not be re-run, so
those attempts wait for one reply rather than racing other writers.
COMMIT_RETRY_ATTEMPTS keeps it at the 50 every write path used before.

An unconditional PutItem that keeps losing the create race gives up with
an internal error. #431 measured that path at 50 attempts with this
backoff: a put blocked by a document another writer removes 100 ms after
the put starts commits well inside it, and the storage tests fail with
the cap put back to 5. CREATE_RACE_ATTEMPTS keeps it at 50, on the
sessionless path and on the transaction path. The transaction path now
gives up as soon as that budget is spent instead of carrying lost races
through the contention budget.

TRANSIENT_RETRY_ATTEMPTS stays at 1,000 and now sizes the contention
loops only: put, delete, update, transact and the GSI backfill.

The constant's doc comment said 1,000 attempts "bound the wait at about
6.4 s of backoff". backoff_sleep draws each sleep uniformly from 0 to the
current base, capped at 12.8 ms, so 6.4 s is the mean of the sleeps and
12.8 s is the bound, before the attempts' own round trips. Measured on
MongoDB 7.0 as a single-node replica set, a put that loses all 1,000
attempts to a transaction another session holds open answered in 9.46 s,
9.85 s and 10.00 s over three runs, where each attempt also waits out
MongoDB's lock timeout. The comment now states the mean, the bound and
the measurement, and the test prints the elapsed time it already
measured.

The RFC's write-conflict paragraph said is_transient_write_conflict
returns true for the UnknownTransactionCommitResult label. It does not,
by design: under that label the commit may already have applied, so the
body must not be re-run, and classify_commit_error handles it alone. The
paragraph now also names the commit and create-race budgets and carries
the corrected mean and bound.

Issue #426
main added four fields to MongoEngine in #384. The with_scratch_engine test
helper builds the engine with a struct literal, so against a main that
carries #384 it failed to compile with E0063. It now sets the four fields the
way backup_live_tests.rs does.

The comments on the retry budget give the measured wall time of a put that
loses every attempt as a range from six runs on a shared host.
The 1,000-attempt budget bounds attempts, not the time a caller waits. At
256 writers putting one key of a GSI table, 89 of 5,120 calls were still
waiting when the client read timeout fired at 120 s, past the SDKs'
default read timeouts.

The contention loops of PutItem, DeleteItem, UpdateItem and
TransactWriteItems now read CONTENTION_DEADLINE (10 s) before each attempt
after the first. A single-item write that reaches it answers
ServiceUnavailable (HTTP 503), which the SDKs retry. A transaction that
reaches it answers TransactionCanceledException with a TransactionConflict
reason per item, as it does when its attempts run out and as the service
answers a transaction that loses to contention. The GSI backfill loop runs
in the background worker and takes no deadline.
The deadline and the 1,000-attempt budget take about the same time against a
contended key, so a test could not say which bound ended a write. The engine
now carries the deadline, set to CONTENTION_DEADLINE in every production
construction, and a storage test sets it: 2 s makes the deadline the bound,
600 s makes the attempt budget the bound.

Three paths that had no test now have one. A contended PutItem, DeleteItem and
UpdateItem that reach the deadline each answer the transient error the engine
answers as HTTP 503, with the operation and the deadline in the message. A
TransactWriteItems that reaches the deadline answers a canceled transaction
with a TransactionConflict reason per operation, which is what the service
answers a transaction that loses to contention. The test named for the attempt
budget reaches the attempt budget again and asserts the 1,000-attempt message
rather than either message. Each test is bounded to the deadline it sets, so a
loop that stopped reading the deadline fails it.

The doc comment on the deadline said both bounds answer the same HTTP 503,
which holds for PutItem and TransactWriteItems only. On this branch DeleteItem
and UpdateItem answer 503 on the deadline and 400 TransactionConflictException
when their attempt budget runs out first, measured in 2 of 4 rounds against a
document a transaction held. The comment and the RFC paragraph now say that,
and name the change that gives all three single-item writes one answer.
… has

tests/test_put_item_gsi_contention.py asserted that all 2,016 puts of 32
writers on one key answer 200. The retry deadline this PR adds makes that
false under load: a put that has been losing for ten seconds is shed with 503
ServiceUnavailable. The file failed 1 of 4 runs in the shape CI uses, two
xdist workers on one server, and failed with 240 of 2,016 shed when another
hot-key load shared the server.

The test now asserts the contract the retry loop gives. Every call answers 200
or 503 ServiceUnavailable, never 400 TransactionConflictException and never
500; the stored item is one writer's item, whole, carrying the gk that writer
sent with that w; and the index holds exactly one entry for it. The number
shed depends on the load the server is under, so the test reports it instead
of asserting it. The docstring keeps what the service answered to this shape,
200 to every call, and says where ExtendDB diverges.

docs/differences-from-dynamodb.md gets a row for that divergence under
Capacity and Throttling, with the measurements at 64 and 256 writers and what
each operation answers at each bound.

@robinnsc robinnsc 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 single-item fix holds up. On a local MongoDB 7 with a GSI + stream table and 32, 64 and 256 writers on one key, PutItem only ever answered 200 or 503. The stored item, its single index entry and the stream (one record per commit, none for a shed put, an unbroken old-image chain) were consistent after every run. UpdateItem, DeleteItem and TransactWriteItems on the same key were consistent too, and conditional puts weren't retried into wrong answers. The longest single-item call was 11.8 s at 256 writers, against 28 s on main. Uncontended puts cost the same as before. The 9 new storage tests pass, and #431's create-race fix holds (2,880 of 2,880 racing creates answered 200).

Two things I'd look at before merging, both in the first two inline comments: BatchWriteItem, and the merge with current main not compiling in test builds.

Smaller notes:

  • On a GSI + stream table, writes to different keys that conflict while writing the index or the stream counter still answer 500, because those errors map to Internal in sync_indexes_in_session and the stream helpers. A mixed BatchWriteItem + PutItem run gave 68 of 240 batches and 9 of 240 puts as 500 on head (main is similar). If that's #437's scope, it might be worth saying so, since the description says no 400 or 500 in any run.
  • A hot key keeps mongod at about 2 cores for as long as the contention lasts (about 1,800-1,900 transactions/s at 64 and 256 writers), since the backoff cap is still 12.8 ms and losers now retry for up to 10 s. That seems like a fair trade-off, just worth a sentence.
  • The overshoot past 10 s (up to 12.4 s at 256 writers) comes from the attempt in flight waiting on the 50-connection pool and the commit retries. The doc comment's "deadline plus one attempt" covers it, but the attempt can be a couple of seconds on its own.
  • Small doc nits: the orphaned doc comment on fn hash_key in the test module; the RFC decision-table row at docs/rfcs/0000-mongodb-backend.md:238 still says the UnknownTransactionCommitResult label is detected, which the rewritten paragraph now contradicts; contention_deadline_exhausted prints as_secs(), so a sub-second test deadline reads "0 seconds".


let tx_options = self.write_transaction_options();
let mut lost_create_races = 0;
let contention_started = std::time::Instant::now();

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 clock starts per storage call, and batch_write_item.rs:127-138 / :181-191 call put_item / delete_item once per item, so a BatchWriteItem gets 10 s per item. With items held and released 7-9 s apart, a 10-item batch answered 200 after 70 s, and with botocore's default 60 s read timeout the client timed out with 8 of 10 written. Main answered 400 in 0.4 s.

The bigger effect is the 503 itself. Earlier items in the batch have already committed when a later one gives up, and since 503 is retried by the SDK (main's 400 wasn't), the whole batch is resent. Repro with [delete A, put B], B held for 14 s, and another client putting A=v2 at 5 s, which got 200: the batch's resend deleted A again, so the final state is A absent, with stream records REMOVE v0, INSERT v2, REMOVE v2. With [put A=v1, put B] the final state was A=v1 after the other client's v2. On main the same shapes answered 400 once, and v2 survived.

DynamoDB returns items it couldn't write in UnprocessedItems, so the SDK never resends the applied ones. Could consider carrying one deadline per request into the batch, and returning the item that gave up plus the rest as UnprocessedItems rather than failing the batch. ImportTable (import_export.rs:154) has the same per-item shape, though there it's a fresh table.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 6c36c14. The BatchWriteItem handler now runs inside a request clock scope (the new extenddb_storage::request_clock), and the MongoDB contention loops measure CONTENTION_DEADLINE from the start that scope carries, so the requests of one batch share one 10 s deadline. A request that gives up with the transient error, or with TransactionConflict (DeleteItem's spent budget on this branch), is returned in UnprocessedItems, and the requests after it are still tried, each with at least one attempt. The batch answers the error only when none of its requests was applied, so a client that retries that error resends nothing that took effect. The capacity of an unprocessed request is still counted.

DynamoDB does the same. With TransactWriteItems calls updating one item and client retries off, 46 of 80 [put held, put free] batches and 53 of 80 [put free, put held] batches answered 200 with the held request in UnprocessedItems and the free item written, each reporting the 2 capacity units of both requests. A batch whose only request is on the held item answered 500 InternalServerError in 54 of 80 calls and never 200 with its request unprocessed. ExtendDB answers that batch with 503.

tests/test_mongodb_batch_write_contention.py runs your repro: [delete A, put B], B held past the deadline by a mongosh transaction, another client putting A=v2 at 5 s, and the SDK's default retries on the batch client. On this head the batch answers 200 in 10.01 s with only the put of B in UnprocessedItems, and A holds v2. Against the build before this commit the same test fails: the batch answered 200 after 15.02 s with nothing unprocessed, because the first send answered 503 at the deadline and the SDK resent the batch, and the resend deleted A=v2 and wrote B=v1 once the hold ended. A second test holds B1 for 6 s and B2 past the deadline: on this head the batch answers in 10.02 s with B2 unprocessed. The build before this commit answered after 14.63 s with nothing unprocessed, because B2's own deadline started 6 s in and B2 committed when its hold ended.

ImportTable is not changed. It writes a table it created at the start of the import, so its puts meet contention only when another client writes that table during the import, and it runs outside any scope, so each of its puts keeps a deadline of its own.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Two statements above are out of date at the current head. DeleteItem's spent budget is now write_conflict::retry_budget_exhausted, the same transient error as PutItem's and UpdateItem's, which the engine answers as 503 and the batch handler returns in UnprocessedItems. And since the merge with main, the handler counts the capacity of the applied requests only. An unprocessed request adds none, and #996 tracks that difference from the service.

/// construction uses. A test sets it short to make the deadline the bound
/// a contended write reaches, or long to make the attempt budget the
/// bound, instead of racing the two.
pub(crate) contention_deadline: std::time::Duration,

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.

git merge-tree against current main is clean, but cargo check -p extenddb-storage-mongodb --tests on the merged tree fails with E0063: missing field contention_deadline at stream_records_live_tests.rs:46. That literal came in with #543 after this branch merged main. It's the same kind of break as the #384 one the description mentions, and #431 on its own also fails against main (its with_scratch_engine literal). A single test constructor for MongoEngine might save the next round of these.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 9212328, after merging main in ac1f3b4. MongoEngine::new now builds the engine in from_parts, and a test-only MongoEngine::for_test calls the same function. The literals in backup_live_tests.rs, stream_records_live_tests.rs, snapshot_engine.rs and the restore backfill test call for_test and set only the fields they change with struct update syntax, so a field added to MongoEngine is set in from_parts and nowhere else. The contention tests moved into data_engine_live_tests_contention.rs and build their engine through the live test module's scratch_engine, setting only contention_deadline. On the merged tree cargo clippy -p extenddb-storage-mongodb --all-targets -- -D warnings is clean and the crate's unit and live tests pass.

# the server is under, so it is reported rather than asserted; what is
# asserted is that a shed put is the only failure a caller can get.
print(f"{len(failures)} of {total} puts were shed, {total - len(failures)} committed")
assert set(failures) <= {SHED}, (

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 only checks the error class, so any build that answers 503 at the first conflict passes as long as one put commits. That includes the old budget of 50 with the new give-up. The storage tests do pin the budget (the deadline tests and the 256-writer test fail with 50), so it's not unguarded, but a loose floor here, say at least half committed, would give the wire test some teeth without the 0-shed flakiness the description mentions. Similarly, unconditional_put_that_spends_its_attempt_budget_gives_up_with_a_transient_error builds its expected message from TRANSIENT_RETRY_ATTEMPTS and only bounds time from above, so it can't tell which budget ran.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d9e3299. The wire test now also requires at least half of the 2,016 puts to commit, so a server that sheds most of them fails it. I kept the floor at half because the shed count follows the server's load (240 of 2,016 with a second hot-key load on the same server), and the storage tests pin the budget and the deadline. On this head the test passed with 0 of 2,016 puts shed, at a host load average of about 14.

The attempt-budget test now expects "PutItem: the write lost 1000 attempts to concurrent writers; retry the request" written out, and requires the give-up to take at least 5 s. The backoff sleeps of 1,000 attempts alone come to about 6.4 s, against about 0.3 s for 50 attempts. With TRANSIENT_RETRY_ATTEMPTS set to 50 the test fails on the message, which reads "lost 50 attempts", and the whole test finished in 0.56 s.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The floor of half did not tell the old budget from the fix. A server built from main's production files, which gives up after 50 attempts, passed this test twice. It shed 431 and 444 of the 2,016 puts, so 1,585 and 1,572 committed, at a host load average of 17 to 19. In d714ee0 the floor is nine in ten, 1,815 of 2,016, and that server fails it on both runs. This branch shed 1, 0, 1 and 0 of 2,016 in four runs at load averages of 13 to 22. The three runs recorded before this round shed 0, 0 and 2.

The attempt budget test now expects main's text, "PutItem: could not commit in 1000 attempts: ", written out, since a48ef73 moved the give-up onto main's retry_budget_exhausted. The 5 s lower bound on its time stays.

Comment thread tests/test_put_item_gsi_contention.py Outdated
kwargs["endpoint_url"] = endpoint_url
if endpoint_url.startswith("https://"):
kwargs["verify"] = False
return boto3.client(**kwargs)

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.

nit: this module-scoped client is shared by all 32 writer threads. A client per thread would avoid the occasional TLS error a shared botocore client gives under threads. Here that would fail the test rather than pass it, so it's a flake risk, not a false pass.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d9e3299. Each of the 32 writer threads now gets a client of its own from the raw_clients fixture, so no botocore client is shared between threads. The test passed on this head with 0 of 2,016 puts shed.

/// 503 whichever bound it reaches.
///
/// The deadline is read before an attempt starts, so a request answers within
/// the deadline plus one attempt. It governs the loops that serve a request:

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 TTL worker reaches one of these loops too: ttl_worker.rs:474 calls DataEngine::delete_item with a condition, so on a GSI or stream table it takes the transaction loop with the deadline. A contended expired item can now hold the sweep for up to 10 s (or 1,000 attempts) where it was 50 attempts before. That's probably fine, but the comment says only request loops take the deadline.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in efe8bc9. The comment now says that the TTL worker's conditional delete runs the delete loop and takes the deadline too, so an expired item that stays contended holds the sweep until the deadline or the 1,000 attempts end that loop, where 50 attempts ended it before. The worker then logs the failure and moves to the next item (ttl_worker.rs, the Err(e) arm after DataEngine::delete_item). The code is unchanged: the sweep runs outside any request clock scope, so each of its deletes measures its own deadline.

// this loop does. The error means another put's item is already in
// the collection, so the next attempt finds that item, replaces it
// and returns it as the old image; if a delete removed that item
// first, the next attempt inserts. Attempts share the 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.

nit: since 544103c the create race has its own CREATE_RACE_ATTEMPTS budget, so "Attempts share the transient retry budget" here and "uses the same retry budget and backoff as a write conflict" near line 563 are out of date.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in efe8bc9. The sessionless path's comment now says it makes at most CREATE_RACE_ATTEMPTS attempts, and the duplicate-key arm's comment says the transaction path counts each such attempt against CREATE_RACE_ATTEMPTS and gives up with the create race error once that budget is spent.

UpdateItem's native upsert, which came in with main's #473, now counts its create race against CREATE_RACE_ATTEMPTS too (88420dd).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

CREATE_RACE_ATTEMPTS is gone since a48ef73, so the two sentences above and the summary comment of 3 Nov name a constant the head no longer has. The create race now counts against TRANSIENT_RETRY_ATTEMPTS (50) on the sessionless path, on the transaction path and in UpdateItem's native upsert. The loops at those three places read that constant.

Comment thread docs/differences-from-dynamodb.md Outdated
| Provisioned throughput | Token bucket per table/partition | Token bucket per table/partition, matching DynamoDB's burst and refill behavior |
| On-demand capacity | Automatic scaling | Fixed initial burst capacity (4000 WCU / 12000 RCU), no auto-scaling |
| Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) |
| Sustained contention on one item (MongoDB backend) | Applies concurrent single-item writes on one key one after another and answers 200 to each. Measured to every call at 32 and 64 writers putting one key of a table with a GSI. A `PutItem` is answered 400 `TransactionConflictException` only while an in-flight `TransactWriteItems` holds the item (33 of 80 calls measured), and a `TransactWriteItems` that loses to other transactions on one key is answered 400 `TransactionCanceledException` with a `TransactionConflict` reason (107 of 160 calls measured) | A write on a table with a secondary index writes the item and its index entries in one transaction, so concurrent writes on one key abort each other and are retried. One request's retry loop stops after 10 seconds (`CONTENTION_DEADLINE`) or 1,000 attempts, whichever comes first, and the request is then shed instead of waiting out the queue of writers on that key: `PutItem` answers 503 `ServiceUnavailable` on either bound, which the SDK retry modes retry and which succeeds once the contention has passed. `DeleteItem` and `UpdateItem` answer 503 on the deadline and 400 `TransactionConflictException` when their 1,000 attempts run out first. `TransactWriteItems` answers `TransactionCanceledException` with a `TransactionConflict` reason per item on either bound, which is the answer the service gives. Measured with one GSI table and all writers on one key: at 64 writers all 1,280 puts committed and none were shed, with the longest call 9.7 s; at 256 writers 1,262 of 5,120 committed and 3,858 were shed, with the longest call 11.7 s. Without the deadline the same 256-writer shape left calls waiting 99.5 s, so a client sees a shed request where it used to see a request outlive its own read timeout. The other three backends keep writes on one key waiting rather than shedding them, and the deadline does not apply to them |

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.

"at 64 writers all 1,280 puts committed and none were shed" didn't hold on a moderately loaded host here: 106 and 149 of 1,280 were shed at load averages 6.8 and 10.5. The description already says the shed count depends on load. Might be worth saying the same in this user-facing row, or keeping only the 256-writer bound.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in efe8bc9. The row now says that how many requests are shed depends on the load on the server's host, keeps only the 256-writer measurement, and drops the 64-writer claim. It also says how a BatchWriteItem answers a request that reaches the deadline.

@navareamol navareamol added the v1 Needed for the 1.0 release label Nov 3, 2026
@navareamol navareamol added this to the 1.0 milestone Nov 3, 2026
Main added a live test module for the data engine in #473: its tests are
#[ignore]d, read EXTENDDB_TEST_MONGODB_URI through one uri() helper, fail
rather than skip when a run passes --ignored without it, and run in the
mongodb-rust job through devtools/run-mongodb-tests --rust-live. Its
scratch_engine helper builds the engine with MongoEngine::new and struct
update syntax, so a field added to MongoEngine needs no change there.

The two create-race storage tests move into that module as
data_engine_live_tests_put_race.rs. They used their own URI gate, which
printed SKIP without the variable, and a with_scratch_engine helper that
built MongoEngine from a struct literal. Against main that literal missed
the four fields #384 added, and the test build failed with E0063. Both
helpers are gone, and the tests check what they checked before.

devtools/run-mongodb-tests exported EXTENDDB_TEST_MONGODB_URI a second
time for these tests. Main exports it since #473, so the line is removed.
The comment on the duplicate-key arm of the transaction path said the arm
handles a put that lost the create race to another put. It does not. On
MongoDB 7.0, two snapshot transactions that upsert the same _id fail the
second upsert with WriteConflict (code 112, "WiredTigerIdIndex::_insert:
index: _id_") and the TransientTransactionError label, both while the
first transaction is open and after it committed past the second one's
snapshot. TxErr::from already retried that error before this branch.

The comment now says the arm is a defence: it is reached only when a
document in the transaction's snapshot holds the item's _id without
matching the key filter, which is the document the storage tests insert.
test_put_item_create_race.py shared one boto3 client across its 8 writer
threads. A botocore client used from several threads at once can fail a
request with a TLS error, and with retries off and the MongoDB xfail marker
gone, that error fails the test. Each writer now has its own client.
Merged with main, the storage-mongodb test build failed with E0063: the
MongoEngine literals in stream_records_live_tests.rs (from #543) and in
snapshot_engine.rs (from #395) do not set contention_deadline. Each test
that needed an engine listed every field, so each field added to
MongoEngine broke every such literal.

MongoEngine::new now builds the engine in from_parts, and a test-only
MongoEngine::for_test calls the same function with the driver's default
pool of 10 connections. The test literals in backup_live_tests.rs,
stream_records_live_tests.rs, snapshot_engine.rs and the restore backfill
test now call for_test and set only the fields they change with struct
update syntax. A new field is set in from_parts and nowhere else.

The four contention storage tests move from the data_engine test module
into data_engine_live_tests_contention.rs, next to the create-race tests
#431 moved. They build the engine through the live test module's
scratch_engine, are #[ignore]d like the other live tests and run under
devtools/run-mongodb-tests --rust-live, and set the deadline with struct
update syntax. The with_scratch_engine helpers and the second URI gate go
with them. What each test checks is unchanged.
…deadline

BatchWriteItem calls put_item or delete_item once per request, and each
call started its own CONTENTION_DEADLINE, so a batch of contended requests
could keep the client waiting 10 s per request. When a later request gave
up with the transient error, the handler failed the whole batch with HTTP
503 after the earlier requests had committed. The SDKs retry a 503, so the
retry sent those requests again, and a put or delete that another client
had overwritten in between was applied a second time.

The new extenddb_storage::request_clock module carries the start of an API
request in a task-local value. The BatchWriteItem handler runs inside
request_clock::scope, and the MongoDB contention loops measure the deadline
from that start (contention_clock_start), so the requests of one batch
share one deadline. The first attempt of every request still runs, so a
request that comes after the deadline is tried once. Outside a scope a
loop measures from the start of its own call, as before.

A request whose write fails with StorageError::Transient or
StorageError::TransactionConflict is returned in UnprocessedItems, and the
requests after it are still tried. On MongoDB the first is the contention
give-up and the second a spent attempt budget of DeleteItem; neither
applied the write. The batch answers the error only when none of its
requests was applied, so a client that retries it resends nothing that
took effect. Every other error still fails the batch. The capacity of a
request returned unprocessed is still counted.

Amazon DynamoDB answers a batch this way. Measured in us-east-1 with client
retries off while TransactWriteItems calls kept updating one item: 46 of 80
batches [put held, put free] and 53 of 80 batches [put free, put held]
answered 200 with the held item's request in UnprocessedItems and the free
item written, each reporting 2 capacity units, the units of both requests.
54 of 80 batches with only the held request answered 500
InternalServerError, and none answered 200 with its request unprocessed.

The handler change applies to every backend: a batch put or delete that
returns one of these two errors on another backend is now returned in
UnprocessedItems where it failed the batch before.

Tests:
- request_clock: a call sees the start of the scope it runs in, and an
  inner scope replaces it until it ends.
- the_contention_clock_starts_with_the_request_scope: the MongoDB loops
  read the scope's start, and their own start outside a scope.
- live_a_write_in_a_request_scope_measures_the_deadline_from_the_scope_start:
  in a scope that started 5 s ago with a 2 s deadline, a put of a held item
  gives up after one attempt and a put of a free item commits.
- tests/test_mongodb_batch_write_contention.py: the shape from the review,
  [delete A, put B] with B held past the deadline and another client
  putting A at 5 s, now answers 200 with only the put of B unprocessed and
  the other client's A kept; and in a batch whose first request is held
  for 6 s and whose second is held past the deadline, the second request
  gives up when the batch's deadline passes and is returned unprocessed.
…lict

On MongoDB, a BatchExecuteStatement statement whose write reached the
contention deadline or the attempt budget answered the code
ValidationError. The message was "Service is temporarily unavailable",
and the entry named the table. A client that does not retry a
ValidationError drops that write.

The service answers a statement whose item concurrent TransactWriteItems
calls hold with the code TransactionConflict and no TableName. Its
message is "Transaction is ongoing for the item", and the batch answers
200 (21 of 60 and 22 of 60 batches, measured 2026-11-25).

StatementError::from_error maps ServiceUnavailable and
TransactionConflictException to that entry and takes the message from
CancellationReason::transaction_conflict. from_item_error leaves the
TableName out of it. On Cassandra, a statement whose item a transaction
holds arrives as TransactionConflictException and gets the same entry.
The engine answers every transient storage fault with the same 503, a
lost connection among them, so each of these faults gets this entry too.

The BatchExecuteStatement test of test_mongodb_batch_write_contention.py
asserts the three entries by equality. A unit test checks both errors
through from_error and from_item_error. The differences row and the RFC
paragraph say what such a statement answers.
The floor of tests/test_put_item_gsi_contention.py is total * 9 // 10,
which is 1,814 of the 2,016 puts. It bounds how many puts the server
sheds, at most 202. It does not hold the attempt budget: with the budget
at 50 instead of 1,000, the test passed in 3 of 4 runs on 2026-11-25.

The comment above the floor and the assertion message say what the
floor bounds. The comment names the four live tests in
data_engine_live_tests_contention.rs that fail with a budget of 50. The
fifth one, the request scope test, passes with it.
BatchWriteItem and BatchExecuteStatement read std::time::Instant::now for
the start of their request clock scope. Both handlers are in the
WebAssembly build. On wasm32-unknown-unknown std has no clock, so the
call panics. The clippy step that main's wasm workflow gained in #1009
refuses the call in batch_write_item.rs, and this branch failed it after
the merge of main.

The handlers now call web_time::Instant::now, and request_clock holds a
web_time::Instant. Elsewhere web_time re-exports std::time. Native
builds run the same code.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

eaa83a5 fixes the crates/engine/src/partiql/common.rs:522 item. A statement that reaches the deadline or the attempt budget now answers {"Error": {"Code": "TransactionConflict", "Message": "Transaction is ongoing for the item"}}, without TableName, which is the entry your measurement shows. StatementError::from_error maps ServiceUnavailable and TransactionConflictException to it and takes the message from CancellationReason::transaction_conflict. from_item_error leaves TableName out of it.

test_the_statements_of_a_batch_execute_statement_share_one_contention_deadline now asserts the three entries by equality. At 3e85e2f it passes, and the batch answers in 10.04 s. It fails on a server built with the old mapping, with the Code changed to XControlCode, and with TableName added back.

Every fault the engine answers 503 gets this entry in a batch now, a lost storage connection included. The 503 doesn't say which fault it was. On Cassandra, a statement whose item a transaction holds reaches the engine as TransactionConflictException and gets the same entry, which a unit test covers.

LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
#487 gives TransactionConflictException and ServiceUnavailable the
BatchExecuteStatement entry measured for a contended statement: Code
TransactionConflict, the message "Transaction is ongoing for the item" and no
TableName. batch_code gave the first TransactionConflict with the error's own
message and TableName, and the second InternalServerError. Once both PRs
merge, #487's arm matches first and those two arms are dead.

batch_code drops the two arms, so they keep ValidationError until #487
merges. The test drops their rows and the ValidationException row, which
main's an_error_of_the_item_operation_names_the_batch_table covers.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
…ient

The backup mapping passes on the backend's message of TableNotFound,
TableAlreadyExists and TableNotActive, and the streams mapping that of
TableNotFound. The security model and the storage extension manual now list
them with the other variants.

ADR-0028 says which BatchExecuteStatement classes keep their listed code,
now that #487 maps the contended entry. It also says that the shard lookup
mapping checks the shard id length before it delegates, and names no
variant of its own.

@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 contended BatchExecuteStatement entry answers TransactionConflict with the service's message at 3e85e2f, and its test pins the Code; the entry has lost its TableName, which my earlier quote of the service's entry left out, and db082ab still ends with "Fixes #426".

  • With items held by a mongosh transaction in two shapes, twice each, the held statements answer {"Code": "TransactionConflict", "Message": "Transaction is ongoing for the item"} within 10.02 to 10.16 s and are not written. The test asserts all three entries by equality, and the reviewed mapping, another Code, another Message or TableName turned back on each fails it and the new unit test.
  • Uncontended BatchExecuteStatement matches the service on 9 shapes, twice each. 32 writers of 30 PutItem on one GSI key give 960 and 956 of 960 answered 200, with the index matching the stored item in both runs. The hot-key comment's 1,814 and 202 hold, and setting CONTENTION_RETRY_ATTEMPTS to 50 fails exactly the four tests it names. fmt, both clippy commands, the wasm clippy step and the 1.91.1 check are clean, 1474 tests pass with a MongoDB URI, and CI is green on 59 of 59.

I will approve once the entry carries TableName and db082ab no longer says "Fixes #426".

Comment thread crates/engine/src/partiql/common.rs Outdated
pub(super) fn from_item_error(err: &DynamoDbError) -> Self {
let mut error = Self::from_error(err);
error.include_table_name = true;
error.include_table_name = error.code != "TransactionConflict";

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 service names the table on this entry. In us-east-1, all 184 conflict entries over two UPDATE runs and three DELETE runs were {"Error":{"Code":"TransactionConflict","Message":"Transaction is ongoing for the item"},"TableName":"<table>"} in batches answered 200; at c85e24e the entry carried TableName too. My earlier review quoted the entry without it, which is where this line and the tests' expected shape come from. Keeping include_table_name true here, with the unit test at tests.rs:201 and the wire test expecting TableName, would match.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

f5c22b6 puts TableName back on this entry. from_item_error names the table on every entry again, as on main, and the TransactionConflict arm of from_error names it too. The unit test in tests.rs expects "TableName": "t" from both. With the common.rs of a24d811 back in place, it fails on the missing TableName.

test_the_statements_of_a_batch_execute_statement_share_one_contention_deadline expects the three entries with the table's name. It passes against a MongoDB server built from 86d02ba, where the batch answered in 10.04 s.

This entry needs an item that a transaction holds, so I could not measure it on a table that does not exist. The code comment and the tests cite your 184 entries. The API reference also gives TableName as the table of a failed statement.

@LJMart11 LJMart11 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed at 3e85e2f. The engine (892), storage (290) and storage-mongodb (290) suites pass under 1.91.1, and a 64-writer hot-key run on MongoDB was measured at this head and at main. The review covers how an upgrading deployment learns about the two behaviour changes.

Docs — outside the diff

  1. docs/manuals/07-upgrade-manual.md:385 — The two changes this PR lists under Breaking changes have no entry in Behavior Changes by Release, which says it covers changes an operator should review before upgrading a live deployment. On MongoDB with 64 writers x 20 PutItem on one GSI key, main answered 573 of 1,280 with 200 and its longest call took 2.2 s. This head answered 1,217 with 200, and its p99 was 10.06 s, so a client read timeout under about 11 s now fires where it did not. A v1.1.0: entry next to the #526 one, covering the MongoDB wait and the BatchExecuteStatement Code change on PostgreSQL and SQLite too, would close it.

The service names the statement's table on the TransactionConflict entry of
BatchExecuteStatement. In us-east-1, 184 of 184 conflict entries carried
TableName, in batches that answered 200 (measured by 2026-11-26).
eaa83a5 left TableName out of that entry. from_item_error now names the
table on every entry again, as on main. The TransactionConflict arm of
from_error names it too. The unit test and the BatchExecuteStatement wire
test expect TableName.
The upgrade manual gets an entry for the two behaviour changes of this
branch. A contended MongoDB write retries for up to 10 seconds. A
BatchExecuteStatement statement that loses to contention, or that meets a
fault the server answers with 503, answers TransactionConflict on every
backend. The entry goes after the v1.2.0 entry of main.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

@demohan The TableName of the entry is in the thread on common.rs: f5c22b6 puts it back.

db082ab is on the remote branch, so its message stays as it is. This PR merges as a squash. The squash message leaves out the last line of db082ab, the one that closes #426, so #426 stays open. The body says so under Why.

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

@LJMart11

  1. 86d02ba adds the entry "v1.2.0: on MongoDB, a contended write retries for up to 10 seconds, and a BatchExecuteStatement statement that loses answers TransactionConflict". The v1.1.0 release of 27 Nov 2026 does not include this change, so the entry goes after main's v1.2.0 entry. It covers the 1,000 attempts and the 10 second deadline, and the later answer with the client read timeout. It also names the CPU that the losing writes use on the MongoDB server. The entry covers the BatchExecuteStatement statement too. On MongoDB that is a statement that reaches either bound. On every backend, PostgreSQL and SQLite included, it is a statement that meets a fault the server answers with 503. The entry names the table, as in 1.1.0, so only the Code and the Message change.

Main is at c057660. This branch last had main at b3510a9. Since
then, #1411 and #1446 merged into main.

One file conflicted: crates/storage-mongodb/src/data_engine_live_tests.rs.
#1446 declares its delete_table test module where this branch declares
put_race and contention. The merge keeps all three, main's first. Git
merged docs/differences-from-dynamodb.md and the upgrade manual at
other lines.

@LJMart11 LJMart11 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checked at d341468 against the list from 3e85e2f.

The follow-up adds a v1.2.0 upgrade-manual entry for the MongoDB contention bounds and puts TableName back on the TransactionConflict entry of a contended BatchExecuteStatement statement; it also merges main at c057660. Confirmed: with the table name dropped from contended entries again, a_write_that_lost_to_contention_answers_transaction_conflict fails at partiql/common/tests.rs:203; 64 writers x 20 unconditional PutItem on one GSI key on MongoDB answered 1,225 with 200 and 55 with 503 ServiceUnavailable, none with 400 or 500. Engine (982) and storage-mongodb (201, 93 live tests ignored) lib tests passed under 1.94.0.

Previous items: 1 fixed.

Main is at 44a7b79, five commits past c057660: #1531, #1466, #1087,
#768 and #1296. In docs/manuals/07-upgrade-manual.md, #1531 adds a
v1.2.0 entry at the top of "Behavior Changes by Release", and git
merged it with no conflict. #1087 adds its v1.2.0 entry after the other
v1.2.0 entries of main, where this branch has its entry. That is the one
conflict. The merge keeps both entries without change: the entry of
#1087 first, then the entry of this branch, before the v1.1.0 entries.

Git merged two other files with no conflict:

- crates/storage-mongodb/src/data_engine.rs: #1087 computes the
  parallel Scan segment with scan_segment in scan_key_in_segment and in
  scan_impl. This branch changes the write functions and their retries
  at other lines.
- crates/storage/src/lib.rs: #1087 rewrites the doc comment of
  scan_key_in_segment, and this branch declares the request_clock
  module.
@LJMart11

LJMart11 commented Dec 4, 2026

Copy link
Copy Markdown

Checked at d341468 against the list from 3e85e2f. The head moved again to fe4d965; this reviewer stops after two rounds and leaves the rest to a person.

Fixed:

  • item 1

Disputed: none.

Needs-human: none.

Main is at 1e2ebdd, six commits past 44a7b79: #1485, #1228,
#1325, #1443, #1269 and the squash commit of #1093.

One file conflicted:
crates/storage-mongodb/src/data_engine_live_tests.rs. #1093 declares
the update_window module after delete_table, where this branch
declares put_race and contention. The merge keeps all three
declarations: update_window first, then the two of this branch.

Git merged five other files with no conflict:

- crates/storage-mongodb/src/snapshot_engine.rs: #1093 checks that a
  table serves with TableStatus::serves, and its tests set a table to
  CREATING instead of UPDATING. This branch builds a test engine with
  MongoEngine::for_test, at other lines.
- crates/storage/src/error.rs: #1093 adds a sentence to the doc comment
  of IndexesInUse. This branch changes the doc comment of Transient.
- crates/storage/src/lib.rs: #1093 declares update_window_conformance,
  and this branch declares request_clock.
- docs/differences-from-dynamodb.md: #1443 changes the default delay
  to 0.25 s, and #1093 changes the row on stream disable and the row of
  the delay setting. This branch changes two rows near the top and adds
  the row on sustained contention.
- docs/manuals/07-upgrade-manual.md: #1093 adds its v1.2.0 entry at the
  top of "Behavior Changes by Release". The entry of this branch stays
  after the v1.2.0 entries of main.

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

v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB: unconditional PutItem on a table with a GSI returns TransactionConflictException under contention

5 participants