From 6285b81ffc3463bfc7607af49d76bab4fc48ec04 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:45:46 +0000 Subject: [PATCH 01/12] feat(storage): a StorageError::Service variant the engine passes through A backend that can classify its own failure into the service's error vocabulary (a hosted database reporting a documented unavailability or capacity condition) had no way to return that error with its own message: every unrecognised StorageError variant reaches the client as the fixed "Internal server error" string after an error-level log line. StorageError::Service(DynamoDbError) carries a fully formed client error. Nine engine functions map a StorageError to a client error. Six own a catch-all and gain a Service arm that returns the error with its variant and message unchanged and without the fault log line: the data path mapping in create_table.rs, the backup mapping in backup.rs, the UpdateTable mapping, the streams and TTL mappings, and sanitize_storage_error for the metadata and tagging paths. The other three (the condition-check variant of the data path mapping, the create-backup and restore mappings) delegate their catch-all to one of the six. The server's authorization read delegates to the data path mapping. The engine keeps one rule for itself. A ConditionalCheckFailedException carries its item to the client only when the request set ReturnValuesOnConditionCheckFailure to ALL_OLD, which the condition-check mapping applies to a backend's error as it does to the engine's own ConditionFailed; the generic data path mapping, which has no such value to read, discards the item as it does for ConditionFailed. The message is kept. Tests: a Service pass-through test at every one of the nine mappings; at each of the six with a catch-all, a control that Internal("driver text") still becomes the fixed string, and a subscriber-based test that counts error-level log events (none for a Service error, one for an Internal error). tracing-subscriber becomes a dev-dependency of the engine crate for that test. The condition-check item rule has a test per ReturnValuesOnConditionCheckFailure value and one for the generic path. The doc comment states the backend's obligation: the message crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials; an unclassified failure stays Internal, and Transient remains the queue workers' retry signal. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 3 + crates/engine/src/backup.rs | 7 +- .../engine/src/backup/service_error_tests.rs | 93 ++++++++ crates/engine/src/create_table.rs | 211 +++++++++++++++++- crates/engine/src/lib.rs | 44 ++++ crates/engine/src/service_error_log_tests.rs | 102 +++++++++ crates/engine/src/streams.rs | 60 ++++- crates/engine/src/ttl.rs | 53 ++++- crates/engine/src/update_table.rs | 50 ++++- crates/storage/src/error.rs | 20 ++ 11 files changed, 639 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/backup/service_error_tests.rs create mode 100644 crates/engine/src/service_error_log_tests.rs diff --git a/Cargo.lock b/Cargo.lock index c59cdea4e..b54f22d7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1821,6 +1821,7 @@ dependencies = [ "sha2 0.10.9", "tokio", "tracing", + "tracing-subscriber", "uuid", ] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3634c9152..313a0d034 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,3 +21,6 @@ hmac = "0.12" sha2 = "0.10" hex = "0.4" tokio = { workspace = true } + +[dev-dependencies] +tracing-subscriber = { workspace = true } diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 67114a013..2670643a3 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -1250,7 +1250,7 @@ pub(crate) async fn handle_restore_table_to_point_in_time( } /// Convert storage errors to `DynamoDB` errors. -fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { +pub(crate) fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { match e { StorageError::TableNotFound(msg) => DynamoDbError::ResourceNotFoundException(msg), StorageError::TableAlreadyExists(msg) @@ -1278,6 +1278,9 @@ fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::Unsupported(msg) => DynamoDbError::ValidationException(msg), StorageError::LimitExceeded(msg) => DynamoDbError::LimitExceededException(msg), StorageError::BackupInUse(msg) => DynamoDbError::BackupInUseException(msg), + // A backend-classified client error passes through unchanged, before + // the catch-all that reports a storage fault. + StorageError::Service(e) => e, other => { tracing::error!(internal_error = %other, "backup storage error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -1287,4 +1290,6 @@ fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { mod overrides; #[cfg(test)] +mod service_error_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine/src/backup/service_error_tests.rs b/crates/engine/src/backup/service_error_tests.rs new file mode 100644 index 000000000..db01c8263 --- /dev/null +++ b/crates/engine/src/backup/service_error_tests.rs @@ -0,0 +1,93 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! A backend-classified client error reaches the client unchanged through the +//! backup mapping, keeping its variant and message. Control: a raw `Internal` +//! message is still redacted behind the fixed string. + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::error::StorageError; + +use super::{ + create_backup_storage_err_to_dynamo, restore_storage_err_to_dynamo, storage_err_to_dynamo, +}; + +const INTERNAL_MSG: &str = + "The server encountered an internal error trying to fulfill the request."; +const UNAVAILABLE_MSG: &str = "The database is temporarily unavailable, retry shortly."; +const CAPACITY_MSG: &str = + "The level of configured provisioned throughput for the table was exceeded."; + +#[test] +fn service_internal_server_error_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( + INTERNAL_MSG.to_owned(), + ))); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), + other => panic!("expected InternalServerError, got {other:?}"), + } +} + +#[test] +fn service_service_unavailable_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( + UNAVAILABLE_MSG.to_owned(), + ))); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } +} + +#[test] +fn service_capacity_error_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service( + DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), + )); + match err { + DynamoDbError::ProvisionedThroughputExceededException(msg) => { + assert_eq!(msg, CAPACITY_MSG); + } + other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), + } +} + +// The restore mapping delegates everything it does not name, so a Service +// error passes through it as well. +#[test] +fn service_error_passes_through_the_restore_mapping() { + let err = restore_storage_err_to_dynamo(StorageError::Service( + DynamoDbError::BackupNotFoundException("Backup not found: arn".to_owned()), + )); + match err { + DynamoDbError::BackupNotFoundException(msg) => assert_eq!(msg, "Backup not found: arn"), + other => panic!("expected BackupNotFoundException, got {other:?}"), + } +} + +// The create-backup mapping names two table-state variants and delegates the +// rest, so a Service error passes through it too. +#[test] +fn service_error_passes_through_the_create_backup_mapping() { + let err = create_backup_storage_err_to_dynamo( + StorageError::Service(DynamoDbError::LimitExceededException( + "Too many backups in progress".to_owned(), + )), + "t", + ); + match err { + DynamoDbError::LimitExceededException(msg) => { + assert_eq!(msg, "Too many backups in progress"); + } + other => panic!("expected LimitExceededException, got {other:?}"), + } +} + +#[test] +fn internal_driver_text_is_still_redacted() { + let err = storage_err_to_dynamo(StorageError::Internal("driver text".to_owned())); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } +} diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index e9948c111..7638ba53b 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -227,6 +227,17 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo tracing::error!(internal_error = %msg, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } + // The backend already classified this failure into the service error + // vocabulary and chose the client-facing message. Pass it through + // with its variant and message unchanged; it is not a storage fault, + // so it is not logged as one. The one rule the engine keeps for itself + // is the item on a conditional check error: this generic path discards + // it, as it does for its own ConditionFailed, and + // `storage_err_to_dynamo_with_ccf` returns it when the caller asked. + StorageError::Service(DynamoDbError::ConditionalCheckFailedException(msg, _)) => { + DynamoDbError::ConditionalCheckFailedException(msg, None) + } + StorageError::Service(e) => e, } } @@ -251,16 +262,34 @@ pub(crate) fn storage_err_to_dynamo_with_ccf( return_item, ) } + // The engine applies the ReturnValuesOnConditionCheckFailure rule to a + // backend-classified conditional check error as it does to its own: the + // message is the backend's, and the item crosses only when the caller + // asked for ALL_OLD, which only this mapper can see. + StorageError::Service(DynamoDbError::ConditionalCheckFailedException(msg, item)) => { + let return_item = if ccf == ReturnValuesOnConditionCheckFailure::AllOld { + item + } else { + None + }; + DynamoDbError::ConditionalCheckFailedException(msg, return_item) + } other => storage_err_to_dynamo(other), } } #[cfg(test)] mod storage_error_mapping_tests { + use super::{storage_err_to_dynamo, storage_err_to_dynamo_with_ccf}; use extenddb_core::error::DynamoDbError; + use extenddb_core::types::ReturnValuesOnConditionCheckFailure; use extenddb_storage::error::StorageError; - use super::storage_err_to_dynamo; + const INTERNAL_MSG: &str = + "The server encountered an internal error trying to fulfill the request."; + const UNAVAILABLE_MSG: &str = "The database is temporarily unavailable, retry shortly."; + const CAPACITY_MSG: &str = + "The level of configured provisioned throughput for the table was exceeded."; /// A snapshot the backend discarded is retryable, like a transient error. #[test] @@ -271,4 +300,184 @@ mod storage_error_mapping_tests { "{err:?}" ); } + + // storage_err_to_dynamo: a backend-classified error reaches the client + // unchanged, keeping both its variant and its message. + + #[test] + fn service_internal_server_error_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( + INTERNAL_MSG.to_owned(), + ))); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + #[test] + fn service_service_unavailable_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( + UNAVAILABLE_MSG.to_owned(), + ))); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + // Any service error class passes through, not only the two above. + #[test] + fn service_capacity_error_passes_through() { + let err = storage_err_to_dynamo(StorageError::Service( + DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), + )); + match err { + DynamoDbError::ProvisionedThroughputExceededException(msg) => { + assert_eq!(msg, CAPACITY_MSG); + } + other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), + } + } + + // Control: a raw driver message is still redacted behind the fixed string. + #[test] + fn internal_driver_text_is_still_redacted() { + let err = storage_err_to_dynamo(StorageError::Internal("driver text".to_owned())); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + // storage_err_to_dynamo_with_ccf delegates everything but ConditionFailed, + // so the same four cases hold through it. + + #[test] + fn service_internal_server_error_passes_through_with_ccf() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Service(DynamoDbError::InternalServerError(INTERNAL_MSG.to_owned())), + ReturnValuesOnConditionCheckFailure::None, + ); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + #[test] + fn service_service_unavailable_passes_through_with_ccf() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Service(DynamoDbError::ServiceUnavailable( + UNAVAILABLE_MSG.to_owned(), + )), + ReturnValuesOnConditionCheckFailure::AllOld, + ); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + #[test] + fn service_capacity_error_passes_through_with_ccf() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Service(DynamoDbError::ProvisionedThroughputExceededException( + CAPACITY_MSG.to_owned(), + )), + ReturnValuesOnConditionCheckFailure::None, + ); + match err { + DynamoDbError::ProvisionedThroughputExceededException(msg) => { + assert_eq!(msg, CAPACITY_MSG); + } + other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), + } + } + + #[test] + fn internal_driver_text_is_still_redacted_with_ccf() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Internal("driver text".to_owned()), + ReturnValuesOnConditionCheckFailure::None, + ); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + // A Service error carrying ConditionalCheckFailedException keeps the + // backend's message, and its item follows the caller's + // ReturnValuesOnConditionCheckFailure like the engine's own ConditionFailed. + fn backend_item() -> extenddb_core::types::Item { + let mut item = extenddb_core::types::Item::new(); + item.insert( + "pk".to_owned(), + extenddb_core::types::AttributeValue::S("secret".to_owned()), + ); + item + } + + // The generic mapper has no ReturnValuesOnConditionCheckFailure to read, so + // it discards the item from a backend's conditional check error the way it + // does from the engine's own, and keeps the message. + #[test] + fn service_condition_failed_drops_the_backend_item_on_the_generic_path() { + let err = storage_err_to_dynamo(StorageError::Service( + DynamoDbError::ConditionalCheckFailedException( + "The conditional request failed".to_owned(), + Some(backend_item()), + ), + )); + match err { + DynamoDbError::ConditionalCheckFailedException(msg, item) => { + assert_eq!(msg, "The conditional request failed"); + assert!( + item.is_none(), + "item reached the client on the generic path: {item:?}" + ); + } + other => panic!("expected ConditionalCheckFailedException, got {other:?}"), + } + } + + #[test] + fn service_condition_failed_drops_the_backend_item_with_ccf_none() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Service(DynamoDbError::ConditionalCheckFailedException( + "The conditional request failed".to_owned(), + Some(backend_item()), + )), + ReturnValuesOnConditionCheckFailure::None, + ); + match err { + DynamoDbError::ConditionalCheckFailedException(msg, item) => { + assert_eq!(msg, "The conditional request failed"); + assert!( + item.is_none(), + "item reached the client with ccf None: {item:?}" + ); + } + other => panic!("expected ConditionalCheckFailedException, got {other:?}"), + } + } + + #[test] + fn service_condition_failed_keeps_the_backend_item_with_ccf_all_old() { + let err = storage_err_to_dynamo_with_ccf( + StorageError::Service(DynamoDbError::ConditionalCheckFailedException( + "The conditional request failed".to_owned(), + Some(backend_item()), + )), + ReturnValuesOnConditionCheckFailure::AllOld, + ); + match err { + DynamoDbError::ConditionalCheckFailedException(msg, item) => { + assert_eq!(msg, "The conditional request failed"); + assert_eq!(item, Some(backend_item())); + } + other => panic!("expected ConditionalCheckFailedException, got {other:?}"), + } + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 74083fbfa..8550b0d13 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -31,6 +31,8 @@ mod read_helpers; mod request_limits; mod scan; mod search_vectors; +#[cfg(test)] +mod service_error_log_tests; pub mod stream_capture; mod streams; mod tagging; @@ -146,7 +148,12 @@ pub(crate) fn serialize_output( /// /// Use this for storage calls that don't go through `storage_err_to_dynamo` /// (e.g., tagging, metadata operations that return `StorageError` directly). +/// A [`StorageError::Service`] error is the backend's own classification of +/// the failure and reaches the client unchanged, without the fault log line. pub(crate) fn sanitize_storage_error(e: extenddb_storage::error::StorageError) -> DynamoDbError { + if let extenddb_storage::error::StorageError::Service(e) = e { + return e; + } tracing::error!(internal_error = %e, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } @@ -527,3 +534,40 @@ pub async fn dispatch( _ => Err(DynamoDbError::UnknownOperationException(String::new())), } } + +#[cfg(test)] +mod sanitize_storage_error_tests { + use super::sanitize_storage_error; + use extenddb_core::error::DynamoDbError; + use extenddb_storage::error::StorageError; + + // The metadata and tagging paths map through this function; a + // backend-classified error keeps its variant and message there too. + #[test] + fn service_error_passes_through() { + let err = sanitize_storage_error(StorageError::Service(DynamoDbError::ServiceUnavailable( + "retry shortly".to_owned(), + ))); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + // Control: every other variant is still redacted behind the fixed string. + #[test] + fn other_variants_are_redacted() { + for e in [ + StorageError::Internal("driver text".to_owned()), + StorageError::Connection("host unreachable".to_owned()), + StorageError::Transient("pool timeout".to_owned()), + ] { + match sanitize_storage_error(e) { + DynamoDbError::InternalServerError(msg) => { + assert_eq!(msg, "Internal server error"); + } + other => panic!("expected InternalServerError, got {other:?}"), + } + } + } +} diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs new file mode 100644 index 000000000..56b4936bd --- /dev/null +++ b/crates/engine/src/service_error_log_tests.rs @@ -0,0 +1,102 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The second half of the `StorageError::Service` contract: a backend-classified +//! error is not logged as a storage fault, while an unclassified one still is. +//! One subscriber counts error-level events around each engine mapping site +//! that has its own catch-all. + +use std::sync::{Arc, Mutex}; + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::error::StorageError; +use tracing::{Event, Level, Subscriber}; +use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + +/// Counts error-level events. +#[derive(Default)] +struct Errors(Arc>); + +impl Layer for Errors { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + if *event.metadata().level() == Level::ERROR { + *self.0.lock().unwrap() += 1; + } + } +} + +/// Runs `f` under a fresh subscriber and returns how many error events it logged. +fn error_events_during(f: impl FnOnce()) -> usize { + let errors = Errors::default(); + let count = Arc::clone(&errors.0); + let subscriber = tracing_subscriber::registry().with(errors); + let _guard = tracing::subscriber::set_default(subscriber); + f(); + *count.lock().unwrap() +} + +fn service() -> StorageError { + StorageError::Service(DynamoDbError::ServiceUnavailable( + "retry shortly".to_owned(), + )) +} + +fn internal() -> StorageError { + StorageError::Internal("driver text".to_owned()) +} + +type Site = (&'static str, fn(StorageError) -> DynamoDbError); + +/// Every engine function that maps a `StorageError` and owns a catch-all arm. +fn sites() -> Vec { + vec![ + ( + "create_table::storage_err_to_dynamo", + crate::create_table::storage_err_to_dynamo, + ), + ( + "backup::storage_err_to_dynamo", + crate::backup::storage_err_to_dynamo, + ), + ("update_table::update_table_err_to_dynamo", |e| { + crate::update_table::update_table_err_to_dynamo(e, "t") + }), + ( + "streams::storage_to_dynamo", + crate::streams::storage_to_dynamo, + ), + ("ttl::storage_to_dynamo", crate::ttl::storage_to_dynamo), + ("sanitize_storage_error", crate::sanitize_storage_error), + ] +} + +#[test] +fn a_service_error_is_not_logged_as_a_storage_fault_at_any_site() { + for (name, map) in sites() { + let logged = error_events_during(|| { + let err = map(service()); + assert!( + matches!(err, DynamoDbError::ServiceUnavailable(_)), + "{name}: expected ServiceUnavailable, got {err:?}" + ); + }); + assert_eq!(logged, 0, "{name} logged a Service error as a fault"); + } +} + +// Control: the same sites still log an unclassified failure once. +#[test] +fn an_internal_error_is_logged_once_as_a_storage_fault_at_every_site() { + for (name, map) in sites() { + let logged = error_events_during(|| { + let err = map(internal()); + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{name}: expected InternalServerError, got {err:?}" + ); + }); + assert_eq!( + logged, 1, + "{name} logged {logged} fault events for an Internal error" + ); + } +} diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index c8ba419bc..de33cb9d7 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -406,10 +406,14 @@ fn get_records_limit(limit: Option) -> Result { } } -fn storage_to_dynamo(e: StorageError) -> DynamoDbError { +pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { match e { StorageError::Validation(msg) => DynamoDbError::ValidationException(msg), StorageError::TableNotFound(name) => DynamoDbError::ResourceNotFoundException(name), + // The backend already classified this failure into the service error + // vocabulary and chose the client-facing message. Pass it through + // unchanged; it is not a storage fault, so it is not logged as one. + StorageError::Service(e) => e, other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -417,6 +421,60 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { } } +#[cfg(test)] +mod storage_error_mapping_tests { + use super::storage_to_dynamo; + use extenddb_core::error::DynamoDbError; + use extenddb_storage::error::StorageError; + + // A backend-classified error reaches the client unchanged through the + // streams mapper, keeping both its variant and its message. + + #[test] + fn service_internal_server_error_passes_through() { + let err = storage_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( + "backend internal".to_owned(), + ))); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "backend internal"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + #[test] + fn service_service_unavailable_passes_through() { + let err = storage_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( + "retry shortly".to_owned(), + ))); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + #[test] + fn service_expired_iterator_passes_through() { + let err = storage_to_dynamo(StorageError::Service( + DynamoDbError::ExpiredIteratorException("Iterator expired.".to_owned()), + )); + match err { + DynamoDbError::ExpiredIteratorException(msg) => assert_eq!(msg, "Iterator expired."), + other => panic!("expected ExpiredIteratorException, got {other:?}"), + } + } + + // Control: an unclassified driver error is still redacted behind the fixed + // string, with the driver text absent from the client message. + #[test] + fn internal_driver_text_is_redacted() { + let err = storage_to_dynamo(StorageError::Internal("driver text".to_owned())); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } +} + #[cfg(test)] mod tests { /// AT_SEQUENCE_NUMBER converts to AFTER by subtracting 1 and padding to diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index fac027d4b..902575181 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -214,7 +214,7 @@ fn validate_ttl_attribute_name(name: &str) -> Result<(), DynamoDbError> { Ok(()) } -fn storage_to_dynamo(e: StorageError) -> DynamoDbError { +pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { match e { // A backend's refusal of the request (the Cassandra backend refuses // TTL on a table with an asynchronously propagated GSI): a client @@ -226,6 +226,10 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::TableNotActive(name) => { DynamoDbError::ResourceInUseException(format!("Table {name} is not in ACTIVE state")) } + // The backend already classified this failure into the service error + // vocabulary and chose the client-facing message. Pass it through + // unchanged; it is not a storage fault, so it is not logged as one. + StorageError::Service(e) => e, other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -237,6 +241,53 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { mod tests { use super::*; + // A backend-classified error reaches the client unchanged through the TTL + // mapper, keeping both its variant and its message. + + #[test] + fn service_internal_server_error_passes_through() { + let err = storage_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( + "backend internal".to_owned(), + ))); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "backend internal"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + + #[test] + fn service_service_unavailable_passes_through() { + let err = storage_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( + "retry shortly".to_owned(), + ))); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + #[test] + fn service_limit_exceeded_passes_through() { + let err = storage_to_dynamo(StorageError::Service( + DynamoDbError::LimitExceededException("limit reached".to_owned()), + )); + match err { + DynamoDbError::LimitExceededException(msg) => assert_eq!(msg, "limit reached"), + other => panic!("expected LimitExceededException, got {other:?}"), + } + } + + // Control: an unclassified driver error is still redacted behind the fixed + // string, with the driver text absent from the client message. + #[test] + fn internal_driver_text_is_redacted() { + let err = storage_to_dynamo(StorageError::Internal("driver text".to_owned())); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + #[test] fn valid_ttl_attribute_names() { assert!(validate_ttl_attribute_name("ttl").is_ok()); diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 6db763f82..357f6c80f 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -309,7 +309,7 @@ fn projected_after_gsi_updates( /// yet returns `Unsupported` or `IndexesInUse` from `update_table`, and the /// vector capability gate refuses vector requests before the backend is called /// at all, so a wire test cannot provoke either one today. -fn update_table_err_to_dynamo( +pub(crate) fn update_table_err_to_dynamo( e: extenddb_storage::error::StorageError, table_name: &str, ) -> DynamoDbError { @@ -339,6 +339,10 @@ fn update_table_err_to_dynamo( // request. The backend supplies the whole message because only it knows // the state. StorageError::IndexesInUse(msg) => DynamoDbError::ResourceInUseException(msg), + // The backend already classified this failure into the service error + // vocabulary and chose the client-facing message. Pass it through + // unchanged; it is not a storage fault, so it is not logged as one. + StorageError::Service(e) => e, other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -351,6 +355,50 @@ mod tests { use super::*; use extenddb_storage::error::StorageError; + // A backend-classified error reaches the client unchanged through the + // UpdateTable mapper, keeping both its variant and its message. + + #[test] + fn service_service_unavailable_passes_through() { + let err = update_table_err_to_dynamo( + StorageError::Service(DynamoDbError::ServiceUnavailable( + "retry shortly".to_owned(), + )), + "t", + ); + match err { + DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), + other => panic!("expected ServiceUnavailable, got {other:?}"), + } + } + + #[test] + fn service_capacity_error_passes_through() { + let err = update_table_err_to_dynamo( + StorageError::Service(DynamoDbError::ProvisionedThroughputExceededException( + "capacity".to_owned(), + )), + "t", + ); + match err { + DynamoDbError::ProvisionedThroughputExceededException(msg) => { + assert_eq!(msg, "capacity"); + } + other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), + } + } + + // Control: an unclassified driver error is still redacted behind the fixed + // string, with the driver text absent from the client message. + #[test] + fn internal_driver_text_is_redacted() { + let err = update_table_err_to_dynamo(StorageError::Internal("driver text".to_owned()), "t"); + match err { + DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), + other => panic!("expected InternalServerError, got {other:?}"), + } + } + #[test] fn a_created_gsi_throughput_below_one_is_refused() { let input = |pt: Value| -> UpdateTableInput { diff --git a/crates/storage/src/error.rs b/crates/storage/src/error.rs index 8fe3ac287..5a03a7d30 100755 --- a/crates/storage/src/error.rs +++ b/crates/storage/src/error.rs @@ -92,4 +92,24 @@ pub enum StorageError { Unsupported(String), #[error("Internal error: {0}")] Internal(String), + /// A client error the backend has already classified. The engine passes it + /// to the client with its variant and message unchanged and does not log it + /// as a storage fault. One exception: a `ConditionalCheckFailedException` + /// carries its item to the client only when the request set + /// `ReturnValuesOnConditionCheckFailure` to `ALL_OLD`, the rule the engine + /// applies to its own `ConditionFailed`. Use this + /// when the backend can map its own failure onto a specific service error + /// with its own message, for example a hosted database reporting a + /// documented unavailability or capacity condition. + /// + /// The message inside crosses the wire verbatim; the engine does not + /// inspect or redact it. It must be the text the service documents for that + /// error class, or text of the same shape, and must not contain driver + /// output, host names, connection strings or credentials. A failure the + /// backend cannot classify stays [`Self::Internal`], which the engine + /// redacts behind a fixed string. Distinct from [`Self::Transient`], which + /// the engine also redacts and which the queue workers read as the retry + /// signal; `Service` is for request paths only. + #[error(transparent)] + Service(extenddb_core::error::DynamoDbError), } From d994093eab779ee73fd88c4b7ad9df392b9688f7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:45:46 +0000 Subject: [PATCH 02/12] docs: describe StorageError::Service in the storage design, the manuals, the RFCs and an ADR The storage design lists the variant beside the Internal redaction rule and states the backend's obligation for the message. The security model's error message section names it as the one path that carries backend-chosen text to a client, under the same wording rule as the engine's own messages. The backend author manual's DataEngine section states when to return it and when a failure stays Internal. RFC-0003 section 9.2 adds the obligation to the error fidelity criteria. RFC-0002 states that variants may be added to StorageError in a minor release, so a backend crate matching on it exhaustively carries a catch-all arm. ADR-0023 records the decision, the options not taken and the consequences. --- .../0023-backend-classified-client-error.md | 92 +++++++++++++++++++ docs/adr/README.md | 3 +- docs/design/04-component-storage.md | 17 +++- docs/manuals/10-security-model.md | 1 + docs/manuals/12-extending-extenddb-storage.md | 1 + docs/rfcs/0002-backend-plugin-policy.md | 2 +- docs/rfcs/0003-backend-acceptance-criteria.md | 2 +- 7 files changed, 113 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0023-backend-classified-client-error.md diff --git a/docs/adr/0023-backend-classified-client-error.md b/docs/adr/0023-backend-classified-client-error.md new file mode 100644 index 000000000..6049626bd --- /dev/null +++ b/docs/adr/0023-backend-classified-client-error.md @@ -0,0 +1,92 @@ +# ADR-0023: A backend-classified client error passes through the engine unchanged + +- Status: Accepted +- Date: 2026-10-24 +- Deciders: @LeeroyHannigan + +## Context + +Every storage trait method returns `Result`. The engine maps a +`StorageError` to the client-facing `DynamoDbError` at nine functions +(`crates/engine/src/create_table.rs`, `backup.rs`, `update_table.rs`, +`streams.rs`, `ttl.rs`, `lib.rs`), each of which names the variants it knows +and ends in a catch-all that logs the error at error level and returns +`InternalServerError("Internal server error")`. The catch-all is the redaction +rule the security model documents: driver text, SQL, paths and connection +details never reach a client (`docs/manuals/10-security-model.md`, Error +Message Security; RFC-0003 section 9.2). + +The rule has a cost for a backend that knows more than the engine does. A +hosted database reports documented conditions with their own class and text: +a capacity limit, a maintenance window, a regional unavailability. The engine +has no variant for "here is the client error, already classified", so such a +backend can only return `Internal` (redacted to a generic 500 and logged as a +fault) or `Transient` (also redacted, and read by the in-tree queue workers as +the retry signal). The client sees a message that says nothing about what to +do, and the operator's log counts a documented condition among storage faults. + +## Options Considered + +1. **A `Service(DynamoDbError)` variant passed through unchanged.** The backend + constructs the client error; every engine mapping site returns it without + inspecting, rewriting or logging it. The backend takes on the redaction + obligation for the message it supplies. +2. **A structured variant per condition** (`Throttled { kind, reasons }`, + `Unavailable { retry_after }`, and so on), with the engine choosing the + message. Keeps the message in the engine, at the cost of one variant and + one engine mapping per condition a backend may want to report, and a + message the backend cannot tailor. +3. **Leave the enum as it is.** A backend reports every failure as `Internal` + or `Transient`; the client sees the fixed 500 text. + +## Decision + +Add `StorageError::Service(DynamoDbError)`, marked `#[error(transparent)]`, +and make every engine function that maps a `StorageError` to a client error +return it unchanged and without the fault log line. The engine applies one +rule of its own to the payload: for `ConditionalCheckFailedException`, the +request's `ReturnValuesOnConditionCheckFailure` decides whether the item is +returned, as it does for the engine's `ConditionFailed`. + +## Rationale + +- The engine cannot know the message for a condition only the backend sees; + option 2 would re-derive each hosted database's documented text inside the + engine, one variant at a time, and lag the databases. +- The status code and the body shape still come from the `DynamoDbError` + variant through the one serializer, so a backend cannot produce a status or + a shape outside the service's catalog through this variant. +- The redaction rule for `Internal` and every other variant is unchanged, and + a test at each site keeps it so. The one new path is named in the security + model, the backend author manual, RFC-0003 section 9.2 and the variant's + doc comment, with the obligation stated the same way in each: the message + crosses the wire verbatim and must be service-shaped text with no driver + output, host names, connection strings or credentials. +- A subscriber-based test counts error-level log events at every mapping + site: none for a `Service` error, one for an `Internal` error, so the + "not logged as a fault" half of the contract cannot regress silently. + +## Consequences + +- A backend can report a documented hosted-database condition with the + service's error class and its own message, and the operator's fault log no + longer counts it. +- Reviewers of a backend crate read the text it puts inside `Service` as + client-visible wording, under the same rule as the engine's own messages. +- `StorageError` gains a variant; RFC-0002 now states that variants may be + added in a minor release, so a backend crate matching on it exhaustively + carries a catch-all arm. The engine's own data path match stays exhaustive + so the compiler reports a mapping site that misses a new variant. +- No in-tree backend returns `Service` yet. The first one to do so adds the + condition it reports and the measured service text to its fidelity notes. + +--- + +## License + +Copyright 2026 ExtendDB contributors. Licensed under the Apache License, Version 2.0. +See [LICENSE](../../LICENSE) for the full text. + +This software is provided "as is" without warranty of any kind. ExtendDB is not +affiliated with, endorsed by, or sponsored by Amazon Web Services. "DynamoDB" is +a trademark of Amazon.com, Inc. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2deec1259..69f3ea0b8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -48,4 +48,5 @@ decision, write a new ADR. | [0019](0019-cassandra-logical-backup-restore.md) | Cassandra: logical backup and restore | Accepted | | [0020](0020-cassandra-occ-update-item.md) | Cassandra: optimistic concurrency control for UpdateItem and PutItem | Accepted | | [0021](0021-cassandra-lwt-delete-atomicity-gap.md) | Cassandra: LWT delete atomicity gap and required worker/saga pattern | Accepted | -| [0022](0022-trust-policy-deny-over-allow.md) | Role trust-policy evaluation follows IAM Deny-over-Allow order | Accepted | \ No newline at end of file +| [0022](0022-trust-policy-deny-over-allow.md) | Role trust-policy evaluation follows IAM Deny-over-Allow order | Accepted | +| [0023](0023-backend-classified-client-error.md) | A backend-classified client error passes through the engine unchanged | Accepted | diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index dcfda3a3d..73565e3e8 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -334,8 +334,21 @@ Storage backends write stream records atomically with data writes when `stream` - `IdempotentMismatch` — idempotency token exists with different operations - `IndexNotFound` — secondary index does not exist - `Internal(String)` — backend-specific error - -The `engine` crate maps `StorageError` to wire protocol error responses. +- `Service(DynamoDbError)`: a client error the backend has already classified, carrying its own message + +The `engine` crate maps `StorageError` to wire protocol error responses. An +`Internal` error is logged at error level and reaches the client as the fixed +`InternalServerError` text, so backend driver messages never cross the wire. +A `Service` error is the exception: the backend has mapped its own failure onto +a service error class (a hosted database reporting a documented unavailability +or capacity condition, for example), so every engine mapping site returns it +to the client with its variant and message unchanged and does not log it as a +storage fault (a conditional check error carries its item only when the +request asked for `ALL_OLD`, as with the engine's own). The backend is +responsible for the message it puts inside: it crosses the wire verbatim, so it +must be service-shaped text with no driver output, host names, connection +strings or credentials, and a failure the backend cannot classify stays +`Internal`. ## 5. PostgreSQL Backend Implementation diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index bb7a1c75d..3c7561af2 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -222,6 +222,7 @@ Import/export file paths are validated: - DynamoDB-fidelity error messages reproduce real DynamoDB exactly (no additional information) - Internal errors (database connection failures, SQL errors, I/O errors) are logged server-side but return generic messages to clients - Stack traces, file paths, and SQL text are never exposed to clients +- One path carries backend-chosen text to a client: a backend may return `StorageError::Service(DynamoDbError)` when it has classified its own failure into a service error class, and the engine returns that error with its message unchanged. The message inside is client-facing text the backend author owns; it must not contain driver output, SQL text, paths or connection details, and it is reviewed as client-visible wording under the same rule as the engine's own messages ## Operational Security diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index 75f701d54..7e0eb5ac8 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -98,6 +98,7 @@ Key design decisions: - **Items** are `BTreeMap`. A new backend must handle the full `AttributeValue` type (S, N, B, SS, NS, BS, L, M, BOOL, NULL). - **Query** must support forward/reverse sort order, exclusive start key pagination, and routing to secondary index storage. - **Parallel scan** uses `segment` and `total_segments` to partition the keyspace. +- **Errors**: return the named `StorageError` variant for every condition the engine maps (`TableNotFound`, `ConditionFailed`, `TransactionCanceled`, `Validation`, `Unsupported`, `Transient` and the rest); the engine chooses the client-facing message and redacts anything it does not recognise behind a fixed `InternalServerError`. When the backend can classify its own failure into a service error class with a message of its own (a hosted database reporting a documented unavailability or capacity condition), return `StorageError::Service(DynamoDbError)`: the engine passes it to the client with its variant and message unchanged and does not log it as a storage fault (a conditional check error carries its item only when the request asked for `ALL_OLD`, as with the engine's own). That message crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials. A failure the backend cannot classify stays `Internal`. ### MetadataEngine diff --git a/docs/rfcs/0002-backend-plugin-policy.md b/docs/rfcs/0002-backend-plugin-policy.md index 7d67abdb3..409012146 100644 --- a/docs/rfcs/0002-backend-plugin-policy.md +++ b/docs/rfcs/0002-backend-plugin-policy.md @@ -255,7 +255,7 @@ cargo build --no-default-features --bin extenddb ### Release model -ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. +ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Variants may be added to `StorageError` in a minor release; a backend crate that matches on it exhaustively must carry a catch-all arm. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. ### Third-party backends outside ExtendDB organization diff --git a/docs/rfcs/0003-backend-acceptance-criteria.md b/docs/rfcs/0003-backend-acceptance-criteria.md index 2c919950e..f5dc37e96 100644 --- a/docs/rfcs/0003-backend-acceptance-criteria.md +++ b/docs/rfcs/0003-backend-acceptance-criteria.md @@ -125,7 +125,7 @@ If implementing pushdown, numeric comparisons must be numeric (not string-lexico **9.1. No silent degradation.** If an operation cannot be performed correctly, the backend must return an error, never silently drop side-effects (stream records, index updates), return partial results without a `LastEvaluatedKey`, or succeed while leaving inconsistent state. -**9.2. DynamoDB error codes.** Client-visible errors must use DynamoDB-compatible error codes and HTTP status codes. Internal storage errors (connection failures, type mismatches) must map to appropriate DynamoDB errors, typically `InternalServerError` (500) with retry semantics, or `ValidationException` (400) for input problems. Backend-specific error codes must never leak to clients. +**9.2. DynamoDB error codes.** Client-visible errors must use DynamoDB-compatible error codes and HTTP status codes. Internal storage errors (connection failures, type mismatches) must map to appropriate DynamoDB errors, typically `InternalServerError` (500) with retry semantics, or `ValidationException` (400) for input problems. Backend-specific error codes must never leak to clients. A backend that returns `StorageError::Service` is responsible for the message it carries: the engine passes that error to the client with its message unchanged and does not redact it, so the message must be service-shaped text with no driver output, host names, connection strings or credentials. ### 10. Operational Correctness From 4ef952e8488322d2c115e80f681d46c94fd762ac Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:36:48 +0000 Subject: [PATCH 03/12] style(engine): keep the backup module declarations in rustfmt order Main added the runtime, store_identity, store_maintenance and sync modules to backup.rs. The merge placed this branch's service_error_tests declaration after them, where rustfmt wants it before store_identity. This commit moves the declaration. Nothing else changes. --- crates/engine/src/backup.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index f578f965a..dce38ad3f 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -2181,12 +2181,12 @@ mod pitr; pub mod reconciler; mod restore; mod runtime; +#[cfg(test)] +mod service_error_tests; pub mod store_identity; pub mod store_maintenance; pub mod sync; #[cfg(test)] -mod service_error_tests; -#[cfg(test)] mod tests; pub use pitr::refuse_before_authorization as refuse_point_in_time_recovery; From 3bcee8db15579c7aa3e9852a08e9ec42c56c359e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:18:54 +0000 Subject: [PATCH 04/12] fix(engine): one Service mapping for every site, which drops a conditional check item A ConditionalCheckFailedException inside StorageError::Service reached the client with its item through the backup, UpdateTable, streams and TTL mappings and through sanitize_storage_error. Only the two create_table mappings applied the ALL_OLD rule that the variant's doc comment states. create_table::service_err_to_dynamo now holds the rule, and every Service arm calls it. It returns the error unchanged, except that a conditional check error loses its item. storage_err_to_dynamo_with_ccf keeps one arm of its own, for a request that set ReturnValuesOnConditionCheckFailure to ALL_OLD. The tests now give every mapping the same rows: five backend-classified errors, each with a message that the engine never writes. Each row holds the body the client gets (error_document), and the CCF row has an item. The rows run at the seven mappings that the crate root can reach. The create-backup, restore and shard lookup mappings delegate to these, and their own modules run the rows through them. This commit removes the per-site tests that the rows replace. They used the engine's own text "The conditional request failed" as the backend message. A mapping that replaced the backend message with that text passed them. --- .../engine/src/backup/service_error_tests.rs | 96 +------ crates/engine/src/backup_requests.rs | 4 +- crates/engine/src/create_table.rs | 262 ++++-------------- crates/engine/src/lib.rs | 18 +- crates/engine/src/service_error_log_tests.rs | 113 ++++++-- crates/engine/src/streams.rs | 5 +- crates/engine/src/streams_tests.rs | 64 +---- crates/engine/src/ttl.rs | 52 +--- crates/engine/src/update_table.rs | 5 +- crates/engine/src/update_table_tests.rs | 44 --- 10 files changed, 176 insertions(+), 487 deletions(-) diff --git a/crates/engine/src/backup/service_error_tests.rs b/crates/engine/src/backup/service_error_tests.rs index db01c8263..a6f6c9301 100644 --- a/crates/engine/src/backup/service_error_tests.rs +++ b/crates/engine/src/backup/service_error_tests.rs @@ -1,93 +1,21 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! A backend-classified client error reaches the client unchanged through the -//! backup mapping, keeping its variant and message. Control: a raw `Internal` -//! message is still redacted behind the fixed string. +//! The create-backup and restore mappings name a few table-state variants and +//! delegate the rest to `backup_requests::storage_err_to_dynamo`, so a +//! backend-classified error reaches the client through them as it does through +//! that mapping (`service_error_log_tests`). -use extenddb_core::error::DynamoDbError; +use extenddb_core::error::error_document; use extenddb_storage::error::StorageError; -use super::{ - create_backup_storage_err_to_dynamo, restore_storage_err_to_dynamo, storage_err_to_dynamo, -}; - -const INTERNAL_MSG: &str = - "The server encountered an internal error trying to fulfill the request."; -const UNAVAILABLE_MSG: &str = "The database is temporarily unavailable, retry shortly."; -const CAPACITY_MSG: &str = - "The level of configured provisioned throughput for the table was exceeded."; - -#[test] -fn service_internal_server_error_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( - INTERNAL_MSG.to_owned(), - ))); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), - other => panic!("expected InternalServerError, got {other:?}"), - } -} - -#[test] -fn service_service_unavailable_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( - UNAVAILABLE_MSG.to_owned(), - ))); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } -} - -#[test] -fn service_capacity_error_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service( - DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), - )); - match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); - } - other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), - } -} - -// The restore mapping delegates everything it does not name, so a Service -// error passes through it as well. -#[test] -fn service_error_passes_through_the_restore_mapping() { - let err = restore_storage_err_to_dynamo(StorageError::Service( - DynamoDbError::BackupNotFoundException("Backup not found: arn".to_owned()), - )); - match err { - DynamoDbError::BackupNotFoundException(msg) => assert_eq!(msg, "Backup not found: arn"), - other => panic!("expected BackupNotFoundException, got {other:?}"), - } -} - -// The create-backup mapping names two table-state variants and delegates the -// rest, so a Service error passes through it too. -#[test] -fn service_error_passes_through_the_create_backup_mapping() { - let err = create_backup_storage_err_to_dynamo( - StorageError::Service(DynamoDbError::LimitExceededException( - "Too many backups in progress".to_owned(), - )), - "t", - ); - match err { - DynamoDbError::LimitExceededException(msg) => { - assert_eq!(msg, "Too many backups in progress"); - } - other => panic!("expected LimitExceededException, got {other:?}"), - } -} +use super::{create_backup_storage_err_to_dynamo, restore_storage_err_to_dynamo}; #[test] -fn internal_driver_text_is_still_redacted() { - let err = storage_err_to_dynamo(StorageError::Internal("driver text".to_owned())); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), +fn a_service_error_reaches_the_client_as_classified_through_create_backup_and_restore() { + for (error, body) in crate::service_error_log_tests::rows() { + let create = create_backup_storage_err_to_dynamo(StorageError::Service(error.clone()), "t"); + assert_eq!(error_document(&create), body, "CreateBackup: {error:?}"); + let restore = restore_storage_err_to_dynamo(StorageError::Service(error.clone())); + assert_eq!(error_document(&restore), body, "Restore: {error:?}"); } } diff --git a/crates/engine/src/backup_requests.rs b/crates/engine/src/backup_requests.rs index 3fcc66147..267173ee4 100644 --- a/crates/engine/src/backup_requests.rs +++ b/crates/engine/src/backup_requests.rs @@ -576,9 +576,7 @@ pub(crate) fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::Unsupported(msg) => DynamoDbError::ValidationException(msg), StorageError::LimitExceeded(msg) => DynamoDbError::LimitExceededException(msg), StorageError::BackupInUse(msg) => DynamoDbError::BackupInUseException(msg), - // A backend-classified client error passes through unchanged, before - // the catch-all that reports a storage fault. - StorageError::Service(e) => e, + StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { tracing::error!(internal_error = %other, "backup storage error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index d6c1a60c0..353a91dfb 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -229,17 +229,26 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo tracing::error!(internal_error = %msg, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } - // The backend already classified this failure into the service error - // vocabulary and chose the client-facing message. Pass it through - // with its variant and message unchanged; it is not a storage fault, - // so it is not logged as one. The one rule the engine keeps for itself - // is the item on a conditional check error: this generic path discards - // it, as it does for its own ConditionFailed, and - // `storage_err_to_dynamo_with_ccf` returns it when the caller asked. - StorageError::Service(DynamoDbError::ConditionalCheckFailedException(msg, _)) => { + StorageError::Service(e) => service_err_to_dynamo(e), + } +} + +/// The client error inside a [`StorageError::Service`], as every mapping in +/// the engine returns it. The backend already classified the failure and +/// chose the message, so the error keeps its variant and message, and it is +/// not logged as a storage fault. The one rule the engine keeps for itself is +/// the item on a conditional check error: it is dropped here, as the generic +/// path drops the item of the engine's own `ConditionFailed`, and only +/// [`storage_err_to_dynamo_with_ccf`] returns it, to a request that set +/// `ReturnValuesOnConditionCheckFailure` to `ALL_OLD`. +/// +/// [`StorageError::Service`]: extenddb_storage::error::StorageError::Service +pub(crate) fn service_err_to_dynamo(e: DynamoDbError) -> DynamoDbError { + match e { + DynamoDbError::ConditionalCheckFailedException(msg, _) => { DynamoDbError::ConditionalCheckFailedException(msg, None) } - StorageError::Service(e) => e, + other => other, } } @@ -264,17 +273,13 @@ pub(crate) fn storage_err_to_dynamo_with_ccf( return_item, ) } - // The engine applies the ReturnValuesOnConditionCheckFailure rule to a - // backend-classified conditional check error as it does to its own: the - // message is the backend's, and the item crosses only when the caller - // asked for ALL_OLD, which only this mapper can see. - StorageError::Service(DynamoDbError::ConditionalCheckFailedException(msg, item)) => { - let return_item = if ccf == ReturnValuesOnConditionCheckFailure::AllOld { - item - } else { - None - }; - DynamoDbError::ConditionalCheckFailedException(msg, return_item) + // A backend-classified conditional check error keeps its message, and + // its item crosses only when the caller asked for ALL_OLD, which only + // this mapper can see. Without ALL_OLD the generic mapping drops it. + StorageError::Service(DynamoDbError::ConditionalCheckFailedException(msg, item)) + if ccf == ReturnValuesOnConditionCheckFailure::AllOld => + { + DynamoDbError::ConditionalCheckFailedException(msg, item) } other => storage_err_to_dynamo(other), } @@ -282,16 +287,12 @@ pub(crate) fn storage_err_to_dynamo_with_ccf( #[cfg(test)] mod storage_error_mapping_tests { - use super::{storage_err_to_dynamo, storage_err_to_dynamo_with_ccf}; - use extenddb_core::error::DynamoDbError; - use extenddb_core::types::ReturnValuesOnConditionCheckFailure; + use extenddb_core::error::{DynamoDbError, error_document}; + use extenddb_core::types::{AttributeValue, Item, ReturnValuesOnConditionCheckFailure}; use extenddb_storage::error::StorageError; + use serde_json::json; - const INTERNAL_MSG: &str = - "The server encountered an internal error trying to fulfill the request."; - const UNAVAILABLE_MSG: &str = "The database is temporarily unavailable, retry shortly."; - const CAPACITY_MSG: &str = - "The level of configured provisioned throughput for the table was exceeded."; + use super::{storage_err_to_dynamo, storage_err_to_dynamo_with_ccf}; /// A snapshot the backend discarded is retryable, like a transient error. #[test] @@ -303,183 +304,38 @@ mod storage_error_mapping_tests { ); } - // storage_err_to_dynamo: a backend-classified error reaches the client - // unchanged, keeping both its variant and its message. - - #[test] - fn service_internal_server_error_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( - INTERNAL_MSG.to_owned(), - ))); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - - #[test] - fn service_service_unavailable_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( - UNAVAILABLE_MSG.to_owned(), - ))); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } - } - - // Any service error class passes through, not only the two above. - #[test] - fn service_capacity_error_passes_through() { - let err = storage_err_to_dynamo(StorageError::Service( - DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), - )); - match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); - } - other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), - } - } - - // Control: a raw driver message is still redacted behind the fixed string. - #[test] - fn internal_driver_text_is_still_redacted() { - let err = storage_err_to_dynamo(StorageError::Internal("driver text".to_owned())); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - - // storage_err_to_dynamo_with_ccf delegates everything but ConditionFailed, - // so the same four cases hold through it. - - #[test] - fn service_internal_server_error_passes_through_with_ccf() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Service(DynamoDbError::InternalServerError(INTERNAL_MSG.to_owned())), - ReturnValuesOnConditionCheckFailure::None, - ); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, INTERNAL_MSG), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - + /// Only this mapper reads `ReturnValuesOnConditionCheckFailure`: a + /// backend's conditional check error reaches the client with its own + /// message, and with its item only under `ALL_OLD`. The mappings that + /// drop the item are checked in `service_error_log_tests`. #[test] - fn service_service_unavailable_passes_through_with_ccf() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Service(DynamoDbError::ServiceUnavailable( - UNAVAILABLE_MSG.to_owned(), - )), - ReturnValuesOnConditionCheckFailure::AllOld, - ); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, UNAVAILABLE_MSG), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } - } - - #[test] - fn service_capacity_error_passes_through_with_ccf() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Service(DynamoDbError::ProvisionedThroughputExceededException( - CAPACITY_MSG.to_owned(), - )), - ReturnValuesOnConditionCheckFailure::None, - ); - match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); - } - other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), - } - } - - #[test] - fn internal_driver_text_is_still_redacted_with_ccf() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Internal("driver text".to_owned()), - ReturnValuesOnConditionCheckFailure::None, - ); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - - // A Service error carrying ConditionalCheckFailedException keeps the - // backend's message, and its item follows the caller's - // ReturnValuesOnConditionCheckFailure like the engine's own ConditionFailed. - fn backend_item() -> extenddb_core::types::Item { - let mut item = extenddb_core::types::Item::new(); - item.insert( - "pk".to_owned(), - extenddb_core::types::AttributeValue::S("secret".to_owned()), - ); - item - } - - // The generic mapper has no ReturnValuesOnConditionCheckFailure to read, so - // it discards the item from a backend's conditional check error the way it - // does from the engine's own, and keeps the message. - #[test] - fn service_condition_failed_drops_the_backend_item_on_the_generic_path() { - let err = storage_err_to_dynamo(StorageError::Service( - DynamoDbError::ConditionalCheckFailedException( - "The conditional request failed".to_owned(), - Some(backend_item()), + fn a_backend_conditional_check_error_keeps_its_item_only_under_all_old() { + let message = "The stored item does not match the condition."; + let mut item = Item::new(); + item.insert("pk".to_owned(), AttributeValue::S("stored".to_owned())); + for (ccf, body) in [ + ( + ReturnValuesOnConditionCheckFailure::None, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", + "message": message, + }), ), - )); - match err { - DynamoDbError::ConditionalCheckFailedException(msg, item) => { - assert_eq!(msg, "The conditional request failed"); - assert!( - item.is_none(), - "item reached the client on the generic path: {item:?}" - ); - } - other => panic!("expected ConditionalCheckFailedException, got {other:?}"), - } - } - - #[test] - fn service_condition_failed_drops_the_backend_item_with_ccf_none() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Service(DynamoDbError::ConditionalCheckFailedException( - "The conditional request failed".to_owned(), - Some(backend_item()), - )), - ReturnValuesOnConditionCheckFailure::None, - ); - match err { - DynamoDbError::ConditionalCheckFailedException(msg, item) => { - assert_eq!(msg, "The conditional request failed"); - assert!( - item.is_none(), - "item reached the client with ccf None: {item:?}" - ); - } - other => panic!("expected ConditionalCheckFailedException, got {other:?}"), - } - } - - #[test] - fn service_condition_failed_keeps_the_backend_item_with_ccf_all_old() { - let err = storage_err_to_dynamo_with_ccf( - StorageError::Service(DynamoDbError::ConditionalCheckFailedException( - "The conditional request failed".to_owned(), - Some(backend_item()), - )), - ReturnValuesOnConditionCheckFailure::AllOld, - ); - match err { - DynamoDbError::ConditionalCheckFailedException(msg, item) => { - assert_eq!(msg, "The conditional request failed"); - assert_eq!(item, Some(backend_item())); - } - other => panic!("expected ConditionalCheckFailedException, got {other:?}"), + ( + ReturnValuesOnConditionCheckFailure::AllOld, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", + "message": message, + "Item": {"pk": {"S": "stored"}}, + }), + ), + ] { + let error = DynamoDbError::ConditionalCheckFailedException( + message.to_owned(), + Some(item.clone()), + ); + let got = storage_err_to_dynamo_with_ccf(StorageError::Service(error), ccf); + assert_eq!(error_document(&got), body, "{ccf:?}"); } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 14548af23..2c83b0b80 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -203,10 +203,11 @@ pub(crate) fn serialize_output( /// Use this for storage calls that don't go through `storage_err_to_dynamo` /// (e.g., tagging, metadata operations that return `StorageError` directly). /// A [`StorageError::Service`] error is the backend's own classification of -/// the failure and reaches the client unchanged, without the fault log line. +/// the failure and reaches the client through +/// [`create_table::service_err_to_dynamo`], without the fault log line. pub(crate) fn sanitize_storage_error(e: extenddb_storage::error::StorageError) -> DynamoDbError { if let extenddb_storage::error::StorageError::Service(e) = e { - return e; + return create_table::service_err_to_dynamo(e); } tracing::error!(internal_error = %e, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -654,19 +655,6 @@ mod sanitize_storage_error_tests { use extenddb_core::error::DynamoDbError; use extenddb_storage::error::StorageError; - // The metadata and tagging paths map through this function; a - // backend-classified error keeps its variant and message there too. - #[test] - fn service_error_passes_through() { - let err = sanitize_storage_error(StorageError::Service(DynamoDbError::ServiceUnavailable( - "retry shortly".to_owned(), - ))); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } - } - // Control: every other variant is still redacted behind the fixed string. #[test] fn other_variants_are_redacted() { diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs index b4b8940ed..643aa5a89 100644 --- a/crates/engine/src/service_error_log_tests.rs +++ b/crates/engine/src/service_error_log_tests.rs @@ -1,14 +1,19 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The second half of the `StorageError::Service` contract: a backend-classified -//! error is not logged as a storage fault, while an unclassified one still is. -//! One subscriber counts error-level events around each engine mapping site -//! that has its own catch-all. +//! The `StorageError::Service` contract at the engine functions that map a +//! `StorageError` to a client error: the client gets the error class and the +//! message the backend chose, never the item of a conditional check error, and +//! the error is not logged as a storage fault, while an unclassified error +//! still is. The three mappings that only delegate to these and are private to +//! their modules (the create-backup, restore and shard lookup mappings) are +//! checked there with [`rows`]. use std::sync::{Arc, Mutex}; -use extenddb_core::error::DynamoDbError; +use extenddb_core::error::{DynamoDbError, error_document}; +use extenddb_core::types::{AttributeValue, Item, ReturnValuesOnConditionCheckFailure}; use extenddb_storage::error::StorageError; +use serde_json::{Value, json}; use tracing::{Event, Level, Subscriber}; use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; @@ -34,25 +39,67 @@ fn error_events_during(f: impl FnOnce()) -> usize { *count.lock().unwrap() } -fn service() -> StorageError { - StorageError::Service(DynamoDbError::ServiceUnavailable( - "retry shortly".to_owned(), - )) -} - -fn internal() -> StorageError { - StorageError::Internal("driver text".to_owned()) +/// Backend-classified errors, each with a message unlike any the engine +/// writes, and the body the client gets for each. +pub(crate) fn rows() -> Vec<(DynamoDbError, Value)> { + let mut stored = Item::new(); + stored.insert("pk".to_owned(), AttributeValue::S("stored".to_owned())); + let body = |class: &str, message: &str| { + json!({ + "__type": format!("com.amazonaws.dynamodb.v20120810#{class}"), + "message": message, + }) + }; + let unavailable = "The database is temporarily unavailable, retry shortly."; + let internal = "The server encountered an internal error trying to fulfill the request."; + let capacity = "The level of configured provisioned throughput for the table was exceeded."; + let limit = "Too many operations are in progress for this account."; + let condition = "The stored item does not match the condition."; + vec![ + ( + DynamoDbError::ServiceUnavailable(unavailable.to_owned()), + body("ServiceUnavailable", unavailable), + ), + ( + DynamoDbError::InternalServerError(internal.to_owned()), + body("InternalServerError", internal), + ), + ( + DynamoDbError::ProvisionedThroughputExceededException(capacity.to_owned()), + body("ProvisionedThroughputExceededException", capacity), + ), + ( + DynamoDbError::LimitExceededException(limit.to_owned()), + body("LimitExceededException", limit), + ), + // The stored item stays out of the body: only a request that set + // ReturnValuesOnConditionCheckFailure to ALL_OLD gets it. + ( + DynamoDbError::ConditionalCheckFailedException(condition.to_owned(), Some(stored)), + body("ConditionalCheckFailedException", condition), + ), + ] } type Site = (&'static str, fn(StorageError) -> DynamoDbError); -/// Every engine function that maps a `StorageError` and owns a catch-all arm. +/// The engine functions that map a `StorageError` to a client error and are +/// reachable from here: the six that log a storage fault (five end in a +/// catch-all; the data path mapping names every variant) and the conditional +/// check mapping, which delegates all but its `ALL_OLD` case to the data path +/// mapping. fn sites() -> Vec { vec![ ( "create_table::storage_err_to_dynamo", crate::create_table::storage_err_to_dynamo, ), + ("create_table::storage_err_to_dynamo_with_ccf", |e| { + crate::create_table::storage_err_to_dynamo_with_ccf( + e, + ReturnValuesOnConditionCheckFailure::None, + ) + }), ( "backup_requests::storage_err_to_dynamo", crate::backup_requests::storage_err_to_dynamo, @@ -70,30 +117,36 @@ fn sites() -> Vec { } #[test] -fn a_service_error_is_not_logged_as_a_storage_fault_at_any_site() { +fn a_service_error_reaches_the_client_as_classified_and_is_not_logged_at_any_site() { for (name, map) in sites() { - let logged = error_events_during(|| { - let err = map(service()); - assert!( - matches!(err, DynamoDbError::ServiceUnavailable(_)), - "{name}: expected ServiceUnavailable, got {err:?}" - ); - }); - assert_eq!(logged, 0, "{name} logged a Service error as a fault"); + for (error, body) in rows() { + let mut got = Value::Null; + let logged = error_events_during(|| { + got = error_document(&map(StorageError::Service(error.clone()))); + }); + assert_eq!(got, body, "{name}: {error:?}"); + assert_eq!(logged, 0, "{name} logged {error:?} as a storage fault"); + } } } -// Control: the same sites still log an unclassified failure once. +// Control: the same sites still redact an unclassified failure behind the +// fixed text and log it once. #[test] -fn an_internal_error_is_logged_once_as_a_storage_fault_at_every_site() { +fn an_internal_error_is_redacted_and_logged_once_at_every_site() { for (name, map) in sites() { + let mut got = Value::Null; let logged = error_events_during(|| { - let err = map(internal()); - assert!( - matches!(err, DynamoDbError::InternalServerError(_)), - "{name}: expected InternalServerError, got {err:?}" - ); + got = error_document(&map(StorageError::Internal("driver text".to_owned()))); }); + assert_eq!( + got, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#InternalServerError", + "message": "Internal server error", + }), + "{name}" + ); assert_eq!( logged, 1, "{name} logged {logged} fault events for an Internal error" diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 791966a00..0a7759cc9 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -544,10 +544,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { match e { StorageError::Validation(msg) => DynamoDbError::ValidationException(msg), StorageError::TableNotFound(name) => DynamoDbError::ResourceNotFoundException(name), - // The backend already classified this failure into the service error - // vocabulary and chose the client-facing message. Pass it through - // unchanged; it is not a storage fault, so it is not logged as one. - StorageError::Service(e) => e, + StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) diff --git a/crates/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index 8c9119fcc..3af3635d7 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -311,54 +311,20 @@ fn a_token_without_a_stream_arn_gets_the_answer_the_authorization_layer_gives() } } -// A backend-classified error reaches the client unchanged through the -// streams mapper, keeping both its variant and its message. -mod storage_error_mapping { - use super::super::storage_to_dynamo; - use extenddb_core::error::DynamoDbError; - use extenddb_storage::error::StorageError; - - #[test] - fn service_internal_server_error_passes_through() { - let err = storage_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( - "backend internal".to_owned(), - ))); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "backend internal"), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - - #[test] - fn service_service_unavailable_passes_through() { - let err = storage_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( - "retry shortly".to_owned(), - ))); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } - } - - #[test] - fn service_expired_iterator_passes_through() { - let err = storage_to_dynamo(StorageError::Service( - DynamoDbError::ExpiredIteratorException("Iterator expired.".to_owned()), - )); - match err { - DynamoDbError::ExpiredIteratorException(msg) => assert_eq!(msg, "Iterator expired."), - other => panic!("expected ExpiredIteratorException, got {other:?}"), - } - } - - // Control: an unclassified driver error is still redacted behind the fixed - // string, with the driver text absent from the client message. - #[test] - fn internal_driver_text_is_redacted() { - let err = storage_to_dynamo(StorageError::Internal("driver text".to_owned())); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), - } +// The shard lookup delegates a shard id within the length bound to +// `storage_to_dynamo`, so a backend-classified error reaches the client as that +// mapping gives it (`service_error_log_tests`). +#[test] +fn a_service_error_reaches_the_client_as_classified_through_the_shard_lookup() { + for (error, body) in crate::service_error_log_tests::rows() { + let got = super::shard_lookup_error( + 65, + extenddb_storage::error::StorageError::Service(error.clone()), + ); + assert_eq!( + extenddb_core::error::error_document(&got), + body, + "{error:?}" + ); } } diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index 0d60a3acf..2ee75d209 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -231,10 +231,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::TableNotActive(name) => { DynamoDbError::ResourceInUseException(format!("Table {name} is not in ACTIVE state")) } - // The backend already classified this failure into the service error - // vocabulary and chose the client-facing message. Pass it through - // unchanged; it is not a storage fault, so it is not logged as one. - StorageError::Service(e) => e, + StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) @@ -246,53 +243,6 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { mod tests { use super::*; - // A backend-classified error reaches the client unchanged through the TTL - // mapper, keeping both its variant and its message. - - #[test] - fn service_internal_server_error_passes_through() { - let err = storage_to_dynamo(StorageError::Service(DynamoDbError::InternalServerError( - "backend internal".to_owned(), - ))); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "backend internal"), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - - #[test] - fn service_service_unavailable_passes_through() { - let err = storage_to_dynamo(StorageError::Service(DynamoDbError::ServiceUnavailable( - "retry shortly".to_owned(), - ))); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } - } - - #[test] - fn service_limit_exceeded_passes_through() { - let err = storage_to_dynamo(StorageError::Service( - DynamoDbError::LimitExceededException("limit reached".to_owned()), - )); - match err { - DynamoDbError::LimitExceededException(msg) => assert_eq!(msg, "limit reached"), - other => panic!("expected LimitExceededException, got {other:?}"), - } - } - - // Control: an unclassified driver error is still redacted behind the fixed - // string, with the driver text absent from the client message. - #[test] - fn internal_driver_text_is_redacted() { - let err = storage_to_dynamo(StorageError::Internal("driver text".to_owned())); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), - } - } - #[test] fn valid_ttl_attribute_names() { assert!(validate_ttl_attribute_name("ttl").is_ok()); diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 9031d181e..f397a29e9 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -391,10 +391,7 @@ pub(crate) fn update_table_err_to_dynamo( // request. The backend supplies the whole message because only it knows // the state. StorageError::IndexesInUse(msg) => DynamoDbError::ResourceInUseException(msg), - // The backend already classified this failure into the service error - // vocabulary and chose the client-facing message. Pass it through - // unchanged; it is not a storage fault, so it is not logged as one. - StorageError::Service(e) => e, + StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { tracing::error!(internal_error = %other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs index 499c44422..c31c3bfbd 100644 --- a/crates/engine/src/update_table_tests.rs +++ b/crates/engine/src/update_table_tests.rs @@ -227,47 +227,3 @@ fn a_stream_specification_that_is_not_an_object_is_a_serialization_error() { let body = serde_json::json!({"TableName": "t", "StreamSpecification": null}); crate::require_stream_enabled_member(&body).expect("an absent member"); } - -// A backend-classified error reaches the client unchanged through the -// UpdateTable mapper, keeping both its variant and its message. - -#[test] -fn service_service_unavailable_passes_through() { - let err = update_table_err_to_dynamo( - StorageError::Service(DynamoDbError::ServiceUnavailable( - "retry shortly".to_owned(), - )), - "t", - ); - match err { - DynamoDbError::ServiceUnavailable(msg) => assert_eq!(msg, "retry shortly"), - other => panic!("expected ServiceUnavailable, got {other:?}"), - } -} - -#[test] -fn service_capacity_error_passes_through() { - let err = update_table_err_to_dynamo( - StorageError::Service(DynamoDbError::ProvisionedThroughputExceededException( - "capacity".to_owned(), - )), - "t", - ); - match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, "capacity"); - } - other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), - } -} - -// Control: an unclassified driver error is still redacted behind the fixed -// string, with the driver text absent from the client message. -#[test] -fn internal_driver_text_is_redacted() { - let err = update_table_err_to_dynamo(StorageError::Internal("driver text".to_owned()), "t"); - match err { - DynamoDbError::InternalServerError(msg) => assert_eq!(msg, "Internal server error"), - other => panic!("expected InternalServerError, got {other:?}"), - } -} From 5f54a421cc3ed0daa5ff997a78c05c7c1dc10ab2 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:38:38 +0000 Subject: [PATCH 05/12] fix(engine): a BatchExecuteStatement entry keeps the listed code of its error class A statement whose item operation failed with a throttle, a conflict or a fault of the server got Code ValidationError in its BatchExecuteStatement entry. A Service error from a backend reaches the entry this way, and so do the engine's own conflict and internal errors. StatementError::from_error now takes the Code from batch_code. That function gives the code that the API Reference lists for each class (BatchStatementError): ProvisionedThroughputExceeded, ThrottlingError, RequestLimitExceeded, TransactionConflict, ItemCollectionSizeLimitExceeded and InternalServerError. The list has no code for ServiceUnavailable, which gets InternalServerError. Every other class keeps ValidationError. The message and the TableName rule do not change: the entry names the table when the failure reached the item. The test has one row per class and compares the whole entry. --- crates/engine/src/partiql/common.rs | 32 +++++++++-- crates/engine/src/partiql/common/tests.rs | 65 +++++++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/partiql/common.rs b/crates/engine/src/partiql/common.rs index 4e73cee80..24729baac 100644 --- a/crates/engine/src/partiql/common.rs +++ b/crates/engine/src/partiql/common.rs @@ -516,10 +516,10 @@ impl StatementError { include_table_name: true, item: None, }, - // Everything else a well-formed statement can raise per-statement is - // a validation error (partial key, bad value, key-type mismatch). + // Every other error keeps its class as the code the API Reference + // lists for a batch statement's error (see `batch_code`). other => Self { - code: "ValidationError", + code: batch_code(other), message: other.message().to_owned(), include_table_name: false, item: None, @@ -573,5 +573,31 @@ impl StatementError { } } +/// The `Code` of a batch statement's error for an error that +/// [`StatementError::from_error`] has no arm of its own for: the code the API +/// Reference lists for its class (`BatchStatementError`), so a throttle, a +/// conflict or a fault that a backend reports for one statement keeps its +/// class. Any other class is a validation error: the failures a well-formed +/// statement raises on its own (partial key, bad value, key-type mismatch). +/// The list has no code for `ServiceUnavailable`, which gets +/// `InternalServerError`, the listed code of a fault of the server. +fn batch_code(err: &DynamoDbError) -> &'static str { + match err { + DynamoDbError::ProvisionedThroughputExceededException { .. } => { + "ProvisionedThroughputExceeded" + } + DynamoDbError::ThrottlingException { .. } => "ThrottlingError", + DynamoDbError::RequestLimitExceeded { .. } => "RequestLimitExceeded", + DynamoDbError::TransactionConflictException { .. } => "TransactionConflict", + DynamoDbError::ItemCollectionSizeLimitExceededException { .. } => { + "ItemCollectionSizeLimitExceeded" + } + DynamoDbError::InternalServerError { .. } | DynamoDbError::ServiceUnavailable { .. } => { + "InternalServerError" + } + _ => "ValidationError", + } +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/partiql/common/tests.rs b/crates/engine/src/partiql/common/tests.rs index 6b6617732..8bdfe160c 100644 --- a/crates/engine/src/partiql/common/tests.rs +++ b/crates/engine/src/partiql/common/tests.rs @@ -183,6 +183,71 @@ fn an_error_of_the_item_operation_names_the_batch_table() { } } +/// An error of the item operation keeps its class as the code the API +/// Reference lists for a batch statement's error (BatchStatementError), with +/// its message and the statement's table: a backend throttle, conflict or +/// fault on one statement is not a validation error. The list has no code for +/// ServiceUnavailable. +#[test] +fn an_error_of_the_item_operation_keeps_the_listed_code_of_its_class() { + for (error, code) in [ + ( + DynamoDbError::ProvisionedThroughputExceededException( + "The level of configured provisioned throughput for the table was exceeded." + .to_owned(), + ), + "ProvisionedThroughputExceeded", + ), + ( + DynamoDbError::ThrottlingException( + "Throughput exceeds the current capacity.".to_owned(), + ), + "ThrottlingError", + ), + ( + DynamoDbError::RequestLimitExceeded("Throughput exceeds the account quota.".to_owned()), + "RequestLimitExceeded", + ), + ( + DynamoDbError::TransactionConflictException( + "Transaction is ongoing for the item".to_owned(), + ), + "TransactionConflict", + ), + ( + DynamoDbError::ItemCollectionSizeLimitExceededException( + "Item collection size limit exceeded.".to_owned(), + ), + "ItemCollectionSizeLimitExceeded", + ), + ( + DynamoDbError::InternalServerError( + "The server encountered an internal error.".to_owned(), + ), + "InternalServerError", + ), + ( + DynamoDbError::ServiceUnavailable( + "The database is temporarily unavailable.".to_owned(), + ), + "InternalServerError", + ), + ( + DynamoDbError::ValidationException("The key value is not a number.".to_owned()), + "ValidationError", + ), + ] { + assert_eq!( + StatementError::from_item_error(&error).into_entry(Some("t")), + json!({ + "Error": { "Code": code, "Message": error.message() }, + "TableName": "t", + }), + "{error:?}" + ); + } +} + #[test] fn a_conditional_failure_without_an_item_has_none() { let err = DynamoDbError::ConditionalCheckFailedException( From dbeb02a6f45eca2ed4d0ba4a09555f5dbf75b3a6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:20 +0000 Subject: [PATCH 06/12] fix(server): a backend's not-found on the authorization key read is a missing table authorize_request reads the table's key schema before the IAM decision, which needs it for dynamodb:LeadingKeys. key_info_for_authz passed every error of that read except TableNotFound to the caller. A backend that answers StorageError::Service(ResourceNotFoundException) there told a caller without access that the table does not exist, before the IAM decision could refuse the caller. key_info_for_authz now treats that error as it treats TableNotFound: the key stays absent, the IAM decision runs, and a caller it refuses gets the refusal. Every other Service error still fails closed with its own class. Mapped to a missing table, such an error would reach the policy evaluator with dynamodb:LeadingKeys absent. The doc comment gives that as the reason for failing closed on transient and connection faults. The tests gain a row for the backend's not-found and one for a backend-classified ServiceUnavailable. --- crates/server/src/request_helpers.rs | 48 ++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 485ce725f..98e78b11c 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -140,12 +140,24 @@ pub(crate) fn metric_table_name( /// `StorageError::TableNotFound` and every other fault as a distinct error, so /// the two are told apart here rather than collapsed to `None`. Every fault /// class fails closed: none authorizes the request. +/// +/// A backend-classified `ResourceNotFoundException` (`StorageError::Service`) +/// is the backend's own not-found answer, so it is a missing table here as +/// well. This read comes before the IAM decision, which needs the key schema +/// for `dynamodb:LeadingKeys`, so its answer reaches callers the IAM decision +/// would refuse. A missing table gives those callers the refusal; passed +/// through, the backend's not-found would tell them that the table does not +/// exist. Every other `Service` error fails closed with its own class, for +/// the reason the transient and connection faults do. fn key_info_for_authz( result: Result, ) -> Result, DynamoDbError> { match result { Ok(info) => Ok(Some(info)), - Err(StorageError::TableNotFound(_)) => Ok(None), + Err( + StorageError::TableNotFound(_) + | StorageError::Service(DynamoDbError::ResourceNotFoundException(_)), + ) => Ok(None), Err(e) => Err(extenddb_engine::storage_err_to_dynamo(e)), } } @@ -556,12 +568,22 @@ mod tests { #[test] fn key_info_for_authz_missing_table_returns_none() { - let out = key_info_for_authz(Err(StorageError::TableNotFound("t".to_owned()))) - .expect("a missing table is not a lookup failure"); - assert!( - out.is_none(), - "a missing table must leave the leading key absent so the engine returns not-found" - ); + // The backend's own not-found answer is a missing table too, so a + // caller the IAM decision refuses gets that refusal and does not learn + // from the backend that the table is missing. + for missing in [ + StorageError::TableNotFound("t".to_owned()), + StorageError::Service(DynamoDbError::ResourceNotFoundException( + "Requested resource not found: Table: t not found".to_owned(), + )), + ] { + let out = key_info_for_authz(Err(missing.clone())) + .unwrap_or_else(|e| panic!("{missing:?} is not a lookup failure, got {e:?}")); + assert!( + out.is_none(), + "{missing:?} must leave the leading key absent so the engine returns not-found" + ); + } } #[test] @@ -606,6 +628,18 @@ mod tests { matches!(engine, DynamoDbError::ResourceInUseException(_)), "the engine maps TableNotActive to ResourceInUseException, got: {engine:?}" ); + + // Any other backend-classified error fails closed with its own class + // and message. + let unavailable = DynamoDbError::ServiceUnavailable( + "The database is temporarily unavailable, retry shortly.".to_owned(), + ); + let err = key_info_for_authz(Err(StorageError::Service(unavailable.clone()))) + .expect_err("a backend-classified fault must fail closed"); + assert_eq!( + extenddb_core::error::error_document(&err), + extenddb_core::error::error_document(&unavailable) + ); } #[test] From 5d146990ca17207d9a72d2107d906ab45ca35e5f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:28 +0000 Subject: [PATCH 07/12] docs: ADR-0028 counts the mapping functions and says what the log test covers The ADR said that nine functions map a StorageError to a client error and that each ends in a catch-all. At this head there are ten. Five end in a catch-all, and the data path mapping names every variant. Four delegate to one of those six: the conditional check mapping, the create-backup and restore mappings and the shard lookup mapping. The ADR now lists them by file. The decision section names create_table::service_err_to_dynamo as the one function every Service arm calls, and the rule it applies to a conditional check error's item. It also records the two answers that depend on the error's class. One is the Code of a BatchExecuteStatement entry. The other is the server's key schema read before the IAM decision, which treats a backend's ResourceNotFoundException as a missing table. The rationale section says that the log test runs at the seven mappings the crate root reaches. The three private mappings write no log line of their own, and their modules' tests cover them. --- .../0028-backend-classified-client-error.md | 63 ++++++++++++------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/docs/adr/0028-backend-classified-client-error.md b/docs/adr/0028-backend-classified-client-error.md index 25e915221..256050055 100644 --- a/docs/adr/0028-backend-classified-client-error.md +++ b/docs/adr/0028-backend-classified-client-error.md @@ -7,14 +7,20 @@ ## Context Every storage trait method returns `Result`. The engine maps a -`StorageError` to the client-facing `DynamoDbError` at nine functions -(`crates/engine/src/create_table.rs`, `backup.rs`, `update_table.rs`, -`streams.rs`, `ttl.rs`, `lib.rs`), each of which names the variants it knows -and ends in a catch-all that logs the error at error level and returns -`InternalServerError("Internal server error")`. The catch-all is the redaction -rule the security model documents: driver text, SQL, paths and connection -details never reach a client (`docs/manuals/10-security-model.md`, Error -Message Security; RFC-0003 section 9.2). +`StorageError` to the client-facing `DynamoDbError` in ten functions. Five end +in a catch-all that logs the error at error level and returns +`InternalServerError("Internal server error")`: the backup mapping +(`crates/engine/src/backup_requests.rs`), the `UpdateTable` mapping +(`update_table.rs`), the streams and TTL mappings (`streams.rs`, `ttl.rs`) and +`sanitize_storage_error` (`lib.rs`). The data path mapping (`create_table.rs`) +names every variant, and it logs and redacts the faults among them the same +way. The other four name a few variants and delegate the rest to one of those +six: the conditional check mapping (`create_table.rs`), the create-backup and +restore mappings (`backup.rs`) and the shard lookup mapping (`streams.rs`). The +server's authorization read delegates to the data path mapping. The redaction +is the rule the security model documents: driver text, SQL, paths and +connection details never reach a client (`docs/manuals/10-security-model.md`, +Error Message Security; RFC-0003 section 9.2). The rule has a cost for a backend that knows more than the engine does. A hosted database reports documented conditions with their own class and text: @@ -43,10 +49,21 @@ do, and the operator's log counts a documented condition among storage faults. Add `StorageError::Service(DynamoDbError)`, marked `#[error(transparent)]`, and make every engine function that maps a `StorageError` to a client error -return it unchanged and without the fault log line. The engine applies one -rule of its own to the payload: for `ConditionalCheckFailedException`, the -request's `ReturnValuesOnConditionCheckFailure` decides whether the item is -returned, as it does for the engine's `ConditionFailed`. +return it through one function, `create_table::service_err_to_dynamo`: +unchanged, and without the fault log line. That function applies the one rule +the engine keeps for the payload. A `ConditionalCheckFailedException` loses its +item, as the engine's own `ConditionFailed` does on the generic path, and only +the conditional check mapping returns the item, to a request that set +`ReturnValuesOnConditionCheckFailure` to `ALL_OLD`. + +Two answers outside these functions depend on the error's class. In a +`BatchExecuteStatement` response, a statement's entry carries the code that the +API Reference lists for the class (`BatchStatementError`), and +`InternalServerError` for `ServiceUnavailable`, which the list does not have. +The server reads a table's key schema before the IAM decision, which needs it +for `dynamodb:LeadingKeys`, so that read treats a `ResourceNotFoundException` +as a missing table: a caller the IAM decision refuses gets the refusal, not the +backend's not-found. ## Rationale @@ -56,15 +73,19 @@ returned, as it does for the engine's `ConditionFailed`. - The status code and the body shape still come from the `DynamoDbError` variant through the one serializer, so a backend cannot produce a status or a shape outside the service's catalog through this variant. -- The redaction rule for `Internal` and every other variant is unchanged, and - a test at each site keeps it so. The one new path is named in the security - model, the backend author manual, RFC-0003 section 9.2 and the variant's - doc comment, with the obligation stated the same way in each: the message - crosses the wire verbatim and must be service-shaped text with no driver - output, host names, connection strings or credentials. -- A subscriber-based test counts error-level log events at every mapping - site: none for a `Service` error, one for an `Internal` error, so the - "not logged as a fault" half of the contract cannot regress silently. +- The redaction rule for `Internal` and every other variant is unchanged. A + test checks it for `Internal` at the seven mappings the crate root can + reach. The one new path is named in the security model, the backend author + manual, RFC-0003 section 9.2 and the variant's doc comment, with the + obligation stated the same way in each: the message crosses the wire + verbatim and must be service-shaped text with no driver output, host names, + connection strings or credentials. +- One set of rows, each a backend-classified error with a message the engine + never writes, runs through every mapping and is compared with the body the + client gets. At the seven mappings the crate root can reach, a subscriber + also counts error-level log events: none for a `Service` error, one for an + `Internal` error. The other three only delegate and write no log line of + their own, and their modules run the rows through them. ## Consequences From f5457b6632d1a7ff8f36e84dde85327b7990cabc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:28 +0000 Subject: [PATCH 08/12] docs: name every variant whose backend text reaches the client The security model and the backend author manual called StorageError::Service the one path that carries backend-chosen text to a client. The data path mapping also passes on the message of Validation, NoOpUpdate, Unsupported, IndexesInUse, LimitExceeded, BackupInUse and TransactionConflict as the backend wrote it. It passes on the cancellation reasons of TransactionCanceled too. Both pages now list these variants and apply the same rule to their text: service-shaped, with no driver output, host names, connection strings or credentials. The security model also records that the server reads a table's key schema before the IAM decision. A backend's ResourceNotFoundException from that read is a missing table, so a caller the IAM decision refuses gets the refusal. --- docs/manuals/10-security-model.md | 3 ++- docs/manuals/12-extending-extenddb-storage.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 57f4627c1..06246f0af 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -367,7 +367,8 @@ Import/export file paths are validated: - DynamoDB-fidelity error messages reproduce real DynamoDB exactly (no additional information) - Internal errors (database connection failures, SQL errors, I/O errors) are logged server-side but return generic messages to clients - Stack traces, file paths, and SQL text are never exposed to clients -- One path carries backend-chosen text to a client: a backend may return `StorageError::Service(DynamoDbError)` when it has classified its own failure into a service error class, and the engine returns that error with its message unchanged. The message inside is client-facing text the backend author owns; it must not contain driver output, SQL text, paths or connection details, and it is reviewed as client-visible wording under the same rule as the engine's own messages +- Backend-chosen text reaches a client in two ways. A backend may return `StorageError::Service(DynamoDbError)` when it has classified its own failure into a service error class, and the engine returns that error with its message unchanged. The engine also passes on, as the backend wrote them, the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict`, and the cancellation reasons of `TransactionCanceled`. That text is client-facing text the backend author owns; it must not contain driver output, SQL text, paths or connection details, and it is reviewed as client-visible wording under the same rule as the engine's own messages +- The server reads a table's key schema before the IAM decision, which needs it for `dynamodb:LeadingKeys`. A `StorageError::Service` carrying `ResourceNotFoundException` from that read is a missing table, as `StorageError::TableNotFound` is: a caller the IAM decision refuses gets the refusal, not the backend's not-found ## Operational Security diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index 8b43cf621..b07f049fc 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -98,7 +98,7 @@ Key design decisions: - **Items** are `BTreeMap`. A new backend must handle the full `AttributeValue` type (S, N, B, SS, NS, BS, L, M, BOOL, NULL). - **Query** must support forward/reverse sort order, exclusive start key pagination, and routing to secondary index storage. - **Parallel scan** uses `segment` and `total_segments` to partition the keyspace. -- **Errors**: return the named `StorageError` variant for every condition the engine maps (`TableNotFound`, `ConditionFailed`, `TransactionCanceled`, `Validation`, `Unsupported`, `Transient` and the rest); the engine chooses the client-facing message and redacts anything it does not recognise behind a fixed `InternalServerError`. When the backend can classify its own failure into a service error class with a message of its own (a hosted database reporting a documented unavailability or capacity condition), return `StorageError::Service(DynamoDbError)`: the engine passes it to the client with its variant and message unchanged and does not log it as a storage fault (a conditional check error carries its item only when the request asked for `ALL_OLD`, as with the engine's own). That message crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials. A failure the backend cannot classify stays `Internal`. +- **Errors**: return the named `StorageError` variant for every condition the engine maps (`TableNotFound`, `ConditionFailed`, `TransactionCanceled`, `Validation`, `Unsupported`, `Transient` and the rest). The engine chooses the error class the client gets, passes on the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict` and the cancellation reasons of `TransactionCanceled` as the backend wrote them, and redacts anything it does not recognise behind a fixed `InternalServerError`. When the backend can classify its own failure into a service error class with a message of its own (a hosted database reporting a documented unavailability or capacity condition), return `StorageError::Service(DynamoDbError)`: the engine passes it to the client with its variant and message unchanged and does not log it as a storage fault (a conditional check error carries its item only when the request asked for `ALL_OLD`, as with the engine's own). Every message the backend writes in these variants crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials. A failure the backend cannot classify stays `Internal`. ### MetadataEngine From 87aa8154624e8ed75cc41dfbf3115a5d9c132fcc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:01:38 +0000 Subject: [PATCH 09/12] test(engine): count fault log lines under the global subscriber the backup log tests use The Service log test sets a counting subscriber as the thread's default. tracing caches each callsite's interest when a thread first reaches it. While one thread default is the only subscriber in the process, that cache comes from the default of the thread that got there first. A test without a subscriber that reaches a mapping's log callsite first caches it as "never", and the count then reads 0. A count of 0 is also the expected answer for a Service error, so that half of the test could pass without checking. The backup log tests already install a global subscriber that is interested in every callsite (InterestedInEveryCallsite). This commit moves it into crates/engine/src/test_tracing.rs, and both the backup LogLines and error_events_during install it before they set a thread default. The new test an_event_from_a_callsite_another_thread_met_first_is_counted makes another thread meet a callsite first, and it counts 0 events without the global subscriber. --- crates/engine/src/backup/tests.rs | 45 ++---------------- crates/engine/src/lib.rs | 2 + crates/engine/src/service_error_log_tests.rs | 22 ++++++++- crates/engine/src/test_tracing.rs | 48 ++++++++++++++++++++ 4 files changed, 75 insertions(+), 42 deletions(-) create mode 100644 crates/engine/src/test_tracing.rs diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index e0f6a5692..ced9602e6 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -13137,48 +13137,11 @@ async fn a_second_create_over_the_job_bound_is_limit_exceeded() { #[derive(Clone, Default)] struct LogLines(Arc>>); -/// The process's global `tracing` subscriber while these tests run: -/// interested in every callsite and enabled for none. `tracing` caches each -/// callsite's interest the first time any thread reaches it; while exactly -/// one scoped subscriber is registered in the process, that cache is -/// computed from the default of the thread that got there first. A test -/// without a subscriber running beside a `LogLines` test on another thread -/// would so cache the job's log callsites as "never", and the `LogLines` -/// test would then see no line from them (tokio-rs/tracing#2743). With this -/// global default the cache reads "sometimes" instead, and each event asks -/// the thread's own default, the `LogLines` where one is set. -struct InterestedInEveryCallsite; - -impl tracing::Subscriber for InterestedInEveryCallsite { - fn register_callsite( - &self, - _: &'static tracing::Metadata<'static>, - ) -> tracing::subscriber::Interest { - tracing::subscriber::Interest::sometimes() - } - fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { - false - } - fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { - tracing::span::Id::from_u64(1) - } - fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} - fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} - fn event(&self, _: &tracing::Event<'_>) {} - fn enter(&self, _: &tracing::span::Id) {} - fn exit(&self, _: &tracing::span::Id) {} -} - impl LogLines { /// A fresh `LogLines` set as this thread's `tracing` default until the /// guard drops, with the process's global default installed once. fn capture() -> (Self, tracing::subscriber::DefaultGuard) { - static GLOBAL: std::sync::Once = std::sync::Once::new(); - GLOBAL.call_once(|| { - // Another global may already be set by a test outside this - // module; then its interest rule applies and this one is moot. - let _ = tracing::subscriber::set_global_default(InterestedInEveryCallsite); - }); + crate::test_tracing::interest_in_every_callsite(); let lines = Self::default(); let guard = tracing::subscriber::set_default(lines.clone()); (lines, guard) @@ -13211,9 +13174,9 @@ struct MessageVisitor<'a>(&'a mut String); /// A callsite met first by a thread without a scoped subscriber is still /// seen by a `LogLines` on another thread (the global default's interest -/// rule; the doc of `InterestedInEveryCallsite`). Without that default the -/// callsite's interest is cached as "never" whenever this is the only -/// `LogLines` alive in the process, and nothing is captured. +/// rule; the doc of `test_tracing::InterestedInEveryCallsite`). Without that +/// default the callsite's interest is cached as "never" whenever this is the +/// only `LogLines` alive in the process, and nothing is captured. #[test] fn a_callsite_first_met_on_another_thread_still_reaches_the_lines() { fn shared_callsite(n: u32) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2c83b0b80..3637e2fd3 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -69,6 +69,8 @@ pub mod stream_capture; mod streams; mod streams_iterator_params; mod tagging; +#[cfg(test)] +mod test_tracing; mod transact_get_items; mod transact_write_helpers; mod transact_write_items; diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs index 643aa5a89..812f9871b 100644 --- a/crates/engine/src/service_error_log_tests.rs +++ b/crates/engine/src/service_error_log_tests.rs @@ -29,8 +29,12 @@ impl Layer for Errors { } } -/// Runs `f` under a fresh subscriber and returns how many error events it logged. +/// Runs `f` with a fresh subscriber as this thread's default and returns how +/// many error events it logged. The global default of `test_tracing` keeps +/// `tracing` from caching a callsite that another thread met first as +/// "never", which would hide its events from this subscriber. fn error_events_during(f: impl FnOnce()) -> usize { + crate::test_tracing::interest_in_every_callsite(); let errors = Errors::default(); let count = Arc::clone(&errors.0); let subscriber = tracing_subscriber::registry().with(errors); @@ -153,3 +157,19 @@ fn an_internal_error_is_redacted_and_logged_once_at_every_site() { ); } } + +/// An event reaches the counting subscriber when another thread, without a +/// subscriber of its own, met its callsite first while the counting +/// subscriber was the only thread default in the process. The callsite is +/// this test's own, so no other test has met it before. +#[test] +fn an_event_from_a_callsite_another_thread_met_first_is_counted() { + fn fault() { + tracing::error!("a fault that two threads log"); + } + let logged = error_events_during(|| { + std::thread::spawn(fault).join().unwrap(); + fault(); + }); + assert_eq!(logged, 1); +} diff --git a/crates/engine/src/test_tracing.rs b/crates/engine/src/test_tracing.rs new file mode 100644 index 000000000..21dbb2f00 --- /dev/null +++ b/crates/engine/src/test_tracing.rs @@ -0,0 +1,48 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The process's global `tracing` subscriber for the tests that read log +//! events through a subscriber set as their thread's default. + +/// The process's global `tracing` subscriber while the tests run: +/// interested in every callsite and enabled for none. `tracing` caches each +/// callsite's interest the first time any thread reaches it; while exactly +/// one scoped subscriber is registered in the process, that cache is +/// computed from the default of the thread that got there first. A test +/// without a subscriber running beside a test with one on another thread +/// would so cache a callsite as "never", and the test with the subscriber +/// would then see no event from it (tokio-rs/tracing#2743). With this +/// global default the cache reads "sometimes" instead, and each event asks +/// the thread's own default. +struct InterestedInEveryCallsite; + +impl tracing::Subscriber for InterestedInEveryCallsite { + fn register_callsite( + &self, + _: &'static tracing::Metadata<'static>, + ) -> tracing::subscriber::Interest { + tracing::subscriber::Interest::sometimes() + } + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + false + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, _: &tracing::Event<'_>) {} + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} +} + +/// Install [`InterestedInEveryCallsite`] as the process's global default, +/// once. A test calls this before it sets its own subscriber as its thread's +/// default. +pub(crate) fn interest_in_every_callsite() { + static GLOBAL: std::sync::Once = std::sync::Once::new(); + GLOBAL.call_once(|| { + // Another global may already be set by a test outside these + // modules; then its interest rule applies and this one is moot. + let _ = tracing::subscriber::set_global_default(InterestedInEveryCallsite); + }); +} From 816e456e952e615a61262f78e2480ba07e9dbc3d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:34 +0000 Subject: [PATCH 10/12] fix(engine): leave the contended statement entry to #487 #487 gives TransactionConflictException and ServiceUnavailable the BatchExecuteStatement entry measured for a contended statement: Code TransactionConflict, the message "Transaction is ongoing for the item" and no TableName. batch_code gave the first TransactionConflict with the error's own message and TableName, and the second InternalServerError. Once both PRs merge, #487's arm matches first and those two arms are dead. batch_code drops the two arms, so they keep ValidationError until #487 merges. The test drops their rows and the ValidationException row, which main's an_error_of_the_item_operation_names_the_batch_table covers. --- crates/engine/src/partiql/common.rs | 15 +++++---------- crates/engine/src/partiql/common/tests.rs | 21 ++------------------- 2 files changed, 7 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/partiql/common.rs b/crates/engine/src/partiql/common.rs index 24729baac..06a395553 100644 --- a/crates/engine/src/partiql/common.rs +++ b/crates/engine/src/partiql/common.rs @@ -575,12 +575,10 @@ impl StatementError { /// The `Code` of a batch statement's error for an error that /// [`StatementError::from_error`] has no arm of its own for: the code the API -/// Reference lists for its class (`BatchStatementError`), so a throttle, a -/// conflict or a fault that a backend reports for one statement keeps its -/// class. Any other class is a validation error: the failures a well-formed -/// statement raises on its own (partial key, bad value, key-type mismatch). -/// The list has no code for `ServiceUnavailable`, which gets -/// `InternalServerError`, the listed code of a fault of the server. +/// Reference lists for its class (`BatchStatementError`), so a throttle or a +/// fault that a backend reports for one statement keeps its class. Any other +/// class is a validation error: the failures a well-formed statement raises +/// on its own (partial key, bad value, key-type mismatch). fn batch_code(err: &DynamoDbError) -> &'static str { match err { DynamoDbError::ProvisionedThroughputExceededException { .. } => { @@ -588,13 +586,10 @@ fn batch_code(err: &DynamoDbError) -> &'static str { } DynamoDbError::ThrottlingException { .. } => "ThrottlingError", DynamoDbError::RequestLimitExceeded { .. } => "RequestLimitExceeded", - DynamoDbError::TransactionConflictException { .. } => "TransactionConflict", DynamoDbError::ItemCollectionSizeLimitExceededException { .. } => { "ItemCollectionSizeLimitExceeded" } - DynamoDbError::InternalServerError { .. } | DynamoDbError::ServiceUnavailable { .. } => { - "InternalServerError" - } + DynamoDbError::InternalServerError { .. } => "InternalServerError", _ => "ValidationError", } } diff --git a/crates/engine/src/partiql/common/tests.rs b/crates/engine/src/partiql/common/tests.rs index 8bdfe160c..6a7aa5086 100644 --- a/crates/engine/src/partiql/common/tests.rs +++ b/crates/engine/src/partiql/common/tests.rs @@ -185,9 +185,8 @@ fn an_error_of_the_item_operation_names_the_batch_table() { /// An error of the item operation keeps its class as the code the API /// Reference lists for a batch statement's error (BatchStatementError), with -/// its message and the statement's table: a backend throttle, conflict or -/// fault on one statement is not a validation error. The list has no code for -/// ServiceUnavailable. +/// its message and the statement's table: a backend throttle or fault on one +/// statement is not a validation error. #[test] fn an_error_of_the_item_operation_keeps_the_listed_code_of_its_class() { for (error, code) in [ @@ -208,12 +207,6 @@ fn an_error_of_the_item_operation_keeps_the_listed_code_of_its_class() { DynamoDbError::RequestLimitExceeded("Throughput exceeds the account quota.".to_owned()), "RequestLimitExceeded", ), - ( - DynamoDbError::TransactionConflictException( - "Transaction is ongoing for the item".to_owned(), - ), - "TransactionConflict", - ), ( DynamoDbError::ItemCollectionSizeLimitExceededException( "Item collection size limit exceeded.".to_owned(), @@ -226,16 +219,6 @@ fn an_error_of_the_item_operation_keeps_the_listed_code_of_its_class() { ), "InternalServerError", ), - ( - DynamoDbError::ServiceUnavailable( - "The database is temporarily unavailable.".to_owned(), - ), - "InternalServerError", - ), - ( - DynamoDbError::ValidationException("The key value is not a number.".to_owned()), - "ValidationError", - ), ] { assert_eq!( StatementError::from_item_error(&error).into_entry(Some("t")), From 999b71d9d8c713bdde7a3305f6cf91347410c8cf Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:34 +0000 Subject: [PATCH 11/12] docs: name the table-state variants whose backend text reaches the client The backup mapping passes on the backend's message of TableNotFound, TableAlreadyExists and TableNotActive, and the streams mapping that of TableNotFound. The security model and the storage extension manual now list them with the other variants. ADR-0028 says which BatchExecuteStatement classes keep their listed code, now that #487 maps the contended entry. It also says that the shard lookup mapping checks the shard id length before it delegates, and names no variant of its own. --- docs/adr/0028-backend-classified-client-error.md | 13 +++++++------ docs/manuals/10-security-model.md | 2 +- docs/manuals/12-extending-extenddb-storage.md | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/adr/0028-backend-classified-client-error.md b/docs/adr/0028-backend-classified-client-error.md index 256050055..2aa9a1c65 100644 --- a/docs/adr/0028-backend-classified-client-error.md +++ b/docs/adr/0028-backend-classified-client-error.md @@ -14,9 +14,10 @@ in a catch-all that logs the error at error level and returns (`update_table.rs`), the streams and TTL mappings (`streams.rs`, `ttl.rs`) and `sanitize_storage_error` (`lib.rs`). The data path mapping (`create_table.rs`) names every variant, and it logs and redacts the faults among them the same -way. The other four name a few variants and delegate the rest to one of those -six: the conditional check mapping (`create_table.rs`), the create-backup and -restore mappings (`backup.rs`) and the shard lookup mapping (`streams.rs`). The +way. The other four delegate to one of those six: the conditional check +mapping (`create_table.rs`) and the create-backup and restore mappings +(`backup.rs`) after a few variants of their own, and the shard lookup mapping +(`streams.rs`) after its check of the shard id length. The server's authorization read delegates to the data path mapping. The redaction is the rule the security model documents: driver text, SQL, paths and connection details never reach a client (`docs/manuals/10-security-model.md`, @@ -57,9 +58,9 @@ the conditional check mapping returns the item, to a request that set `ReturnValuesOnConditionCheckFailure` to `ALL_OLD`. Two answers outside these functions depend on the error's class. In a -`BatchExecuteStatement` response, a statement's entry carries the code that the -API Reference lists for the class (`BatchStatementError`), and -`InternalServerError` for `ServiceUnavailable`, which the list does not have. +`BatchExecuteStatement` response, the entry of a statement that failed with a +throttle, an item collection size limit or an internal error carries the code +that the API Reference lists for that class (`BatchStatementError`). The server reads a table's key schema before the IAM decision, which needs it for `dynamodb:LeadingKeys`, so that read treats a `ResourceNotFoundException` as a missing table: a caller the IAM decision refuses gets the refusal, not the diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 06246f0af..a60e77b10 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -367,7 +367,7 @@ Import/export file paths are validated: - DynamoDB-fidelity error messages reproduce real DynamoDB exactly (no additional information) - Internal errors (database connection failures, SQL errors, I/O errors) are logged server-side but return generic messages to clients - Stack traces, file paths, and SQL text are never exposed to clients -- Backend-chosen text reaches a client in two ways. A backend may return `StorageError::Service(DynamoDbError)` when it has classified its own failure into a service error class, and the engine returns that error with its message unchanged. The engine also passes on, as the backend wrote them, the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict`, and the cancellation reasons of `TransactionCanceled`. That text is client-facing text the backend author owns; it must not contain driver output, SQL text, paths or connection details, and it is reviewed as client-visible wording under the same rule as the engine's own messages +- Backend-chosen text reaches a client in two ways. A backend may return `StorageError::Service(DynamoDbError)` when it has classified its own failure into a service error class, and the engine returns that error with its message unchanged. The engine also passes on, as the backend wrote them, the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict`, the message of `TableNotFound` in the backup and streams mappings and of `TableAlreadyExists` and `TableNotActive` in the backup mapping, and the cancellation reasons of `TransactionCanceled`. That text is client-facing text the backend author owns; it must not contain driver output, SQL text, paths or connection details, and it is reviewed as client-visible wording under the same rule as the engine's own messages - The server reads a table's key schema before the IAM decision, which needs it for `dynamodb:LeadingKeys`. A `StorageError::Service` carrying `ResourceNotFoundException` from that read is a missing table, as `StorageError::TableNotFound` is: a caller the IAM decision refuses gets the refusal, not the backend's not-found ## Operational Security diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index b07f049fc..82ec79506 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -98,7 +98,7 @@ Key design decisions: - **Items** are `BTreeMap`. A new backend must handle the full `AttributeValue` type (S, N, B, SS, NS, BS, L, M, BOOL, NULL). - **Query** must support forward/reverse sort order, exclusive start key pagination, and routing to secondary index storage. - **Parallel scan** uses `segment` and `total_segments` to partition the keyspace. -- **Errors**: return the named `StorageError` variant for every condition the engine maps (`TableNotFound`, `ConditionFailed`, `TransactionCanceled`, `Validation`, `Unsupported`, `Transient` and the rest). The engine chooses the error class the client gets, passes on the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict` and the cancellation reasons of `TransactionCanceled` as the backend wrote them, and redacts anything it does not recognise behind a fixed `InternalServerError`. When the backend can classify its own failure into a service error class with a message of its own (a hosted database reporting a documented unavailability or capacity condition), return `StorageError::Service(DynamoDbError)`: the engine passes it to the client with its variant and message unchanged and does not log it as a storage fault (a conditional check error carries its item only when the request asked for `ALL_OLD`, as with the engine's own). Every message the backend writes in these variants crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials. A failure the backend cannot classify stays `Internal`. +- **Errors**: return the named `StorageError` variant for every condition the engine maps (`TableNotFound`, `ConditionFailed`, `TransactionCanceled`, `Validation`, `Unsupported`, `Transient` and the rest). The engine chooses the error class the client gets, passes on the message of `Validation`, `NoOpUpdate`, `Unsupported`, `IndexesInUse`, `LimitExceeded`, `BackupInUse` and `TransactionConflict`, the message of `TableNotFound` in the backup and streams mappings and of `TableAlreadyExists` and `TableNotActive` in the backup mapping, and the cancellation reasons of `TransactionCanceled` as the backend wrote them, and redacts anything it does not recognise behind a fixed `InternalServerError`. When the backend can classify its own failure into a service error class with a message of its own (a hosted database reporting a documented unavailability or capacity condition), return `StorageError::Service(DynamoDbError)`: the engine passes it to the client with its variant and message unchanged and does not log it as a storage fault (a conditional check error carries its item only when the request asked for `ALL_OLD`, as with the engine's own). Every message the backend writes in these variants crosses the wire verbatim, so it must be service-shaped text with no driver output, host names, connection strings or credentials. A failure the backend cannot classify stays `Internal`. ### MetadataEngine From ea4efd4b9362e023ce7d5dc304aeb540107cbc16 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:34 +0000 Subject: [PATCH 12/12] test(engine): keep only the ALL_OLD case in the conditional check test The None case repeated service_error_log_tests, whose sites() runs the conditional check mapping without ALL_OLD over the conditional check row. The comment on sites() now says that this mapping also maps the engine's own ConditionFailed. --- crates/engine/src/create_table.rs | 44 ++++++++------------ crates/engine/src/service_error_log_tests.rs | 5 ++- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 353a91dfb..08325fdfb 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -305,37 +305,27 @@ mod storage_error_mapping_tests { } /// Only this mapper reads `ReturnValuesOnConditionCheckFailure`: a - /// backend's conditional check error reaches the client with its own - /// message, and with its item only under `ALL_OLD`. The mappings that - /// drop the item are checked in `service_error_log_tests`. + /// backend's conditional check error reaches a request that set it to + /// `ALL_OLD` with its own message and its item. The mappings that drop + /// the item, this one without `ALL_OLD` among them, are checked in + /// `service_error_log_tests`. #[test] fn a_backend_conditional_check_error_keeps_its_item_only_under_all_old() { let message = "The stored item does not match the condition."; let mut item = Item::new(); item.insert("pk".to_owned(), AttributeValue::S("stored".to_owned())); - for (ccf, body) in [ - ( - ReturnValuesOnConditionCheckFailure::None, - json!({ - "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", - "message": message, - }), - ), - ( - ReturnValuesOnConditionCheckFailure::AllOld, - json!({ - "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", - "message": message, - "Item": {"pk": {"S": "stored"}}, - }), - ), - ] { - let error = DynamoDbError::ConditionalCheckFailedException( - message.to_owned(), - Some(item.clone()), - ); - let got = storage_err_to_dynamo_with_ccf(StorageError::Service(error), ccf); - assert_eq!(error_document(&got), body, "{ccf:?}"); - } + let error = DynamoDbError::ConditionalCheckFailedException(message.to_owned(), Some(item)); + let got = storage_err_to_dynamo_with_ccf( + StorageError::Service(error), + ReturnValuesOnConditionCheckFailure::AllOld, + ); + assert_eq!( + error_document(&got), + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException", + "message": message, + "Item": {"pk": {"S": "stored"}}, + }) + ); } } diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs index 812f9871b..97e721b05 100644 --- a/crates/engine/src/service_error_log_tests.rs +++ b/crates/engine/src/service_error_log_tests.rs @@ -90,8 +90,9 @@ type Site = (&'static str, fn(StorageError) -> DynamoDbError); /// The engine functions that map a `StorageError` to a client error and are /// reachable from here: the six that log a storage fault (five end in a /// catch-all; the data path mapping names every variant) and the conditional -/// check mapping, which delegates all but its `ALL_OLD` case to the data path -/// mapping. +/// check mapping, which maps the engine's own `ConditionFailed` and, under +/// `ALL_OLD`, a backend's conditional check error itself, and delegates the +/// rest to the data path mapping. fn sites() -> Vec { vec![ (