Skip to content

fix(cassandra): record stream records for transacted writes - #576

Merged
navareamol merged 9 commits into
mainfrom
fix/516-cassandra-transact-stream-records
Oct 29, 2026
Merged

navareamol merged 9 commits into
mainfrom
fix/516-cassandra-transact-stream-records

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #516.

What was wrong

On Cassandra a TransactWriteItems Put, Update or Delete on a table with an enabled stream recorded nothing; PutItem, UpdateItem, DeleteItem and BatchWriteItem on the same table recorded as expected, and SQLite recorded all five shapes. On a main binary four of the five new wire tests fail; on the branch all pass on every backend.

What changed

One source file, crates/storage-cassandra/src/data/transactions.rs, plus a new sibling data/transact_stream.rs holding the pure pieces (the old-image rule and the batch builder) with their unit tests.

The commit phase builds a stream record for each item mutation with the same stream_record_statement every single-item path uses, with the same image pair. A pure builder decides how the record is batched with the index rows and the commit path executes what it returns. Unit tests pin how the statements are grouped. Two storage tests pin that a rejected index statement leaves no record and a rejected record statement leaves no index row.

The stream record goes into the same LOGGED BATCH as the index rows, and that batch runs after the base row's lightweight transaction. Cassandra rejects a batch that writes more than one partition once its data passes batch_size_fail_threshold, which is 51,200 bytes unless the operator changed it. A large item therefore made the transaction fail after its first operation had committed. On a table with one GSI and a NEW_AND_OLD_IMAGES stream, with the default threshold, a transacted insert committed at 24 KB and failed at 28 KB, and a transacted overwrite committed at 16 KB and failed at 20 KB. The failed transaction left the item written without its index rows or its record, left the ledger entry in COMMITTING, left the later operations uncommitted, and answered 500.

secondary_effect_batches now adds up the bytes of the index statements and the record statement. Up to 24,000 bytes the record shares the index batch. Past that, the index rows run first and the record runs after them as a batch of its own. A batch with one statement writes one partition, so the limit does not apply to it. 24,000 is under half of the default limit, so the margin covers the difference between this count and the size Cassandra measures, and a server set to a lower threshold. The code cannot read that setting. The count includes the index statements because each index adds a copy of the item: an 18 KB insert on a table with two GSIs has a 19 KB record, and 57 KB with its two index entries.

For the writes over the budget, the index rows and the record are no longer one atomic unit. If the process stops after the first batch, or the second batch fails, the index rows are written and the record is not, and nothing writes the record afterwards. With the split, an insert, an overwrite and a two-operation transaction at 16, 20, 24, 28 and 32 KB all commit with their records on the one-GSI table, where the single batch failed from 28 KB for an insert and from 20 KB for an overwrite. The split does not bound the index batch, which is sent whole: when the index rows write more than one partition and pass the limit by themselves (two synchronous GSIs, or one synchronous and one asynchronous GSI, from about 26 KB), the item is written without them. That failure is the same on main and is filed separately.

The sequence number of each record is taken after the base write, on the Put, Update and Delete arms. Before this change it was taken before the lightweight transaction, and in 25 of 40 transacted Puts and Updates the record's millisecond was earlier than the row's own write time, so a consumer reading by sequence number could miss a record that landed behind a later-numbered one; after the change 0 of 40.

The old image is read at commit time from the row together with created_to_prepare and last_committed_txn_timestamp. PREPARE plants a placeholder row holding the request's own item for an absent key, so the row's item_data alone would report an insert as a modify; and PREPARE's own read is one write stale when a single-item write commits inside the PREPARE window, which main accepts and the marker does not detect. The commit and the recovery replay now clear created_to_prepare. Rows committed by earlier releases still carry the flag over a committed item; the commit timestamp, which only a commit writes, tells them apart, so the first transacted write on such a row after an upgrade records MODIFY or REMOVE rather than INSERT or nothing. Clearing the flag also means a committed item is kept when a later transaction that prepared the key is cancelled: the rollback deletes a row only when the flag is still set, and a storage test on a hash-key and on a sort-key table pins that the committed item survives.

The index metadata read moved above the base write on the Put and Update arms, so the record does not wait an uncached catalog round trip behind an already-committed item.

Measured on Amazon DynamoDB (2026-10-25)

Record order within one transaction: the service does not return a transaction's records in request order (a Put to k5 then a Put to k7 came back k7, k5; a Put, Update and Delete came back REMOVE, INSERT, MODIFY, one shard, composite key). ExtendDB returns request order on every backend. The wire tests assert per key, which is the guarantee the service gives.

Record contents: a transacted record carries the same field set as a single-item record (awsRegion, dynamodb, eventID, eventName, eventSource, eventVersion; inside dynamodb, ApproximateCreationDateTime, Keys, the images for the view type, SequenceNumber, SizeBytes, StreamViewType), no userIdentity, nothing marking it as transacted; sequence numbers of one transaction are not contiguous. ExtendDB matches: same builder, same arguments, one number per mutation from the same clock. On Cassandra and SQLite the transacted record equals the single-item record of the same verb field for field, for a Put, an Update and a Delete under NEW_AND_OLD_IMAGES.

Tests

Storage (tests/direct/transact_write_stream_records.rs, transact_write_stream_images.rs, transact_write_stream_batch_limit.rs, transact_write_stream_size_sweep.rs, transact_write_stream_sequence.rs, transact_write_stream_tables.rs, transact_write_rollback_after_commit.rs, in the direct_integration binary CI runs whole): one record per mutation, two mutations in request order, a streamed and an unstreamed table in one transaction, KEYS_ONLY, ConditionCheck, a cancelled transaction, a delete of an absent key, an update creating a key, a Put over an existing item, a Put over a planted row, a Put and a Delete over a row committed before the flag was cleared, a field-for-field comparison with the single-item records, the batch limit (a 24 KB overwrite under NEW_AND_OLD_IMAGES on a GSI table commits with one MODIFY record and no ledger entry; the size sweep at 16 to 32 KB), the sequence order (no record's millisecond earlier than its row's write time in 20 Puts and 20 Updates), the all-verbs test on S, N and B sort-key tables and on a GSI table, a failing index statement leaving no record and a failing record statement leaving no index row, and a cancelled transaction keeping a committed item on a hash-key and on a sort-key table. Unit: eight tests on the pure functions, including the budget boundary, bound values counting toward it, and the record batch carrying the index batch's type, consistency, serial consistency, timestamp, keyspace and now-in-seconds. Wire (tests/python/test_streams_transactions.py, collected by every backend job): five tests, 36 of 36 with test_streams.py and test_transactions.py on Cassandra, and the same on SQLite, PostgreSQL and MongoDB.

Controls, each on a committed tree: the fix removed, 6 of 8 original storage tests and 4 of 5 wire tests fail; the old image taken from PREPARE's read instead of the commit-time read, only the planted-row test fails; the Put arm dropping its old image, two storage tests and the wire row fail; the record forced back into the index batch, the four batch-limit tests and the size sweep fail with the batch-too-large error after the lightweight transaction; the sequence number taken before the write, 9 to 14 of 40 records early; the created_to_prepare clearing removed, the committed item is lost on the hash-key and on the sort-key table; the budget counting only the record, one integration test and two unit tests fail; the commit-timestamp rule removed, the two upgrade tests fail. cargo fmt, clippy 1.97 and the 1.88 build are clean; 69 lib tests; direct_integration whole 173 of 173 at four threads.

Stated limits

A failure while writing op k's index rows or record leaves k items mutated and k-1 records written. Op k's index rows are missing too, unless the record was split into its own batch and the failure came in that second batch. A failure in the read or the lightweight transaction of op k+1 leaves k items mutated and k records written. The recovery worker finishes the base mutations of the remaining ops and writes no further records and no index rows. A transaction recovered after a crash writes no stream record and no index rows, because the ledger carries neither the capture nor the key schema. Both are the backend's pre-existing behaviour on this path.

A single-item write that commits inside a transaction's PREPARE window is accepted and not detected, and an item deleted there is resurrected by the transaction; pre-existing, filed separately. This branch's commit-time read means the record reflects the row as committed, so it no longer claims a transition that did not happen.

Index rows: this branch leaves the index arms as main had them. A transacted Put passes no old image to the index sync and a transacted Delete reaches no index sync, so a key-changing Put leaves the old GSI row and a Delete removes none; on the service the GSI is correct within 4 s on both shapes. Filed as #568. With this branch a consumer sees a REMOVE record for a transacted delete while a Query on the GSI still returns the item.

The budget was measured on a single-node cassandra:4.1 with the default threshold and a string attribute carrying the size. The Delete arm's sequence-number order has no test, because a deleted row has no write time to compare against.

Composition with #515

The stream capture is resolved before the PREPARE phase and the record is built in the commit loop, so the window between resolution and record write on the transaction path is the whole PREPARE phase (row reads, condition evaluation, marker LWTs, up to five create-race retries with 50 ms polls, the ledger update). #515 models a stream's shard as a sequence range of a physical partition that every write lands in regardless of the current stream; after it merges, a transacted write acked before a disable can land past the closed shard's ending number and inside no stream's range, and the count is not bounded by what #515's race probe measured, which exercised single-item writers only. Whoever merges second should measure transacted writers. Trial merges with #515 and #543 are clean.

Cassandra's SequenceNumber is 23 characters where SQLite's is 21, and MongoDB numbers per shard from 1 where the other three use one counter; pre-existing in the single-item paths and unchanged here.

A TransactWriteItems Put, Update or Delete on a Cassandra table with an
enabled stream recorded nothing. The commit phase wrote the item mutation
and such index rows as it maintained, and skipped the stream capture the
request carries per operation.

The commit phase now builds the stream record for each item mutation with
the same stream_util::stream_record_statement the single-item paths use,
with the same image pair, so the event name, the images for the table's
view type, the shard assignment and the sequence number come from the same
source as the equivalent PutItem, UpdateItem or DeleteItem. The record
joins the secondary-effects LOGGED BATCH that already carries the index
rows; Cassandra rejects a batch mixing an LWT with writes to another
partition, so neither the single-item path nor this one can put the record
in the base mutation's own statement. A pure builder returns that batch
and the commit path executes what it returns, so a unit test holds the
index rows and the record together.

The old image is read at commit time, from the row together with its
created_to_prepare and last_committed_txn_timestamp columns: a row PREPARE
planted, which has never had a commit land on it, has no old image;
otherwise the old image is the row's item_data, which is itself absent
when the row holds a marker with no item. PREPARE plants the request's own
item for a Put and the bare key for an Update, so the row's item_data
alone would report an insert as a modify, and PREPARE's own read is one
write stale when a single-item write commits inside the PREPARE window,
where it is accepted and the marker's IF prepared_txn_id = null does not
detect it. This costs one read per streamed Put and Delete op; the Update
arm reads the row anyway. Committing, and the recovery worker's replay,
now clear created_to_prepare. Releases before this one did not clear it,
so a row they committed carries the flag over a committed item; the commit
timestamp, which only a commit writes, tells that row apart from a planted
one, and the first transacted write on it after an upgrade records MODIFY
or REMOVE rather than INSERT or nothing.

The index metadata read moves above the base LWT on the Put and Update
arms, as occ_write does it, so the record does not wait an uncached
catalog round trip behind an item that has already committed.

A ConditionCheck records nothing, a cancelled transaction records nothing
for any of its items, and a delete of an absent key records nothing.
Records land in request order, which is ExtendDB's own behaviour on every
backend rather than a promise the service makes.

Storage tests cover fourteen shapes on a live Cassandra node, including a
Put over an existing item, a Put over a planted row, a Put and a Delete
over an item committed before the flag was cleared, and a transacted
record compared field by field with the single-item record of the same
verb. A wire test covers a transacted Put over an existing item, an
Update, a Delete, a ConditionCheck, a cancelled transaction and a
KEYS_ONLY stream; it asserts per key, since records for one key share a
shard and records for different keys do not.

Closes #516
A transacted write on a table with a stream and an index put the stream
record in the same LOGGED BATCH as the index rows. That batch runs after
the base row's lightweight transaction has committed. Cassandra rejects a
batch that writes more than one partition once its data passes
batch_size_fail_threshold, which is 51,200 bytes unless the operator
changed it. The rejection left the item written without its index rows or
its record, left the ledger entry in COMMITTING, left the later operations
of the transaction uncommitted, and answered 500.

secondary_effect_batches now adds up the bytes of the index statements
(text and bound values) and of the record statement. Up to 24,000 bytes
the record joins the index batch as before. Past that, the index rows run
first and the record runs after them as a batch of its own. A batch with
one statement writes one partition and is not subject to the limit, so a
record of any size commits. commit_secondary_effects already ran the
batches in order. It now builds the index batch before calling the helper,
because the size can only be read from a built batch.

The budget is 24,000 bytes. On cassandra:4.1 with the default threshold, a
table with one GSI and a NEW_AND_OLD_IMAGES stream took a transacted insert
of 24 KB and refused one of 28 KB, and took a transacted overwrite of 16 KB
and refused one of 20 KB. The index entry and the record total about 48 KB
where those committed and 56 to 60 KB where they were refused, which fits
the 51,200 byte limit. 24,000 is under half of the limit, so the margin
covers the difference between this count and the size Cassandra measures,
and a server configured with a lower threshold, which the code cannot read.
The count includes the index statements because every index adds a copy of
the item. An 18 KB insert on a table with two GSIs has a 19 KB record, which
is under any cutoff on the record alone, and the record plus the two index
entries is 57 KB.

For the writes it applies to, the split means the index rows and the record
are no longer one atomic unit. If the process stops after the first batch,
or the second batch fails, the index rows are written and the record is not,
and nothing writes the record afterwards.

A storage test overwrites a 24 KB item in a transaction on a GSI table with
a NEW_AND_OLD_IMAGES stream and requires success, one MODIFY record with
both images, and no ledger entry. A second storage test runs an insert, an
overwrite and a two-operation transaction under a client token at 16, 20,
24, 28 and 32 KB. Two more cover a transacted Update of a 20 KB item and the
two-index insert above. Unit tests pin that a 30,000-byte record yields two
batches with the record last, where the budget boundary lies, that bound
values count toward it, and that a record with no index rows stays one
batch whatever its size.
The transacted Put, Update and Delete arms built the stream record
statement before the base write. The statement takes its sequence number
when it is built, so the number was taken before the item's lightweight
transaction. For a Put or Update it was also taken before the catalog read
for the table's indexes, and for a Delete before two or three lightweight
transactions. A record numbered earlier than the write it describes can
land after a record that another write on the same shard has already
published, and a consumer that has read the later record can miss the
earlier one.

The arms now read the old image before the base write and build the
statement after it: after commit_put_or_update for a Put or Update, and
after check_lwt_applied for a Delete. The old image is the same row as
before. The Update arm already held it from the read it uses to apply the
update.

On loopback against cassandra:4.1, 40 single-operation transactions (20
Puts and 20 Updates) took a sequence number whose millisecond was earlier
than WRITETIME(item_data) of the stored item in 25 cases on the previous
commit, 14 of the Puts and 11 of the Updates, each by 1 ms. With this change
it was 0 of 40. The new storage test makes that comparison for the same 20
Puts and 20 Updates. It does not cover the Delete arm, because a deleted row
has no write time to compare with.
Committing a transacted Put or Update clears created_to_prepare as well as
prepared_txn_id. The doc comment on commit_put_or_update gave a different
reason, that a flag left set would make the next transacted write on the key
record an insert over a committed item. The commit-timestamp rule in
fetch_row_for_transaction already tells a committed row from a placeholder
when the flag is set, so the clearing does not change which old image a
record carries.

The clearing affects rollback. rollback_single_operation and
recover_rollback_op run DELETE .. IF prepared_txn_id = ? AND
created_to_prepare = true before they clear prepared_txn_id. A committed row
that kept the flag matches that DELETE when a later transaction that
prepared the key is cancelled, and the committed item is deleted. The doc
comment now says this. It also says that rows committed before the clearing
existed still carry the flag and are still deleted this way.

The new storage test commits an item through a transaction, then runs a
transaction that overwrites the key and carries a condition on another key
that fails. It requires the cancelled transaction to leave the first
transaction's value in place and the other key unwritten. With the clearing
taken out of both commit statements, get_item returns nothing after the
cancelled transaction.
The scenario in test_transact_write_records_one_stream_record_per_mutation,
a Put, an Update and a Delete in one transaction, now lives in a function
that takes the table and the builders for its items and keys. The original
test calls it on a table with a hash key only. New tests call it on tables
with a string, a number and a binary sort key, checking that every record
carries both key attributes, and on a table with a GSI pinned to synchronous
propagation, checking that the Put's index row is written.

Two more tests pin that the index rows and the record of a small item are one
batch. In the first, the index's table has been removed, so the server
rejects the index statement. The transaction fails with an error from the
secondary-effects batch and no record exists. In the second, the account's
stream_records table has been removed, so the server rejects the record
statement. The transaction fails the same way and the index scan holds no
row. The first test fails if the record can be written when the index
statement is rejected, and the second if the index rows can be written when
the record statement is rejected.
commit_secondary_effects said the queue row an asynchronous GSI takes is
written outside the batch. enqueue_async_indexes adds it to the same batch as
the index rows, and its own doc comment says so. The same comment called the
window after the base LWT brief and compared it to the one async GSIs accept.
An async GSI row converges through its queue. An index row or a record lost
after the base LWT is not written again, because recovery re-runs the base
mutation only. The comment now says that, and says the queue row goes into
the index batch.

indexes_for_commit said occ_write reads the indexes before its own base write.
occ_write receives them from its callers, which read them once at entry, so
the sentence is dropped.

The planted-row helper in the images test described a row with no
prepared_txn_id and called it the shape a single-item write leaves. PREPARE
sets prepared_txn_id, and no single-item path writes created_to_prepare. The
comment now describes the row PREPARE plants and what the helper writes.

The comment in the transact_write_items engine handler said stream records are
captured atomically within the storage transaction. That holds for
PostgreSQL, SQLite and MongoDB, and not for Cassandra, and the comment now
says which.

The debug_assert_eq on pre_commit_images is removed. The loop above it pushes
one image per op in every arm, so the assertion cannot fail. A docstring in the
Python test now says "an extenddb endpoint".
The doc comment on secondary_effect_batches said that splitting the record
into its own batch keeps a large write from reaching the state where the
item is written without its index rows or its record. The split returns the
index batch unchanged. Cassandra refuses any batch that writes more than one
partition once its data passes batch_size_fail_threshold, 50 KiB by default,
whatever statements the batch holds. On two synchronous GSIs, or one
synchronous and one asynchronous GSI, the index rows alone pass that limit
from an item of about 26 KB, with or without a stream, and the batch is
refused after the base row's lightweight transaction has committed.

The comment now says that the split keeps the record from being the
statement that pushes a batch over the limit, that it does not bound the
index batch, and when the item is written without its index rows. The
sentence about the lost atomicity said "It" after the replaced sentence, so
it now names the split. No code changes.
commit_put_or_update clears created_to_prepare in two statements, one for a
table with a sort key and one for a table with a hash key only. The
cancelled-transaction test created its table with no sort key, so every
commit in it went through the hash-key statement and no test ran the
sort-key statement's clearing. A committed sort-key row that kept the flag
matches the rollback DELETE of a later cancelled transaction that prepared
the key, and the committed item is deleted.

The scenario now lives in a function that takes the table and the builders
for its items and keys, and the existing test calls it on the hash-key
table. A second test calls it on a table with a string sort key, with the
sort-key item and key builders of the stream tables tests, whose with_sort
helper is now visible to the other test modules. It requires the item the
first transaction committed to be stored with its first value after a second
transaction that prepared the same key is cancelled, and the second
transaction's other key to be unwritten.
secondary_effect_batches builds the record's batch from the index batch's
request and copies its batch type, consistency, serial consistency,
timestamp, keyspace and now_in_seconds. The unit test for a record too large
to share the index batch compared the consistency and the batch type only,
and its index batch left the other four settings at their defaults, so a
record batch that dropped them would have passed.

The shared index_batch fixture now sets the serial consistency, the
timestamp, the keyspace and now_in_seconds to values other than their
defaults. The test checks that the index batch has all four set, then
requires the record batch to carry each of them.
LeeroyHannigan added a commit that referenced this pull request Oct 27, 2026
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.
@jcshepherd jcshepherd self-assigned this Oct 29, 2026
@jcshepherd

jcshepherd commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

24,000 is under half of the default limit, so the margin covers the difference between this count and the size Cassandra measures, and a server set to a lower threshold. The code cannot read that setting

This is incorrect. Some configuration values are projected into "views" which are similar to tables. A query like the following will return the configured maximum batch size for the node:

SELECT name, value
FROM system_views.settings
WHERE name = 'batch_size_fail_threshold_in_kb';

Increasing it might help reduce the need for splitting batches and losing atomicity, but it also risks causing performance impact (Cassandra batches are not performance optimizations, like they are on many other engines).

@jcshepherd

Copy link
Copy Markdown
Collaborator

Clearing the flag also means a committed item is kept when a later transaction that prepared the key is cancelled: the rollback deletes a row only when the flag is still set, and a storage test on a hash-key and on a sort-key table pins that the committed item survives

This is partially true. I don't think it is a big issue given that the Cassandra plug-in is considered experimental, but there is a loophole through which items created before this change can be deleted by a transaction cancel with this change:
#659

This is probably not a difficult fix. Add AND last_committed_txn_timestamp = null to the DELETE condition in rollback_single_operation and recover_rollback_op. A planted row never has that column set, so planted-row cleanup still works. A committed row always has it set. (#576 already uses this column to tell such rows apart, at transactions.rs:1254 on its branch.)

///
/// The caller executes exactly what this returns, in order, so the grouping is
/// asserted in unit tests rather than resting on the shape of the calling code.
pub(super) fn secondary_effect_batches(

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 should probably be pulled up out of transact_stream. Similar constraints apply to single item mutations, not just transact writes. I don't know if you want to do this as part of this PR or not, but if not it should be tracked as follow-up work.

} else {
None
};
self.commit_secondary_effects(

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 may be unintentionally worsening a risk of stream record HLCs for newly inserted records falling behind a stream reader's "cursor". That problem already exists here and probably in the PostgreSQL implementation as well, so it's out of scope of this PR in my opinion, but captured here if we want to come back to it: #660

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

I'm approving because I don't have a strong reason to block this as an improvement, but I have left a few comments about gaps that the fix has exposed and/or potentially made a little worse.

@navareamol
navareamol added this pull request to the merge queue Oct 29, 2026
Merged via the queue into main with commit c883e33 Oct 29, 2026
34 checks passed
@navareamol
navareamol deleted the fix/516-cassandra-transact-stream-records branch October 29, 2026 19:59
LeeroyHannigan added a commit that referenced this pull request Oct 31, 2026
The case was skipped on Cassandra because its transaction path wrote no
stream record for any operation. #576 changed that, so the skip's reason
no longer holds. On Cassandra the case passes, and without the
removal-only fix it fails with an INSERT record for the removed key.
LeeroyHannigan added a commit that referenced this pull request Oct 31, 2026
The doc comment on commit_single_operation said COMMIT cannot tell
PREPARE's marker row from an item that was already there. Since #576
COMMIT re-reads the row together with created_to_prepare, which does
tell them apart. The decision is made in PREPARE and recorded in the
ledger because recovery replays from the ledger, which carries
item_data and not the update's actions.
LeeroyHannigan added a commit that referenced this pull request Oct 31, 2026
The case was skipped on Cassandra because its transaction path wrote no
stream record for any operation. #576 changed that, so the skip's reason
no longer holds. On Cassandra the case passes, and without the
removal-only fix it fails with an INSERT record for the removed key.
LeeroyHannigan added a commit that referenced this pull request Oct 31, 2026
The doc comment on commit_single_operation said COMMIT cannot tell
PREPARE's marker row from an item that was already there. Since #576
COMMIT re-reads the row together with created_to_prepare, which does
tell them apart. The decision is made in PREPARE and recorded in the
ledger because recovery replays from the ledger, which carries
item_data and not the update's actions.
@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
@navareamol navareamol added the release-blocker Must ship for its milestone's release label Nov 3, 2026
LeeroyHannigan added a commit that referenced this pull request Nov 5, 2026
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.
Dodothereal pushed a commit to Dodothereal/extenddb that referenced this pull request Nov 6, 2026
…ExtendDB#513)

* fix(transact): write nothing when a removal-only update finds no item

A TransactWriteItems Update whose actions are all REMOVE or DELETE, on a
key that holds no item, created an item holding only the key. Amazon
DynamoDB writes nothing for such an update: no item, no index entry and
no stream record, while the transaction's other items are written as
before and ConsumedCapacity reports the same 2.0 capacity units as a
SET. The update's own condition still runs, so a condition that fails
cancels the transaction.

Each backend has its own transaction update path, so the single-item
decision in extenddb_core::expression::removes_only did not reach them.
Every path now applies it after the actions have run against the
key-only image, so validation errors are raised exactly as before, and
returns no images, which keeps the stream record and the index work out
of the operation.

PostgreSQL reserves the key first, the way a delete of a missing item
does, so a concurrent create cannot commit between the condition check
and the end of the transaction. Cassandra decides in PREPARE, which is
the phase that reads the pre-image: its marker row carries the key in
item_data, so COMMIT cannot tell that row from an item that was already
there. PREPARE records no post-image for the update, and COMMIT and
recovery then delete the marker instead of writing it.

The new wire tests cover the removal-only shapes on both key shapes, the
conditions, ReturnValuesOnConditionCheckFailure, ConsumedCapacity TOTAL
and INDEXES, ReturnItemCollectionMetrics, ClientRequestToken replay and
reuse, index entries, streams, the shapes that must still create the
item, and the existing-item paths. The stream case is skipped on the
Cassandra backend, which writes no stream record for any transaction
operation. Every expected response was measured against Amazon DynamoDB
in us-east-1 on 2026-10-24.

Fixes ExtendDB#510

* test(transact): a removal-only update of a missing item does not write skew

Two transactions each run a conditional removal-only Update on a key the
other one creates. The update writes nothing, but its condition read that the
key was absent, so at most one of the two commits. Measured on Amazon
DynamoDB on 2026-10-24: none of 40 rounds committed both. On PostgreSQL this
is the case the key reservation on the removal-only path exists for.

* test(transact): run the removal-only stream case on Cassandra

The case was skipped on Cassandra because its transaction path wrote no
stream record for any operation. ExtendDB#576 changed that, so the skip's reason
no longer holds. On Cassandra the case passes, and without the
removal-only fix it fails with an INSERT record for the removed key.

* docs(storage-cassandra): say why PREPARE records a removal-only update

The doc comment on commit_single_operation said COMMIT cannot tell
PREPARE's marker row from an item that was already there. Since ExtendDB#576
COMMIT re-reads the row together with created_to_prepare, which does
tell them apart. The decision is made in PREPARE and recorded in the
ledger because recovery replays from the ledger, which carries
item_data and not the update's actions.
LeeroyHannigan added a commit that referenced this pull request Nov 10, 2026
Main is 247 commits ahead of the branch point (744ea29), and the
merge is clean. crates/engine/src/transact_write_items.rs changed on
both sides. Main checks the attribute name sizes of every member before
the table lookups (#433) and rewords the comment on stream records
(#576). This branch passes the two Return fields to compute_fingerprint
and changes the mismatch message.

Main adds the PartiQL ExecuteStatement, BatchExecuteStatement and
ExecuteTransaction operations (#411). For an ExecuteTransaction write,
crates/engine/src/partiql/transaction.rs builds a TransactWriteItems
body from the statements. It copies the request's ClientRequestToken
and ReturnConsumedCapacity into that body and passes the body to
handle_transact_write_items. With this branch, the fingerprint of the
body covers ReturnConsumedCapacity. An ExecuteTransaction retry that
keeps the token and the statements but changes ReturnConsumedCapacity
now answers IdempotentParameterMismatchException, where main serves it
as a replay. Amazon DynamoDB answers the mismatch to three such
retries: TOTAL then no field, no field then TOTAL, TOTAL then INDEXES
(us-east-1, 2026-11-10, two sends each). remap_write_error in
the same file rewrites the mismatch message to the text that the
classic handler now returns.
parsnips pushed a commit to parsnips/extenddb that referenced this pull request Nov 13, 2026
…xtendDB#475)

* fix(mongodb): retry a write conflict on the stream sequence counter

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 ExtendDB#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 ExtendDB#437

* fix(mongodb): one answer for every single-item write that spends its 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 ExtendDB#437

* test(mongodb): cover the contended batch request in both positions

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 ExtendDB#437

* fix(engine): BatchWriteItem checks the whole batch before it writes

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.

* test(engine): pin the batch answer to an item a transaction holds

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.

* fix(engine): BatchWriteItem tries every request, 503 if none applied

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.

* fix(mongodb): the exhausted-budget error carries the last cause

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.

* test: transactions on a stream table, bounded batch replay

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.

* docs(mongodb): match the retry and exhaustion text to the code

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.

* test: pin every BatchWriteItem request check before the first write

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.

* docs: narrow the batch and retry text to what the code does

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.

* test: accept Cassandra's answers in the stream contention tests

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 ExtendDB#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.

* test: expect transacted stream records on Cassandra too

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 ExtendDB#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.

* test: check the message of each rejected batch in the order tests

tests/test_batch_write_validation_order.py checked only the error code
of each rejected batch. Each test now also checks Error.Message against
the text that Amazon DynamoDB answered to the same batch in us-east-1
on 2026-11-10. Each batch went out twice and got the same answer both
times.

- A key that does not match the schema: "The provided key element does
  not match the schema". This covers a put in the same table, after a
  delete and in a second table, and a delete with an extra key
  attribute.
- A put to a table that does not exist: "Requested resource not found".
- Two puts of one key in a second table: "Provided list of item keys
  contains duplicates".
- A put of 401 KB: "Item size has exceeded the maximum allowed size".

ExtendDB answers the same text in each case, so no server message
changes.

* fix(engine): BatchWriteItem checks secondary index keys before it writes

validate_request did not run validate_index_keys. Only the storage
layer ran that check, inside put_item. The check refuses a global or
local secondary index key of the wrong type, and an empty string or
binary key. A put failed it only when the handler wrote that put. The
requests ahead of it were already applied when the batch answered 400.

Amazon DynamoDB refuses such a batch with nothing applied. The
measurement ran in us-east-1 on 2026-11-10, two sends each. The table
had the key pk (S) and a global secondary index by-g on g (S). A valid
put came first in each batch, and it was not applied:

- g as a number: 400 ValidationException "One or more parameter values
  were invalid: Type mismatch for Index Key g Expected: S Actual: N
  IndexName: by-g".
- g as 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".

validate_request now builds the index key references from the global
and local secondary indexes in the table's key info and calls
validate_index_keys. So check_batch refuses the batch before the first
write. The storage-side check stays. It reads the indexes at write
time, so it also covers an index that an UpdateTable added after the
lookup. The doc comments of write_batch name that index as the one case
in which the handler finds a request fault after a request applied.

The local secondary index path was not measured. It goes through the
same validate_index_keys call. Its engine test checks the 400 and that
the storage double recorded no write, and not the message.

write_batch_tests.rs gets four engine tests. Two cover a global
secondary index key of the wrong type and an empty one, with the
measured messages. One covers a local secondary index key of the wrong
type. One writes a batch with valid index keys.
tests/test_batch_write_validation_order.py gets
test_valid_put_before_a_faulty_gsi_key_is_not_applied with the two
measured cases.

* test: resend a 503 in the stream churn test

test_racing_puts_and_deletes_on_a_stream_table_all_succeed failed on
any error. On the MongoDB backend all 8 writers conflict on the stream
sequence counter. A write that does not commit within the server's 50
attempts answers 503 ServiceUnavailable with nothing applied. A busy CI
runner can produce that answer. This branch documents the 503, and the
batch and UpdateItem tests in the same file accept it.

The churn test now sends a write that answered 503 again, up to 20
times, with the exponential backoff and jitter of
tests/test_concurrency.py. A 500, any other error and a 503 after the
last resend still fail the test. A stream record count that differs
from the writes that changed an item fails it too. A 503 means that
the server applied nothing, so a resend cannot write a second stream
record.

Amazon DynamoDB answered 200 to every contended single-item write in
the measurements of 2026-10-23 (us-east-1, client retries off, up to 64
writers on one key). So the resend does not change the test against the
service.

* refactor(engine): tidy the BatchWriteItem loop and its comments

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.

* docs: note the unmeasured capacity answer of a partly applied batch

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.

* test: check that a batch with two faults reports the first

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.

* test: count the churn writes that needed a resend

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

Cassandra: TransactWriteItems writes no stream record

3 participants