diff --git a/crates/engine/src/partiql/transaction.rs b/crates/engine/src/partiql/transaction.rs index 08300594c..25316f98f 100644 --- a/crates/engine/src/partiql/transaction.rs +++ b/crates/engine/src/partiql/transaction.rs @@ -16,7 +16,8 @@ //! rejection, and `ClientRequestToken` idempotency). It translates each //! PartiQL statement into the corresponding transact member, cancels the write //! form with positional reasons when a member cannot be translated against its -//! table, and remaps two error strings the PartiQL surface words differently. +//! table, and remaps the cancellation reason of a duplicate-key `INSERT`, which +//! the PartiQL surface words differently. //! //! The members are authorized after the checks of their form (see //! `authorize_members`). In an all-read transaction, a member on a table @@ -497,13 +498,14 @@ fn reshape_write(result: DispatchResult) -> DispatchResult { } } -/// Remap the two write errors the PartiQL surface words differently from the +/// Remap the write error the PartiQL surface words differently from the /// classic `TransactWriteItems` handler. /// /// A duplicate-key `INSERT` fails the underlying `Put`'s `attribute_not_exists` /// condition, which the handler reports as `ConditionalCheckFailed`; the PartiQL /// surface reports `DuplicateItem` for that position. A reused idempotency token -/// with a different body uses the PartiQL message. +/// with a different body passes through: both surfaces answer it with +/// `transact_write_helpers::IDEMPOTENT_MISMATCH_MESSAGE`. fn remap_write_error(err: DynamoDbError, is_insert: &[bool]) -> DynamoDbError { match err { DynamoDbError::TransactionCanceledException { @@ -518,12 +520,6 @@ fn remap_write_error(err: DynamoDbError, is_insert: &[bool]) -> DynamoDbError { } cancellation(reasons) } - DynamoDbError::IdempotentParameterMismatchException(_) => { - DynamoDbError::IdempotentParameterMismatchException( - "Specified idempotent token was used with different request parameters within the idempotency window" - .to_owned(), - ) - } other => other, } } diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 8295ef6db..2a09d062a 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -9,8 +9,8 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ExpressionMaps, PathElement, UpdateAction}; use extenddb_core::types::{ - ReturnItemCollectionMetrics, ReturnValuesOnConditionCheckFailure, TableKeyInfo, - attribute_value_size, extract_key, item_size_bytes, + ReturnConsumedCapacity, ReturnItemCollectionMetrics, ReturnValuesOnConditionCheckFailure, + TableKeyInfo, attribute_value_size, extract_key, item_size_bytes, }; use extenddb_storage::TransactWriteOp; use hmac::{Hmac, Mac}; @@ -260,14 +260,51 @@ pub(crate) fn validate_client_request_token(token: &str) -> Result<(), DynamoDbE Ok(()) } -/// Compute a collision-resistant fingerprint of the transaction operations. +/// The message of the `IdempotentParameterMismatchException` that a request +/// answers when its token was used by a different request inside the +/// idempotency window. `TransactWriteItems` and `ExecuteTransaction` both +/// answer with it. +pub(crate) const IDEMPOTENT_MISMATCH_MESSAGE: &str = "Specified idempotent token was used with \ + different request parameters within the idempotency window"; + +/// Compute a collision-resistant fingerprint of the transaction request. /// /// Uses HMAC-SHA256 keyed by the client request token over the JSON-serialized -/// `TransactItems` array. The keyed hash prevents an attacker from crafting a +/// `TransactItems` array, followed by the request's `ReturnConsumedCapacity` +/// and `ReturnItemCollectionMetrics` values. The service compares those two +/// fields on a token replay and treats an absent field as `NONE`, so each +/// field contributes to the hash only when it is not `NONE`. An +/// `ExecuteTransaction` write calls `handle_transact_write_items` with its +/// `ReturnConsumedCapacity`, so this fingerprint decides its replays too. +/// +/// Versions before this change hashed the items alone. A retry replays only +/// when its fingerprint equals the stored one. A token stored before an +/// upgrade or a downgrade therefore answers as follows while the backend +/// keeps it: +/// - A token stored for a request with neither field, or with both set to +/// `NONE`, has the same fingerprint in both versions. An identical retry +/// replays in both directions. +/// - A token that an earlier version stored for a request with `TOTAL`, +/// `INDEXES` or `SIZE` answers `IdempotentParameterMismatchException` to an +/// identical retry on this version. A retry without the field replays. +/// - A token that this version stored for a request with `TOTAL`, `INDEXES` +/// or `SIZE` answers `IdempotentParameterMismatchException` to every retry +/// on an earlier version. This includes an identical retry and a retry +/// without the field. +/// +/// PostgreSQL, SQLite and MongoDB keep a token for 10 minutes. Cassandra +/// keeps it with no expiry. +/// +/// The keyed hash prevents an attacker from crafting a /// different request body that produces the same fingerprint for a given token. /// The result is truncated to 16 hex chars (64 bits) for storage efficiency /// while remaining collision-resistant for the idempotency use case. -pub(crate) fn compute_fingerprint(body: &Value, token: &str) -> String { +pub(crate) fn compute_fingerprint( + body: &Value, + token: &str, + return_consumed_capacity: ReturnConsumedCapacity, + return_item_collection_metrics: ReturnItemCollectionMetrics, +) -> String { let items = body.get("TransactItems").unwrap_or(&Value::Null); // serde_json::to_string on a Value is infallible — all Value variants // are representable as JSON. Using unwrap_or_default as a defensive fallback. @@ -278,6 +315,17 @@ pub(crate) fn compute_fingerprint(body: &Value, token: &str) -> String { let mut mac = Hmac::::new_from_slice(token.as_bytes()).expect("HMAC accepts any key length"); mac.update(json.as_bytes()); + // The items JSON is a complete JSON value, so a suffix that is not JSON + // cannot coincide with the serialization of another items array. + match return_consumed_capacity { + ReturnConsumedCapacity::None => {} + ReturnConsumedCapacity::Total => mac.update(b"\nReturnConsumedCapacity=TOTAL"), + ReturnConsumedCapacity::Indexes => mac.update(b"\nReturnConsumedCapacity=INDEXES"), + } + match return_item_collection_metrics { + ReturnItemCollectionMetrics::None => {} + ReturnItemCollectionMetrics::Size => mac.update(b"\nReturnItemCollectionMetrics=SIZE"), + } let result = mac.finalize().into_bytes(); hex::encode(&result[..8]) } @@ -343,11 +391,18 @@ mod tests { assert!(validate_client_request_token("abc!").is_err()); } + const NO_RCC: ReturnConsumedCapacity = ReturnConsumedCapacity::None; + const NO_RICM: ReturnItemCollectionMetrics = ReturnItemCollectionMetrics::None; + + fn fp(body: &Value, token: &str) -> String { + compute_fingerprint(body, token, NO_RCC, NO_RICM) + } + #[test] fn fingerprint_deterministic() { let body: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t"}}]}); - let a = compute_fingerprint(&body, "tok-1"); - let b = compute_fingerprint(&body, "tok-1"); + let a = fp(&body, "tok-1"); + let b = fp(&body, "tok-1"); assert_eq!(a, b); } @@ -355,18 +410,119 @@ mod tests { fn fingerprint_differs_for_different_ops() { let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]}); let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]}); - assert_ne!( - compute_fingerprint(&a, "tok-1"), - compute_fingerprint(&b, "tok-1") - ); + assert_ne!(fp(&a, "tok-1"), fp(&b, "tok-1")); + } + + /// A Return field is added to the hashed items, so a retry that sets the + /// field and changes the items is a mismatch, not a replay. + #[test] + fn fingerprint_differs_for_different_ops_with_total() { + let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]}); + let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]}); + let total = + |body| compute_fingerprint(body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM); + assert_ne!(total(&a), total(&b)); + } + + #[test] + fn fingerprint_differs_for_different_ops_with_size() { + let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]}); + let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]}); + let size = + |body| compute_fingerprint(body, "tok-1", NO_RCC, ReturnItemCollectionMetrics::Size); + assert_ne!(size(&a), size(&b)); } #[test] fn fingerprint_differs_for_different_tokens() { let body: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t"}}]}); - assert_ne!( - compute_fingerprint(&body, "tok-1"), - compute_fingerprint(&body, "tok-2") + assert_ne!(fp(&body, "tok-1"), fp(&body, "tok-2")); + } + + /// The value stored for this body and token by 744ea291, whose fingerprint + /// hashed `TransactItems` alone. A request with neither Return field, or + /// with both set to NONE, must keep producing it so tokens stored before + /// the upgrade still replay. + const PINNED_ITEMS_ONLY: &str = "ef18f4e7c37d6b12"; + + /// The values this version stores for this body and token when a Return + /// field is set. A later version must keep producing them so these tokens + /// replay after an upgrade, which fixes the suffix bytes and their order. + const PINNED_TOTAL: &str = "8fa51ffc1314a046"; + const PINNED_INDEXES: &str = "ee2c3412f0fdbdf1"; + const PINNED_SIZE: &str = "70eb830c93e9079f"; + const PINNED_TOTAL_SIZE: &str = "e9957d3c7431e1d4"; + + /// Keys are written in sorted order at every level so the serialized + /// JSON is the same whether serde_json sorts map keys or preserves + /// insertion order (the MongoDB build enables `preserve_order` through + /// bson). + fn pinned_body() -> Value { + serde_json::json!({"TransactItems": [{"Put": {"Item": {"pk": {"S": "a"}}, "TableName": "t"}}]}) + } + + #[test] + fn fingerprint_items_only_keeps_stored_value() { + assert_eq!(fp(&pinned_body(), "tok-1"), PINNED_ITEMS_ONLY); + } + + #[test] + fn fingerprint_with_return_fields_keeps_stored_values() { + let body = pinned_body(); + let f = |rcc, ricm| compute_fingerprint(&body, "tok-1", rcc, ricm); + let total = ReturnConsumedCapacity::Total; + let indexes = ReturnConsumedCapacity::Indexes; + let size = ReturnItemCollectionMetrics::Size; + assert_eq!(f(total, NO_RICM), PINNED_TOTAL, "TOTAL"); + assert_eq!(f(indexes, NO_RICM), PINNED_INDEXES, "INDEXES"); + assert_eq!(f(NO_RCC, size), PINNED_SIZE, "SIZE"); + assert_eq!(f(total, size), PINNED_TOTAL_SIZE, "TOTAL with SIZE"); + } + + #[test] + fn fingerprint_none_equals_absent() { + let mut body = pinned_body(); + body["ReturnConsumedCapacity"] = Value::String("NONE".to_owned()); + body["ReturnItemCollectionMetrics"] = Value::String("NONE".to_owned()); + assert_eq!( + compute_fingerprint( + &body, + "tok-1", + ReturnConsumedCapacity::None, + ReturnItemCollectionMetrics::None + ), + PINNED_ITEMS_ONLY + ); + } + + #[test] + fn fingerprint_differs_for_return_consumed_capacity() { + let body = pinned_body(); + let total = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM); + let indexes = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Indexes, NO_RICM); + assert_ne!(total, PINNED_ITEMS_ONLY); + assert_ne!(indexes, PINNED_ITEMS_ONLY); + assert_ne!(total, indexes); + assert_eq!( + total, + compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM) + ); + } + + #[test] + fn fingerprint_differs_for_return_item_collection_metrics() { + let body = pinned_body(); + let size = compute_fingerprint(&body, "tok-1", NO_RCC, ReturnItemCollectionMetrics::Size); + let both = compute_fingerprint( + &body, + "tok-1", + ReturnConsumedCapacity::Total, + ReturnItemCollectionMetrics::Size, ); + let total = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM); + assert_ne!(size, PINNED_ITEMS_ONLY); + assert_ne!(size, total); + assert_ne!(both, total); + assert_ne!(both, size); } } diff --git a/crates/engine/src/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index 360ed2ffa..fb19f56c1 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -15,7 +15,8 @@ use crate::request_limits; use crate::serialize_output; use crate::stream_capture; use crate::transact_write_helpers::{ - PreparedOp, compute_fingerprint, validate_client_request_token, validate_no_key_updates, + IDEMPOTENT_MISMATCH_MESSAGE, PreparedOp, compute_fingerprint, validate_client_request_token, + validate_no_key_updates, }; use crate::{DispatchMetrics, DispatchResult}; use extenddb_core::error::DynamoDbError; @@ -48,11 +49,20 @@ pub async fn handle_transact_write_items( serde_json::from_value(body.clone()).map_err(crate::deserialize_error)?; // Compute fingerprint keyed by the client request token for collision - // resistance. Must happen after parsing so the token is available. + // resistance. Must happen after parsing so the token is available. The + // two Return fields are part of the fingerprint: the service refuses a + // replay that changes either of them. let fingerprint = input .client_request_token .as_deref() - .map(|t| compute_fingerprint(&body, t)) + .map(|t| { + compute_fingerprint( + &body, + t, + input.return_consumed_capacity, + input.return_item_collection_metrics, + ) + }) .unwrap_or_default(); // At least one and at most 100 items. The server runs the same check @@ -228,9 +238,7 @@ pub async fn handle_transact_write_items( } Err(extenddb_storage::error::StorageError::IdempotentMismatch) => { return Err(DynamoDbError::IdempotentParameterMismatchException( - "The request uses the same client token as a previous, \ - but different, request." - .to_owned(), + IDEMPOTENT_MISMATCH_MESSAGE.to_owned(), )); } Err(e) => return Err(storage_err_to_dynamo(e)), diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index 2e75cb64e..92b651850 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -343,7 +343,7 @@ Storage backends write stream records atomically with data writes when `stream` - `ConditionFailed { old_item: Option }` — condition expression evaluated to false - `TransactionCanceled(Vec)` — transaction failed with per-item reasons - `IdempotentReplay` — idempotency token matched previous request -- `IdempotentMismatch` — idempotency token exists with different operations +- `IdempotentMismatch`: idempotency token exists with a different fingerprint (the items or a Return field) - `IndexNotFound` — secondary index does not exist - `Internal(String)` — backend-specific error @@ -832,6 +832,22 @@ account in DynamoDB, so the same token value from two accounts never collides. If a request arrives with the same `(account_id, token)` but a different fingerprint, return `IdempotentParameterMismatchException`. +The fingerprint (`compute_fingerprint` in +`crates/engine/src/transact_write_helpers.rs`) is an HMAC-SHA256 keyed by the +token. It hashes the request's `TransactItems` JSON, then its +`ReturnConsumedCapacity` and `ReturnItemCollectionMetrics`. Each of the two +fields adds to the hashed input only when it is not `NONE`. The service treats +an absent field as `NONE` and refuses a replay that changes either field. The +stored value is the first 64 bits of the HMAC, as 16 hex characters. For a +`TransactWriteItems` request, the fingerprint hashes the items as the request +writes them. Some retries that the service replays therefore answer the +mismatch in ExtendDB (see "Transactions" in +`docs/differences-from-dynamodb.md`). ExtendDB translates an +`ExecuteTransaction` write into a `TransactWriteItems` request before it +computes the fingerprint. It builds the `TransactItems` from the parsed +statements and copies the request's token and `ReturnConsumedCapacity`. The +same fingerprint then decides the replays of the write. + ## 10. Backend Plugin Architecture ExtendDB uses a factory pattern with compile-time registration to enable diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index c44479284..099c997ad 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -204,6 +204,23 @@ alone, with the same wording. For PartiQL this holds in `ExecuteStatement`, | Warm throughput | Pre-provisions partitions to the requested read and write units; raising it is a long-running operation (`Status: UPDATING` for minutes, the previous values reported meanwhile); a request above the account's table maximum is `LimitExceededException` | Stored and reported with the same shape, defaults and validation so clients that read it (the Terraform AWS provider since 6.13.0) work: the previous values are reported with `Status: UPDATING` for `control_plane_delay_seconds` after a change, then the new values `ACTIVE`; a decrease is measured against the reported values, as on the service. Nothing acts on the values: no pre-warming and no scaling at the database level. The account maximum is not known to ExtendDB and is not enforced. A provisioned table whose warm throughput was never set, or was set on one side only, reports its new units at once after a capacity change, where the service reports the old units until the table is `ACTIVE`. Switching a table to `PAY_PER_REQUEST` stores 12000 read and 4000 write units where its warm throughput is lower, and the stored values stay after a switch back to `PROVISIONED`, as on the service; the response to the switch reads the new values with `Status: UPDATING` for `control_plane_delay_seconds`, where the service answers with the previous values and `Status: ACTIVE` | | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | +## Transactions + +ExtendDB decides whether a `TransactWriteItems` request, or an +`ExecuteTransaction` write, with a known `ClientRequestToken` is a replay. It +compares a fingerprint of the `TransactItems` JSON, `ReturnConsumedCapacity` +and `ReturnItemCollectionMetrics` with the fingerprint stored for the token. +For an `ExecuteTransaction` write, ExtendDB builds the `TransactItems` from the +parsed statements. The service compares the parsed request. + +| Area | DynamoDB | ExtendDB | +|------|----------|------| +| `TransactWriteItems` token retry that changes only the spelling of a number (`1` and `1.0`) or the spacing of an expression | Replays it (measured 2026-10-24) | Answers `IdempotentParameterMismatchException`, because the fingerprint hashes the `TransactItems` JSON as the request writes it (measured on SQLite) | +| `TransactWriteItems` token retry that names an attribute through an `ExpressionAttributeNames` alias, or adds `ReturnValuesOnConditionCheckFailure: NONE` inside an item | Replays it (measured 2026-10-24) | Answers `IdempotentParameterMismatchException`, for the same reason (measured on SQLite) | +| `TransactWriteItems` token retry whose item lists the same attributes in another key order | Answers 200, as it does to an identical retry (measured 2026-11-10) | Replays in a build without the MongoDB backend, where serde_json writes map keys in sorted order. A build with the MongoDB backend keeps map keys in request order (bson enables serde_json's `preserve_order`), so the retry answers `IdempotentParameterMismatchException` *(from the code)* | +| Unknown top-level field in `TransactWriteItems` | A raw signed request with the field answers 200 and writes the item (measured 2026-11-10) | Refused with `SerializationException` "Start of structure or map found where not expected: unknown field ..." (measured on SQLite) | +| `ReturnItemCollectionMetrics: SIZE` on the first call, table without a local secondary index | `{"ItemCollectionMetrics": {}}` (measured 2026-11-10) | `{}`, without the key (measured on SQLite) | + ## PartiQL ExtendDB implements `ExecuteStatement`, `BatchExecuteStatement`, and diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index f0f5105a9..cf9a493eb 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -1232,6 +1232,51 @@ DescribeStream and GetShardIterator now refuse a client-built `StreamArn` with t --- +### v1.1.0: a `ClientRequestToken` retry compares `ReturnConsumedCapacity` and `ReturnItemCollectionMetrics` + +**What changed.** `TransactWriteItems` decides whether a request with a known +`ClientRequestToken` is a replay. It compares a fingerprint of the request with +the fingerprint stored for the token. Before this release the fingerprint +covered `TransactItems` only. It now also covers `ReturnConsumedCapacity` when +the value is `TOTAL` or `INDEXES`, and `ReturnItemCollectionMetrics` when the +value is `SIZE`. A retry that keeps the token and the items but changes either +field now answers `IdempotentParameterMismatchException`, as Amazon DynamoDB +does (measured 2026-10-24). Earlier releases served it as a replay. A request +with neither field, or with both set to `NONE`, has the same fingerprint as in +earlier releases. An `ExecuteTransaction` write uses the same fingerprint with +the request's `ReturnConsumedCapacity`, and the service answers its retries the +same way (measured 2026-11-10). + +**Who is affected.** Clients that retry a `TransactWriteItems` or +`ExecuteTransaction` request with the same token across an upgrade or a +downgrade. The change affects requests that set `ReturnConsumedCapacity` to +`TOTAL` or `INDEXES`, or `ReturnItemCollectionMetrics` to `SIZE`. 0.1.15 and +1.0.0 serve `ExecuteTransaction` with the earlier fingerprint. A token that +either release stored for an `ExecuteTransaction` write therefore gets the same +answers as one stored for a `TransactWriteItems` request. + +**Impact.** After an upgrade, a token that the earlier release stored for such +a request answers `IdempotentParameterMismatchException` to an identical retry. +The server replays a retry without the field. After a downgrade, a token that +this release stored for such a request answers +`IdempotentParameterMismatchException` to every retry. This includes an +identical retry and a retry without the field. A token for a request with +neither field, or with both set to `NONE`, replays in both directions. On +PostgreSQL, MongoDB and Cassandra nothing stops servers of both releases from +sharing one database during a rolling upgrade (see the deployment guide's +[Multi-Instance Considerations](11-deployment-guide.md#multi-instance-considerations)). +A retry that reaches a server of the other release then gets the same answers. +On SQLite, run the two releases one after the other. On Linux and macOS a +second server refuses to start while another process holds the lock on +`.lock`. On Windows the server takes no lock (#642). PostgreSQL, +SQLite and MongoDB keep a token for 10 minutes. On those backends every token +that the release you upgrade or downgrade from stored expires at most 10 +minutes after its last server stops. The Cassandra backend does not expire +tokens, so there a later retry with such a token gets these answers at any time. +No catalog migration is required. + +--- + ## License Copyright 2026 ExtendDB contributors. Licensed under the Apache License, Version 2.0. diff --git a/tests/test_partiql_transaction.py b/tests/test_partiql_transaction.py index 7254e05d9..1de53efdc 100644 --- a/tests/test_partiql_transaction.py +++ b/tests/test_partiql_transaction.py @@ -287,6 +287,54 @@ def test_idempotent_replay_and_mismatch(dynamodb_client, ttable): ) +# A replay with the same token and statements is compared on +# ReturnConsumedCapacity too, an absent field being NONE (measured 2026-11-10, +# two sends each). + +_IDEMPOTENT_MISMATCH = ( + "IdempotentParameterMismatchException", + "Specified idempotent token was used with different request parameters within the idempotency window", +) + + +def _insert_one(table): + pk = f"t5rcc-{uuid.uuid4().hex[:12]}" + return [{"Statement": f"INSERT INTO \"{table}\" VALUE {{'pk':'{pk}','sk':'s1','a':1}}"}] + + +@pytest.mark.parametrize( + ("first", "replay"), + [ + pytest.param({"ReturnConsumedCapacity": "TOTAL"}, {}, id="total-then-absent"), + pytest.param({}, {"ReturnConsumedCapacity": "TOTAL"}, id="absent-then-total"), + pytest.param( + {"ReturnConsumedCapacity": "TOTAL"}, + {"ReturnConsumedCapacity": "INDEXES"}, + id="total-then-indexes", + ), + ], +) +def test_idempotent_replay_with_another_return_consumed_capacity_is_a_mismatch( + dynamodb_client, ttable, first, replay +): + token = uuid.uuid4().hex + statements = _insert_one(ttable) + resp = _txn(dynamodb_client, statements, ClientRequestToken=token, **first) + assert resp["Responses"] == [] + with pytest.raises(ClientError) as excinfo: + _txn(dynamodb_client, statements, ClientRequestToken=token, **replay) + assert _error(excinfo) == _IDEMPOTENT_MISMATCH + + +def test_idempotent_replay_without_return_consumed_capacity(dynamodb_client, ttable): + token = uuid.uuid4().hex + statements = _insert_one(ttable) + for _ in range(2): + resp = _txn(dynamodb_client, statements, ClientRequestToken=token) + resp.pop("ResponseMetadata", None) + assert resp == {"Responses": []} + + # --- T6: conflicting keys (request-level) --------------------------------- diff --git a/tests/test_transact_token_return_fields.py b/tests/test_transact_token_return_fields.py new file mode 100644 index 000000000..d05ff95f4 --- /dev/null +++ b/tests/test_transact_token_return_fields.py @@ -0,0 +1,313 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""TransactWriteItems token replay and the two Return fields. + +A ClientRequestToken replay is compared against the first request by +TransactItems, ReturnConsumedCapacity and ReturnItemCollectionMetrics. An +absent Return field is NONE. A replay that changes either field answers +IdempotentParameterMismatchException with the message + + Specified idempotent token was used with different request parameters + within the idempotency window + +On a table without a local secondary index, a replay with matching +fields answers 200 and reports the replay as a transactional read +(ReadCapacityUnits, no WriteCapacityUnits) when ReturnConsumedCapacity +asks for capacity, and carries no ItemCollectionMetrics. An invalid enum +value on the replay is refused by validation before the token is +compared. + +The expected answers were measured against Amazon DynamoDB in us-east-1, +client retries off, on 2026-10-24 (17:31 UTC and 17:36 UTC), except as +follows. The answers and reads of +test_changed_items_with_the_same_return_field_is_a_mismatch were +measured on 2026-11-10, two sends for each parameter. Two other tests +read the changed key back and expect no item. The read in +test_changed_items_and_return_field_is_a_mismatch was measured on +2026-10-24. The read in test_changed_items_alone_is_a_mismatch was +measured on 2026-11-10, two sends. The tests run against both Amazon +DynamoDB and ExtendDB. +""" + +from __future__ import annotations + +import uuid + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +MISMATCH = "IdempotentParameterMismatchException" +MISMATCH_MESSAGE = ( + "Specified idempotent token was used with different request parameters " + "within the idempotency window" +) +RCC_ENUM_MESSAGE = ( + "1 validation error detected: Value '{value}' at 'returnConsumedCapacity' " + "failed to satisfy constraint: Member must satisfy enum value set: " + "[INDEXES, TOTAL, NONE]" +) +RICM_ENUM_MESSAGE = ( + "1 validation error detected: Value '{value}' at 'returnItemCollectionMetrics' " + "failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE]" +) + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + with scoped_table(dynamodb_client) as name: + yield name + + +def _items(table: str, pk: str) -> list[dict]: + return [ + { + "Update": { + "TableName": table, + "Key": {"pk": {"S": pk}}, + "UpdateExpression": "SET v = :v", + "ExpressionAttributeValues": {":v": {"S": "x"}}, + } + } + ] + + +def _fresh() -> tuple[str, str]: + """Return a new (pk, token) pair.""" + return uuid.uuid4().hex[:32], f"tok-{uuid.uuid4().hex}" + + +def _call(client, table: str, pk: str, token: str, **extra) -> dict: + resp = client.transact_write_items( + TransactItems=_items(table, pk), ClientRequestToken=token, **extra + ) + resp.pop("ResponseMetadata", None) + return resp + + +def _assert_mismatch(exc: pytest.ExceptionInfo) -> None: + err = exc.value.response["Error"] + assert err["Code"] == MISMATCH + assert err["Message"] == MISMATCH_MESSAGE + + +# --------------------------------------------------------------------------- +# A changed Return field is a different request +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("first", "replay"), + [ + pytest.param({}, {"ReturnConsumedCapacity": "TOTAL"}, id="none-then-rcc-total"), + pytest.param( + {}, {"ReturnItemCollectionMetrics": "SIZE"}, id="none-then-ricm-size" + ), + pytest.param({"ReturnConsumedCapacity": "TOTAL"}, {}, id="rcc-total-then-none"), + pytest.param( + {"ReturnConsumedCapacity": "TOTAL"}, + {"ReturnConsumedCapacity": "INDEXES"}, + id="rcc-total-then-indexes", + ), + pytest.param( + {"ReturnConsumedCapacity": "INDEXES"}, + {"ReturnConsumedCapacity": "TOTAL"}, + id="rcc-indexes-then-total", + ), + pytest.param( + {"ReturnItemCollectionMetrics": "SIZE"}, + {"ReturnItemCollectionMetrics": "NONE"}, + id="ricm-size-then-none", + ), + pytest.param( + {}, + {"ReturnConsumedCapacity": "TOTAL", "ReturnItemCollectionMetrics": "SIZE"}, + id="none-then-both", + ), + ], +) +def test_changed_return_field_is_a_mismatch(dynamodb_client, table, first, replay): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token, **first) + with pytest.raises(ClientError) as exc: + _call(dynamodb_client, table, pk, token, **replay) + _assert_mismatch(exc) + + +def test_changed_items_and_return_field_is_a_mismatch(dynamodb_client, table): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token) + with pytest.raises(ClientError) as exc: + _call(dynamodb_client, table, pk + "-b", token, ReturnConsumedCapacity="TOTAL") + _assert_mismatch(exc) + assert "Item" not in dynamodb_client.get_item( + TableName=table, Key={"pk": {"S": pk + "-b"}}, ConsistentRead=True + ) + + +def test_changed_items_alone_is_a_mismatch(dynamodb_client, table): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token) + with pytest.raises(ClientError) as exc: + _call(dynamodb_client, table, pk + "-b", token) + _assert_mismatch(exc) + assert "Item" not in dynamodb_client.get_item( + TableName=table, Key={"pk": {"S": pk + "-b"}}, ConsistentRead=True + ) + + +@pytest.mark.parametrize( + "fields", + [ + pytest.param({"ReturnConsumedCapacity": "TOTAL"}, id="rcc-total"), + pytest.param({"ReturnItemCollectionMetrics": "SIZE"}, id="ricm-size"), + ], +) +def test_changed_items_with_the_same_return_field_is_a_mismatch( + dynamodb_client, table, fields +): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token, **fields) + with pytest.raises(ClientError) as exc: + _call(dynamodb_client, table, pk + "-b", token, **fields) + _assert_mismatch(exc) + assert "Item" not in dynamodb_client.get_item( + TableName=table, Key={"pk": {"S": pk + "-b"}}, ConsistentRead=True + ) + + +# --------------------------------------------------------------------------- +# An absent Return field is NONE +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("first", "replay"), + [ + pytest.param({}, {}, id="same-body"), + pytest.param({}, {"ReturnConsumedCapacity": "NONE"}, id="none-then-rcc-none"), + pytest.param( + {}, {"ReturnItemCollectionMetrics": "NONE"}, id="none-then-ricm-none" + ), + pytest.param( + {"ReturnConsumedCapacity": "NONE", "ReturnItemCollectionMetrics": "NONE"}, + {}, + id="both-none-then-absent", + ), + ], +) +def test_none_and_absent_replay(dynamodb_client, table, first, replay): + pk, token = _fresh() + assert _call(dynamodb_client, table, pk, token, **first) == {} + assert _call(dynamodb_client, table, pk, token, **replay) == {} + + +# --------------------------------------------------------------------------- +# The matching replay's body +# --------------------------------------------------------------------------- + + +def test_matching_replay_total_reports_read_capacity(dynamodb_client, table): + pk, token = _fresh() + first = _call(dynamodb_client, table, pk, token, ReturnConsumedCapacity="TOTAL") + assert first["ConsumedCapacity"] == [ + {"TableName": table, "CapacityUnits": 2.0, "WriteCapacityUnits": 2.0} + ] + replay = _call(dynamodb_client, table, pk, token, ReturnConsumedCapacity="TOTAL") + assert replay == { + "ConsumedCapacity": [ + {"TableName": table, "CapacityUnits": 2.0, "ReadCapacityUnits": 2.0} + ] + } + + +def test_matching_replay_indexes_reports_read_capacity(dynamodb_client, table): + pk, token = _fresh() + first = _call(dynamodb_client, table, pk, token, ReturnConsumedCapacity="INDEXES") + assert first["ConsumedCapacity"] == [ + { + "TableName": table, + "CapacityUnits": 2.0, + "WriteCapacityUnits": 2.0, + "Table": {"CapacityUnits": 2.0, "WriteCapacityUnits": 2.0}, + } + ] + replay = _call(dynamodb_client, table, pk, token, ReturnConsumedCapacity="INDEXES") + assert replay == { + "ConsumedCapacity": [ + { + "TableName": table, + "CapacityUnits": 2.0, + "ReadCapacityUnits": 2.0, + "Table": {"CapacityUnits": 2.0, "ReadCapacityUnits": 2.0}, + } + ] + } + + +def test_matching_replay_size_carries_no_metrics(dynamodb_client, table): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token, ReturnItemCollectionMetrics="SIZE") + replay = _call(dynamodb_client, table, pk, token, ReturnItemCollectionMetrics="SIZE") + assert replay == {} + + +# --------------------------------------------------------------------------- +# Validation of the Return fields runs before the token is compared +# --------------------------------------------------------------------------- + + +def _raw(client, table: str, pk: str, token: str, **extra) -> ClientError: + with pytest.raises(ClientError) as exc: + client.transact_write_items( + TransactItems=_items(table, pk), ClientRequestToken=token, **extra + ) + return exc.value + + +@pytest.mark.parametrize( + ("field", "value", "message"), + [ + pytest.param("ReturnConsumedCapacity", "total", RCC_ENUM_MESSAGE, id="rcc-lowercase"), + pytest.param("ReturnConsumedCapacity", "BOGUS", RCC_ENUM_MESSAGE, id="rcc-bogus"), + pytest.param( + "ReturnItemCollectionMetrics", "BOGUS", RICM_ENUM_MESSAGE, id="ricm-bogus" + ), + ], +) +def test_invalid_return_value_on_replay_is_a_validation_error( + dynamodb_client, dynamodb_client_no_validation, table, field, value, message +): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token) + err = _raw(dynamodb_client_no_validation, table, pk, token, **{field: value}) + assert err.response["Error"]["Code"] == "ValidationException" + assert err.response["Error"]["Message"] == message.format(value=value) + + +def test_invalid_return_value_wins_over_changed_items( + dynamodb_client, dynamodb_client_no_validation, table +): + pk, token = _fresh() + _call(dynamodb_client, table, pk, token) + err = _raw( + dynamodb_client_no_validation, + table, + pk + "-b", + token, + ReturnConsumedCapacity="BOGUS", + ) + assert err.response["Error"]["Code"] == "ValidationException" + assert err.response["Error"]["Message"] == RCC_ENUM_MESSAGE.format(value="BOGUS") + + +def test_invalid_return_value_without_token(dynamodb_client_no_validation, table): + pk = uuid.uuid4().hex[:32] + with pytest.raises(ClientError) as exc: + dynamodb_client_no_validation.transact_write_items( + TransactItems=_items(table, pk), ReturnConsumedCapacity="total" + ) + assert exc.value.response["Error"]["Code"] == "ValidationException" + assert exc.value.response["Error"]["Message"] == RCC_ENUM_MESSAGE.format(value="total")