Skip to content

fix(mongodb): retry a write conflict on the stream sequence counter - #475

Merged
LeeroyHannigan merged 24 commits into
mainfrom
fix/mongodb-stream-counter-conflict
Nov 11, 2026
Merged

LeeroyHannigan merged 24 commits into
mainfrom
fix/mongodb-stream-counter-conflict

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #437. A write to a stream-enabled table that spends its 50 attempts under
sustained contention answers 503 here. The service answers 200 to that write.
#426 tracks the work to retry a lost race until it commits.

On a table with a stream enabled, every write draws a sequence number from a
per-shard counter inside the write's transaction. Two writes on the same shard
conflict on that counter. MongoDB aborts one of them with WriteConflict (code
112) and the TransientTransactionError label. next_sequence_number_in_session
mapped that error to StorageError::Internal, so the retry loop never saw the
conflict and the request answered HTTP 500. The same mapping sat on the index
entry writes, the shard lookup and the stream record insert.

write_conflict::transaction_error now classifies a driver error raised inside
a write transaction. A transient write conflict becomes
StorageError::Transient. On that error the transaction bodies run again, with
the same backoff and budget as a conflict on the data collection. Any other
error stays Internal. The UnknownTransactionCommitResult label is not
transient, and the commit path alone still classifies it. That path retries
commitTransaction in place and never re-runs the body.

A single-item write that spends its whole retry budget returns
StorageError::Transient, answered as HTTP 503 ServiceUnavailable, from
PutItem, DeleteItem and UpdateItem. TransactWriteItems keeps
TransactionCanceledException with a per-operation TransactionConflict
reason.

BatchWriteItem applied its requests one after another and answered any write
error for the whole batch. So a batch whose first put had committed answered
500, and a later PutItem returned that put's item as its old image.
BatchWriteItem now checks the whole batch before it writes anything. The table
lookups, the duplicate-key check and the checks of every request run first. A
request fault rejects the batch with a 400 and nothing applied, wherever the
faulty request sits. The request faults are a missing table, a key that does
not match the schema, duplicate keys and an item over the size limit. A
secondary index key of the wrong type or an empty one is a request fault too.

On main, the handler wrote the requests ahead of a faulty request before it
answered 400. This branch writes none of them. check_batch_counts checks the
limits on the number of tables and requests before write_batch runs, and the
HTTP layer checks the request size limit. The storage layer checks a put's
index keys again at write time, against the indexes it reads then. A secondary
index that an UpdateTable added after the lookup is the one case of a request
fault found after a request applied.

The handler then tries every request, in the order listed within a table and
in the order the map yields the tables. A request the backend cannot apply now
does not stop the others. The handler returns it in UnprocessedItems, and the
batch answers 200 when at least one request applied. Such a request met a
transient error, for example a spent retry budget, or a transaction conflict. A
connection error ends the attempt. The handler returns the request that met it
and every request after it in UnprocessedItems. A batch of which no request
applied answers 503 ServiceUnavailable.

An internal error, which a replay does not clear, still fails the batch with a
500 after earlier requests were applied. So does a put or a delete on a
Cassandra table without TTL that meets an item a TransactWriteItems holds. That
write returns TransactionCanceled, and the batch answers 400
TransactionCanceledException. A Cassandra write that spends its retries on a
lost race, on any table, or on a held item of a TTL table returns
TransactionConflict. The batch leaves that request in UnprocessedItems. The
BatchWriteItem row of docs/differences-from-dynamodb.md states both Cassandra
paths.

Consumed capacity and item collection metrics count the applied requests only.
A table of which no request applied gets no ConsumedCapacity entry. What the
service reports for such a table in a partial batch is not measured, and the
docs row says so. A request is applied at most once. The storage layer retries
before commit and never re-runs a body after a commit of unknown outcome. The
handler assumes that a deferred request was not applied, so a backend must
report a commit of unknown outcome as Internal. MongoDB does so for an
UnknownTransactionCommitResult that outlasts the commit retries. On SQLite,
put_item and delete_item map an error of the COMMIT to Internal without
map_sqlx_err. So an I/O error at COMMIT, which can leave the write applied,
fails the batch with 500 and is not deferred. The comment of is_deferrable
states this.

Each failed request spends its own retry budget before the batch answers. So a
batch of 25 contended requests can spend 25 budgets in one call. A deferred
request logs at debug level. The batch logs one warning with the counts of
applied requests and of requests not applied, and the last error.

Merges with main

ec85c6a merges main at b5858c7, 73 commits past the merge base 38992eb.
Seven files changed on both sides and the textual merge is clean. This branch
gives TxErr::Transient and CommitOutcome::RerunBody a String with the
driver's error text. Main's new claim_restore_tx
(crates/storage-mongodb/src/backup_catalog.rs) and insert_restore_batch
(crates/storage-mongodb/src/restore_engine.rs) matched both variants without a
payload, so the merged tree did not compile. The merge commit adds the payload
in those four places and changes nothing else.

08a9589 merges main at cbc3680, three commits later: #515 (disabling a
stream closes its shards), #355 (auth) and #896 (npm). The textual merge is
clean and the commit has no change beyond git's merge. In
assign_shard_in_session, #515's open-shard filter and its None return stay.
This branch's transaction_error on the table read, the shard find and the
cursor stays too. The stream record path takes the let-else of #515, so a write
that finds no open shard records nothing. #515 adds no code that runs inside a
write transaction, so the driver errors of its new code stay Internal. A
stream close updates stream_shards documents, which a write transaction only
reads, so a close cannot abort a write with WriteConflict.

What the service does

Every measurement below is against DynamoDB in us-east-1. The measurements of
2026-10-23 and 2026-10-27 ran with client retries off
(retries={"max_attempts": 0}) on existing bb- tables with a string hash
key, a GSI and a stream. The measurements of 2026-11-10 ran on tables keyed on
pk (S) with a global secondary index by-g on g (S). Each batch went out twice
and got the same answer both times.

2026-10-23, one key, all writers on the same item:

shape calls outcome
16 threads x 30 PutItem on one key 480 480 answered 200, 0.6 s
64 threads x 30 PutItem on one key 1,920 1,920 answered 200, 2.5 s
16 writers x 30 rounds, 8 BatchWriteItem (hot key plus a side key) racing 8 PutItem with ALL_OLD on the hot key 240 batch and 240 put all 200, no UnprocessedItems, 0.6 s
16 threads x 20 UpdateItem ADD #c :one SET #g = :g with ALL_NEW on one key 320 320 answered 200, 0.5 s
16 threads x 20 UpdateItem SET l = list_append(l, :m) on one key 320 320 answered 200, 0.5 s
16 threads x 30 PutItem each on its own key of the GSI table 480 480 answered 200, 0.6 s
64 threads x 30 PutItem each on its own key of the GSI table 1,920 1,920 answered 200, 2.3 s

The UpdateItem rows also hold for what the accepted calls did. The stored
counter was 320, equal to the number of calls that answered 200. The 320
ALL_NEW counter values were 1 to 320, and each went to exactly one caller. The
stored list held each of the 320 markers once, none missing and none
duplicated.

The service sheds none of this load at any writer count measured. It answers a
single-item write with TransactionConflictException only while a
TransactWriteItems holds the item. This backend cannot distinguish that case
from a race against other single-item writes.

BatchWriteItem racing TransactWriteItems, 2026-10-27. Four threads looped
TransactWriteItems over two items while four threads sent BatchWriteItem calls
on the same items. Two samples of 640 batch calls each. About half of the
transactions cancelled each other (107 of 222 and 125 of 240), so the items
were held often.

batch answer calls, sample 1 and 2
two requests, one on a held item and one on an item no transaction touches, held item first 200, the held item's request in UnprocessedItems, the other request applied 85 and 101
the same, held item second 200, the held item's request in UnprocessedItems, the other request applied 75 and 80
two requests on two held items 200 with the one request that lost in UnprocessedItems 10 and 21
two requests on two held items 500 InternalServerError 80 and 68
one request on a held item 500 InternalServerError 78 and 82 of 160

The item no transaction touched was present after all 640 calls of both
samples. No call answered TransactionConflictException (0 of 1,280) and none
answered 200 with every request unprocessed. So the batch handler keeps
TransactionConflict deferrable. For a batch of which no request applied, the
service answers an error and this server answers 503.

BatchWriteItem faults, 2026-10-27, two samples of each. A valid put followed by
a put with a key of the wrong type answered 400 ValidationException. A valid
put followed by a put to a missing table answered 400
ResourceNotFoundException. A valid put followed by duplicate keys in a second
table answered 400 ValidationException. None of these batches applied a
request. A delete followed by a put with a key of the wrong type answered 400
ValidationException and the item was still present.

BatchWriteItem faults and their messages, 2026-11-10 at 21:24 UTC. A valid put
came first in each batch, and it was not applied in any case:

  • A put with a number partition key, in the same table or in a second table:
    400 ValidationException. The message was "The provided key element does not
    match the schema". A valid delete of a stored item ahead of that put gave
    the same answer, and the item was still present. A delete whose key has an
    extra attribute gave the same code and message.
  • A put to a table that does not exist: 400 ResourceNotFoundException
    "Requested resource not found".
  • Two puts of one key in a second table: 400 ValidationException "Provided
    list of item keys contains duplicates".
  • A put of 401 KB: 400 ValidationException "Item size has exceeded the maximum
    allowed size".
  • A put whose GSI key g is a number: 400 ValidationException. The message was
    "One or more parameter values were invalid: Type mismatch for Index Key g
    Expected: S Actual: N IndexName: by-g".
  • A put whose GSI key g is an empty string: 400 ValidationException "One or
    more parameter values are not valid. A value specified for a secondary index
    key is not supported. The AttributeValue for a key attribute cannot contain
    an empty string value. IndexName: by-g, IndexKey: g".

Two faults in one table, 2026-11-10 at 22:57 UTC. Each batch held a valid put,
then two faulty puts in one table. One faulty put had pk as a number. The other
had g as a number or as an empty string. Each pair went in both orders. The
service answered 400 ValidationException with the message of the first faulty
put in list order, and the valid put was not applied. With g first, the message
was the index key message above. With pk first, it was "The provided key
element does not match the schema".

What each status means here

  • 200: the write committed.
  • 200 with UnprocessedItems (BatchWriteItem): the listed requests were not
    applied and the client replays them. The API reference puts a request that
    failed because the throughput was exceeded or an internal processing failure
    occurred into UnprocessedItems. It lists the request faults that reject the
    whole batch. They are a missing table, a key that does not match the schema,
    duplicate keys and more than 25 requests. An item over 400 KB, a request
    over 16 MB and a key over the key length limits are on the list too. None of
    these is contention. The one error the page names for a batch that processed
    nothing is a throttle (ProvisionedThroughputExceededException or
    ThrottlingException), which this server does not account for. A batch of
    which no request could be applied answers 503 ServiceUnavailable, which the
    SDKs retry with backoff. So a client's UnprocessedItems loop does not spin
    on a batch that makes no progress. The service answers 500
    InternalServerError for that case (measured 2026-10-27, above).
  • 503 ServiceUnavailable: a single-item write lost every attempt of its retry
    budget, or a batch applied none of its requests. The error-handling
    documentation lists ServiceUnavailable (HTTP 503) as "OK to retry? Yes", and
    the SDK retry modes retry it. The SDK hands a 400
    TransactionConflictException to the application.
  • 500: a storage fault. An internal error is not deferred into
    UnprocessedItems. A replay of the request does not clear it, and a client's
    UnprocessedItems loop would spin on it.

The known limit this PR does not change

MongoDB aborts the loser of a same-document conflict at once instead of
queueing it, so retries settle a hot key. The numbers in this section come from
this branch before the merges with main, at 7ea211b or an earlier head. The
setup was MongoDB 7.0 as a single-node replica set with a stream and GSI table,
client retries off. The host was shared with other sessions (load average 17
to 20). With 64 writers x 20 PutItem on one key, 337 of 1,280 calls committed,
a commit rate of 6.5 per second. At 256 writers, 298 of 5,120 committed, a rate
of 2.4 per second. The service answered 1,920 of 1,920 calls from 64 writers on
one key in 2.5 s, about 770 per second. The difference comes from aborting the
loser rather than queueing it, which this PR does not change. This PR changes
the answer a losing write gets to a 503 the SDKs retry, in place of a 500 or a
400. #426 tracks the work to retry a lost race until it commits.

Tests

tests/test_stream_write_contention.py. Its module docstring says that these
tests fail on a server that answers 500 InternalServerError for the counter
conflict.

  • test_racing_puts_and_deletes_on_a_stream_table_all_succeed: 8 writers x 60
    operations over 4 keys of a stream table. The stream must hold one record per
    write that changed the item. A writer sends a PutItem or DeleteItem that
    answered 503 ServiceUnavailable again, up to 20 times, with the backoff and
    jitter of tests/test_concurrency.py. A 500, any other error, and a 503
    after the last resend fail the test. Both assertion messages report how many
    of the 480 writes answered 200 only after a resend. That count has no bound,
    because it depends on the load on the host.
  • test_batch_writes_racing_puts_on_a_stream_table_never_fail: 16 writers, 8
    sending BatchWriteItem (the raced key plus a per-writer side key) and 8
    sending PutItem on the raced key, 30 rounds. Even rounds put the raced
    request first and odd rounds put the side request first, so the test covers
    both positions. A batch call answers 200 when at least one request applied
    and 503 when none did. A batch that did not apply every request lists the
    rest in UnprocessedItems. A replay of those writes each side item once, and
    the stream record count equals the number of applied writes. A PutItem may
    answer 503 once it has spent its budget and nothing else.
  • test_update_item_contention_is_never_a_transaction_conflict: 16 writers x
    20 ADD #c :one SET #g = :g and 16 x 20 SET l = list_append(l, :m) on one
    key of a table with a GSI and a stream, the shape measured above. No call may
    answer 400 TransactionConflictException. The stored counter must equal the
    number of calls that answered 200. Each ALL_NEW counter value must go to
    exactly one caller, and every marker a caller was told committed must be
    stored once.
  • test_transactions_on_a_stream_table_all_commit: six writers send
    TransactWriteItems (a put, a delete and an update on disjoint keys) to a
    stream table. Every call must commit. A cancellation by TransactionConflict
    after 50 attempts is resent. Each counter and the stream record count show
    every transaction applied once.

Engine unit test only_errors_a_replay_may_clear_are_deferred pins the
deferrable set. The handler defers a transaction conflict, a transient error
and a connection error. It does not defer an internal error, a validation
error, a missing table, a failed condition or an exceeded limit.

Further tests on this branch:

  • crates/engine/src/batch_write_item/write_batch_tests.rs, 15 tests. A
    storage double whose first put fails with Transient, followed by a request
    whose key does not match the schema, answers 400 with nothing written. The
    same fault in a later table, a missing later table and duplicate keys in a
    later table do the same. The handler writes a valid batch with each table's
    own key information. A put that returns TransactionConflict after another
    request applied leaves exactly that request in UnprocessedItems. One test
    per pre-write check puts the fault in the second request and asserts 400 and
    no write. The checks are item size, nesting depth, key size, vector
    dimension and key-only delete shape. Four tests cover the index keys. A
    global secondary index key of the wrong type and an empty one reject the
    batch before any write, with the measured messages. A local secondary index
    key of the wrong type rejects it with 400 and no write, with no message
    assertion. The handler writes a batch with valid secondary index keys.
    Moving any one of the pre-write checks back inside the write loop fails its
    test. The attribute-name size check runs before write_batch since main's
    fix(limits): attribute-name size limit on every write path #433, ahead of the table lookups, and main's wire tests cover it.
  • crates/engine/src/batch_write_item/write_batch_deferral_tests.rs, 6 tests.
    A failed first request does not stop the rest. UnprocessedItems holds exactly
    the failed requests per table and the consumed capacity counts the applied
    ones. A double that fails every put answers 503 after trying every request,
    for Transient and for TransactionConflict. A connection error leaves the rest
    unattempted, and a connection error with nothing applied answers 503 after
    one attempt. An internal error after a failed request still fails the batch
    with 500.
  • tests/test_batch_write_validation_order.py, 13 cases, which need no
    contention. Every case asserts Error.Code, Error.Message equal to the
    text the service answered on 2026-11-10, and that the valid request was not
    applied. Seven cases pair a valid put or delete with one of the original
    faults. Those faults are a key of the wrong type, in the same table or a
    second one, and a missing table. Duplicate keys in a second table, a 401 KB
    item and a delete with an extra key attribute complete the seven. Two cases
    run on a table with a global secondary index by-g on g (S). They send a
    valid put ahead of a put whose g is a number or an empty string. Four cases
    of test_two_faulty_puts_report_the_first_in_list_order send a valid put,
    then pk as a number and g as a number or an empty string, in both orders.
  • crates/storage-mongodb: the exhausted-budget error carries the operation,
    the attempt count and the last error that ended an attempt. The conversions
    into the retry loops keep the driver's text.
  • The batch replay loop in the stream contention test stops after 200 passes
    with a failing assertion. ServiceUnavailable is a retryable code in
    tests/test_concurrency.py. On Cassandra the batch and UpdateItem contention
    tests accept 400 TransactionConflictException for a lost single-item race.
    Cassandra gives that answer once its retries are spent. The transaction test
    expects a stream record for each setup put and each transacted write on
    every backend. fix(cassandra): record stream records for transacted writes #576 on main makes Cassandra record transacted writes.

What fails without the fix

The runs in this section that name no commit ran on this branch before the
merges with main, at 7ea211b or an earlier head.

On main (9d13202), measured on MongoDB 7.0, the two tests then in
test_stream_write_contention.py fail. 88 of 480 churn writes and 9 batch calls
answer 500 InternalServerError.

The wider comparison measured while this branch was written, same backend,
client retries off:

shape main (9d13202) 879a419
PutItem and DeleteItem churn over 4 keys, 8 threads, 2,016 calls 286 PutItem and 136 DeleteItem answered 500 no errors
the same churn at 32 threads, 2,016 calls 500s on the same shape 94 of 1,024 PutItem answered 503, no DeleteItem error
BatchWriteItem racing PutItem on one key, 16 writers, 480 calls 63 BatchWriteItem and 1 PutItem answered 500, and 25 PutItem ALL_OLD images were items of a batch that had answered an error 8 BatchWriteItem and 7 PutItem answered 503, no such image

The 503s in that table are writes that spent the 50-attempt budget. #426
tracks the work to retry a lost race until it commits. The server log on the
branch carries no WriteConflict line and no internal error for these runs.

On 879a419, the first commit of this branch, the test file of this branch at
that time ran 8 times. The UpdateItem test failed 7 runs, with 1 to 25 of 640
calls answering 400 TransactionConflictException. The batch order test failed
2 runs, both with BatchWriteItem 503 ServiceUnavailable on a round that put the
raced request first. With the fix in the tree, 8 of 8 runs passed all three
tests.

Controls on the committed tree with the change reverted or the server edited to
force the case:

  • The old order restored, each request checked before its own write: 4 of the
    7 engine batch tests at that head fail. All 5
    original tests of tests/test_batch_write_validation_order.py fail too. The
    first head's binary fails the same 5 wire tests. With item size and the
    key-only delete shape moved back inside the write loop, the two tests of
    those checks fail. The two wire parameters of those checks fail at the
    not-applied assertion.
  • validate_request without its validate_index_keys call, at 035ac2d: 3
    of the 23 engine batch tests fail (the two global secondary index tests and
    the local one). The test double runs no storage-side check, so the batch
    answered 200 with both puts written. On a dev-mode SQLite server built from
    that tree, the two GSI cases of
    test_valid_put_before_a_faulty_gsi_key_is_not_applied fail at the
    not-applied assertion and the other 7 cases pass. The storage layer still
    refused the faulty put with the measured code and message, after the valid
    put ahead of it was applied.
  • The stop at the first failed request restored, and no zero-progress answer:
    5 of the 14 engine batch tests at that head fail.
  • A helper conflict inside TransactWriteItems answered 503 instead of
    re-running the transaction: the transaction test fails with 42 of 60
    transactions answering 503.
  • A server that never applies a batch: the stream contention test fails after
    four seconds at the 200-pass limit. The test without the limit does not
    finish within 60 seconds.
  • A server that answers the exhausted-budget 503 to every fifth UpdateItem:
    the three single-row classes of tests/test_concurrency.py fail 3 of 3 runs.
    That is without ServiceUnavailable in the retryable codes. They pass 3 of 3
    runs with it.

The batch order control is probabilistic. It fires when the first request of a
batch spends its 50-attempt budget.

Gates

At 08a9589, the merge of main at cbc3680 and the last commit on this branch
that changes a Rust file:

  • cargo +1.97.0 fmt --all -- --check: exit 0.
  • The two CI clippy commands, cargo +1.97.0 clippy --locked --all-targets -- -D warnings, once with
    extenddb-storage-cassandra/test-hooks,extenddb-storage-mongodb/test-hooks
    enabled and once with extenddb-engine/backup-test-hooks enabled: exit 0, no
    warning.
  • cargo +1.97.0 test --locked -p extenddb-engine --lib batch_write_item: 23
    passed, 0 failed.
  • cargo +1.97.0 test --locked -p extenddb-storage-mongodb --lib: 179 passed,
    0 failed, 69 ignored.
  • Wire tests against a dev-mode SQLite server,
    tests/test_batch_write_validation_order.py and
    tests/test_stream_write_contention.py: 13 passed, 0 failed (9 and 4).
  • Wire tests against a MongoDB-backed server on a mongo:7 single-node replica
    set, tests/test_stream_write_contention.py: 4 passed, 0 failed. The server
    log has no internal error line. Six PutItem and 23 UpdateItem answers were
    503 after 50 attempts that each lost to a WriteConflict (code 112). No
    DeleteItem or TransactWriteItems answer was 503, and no BatchWriteItem
    logged a request it did not apply.
  • storage-mongodb live tests against the same replica set (--ignored --test-threads=1, filters live_stream, records_live and
    data_engine::live_tests::): 28 passed, 0 failed.

The two commits after 08a9589 change only tests/*.py. At b349959, the same
two wire files against a dev-mode SQLite server: 17 passed, 0 failed (13 and
4). SQLite runs one writer at a time and answered no 503, so the churn test's
resend path and its count were not exercised on it.

Not run since the merges with main: cargo test --workspace, wire runs on
PostgreSQL and Cassandra, and the full pytest run on MongoDB. CI runs them.
Cargo.lock is unchanged against main at cbc3680, so the license notice checks
do not apply.

Before the merges with main, at 7ea211b or an earlier head:

  • cargo test --workspace and cargo +1.88.0 test --workspace: 1,835 passed,
    0 failed, 26 ignored on each. The Cassandra integration targets ran as unit
    tests only. Another process on the build host held a Cassandra on
    127.0.0.1:9042 that those targets would otherwise use.
  • MongoDB wire tests (devtools/run-tests --backend mongodb --pytest) for
    test_stream_write_contention, test_batch_operations, test_item_operations
    and test_put_item_create_race: 170 passed, 3 xfailed, 0 failed. The three
    xfails were the lost-create-race 500s of [Bug] MongoDB: concurrent same-key PutItem surfaces E11000 as InternalServerError #356, which fix(mongodb): retry an unconditional PutItem that loses the create race #431 fixes and which
    that head's base did not carry.
  • SQLite wire tests for test_batch_operations and test_item_operations, the
    shared engine paths that batch_write_item.rs serves on every backend: 161
    passed, 0 failed.

CI at b349959: 57 of 57 checks passed.

On a table with a stream enabled, every write draws a sequence number from
a per-shard counter inside the write's transaction. Two writes on the same
shard conflict on that counter, MongoDB aborts one with WriteConflict (code
112) and the TransientTransactionError label, and
next_sequence_number_in_session mapped the error to StorageError::Internal.
The transaction retry loop never saw the conflict and the request answered
HTTP 500. The same mapping sat on the index entry writes, the shard lookup
and the stream record insert.

A new write_conflict::transaction_error classifies a driver error raised
inside a write transaction: a transient write conflict becomes
StorageError::Transient, anything else stays Internal. The in-session
helpers use it, and TxErr and TransactOpError turn a Transient error from
a helper into a re-run of the transaction, with the same backoff and budget
as a conflict on the data collection. The UnknownTransactionCommitResult
label is not transient and is still classified by the commit path alone.

A PutItem or DeleteItem that runs out of its retry budget now returns
StorageError::Transient, which the engine answers as HTTP 503
ServiceUnavailable, instead of a 400 TransactionConflictException. Amazon
DynamoDB answers a single-item write with TransactionConflictException
only while a TransactWriteItems holds the item, which this backend cannot
tell apart from a race against other single-item writes. 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. UpdateItem keeps its own exhaustion
error.

BatchWriteItem applied its requests one after another and answered any
write error for the whole batch, so a batch whose first put had committed
answered 500 and a later PutItem returned that put's item as its old
image. The handler now keeps the error only when no request was applied.
After a committed request, a write the backend could not apply now (a
spent retry budget, a transient, connection or internal failure) and every
request after it are reported in UnprocessedItems with a 200, which is
what the service documents for a batch with individual failures. Consumed
capacity and item collection metrics count the applied requests only. A
request is applied at most once: the storage layer retries before commit
and never re-runs a body after a commit of unknown outcome.

Measured on 2026-10-23 against the service in us-east-1 with client
retries off: PutItem and DeleteItem churn over 4 keys from 8 threads, 480
calls, all 200; BatchWriteItem racing PutItem on one key from 16 writers,
240 calls, all 200 and no UnprocessedItems. On MongoDB 7.0 (single-node
replica set, client never retries): the same churn with 2,016 calls
answered 286 PutItem and 136 DeleteItem with 500 on main and 0 on this
branch; 16 writers racing BatchWriteItem against PutItem on one key, 480
calls: main answered 63 BatchWriteItem and 1 PutItem with 500 and 25
PutItem ALL_OLD images were items of a batch that had failed; this branch
answered 8 BatchWriteItem and 7 PutItem with 503 and no such image. With
32 threads on the churn shape 94 of 1,024 PutItem calls still run out of
the 50-attempt budget and answer 503; the budget is the subject of #426.
tests/test_stream_write_contention.py fails on main (88 of 480 churn
writes and 10 batch calls answered 500) and passes on this branch.

Fixes #437
…retry budget

UpdateItem returned TransactionConflict when its retry budget ran out,
while PutItem and DeleteItem returned the transient error the engine
answers as HTTP 503 ServiceUnavailable. One backend gave two answers to
the same contention on the same item, and the 400 is the answer the
application sees rather than the one the SDKs retry. UpdateItem now
returns write_conflict::retry_budget_exhausted as well.
TransactWriteItems keeps TransactionCanceledException with a per-operation
TransactionConflict reason, which is what the service answers for a
transaction.

Measured on 2026-10-23 against the service in us-east-1, client retries
off, on a table with a GSI and a stream: 16 writers x 20 UpdateItem
ADD c :1 on one key answered 320 of 320 with 200, the stored counter
equalled the number of calls that answered 200, and the 320 ALL_NEW
counter values were 1 to 320, each returned to one caller; 16 writers x
20 SET l = list_append(l, :m) answered 320 of 320 with 200 and the stored
list held each marker once. The service answers a single-item write with
TransactionConflictException only while a TransactWriteItems holds the
item, which none of these callers sent.

BatchWriteItem deferred a failed write into UnprocessedItems only when an
earlier request in the same batch had been applied, so the same
contention answered 200 with UnprocessedItems or 503 for the whole batch
depending on where the contended request sat in the batch. A deferrable
failure now goes to UnprocessedItems wherever it sat, and a batch that
could apply none of its requests answers 200 with every request in
UnprocessedItems. The BatchWriteItem documentation puts a request that
failed because the throughput was exceeded or an internal processing
failure occurred into UnprocessedItems, lists the request faults that
reject the whole batch (a missing table, a key that does not match the
schema, duplicate keys, more than 25 requests, an item over 400 KB, a
request over 16 MB, an oversized key), and names an error for a batch
that processed nothing only for throttling, which this server does not
account for.

A storage fault is no longer deferred: is_deferrable drops
StorageError::Internal, so an internal error keeps answering HTTP 500
instead of being handed to a client's UnprocessedItems loop, which a
replay cannot clear.

tests/test_stream_write_contention.py gains the UpdateItem shape above on
a table with a GSI and a stream: no call answers a 400
TransactionConflictException, the counter matches the calls that answered
200, and every marker a caller was told committed is stored once. Its
BatchWriteItem test now sends the contended request first as well as
last, which is the order that answered 503 for the whole batch.

The RFC's write-conflict paragraph said is_transient_write_conflict
matches 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.

Issue #437
The BatchWriteItem contention test sent the raced put after a side put in
every round, the order in which an earlier request has already committed
when the raced one fails. It now alternates: the raced put leads on even
rounds and the side put on odd rounds, and a failure records which arm
raised it and which order the round used. The writer count goes to 16, 8
batch writers racing 8 putters, the shape measured against the service
(240 BatchWriteItem and 240 PutItem on one key, all 200).

The batch arm must not fail in either order. A single-item PutItem that
spends its whole retry budget answers 503 ServiceUnavailable, which the
SDKs retry, so the put arm allows that one answer and no other.

With the sources of 879a419 in the tree and this test file, over 8 runs
against MongoDB 7.0: the batch test failed 2 runs, both with
BatchWriteItem 503 ServiceUnavailable on a raced-first round, and the
UpdateItem test failed 7 runs, with 1 to 25 of 640 calls answering 400
TransactionConflictException. With the fixes in the tree, 8 of 8 runs
passed all three tests.

Issue #437
The handler looked up each table, checked its duplicate keys and validated
each request immediately before writing that request. A write that could not
be applied now (a spent retry budget or a connection fault) ended the loop
and returned every later request in UnprocessedItems with a 200, so a later
request that fails validation was never checked and came back as unprocessed.
Without any contention the same order already applied the requests ahead of a
faulty one and then answered 400, so a rejected batch could leave part of
itself applied.

Every table lookup, the duplicate-key check and the validation of every
request now run before the first write, in the order the faults used to be
reached. A fault rejects the whole batch with nothing applied, wherever the
faulty request sits, which is what the BatchWriteItem reference documents for
these faults. This also closes the partial application that preceded a later
request's validation error. The writes run in a separate function that takes
a DataEngine, so the handler tests drive it with a storage double.

Tests: write_batch_tests has a double whose first put fails with Transient
and a second request whose key does not match the schema (400, nothing
written), the same fault in a later table, a missing later table, duplicate
keys in a later table, and a valid batch written with each table's own key
info. tests/test_batch_write_validation_order.py sends a valid put or delete
ahead of an invalid put, a put to a missing table, or a table with duplicate
keys, and requires a 400 with the valid request not applied. It needs no
contention.
The batch handler defers TransactionConflict, which the Cassandra backend
raises from a put when a transaction or an expiration claim holds the item.
No measurement of the service backed that, so it was open whether the batch
should defer the request or fail with TransactionConflictException.

Measured on the service (us-east-1, 2026-10-27, client retries off): four
writers ran TransactWriteItems on the same two items in a loop while four
batch writers sent BatchWriteItem calls on them, two samples of 640 batch
calls. About half of the transactions were cancelled by each other (107 of
222 and 125 of 240), so the items were held often.

- A batch of two requests, one on a held item and one on an item no
  transaction touches, answered 200 with the held item's request in
  UnprocessedItems and the other request applied, in either order. The held
  item came first in 85 and 101 of the calls and second in 75 and 80 of them
  (first and second sample). The other item was present after all 640 calls.
- A batch of two requests on two held items answered 200 with the one
  request that lost in UnprocessedItems in 10 and 21 calls, and 500
  InternalServerError in 80 and 68 calls. No call answered 200 with both
  requests unprocessed.
- A batch of one request on a held item answered 500 InternalServerError in 78
  and 82 of 160 calls.
- No BatchWriteItem call answered TransactionConflictException.

So TransactionConflict stays deferrable, and the handler test pins the
answer: a put that returns it after another request applied leaves exactly
that request in UnprocessedItems with a 200. The Cassandra side of the pin is
the existing storage test in ttl_integration.rs, which holds a claim on a row
and asserts that a put on it returns TransactionConflict. The answer for a
batch where nothing applied is a separate decision, taken in the next commit.
The handler stopped at the first request the backend could not apply and
returned that request and every request after it in UnprocessedItems with a
200. Two things followed. The answer for a contended request depended on its
position in the batch, and a batch of which no request applied answered 200
with every request unprocessed. The boto3 batch writer adds unprocessed items
to its next flush with no pause, so under the contention that caused the
failure such a client loops at full speed, and each pass costs the server
another full retry budget.

The service does neither (measured 2026-10-27 in us-east-1, client retries
off, while a TransactWriteItems held the items). A batch of two requests in
which one was on a held item answered 200 with that request unprocessed and
the other applied, whichever came first; the other request applied in all 640
calls of both samples. A batch whose requests were all on held items, one
request or two, answered 500 InternalServerError, and no call answered 200
with every request unprocessed.

The handler now tries every request. A request that fails with an error a
replay may clear is added to UnprocessedItems and the loop goes on. When no
request applied, the batch answers 503 ServiceUnavailable, which the SDKs
retry with backoff; the service's 500 for the same case is recorded in
docs/differences-from-dynamodb.md. A connection error still ends the attempt,
because the requests after it would wait on the same unreachable backend: the
request that met it and the rest are returned unprocessed, or the batch
answers 503 if nothing applied.

Trade-off: each failed request spends its own retry budget before the batch
answers, so a batch of 25 contended requests can spend 25 budgets in one call
where it spent one before. The 50-attempt budget still bounds each of them.

Tests (write_batch_deferral_tests): a failed first request does not stop the
rest; UnprocessedItems holds exactly the failed requests per table and the
consumed capacity and WriteCapacityUnits count the applied ones; a double
that fails every put gives 503 after trying every request, for Transient and
for TransactionConflict; a connection error leaves the rest unattempted, and
with nothing applied answers 503 after one attempt; an internal error after a
failed request still fails the batch with 500. The shared fixtures moved into
scripted.rs next to the double. The stream contention test retries a batch
that answers 503, as an SDK does.
When a single-item write ran out of attempts, the error said the write "lost
50 attempts to concurrent writers". The loops re-run a transaction for any
error that a re-run may clear, which includes a primary step-down and a
snapshot error, so a write that failed for those reasons was reported as
write contention, and the last driver error was dropped.

TxErr::Transient, TransactOpError::Transient and CommitOutcome::RerunBody
now carry the driver's error text, and each loop keeps the last one. The
exhaustion message reads "<operation>: could not commit in <N> attempts:
<cause>", and the engine logs it with its 503 warning. Each retry writes one
debug line with the operation, the attempt and the cause, so contention that
the final answer hides can be seen with the log level raised.
TransactWriteItems logs its last cause when it answers with the synthetic
TransactionConflict reasons; those reasons are unchanged.

docs/differences-from-dynamodb.md states that a single-item write on a
MongoDB table with a stream or an index answers 503 after 50 attempts where
the service answers 200, and that the server counts the 503 as a system
error, not under TransactionConflict.

Tests: retry_budget_exhausted puts the operation, the attempt count and the
cause in the message; retrying returns its cause; the conversions into TxErr
and TransactOpError keep the driver's text and a helper's Transient text.
The batch contention test replayed UnprocessedItems in a loop with no
limit and no pause, so a server that never applies the requests would
hold the job until its timeout. The loop now makes at most 200 passes,
sleeps 10 ms between two, and fails with the number of requests still
unapplied.

test_transactions_on_a_stream_table_all_commit sends TransactWriteItems
(a put, a delete and an update on disjoint keys) from six writers to a
stream table. On MongoDB the transactions conflict on the stream's
sequence counters, so a helper conflict has to re-run the whole
transaction. The test fails when a call answers 500 or 503, resends the
TransactionConflict cancellation that MongoDB answers after 50 attempts,
and checks that each counter and the stream record count show every
transaction applied once. No test combined TransactWriteItems with a
stream before.

tests/test_concurrency.py: ServiceUnavailable joins the retryable codes.
A MongoDB write that cannot commit in 50 attempts answers 503 where it
answered 400 TransactionConflictException, and the helper's client
allows the SDK a single retry, so the single-row tests would fail on the
first exhausted write.

The UpdateItem contention test accepts 400 TransactionConflictException
when EXTENDDB_TEST_BACKEND is cassandra, which settles a lost
optimistic-concurrency race that way. Every other backend keeps the
strict check.
The RFC and design document 13 listed the UnknownTransactionCommitResult
label as a trigger for re-running a transaction body. The code does not
re-run a body for that label: the commit may already have applied, so
classify_commit_error retries commitTransaction in place. Both documents
now say so.

Design document 13 said a single-item write that spends its attempts
returns StorageError::Internal. It returns StorageError::Transient, which
the engine answers as 503 ServiceUnavailable and the server counts as a
system error. The text now says that and describes the message.

"Base 50 microseconds" gave a backoff shorter than the 1 ms tick of the
tokio timer. Both documents now give the wait (a uniform 0 to 50 us times
2^min(attempt, 8)), its totals over 50 attempts, and the effect of the
tick on the first attempts.

The comments on StorageError::TransactionConflict and
StorageError::Transient, and on the engine arm that maps
TransactionConflict, described a single-item write that loses to other
writers as TransactionConflictException. The service answers that error
to a single-item write only while a TransactWriteItems holds the item,
and the MongoDB backend reports the other case as Transient.
BatchWriteItem runs seven checks on each request before it writes
anything: the key shape of a put, the nesting depth, the item size, the
attribute name sizes, the key sizes, the vector attributes and the key
shape of a delete. The tests covered the first check only, with a put whose
key has the wrong type. Moving any of the other six back into the write
loop, which applies the requests ahead of the faulty one before the 400,
left the tests green.

write_batch_tests.rs gets one test for each of the other six. Each sends a
valid put followed by a request that fails that check alone (an item of
401 KB, 40 levels of nesting, an attribute name of 70,000 bytes, a
partition key of 3,000 bytes, a vector of two components for an index of
three, a delete whose key has an extra attribute). The test requires a 400
that carries the message of that check and requires that the storage
double recorded no write, so a check that runs after the write of the put
ahead of it fails the test.

test_batch_write_validation_order.py adds the item of 401 KB and the
delete with an extra key attribute as the second request of a batch. Both
batches answer 400 ValidationException and the first put is not stored.
This commit changes comments and documents only.

batch_write_item.rs: the tables come from a HashMap, so requests are
checked in listed order within a table and the tables in map order, and
which of two table faults is reported is not defined. The sentences that
claimed an applied request is never followed by a rejection of the batch
and that a rejected batch never has an applied request now cover request
faults, and they name check_batch_counts and the HTTP layer for the limits
on the number of requests and on the request size. A storage error that a
replay does not clear still fails the batch after earlier requests were
applied (a 500 for an internal error), and a batch of which no request
applied answers 503.

is_deferrable described Transient as a write that lost every retry against
concurrent writers. Transient is a failure expected to clear on retry. The
MongoDB conflict is one case; step-down and snapshot errors on MongoDB, and
I/O errors, pool timeouts and busy databases on SQLite, are others.

The Cassandra backend raises TransactionConflict from a put or a delete
only on a table with TTL enabled. Without TTL it returns
TransactionCanceled, which is not deferred, so a batch on such a table
answers 400 after earlier requests were applied. The comment on the
TransactionConflict test is qualified and the differences row states the
case.

differences-from-dynamodb.md: the two batch measurements carry their date,
region and client retry setting (2026-10-27, us-east-1, retries off), and
the single-item contention row carries the date of its measurement
(2026-10-23).

create_table.rs names MongoDB where it says a write that lost to
single-item writers is reported as Transient. Cassandra reports it as
TransactionConflict.

Design document 13, section 5.6, said both transient-conflict signals mean
the write lost to a concurrent writer. They mean nothing was applied and
the transaction may be re-run, and a concurrent writer is the usual cause.

After an UpdateItem version miss the exhaustion message carries a fixed
sentence where other attempts carry a driver error. Design document 13, the
RFC, the differences row, StorageError::Transient and retry_budget_exhausted
call it the last error that ended an attempt.
The Cassandra pytest job failed two tests of tests/test_stream_write_contention.py
on this branch.

The batch test rejected a PutItem that answered 400 TransactionConflictException.
Cassandra settles a lost optimistic-concurrency race that way once its retries
are spent, and the UpdateItem test in the same file already accepts it when
EXTENDDB_TEST_BACKEND names that backend. The batch test now accepts it the same
way; MongoDB, SQLite and PostgreSQL keep 503 as the only allowed failure.

The transaction test expected one stream record per operation of every
transaction. Cassandra writes no stream record for a transacted write until
PR #576 lands, so the stream held only the setup puts (60 of the 240 wanted).
On that backend the test now expects the setup puts alone; the assertions that
every transaction committed and that each counter holds its writer's rounds
run unchanged on every backend.
LeeroyHannigan added a commit that referenced this pull request Nov 3, 2026
- The sessionless PutItem path and the duplicate-key arm of the
  transaction path said their attempts share the transient retry budget.
  Both count against CREATE_RACE_ATTEMPTS since the create race got a
  budget of its own.
- CONTENTION_DEADLINE's comment said only the loops that serve a request
  take the deadline. The TTL worker's conditional delete runs the delete
  loop too, so an expired item that stays contended holds the sweep until
  the deadline or the attempt budget ends that loop; the worker then logs
  the failure and moves on. The comment now says so, says that the
  requests of one BatchWriteItem share one deadline, and says that the
  attempt already running when the deadline passes has no bound of its
  own: it waits for a connection from the pool and for the commit's own
  retries, and the longest call at 256 writers on one key measured 11.7 s.
  It also states the cost of retrying for up to 10 s, CPU on the MongoDB
  server for as long as a key stays hot.
- contention_deadline_exhausted printed the deadline with as_secs(), so a
  deadline a test sets below one second read as "0 seconds". It now
  prints as_secs_f64(): "10 seconds", "2 seconds", "0.25 seconds".
- The RFC's decision table still listed the UnknownTransactionCommitResult
  label as a conflict the body retry detects, which the write conflict
  section contradicts. The row now says that label retries
  commitTransaction in place and never re-runs the body.
- The RFC section and the code now name #475, the fix for #437, as the
  change that gives DeleteItem and UpdateItem the transient give-up.
- docs/differences-from-dynamodb.md said all 1,280 puts committed at 64
  writers. On a loaded host 106 and 149 of 1,280 were shed. The row now
  says the shed count depends on the host's load, keeps the 256-writer
  measurement, and says how a BatchWriteItem answers a request that
  reaches the deadline.
crates/engine/src/batch_write_item.rs: main checks the attribute-name
size of every PutRequest item in one pass ahead of the table lookups,
with the BatchWriteItem wording, and removed the name check from the
per-request loop. The branch moved the table lookups and the per-request
checks ahead of the first write, into write_batch, check_batch and
validate_request, and tries every request before it answers. The merged
file keeps main's name pass in handle_batch_write_item ahead of the
branch's lookups, then calls the branch's write_batch. validate_request
no longer checks attribute names, as main's loop no longer does, and the
write_batch comment lists the name pass among the checks that run before
it.

crates/storage-mongodb/src/data_engine.rs: main added an
AttemptOk::NoWrite arm to the UpdateItem retry loop for a removal-only
update on a missing item. The branch made TxErr::Transient carry the
driver's text, which its arm records as the last cause. The merged loop
keeps both arms.

crates/engine/src/batch_write_item/write_batch_tests.rs: the merge
removes the branch's test that an attribute name over the limit rejects
the batch inside write_batch, because main's name pass runs before
write_batch. tests/test_attribute_name_limit_on_update.py on main covers
the batch refusal and its order ahead of the table lookup and the key
check.

crates/storage-mongodb/src/data_engine_key_repair.rs: main's key repair
matched CommitOutcome::RerunBody as a unit variant, and the branch made
that variant carry the driver's text. The match now takes RerunBody(_).
test_transactions_on_a_stream_table_all_commit expected only the setup
puts on Cassandra, because Cassandra wrote no stream record for a
transacted write. Main has #576, which records them, and after the merge
of main the Cassandra pytest job read 240 records where the test wanted
60. The test now wants the setup puts and every transacted write on all
backends.
No answer of BatchWriteItem changes.

- write_batch, check_batch and remaining_requests take the tables as
  &[(&str, &[WriteRequest])] instead of
  &[(&String, &Vec<WriteRequest>)]. handle_batch_write_item and the
  run_body test fixture build that slice.
- The write loop matches on (put_request, delete_request) once. The
  shape check in handle_batch_write_item rejects a request with neither
  or both, so that arm is unreachable!, where it was a continue.
- A deferred request logs at debug level. The batch logs one warning
  with the counts of applied requests and of requests not applied, and
  the last error. That warning replaces the one that a batch with
  nothing applied logged. A batch of 25 requests of which none applied
  now logs one warning instead of 26.
- The doc comment of is_deferrable states that the handler assumes a
  deferred request was not applied. A replay of a request that had
  committed would apply it twice and write a second stream record. A
  commit of unknown outcome has to end as Internal. MongoDB does that
  for UnknownTransactionCommitResult once the commit retries are spent.
  On SQLite, map_sqlx_err classes an I/O error as Transient, but
  put_item and delete_item map an error of the COMMIT to Internal
  without map_sqlx_err. So an I/O error at COMMIT, which can leave the
  write applied, fails the batch with 500 and is not deferred.

docs/differences-from-dynamodb.md gets one sentence in the
BatchWriteItem row about the Cassandra paths. The row says that a put
or a delete of an item that a TransactWriteItems holds returns
TransactionCanceled on a table without TTL. The new sentence covers the
other path. A write that spends its retries on a lost race, on any
table, returns TransactionConflict. So does a write that spends them on
a held item of a TTL table. The batch leaves both in UnprocessedItems.
crates/storage/src/error.rs describes that second path.
The BatchWriteItem row of docs/differences-from-dynamodb.md now says
that ExtendDB gives no ConsumedCapacity entry to a table of which no
request applied. write_batch builds ConsumedCapacity from the units of
the applied requests, so such a table has no units to report. What
Amazon DynamoDB reports for that table in a partial batch was not
measured.
@pdf-amzn

Copy link
Copy Markdown
Collaborator

I think this also needs a rebase

Main is 3 commits ahead of the last merge (b5858c7), up to cbc3680:
#515 (disabling a stream closes its shards), #355 (auth) and #896
(npm). The textual merge is clean and the merged tree compiles with no
change. Seven files changed on both sides: crates/engine/src/
create_table.rs, data_engine.rs, lib.rs, stream_engine.rs and
table_engine.rs in crates/storage-mongodb/src, and
docs/design/13-storage-mongodb.md and docs/differences-from-dynamodb.md.

In assign_shard_in_session, #515 reads only the open shards and returns
None when the table has none. This branch maps the errors of the
table read, the shard find and the cursor in that function through
write_conflict::transaction_error. The merge keeps both. The stream
record path in data_engine.rs takes the let-else of #515, so a write
that finds no open shard records nothing. The record insert keeps
transaction_error.

#515 adds no code that runs inside a write transaction. The new
stream_lifecycle.rs and the UpdateTable stream change in
table_engine.rs run without a session, because UpdateTable has no
transaction on this backend. So their driver errors stay Internal.
A plain CreateTable runs no transaction. The CreateTable of a restore
calls init_stream_shards after it commits its registration
transaction. The close of a stream updates stream_shards
documents, and a write transaction only reads those documents. So a
close does not abort a write with WriteConflict. The counter
documents in the counters collection, which writers do conflict on,
are not touched by a close.

In lib.rs the module list gets stream_lifecycle from main and keeps
write_conflict. In create_table.rs main adds
require_stream_enabled_member and this branch's comment on the
TransactionConflict arm stays.
A batch can hold a valid put and then two faulty puts in one table.
Amazon DynamoDB answers such a batch with the fault of the first faulty
put in list order and applies nothing. The measurement ran in us-east-1
on 2026-11-10, two sends of each batch. The table had the key pk (S)
and a global secondary index by-g on g (S). One faulty put had pk as a
number, and the other had g as a number or as an empty string. Each
pair went in both orders.

g as a number:

- g first: 400 ValidationException "One or more parameter values were
  invalid: Type mismatch for Index Key g Expected: S Actual: N
  IndexName: by-g".
- pk first: 400 ValidationException "The provided key element does not
  match the schema".

g as an empty string:

- g first: 400 ValidationException "One or more parameter values are
  not valid. A value specified for a secondary index key is not
  supported. The AttributeValue for a key attribute cannot contain an
  empty string value. IndexName: by-g, IndexKey: g".
- pk first: 400 ValidationException "The provided key element does not
  match the schema".

check_batch checks the requests of a table in list order, and
validate_request runs validate_index_keys after the table key checks.
So ExtendDB gives the same four answers, and no server code changes.

tests/test_batch_write_validation_order.py gets
test_two_faulty_puts_report_the_first_in_list_order with the four
batches, on the table with the global secondary index. Each case checks
the 400, the message and that the valid put was not applied.
The churn test of tests/test_stream_write_contention.py sends a write
that answered 503 ServiceUnavailable again, up to 20 times. So a server
that answers 503 at the first counter conflict, instead of running the
transaction again, can pass the test. A failing run also did not show
how many writes answered 503 before they answered 200.

_resend_unavailable now returns the number of resends with the answer.
The churn test counts the writes that answered 200 only after a resend
and puts that count in both of its assertion messages. The count has no
bound, because it depends on the load on the host.

The module docstring said that these tests fail on a server that
reports the counter conflict as an error. The churn, batch and
UpdateItem tests accept a 503 once the retry budget is spent. So the
sentence now says that the tests fail on a server that answers 500
InternalServerError for that conflict. Each of the four tests fails on
such a server.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

@pdf-amzn I pushed b349959. It merges main twice, at b5858c7 and at cbc3680. The branch merges main and does not rebase, because its pushed commits stay as they are. On 2026-11-10 I measured each new service answer that the tests encode, two sends each.

  • Finding 1: 3cbdb82 makes validate_request call validate_index_keys with the table's global and local secondary indexes, so check_batch refuses the batch before the first write. The storage-side check stays, for an index added after the lookup. The service refuses a GSI key of the wrong type or an empty one with nothing applied (21:24 UTC). The engine tests and test_batch_write_validation_order.py encode both answers. With two faulty puts in one table, the service reports the first in list order (22:57 UTC), and 83e1bf8 adds those four batches. The LSI path goes through the same call and is not measured.
  • Finding 2: the 503 for a batch that applied nothing does not change in this round. Lee decides between that and the measured 500.
  • Finding 3: 6d3a927 sends a 503 again, up to 20 times, with the backoff of tests/test_concurrency.py. b349959 counts the writes that needed a resend and puts the count in the assertion messages. A 500 and a lost stream record still fail the test.
  • Nit 4: 511f1dd asserts the message of each rejected batch as measured. ExtendDB already answered each text.
  • Nit 5: docs/differences-from-dynamodb.md says that the service's ConsumedCapacity for a table with no applied request is not measured.
  • Nit 6: the comment of is_deferrable says that the handler assumes a deferred request was not applied. On SQLite an I/O error at COMMIT does not reach that function: put_item and delete_item map it to Internal, so the batch answers 500.
  • Nit 7: MongoDB: no test covers two first writes on a new stream shard's counter #944.
  • Nit 8: d6ecb09 has the slices, the unreachable! arm and one warning per batch. The lookup loop already pushed into a Vec::with_capacity.
  • Nit 9: the BatchWriteItem row now says which Cassandra path answers TransactionConflict and which answers TransactionCanceled.

The merge at b5858c7 (ec85c6a) adds the String payload of TxErr::Transient and CommitOutcome::RerunBody to main's claim_restore_tx and insert_restore_batch, so the merged tree compiles. The merge at cbc3680 (08a9589) changes no code. At 08a9589, test_stream_write_contention.py passed 4 of 4 against a MongoDB-backed server.

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

Nothing blocking, thanks for the quick turnaround. The 503 vs 500 question is still open and needs followup. Please do the index-key builder follow-up soon; the rest are optional. I'll let you decide whether to merge now or address the index-key builder first.

Tested b349959 merged with main 9a1105b. PostgreSQL suite: no test that passes on main fails here, and the 17 new tests pass. MongoDB (run-mongodb-tests, stream_write_contention / batch_write / test_concurrency): 49 passed. Real DynamoDB (us-east-1): the 17 new tests in test_batch_write_validation_order.py and test_stream_write_contention.py pass. The merge fix in ec85c6a only touches the four match arms in claim_restore_tx and insert_restore_batch, and those keep their earlier retry behaviour.

Open: crates/engine/src/batch_write_item.rs:319-330. A batch that applied nothing answers 503, where DynamoDB was measured answering 500. botocore and the Java SDK v2 retry 500 as well, so the SDK-retry reason doesn't settle it either way. Pick one on purpose: answer InternalServerError and drop the differences row, or keep 503 and give the real reason in docs/differences-from-dynamodb.md.

Important follow-up: crates/engine/src/batch_write_item.rs:512. secondary_index_keys is now the third builder of a write's index keys, next to index_keys in partiql/write.rs:352 and the inline builder in update_item.rs:265. Each one decides separately which attributes make up a GSI or LSI key, including multi-attribute GSI keys and the sparse case where a key attribute is absent. If one of them changes and the others don't, BatchWriteItem, PartiQL and UpdateItem validate index keys differently, and nothing would catch it. Move them into one helper, for example a method on TableKeyInfo, and have all three call it. While there, build it once per table in check_batch rather than allocating a Vec for every put.

Nit-or-follow-up: crates/engine/src/batch_write_item.rs:452-466. Within one table, faults are reported in list order and 83e1bf8 pins that. Across tables the order follows HashMap iteration and is undefined; the doc says so and no test depends on it. A few orders are still unmeasured: a table-key fault vs an index-key fault in the same put, item size vs index key, and the LSI path (write_batch_tests.rs:313 asserts only the 400). Add an LSI parameter to test_batch_write_validation_order.py when someone next measures.

Nit-or-follow-up: tests/test_stream_write_contention.py:147-163. Now that the churn test resends 503s, it would also pass on a server that answers 503 at the first counter conflict without retrying. The 50-attempt body re-run is pinned only by the classifier unit tests. A MongoDB test hook that injects fewer than 50 write conflicts and expects a 200 with one stream record would cover the loop itself.

Nit-or-follow-up: crates/storage-mongodb/src/backup_catalog.rs:674,816 and restore_engine.rs:186,188 ignore the new error payload, so a restore or backup delete that runs out of attempts still reports "did not commit" without the driver error. Same as before this PR. Passing the cause to write_conflict::retry_budget_exhausted would match the data path.

Nit-or-follow-up: crates/engine/src/batch_write_item.rs:197,265. last_error builds a String for every deferred request but only the last is used. Keep the StorageError and format it once at the warn!.

Not checked: whether TableKeyInfo's index list and the storage write path agree on indexes in CREATING or DELETING state. Postgres fetch_write_path_indexes has no status filter.

@pdf-amzn pdf-amzn removed their assignment Nov 11, 2026
@LeeroyHannigan
LeeroyHannigan added this pull request to the merge queue Nov 11, 2026
Merged via the queue into main with commit 466faa4 Nov 11, 2026
57 checks passed
@LeeroyHannigan
LeeroyHannigan deleted the fix/mongodb-stream-counter-conflict branch November 11, 2026 21:38
LeeroyHannigan added a commit that referenced this pull request Nov 12, 2026
Main at 06534e1 adds #228, #923, #475, #732 and #900 since the last
merge. One file conflicted: crates/storage-postgres/src/backup_catalog.rs.

#900 moves the insert statement of insert_backup_row into a new
function, insert_unowned_row. The legacy reader's
replace_with_index_row runs that function inside its own transaction.
On this branch, the same insert stores source_table_details_json
through escape_json. The merge keeps main's function and adds the
escape to it, so both callers store the escaped form that
row_from_tuple reads back. The module comment now names
insert_unowned_row in place of insert_backup_row.

Main adds no other write of a catalog document that carries attribute
names. #900's legacy reader takes the source table from restore_source,
which reads the stored documents through from_catalog_json and
unescape_json.

Against main, the merged tree changes the same 44 files, with the same
line counts, as this branch did against its merge base. In
backup_catalog.rs the escape of the unowned insert is in
insert_unowned_row, and the module comment names that function.
LeeroyHannigan added a commit that referenced this pull request Nov 12, 2026
Main is 12 commits ahead of the last merge (9c3fbfb), up to
511d6c7. One file conflicted.

- crates/engine/src/batch_write_item.rs: #475 reads the key info of
  every table in handle_batch_write_item and moves the checks and the
  writes into a new write_batch function. The merge keeps this
  branch's number check after the attribute name size checks and
  before the table lookups, where it was.
LeeroyHannigan added a commit that referenced this pull request Nov 12, 2026
Brings in main at ce3a51a (#833), 63 commits past the main that
#399's head carries.

docs/differences-from-dynamodb.md conflicted in two tables where both
sides added rows after the same line. The Storage and Infrastructure
table keeps #399's CancellationReasons row and main's BatchWriteItem and
MongoDB single-item write rows. The Control Plane table keeps #399's
Table ARN row and main's U+0000 and stream disable rows.

#399 added creation_date_time to TableKeyInfo. Two test fixtures that
main added since build a TableKeyInfo without it: the scripted
BatchWriteItem engine fixture (crates/engine/src/batch_write_item/
scripted.rs, #475) and the isolated account fixture of the Cassandra
integration tests (crates/storage-cassandra/tests/common/mod.rs). Both
now set it to 0.0, as the other fixtures in those crates do.

Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com>
LeeroyHannigan added a commit that referenced this pull request Nov 14, 2026
Main added two TableKeyInfo literals in test code: the table helper in crates/engine/src/batch_write_item/scripted.rs (#475) and isolated_account in crates/storage-cassandra/tests/common/mod.rs (#829). This branch adds the creation_date_time field to TableKeyInfo, so neither literal compiles after the merge. Both literals now set creation_date_time to 0.0, as the other test literals on this branch do.
LeeroyHannigan added a commit that referenced this pull request Nov 17, 2026
Since main #475, BatchWriteItem leaves a request that failed with a transient, conflict or connection error in UnprocessedItems. record_partial_batch_throttle read UnprocessedItems and UnprocessedKeys from the response, so it recorded those deferrals as throttles.

DispatchMetrics now carries throttled_tables, by the catalog's table name. It lists each table of a batch with at least one request or key that a backend throttled, once. write_batch adds a table where it counts a throttle, and handle_batch_get_item adds one where it leaves a key unprocessed. record_partial_batch_throttle records ThrottledRequests and the read or write throttle event for each of those tables. A table that a request named by its ARN gets the same table dimension as main's other records (#922).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-blocker Must ship for its milestone's release v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants