From 5391e2fb9c7d7e43fbf30dc25227581dc9fcac85 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 18:08:00 +0000 Subject: [PATCH 01/12] fix(engine): include Return fields in the TransactWriteItems token fingerprint The idempotency fingerprint hashed TransactItems only, so a replay that changed ReturnConsumedCapacity or ReturnItemCollectionMetrics was served as a replay. The service answers IdempotentParameterMismatchException for such a request and treats an absent field as NONE. Hash the two fields after the items when they are not NONE. A request with neither field, or with both NONE, keeps the value stored by earlier versions, pinned by a unit test. Use the service's mismatch message. --- crates/engine/src/transact_write_helpers.rs | 117 +++++++++++++++++--- crates/engine/src/transact_write_items.rs | 17 ++- 2 files changed, 116 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 8295ef6db..4d4375488 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,25 @@ pub(crate) fn validate_client_request_token(token: &str) -> Result<(), DynamoDbE Ok(()) } -/// Compute a collision-resistant fingerprint of the transaction operations. +/// 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`. A request with +/// neither field, or with both set to `NONE`, hashes the items alone, which +/// is the value stored by earlier versions; tokens stored before this change +/// still replay. 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 +289,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 +365,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 +384,78 @@ 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")); } #[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 by versions that hashed `TransactItems` alone, for + /// this body and token. 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"; + + /// 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_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 43fb78a1c..4d8532fd1 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -46,11 +46,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 @@ -201,8 +210,8 @@ 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." + "Specified idempotent token was used with different request parameters \ + within the idempotency window" .to_owned(), )); } From 386a775a6209265b906c59c549c5919d5f7cbf9e Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 18:08:00 +0000 Subject: [PATCH 02/12] test(transact): wire tests for token replay with the Return fields Cover each measured answer: a changed ReturnConsumedCapacity or ReturnItemCollectionMetrics on a token replay is a mismatch with the service's message, NONE equals absent, the matching replay reports read capacity and no ItemCollectionMetrics, and an invalid enum value is refused before the token comparison. --- tests/test_transact_token_return_fields.py | 281 +++++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 tests/test_transact_token_return_fields.py diff --git a/tests/test_transact_token_return_fields.py b/tests/test_transact_token_return_fields.py new file mode 100644 index 000000000..a296c24b6 --- /dev/null +++ b/tests/test_transact_token_return_fields.py @@ -0,0 +1,281 @@ +# 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 + +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. + +Every expected answer here was measured against Amazon DynamoDB in +us-east-1 on 2026-10-24 (17:31 UTC and 17:36 UTC), client retries off. +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 f"tok-{uuid.uuid4().hex}", uuid.uuid4().hex[:32] + + +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) + + +# --------------------------------------------------------------------------- +# 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") From 2d4aa667c1bc5234c3cdee5d4c771f980441a1cc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:15:30 +0000 Subject: [PATCH 03/12] docs(engine): say which stored tokens replay across a version change The compute_fingerprint comment said that tokens stored before this change still replay. That holds only for a request with neither Return field, or with both set to NONE. The comment now gives the three cases for the 10 minutes after an upgrade or a downgrade. The function at 744ea2915 hashes the TransactItems JSON alone. This version appends a suffix for TOTAL, INDEXES and SIZE, and nothing for NONE. All four storage backends replay a retry only when its fingerprint equals the stored one. A token for a request without the fields therefore replays in both directions. A token that an earlier version stored for 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 one of those values answers the mismatch to every retry on an earlier version. The comment also says that ExecuteTransaction writes use this fingerprint, because they call handle_transact_write_items with their ReturnConsumedCapacity. --- crates/engine/src/transact_write_helpers.rs | 23 +++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 4d4375488..530dabac0 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -266,10 +266,25 @@ pub(crate) fn validate_client_request_token(token: &str) -> Result<(), DynamoDbE /// `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`. A request with -/// neither field, or with both set to `NONE`, hashes the items alone, which -/// is the value stored by earlier versions; tokens stored before this change -/// still replay. The keyed hash prevents an attacker from crafting a +/// 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, and a token expires after 10 +/// minutes, so for 10 minutes after an upgrade or a downgrade: +/// - 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. +/// +/// 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. From bd07f9e3a6827da7a564033903c3f76df225cc51 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:16:53 +0000 Subject: [PATCH 04/12] test(engine): check the items and pin the values with a Return field The fingerprint test for different items used ReturnConsumedCapacity NONE only. A build that hashes the items only when the field is NONE passed every unit test. In that build, a retry with TOTAL and different items replays and writes nothing. Amazon DynamoDB answers that retry with IdempotentParameterMismatchException and stores nothing, for TOTAL and for SIZE (us-east-1, 2026-11-10, two sends each). Two new tests run the different items check with TOTAL and with SIZE. The fingerprint stored for a request with TOTAL, INDEXES or SIZE must also stay the same across versions. Otherwise its token stops replaying after an upgrade. A new test pins the values for pinned_body() and token tok-1: TOTAL 8fa51ffc1314a046, INDEXES ee2c3412f0fdbdf1, SIZE 70eb830c93e9079f, and TOTAL with SIZE e9957d3c7431e1d4. An HMAC-SHA256 computed outside the crate gives the same four values. The comment on PINNED_ITEMS_ONLY now names 744ea291, the commit whose fingerprint produced that value. --- crates/engine/src/transact_write_helpers.rs | 49 +++++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 530dabac0..782a8b4b4 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -402,18 +402,46 @@ mod tests { 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!(fp(&body, "tok-1"), fp(&body, "tok-2")); } - /// The value stored by versions that hashed `TransactItems` alone, for - /// this body and token. A request with neither Return field, or with both - /// set to NONE, must keep producing it so tokens stored before the upgrade - /// still replay. + /// 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 @@ -427,6 +455,19 @@ mod tests { 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(); From 7c6edc8e0d207a6fa4fc1eea03724dd98cc22928 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:18:41 +0000 Subject: [PATCH 05/12] refactor(engine): keep the token mismatch message in one constant After the merge of main, the mismatch message was a literal in two places: the classic TransactWriteItems handler and remap_write_error in crates/engine/src/partiql/transaction.rs. The remap arm for IdempotentParameterMismatchException replaced the handler's message with the same text, so it changed nothing. The text is now IDEMPOTENT_MISMATCH_MESSAGE in crates/engine/src/transact_write_helpers.rs, and the handler uses it. This change removes the remap arm, so the PartiQL surface passes the handler's error through. The comments on remap_write_error and on the module now say that it remaps only the reason of a duplicate-key INSERT. No answer changes. --- crates/engine/src/partiql/transaction.rs | 14 +++++--------- crates/engine/src/transact_write_helpers.rs | 7 +++++++ crates/engine/src/transact_write_items.rs | 7 +++---- 3 files changed, 15 insertions(+), 13 deletions(-) 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 782a8b4b4..6a30c39c7 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -260,6 +260,13 @@ pub(crate) fn validate_client_request_token(token: &str) -> Result<(), DynamoDbE Ok(()) } +/// 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 diff --git a/crates/engine/src/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index a24779ed0..1ade0d473 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; @@ -220,9 +221,7 @@ pub async fn handle_transact_write_items( } Err(extenddb_storage::error::StorageError::IdempotentMismatch) => { return Err(DynamoDbError::IdempotentParameterMismatchException( - "Specified idempotent token was used with different request parameters \ - within the idempotency window" - .to_owned(), + IDEMPOTENT_MISMATCH_MESSAGE.to_owned(), )); } Err(e) => return Err(storage_err_to_dynamo(e)), From bf378e0343b4abe829a4609ba25c7cb0ef9d16d4 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:09:57 +0000 Subject: [PATCH 06/12] test(transact): read back the changed key and keep a Return field tests/test_transact_token_return_fields.py changes in four places. The module docstring now limits the sentence about a matching replay to tables without a local secondary index. The tests use such a table: scoped_table keys it on pk alone. The docstring also gives the date of the measurement behind each read of a changed key. _fresh() returned (token, pk), and every caller unpacks pk, token = _fresh(). It now returns (pk, token), so failure output names the two values correctly. test_changed_items_alone_is_a_mismatch now reads the second key back and expects no item, as its sibling test does. For a retry with no Return field and another item, Amazon DynamoDB answers IdempotentParameterMismatchException. It stores no item for the second key (us-east-1, 2026-11-10, two sends). A new test sends ReturnConsumedCapacity TOTAL, or ReturnItemCollectionMetrics SIZE, on both calls, and another item on the second call. Amazon DynamoDB answers the second call with IdempotentParameterMismatchException and stores no item for its key (us-east-1, 2026-11-10, two sends each). The test checks the different items case of the fingerprint unit tests through the server. --- tests/test_transact_token_return_fields.py | 52 +++++++++++++++++----- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/tests/test_transact_token_return_fields.py b/tests/test_transact_token_return_fields.py index a296c24b6..d05ff95f4 100644 --- a/tests/test_transact_token_return_fields.py +++ b/tests/test_transact_token_return_fields.py @@ -11,15 +11,23 @@ Specified idempotent token was used with different request parameters within the idempotency window -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. - -Every expected answer here was measured against Amazon DynamoDB in -us-east-1 on 2026-10-24 (17:31 UTC and 17:36 UTC), client retries off. -The tests run against both Amazon DynamoDB and ExtendDB. +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 @@ -67,7 +75,8 @@ def _items(table: str, pk: str) -> list[dict]: def _fresh() -> tuple[str, str]: - return f"tok-{uuid.uuid4().hex}", uuid.uuid4().hex[:32] + """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: @@ -144,6 +153,29 @@ def test_changed_items_alone_is_a_mismatch(dynamodb_client, table): 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 + ) # --------------------------------------------------------------------------- From f6ee11219a7d4e86b498e50b4a1a8c177f0e9eef Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:10:13 +0000 Subject: [PATCH 07/12] test(partiql): ExecuteTransaction replay with ReturnConsumedCapacity An ExecuteTransaction write reaches handle_transact_write_items with the request's ReturnConsumedCapacity, so the fingerprint that compares the field decides ExecuteTransaction replays as well. Four tests next to the T5 test in tests/test_partiql_transaction.py send one INSERT twice with the same token. Amazon DynamoDB answers the second call with IdempotentParameterMismatchException in three cases: TOTAL then no field, no field then TOTAL, and TOTAL then INDEXES. The message is the one TransactWriteItems gives. With no field on both calls the service answers 200 {"Responses": []} to both (us-east-1, 2026-11-10, two sends each). Each case uses its own key and token. --- tests/test_partiql_transaction.py | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) 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) --------------------------------- From cd635eb27d6b43381b454b32bec4a1e1768c9f04 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:14:01 +0000 Subject: [PATCH 08/12] docs: the token fingerprint, its replay gaps and the upgrade window docs/design/04-component-storage.md described the stored fingerprint without its inputs. Section 9 now says that the fingerprint is an HMAC-SHA256 keyed by the token over the TransactItems JSON. The ReturnConsumedCapacity and ReturnItemCollectionMetrics values follow the items when they are not NONE. ExtendDB translates an ExecuteTransaction write into a TransactWriteItems request before it computes the fingerprint. The IdempotentMismatch item of the storage error list now says that the token exists with a different fingerprint. docs/differences-from-dynamodb.md gets a Transactions section with the replay gaps that remain. The rows about how a request writes its items name TransactWriteItems, the operation of the measurements: - The service replays a retry that changes only the spelling of a number, the spacing of an expression or an ExpressionAttributeNames alias. It also replays a retry that adds ReturnValuesOnConditionCheckFailure NONE inside an item (measured 2026-10-24). ExtendDB answers each with IdempotentParameterMismatchException (measured on SQLite at this branch). - The service answers 200 to a retry whose item lists the same attributes in another key order. An identical retry gets the same answer (us-east-1, 2026-11-10, two sends). A build with the MongoDB backend keeps map keys in request order, so there the retry answers the mismatch (from the code). - The service answers 200 to a raw signed request with an unknown top-level field and writes the item (us-east-1, 2026-11-10, two sends). ExtendDB refuses the request with SerializationException (measured on SQLite at this branch). - On a table without a local secondary index, the service answers the first SIZE call with {"ItemCollectionMetrics": {}} (us-east-1, 2026-11-10, two sends). ExtendDB answers {}. docs/manuals/07-upgrade-manual.md gets a v0.1.15 entry for stored tokens. After an upgrade, a token that v0.1.14 stored for a request with TOTAL, INDEXES or SIZE answers the mismatch to an identical retry. After a downgrade, a token that this release stored for such a request answers the mismatch to every retry. v0.1.14 does not serve ExecuteTransaction. PostgreSQL, SQLite and MongoDB keep a token for 10 minutes. The Cassandra backend stores a token without an expiry time and does not check its age. --- docs/design/04-component-storage.md | 18 ++++++++++++- docs/differences-from-dynamodb.md | 17 +++++++++++++ docs/manuals/07-upgrade-manual.md | 39 +++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index f9ac92dab..071e76acb 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -333,7 +333,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 @@ -821,6 +821,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 b768e0a76..c4c96555f 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -196,6 +196,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 7f244409f..bec8b863d 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -888,6 +888,45 @@ DescribeStream and GetShardIterator now refuse a client-built `StreamArn` with t --- +### v0.1.15: 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` 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`. v0.1.14 does not serve +`ExecuteTransaction`, so no token that v0.1.14 stored comes from an +`ExecuteTransaction` write. + +**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. Servers +of both releases can share one database during a rolling upgrade. A retry that +reaches a server of the other release then gets the same answers. 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. From 6fabc1c4ef00d02ef8f0a87bc7355ac51cd0b35f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:15:08 +0000 Subject: [PATCH 09/12] docs(engine): give the token lifetime per backend in the comment The compute_fingerprint comment said that a token expires after 10 minutes. It described the answers for 10 minutes after an upgrade or a downgrade. PostgreSQL, SQLite and MongoDB check the age of a token against 10 minutes. The Cassandra backend inserts a token without a TTL, and its token table has no default TTL. Its token check reads no creation time, and its cleanup of expired tokens does nothing. A Cassandra token therefore has no expiry. The comment now describes the answers for a token stored before the version change, and it gives the lifetime per backend. The upgrade manual entry states the same lifetimes. --- crates/engine/src/transact_write_helpers.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 6a30c39c7..2a09d062a 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -278,8 +278,9 @@ pub(crate) const IDEMPOTENT_MISMATCH_MESSAGE: &str = "Specified idempotent token /// `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, and a token expires after 10 -/// minutes, so for 10 minutes after an upgrade or a downgrade: +/// 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. @@ -291,6 +292,9 @@ pub(crate) const IDEMPOTENT_MISMATCH_MESSAGE: &str = "Specified idempotent token /// 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 From e114c9a8dc4839783f2bfe77d6b5ca66d3a93c4f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:04:54 +0000 Subject: [PATCH 10/12] docs(upgrade): give the ClientRequestToken entry release v1.0.0 Release 0.1.15 shipped without this branch, and main (#1107) now carries version 1.0.0. The entry of this branch said v0.1.15, so its heading now says v1.0.0. The entry also said that v0.1.14 does not serve ExecuteTransaction, so that no stored token came from an ExecuteTransaction write. 0.1.15 serves ExecuteTransaction and fingerprints its token over the items alone, as it does for TransactWriteItems. The entry now names both operations in its list of affected clients. --- docs/manuals/07-upgrade-manual.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index ce89b98c0..9f97dac10 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -1232,7 +1232,7 @@ DescribeStream and GetShardIterator now refuse a client-built `StreamArn` with t --- -### v0.1.15: a `ClientRequestToken` retry compares `ReturnConsumedCapacity` and `ReturnItemCollectionMetrics` +### v1.0.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 @@ -1247,12 +1247,13 @@ 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` 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`. v0.1.14 does not serve -`ExecuteTransaction`, so no token that v0.1.14 stored comes from an -`ExecuteTransaction` write. +**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 +serves `ExecuteTransaction` with the earlier fingerprint, so a token that +0.1.15 stored for an `ExecuteTransaction` write 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. From 017335d865ff5d368038c9b80f063acfd2bd2411 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:18:49 +0000 Subject: [PATCH 11/12] docs(upgrade): move the ClientRequestToken entry to v1.1.0 Release 1.0.0 shipped without this branch. The entry of this branch said v1.0.0, so its heading now says v1.1.0. docs/versioning.md puts a change that makes ExtendDB answer as DynamoDB does in a minor release. The entry also named 0.1.15 as the release that serves ExecuteTransaction with the earlier fingerprint. 1.0.0 does the same, and the entry now names both releases. --- docs/manuals/07-upgrade-manual.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 9f97dac10..dc4f007be 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -1232,7 +1232,7 @@ DescribeStream and GetShardIterator now refuse a client-built `StreamArn` with t --- -### v1.0.0: a `ClientRequestToken` retry compares `ReturnConsumedCapacity` and `ReturnItemCollectionMetrics` +### 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 @@ -1250,10 +1250,10 @@ 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 -serves `ExecuteTransaction` with the earlier fingerprint, so a token that -0.1.15 stored for an `ExecuteTransaction` write gets the same answers as one -stored for a `TransactWriteItems` request. +`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. From c38b72284651cb8e4cee7f0266255c5b60e41559 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:51:56 +0000 Subject: [PATCH 12/12] docs(upgrade): say how each backend runs two releases on one database The v1.1.0 entry said that servers of both releases can share one database during a rolling upgrade. The deployment guide says to run one instance per catalog. SQLite enforces that limit on Unix, and the other backends do not. On PostgreSQL, MongoDB and Cassandra each server holds its own serving registration. The tokens live in the database: the idempotency_tokens table on PostgreSQL, the idempotency_tokens collection on MongoDB and the idempotency_tokens_by_account table on Cassandra. A retry that reaches a server of the other release reads the same stored token. The sentence now names these three backends and links the deployment guide's Multi-Instance Considerations section. On SQLite the entry now says to run the two releases one after the other. On Unix `serve` takes an exclusive flock on `.lock`, and a second server refuses to start (serve_lock.rs). On Windows the server takes no lock, which #642 tracks. --- docs/manuals/07-upgrade-manual.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index dc4f007be..cf9a493eb 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -1261,9 +1261,14 @@ 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. Servers -of both releases can share one database during a rolling upgrade. A retry that -reaches a server of the other release then gets the same answers. PostgreSQL, +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