diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index f63f31c14..842eaf03a 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -7,6 +7,8 @@ pub use messages::{ validation_errors_detected, }; +use serde::ser::{SerializeMap as _, Serializer as _}; + use crate::types::{CancellationReason, Item}; /// The `ExpiredIteratorException` message for a shard iterator older than its @@ -411,32 +413,48 @@ impl DynamoDbError { pub const SERIALIZATION_FAILURE_BODY: &[u8] = br#"{"__type":"com.amazonaws.dynamodb.v20120810#InternalServerError","message":"Internal error"}"#; -/// Build the DynamoDB-shaped error document for `error`. +/// Build the DynamoDB-shaped error document for `error`, as JSON bytes. /// -/// Returns the JSON body a client receives for a failed request: `__type` with -/// its namespace prefix (REQ-ERR-001), an optional message under the key -/// `message_key` picks (REQ-ERR-002), omitted when empty -/// (REQ-ERR-003 — real DynamoDB omits it for `UnknownOperationException` and -/// other messageless errors), and the `CancellationReasons` /`Item` members -/// that `TransactionCanceledException` and `ConditionalCheckFailedException` -/// carry. This is only the body; the HTTP status line and headers belong to a -/// transport and stay with the caller that has one. Error responses are part of -/// the observable contract, so every entry point builds this body the same way. +/// Returns the JSON body a client receives for a failed request, with its +/// members in the order DynamoDB writes them (us-east-1, raw bodies, +/// 2026-11-20): `__type` with its namespace prefix (REQ-ERR-001), then the +/// `CancellationReasons` of a `TransactionCanceledException` or the `Item` of +/// a `ConditionalCheckFailedException`, then the message under the key +/// `message_key` picks (REQ-ERR-002), omitted when empty (REQ-ERR-003: +/// DynamoDB omits it for `UnknownOperationException` and other messageless +/// errors). The top-level members are written one by one, so their order does +/// not depend on serde_json's `preserve_order` feature, which bson turns on in +/// any build that includes the MongoDB backend. If the body cannot be +/// serialized, the bytes are [`SERIALIZATION_FAILURE_BODY`]. This is only the +/// body; the HTTP status line and headers belong to a transport and stay with +/// the caller that has one. Error responses are part of the observable +/// contract, so every entry point builds this body the same way. #[doc(hidden)] #[must_use] -pub fn error_document(error: &DynamoDbError) -> serde_json::Value { - let mut body = serde_json::json!({ "__type": error.full_error_type() }); - let message = error.message(); - if !message.is_empty() { - body[message_key(error)] = serde_json::Value::String(message.to_owned()); - } +pub fn error_document(error: &DynamoDbError) -> Vec { + error_body(error).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec()) +} + +/// The members of [`error_document`], in its order. +fn error_body(error: &DynamoDbError) -> serde_json::Result> { + let mut bytes = Vec::new(); + let mut serializer = serde_json::Serializer::new(&mut bytes); + let mut body = serializer.serialize_map(None)?; + body.serialize_entry("__type", &error.full_error_type())?; + // Each reason writes `Code`, `Item`, `Message`, the field order of + // `CancellationReason` and the order `DynamoDB` writes. if let Some(reasons) = error.cancellation_reasons() { - body["CancellationReasons"] = serde_json::to_value(reasons).unwrap_or_default(); + body.serialize_entry("CancellationReasons", reasons)?; } if let Some(item) = error.condition_check_item() { - body["Item"] = serde_json::to_value(item).unwrap_or_default(); + body.serialize_entry("Item", item)?; } - body + let msg = error.message(); + if !msg.is_empty() { + body.serialize_entry(message_key(error), msg)?; + } + body.end()?; + Ok(bytes) } /// The key that carries the error message: `Message` on the errors matched @@ -485,6 +503,7 @@ pub fn webassembly_unsupported_message(subject: &str, reason: &str) -> String { #[cfg(test)] mod tests { use super::*; + use crate::types::AttributeValue; /// SP-ERR-002: verify every variant returns the correct HTTP status code. #[test] @@ -634,46 +653,50 @@ mod tests { ); } + /// The bytes of each body: `__type`, then `CancellationReasons` or `Item`, + /// then the message, which is omitted when empty (REQ-ERR-003), and a + /// cancellation reason as `Code`, `Item`, `Message`. DynamoDB wrote these + /// orders in us-east-1 on 2026-11-20 (raw bodies, each request twice). An + /// `Item` here holds one attribute, because DynamoDB changed the order of + /// the attributes inside an `Item` between two sends of one request. #[test] - fn error_document_carries_type_and_message() { - let doc = error_document(&DynamoDbError::ValidationException("bad input".to_owned())); - assert_eq!( - doc["__type"], - serde_json::json!("com.amazon.coral.validate#ValidationException") - ); - assert_eq!(doc["message"], serde_json::json!("bad input")); - } - - #[test] - fn error_document_omits_empty_message() { - // REQ-ERR-003: real DynamoDB omits `message` when it is empty. - let doc = error_document(&DynamoDbError::UnknownOperationException(String::new())); - assert_eq!( - doc["__type"], - serde_json::json!("com.amazon.coral.service#UnknownOperationException") - ); - assert!(doc.get("message").is_none(), "{doc}"); - } - - #[test] - fn error_document_includes_cancellation_reasons() { - let doc = error_document(&DynamoDbError::TransactionCanceledException { - message: "Transaction cancelled".to_owned(), - cancellation_reasons: vec![CancellationReason { - code: "ConditionalCheckFailed".to_owned(), - message: Some("The conditional request failed".to_owned()), - item: None, - }], - }); - assert_eq!(doc["Message"], serde_json::json!("Transaction cancelled")); - let reasons = doc["CancellationReasons"] - .as_array() - .expect("CancellationReasons is an array"); - assert_eq!(reasons.len(), 1); - assert_eq!( - reasons[0]["Code"], - serde_json::json!("ConditionalCheckFailed") - ); + fn error_document_writes_the_members_in_the_service_order() { + let item = Item::from([("pk".to_owned(), AttributeValue::S("e1222".to_owned()))]); + let failed = "The conditional request failed"; + let rows = [ + ( + DynamoDbError::ValidationException("bad input".to_owned()), + r#"{"__type":"com.amazon.coral.validate#ValidationException","message":"bad input"}"#, + ), + ( + DynamoDbError::UnknownOperationException(String::new()), + r#"{"__type":"com.amazon.coral.service#UnknownOperationException"}"#, + ), + ( + DynamoDbError::TransactionCanceledException { + message: + "Transaction cancelled, please refer cancellation reasons for specific \ + reasons [ConditionalCheckFailed]" + .to_owned(), + cancellation_reasons: vec![CancellationReason { + code: "ConditionalCheckFailed".to_owned(), + item: Some(item.clone()), + message: Some(failed.to_owned()), + }], + }, + r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Item":{"pk":{"S":"e1222"}},"Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#, + ), + ( + DynamoDbError::ConditionalCheckFailedException(failed.to_owned(), Some(item)), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","Item":{"pk":{"S":"e1222"}},"message":"The conditional request failed"}"#, + ), + ]; + let got: Vec = rows + .iter() + .map(|(error, _)| String::from_utf8(error_document(error)).expect("UTF-8 body")) + .collect(); + let want: Vec<&str> = rows.iter().map(|(_, body)| *body).collect(); + assert_eq!(got, want); } #[test] diff --git a/crates/core/src/types/transaction.rs b/crates/core/src/types/transaction.rs index 2f311abfe..b36668fc0 100755 --- a/crates/core/src/types/transaction.rs +++ b/crates/core/src/types/transaction.rs @@ -259,17 +259,20 @@ pub struct TransactWriteItemsOutput { } /// Per-item cancellation reason in a `TransactionCanceledException`. +/// +/// The fields are declared in the order `DynamoDB` writes the members of a +/// reason (`Code`, `Item`, `Message`), and serialize in that order. #[derive(Debug, Clone, Serialize)] pub struct CancellationReason { /// Status code: `"None"`, `"ConditionalCheckFailed"`, `"ValidationError"`, etc. #[serde(rename = "Code")] pub code: String, - /// Human-readable message, omitted for items with no error. - #[serde(rename = "Message", skip_serializing_if = "Option::is_none")] - pub message: Option, /// The existing item when `ReturnValuesOnConditionCheckFailure` is `ALL_OLD`. #[serde(rename = "Item", skip_serializing_if = "Option::is_none")] pub item: Option, + /// Human-readable message, omitted for items with no error. + #[serde(rename = "Message", skip_serializing_if = "Option::is_none")] + pub message: Option, } impl CancellationReason { diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index 1b26cd378..bf24122b7 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -37,12 +37,11 @@ pub(crate) fn success_response(body: &Value, request_id: &str) -> Response { /// key `error_document` picks. REQ-ERR-003: Omit the message field when empty /// (real `DynamoDB` behavior, verified 2026-05-04). pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Response { - // The body shape (`__type`, optional message, `CancellationReasons`, `Item`) - // is built by the shared `error_document` helper so the wire body and the - // in-process body come from the same code; this transport adds the HTTP status and headers. - let body = error_document(error); - let body_bytes = - serde_json::to_vec(&body).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec()); + // The body (`__type`, then `CancellationReasons` or `Item`, then the + // message) is written by the shared `error_document` helper so the wire + // body and the in-process body come from the same code; this transport adds + // the HTTP status and headers. + let body_bytes = error_document(error); let crc = crc32fast::hash(&body_bytes); let status = StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); diff --git a/crates/server/src/response_tests.rs b/crates/server/src/response_tests.rs index cb71f310b..ae313e82d 100644 --- a/crates/server/src/response_tests.rs +++ b/crates/server/src/response_tests.rs @@ -4,60 +4,89 @@ //! Tests of the error bodies [`super::error_response`] sends. use extenddb_core::error::DynamoDbError; -use extenddb_core::types::CancellationReason; +use extenddb_core::types::{AttributeValue, CancellationReason, Item}; use super::error_response; -/// The top-level keys of the body `error_response` sends for `error`. -async fn body_keys(error: &DynamoDbError) -> Vec { +/// The body `error_response` sends for `error`. +async fn body(error: &DynamoDbError) -> String { let response = error_response(error, "request-1"); let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) .await .expect("body"); - let body: serde_json::Value = serde_json::from_slice(&bytes).expect("json body"); - let mut keys: Vec = body.as_object().expect("object").keys().cloned().collect(); - keys.sort_unstable(); - keys + String::from_utf8(bytes.to_vec()).expect("UTF-8 body") } -/// The errors measured with `Message` carry it under that key, as the -/// service sends them; the errors measured with `message` keep it. +/// Each expected body is the one the service sent for that error (us-east-1, +/// raw bodies, 2026-11-20, each request twice): `__type` first, the other +/// members in the service's order, and the message under the key the service +/// uses for that error. An `Item` here holds one attribute, because the service +/// changed the order of the attributes inside an `Item` between two sends of +/// one request. The `SerializationException` with an empty text has no measured +/// body: ExtendDB omits an empty message (REQ-ERR-003). #[tokio::test] -async fn the_message_key_follows_the_service_per_error() { - let cancelled = DynamoDbError::TransactionCanceledException { +async fn the_members_follow_the_service_per_error() { + let cancelled = |item: Option| DynamoDbError::TransactionCanceledException { message: "Transaction cancelled, please refer cancellation reasons for specific \ reasons [ConditionalCheckFailed]" .to_owned(), cancellation_reasons: vec![CancellationReason { code: "ConditionalCheckFailed".to_owned(), message: Some("The conditional request failed".to_owned()), - item: None, + item, }], }; - assert_eq!( - body_keys(&cancelled).await, - ["CancellationReasons", "Message", "__type"] - ); - let mismatch = DynamoDbError::IdempotentParameterMismatchException( - "Specified idempotent token was used with different request parameters within \ - the idempotency window" - .to_owned(), - ); - assert_eq!(body_keys(&mismatch).await, ["Message", "__type"]); - let serialization = DynamoDbError::SerializationException( - "STRING_VALUE cannot be converted to Integer".to_owned(), - ); - assert_eq!(body_keys(&serialization).await, ["Message", "__type"]); - let empty = DynamoDbError::SerializationException(String::new()); - assert_eq!(body_keys(&empty).await, ["__type"]); - for other in [ - DynamoDbError::ValidationException("One or more parameter values were invalid".into()), - DynamoDbError::ConditionalCheckFailedException( - "The conditional request failed".into(), - None, - ), - DynamoDbError::TransactionConflictException("Transaction is ongoing".into()), - ] { - assert_eq!(body_keys(&other).await, ["__type", "message"], "{other:?}"); + let old_item = Item::from([("pk".to_owned(), AttributeValue::S("e1222".to_owned()))]); + let failed = "The conditional request failed"; + let rows: [(DynamoDbError, &str); 8] = [ + ( + cancelled(None), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#, + ), + ( + cancelled(Some(old_item.clone())), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Item":{"pk":{"S":"e1222"}},"Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#, + ), + ( + DynamoDbError::ConditionalCheckFailedException(failed.into(), Some(old_item)), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","Item":{"pk":{"S":"e1222"}},"message":"The conditional request failed"}"#, + ), + ( + DynamoDbError::ConditionalCheckFailedException(failed.into(), None), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","message":"The conditional request failed"}"#, + ), + ( + DynamoDbError::IdempotentParameterMismatchException( + "Specified idempotent token was used with different request parameters \ + within the idempotency window" + .to_owned(), + ), + r#"{"__type":"com.amazonaws.dynamodb.v20120810#IdempotentParameterMismatchException","Message":"Specified idempotent token was used with different request parameters within the idempotency window"}"#, + ), + ( + DynamoDbError::SerializationException( + "STRING_VALUE cannot be converted to Integer".to_owned(), + ), + r#"{"__type":"com.amazon.coral.service#SerializationException","Message":"STRING_VALUE cannot be converted to Integer"}"#, + ), + ( + DynamoDbError::SerializationException(String::new()), + r#"{"__type":"com.amazon.coral.service#SerializationException"}"#, + ), + ( + DynamoDbError::ValidationException( + "1 validation error detected: Value null at 'key' failed to satisfy \ + constraint: Member must not be null" + .to_owned(), + ), + r#"{"__type":"com.amazon.coral.validate#ValidationException","message":"1 validation error detected: Value null at 'key' failed to satisfy constraint: Member must not be null"}"#, + ), + ]; + let mut got = Vec::new(); + let mut want = Vec::new(); + for (error, expected) in &rows { + got.push(body(error).await); + want.push(*expected); } + assert_eq!(got, want); } diff --git a/crates/wasm-adapter/src/runtime.rs b/crates/wasm-adapter/src/runtime.rs index dd23c2a0e..9bbbd3c5f 100644 --- a/crates/wasm-adapter/src/runtime.rs +++ b/crates/wasm-adapter/src/runtime.rs @@ -145,13 +145,13 @@ impl Engine { /// operation that takes no parameters). #[must_use] pub async fn submit(&self, operation: &str, body_json: &str) -> String { - let value = match self.dispatch(operation, body_json).await { - Ok(body) => body, - Err(err) => error_document(&err), - }; - serde_json::to_string(&value).unwrap_or_else(|_| { - String::from_utf8_lossy(extenddb_core::error::SERIALIZATION_FAILURE_BODY).into_owned() - }) + match self.dispatch(operation, body_json).await { + Ok(body) => serde_json::to_string(&body).unwrap_or_else(|_| { + String::from_utf8_lossy(extenddb_core::error::SERIALIZATION_FAILURE_BODY) + .into_owned() + }), + Err(err) => String::from_utf8_lossy(&error_document(&err)).into_owned(), + } } /// The response to a call whose `argument` (`"operation"` or `"body"`) is @@ -162,9 +162,7 @@ impl Engine { #[must_use] pub fn non_string_argument(argument: &str) -> String { let err = DynamoDbError::ValidationException(format!("{argument} must be a string")); - serde_json::to_string(&error_document(&err)).unwrap_or_else(|_| { - String::from_utf8_lossy(extenddb_core::error::SERIALIZATION_FAILURE_BODY).into_owned() - }) + String::from_utf8_lossy(&error_document(&err)).into_owned() } /// Apply the browser-build operation policy and the engine's pre-dispatch @@ -334,4 +332,48 @@ mod tests { ); } } + + /// An error answer is the body the server sends: `__type` first, then + /// `Item` or `CancellationReasons`, then the message, and a cancellation + /// reason as `Code`, `Item`, `Message`. In name order, the `Message` of a + /// `SerializationException` would come before `__type`. + #[tokio::test] + async fn an_error_answer_writes_type_first() { + let engine = engine().await; + for (operation, body) in [ + ( + "CreateTable", + r#"{"TableName":"ErrorOrder","KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}],"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"}],"BillingMode":"PAY_PER_REQUEST"}"#, + ), + ( + "PutItem", + r#"{"TableName":"ErrorOrder","Item":{"pk":{"S":"a"}}}"#, + ), + ] { + ok_value(&engine.submit(operation, body).await); + } + let cases = [ + ( + "ListTables", + "not json", + r#"{"__type":"com.amazon.coral.service#SerializationException","Message":"Start of structure or map found where not expected: expected ident at line 1 column 2"}"#, + ), + ( + "PutItem", + r#"{"TableName":"ErrorOrder","Item":{"pk":{"S":"a"}},"ConditionExpression":"attribute_not_exists(pk)","ReturnValuesOnConditionCheckFailure":"ALL_OLD"}"#, + r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","Item":{"pk":{"S":"a"}},"message":"The conditional request failed"}"#, + ), + ( + "TransactWriteItems", + r#"{"TransactItems":[{"ConditionCheck":{"TableName":"ErrorOrder","Key":{"pk":{"S":"a"}},"ConditionExpression":"attribute_not_exists(pk)","ReturnValuesOnConditionCheckFailure":"ALL_OLD"}}]}"#, + r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Item":{"pk":{"S":"a"}},"Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#, + ), + ]; + let mut got = Vec::new(); + for (operation, body, _) in cases { + got.push(engine.submit(operation, body).await); + } + let want: Vec<&str> = cases.iter().map(|(_, _, answer)| *answer).collect(); + assert_eq!(got, want); + } } diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 19746dd3f..3f6d021a4 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -437,6 +437,12 @@ deployment, even when no catalog migration is required. **Who is affected.** A client that reads `message` from the raw body of a `SerializationException` finds the text under `Message` instead. No catalog migration or configuration change is required. +### v1.2.0: an error body writes `__type` first + +**What changed** (#1249, fixes #1222). An error body writes `__type` first, then `CancellationReasons` or `Item`, then the message, as DynamoDB writes them (measured 2026-11-20). A cancellation reason writes `Code`, `Item`, `Message`. In 1.1.0, a build without the MongoDB backend, such as the WebAssembly build, wrote the members in name order, so `CancellationReasons`, `Item` and `Message` came before `__type`. A build with the MongoDB backend wrote `__type`, then the message, then `CancellationReasons` or `Item`, and wrote a reason as `Code`, `Message`, `Item`. The new order applies in every build. + +**Who is affected.** A client that compares the raw bytes of an error body, or reads its members in order. A client that looks up the members by name sees no change. No catalog migration or configuration change is required. + ### v1.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: diff --git a/tests/test_error_message_key.py b/tests/test_error_message_key.py index 9f4e5b649..81e1412fc 100644 --- a/tests/test_error_message_key.py +++ b/tests/test_error_message_key.py @@ -9,10 +9,19 @@ (raw bodies measured in us-east-1 on 2026-10-29, 2026-11-03 and 2026-11-19). It also sends ``Message`` on TransactionInProgressException, AccessDeniedException and SerializationException. REQ-ERR-002 in -docs/design/01-requirements.md lists the errors measured. botocore reads +docs/design/01-requirements.md lists the errors measured. DynamoDB writes +``__type`` first in each of these bodies (2026-11-20), so the tests read the +keys in the order of the raw bytes. botocore reads either key, so these tests read the raw body from botocore's ``before-parse`` event before it normalizes it. +With ``ReturnValuesOnConditionCheckFailure`` set to ``ALL_OLD``, DynamoDB +wrote ``__type``, ``Item``, ``message`` for a PutItem whose condition failed, +and ``__type``, ``CancellationReasons``, ``Message`` for a TransactWriteItems +whose ConditionCheck failed, with ``Code``, ``Item``, ``Message`` in the +reason (us-east-1, 2026-11-20, each request twice). These two requests need +a table, so they were not measured again for these tests. + Dual-target against Amazon DynamoDB and extenddb. """ @@ -39,9 +48,10 @@ def hash_table(dynamodb_client): yield name -def _error_code_and_keys(client, operation: str, call) -> tuple[str, list[str], int]: - """Run ``call``, which must fail, and return the error code, the sorted - top-level keys of the raw response body and the HTTP status.""" +def _error_code_and_body(client, operation: str, call) -> tuple[str, dict, int]: + """Run ``call``, which must fail, and return the error code, the raw + response body with its members in the order of the bytes, and the HTTP + status.""" raw: list[bytes] = [] def capture(response_dict, **_kwargs): @@ -57,13 +67,25 @@ def capture(response_dict, **_kwargs): response = exc_info.value.response return ( response["Error"]["Code"], - sorted(json.loads(raw[-1])), + json.loads(raw[-1]), response["ResponseMetadata"]["HTTPStatusCode"], ) -def test_transaction_canceled_carries_message_under_capital_m(dynamodb_client, hash_table): - code, keys, _ = _error_code_and_keys( +@pytest.mark.parametrize( + "return_values, reason_keys", + [ + ({}, ["Code", "Message"]), + ({"ReturnValuesOnConditionCheckFailure": "ALL_OLD"}, ["Code", "Item", "Message"]), + ], + ids=["NONE", "ALL_OLD"], +) +def test_transaction_canceled_carries_message_under_capital_m( + dynamodb_client, hash_table, return_values, reason_keys +): + pk = f"held-{uuid.uuid4().hex}" + dynamodb_client.put_item(TableName=hash_table, Item={"pk": {"S": pk}}) + code, body, _ = _error_code_and_body( dynamodb_client, "TransactWriteItems", lambda: dynamodb_client.transact_write_items( @@ -71,15 +93,17 @@ def test_transaction_canceled_carries_message_under_capital_m(dynamodb_client, h { "ConditionCheck": { "TableName": hash_table, - "Key": {"pk": {"S": f"missing-{uuid.uuid4().hex}"}}, - "ConditionExpression": "attribute_exists(pk)", + "Key": {"pk": {"S": pk}}, + "ConditionExpression": "attribute_not_exists(pk)", + **return_values, } } ] ), ) assert code == "TransactionCanceledException" - assert keys == ["CancellationReasons", "Message", "__type"] + assert list(body) == ["__type", "CancellationReasons", "Message"] + assert [list(reason) for reason in body["CancellationReasons"]] == [reason_keys] def test_idempotent_parameter_mismatch_carries_message_under_capital_m( @@ -97,11 +121,11 @@ def put(value: str): ) put("first") - code, keys, _ = _error_code_and_keys( + code, body, _ = _error_code_and_body( dynamodb_client, "TransactWriteItems", lambda: put("second") ) assert code == "IdempotentParameterMismatchException" - assert keys == ["Message", "__type"] + assert list(body) == ["__type", "Message"] # Raw bodies measured in us-east-1 on 2026-11-20, each request sent twice, @@ -135,32 +159,45 @@ def test_serialization_error_carries_message_under_capital_m( ): client = dynamodb_client_no_validation call = getattr(client, xform_name(operation)) - code, keys, status = _error_code_and_keys(client, operation, lambda: call(**params)) + code, body, status = _error_code_and_body(client, operation, lambda: call(**params)) # The texts are not asserted: ExtendDB's texts differ from DynamoDB's (#1012, #884). assert status == 400 assert code == "SerializationException" - assert keys == ["Message", "__type"] + assert list(body) == ["__type", "Message"] -def test_conditional_check_failed_carries_message_under_lower_case(dynamodb_client, hash_table): - code, keys, _ = _error_code_and_keys( +@pytest.mark.parametrize( + "return_values, keys", + [ + ({}, ["__type", "message"]), + ({"ReturnValuesOnConditionCheckFailure": "ALL_OLD"}, ["__type", "Item", "message"]), + ], + ids=["NONE", "ALL_OLD"], +) +def test_conditional_check_failed_carries_message_under_lower_case( + dynamodb_client, hash_table, return_values, keys +): + pk = f"held-{uuid.uuid4().hex}" + dynamodb_client.put_item(TableName=hash_table, Item={"pk": {"S": pk}}) + code, body, _ = _error_code_and_body( dynamodb_client, "PutItem", lambda: dynamodb_client.put_item( TableName=hash_table, - Item={"pk": {"S": f"missing-{uuid.uuid4().hex}"}}, - ConditionExpression="attribute_exists(pk)", + Item={"pk": {"S": pk}}, + ConditionExpression="attribute_not_exists(pk)", + **return_values, ), ) assert code == "ConditionalCheckFailedException" - assert keys == ["__type", "message"] + assert list(body) == keys def test_validation_error_carries_message_under_lower_case(dynamodb_client, hash_table): - code, keys, _ = _error_code_and_keys( + code, body, _ = _error_code_and_body( dynamodb_client, "GetItem", lambda: dynamodb_client.get_item(TableName=hash_table, Key={"pk": {"N": "1"}}), ) assert code == "ValidationException" - assert keys == ["__type", "message"] + assert list(body) == ["__type", "message"]