From 4428a3c678f75183e4b544ec2dc9ce5aef9f81dd Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 22:02:14 +0000 Subject: [PATCH 01/33] 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 | 217 ++++++++++++++++++ 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, 646 insertions(+), 4 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 19bb60c51..f5652c627 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1343,6 +1343,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 424e27b55..34c56a0b8 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -220,6 +220,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, } } @@ -244,6 +255,212 @@ 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; + + 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."; + + // 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 83b297253..527fac740 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -349,10 +349,14 @@ pub async fn handle_get_records( serialize_output(&output) } -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()) @@ -360,6 +364,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 34a93c340..65e36425e 100755 --- a/crates/storage/src/error.rs +++ b/crates/storage/src/error.rs @@ -86,4 +86,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 1fd29a0b2d4449f78674353eebfeb3b746a12085 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 22:02:14 +0000 Subject: [PATCH 02/33] 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 d3591a5bd..a15034a70 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 f66d2bdedbd8f87d0990c3028b8b44b0520c285a Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 23:20:54 +0000 Subject: [PATCH 03/33] test(engine): build the capacity error through its constructor after the throttle variants became structs The StorageError::Service tests constructed ProvisionedThroughputExceededException as a tuple variant; with the reasons list it is a struct variant with a constructor. This commit reconciles the two changes and belongs to whichever of them lands second. --- crates/engine/src/backup/service_error_tests.rs | 6 +++--- crates/engine/src/create_table.rs | 15 ++++++++------- crates/engine/src/update_table.rs | 9 +++++---- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/backup/service_error_tests.rs b/crates/engine/src/backup/service_error_tests.rs index db01c8263..cff4dffb8 100644 --- a/crates/engine/src/backup/service_error_tests.rs +++ b/crates/engine/src/backup/service_error_tests.rs @@ -42,11 +42,11 @@ fn service_service_unavailable_passes_through() { #[test] fn service_capacity_error_passes_through() { let err = storage_err_to_dynamo(StorageError::Service( - DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), + DynamoDbError::provisioned_throughput_exceeded(CAPACITY_MSG, vec![]), )); match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); + DynamoDbError::ProvisionedThroughputExceededException { message, .. } => { + assert_eq!(message, CAPACITY_MSG); } other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), } diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 34c56a0b8..7241bd630 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -313,11 +313,11 @@ mod storage_error_mapping_tests { #[test] fn service_capacity_error_passes_through() { let err = storage_err_to_dynamo(StorageError::Service( - DynamoDbError::ProvisionedThroughputExceededException(CAPACITY_MSG.to_owned()), + DynamoDbError::provisioned_throughput_exceeded(CAPACITY_MSG, vec![]), )); match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); + DynamoDbError::ProvisionedThroughputExceededException { message, .. } => { + assert_eq!(message, CAPACITY_MSG); } other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), } @@ -365,14 +365,15 @@ mod storage_error_mapping_tests { #[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(), + StorageError::Service(DynamoDbError::provisioned_throughput_exceeded( + CAPACITY_MSG, + vec![], )), ReturnValuesOnConditionCheckFailure::None, ); match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, CAPACITY_MSG); + DynamoDbError::ProvisionedThroughputExceededException { message, .. } => { + assert_eq!(message, CAPACITY_MSG); } other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), } diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 357f6c80f..c11dcb7ee 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -375,14 +375,15 @@ mod tests { #[test] fn service_capacity_error_passes_through() { let err = update_table_err_to_dynamo( - StorageError::Service(DynamoDbError::ProvisionedThroughputExceededException( - "capacity".to_owned(), + StorageError::Service(DynamoDbError::provisioned_throughput_exceeded( + "capacity", + vec![], )), "t", ); match err { - DynamoDbError::ProvisionedThroughputExceededException(msg) => { - assert_eq!(msg, "capacity"); + DynamoDbError::ProvisionedThroughputExceededException { message, .. } => { + assert_eq!(message, "capacity"); } other => panic!("expected ProvisionedThroughputExceededException, got {other:?}"), } From 4fbf180720c5e86fc3639cc0c9c5b025f05cc226 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 23:45:35 +0000 Subject: [PATCH 04/33] feat(engine): serve a batch partially when a backend throttles some entries Amazon DynamoDB serves the entries of a BatchGetItem or BatchWriteItem that the table has capacity for and returns the rest under UnprocessedKeys or UnprocessedItems; the call fails with the throttle error only when no entry could be served. ExtendDB's two batch handlers failed the whole request on the first storage error of any kind. A per-key storage call that fails with StorageError::Service carrying a throttle error (ProvisionedThroughputExceededException, ThrottlingException or RequestLimitExceeded) now moves that entry to the unprocessed set and the loop continues. BatchGetItem returns the table's KeysAndAttributes with Keys reduced to the unprocessed ones, in request order, and the other request fields echoed as sent; BatchWriteItem returns the throttled WriteRequest entries as sent, in request order. ConsumedCapacity and ItemCollectionMetrics count the served entries only, so the capacity and metrics bookkeeping moves after the storage call. When every entry of the request was throttled the call fails with the first throttle error. Every other storage error still fails the request as before. A BatchWriteItem that asked for ReturnItemCollectionMetrics SIZE carries the field as an empty map when no written item belongs to an item collection, and omits it without SIZE. The server records ThrottledRequests once and a read or write throttle event per table when a batch response carries a non-empty unprocessed map, since its own bucket never saw that throttle and the metrics would otherwise read as zero. Measured against the service on 2026-10-21 (1,070 raw responses on a 1 RCU / 1 WCU table seeded with 100 items of 4 KB): two partial BatchGetItem responses served 16 of 25 keys and echoed ConsistentRead and ProjectionExpression beside the 9 unprocessed keys, ConsumedCapacity counting the 16; 26 of 26 fully served responses carried UnprocessedKeys as an empty map; 13 of 13 fully processed BatchWriteItem responses carried UnprocessedItems as an empty map and, with SIZE, ItemCollectionMetrics as an empty map. The partial BatchWriteItem shape was measured on 2026-10-20 on an on-demand table: 18 of 80 batches returned 200 with 6 to 24 of 25 PutRequest entries echoed under UnprocessedItems. Documented in the API Reference and not reached in the samples: the echo of ExpressionAttributeNames and AttributesToGet, DeleteRequest entries under UnprocessedItems, and the all-throttled failure. The order of the service's served and unprocessed lists was neither request nor sorted order; the engine returns request order. Tests drive both handlers against a storage double that throttles a chosen set of partition key values: the partial shapes with the request fields echoed and served-only capacity, capacity by item size, the AttributesToGet echo, one table throttled beside a served one with an empty Responses list for it, exactly one entry served, every entry throttled failing with the throttle error carrying the read or write reason, nothing throttled serializing the empty maps, SIZE without collections, and a non-throttle Service error still failing the request. The partial-response metrics have their own unit tests. The double lives in its own file beside the tests. This change uses StorageError::Service and DynamoDbError::is_throttle and stacks on the pull requests that introduce them. --- crates/core/src/metrics/types.rs | 2 +- crates/engine/src/batch_get_item.rs | 72 ++- crates/engine/src/batch_write_item.rs | 122 +++- crates/engine/tests/batch_partial.rs | 532 ++++++++++++++++ .../tests/batch_partial/failing_store.rs | 577 ++++++++++++++++++ crates/server/src/handler.rs | 7 +- crates/server/src/throttle_helpers.rs | 99 +++ 7 files changed, 1368 insertions(+), 43 deletions(-) create mode 100644 crates/engine/tests/batch_partial.rs create mode 100644 crates/engine/tests/batch_partial/failing_store.rs diff --git a/crates/core/src/metrics/types.rs b/crates/core/src/metrics/types.rs index 39d9d07f4..f142b6a66 100755 --- a/crates/core/src/metrics/types.rs +++ b/crates/core/src/metrics/types.rs @@ -14,7 +14,7 @@ pub enum MetricName { SuccessfulRequestLatency, SystemErrors, UserErrors, - /// Throttled request count. Recorded when token bucket rejects a request. + /// Throttled request count. Recorded when the token bucket rejects a request or a backend serves a batch partially. ThrottledRequests, /// Read throttle events. Recorded when a read operation is throttled. ReadThrottleEvents, diff --git a/crates/engine/src/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index d392c4a1c..aca4fe49c 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -9,8 +9,11 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::Projection; -use extenddb_core::types::{BatchGetItemInput, BatchGetItemOutput, Item, item_size_bytes}; +use extenddb_core::types::{ + BatchGetItemInput, BatchGetItemOutput, Item, KeysAndAttributes, item_size_bytes, +}; use extenddb_core::validation::{validate_batch_key_only, validate_key_sizes}; +use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; @@ -45,6 +48,8 @@ pub async fn handle_batch_get_item( .map(|(table_name, ka)| (table_name.as_str(), Some(ka.keys.len()))) .collect(); request_limits::check_batch_counts("BatchGetItem", &counts)?; + // The partial-success boundary below compares against the whole request. + let total_keys: usize = counts.iter().map(|(_, n)| n.unwrap_or(0)).sum(); // Reject mixing expression and non-expression parameters anywhere in the // request. The check is request-wide: ProjectionExpression on one table and @@ -151,6 +156,15 @@ pub async fn handle_batch_get_item( } let mut responses: HashMap> = HashMap::new(); + // Keys a backend throttled, grouped by table. The service serves the rest + // of the batch and returns these under `UnprocessedKeys` with the table's + // request fields echoed (measured 2026-10-21: 2 partial responses, 16 of + // 25 keys served, `ConsistentRead` and `ProjectionExpression` echoed); + // when every key was throttled the call fails with the throttle error + // instead (API Reference; documented, not reached in the sample). + let mut unprocessed_keys: HashMap = HashMap::new(); + let mut throttled_count: usize = 0; + let mut first_throttle: Option = None; let mut total_rcu: f64 = 0.0; let mut total_pre_proj_bytes: usize = 0; let mut returned_count: u64 = 0; @@ -165,16 +179,27 @@ pub async fn handle_batch_get_item( let projection = table_projections.get(table_name).and_then(Option::as_ref); let mut table_items: Vec = Vec::new(); + let mut table_unprocessed: Vec = Vec::new(); for key in &ka.keys { validate_batch_key_only(key, &key_info.key_schema, &key_info.attribute_definitions)?; validate_key_sizes(key, &key_info.key_schema, &ctx.limits)?; - if let Some(item) = ctx - .storage - .get_item(&key_info, key) - .await - .map_err(storage_err_to_dynamo)? - { + let fetched = match ctx.storage.get_item(&key_info, key).await { + Ok(fetched) => fetched, + // A throttled key is not an error for the batch: it is reported + // back unprocessed and the loop continues. Every other storage + // error still fails the request. + Err(StorageError::Service(e)) if e.is_throttle() => { + table_unprocessed.push(key.clone()); + throttled_count += 1; + if first_throttle.is_none() { + first_throttle = Some(e); + } + continue; + } + Err(e) => return Err(storage_err_to_dynamo(e)), + }; + if let Some(item) = fetched { let size = item_size_bytes(&item); let strongly_consistent = ka.consistent_read == Some(true); let item_rcu = capacity_helpers::read_capacity_units(size, strongly_consistent); @@ -190,9 +215,40 @@ pub async fn handle_batch_get_item( table_items.push(item); } } + if !table_unprocessed.is_empty() { + // The request's KeysAndAttributes with Keys reduced to the + // unprocessed ones, in request order (the service's order is not + // measured: its served and unprocessed lists came back in neither + // request nor sorted order); the other fields are echoed as sent + // (ConsistentRead and ProjectionExpression measured, + // ExpressionAttributeNames and AttributesToGet documented). + unprocessed_keys.insert( + table_name.clone(), + KeysAndAttributes { + keys: table_unprocessed, + consistent_read: ka.consistent_read, + projection_expression: ka.projection_expression.clone(), + expression_attribute_names: ka.expression_attribute_names.clone(), + attributes_to_get: ka.attributes_to_get.clone(), + }, + ); + } responses.insert(table_name.clone(), table_items); } + // No key of any table could be read: the call fails with the first + // throttle error (API Reference; documented, not measured). "First" is the + // request map's iteration order, so with tables of different billing modes + // either error class can come out; the service's choice for that case is + // not measured (one table per request in the sample). A table whose every + // key was throttled beside a served table keeps an empty `Responses` list; + // unmeasured as well. + if let Some(e) = first_throttle + && throttled_count == total_keys + { + return Err(e); + } + let consumed_capacity = capacity_helpers::batch_read_capacity( input.return_consumed_capacity, per_table_rcu.iter().map(|(t, cu)| (t.as_str(), *cu)), @@ -203,7 +259,7 @@ pub async fn handle_batch_get_item( let output = BatchGetItemOutput { responses, - unprocessed_keys: HashMap::new(), + unprocessed_keys, consumed_capacity, }; let body = serialize_output(&output)?; diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index b0381c7a7..9cd3c095b 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -17,6 +17,7 @@ use extenddb_core::validation::{ validate_attribute_name_sizes, validate_batch_item_keys, validate_batch_key_only, validate_item_nesting_depth, validate_item_size, validate_key_sizes, }; +use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; @@ -51,6 +52,8 @@ pub async fn handle_batch_write_item( .map(|(table_name, reqs)| (table_name.as_str(), Some(reqs.len()))) .collect(); request_limits::check_batch_counts("BatchWriteItem", &counts)?; + // The partial-success boundary below compares against the whole request. + let total_ops: usize = counts.iter().map(|(_, n)| n.unwrap_or(0)).sum(); // Validate: each WriteRequest has exactly one of PutRequest or DeleteRequest for reqs in input.request_items.values() { @@ -78,6 +81,15 @@ pub async fn handle_batch_write_item( input.return_consumed_capacity == extenddb_core::types::ReturnConsumedCapacity::Indexes; let mut per_table_gsi: HashMap> = HashMap::new(); let mut per_table_lsi: HashMap> = HashMap::new(); + // Entries a backend throttled, echoed as sent under `UnprocessedItems` + // (measured for PutRequest on an on-demand table, 2026-10-20: 18 of 80 + // batches returned 200 with 6 to 24 of 25 entries unprocessed; + // DeleteRequest documented, not measured). When every entry was throttled + // the call fails with the throttle error instead (API Reference; + // documented, not measured). + let mut unprocessed_items: HashMap> = HashMap::new(); + let mut throttled_count: usize = 0; + let mut first_throttle: Option = None; for (table_name, reqs) in &input.request_items { let key_info = ctx @@ -89,6 +101,7 @@ pub async fn handle_batch_write_item( validate_no_duplicate_keys(reqs, &key_info.key_schema)?; let view_type = stream_capture::stream_view_type(&key_info); + let mut table_unprocessed: Vec = Vec::new(); for wr in reqs { if let Some(put) = &wr.put_request { @@ -107,24 +120,13 @@ pub async fn handle_batch_write_item( &key_info.attribute_definitions, )?; - collect_icm_if_needed( - input.return_item_collection_metrics, - &key_info, - &put.item, - table_name, - &mut all_icm, - ); - let stream = view_type.map(|vt| extenddb_storage::StreamCapture { view_type: vt, user_identity: None, region: ctx.region.clone(), }); let need_old_for_stream = stream.is_some(); - let item_wcu = capacity_helpers::write_capacity_units(item_size_bytes(&put.item)); - total_wcu += item_wcu; - *per_table_wcu.entry(table_name.clone()).or_default() += item_wcu; - let old_item = ctx + let old_item = match ctx .storage .put_item( &key_info, @@ -135,7 +137,32 @@ pub async fn handle_batch_write_item( stream.as_ref(), ) .await - .map_err(storage_err_to_dynamo)?; + { + Ok(old_item) => old_item, + // A throttled entry is returned unprocessed and the loop + // continues; nothing below is charged or reported for it. + // Every other storage error still fails the request. + Err(StorageError::Service(e)) if e.is_throttle() => { + table_unprocessed.push(wr.clone()); + throttled_count += 1; + if first_throttle.is_none() { + first_throttle = Some(e); + } + continue; + } + Err(e) => return Err(storage_err_to_dynamo(e)), + }; + // Applied: charge capacity and report metrics for this entry. + collect_icm_if_needed( + input.return_item_collection_metrics, + &key_info, + &put.item, + table_name, + &mut all_icm, + ); + let item_wcu = capacity_helpers::write_capacity_units(item_size_bytes(&put.item)); + total_wcu += item_wcu; + *per_table_wcu.entry(table_name.clone()).or_default() += item_wcu; if want_index_cc { let (gsi, lsi) = capacity_helpers::index_write_units( old_item.as_ref(), @@ -159,26 +186,13 @@ pub async fn handle_batch_write_item( &key_info.attribute_definitions, )?; - collect_icm_if_needed( - input.return_item_collection_metrics, - &key_info, - &del.key, - table_name, - &mut all_icm, - ); - let stream = view_type.map(|vt| extenddb_storage::StreamCapture { view_type: vt, user_identity: None, region: ctx.region.clone(), }); let need_old_for_stream = stream.is_some(); - // TODO(fidelity): DynamoDB charges WCU based on old item size for deletes, - // but old item size is not available here. Using key size as lower bound. - let item_wcu = capacity_helpers::write_capacity_units(item_size_bytes(&del.key)); - total_wcu += item_wcu; - *per_table_wcu.entry(table_name.clone()).or_default() += item_wcu; - let old_item = ctx + let old_item = match ctx .storage .delete_item( &key_info, @@ -189,7 +203,31 @@ pub async fn handle_batch_write_item( stream.as_ref(), ) .await - .map_err(storage_err_to_dynamo)?; + { + Ok(old_item) => old_item, + Err(StorageError::Service(e)) if e.is_throttle() => { + table_unprocessed.push(wr.clone()); + throttled_count += 1; + if first_throttle.is_none() { + first_throttle = Some(e); + } + continue; + } + Err(e) => return Err(storage_err_to_dynamo(e)), + }; + // Applied: charge capacity and report metrics for this entry. + collect_icm_if_needed( + input.return_item_collection_metrics, + &key_info, + &del.key, + table_name, + &mut all_icm, + ); + // TODO(fidelity): DynamoDB charges WCU based on old item size for deletes, + // but old item size is not available here. Using key size as lower bound. + let item_wcu = capacity_helpers::write_capacity_units(item_size_bytes(&del.key)); + total_wcu += item_wcu; + *per_table_wcu.entry(table_name.clone()).or_default() += item_wcu; if want_index_cc { let (gsi, lsi) = capacity_helpers::index_write_units( old_item.as_ref(), @@ -208,6 +246,19 @@ pub async fn handle_batch_write_item( } } } + if !table_unprocessed.is_empty() { + // Request order; the service's lists came back in neither request + // nor sorted order. + unprocessed_items.insert(table_name.clone(), table_unprocessed); + } + } + + // No entry of any table could be written: the call fails with the first + // throttle error (API Reference; documented, not measured). + if let Some(e) = first_throttle + && throttled_count == total_ops + { + return Err(e); } // With INDEXES, each per-table entry carries the arms the batch actually @@ -241,12 +292,19 @@ pub async fn handle_batch_write_item( let wcu = total_wcu; let output = BatchWriteItemOutput { - unprocessed_items: HashMap::new(), + unprocessed_items, consumed_capacity, - item_collection_metrics: if all_icm.is_empty() { - None - } else { + // The service answers a SIZE request with the field present even when + // no written item belongs to an item collection: 13 of 13 fully + // processed batches on a table without a local secondary index carried + // "ItemCollectionMetrics": {} (measured 2026-10-21). Without SIZE the + // field is absent. + item_collection_metrics: if input.return_item_collection_metrics + == ReturnItemCollectionMetrics::Size + { Some(all_icm) + } else { + None }, }; let body = serialize_output(&output)?; diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs new file mode 100644 index 000000000..97adabbf5 --- /dev/null +++ b/crates/engine/tests/batch_partial.rs @@ -0,0 +1,532 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Partial success on `BatchGetItem` and `BatchWriteItem` when a backend +//! throttles some entries. +//! +//! Expected behaviour was measured against Amazon DynamoDB on 2026-10-21 +//! (1,070 raw responses on a 1 RCU / 1 WCU table) and 2026-10-20 (an +//! on-demand table): a throttled entry moves to `UnprocessedKeys` or +//! `UnprocessedItems` with the request fields echoed (`ConsistentRead` and +//! `ProjectionExpression` measured), served and unprocessed sets are disjoint +//! and complete, `ConsumedCapacity` counts served entries only, and an empty +//! unprocessed map is present as `{}`. A batch whose every entry was throttled +//! fails with the throttle error per the API Reference; that case and the +//! echo of `ExpressionAttributeNames` and `AttributesToGet` were not reached +//! in the samples. The order of the unprocessed lists, which the samples +//! returned in neither request nor sorted order, is not asserted. The storage +//! double throttles a chosen set of partition key values and records which +//! writes it applied. + +#[path = "batch_partial/failing_store.rs"] +mod failing_store; + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use extenddb_auth::AuthCacheRegistry; +use extenddb_core::error::{DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE}; +use extenddb_core::limits::LimitsConfig; +use extenddb_engine::{ + DispatchResult, OperationContext, handle_batch_get_item, handle_batch_write_item, +}; + +use failing_store::*; + +fn ctx(store: Arc) -> OperationContext { + OperationContext { + storage: store, + limits: Arc::new(LimitsConfig::default()), + region: Arc::from(REGION), + account_id: Arc::from(ACCOUNT), + import_paths: Arc::from(Vec::>::new()), + export_paths: Arc::from(Vec::>::new()), + authorized_key_info: extenddb_engine::AuthorizedKeyInfo::new(), + auth_cache: AuthCacheRegistry::empty(), + table_key_info_lookup: None, + } +} + +fn keys_json(pks: &[&str]) -> Value { + Value::Array(pks.iter().map(|p| json!({"pk": {"S": p}})).collect()) +} + +/// Partition key values of a JSON list of keys or items. +fn pks(list: &Value) -> BTreeSet { + list.as_array() + .expect("list") + .iter() + .map(|k| k["pk"]["S"].as_str().expect("pk").to_owned()) + .collect() +} + +/// The error of a handler result, or a panic naming the body that came back. +fn err_of(result: Result) -> DynamoDbError { + match result { + Err(e) => e, + Ok(ok) => panic!("expected an error, got a response: {}", ok.body), + } +} + +fn assert_throttle(err: &DynamoDbError, reason: &str) { + assert_eq!(err.status_code(), 400); + assert_eq!(err.error_type(), "ProvisionedThroughputExceededException"); + assert_eq!(err.message(), PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE); + let reasons = err.throttling_reasons().expect("reasons"); + assert_eq!(reasons.len(), 1); + assert_eq!(reasons[0].reason, reason); +} + +// --------------------------------------------------------------------------- +// BatchGetItem +// --------------------------------------------------------------------------- + +/// Measured 2026-10-21: served items in `Responses`, the throttled keys under +/// `UnprocessedKeys[]` beside the request's `ConsistentRead` and +/// `ProjectionExpression`, sets disjoint and complete, `ConsumedCapacity` for +/// the served items only. `ExpressionAttributeNames` is echoed per the API +/// Reference; the sample sent none. +#[tokio::test] +async fn batch_get_partial_echoes_request_fields_and_charges_served_only() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["k1", "k2", "k3", "k4", "k5"]) + .failing_on(&["k2", "k4"]), + ); + let body = json!({ + "RequestItems": { + "T": { + "Keys": keys_json(&["k1", "k2", "k3", "k4", "k5"]), + "ConsistentRead": true, + "ProjectionExpression": "#p", + "ExpressionAttributeNames": {"#p": "pk"} + } + }, + "ReturnConsumedCapacity": "TOTAL" + }); + + let result = handle_batch_get_item(body, &ctx(store)) + .await + .expect("partial success is a 200"); + + let served = pks(&result.body["Responses"]["T"]); + assert_eq!(served, ["k1", "k3", "k5"].map(str::to_owned).into()); + for it in result.body["Responses"]["T"].as_array().expect("items") { + assert!(it.get("v").is_none(), "projection applied to served items"); + } + + let unprocessed = &result.body["UnprocessedKeys"]["T"]; + assert_eq!( + pks(&unprocessed["Keys"]), + ["k2", "k4"].map(str::to_owned).into() + ); + assert_eq!(unprocessed["ConsistentRead"], json!(true)); + assert_eq!(unprocessed["ProjectionExpression"], json!("#p")); + assert_eq!(unprocessed["ExpressionAttributeNames"], json!({"#p": "pk"})); + assert!(unprocessed.get("AttributesToGet").is_none()); + assert_eq!( + unprocessed.as_object().expect("map").len(), + 4, + "Keys plus the three request fields that were sent" + ); + + // Disjoint and complete. + let unread = pks(&unprocessed["Keys"]); + assert!(served.is_disjoint(&unread)); + let all: BTreeSet = served.union(&unread).cloned().collect(); + assert_eq!( + all, + ["k1", "k2", "k3", "k4", "k5"].map(str::to_owned).into() + ); + + // Three consistent reads under 4 KB: 1 unit each, nothing for k2 and k4. + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 3.0}]) + ); + assert_eq!(result.metrics.read_capacity_units, 3.0); + assert_eq!(result.metrics.returned_item_count, 3); +} + +/// Two tables: one throttled on every key, the other fully served. The +/// throttled table lists all its keys under `UnprocessedKeys`; the served +/// table is absent from it. +#[tokio::test] +async fn batch_get_one_table_throttled_beside_a_served_table() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["t1", "t2", "u1", "u2"]) + .failing_on(&["t1", "t2"]), + ); + let body = json!({ + "RequestItems": { + "T": {"Keys": keys_json(&["t1", "t2"])}, + "U": {"Keys": keys_json(&["u1", "u2"]), "ConsistentRead": false} + }, + "ReturnConsumedCapacity": "TOTAL" + }); + + let result = handle_batch_get_item(body, &ctx(store)) + .await + .expect("at least one key served is a 200"); + + let unprocessed = result.body["UnprocessedKeys"].as_object().expect("map"); + assert_eq!(unprocessed.len(), 1); + assert_eq!( + pks(&unprocessed["T"]["Keys"]), + ["t1", "t2"].map(str::to_owned).into() + ); + assert!(unprocessed["T"].get("ConsistentRead").is_none()); + // The fully throttled table keeps an empty list under Responses (the + // branch's own contract; the service's shape for this case is unmeasured). + let responses = result.body["Responses"].as_object().expect("map"); + assert_eq!(responses.len(), 2); + assert_eq!(responses["T"], json!([])); + assert_eq!( + pks(&result.body["Responses"]["U"]), + ["u1", "u2"].map(str::to_owned).into() + ); + // Eventually consistent reads under 4 KB: 0.5 each; nothing for T. + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "U", "CapacityUnits": 1.0}]) + ); + assert_eq!(result.metrics.read_capacity_units, 1.0); +} + +/// Every key of every table throttled: the call fails with the throttle +/// error (API Reference; documented, not measured). +#[tokio::test] +async fn batch_get_every_key_throttled_fails_with_the_throttle_error() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["t1", "u1"]) + .failing_on(&["t1", "u1"]), + ); + let body = json!({ + "RequestItems": { + "T": {"Keys": keys_json(&["t1"])}, + "U": {"Keys": keys_json(&["u1"])} + } + }); + + let err = err_of(handle_batch_get_item(body, &ctx(store)).await); + assert_throttle(&err, "TableReadProvisionedThroughputExceeded"); +} + +/// The boundary of the all-throttled rule: with one key served and every +/// other throttled the call is a 200 carrying that one item, the rest +/// unprocessed, and capacity for the one. +#[tokio::test] +async fn batch_get_one_served_key_is_a_partial_success() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["k1", "k2", "k3"]) + .failing_on(&["k1", "k2"]), + ); + let body = json!({ + "RequestItems": {"T": {"Keys": keys_json(&["k1", "k2", "k3"]), "ConsistentRead": true}}, + "ReturnConsumedCapacity": "TOTAL" + }); + let result = handle_batch_get_item(body, &ctx(store)) + .await + .expect("one key served is a 200"); + assert_eq!( + pks(&result.body["Responses"]["T"]), + ["k3".to_owned()].into() + ); + assert_eq!( + pks(&result.body["UnprocessedKeys"]["T"]["Keys"]), + ["k1", "k2"].map(str::to_owned).into() + ); + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 1.0}]) + ); +} + +/// `AttributesToGet` is echoed beside the unprocessed keys (API Reference; +/// the sample sent `ProjectionExpression` instead). +#[tokio::test] +async fn batch_get_partial_echoes_attributes_to_get() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["k1", "k2"]) + .failing_on(&["k2"]), + ); + let body = json!({ + "RequestItems": {"T": {"Keys": keys_json(&["k1", "k2"]), "AttributesToGet": ["pk"]}} + }); + let result = handle_batch_get_item(body, &ctx(store)) + .await + .expect("one key served is a 200"); + let t = result.body["UnprocessedKeys"]["T"] + .as_object() + .expect("map"); + assert_eq!(t.len(), 2, "{t:?}"); + assert_eq!(t["AttributesToGet"], json!(["pk"])); + assert_eq!(pks(&t["Keys"]), ["k2".to_owned()].into()); +} + +/// Capacity for a served item follows its size: a consistent read of an item +/// over 4 KB costs two units (the measured 16.0 for 16 reads of 4 KB items +/// sits at the one-unit tier; this pins the tier boundary the engine applies). +#[tokio::test] +async fn batch_get_partial_charges_served_items_by_size() { + let store = Arc::new( + FailingStore::throttling() + .with_items(&["k1"]) + .with_large_item("k2") + .failing_on(&["k3"]) + .with_items(&["k3"]), + ); + let body = json!({ + "RequestItems": {"T": {"Keys": keys_json(&["k1", "k2", "k3"]), "ConsistentRead": true}}, + "ReturnConsumedCapacity": "TOTAL" + }); + let result = handle_batch_get_item(body, &ctx(store)) + .await + .expect("two keys served is a 200"); + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 3.0}]) + ); + assert_eq!(result.metrics.read_capacity_units, 3.0); +} + +/// Nothing throttled: `UnprocessedKeys` is present as `{}` (26 of 26 +/// measured). +#[tokio::test] +async fn batch_get_nothing_throttled_serializes_empty_unprocessed_keys() { + let store = Arc::new(FailingStore::throttling().with_items(&["k1"])); + let body = json!({ + "RequestItems": {"T": {"Keys": keys_json(&["k1", "k2"])}} + }); + + let result = handle_batch_get_item(body, &ctx(store)).await.expect("200"); + let serialized = serde_json::to_string(&result.body).expect("serialize"); + assert!( + serialized.contains(r#""UnprocessedKeys":{}"#), + "body: {serialized}" + ); + assert_eq!( + pks(&result.body["Responses"]["T"]), + ["k1"].map(str::to_owned).into() + ); +} + +/// A storage `Service` error that is not a throttle still fails the request. +#[tokio::test] +async fn batch_get_non_throttle_service_error_fails_the_request() { + let store = Arc::new( + FailingStore::new(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + .with_items(&["k1", "k2"]) + .failing_on(&["k2"]), + ); + let body = json!({ + "RequestItems": {"T": {"Keys": keys_json(&["k1", "k2"])}} + }); + + let err = err_of(handle_batch_get_item(body, &ctx(store)).await); + assert_eq!(err.status_code(), 500); + assert_eq!(err.error_type(), "InternalServerError"); +} + +// --------------------------------------------------------------------------- +// BatchWriteItem +// --------------------------------------------------------------------------- + +/// Puts and deletes, some throttled: 200, the throttled entries echoed as +/// sent under `UnprocessedItems[
]`, `ConsumedCapacity` and +/// `ItemCollectionMetrics` for the applied entries only, and the backend saw +/// exactly the applied writes. +#[tokio::test] +async fn batch_write_partial_echoes_entries_and_charges_applied_only() { + let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p2", "d2"])); + let body = json!({ + "RequestItems": { + "T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}, "v": {"N": "1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}, "v": {"N": "2"}}}}, + {"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}, + {"DeleteRequest": {"Key": {"pk": {"S": "d2"}}}} + ] + }, + "ReturnConsumedCapacity": "TOTAL", + "ReturnItemCollectionMetrics": "SIZE" + }); + + let result = handle_batch_write_item(body, &ctx(Arc::clone(&store))) + .await + .expect("partial success is a 200"); + + let unprocessed = result.body["UnprocessedItems"]["T"] + .as_array() + .expect("list"); + assert_eq!(unprocessed.len(), 2); + assert!(unprocessed.contains(&json!({ + "PutRequest": {"Item": {"pk": {"S": "p2"}, "v": {"N": "2"}}} + }))); + assert!(unprocessed.contains(&json!({ + "DeleteRequest": {"Key": {"pk": {"S": "d2"}}} + }))); + assert_eq!( + result.body["UnprocessedItems"] + .as_object() + .expect("map") + .len(), + 1 + ); + + // Two applied writes under 1 KB: 1 unit each. + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 2.0}]) + ); + assert_eq!(result.metrics.write_capacity_units, 2.0); + + let icm: BTreeSet = result.body["ItemCollectionMetrics"]["T"] + .as_array() + .expect("metrics list") + .iter() + .map(|m| { + m["ItemCollectionKey"]["pk"]["S"] + .as_str() + .expect("pk") + .to_owned() + }) + .collect(); + assert_eq!(icm, ["p1", "d1"].map(str::to_owned).into()); + + assert_eq!( + store.applied(), + vec![ + Applied::Put("p1".to_owned()), + Applied::Delete("d1".to_owned()) + ] + ); +} + +/// Every entry throttled: the call fails with the throttle error and nothing +/// was applied. +#[tokio::test] +async fn batch_write_every_entry_throttled_fails_with_the_throttle_error() { + let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p1", "d1"])); + let body = json!({ + "RequestItems": { + "T": [{"PutRequest": {"Item": {"pk": {"S": "p1"}}}}], + "U": [{"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}] + } + }); + + let err = err_of(handle_batch_write_item(body, &ctx(Arc::clone(&store))).await); + assert_throttle(&err, "TableWriteProvisionedThroughputExceeded"); + assert!(store.applied().is_empty()); +} + +/// The boundary of the all-throttled rule on writes: one entry applied and +/// the rest throttled is a 200 with that one write applied and the others +/// echoed under `UnprocessedItems`. +#[tokio::test] +async fn batch_write_one_applied_entry_is_a_partial_success() { + let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p1", "p2"])); + let body = json!({ + "RequestItems": { + "T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p3"}}}} + ] + }, + "ReturnConsumedCapacity": "TOTAL" + }); + let result = handle_batch_write_item(body, &ctx(Arc::clone(&store))) + .await + .expect("one entry applied is a 200"); + assert_eq!(store.applied(), vec![Applied::Put("p3".to_owned())]); + let unprocessed = result.body["UnprocessedItems"]["T"] + .as_array() + .expect("list"); + assert_eq!(unprocessed.len(), 2); + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 1.0}]) + ); +} + +/// Nothing throttled: `UnprocessedItems` is present as `{}` (13 of 13 fully +/// processed responses measured on 2026-10-21 carried it). +#[tokio::test] +async fn batch_write_nothing_throttled_serializes_empty_unprocessed_items() { + let store = Arc::new(FailingStore::throttling()); + let body = json!({ + "RequestItems": { + "T": [{"PutRequest": {"Item": {"pk": {"S": "p1"}}}}] + } + }); + + let result = handle_batch_write_item(body, &ctx(store)) + .await + .expect("200"); + let serialized = serde_json::to_string(&result.body).expect("serialize"); + assert!( + serialized.contains(r#""UnprocessedItems":{}"#), + "body: {serialized}" + ); + assert!( + !serialized.contains("ItemCollectionMetrics"), + "no SIZE requested, the field is absent: {serialized}" + ); +} + +/// A fully processed batch that asked for `ReturnItemCollectionMetrics: SIZE` +/// on a table without a local secondary index carries +/// `"ItemCollectionMetrics": {}`, the field present and empty (measured 13 of +/// 13 on 2026-10-21). +#[tokio::test] +async fn batch_write_size_requested_without_collections_serializes_empty_metrics() { + let store = Arc::new(FailingStore::throttling()); + let body = json!({ + "RequestItems": { + "U": [{"PutRequest": {"Item": {"pk": {"S": "p1"}}}}] + }, + "ReturnItemCollectionMetrics": "SIZE" + }); + + let result = handle_batch_write_item(body, &ctx(store)) + .await + .expect("200"); + let serialized = serde_json::to_string(&result.body).expect("serialize"); + assert!( + serialized.contains(r#""ItemCollectionMetrics":{}"#), + "body: {serialized}" + ); +} + +/// A storage `Service` error that is not a throttle still fails the request. +#[tokio::test] +async fn batch_write_non_throttle_service_error_fails_the_request() { + let store = Arc::new( + FailingStore::new(DynamoDbError::InternalServerError( + "Internal server error".to_owned(), + )) + .failing_on(&["p2"]), + ); + let body = json!({ + "RequestItems": { + "T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}}}} + ] + } + }); + + let err = err_of(handle_batch_write_item(body, &ctx(store)).await); + assert_eq!(err.status_code(), 500); + assert_eq!(err.error_type(), "InternalServerError"); +} diff --git a/crates/engine/tests/batch_partial/failing_store.rs b/crates/engine/tests/batch_partial/failing_store.rs new file mode 100644 index 000000000..7c7c120cc --- /dev/null +++ b/crates/engine/tests/batch_partial/failing_store.rs @@ -0,0 +1,577 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! A storage double whose per-key data calls fail with a chosen service error +//! for a chosen set of partition key values and succeed for every other key, +//! recording the writes it applied. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::Mutex; + +use extenddb_core::error::{ + DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, ThrottlingReason, +}; +use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition, UpdateAction}; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, BackupDescription, BackupDetails, BackupSummary, + ContinuousBackupsDescription, CreateTableInput, DeleteTableInput, DescribeStreamInput, + DescribeTableInput, IndexInfo, Item, KeySchemaElement, KeyType, ListTablesInput, + ListTablesOutput, ScalarAttributeType, StreamDescription, StreamRecord, TableDescription, + TableKeyInfo, Tag, TimeToLiveDescription, UpdateTableInput, +}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{ + BackupEngine, BackupRestoreSource, BoxedFuture, DataEngine, IdempotencyKey, ItemPairResult, + MetadataEngine, QueryResult, RestoreRequest, StreamCapture, StreamEngine, StreamListResult, + StreamRecordsResult, TableEngine, TransactGetOp, TransactWriteOp, TtlTableInfo, WorkerStore, +}; + +pub const ACCOUNT: &str = "123456789012"; +pub const REGION: &str = "us-east-1"; + +/// One applied write, as the double saw it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum Applied { + Put(String), + Delete(String), +} + +/// A storage double whose per-key calls fail with a chosen service error for +/// a chosen set of partition key values and succeed for every other key. +pub struct FailingStore { + /// Tables the double knows, with whether each has a local secondary index. + tables: HashMap, + /// Items served by `get_item`, by partition key value. + items: BTreeMap, + /// Partition key values whose data calls fail with `error`. + failing: HashSet, + /// The error returned for a failing key. + error: DynamoDbError, + /// Writes that reached the backend, in call order. + applied: Mutex>, +} + +impl FailingStore { + pub fn new(error: DynamoDbError) -> Self { + Self { + tables: HashMap::from([("T".to_owned(), true), ("U".to_owned(), false)]), + items: BTreeMap::new(), + failing: HashSet::new(), + error, + applied: Mutex::new(Vec::new()), + } + } + + pub fn throttling() -> Self { + Self::new(throttle_error("TableReadProvisionedThroughputExceeded")) + } + + /// A double that throttles writes, carrying the write reason. + pub fn throttling_writes() -> Self { + Self::new(throttle_error("TableWriteProvisionedThroughputExceeded")) + } + + pub fn with_items(mut self, pks: &[&str]) -> Self { + for pk in pks { + self.items.insert((*pk).to_owned(), item(pk)); + } + self + } + + pub fn with_large_item(mut self, pk: &str) -> Self { + self.items.insert(pk.to_owned(), large_item(pk)); + self + } + + pub fn failing_on(mut self, pks: &[&str]) -> Self { + self.failing = pks.iter().map(|p| (*p).to_owned()).collect(); + self + } + + fn fails(&self, key_or_item: &Item) -> bool { + self.failing.contains(&pk_of(key_or_item)) + } + + pub fn applied(&self) -> Vec { + self.applied.lock().expect("applied lock").clone() + } +} + +pub fn throttle_error(reason: &str) -> DynamoDbError { + DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + vec![ThrottlingReason { + reason: reason.to_owned(), + resource: format!("arn:aws:dynamodb:{REGION}:{ACCOUNT}:table/T"), + }], + ) +} + +pub fn pk_of(item: &Item) -> String { + match item.get("pk") { + Some(AttributeValue::S(s)) => s.clone(), + other => panic!("item without string pk: {other:?}"), + } +} + +pub fn key(pk: &str) -> Item { + BTreeMap::from([("pk".to_owned(), AttributeValue::S(pk.to_owned()))]) +} + +pub fn item(pk: &str) -> Item { + let mut it = key(pk); + it.insert("v".to_owned(), AttributeValue::N("1".to_owned())); + it +} + +/// An item just over 4 KB, so a consistent read of it costs two capacity +/// units and a size-blind charge of one per item is told apart. +pub fn large_item(pk: &str) -> Item { + let mut it = key(pk); + it.insert("v".to_owned(), AttributeValue::S("x".repeat(4_100))); + it +} + +pub fn key_info(table: &str, has_lsi: bool) -> TableKeyInfo { + TableKeyInfo { + table_name: table.to_owned(), + account_id: ACCOUNT.to_owned(), + table_id: format!("id-{table}"), + key_schema: vec![KeySchemaElement { + attribute_name: "pk".to_owned(), + key_type: KeyType::Hash, + }], + base_key_schema: vec![KeySchemaElement { + attribute_name: "pk".to_owned(), + key_type: KeyType::Hash, + }], + attribute_definitions: vec![AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }], + has_lsi, + global_secondary_indexes: Vec::new(), + local_secondary_indexes: Vec::new(), + stream_specification: None, + vector_indexes: Vec::new(), + } +} + +impl TableEngine for FailingStore { + fn create_table( + &self, + _account_id: &str, + _input: CreateTableInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn delete_table( + &self, + _account_id: &str, + _input: DeleteTableInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn describe_table( + &self, + _account_id: &str, + _input: DescribeTableInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn list_tables( + &self, + _account_id: &str, + _input: ListTablesInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn update_table( + &self, + _account_id: &str, + _input: UpdateTableInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn table_key_info( + &self, + _account_id: &str, + table_name: &str, + ) -> BoxedFuture<'_, Result> { + let result = match self.tables.get(table_name) { + Some(has_lsi) => Ok(key_info(table_name, *has_lsi)), + None => Err(StorageError::TableNotFound(table_name.to_owned())), + }; + Box::pin(async move { result }) + } + fn index_info( + &self, + _account_id: &str, + _table_name: &str, + _index_name: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn index_info_by_table_id( + &self, + _table_id: &str, + _index_name: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } +} + +impl DataEngine for FailingStore { + fn put_item( + &self, + _key_info: &TableKeyInfo, + item: Item, + _return_old: bool, + _condition: Option<&Expr>, + _maps: &ExpressionMaps, + _stream: Option<&StreamCapture>, + ) -> BoxedFuture<'_, Result, StorageError>> { + let result = if self.fails(&item) { + Err(StorageError::Service(self.error.clone())) + } else { + self.applied + .lock() + .expect("applied lock") + .push(Applied::Put(pk_of(&item))); + Ok(None) + }; + Box::pin(async move { result }) + } + + fn get_item( + &self, + _key_info: &TableKeyInfo, + key: &Item, + ) -> BoxedFuture<'_, Result, StorageError>> { + let result = if self.fails(key) { + Err(StorageError::Service(self.error.clone())) + } else { + Ok(self.items.get(&pk_of(key)).cloned()) + }; + Box::pin(async move { result }) + } + + fn delete_item( + &self, + _key_info: &TableKeyInfo, + key: &Item, + _return_old: bool, + _condition: Option<&Expr>, + _maps: &ExpressionMaps, + _stream: Option<&StreamCapture>, + ) -> BoxedFuture<'_, Result, StorageError>> { + let result = if self.fails(key) { + Err(StorageError::Service(self.error.clone())) + } else { + self.applied + .lock() + .expect("applied lock") + .push(Applied::Delete(pk_of(key))); + Ok(None) + }; + Box::pin(async move { result }) + } + + fn update_item( + &self, + _key_info: &TableKeyInfo, + _key: &Item, + _actions: &[UpdateAction], + _return_old: bool, + _return_new: bool, + _condition: Option<&Expr>, + _maps: &ExpressionMaps, + _stream: Option<&StreamCapture>, + ) -> BoxedFuture<'_, ItemPairResult> { + unimplemented!("not exercised") + } + + fn query( + &self, + _key_info: &TableKeyInfo, + _key_condition: &KeyCondition, + _maps: &ExpressionMaps, + _forward: bool, + _limit: Option, + _exclusive_start_key: Option<&Item>, + _index_name: Option<&str>, + ) -> BoxedFuture<'_, QueryResult> { + unimplemented!("not exercised") + } + + fn scan( + &self, + _key_info: &TableKeyInfo, + _limit: Option, + _exclusive_start_key: Option<&Item>, + _segment: Option, + _total_segments: Option, + _index_name: Option<&str>, + ) -> BoxedFuture<'_, QueryResult> { + unimplemented!("not exercised") + } + + fn scan_key_in_segment( + &self, + _key_info: &TableKeyInfo, + _key: &Item, + _segment: i64, + _total_segments: i64, + _index_name: Option<&str>, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + + fn transact_get_items( + &self, + _ops: &[TransactGetOp<'_>], + ) -> BoxedFuture<'_, Result>, StorageError>> { + unimplemented!("not exercised") + } + + fn transact_write_items( + &self, + _ops: &[TransactWriteOp<'_>], + _idempotency: Option>, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + + fn cleanup_expired_idempotency_tokens( + &self, + _max_age_seconds: i64, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } +} + +impl MetadataEngine for FailingStore { + fn describe_ttl( + &self, + _account_id: &str, + _table_name: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn update_ttl( + &self, + _account_id: &str, + _table_name: &str, + _attribute_name: &str, + _enabled: bool, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn tag_resource(&self, _arn: &str, _tags: &[Tag]) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn untag_resource( + &self, + _arn: &str, + _tag_keys: &[String], + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn list_tags(&self, _arn: &str) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn tables_with_ttl( + &self, + _account_id: &str, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn all_tables_with_ttl(&self) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn all_tables_with_ttl_index_ready( + &self, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn create_ttl_index( + &self, + _account_id: &str, + _table_name: &str, + _ttl_attribute: &str, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn drop_ttl_index( + &self, + _account_id: &str, + _table_name: &str, + _ttl_attribute: &str, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn find_expired_items_indexed( + &self, + _account_id: &str, + _table_name: &str, + _ttl_attribute: &str, + _limit: usize, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn refresh_table_size( + &self, + _account_id: &str, + _table_name: &str, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn list_active_table_names( + &self, + _account_id: &str, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn all_active_tables(&self) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } +} + +impl StreamEngine for FailingStore { + fn write_stream_record( + &self, + _account_id: &str, + _record: &StreamRecord, + _shard_id: &str, + _table_name: &str, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn get_stream_records( + &self, + _account_id: &str, + _shard_id: &str, + _after_sequence: Option<&str>, + _limit: i64, + ) -> BoxedFuture<'_, StreamRecordsResult> { + unimplemented!("not exercised") + } + fn describe_stream( + &self, + _account_id: &str, + _input: &DescribeStreamInput, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn list_streams( + &self, + _account_id: &str, + _table_name: Option<&str>, + _limit: i64, + _exclusive_start_stream_arn: Option<&str>, + ) -> BoxedFuture<'_, StreamListResult> { + unimplemented!("not exercised") + } + fn cleanup_expired_stream_records( + &self, + _retention_hours: i64, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn assign_shard( + &self, + _account_id: &str, + _table_name: &str, + _partition_key: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn next_sequence_number( + &self, + _shard_id: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn validate_shard( + &self, + _account_id: &str, + _stream_arn: &str, + _shard_id: &str, + ) -> BoxedFuture<'_, Result<(), StorageError>> { + unimplemented!("not exercised") + } + fn latest_sequence_number( + &self, + _shard_id: &str, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } +} + +impl BackupEngine for FailingStore { + fn create_backup( + &self, + _account_id: &str, + _table_name: &str, + _backup_name: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn describe_backup( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn list_backups( + &self, + _account_id: &str, + _table_name: Option<&str>, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn delete_backup( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn backup_restore_source( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn restore_table_from_backup( + &self, + _account_id: &str, + _request: RestoreRequest, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn describe_continuous_backups( + &self, + _account_id: &str, + _table_name: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn update_continuous_backups( + &self, + _account_id: &str, + _table_name: &str, + _pitr_enabled: bool, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } +} + +impl WorkerStore for FailingStore { + fn process_control_plane_transitions( + &self, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } +} diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 5c2f19cbb..fbd3abebf 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -19,8 +19,8 @@ use crate::AppState; use crate::request_helpers::{authorize_request, extract_operation, extract_table_name}; use crate::response::{error_response, record_error_metrics, success_response}; use crate::throttle_helpers::{ - classify_data_operation, extract_partition_value, table_description_to_throughput, - throttle_error, update_throttle_buckets, + classify_data_operation, extract_partition_value, record_partial_batch_throttle, + table_description_to_throughput, throttle_error, update_throttle_buckets, }; /// Main Virtual `DynamoDB` request handler. @@ -275,6 +275,9 @@ pub(crate) async fn handle_request( table_name.as_deref(), &result.body, ); + // A batch a backend served partially is a throttle the server's own + // bucket never saw; count it so the metrics do not read as zero. + record_partial_batch_throttle(&state.metrics, &operation, &result.body); let m = &result.metrics; if let Some(ref tn) = table_name { diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index c97a4ce57..21da75787 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -115,6 +115,45 @@ fn extract_throughput_from_response( )) } +/// Record throttle metrics for a batch response a backend served partially. +/// +/// The server's own bucket records `ThrottledRequests` and the read or write +/// throttle event when it refuses a request. A backend throttle that leaves +/// entries under `UnprocessedKeys` or `UnprocessedItems` returns a 200 and +/// would otherwise count as no throttle at all, so this records +/// `ThrottledRequests` and the read or write throttle event once per table +/// named in the non-empty map, with the table as the dimension the bucket's +/// own records carry. The map's keys are the table names, which the batch +/// operations do not carry at the top level. +pub(crate) fn record_partial_batch_throttle( + metrics: &extenddb_core::metrics::MetricsCollector, + operation: &str, + body: &Value, +) { + use extenddb_core::metrics::MetricName; + let (field, event) = match operation { + "BatchGetItem" => ("UnprocessedKeys", MetricName::ReadThrottleEvents), + "BatchWriteItem" => ("UnprocessedItems", MetricName::WriteThrottleEvents), + _ => return, + }; + let Some(tables) = body.get(field).and_then(Value::as_object) else { + return; + }; + if tables.is_empty() { + return; + } + for table in tables.keys() { + metrics.record( + MetricName::ThrottledRequests, + 1.0, + Some(table), + None, + Some(operation), + ); + metrics.record(event, 1.0, Some(table), None, Some(operation)); + } +} + /// Extract the partition key value from a request body for per-partition throttling. /// /// For item-level operations (`GetItem`, `PutItem`, `DeleteItem`, `UpdateItem`), @@ -459,3 +498,63 @@ mod throttle_error_tests { } } } + +#[cfg(test)] +mod partial_batch_throttle_tests { + use extenddb_core::metrics::{MetricName, MetricsCollector, MetricsQuery, TimeWindow}; + use serde_json::json; + + use super::record_partial_batch_throttle; + + fn sum(c: &MetricsCollector, metric: MetricName, table: Option<&str>) -> f64 { + c.query(&MetricsQuery { + table_name: table.map(str::to_owned), + metric: Some(metric), + window: Some(TimeWindow::AllTime), + ..Default::default() + }) + .iter() + .map(|s| s.sum) + .sum() + } + + #[test] + fn a_partial_batch_get_records_a_request_and_a_read_event_per_table() { + let c = MetricsCollector::new(); + record_partial_batch_throttle( + &c, + "BatchGetItem", + &json!({"Responses": {"T": []}, "UnprocessedKeys": {"T": {"Keys": []}, "U": {"Keys": []}}}), + ); + assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 2.0); + assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); + assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("U")), 1.0); + assert_eq!(sum(&c, MetricName::ReadThrottleEvents, Some("T")), 1.0); + assert_eq!(sum(&c, MetricName::ReadThrottleEvents, Some("U")), 1.0); + assert_eq!(sum(&c, MetricName::WriteThrottleEvents, None), 0.0); + } + + #[test] + fn a_partial_batch_write_records_a_write_event() { + let c = MetricsCollector::new(); + record_partial_batch_throttle( + &c, + "BatchWriteItem", + &json!({"UnprocessedItems": {"T": [{"PutRequest": {"Item": {}}}]}}), + ); + assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); + assert_eq!(sum(&c, MetricName::WriteThrottleEvents, Some("T")), 1.0); + } + + /// A fully served batch (the map present and empty) and a non-batch + /// operation record nothing. + #[test] + fn a_full_batch_or_another_operation_records_nothing() { + let c = MetricsCollector::new(); + record_partial_batch_throttle(&c, "BatchGetItem", &json!({"UnprocessedKeys": {}})); + record_partial_batch_throttle(&c, "BatchWriteItem", &json!({"UnprocessedItems": {}})); + record_partial_batch_throttle(&c, "GetItem", &json!({"UnprocessedKeys": {"T": {}}})); + assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 0.0); + assert_eq!(sum(&c, MetricName::ReadThrottleEvents, None), 0.0); + } +} From 2c87bf852c5219d16b50239eecc1adce7420276e Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 23:45:35 +0000 Subject: [PATCH 05/33] docs: describe partial batch success under a backend throttle --- docs/differences-from-dynamodb.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 6add1c700..9406c4275 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -147,6 +147,7 @@ The same on all four backends. | On-demand capacity | Automatic scaling | Fixed initial burst capacity (4000 WCU / 12000 RCU), no auto-scaling; a table with `OnDemandThroughput` caps is sized by the caps, per direction; the bucket starts with one second of the rate and accumulates unused capacity up to 300 seconds of it | | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | | Throttle error bodies | A throttle names the throttled resource and the limit. A provisioned table's own capacity is `ProvisionedThroughputExceededException` with `ThrottlingReasons: [{reason: Table{Read\|Write}ProvisionedThroughputExceeded, resource:
}]` on every read and write operation; a hot key on an on-demand table is `ThrottlingException` in the `com.amazon.coral.availability#` namespace with `throttlingReasons` (lower t) naming `TableWriteKeyRangeThroughputExceeded` on a write and no reasons list on a read; an on-demand table at its `OnDemandThroughput` caps is `ThrottlingException` with the message `Throughput exceeds the maximum OnDemandThroughput configured on table or index` and `Table{Read\|Write}MaxOnDemandThroughputExceeded`. Measured 2026-10-20 (435 bodies, one Region) and 2026-10-24 (9,622 bodies, two Regions). No `x-amz-retry-after` header | The same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. The account aggregate bucket sends `RequestLimitExceeded` with `Table{Read\|Write}AccountLimitExceeded`, and an on-demand table past its default ceiling sends `ThrottlingException` with the same reason: both follow the API Reference and were not produced by the measurements. A hot key on a provisioned table names `Table{Read\|Write}KeyRangeThroughputExceeded` with the provisioned class and message; the write form was captured once on 2026-10-20, the read form follows the documented grammar | +| Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails the request | | Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24: 104 index-write bodies, 648 index-read bodies) | Not modelled: the token buckets are per table and per partition key, with no per-index capacity | ## Operations Not Implemented 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 06/33] 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 07/33] 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 542d0733249c8b59a2740f1124825cb02058614e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:45:22 +0000 Subject: [PATCH 08/33] fix: adapt the partial batch throttle code to the merged interfaces MetricsCollector::record takes the account since #955. record_partial_batch_throttle now takes the account of the request and records both metrics under it, as the throttle records of the bucket do. Its tests query the metrics by that account. The storage traits changed on feat/throttling-reasons. BackupEngine is gone, and StorageEngine requires BackupCatalog, LegacyBackupReader, RestoreEngine and SnapshotEngine. get_stream_records takes the stream ARN. The test double of crates/engine/tests/batch_partial.rs implements the four traits with stubs that the tests never reach, as it did for BackupEngine. It also takes the new parameter. OperationContext has a backup runtime and an item authorizer, and the test context sets a runtime with one job slot and no authorizer. In crates/engine/src/backup.rs the merge put the service_error_tests module after the modules that feat/throttling-reasons added. rustfmt orders that list by name, so the commit moves the module into its place. --- crates/engine/src/backup.rs | 4 +- crates/engine/tests/batch_partial.rs | 4 +- .../tests/batch_partial/failing_store.rs | 321 ++++++++++++++++-- crates/server/src/handler.rs | 7 +- crates/server/src/throttle_helpers.rs | 38 ++- 5 files changed, 343 insertions(+), 31 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; diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs index 97adabbf5..f9e285d9d 100644 --- a/crates/engine/tests/batch_partial.rs +++ b/crates/engine/tests/batch_partial.rs @@ -31,7 +31,7 @@ use extenddb_auth::AuthCacheRegistry; use extenddb_core::error::{DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE}; use extenddb_core::limits::LimitsConfig; use extenddb_engine::{ - DispatchResult, OperationContext, handle_batch_get_item, handle_batch_write_item, + BackupRuntime, DispatchResult, OperationContext, handle_batch_get_item, handle_batch_write_item, }; use failing_store::*; @@ -39,6 +39,7 @@ use failing_store::*; fn ctx(store: Arc) -> OperationContext { OperationContext { storage: store, + backup: Arc::new(BackupRuntime::new(1)), limits: Arc::new(LimitsConfig::default()), region: Arc::from(REGION), account_id: Arc::from(ACCOUNT), @@ -47,6 +48,7 @@ fn ctx(store: Arc) -> OperationContext { authorized_key_info: extenddb_engine::AuthorizedKeyInfo::new(), auth_cache: AuthCacheRegistry::empty(), table_key_info_lookup: None, + item_authorizer: None, } } diff --git a/crates/engine/tests/batch_partial/failing_store.rs b/crates/engine/tests/batch_partial/failing_store.rs index 7c7c120cc..7544e4fb5 100644 --- a/crates/engine/tests/batch_partial/failing_store.rs +++ b/crates/engine/tests/batch_partial/failing_store.rs @@ -6,24 +6,35 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Mutex; +use std::time::Duration; +use extenddb_core::backup_format::BackupArn; use extenddb_core::error::{ DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, ThrottlingReason, }; use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition, UpdateAction}; use extenddb_core::types::{ AttributeDefinition, AttributeValue, BackupDescription, BackupDetails, BackupSummary, - ContinuousBackupsDescription, CreateTableInput, DeleteTableInput, DescribeStreamInput, - DescribeTableInput, IndexInfo, Item, KeySchemaElement, KeyType, ListTablesInput, - ListTablesOutput, ScalarAttributeType, StreamDescription, StreamRecord, TableDescription, - TableKeyInfo, Tag, TimeToLiveDescription, UpdateTableInput, + CreateTableInput, DeleteTableInput, DescribeStreamInput, DescribeTableInput, IndexInfo, Item, + KeySchemaElement, KeyType, ListTablesInput, ListTablesOutput, ScalarAttributeType, + StreamDescription, StreamRecord, TableDescription, TableKeyInfo, Tag, TimeToLiveDescription, + UpdateTableInput, +}; +use extenddb_storage::backup_catalog::{ + AbandonedLegacyBackup, BackupKey, BackupRow, BackupStatus, DeleteStart, ForgetRow, JobStatus, + LegacyBackupItems, LegacyBackupKey, Replaced, RestoreJobRow, RestoreRegistered, + RestoreRegistrationRow, RestoreTargetKey, StaleClock, StoreIdentity, StoreKind, StoreRootCount, + TimeBounds, }; use extenddb_storage::error::StorageError; use extenddb_storage::{ - BackupEngine, BackupRestoreSource, BoxedFuture, DataEngine, IdempotencyKey, ItemPairResult, - MetadataEngine, QueryResult, RestoreRequest, StreamCapture, StreamEngine, StreamListResult, - StreamRecordsResult, TableEngine, TransactGetOp, TransactWriteOp, TtlTableInfo, WorkerStore, + BackupCatalog, BackupRestoreSource, BoxedFuture, BulkLoadFile, DataEngine, Finished, + IdempotencyKey, ItemPairResult, JobClaim, JobPermit, LegacyBackupReader, MaintenanceClaim, + MetadataEngine, QueryResult, RestoreEngine, RestoreRequest, SnapshotEngine, StreamCapture, + StreamEngine, StreamListResult, StreamRecordsResult, TableEngine, TableSnapshot, TransactGetOp, + TransactWriteOp, TtlTableInfo, WorkerStore, }; +use futures::stream::BoxStream; pub const ACCOUNT: &str = "123456789012"; pub const REGION: &str = "us-east-1"; @@ -449,6 +460,7 @@ impl StreamEngine for FailingStore { fn get_stream_records( &self, _account_id: &str, + _stream_arn: &str, _shard_id: &str, _after_sequence: Option<&str>, _limit: i64, @@ -507,63 +519,332 @@ impl StreamEngine for FailingStore { } } -impl BackupEngine for FailingStore { - fn create_backup( +impl BackupCatalog for FailingStore { + fn catalog_id(&self) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn claim_backup<'a>( + &'a self, + _row: &'a BackupRow, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn insert_backup_row<'a>( + &'a self, + _row: &'a BackupRow, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn list_backup_rows<'a>( + &'a self, + _status: Option, + _store: &'a StoreIdentity, + ) -> BoxStream<'a, Result> { + unimplemented!("not exercised") + } + fn list_backup_rows_by_root<'a>( + &'a self, + _store_kind: StoreKind, + _store_root: &'a str, + _status: Option, + ) -> BoxStream<'a, Result> { + unimplemented!("not exercised") + } + fn newest_available_backup_row<'a>( + &'a self, + _store: &'a StoreIdentity, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn list_account_backup_rows<'a>( + &'a self, + _account_id: &'a str, + _table_name: Option<&'a str>, + _bounds: &'a TimeBounds, + ) -> BoxStream<'a, Result> { + unimplemented!("not exercised") + } + fn read_backup_row<'a>( + &'a self, + _arn: &'a BackupArn, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn row_holding_backup_id<'a>( + &'a self, + _backup_id: &'a str, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn start_backup_delete<'a>( + &'a self, + _key: &'a BackupKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn set_backup_deleted<'a>( + &'a self, + _key: &'a BackupKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn remove_backup_row<'a>( + &'a self, + _key: &'a BackupKey, + _store_kind: StoreKind, + _store_root: &'a str, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn forget_available_backup_row<'a>( + &'a self, + _key: &'a BackupKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn rewrite_store<'a>( + &'a self, + _from_kind: StoreKind, + _from_root: &'a str, + _keys: &'a [BackupKey], + _to: &'a StoreIdentity, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn remove_dead_creating_backup_row<'a>( + &'a self, + _key: &'a BackupKey, + _stale_after: Duration, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn claim_dead_backup<'a>( + &'a self, + _key: &'a BackupKey, + _stale_after: Duration, + ) -> BoxedFuture<'a, Result>, StorageError>> { + unimplemented!("not exercised") + } + fn list_backup_rows_older_than<'a>( + &'a self, + _status: BackupStatus, + _store: &'a StoreIdentity, + _clock: StaleClock, + _age: Duration, + ) -> BoxStream<'a, Result> { + unimplemented!("not exercised") + } + fn backup_in_use<'a>( + &'a self, + _key: &'a BackupKey, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn remove_restore_target<'a>( + &'a self, + _key: &'a RestoreTargetKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn list_dead_restore_jobs( + &self, + _stale_after: Duration, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn list_running_restore_jobs( + &self, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn fail_restore_job<'a>( + &'a self, + _key: &'a RestoreTargetKey, + _owner_generation: u64, + _heartbeat_at: f64, + _reason: &'a str, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn claim_restore<'a>( + &'a self, + _account_id: &'a str, + _input: CreateTableInput, + _registration: &'a RestoreRegistrationRow, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn claim_restore_dead<'a>( + &'a self, + _key: &'a RestoreTargetKey, + _stale_after: Duration, + _spool_host: Option<&'a str>, + ) -> BoxedFuture<'a, Result>, StorageError>> { + unimplemented!("not exercised") + } + fn read_restore_job<'a>( + &'a self, + _key: &'a RestoreTargetKey, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn list_restore_jobs<'a>( + &'a self, + _status: Option, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn read_store_ids<'a>( + &'a self, + _store_kind: StoreKind, + _store_root: &'a str, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn summarize_store_roots(&self) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn maintenance_claim<'a>( + &'a self, + _holder: &'a str, + _stale_after: Duration, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn check_maintenance_claim( + &self, + _stale_after: Duration, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } +} + +impl LegacyBackupReader for FailingStore { + fn create( &self, _account_id: &str, _table_name: &str, _backup_name: &str, + _permit: JobPermit, ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } - fn describe_backup( + fn describe( &self, _account_id: &str, _backup_arn: &str, ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } - fn list_backups( + fn list( &self, _account_id: &str, _table_name: Option<&str>, ) -> BoxedFuture<'_, Result, StorageError>> { unimplemented!("not exercised") } - fn delete_backup( + fn delete( &self, _account_id: &str, _backup_arn: &str, ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } - fn backup_restore_source( + fn restore_source( &self, _account_id: &str, _backup_arn: &str, ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } - fn restore_table_from_backup( + fn restore( &self, _account_id: &str, _request: RestoreRequest, + _permit: JobPermit, ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } - fn describe_continuous_backups( + fn abandoned_creating_backups( + &self, + _stale_after: Duration, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn list_all(&self) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn list_deleted(&self) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn holder_status<'a>( + &'a self, + _account_id: &'a str, + _backup_arn: &'a str, + ) -> BoxedFuture<'a, Result, StorageError>> { + unimplemented!("not exercised") + } + fn remove_deleted<'a>( + &'a self, + _account_id: &'a str, + _backup_arn: &'a str, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn items( &self, _account_id: &str, - _table_name: &str, - ) -> BoxedFuture<'_, Result> { + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn replace_with_index_row<'a>( + &'a self, + _row: &'a BackupRow, + ) -> BoxedFuture<'a, Result> { unimplemented!("not exercised") } - fn update_continuous_backups( +} + +impl RestoreEngine for FailingStore { + fn bulk_load<'a>( + &'a self, + _target: &'a RestoreTargetKey, + _claim: &'a dyn JobClaim, + _file: BulkLoadFile, + _items: BoxStream<'a, Result>, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn finish_restore<'a>( + &'a self, + _target: &'a RestoreTargetKey, + _claim: &'a dyn JobClaim, + _item_count: u64, + _size_bytes: u64, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn count_restore_target<'a>( + &'a self, + _key: &'a RestoreTargetKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } + fn restore_target_ready<'a>( + &'a self, + _key: &'a RestoreTargetKey, + ) -> BoxedFuture<'a, Result> { + unimplemented!("not exercised") + } +} + +impl SnapshotEngine for FailingStore { + fn open_table_snapshot( &self, _account_id: &str, _table_name: &str, - _pitr_enabled: bool, - ) -> BoxedFuture<'_, Result> { + ) -> BoxedFuture<'_, Result> { unimplemented!("not exercised") } } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index dd10fa8fc..dafce6c1d 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -329,7 +329,12 @@ pub(crate) async fn handle_request( ); // A batch a backend served partially is a throttle the server's own // bucket never saw; count it so the metrics do not read as zero. - record_partial_batch_throttle(&state.metrics, &operation, &result.body); + record_partial_batch_throttle( + &state.metrics, + &ctx.account_id, + &operation, + &result.body, + ); let m = &result.metrics; if let Some(ref tn) = metric_table { diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 21da75787..0f521c1ea 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -122,11 +122,12 @@ fn extract_throughput_from_response( /// entries under `UnprocessedKeys` or `UnprocessedItems` returns a 200 and /// would otherwise count as no throttle at all, so this records /// `ThrottledRequests` and the read or write throttle event once per table -/// named in the non-empty map, with the table as the dimension the bucket's -/// own records carry. The map's keys are the table names, which the batch -/// operations do not carry at the top level. +/// named in the non-empty map, with the account and the table as the +/// dimensions the bucket's own records carry. The map's keys are the table +/// names, which the batch operations do not carry at the top level. pub(crate) fn record_partial_batch_throttle( metrics: &extenddb_core::metrics::MetricsCollector, + account_id: &str, operation: &str, body: &Value, ) { @@ -146,11 +147,19 @@ pub(crate) fn record_partial_batch_throttle( metrics.record( MetricName::ThrottledRequests, 1.0, + Some(account_id), + Some(table), + None, + Some(operation), + ); + metrics.record( + event, + 1.0, + Some(account_id), Some(table), None, Some(operation), ); - metrics.record(event, 1.0, Some(table), None, Some(operation)); } } @@ -506,8 +515,11 @@ mod partial_batch_throttle_tests { use super::record_partial_batch_throttle; + const ACCOUNT: &str = "111111111111"; + fn sum(c: &MetricsCollector, metric: MetricName, table: Option<&str>) -> f64 { c.query(&MetricsQuery { + account_id: Some(ACCOUNT.to_owned()), table_name: table.map(str::to_owned), metric: Some(metric), window: Some(TimeWindow::AllTime), @@ -523,6 +535,7 @@ mod partial_batch_throttle_tests { let c = MetricsCollector::new(); record_partial_batch_throttle( &c, + ACCOUNT, "BatchGetItem", &json!({"Responses": {"T": []}, "UnprocessedKeys": {"T": {"Keys": []}, "U": {"Keys": []}}}), ); @@ -539,6 +552,7 @@ mod partial_batch_throttle_tests { let c = MetricsCollector::new(); record_partial_batch_throttle( &c, + ACCOUNT, "BatchWriteItem", &json!({"UnprocessedItems": {"T": [{"PutRequest": {"Item": {}}}]}}), ); @@ -551,9 +565,19 @@ mod partial_batch_throttle_tests { #[test] fn a_full_batch_or_another_operation_records_nothing() { let c = MetricsCollector::new(); - record_partial_batch_throttle(&c, "BatchGetItem", &json!({"UnprocessedKeys": {}})); - record_partial_batch_throttle(&c, "BatchWriteItem", &json!({"UnprocessedItems": {}})); - record_partial_batch_throttle(&c, "GetItem", &json!({"UnprocessedKeys": {"T": {}}})); + record_partial_batch_throttle(&c, ACCOUNT, "BatchGetItem", &json!({"UnprocessedKeys": {}})); + record_partial_batch_throttle( + &c, + ACCOUNT, + "BatchWriteItem", + &json!({"UnprocessedItems": {}}), + ); + record_partial_batch_throttle( + &c, + ACCOUNT, + "GetItem", + &json!({"UnprocessedKeys": {"T": {}}}), + ); assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 0.0); assert_eq!(sum(&c, MetricName::ReadThrottleEvents, None), 0.0); } From f5ef7948477dc76eb7a2d1c25847e8cfbe210265 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:46:08 +0000 Subject: [PATCH 09/33] docs(adr): number the backend-classified client error ADR 0028 feat/throttling-reasons has ADR 0023 for the catalog migrations, and this branch carried the backend-classified client error decision as a second 0023. feat/storage-service-error moved that decision to 0028. This commit renames the file to 0028-backend-classified-client-error.md with the same content and title as on feat/storage-service-error, and moves its index row to 0028. The index row was the only link to the old name. --- ...-client-error.md => 0028-backend-classified-client-error.md} | 2 +- docs/adr/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/adr/{0023-backend-classified-client-error.md => 0028-backend-classified-client-error.md} (98%) diff --git a/docs/adr/0023-backend-classified-client-error.md b/docs/adr/0028-backend-classified-client-error.md similarity index 98% rename from docs/adr/0023-backend-classified-client-error.md rename to docs/adr/0028-backend-classified-client-error.md index 6049626bd..25e915221 100644 --- a/docs/adr/0023-backend-classified-client-error.md +++ b/docs/adr/0028-backend-classified-client-error.md @@ -1,4 +1,4 @@ -# ADR-0023: A backend-classified client error passes through the engine unchanged +# ADR-0028: A backend-classified client error passes through the engine unchanged - Status: Accepted - Date: 2026-10-24 diff --git a/docs/adr/README.md b/docs/adr/README.md index 56d2adeda..8af407ad8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -52,9 +52,9 @@ decision, write a new ADR. | [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 | | [0023](0023-catalog-migrations.md) | One list of catalog migrations for every backend, with a ledger in every store | Accepted | -| [0023](0023-backend-classified-client-error.md) | A backend-classified client error passes through the engine unchanged | Accepted | | [0026](0026-credential-crypto-on-aws-lc.md) | Credential cryptography uses AWS-LC through aws-lc-rs | Accepted | | [0027](0027-cassandra-index-row-version-stamps.md) | Cassandra: index rows carry the base-row version as their write timestamp | Accepted | +| [0028](0028-backend-classified-client-error.md) | A backend-classified client error passes through the engine unchanged | Accepted | | [0029](0029-crates-io-packaging.md) | The workspace crates go to crates.io together, at one version with exact pins | Accepted | --- From fa7a1e524d2b5b0d0eb6b9d4cc4b250a409f12b7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:28:29 +0000 Subject: [PATCH 10/33] fix: record a partial batch throttle only for throttled tables Since main #475, BatchWriteItem leaves a request that failed with a transient, conflict or connection error in UnprocessedItems. record_partial_batch_throttle read UnprocessedItems and UnprocessedKeys from the response, so it recorded those deferrals as throttles. DispatchMetrics now carries throttled_tables, by the catalog's table name. It lists each table of a batch with at least one request or key that a backend throttled, once. write_batch adds a table where it counts a throttle, and handle_batch_get_item adds one where it leaves a key unprocessed. record_partial_batch_throttle records ThrottledRequests and the read or write throttle event for each of those tables. A table that a request named by its ARN gets the same table dimension as main's other records (#922). --- crates/engine/src/batch_get_item.rs | 6 ++ crates/engine/src/batch_write_item.rs | 5 ++ .../write_batch_deferral_tests.rs | 2 + crates/engine/src/lib.rs | 4 ++ crates/engine/tests/batch_partial.rs | 2 + crates/server/src/handler.rs | 2 +- crates/server/src/throttle_helpers.rs | 59 ++++++------------- 7 files changed, 39 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index f8feac8ab..daaa4fe47 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -180,6 +180,7 @@ pub async fn handle_batch_get_item( let mut unprocessed_keys: HashMap = HashMap::new(); let mut throttled_count: usize = 0; let mut first_throttle: Option = None; + let mut throttled_tables: Vec = Vec::new(); let mut total_rcu: f64 = 0.0; let mut total_pre_proj_bytes: usize = 0; let mut returned_count: u64 = 0; @@ -231,6 +232,10 @@ pub async fn handle_batch_get_item( } } if !table_unprocessed.is_empty() { + // Only a throttle leaves a key unprocessed. + if !throttled_tables.contains(&key_info.table_name) { + throttled_tables.push(key_info.table_name.clone()); + } // The request's KeysAndAttributes with Keys reduced to the // unprocessed ones, in request order (the service's order is not // measured: its served and unprocessed lists came back in neither @@ -284,6 +289,7 @@ pub async fn handle_batch_get_item( read_capacity_units: rcu, returned_item_count: returned_count, returned_bytes: total_pre_proj_bytes as u64, + throttled_tables, ..Default::default() }, }) diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 131542f1c..aefc69fa4 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -217,6 +217,7 @@ async fn write_batch( // a batch of which every request was throttled answers that error. let mut throttled_count: usize = 0; let mut first_throttle: Option = None; + let mut throttled_tables: Vec = Vec::new(); 'tables: for (table_index, ((table_name, reqs), key_info)) in tables.iter().zip(&key_infos).enumerate() @@ -301,6 +302,9 @@ async fn write_batch( if first_throttle.is_none() { first_throttle = Some(e); } + if !throttled_tables.contains(&key_info.table_name) { + throttled_tables.push(key_info.table_name.clone()); + } } unprocessed .entry(table_name.to_owned()) @@ -419,6 +423,7 @@ async fn write_batch( body, metrics: DispatchMetrics { write_capacity_units: wcu, + throttled_tables, ..Default::default() }, }) diff --git a/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs b/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs index f3aed3d43..5a190d8e7 100644 --- a/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs +++ b/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs @@ -36,6 +36,8 @@ async fn a_failed_first_request_does_not_stop_the_rest() { assert_eq!(out.body["UnprocessedItems"], json!({"t": [put("held")]})); assert_eq!(data.writes(), ["t/held", "t/side"]); + // A held item is no throttle: the server records none for the batch. + assert!(out.metrics.throttled_tables.is_empty()); } /// UnprocessedItems holds exactly the requests that failed, per table, and the diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aff9035d4..5c481093a 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -361,6 +361,10 @@ pub struct DispatchMetrics { /// GSI/LSI name when the operation targets a secondary index. /// Used to attribute metrics to the specific index. pub index_name: Option, + /// The tables of a batch that answered 200 with requests or keys a + /// backend throttled left unprocessed, by table name, once each. The + /// server records a throttle for each: its own bucket never saw them. + pub throttled_tables: Vec, } /// Result of an engine dispatch: the JSON response body plus sideband metrics. diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs index f9e285d9d..eb7b3b21f 100644 --- a/crates/engine/tests/batch_partial.rs +++ b/crates/engine/tests/batch_partial.rs @@ -197,6 +197,7 @@ async fn batch_get_one_table_throttled_beside_a_served_table() { json!([{"TableName": "U", "CapacityUnits": 1.0}]) ); assert_eq!(result.metrics.read_capacity_units, 1.0); + assert_eq!(result.metrics.throttled_tables, ["T"]); } /// Every key of every table throttled: the call fails with the throttle @@ -459,6 +460,7 @@ async fn batch_write_one_applied_entry_is_a_partial_success() { result.body["ConsumedCapacity"], json!([{"TableName": "T", "CapacityUnits": 1.0}]) ); + assert_eq!(result.metrics.throttled_tables, ["T"]); } /// Nothing throttled: `UnprocessedItems` is present as `{}` (13 of 13 fully diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index dafce6c1d..6b0962cab 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -333,7 +333,7 @@ pub(crate) async fn handle_request( &state.metrics, &ctx.account_id, &operation, - &result.body, + &result.metrics.throttled_tables, ); let m = &result.metrics; diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 0f521c1ea..fa56868e3 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -119,31 +119,26 @@ fn extract_throughput_from_response( /// /// The server's own bucket records `ThrottledRequests` and the read or write /// throttle event when it refuses a request. A backend throttle that leaves -/// entries under `UnprocessedKeys` or `UnprocessedItems` returns a 200 and -/// would otherwise count as no throttle at all, so this records -/// `ThrottledRequests` and the read or write throttle event once per table -/// named in the non-empty map, with the account and the table as the -/// dimensions the bucket's own records carry. The map's keys are the table -/// names, which the batch operations do not carry at the top level. +/// requests or keys unprocessed returns a 200 and would otherwise count as no +/// throttle at all, so this records `ThrottledRequests` and the read or write +/// throttle event once per table the engine reports throttled +/// (`DispatchMetrics::throttled_tables`), with the account and the table as +/// the dimensions the bucket's own records carry. The response's +/// `UnprocessedItems` is no throttle count: it also holds requests deferred +/// for a transient, conflict or connection failure. pub(crate) fn record_partial_batch_throttle( metrics: &extenddb_core::metrics::MetricsCollector, account_id: &str, operation: &str, - body: &Value, + throttled_tables: &[String], ) { use extenddb_core::metrics::MetricName; - let (field, event) = match operation { - "BatchGetItem" => ("UnprocessedKeys", MetricName::ReadThrottleEvents), - "BatchWriteItem" => ("UnprocessedItems", MetricName::WriteThrottleEvents), + let event = match operation { + "BatchGetItem" => MetricName::ReadThrottleEvents, + "BatchWriteItem" => MetricName::WriteThrottleEvents, _ => return, }; - let Some(tables) = body.get(field).and_then(Value::as_object) else { - return; - }; - if tables.is_empty() { - return; - } - for table in tables.keys() { + for table in throttled_tables { metrics.record( MetricName::ThrottledRequests, 1.0, @@ -511,7 +506,6 @@ mod throttle_error_tests { #[cfg(test)] mod partial_batch_throttle_tests { use extenddb_core::metrics::{MetricName, MetricsCollector, MetricsQuery, TimeWindow}; - use serde_json::json; use super::record_partial_batch_throttle; @@ -537,7 +531,7 @@ mod partial_batch_throttle_tests { &c, ACCOUNT, "BatchGetItem", - &json!({"Responses": {"T": []}, "UnprocessedKeys": {"T": {"Keys": []}, "U": {"Keys": []}}}), + &["T".to_owned(), "U".to_owned()], ); assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 2.0); assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); @@ -550,34 +544,19 @@ mod partial_batch_throttle_tests { #[test] fn a_partial_batch_write_records_a_write_event() { let c = MetricsCollector::new(); - record_partial_batch_throttle( - &c, - ACCOUNT, - "BatchWriteItem", - &json!({"UnprocessedItems": {"T": [{"PutRequest": {"Item": {}}}]}}), - ); + record_partial_batch_throttle(&c, ACCOUNT, "BatchWriteItem", &["T".to_owned()]); assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); assert_eq!(sum(&c, MetricName::WriteThrottleEvents, Some("T")), 1.0); } - /// A fully served batch (the map present and empty) and a non-batch - /// operation record nothing. + /// A batch with no throttled table and a non-batch operation record + /// nothing. #[test] fn a_full_batch_or_another_operation_records_nothing() { let c = MetricsCollector::new(); - record_partial_batch_throttle(&c, ACCOUNT, "BatchGetItem", &json!({"UnprocessedKeys": {}})); - record_partial_batch_throttle( - &c, - ACCOUNT, - "BatchWriteItem", - &json!({"UnprocessedItems": {}}), - ); - record_partial_batch_throttle( - &c, - ACCOUNT, - "GetItem", - &json!({"UnprocessedKeys": {"T": {}}}), - ); + record_partial_batch_throttle(&c, ACCOUNT, "BatchGetItem", &[]); + record_partial_batch_throttle(&c, ACCOUNT, "BatchWriteItem", &[]); + record_partial_batch_throttle(&c, ACCOUNT, "GetItem", &["T".to_owned()]); assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 0.0); assert_eq!(sum(&c, MetricName::ReadThrottleEvents, None), 0.0); } From 3cd1be409b2b59021220179286f936a8f6bf2ef3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:28:29 +0000 Subject: [PATCH 11/33] docs: describe the BatchWriteItem throttle answer in the differences page The merge of feat/throttling-reasons brought main's row for a BatchWriteItem with no request applied, which says that the batch answers 503. This branch's row on partial batch success says that any other backend error still fails the request. A batch of which a backend throttled every request answers the first throttle error, and BatchWriteItem defers transient, conflict and connection failures. Each row now says so and names the other row. --- docs/differences-from-dynamodb.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 2c483f15f..3e92dbdb6 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -20,7 +20,7 @@ from a request sent to that service or backend. | `TransactGetItems` overlapping an in-flight `TransactWriteItems` on the same item | May cancel the read with `TransactionCanceledException` and reason `TransactionConflict` | Never cancels for this reason on PostgreSQL: the read runs in one `REPEATABLE READ` snapshot taken at its first read, so it sees either all of the write or none of it and returns the pre-write state while the write is in flight. That is a legal serial order (the read ordered before the write) and the all-or-nothing guarantee holds, but a client that retries on `TransactionConflict` to observe the newest state will not get that signal here. SQLite behaves the same (one WAL snapshot); MongoDB with the default `snapshot` read concern likewise, and the row above covers the other read concerns. | | Transaction read concern (MongoDB backend only) | No user-configurable equivalent | `snapshot` is the default, fidelity-preserving mode. With `majority` or `local`, `TransactGetItems` is not guaranteed a single point-in-time snapshot and transaction condition reads have weaker isolation. With `local`, a condition can be evaluated against data that is later rolled back after failover. | | Contended `TransactWriteItems` | A transaction that conflicts with another in-flight transaction on the same item is canceled with a `TransactionConflict` reason ("Transaction is ongoing for the item") | **PostgreSQL** queues the second transaction on the first one's row locks and **SQLite** runs one writer at a time, so both normally commit and no `TransactionConflict` is returned. PostgreSQL locks each transaction's items in table and key order, so two `TransactWriteItems` cannot deadlock on each other. A PutItem, UpdateItem, DeleteItem or BatchWriteItem of an item that a `TransactWriteItems` has locked also waits for it, where the Amazon DynamoDB developer guide lists that request as a conflict. On PostgreSQL this includes an item that the transaction checks or deletes while it is missing: the transaction holds the key until it commits or rolls back, so a request that creates the item waits. Many transactions that check one hot missing item queue less fairly than on an existing item, because every waiter wakes at each commit and only one proceeds. Each such check or delete of a missing item also inserts and deletes its key, so it writes WAL and leaves a dead row and index entry for autovacuum, even though it changes no item. When PostgreSQL still aborts a transaction (a deadlock with another lock holder, or a serialization failure under a stricter `default_transaction_isolation`), the answer is a `TransactionCanceledException` with a `TransactionConflict` reason, not a 500. **MongoDB** retries write conflicts internally and cancels with `TransactionConflict` on every item only after sustained contention. A client that relies on `TransactionConflict` to back off does not see it under ordinary contention. | -| `BatchWriteItem` where no request could be applied now | A request that could not be applied is returned in `UnprocessedItems` with a 200 when another request of the batch applied, whichever came first (measured 2026-10-27 in us-east-1, client retries off, while a `TransactWriteItems` held the items: a batch of two requests, one on a held item, answered 200 with that request unprocessed and the other applied). When no request applied the batch answers an error, not a 200 with every request unprocessed (measured 2026-10-27 in us-east-1, client retries off, with every request on an item a `TransactWriteItems` held, for one request and for two: 500 `InternalServerError`) | The same 200 for a partial batch. When no request could be applied the answer is 503 `ServiceUnavailable`, which the SDKs retry with backoff, so a client's `UnprocessedItems` loop does not spin on a batch that makes no progress. Every request is tried before the batch answers, so a batch of 25 contended requests can spend 25 retry budgets in one call. A connection error ends the attempt: the request that met it and the requests after it are returned unprocessed, or the batch answers 503 if nothing applied. An internal storage error fails the batch with 500 as before. On a Cassandra table without TTL, a put or a delete of an item that a `TransactWriteItems` holds returns `TransactionCanceled`, which is not left for the client to replay, so the batch answers 400 `TransactionCanceledException` after the requests ahead of it were applied. A Cassandra write that spends its retries on a lost race, or on a held item of a TTL table, returns `TransactionConflict`, left in `UnprocessedItems`. A table of which no request applied gets no `ConsumedCapacity` entry. What the service reports for such a table in a partial batch is not measured. | +| `BatchWriteItem` where no request could be applied now | A request that could not be applied is returned in `UnprocessedItems` with a 200 when another request of the batch applied, whichever came first (measured 2026-10-27 in us-east-1, client retries off, while a `TransactWriteItems` held the items: a batch of two requests, one on a held item, answered 200 with that request unprocessed and the other applied). When no request applied the batch answers an error, not a 200 with every request unprocessed (measured 2026-10-27 in us-east-1, client retries off, with every request on an item a `TransactWriteItems` held, for one request and for two: 500 `InternalServerError`) | The same 200 for a partial batch. When no request could be applied the answer is 503 `ServiceUnavailable`, which the SDKs retry with backoff, so a client's `UnprocessedItems` loop does not spin on a batch that makes no progress. A batch of which a backend throttled every request answers the first throttle error instead (see "Partial batch success under throttling"). Every request is tried before the batch answers, so a batch of 25 contended requests can spend 25 retry budgets in one call. A connection error ends the attempt: the request that met it and the requests after it are returned unprocessed, or the batch answers 503 if nothing applied. An internal storage error fails the batch with 500 as before. On a Cassandra table without TTL, a put or a delete of an item that a `TransactWriteItems` holds returns `TransactionCanceled`, which is not left for the client to replay, so the batch answers 400 `TransactionCanceledException` after the requests ahead of it were applied. A Cassandra write that spends its retries on a lost race, or on a held item of a TTL table, returns `TransactionConflict`, left in `UnprocessedItems`. A table of which no request applied gets no `ConsumedCapacity` entry. What the service reports for such a table in a partial batch is not measured. | | Contended single-item writes on a MongoDB table that has a stream or an index | `PutItem`, `DeleteItem` and `UpdateItem` on one item are applied one after another and each answers 200 (measured 2026-10-23, client retries off, on a table with a GSI and a stream); `TransactionConflictException` is answered to them only while a `TransactWriteItems` holds the item | MongoDB aborts the later of two transactions that write one document, so each write runs as a transaction that is re-run with jittered backoff, up to 50 attempts. A write on a table with a stream also conflicts on the sequence counter of the shard it is assigned to, so writers of different keys can conflict. A write that could not commit in 50 attempts answers 503 `ServiceUnavailable`, which the SDKs retry, where the service answers 200. The server records that 503 as a system error, not under `TransactionConflict` (which counts `TransactionConflictException` answers), so contention shows in the system error metrics. The warning in the server log carries the last error that ended an attempt of the failed write. | ## Authentication and Authorization (AWS IAM/STS auth surface used by DynamoDB) @@ -204,7 +204,7 @@ alone, with the same wording. For PartiQL this holds in `ExecuteStatement`, | Warm throughput | Pre-provisions partitions to the requested read and write units; raising it is a long-running operation (`Status: UPDATING` for minutes, the previous values reported meanwhile); a request above the account's table maximum is `LimitExceededException` | Stored and reported with the same shape, defaults and validation so clients that read it (the Terraform AWS provider since 6.13.0) work: the previous values are reported with `Status: UPDATING` for `control_plane_delay_seconds` after a change, then the new values `ACTIVE`; a decrease is measured against the reported values, as on the service. Nothing acts on the values: no pre-warming and no scaling at the database level. The account maximum is not known to ExtendDB and is not enforced. A provisioned table whose warm throughput was never set, or was set on one side only, reports its new units at once after a capacity change, where the service reports the old units until the table is `ACTIVE`. Switching a table to `PAY_PER_REQUEST` stores 12000 read and 4000 write units where its warm throughput is lower, and the stored values stay after a switch back to `PROVISIONED`, as on the service; the response to the switch reads the new values with `Status: UPDATING` for `control_plane_delay_seconds`, where the service answers with the previous values and `Status: ACTIVE` | | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | | Throttle error bodies | A throttle names the throttled resource and the limit. A provisioned table's own capacity is `ProvisionedThroughputExceededException` with `ThrottlingReasons: [{reason: Table{Read\|Write}ProvisionedThroughputExceeded, resource:
}]` on every read and write operation; a hot key on an on-demand table is `ThrottlingException` in the `com.amazon.coral.availability#` namespace with `throttlingReasons` (lower t) naming `TableWriteKeyRangeThroughputExceeded` on a write and no reasons list on a read; an on-demand table at its `OnDemandThroughput` caps is `ThrottlingException` with the message `Throughput exceeds the maximum OnDemandThroughput configured on table or index` and `Table{Read\|Write}MaxOnDemandThroughputExceeded`. Measured 2026-10-20 (435 bodies, one Region) and 2026-10-24 (9,622 bodies, two Regions). No `x-amz-retry-after` header | The same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. The account aggregate bucket sends `RequestLimitExceeded` with `Table{Read\|Write}AccountLimitExceeded`, and an on-demand table past its default ceiling sends `ThrottlingException` with the same reason: both follow the API Reference and were not produced by the measurements. A hot key on a provisioned table names `Table{Read\|Write}KeyRangeThroughputExceeded` with the provisioned class and message; the write form was captured once on 2026-10-20, the read form follows the documented grammar | -| Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails the request | +| Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails a `BatchGetItem`. A `BatchWriteItem` also defers a transient, conflict or connection failure, and answers 503 when nothing applied and not every request was throttled (see "`BatchWriteItem` where no request could be applied now") | | Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24: 104 index-write bodies, 648 index-read bodies) | Not modelled: the token buckets are per table and per partition key, with no per-index capacity | ## PartiQL 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 12/33] 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 e63887da6a577fff97301d9d1cb900cee2353335 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:23:38 +0000 Subject: [PATCH 13/33] docs: say which BatchWriteItem batches with nothing applied answer 503 A batch with nothing applied answers 503 when the engine deferred one of its requests for a transient, conflict or connection failure. A request that meets an internal error still fails the batch with 500. The rule comment in write_batch and the partial batch row of the differences page said 503 for any other failure. Both now name the deferral. The comment on the throttle count no longer repeats the rule. --- crates/engine/src/batch_write_item.rs | 7 +++---- docs/differences-from-dynamodb.md | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index aefc69fa4..07f57d5ba 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -191,8 +191,8 @@ async fn write_batch( // ThrottlingReasons: the API reference documents // ProvisionedThroughputExceededException or ThrottlingException for a // batch that cannot process any item because of throttling (documented, - // not measured). A batch with nothing applied in which a request failed - // for another reason answers 503. + // not measured). A batch with nothing applied in which a request was + // deferred for another reason answers 503. // // The request faults the same page lists reject the whole batch before // anything is written. `check_batch` finds a missing table, a key that @@ -213,8 +213,7 @@ async fn write_batch( // The error of the last request that was not applied, for the warning // logged once per batch below. let mut last_error = String::new(); - // How many requests the backend throttled, and the first throttle error: - // a batch of which every request was throttled answers that error. + // How many requests the backend throttled, and the first throttle error. let mut throttled_count: usize = 0; let mut first_throttle: Option = None; let mut throttled_tables: Vec = Vec::new(); diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 3e92dbdb6..4b57d4d86 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -204,7 +204,7 @@ alone, with the same wording. For PartiQL this holds in `ExecuteStatement`, | Warm throughput | Pre-provisions partitions to the requested read and write units; raising it is a long-running operation (`Status: UPDATING` for minutes, the previous values reported meanwhile); a request above the account's table maximum is `LimitExceededException` | Stored and reported with the same shape, defaults and validation so clients that read it (the Terraform AWS provider since 6.13.0) work: the previous values are reported with `Status: UPDATING` for `control_plane_delay_seconds` after a change, then the new values `ACTIVE`; a decrease is measured against the reported values, as on the service. Nothing acts on the values: no pre-warming and no scaling at the database level. The account maximum is not known to ExtendDB and is not enforced. A provisioned table whose warm throughput was never set, or was set on one side only, reports its new units at once after a capacity change, where the service reports the old units until the table is `ACTIVE`. Switching a table to `PAY_PER_REQUEST` stores 12000 read and 4000 write units where its warm throughput is lower, and the stored values stay after a switch back to `PROVISIONED`, as on the service; the response to the switch reads the new values with `Status: UPDATING` for `control_plane_delay_seconds`, where the service answers with the previous values and `Status: ACTIVE` | | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | | Throttle error bodies | A throttle names the throttled resource and the limit. A provisioned table's own capacity is `ProvisionedThroughputExceededException` with `ThrottlingReasons: [{reason: Table{Read\|Write}ProvisionedThroughputExceeded, resource:
}]` on every read and write operation; a hot key on an on-demand table is `ThrottlingException` in the `com.amazon.coral.availability#` namespace with `throttlingReasons` (lower t) naming `TableWriteKeyRangeThroughputExceeded` on a write and no reasons list on a read; an on-demand table at its `OnDemandThroughput` caps is `ThrottlingException` with the message `Throughput exceeds the maximum OnDemandThroughput configured on table or index` and `Table{Read\|Write}MaxOnDemandThroughputExceeded`. Measured 2026-10-20 (435 bodies, one Region) and 2026-10-24 (9,622 bodies, two Regions). No `x-amz-retry-after` header | The same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. The account aggregate bucket sends `RequestLimitExceeded` with `Table{Read\|Write}AccountLimitExceeded`, and an on-demand table past its default ceiling sends `ThrottlingException` with the same reason: both follow the API Reference and were not produced by the measurements. A hot key on a provisioned table names `Table{Read\|Write}KeyRangeThroughputExceeded` with the provisioned class and message; the write form was captured once on 2026-10-20, the read form follows the documented grammar | -| Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails a `BatchGetItem`. A `BatchWriteItem` also defers a transient, conflict or connection failure, and answers 503 when nothing applied and not every request was throttled (see "`BatchWriteItem` where no request could be applied now") | +| Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails the request. A `BatchWriteItem` also defers a transient, conflict or connection failure, and a batch with nothing applied that has such a deferral answers 503 (see "`BatchWriteItem` where no request could be applied now") | | Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24: 104 index-write bodies, 648 index-read bodies) | Not modelled: the token buckets are per table and per partition key, with no per-index capacity | ## PartiQL 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 14/33] 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 15/33] 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 16/33] 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 17/33] 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 18/33] 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 19/33] 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 20/33] 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 21/33] 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 22/33] 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![ ( From f7a2adac90413f9ef05c29bdbca3f9fc1fc50175 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:50:40 +0000 Subject: [PATCH 23/33] fix: compile the engine tests against the merged throttling-reasons head The merge brings main's move of the backup storage error mapping from backup.rs to backup_requests.rs. So the fault log test names the function at its new path. StreamEngine gained first_sequence_number_at_or_after on main, so the batch_partial storage double implements it as not exercised, like its other stream methods. --- crates/engine/src/service_error_log_tests.rs | 4 ++-- crates/engine/tests/batch_partial/failing_store.rs | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs index 56b4936bd..b4b8940ed 100644 --- a/crates/engine/src/service_error_log_tests.rs +++ b/crates/engine/src/service_error_log_tests.rs @@ -54,8 +54,8 @@ fn sites() -> Vec { crate::create_table::storage_err_to_dynamo, ), ( - "backup::storage_err_to_dynamo", - crate::backup::storage_err_to_dynamo, + "backup_requests::storage_err_to_dynamo", + crate::backup_requests::storage_err_to_dynamo, ), ("update_table::update_table_err_to_dynamo", |e| { crate::update_table::update_table_err_to_dynamo(e, "t") diff --git a/crates/engine/tests/batch_partial/failing_store.rs b/crates/engine/tests/batch_partial/failing_store.rs index 7544e4fb5..cc49f6e54 100644 --- a/crates/engine/tests/batch_partial/failing_store.rs +++ b/crates/engine/tests/batch_partial/failing_store.rs @@ -517,6 +517,13 @@ impl StreamEngine for FailingStore { ) -> BoxedFuture<'_, Result, StorageError>> { unimplemented!("not exercised") } + fn first_sequence_number_at_or_after( + &self, + _shard_id: &str, + _at_ms: i64, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } } impl BackupCatalog for FailingStore { From 523e3b43e227f2ce47671a78224a0b31e9aced79 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:54:53 +0000 Subject: [PATCH 24/33] test(engine): build the throttle errors of the merged service error tests through their constructors The merged storage-service-error head builds ProvisionedThroughputExceededException, ThrottlingException and RequestLimitExceeded as tuple variants in the fault log rows and in the BatchExecuteStatement code test. On this branch they are struct variants with a reasons list, so the tests build them with provisioned_throughput_exceeded, throttling and request_limit_exceeded and an empty list. An empty list is left out of the error body, so the expected bodies do not change. --- crates/engine/src/partiql/common/tests.rs | 12 +++++------- crates/engine/src/service_error_log_tests.rs | 2 +- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/partiql/common/tests.rs b/crates/engine/src/partiql/common/tests.rs index 6a7aa5086..f101b45c9 100644 --- a/crates/engine/src/partiql/common/tests.rs +++ b/crates/engine/src/partiql/common/tests.rs @@ -191,20 +191,18 @@ fn an_error_of_the_item_operation_names_the_batch_table() { 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(), + DynamoDbError::provisioned_throughput_exceeded( + "The level of configured provisioned throughput for the table was exceeded.", + vec![], ), "ProvisionedThroughputExceeded", ), ( - DynamoDbError::ThrottlingException( - "Throughput exceeds the current capacity.".to_owned(), - ), + DynamoDbError::throttling("Throughput exceeds the current capacity.", vec![]), "ThrottlingError", ), ( - DynamoDbError::RequestLimitExceeded("Throughput exceeds the account quota.".to_owned()), + DynamoDbError::request_limit_exceeded("Throughput exceeds the account quota.", vec![]), "RequestLimitExceeded", ), ( diff --git a/crates/engine/src/service_error_log_tests.rs b/crates/engine/src/service_error_log_tests.rs index 97e721b05..bf5058290 100644 --- a/crates/engine/src/service_error_log_tests.rs +++ b/crates/engine/src/service_error_log_tests.rs @@ -69,7 +69,7 @@ pub(crate) fn rows() -> Vec<(DynamoDbError, Value)> { body("InternalServerError", internal), ), ( - DynamoDbError::ProvisionedThroughputExceededException(capacity.to_owned()), + DynamoDbError::provisioned_throughput_exceeded(capacity, vec![]), body("ProvisionedThroughputExceededException", capacity), ), ( From 0890859b8e3839f281a9cd4a714468858fe4444b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:18 +0000 Subject: [PATCH 25/33] fix: count each backend-throttled batch entry as a throttle event CloudWatch's metrics page for DynamoDB counts each throttled entry of a BatchGetItem or BatchWriteItem as a ReadThrottleEvents or WriteThrottleEvents event. A batch counts in ThrottledRequests only when every entry was throttled. A throttled request stays out of UserErrors. The server recorded ThrottledRequests and one throttle event per table on a batch that answered 200 with entries a backend throttled. It counted the throttle error of a batch whose every entry was throttled in UserErrors. DispatchMetrics::throttled_tables now maps each table, by catalog name, to the number of its entries a backend throttled. On a 200 the server records that number as one read or write throttle event data point per table. It records no ThrottledRequests there. record_error_metrics counts a throttle error in ThrottledRequests, under the table the request named when it names one, and not in UserErrors. The server's own bucket records its refusals before dispatch. So that arm counts a throttle a backend reported. --- crates/engine/src/batch_get_item.rs | 11 ++- crates/engine/src/batch_write_item.rs | 10 +-- crates/engine/src/lib.rs | 8 +- crates/engine/tests/batch_partial.rs | 11 ++- crates/server/src/response.rs | 46 +++++++++- crates/server/src/throttle_helpers.rs | 123 ++++++++++++++------------ 6 files changed, 133 insertions(+), 76 deletions(-) diff --git a/crates/engine/src/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index daaa4fe47..d7b38f2e2 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -3,7 +3,7 @@ //! `BatchGetItem` operation handler. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use serde_json::Value; @@ -180,7 +180,7 @@ pub async fn handle_batch_get_item( let mut unprocessed_keys: HashMap = HashMap::new(); let mut throttled_count: usize = 0; let mut first_throttle: Option = None; - let mut throttled_tables: Vec = Vec::new(); + let mut throttled_tables: BTreeMap = BTreeMap::new(); let mut total_rcu: f64 = 0.0; let mut total_pre_proj_bytes: usize = 0; let mut returned_count: u64 = 0; @@ -208,6 +208,9 @@ pub async fn handle_batch_get_item( Err(StorageError::Service(e)) if e.is_throttle() => { table_unprocessed.push(key.clone()); throttled_count += 1; + *throttled_tables + .entry(key_info.table_name.clone()) + .or_default() += 1; if first_throttle.is_none() { first_throttle = Some(e); } @@ -232,10 +235,6 @@ pub async fn handle_batch_get_item( } } if !table_unprocessed.is_empty() { - // Only a throttle leaves a key unprocessed. - if !throttled_tables.contains(&key_info.table_name) { - throttled_tables.push(key_info.table_name.clone()); - } // The request's KeysAndAttributes with Keys reduced to the // unprocessed ones, in request order (the service's order is not // measured: its served and unprocessed lists came back in neither diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 07f57d5ba..419d3b372 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -3,7 +3,7 @@ //! `BatchWriteItem` operation handler. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use serde_json::Value; @@ -216,7 +216,7 @@ async fn write_batch( // How many requests the backend throttled, and the first throttle error. let mut throttled_count: usize = 0; let mut first_throttle: Option = None; - let mut throttled_tables: Vec = Vec::new(); + let mut throttled_tables: BTreeMap = BTreeMap::new(); 'tables: for (table_index, ((table_name, reqs), key_info)) in tables.iter().zip(&key_infos).enumerate() @@ -301,9 +301,9 @@ async fn write_batch( if first_throttle.is_none() { first_throttle = Some(e); } - if !throttled_tables.contains(&key_info.table_name) { - throttled_tables.push(key_info.table_name.clone()); - } + *throttled_tables + .entry(key_info.table_name.clone()) + .or_default() += 1; } unprocessed .entry(table_name.to_owned()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c98305703..ae55ba3aa 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -380,10 +380,10 @@ pub struct DispatchMetrics { /// GSI/LSI name when the operation targets a secondary index. /// Used to attribute metrics to the specific index. pub index_name: Option, - /// The tables of a batch that answered 200 with requests or keys a - /// backend throttled left unprocessed, by table name, once each. The - /// server records a throttle for each: its own bucket never saw them. - pub throttled_tables: Vec, + /// The requests or keys a backend throttled in a batch that answered 200, + /// counted per table by its catalog name. The server records each count + /// as read or write throttle events: its own bucket never saw them. + pub throttled_tables: std::collections::BTreeMap, } /// Result of an engine dispatch: the JSON response body plus sideband metrics. diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs index eb7b3b21f..812a63ae7 100644 --- a/crates/engine/tests/batch_partial.rs +++ b/crates/engine/tests/batch_partial.rs @@ -21,7 +21,7 @@ #[path = "batch_partial/failing_store.rs"] mod failing_store; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; use std::sync::Arc; @@ -65,6 +65,11 @@ fn pks(list: &Value) -> BTreeSet { .collect() } +/// The throttled entry count per table the engine hands the server. +fn counts(rows: &[(&str, u32)]) -> BTreeMap { + rows.iter().map(|(t, n)| ((*t).to_owned(), *n)).collect() +} + /// The error of a handler result, or a panic naming the body that came back. fn err_of(result: Result) -> DynamoDbError { match result { @@ -197,7 +202,7 @@ async fn batch_get_one_table_throttled_beside_a_served_table() { json!([{"TableName": "U", "CapacityUnits": 1.0}]) ); assert_eq!(result.metrics.read_capacity_units, 1.0); - assert_eq!(result.metrics.throttled_tables, ["T"]); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); } /// Every key of every table throttled: the call fails with the throttle @@ -460,7 +465,7 @@ async fn batch_write_one_applied_entry_is_a_partial_success() { result.body["ConsumedCapacity"], json!([{"TableName": "T", "CapacityUnits": 1.0}]) ); - assert_eq!(result.metrics.throttled_tables, ["T"]); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); } /// Nothing throttled: `UnprocessedItems` is present as `{}` (13 of 13 fully diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index 8ea195307..6e31dec99 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -68,8 +68,13 @@ pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Respons /// /// `UserErrors` carries no table name: CloudWatch reports it per account and /// Region only, and a 4xx is often a request whose `TableName` broke the -/// rules. A failed condition counts in `ConditionalCheckFailedRequests` and not -/// in `UserErrors`, as CloudWatch's metrics page says. `table_name` is the name +/// rules. A failed condition counts in `ConditionalCheckFailedRequests` and a +/// throttle error in `ThrottledRequests`, neither in `UserErrors`, as +/// CloudWatch's metrics page says. The server's own bucket records its +/// refusals before dispatch, so a throttle error here is one a backend +/// reported. On `BatchGetItem` and `BatchWriteItem` it answers a batch whose +/// every entry was throttled, the one batch CloudWatch counts in +/// `ThrottledRequests`. `table_name` is the name /// `request_helpers::metric_table_name` checked, used by the metrics that carry /// one. Every metric carries `account_id`, the account the request was /// authenticated for. @@ -91,6 +96,16 @@ pub(crate) fn record_error_metrics( metrics.record_user_error(account_id, None, operation); metrics.record_transaction_conflict(account_id, operation); } + e if e.is_throttle() => { + metrics.record( + extenddb_core::metrics::MetricName::ThrottledRequests, + 1.0, + Some(account_id), + table_name, + None, + Some(operation), + ); + } _ => { metrics.record_user_error(account_id, None, operation); } @@ -171,6 +186,33 @@ mod tests { ); } + /// A throttle error of each class counts in `ThrottledRequests`, under the + /// table the request named, and not in `UserErrors`. + #[test] + fn a_throttle_error_is_a_throttled_request_and_not_a_user_error() { + for error in [ + DynamoDbError::provisioned_throughput_exceeded("capacity", vec![]), + DynamoDbError::throttling("throughput", vec![]), + DynamoDbError::request_limit_exceeded("quota", vec![]), + ] { + let collector = MetricsCollector::new(); + record_error_metrics(&collector, &error, ACCOUNT, Some("Orders"), "GetItem"); + record_error_metrics(&collector, &error, ACCOUNT, None, "BatchGetItem"); + assert!( + dimensions_of(&collector, MetricName::UserErrors).is_empty(), + "{error:?}" + ); + let mut throttled = dimensions_of(&collector, MetricName::ThrottledRequests); + throttled.sort_by_key(|dims| has_table(dims)); + assert_eq!(throttled.len(), 2, "{error:?}: {throttled:?}"); + assert!(!has_table(&throttled[0]), "{error:?}: {throttled:?}"); + assert!( + throttled[1].contains(&Dimension::TableName("Orders".to_owned())), + "{error:?}: {throttled:?}" + ); + } + } + #[test] fn table_scoped_error_metrics_keep_the_checked_table_name() { let collector = MetricsCollector::new(); diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 4ed4b2f9e..5e6e7f28c 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -115,22 +115,24 @@ fn extract_throughput_from_response( )) } -/// Record throttle metrics for a batch response a backend served partially. +/// Record the throttle events of a batch response a backend served partially. /// -/// The server's own bucket records `ThrottledRequests` and the read or write -/// throttle event when it refuses a request. A backend throttle that leaves -/// requests or keys unprocessed returns a 200 and would otherwise count as no -/// throttle at all, so this records `ThrottledRequests` and the read or write -/// throttle event once per table the engine reports throttled -/// (`DispatchMetrics::throttled_tables`), with the account and the table as -/// the dimensions the bucket's own records carry. The response's +/// A backend throttle that leaves requests or keys unprocessed returns a 200 +/// that the server's own bucket never saw. CloudWatch counts each throttled +/// entry of a batch as a read or write throttle event, and counts the batch +/// in `ThrottledRequests` only when every entry was throttled, which answers +/// the throttle error (`record_error_metrics` counts that one). So this +/// records one data point per table the engine reports +/// (`DispatchMetrics::throttled_tables`), with the number of the table's +/// throttled entries as its value, and the account and the table as the +/// dimensions the bucket's own records carry. The response's /// `UnprocessedItems` is no throttle count: it also holds requests deferred /// for a transient, conflict or connection failure. pub(crate) fn record_partial_batch_throttle( metrics: &extenddb_core::metrics::MetricsCollector, account_id: &str, operation: &str, - throttled_tables: &[String], + throttled_tables: &std::collections::BTreeMap, ) { use extenddb_core::metrics::MetricName; let event = match operation { @@ -138,18 +140,10 @@ pub(crate) fn record_partial_batch_throttle( "BatchWriteItem" => MetricName::WriteThrottleEvents, _ => return, }; - for table in throttled_tables { - metrics.record( - MetricName::ThrottledRequests, - 1.0, - Some(account_id), - Some(table), - None, - Some(operation), - ); + for (table, entries) in throttled_tables { metrics.record( event, - 1.0, + f64::from(*entries), Some(account_id), Some(table), None, @@ -482,13 +476,17 @@ mod throttle_error_tests { #[cfg(test)] mod partial_batch_throttle_tests { + use std::collections::BTreeMap; + use extenddb_core::metrics::{MetricName, MetricsCollector, MetricsQuery, TimeWindow}; use super::record_partial_batch_throttle; const ACCOUNT: &str = "111111111111"; - fn sum(c: &MetricsCollector, metric: MetricName, table: Option<&str>) -> f64 { + /// The sum and the number of data points of `metric` for `table`, or for + /// every table with `None`. + fn points(c: &MetricsCollector, metric: MetricName, table: Option<&str>) -> (f64, u64) { c.query(&MetricsQuery { account_id: Some(ACCOUNT.to_owned()), table_name: table.map(str::to_owned), @@ -497,44 +495,57 @@ mod partial_batch_throttle_tests { ..Default::default() }) .iter() - .map(|s| s.sum) - .sum() - } - - #[test] - fn a_partial_batch_get_records_a_request_and_a_read_event_per_table() { - let c = MetricsCollector::new(); - record_partial_batch_throttle( - &c, - ACCOUNT, - "BatchGetItem", - &["T".to_owned(), "U".to_owned()], - ); - assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 2.0); - assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); - assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("U")), 1.0); - assert_eq!(sum(&c, MetricName::ReadThrottleEvents, Some("T")), 1.0); - assert_eq!(sum(&c, MetricName::ReadThrottleEvents, Some("U")), 1.0); - assert_eq!(sum(&c, MetricName::WriteThrottleEvents, None), 0.0); + .fold((0.0, 0), |(sum, count), s| (sum + s.sum, count + s.count)) } + /// CloudWatch counts each throttled entry of a batch as a read or write + /// throttle event and leaves a partly served batch out of + /// `ThrottledRequests`. Each row: the operation, the throttled entries per + /// table, and the read and write events expected per table as (sum, data + /// points), one point per table carrying its entry count. #[test] - fn a_partial_batch_write_records_a_write_event() { - let c = MetricsCollector::new(); - record_partial_batch_throttle(&c, ACCOUNT, "BatchWriteItem", &["T".to_owned()]); - assert_eq!(sum(&c, MetricName::ThrottledRequests, Some("T")), 1.0); - assert_eq!(sum(&c, MetricName::WriteThrottleEvents, Some("T")), 1.0); - } - - /// A batch with no throttled table and a non-batch operation record - /// nothing. - #[test] - fn a_full_batch_or_another_operation_records_nothing() { - let c = MetricsCollector::new(); - record_partial_batch_throttle(&c, ACCOUNT, "BatchGetItem", &[]); - record_partial_batch_throttle(&c, ACCOUNT, "BatchWriteItem", &[]); - record_partial_batch_throttle(&c, ACCOUNT, "GetItem", &["T".to_owned()]); - assert_eq!(sum(&c, MetricName::ThrottledRequests, None), 0.0); - assert_eq!(sum(&c, MetricName::ReadThrottleEvents, None), 0.0); + fn a_partial_batch_records_one_throttle_event_per_throttled_entry() { + type Events<'a> = &'a [(&'a str, (f64, u64))]; + let rows: [(&str, &[(&str, u32)], Events, Events); 4] = [ + ( + "BatchGetItem", + &[("T", 3), ("U", 1)], + &[("T", (3.0, 1)), ("U", (1.0, 1))], + &[], + ), + ("BatchWriteItem", &[("T", 25)], &[], &[("T", (25.0, 1))]), + ("BatchGetItem", &[], &[], &[]), + ("GetItem", &[("T", 1)], &[], &[]), + ]; + for (operation, throttled, reads, writes) in rows { + let c = MetricsCollector::new(); + let throttled: BTreeMap = throttled + .iter() + .map(|(t, n)| ((*t).to_owned(), *n)) + .collect(); + record_partial_batch_throttle(&c, ACCOUNT, operation, &throttled); + let row = format!("{operation} {throttled:?}"); + assert_eq!( + points(&c, MetricName::ThrottledRequests, None), + (0.0, 0), + "{row}" + ); + for (metric, expected) in [ + (MetricName::ReadThrottleEvents, reads), + (MetricName::WriteThrottleEvents, writes), + ] { + let total = expected + .iter() + .fold((0.0, 0), |(sum, count), (_, (s, n))| (sum + s, count + n)); + assert_eq!(points(&c, metric, None), total, "{row} {metric:?}"); + for (table, sum_and_points) in expected { + assert_eq!( + points(&c, metric, Some(table)), + *sum_and_points, + "{row} {metric:?} {table}" + ); + } + } + } } } From 15805a722d727f44a053bbf8ede1441a914f5f4b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:47 +0000 Subject: [PATCH 26/33] test(engine): compare the partial batch lists in request order for every throttle class The partial batch tests compared the served and unprocessed lists as sets, so a list returned in reverse order passed. They also ran with ProvisionedThroughputExceededException only, so a check narrowed to that class passed. No test held the first throttle error of an all-throttled batch or the catalog name the engine hands the server. The tests now compare Responses, UnprocessedKeys, UnprocessedItems and ItemCollectionMetrics in request order. The partial and all-throttled tests of both operations run for ProvisionedThroughputExceededException, ThrottlingException and RequestLimitExceeded. Each class has its service message and reasons list, and the tests compare the error by status and body. Two tests throttle the keys or puts of one table with different errors. They rotate the errors so that each class comes first once, and expect the error of the first entry. Two tests send a table ARN as the request name. They expect the answer under the ARN and the throttled entry count under the catalog name. The storage double takes an error per key for this. --- crates/engine/tests/batch_partial.rs | 452 +++++++++++------- .../tests/batch_partial/failing_store.rs | 70 ++- 2 files changed, 321 insertions(+), 201 deletions(-) diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs index 812a63ae7..e033e6487 100644 --- a/crates/engine/tests/batch_partial.rs +++ b/crates/engine/tests/batch_partial.rs @@ -13,22 +13,24 @@ //! unprocessed map is present as `{}`. A batch whose every entry was throttled //! fails with the throttle error per the API Reference; that case and the //! echo of `ExpressionAttributeNames` and `AttributesToGet` were not reached -//! in the samples. The order of the unprocessed lists, which the samples -//! returned in neither request nor sorted order, is not asserted. The storage -//! double throttles a chosen set of partition key values and records which -//! writes it applied. +//! in the samples. The samples returned the service's lists in neither +//! request nor sorted order; the engine keeps request order in `Responses` +//! and in the unprocessed lists, and the tests compare in that order. Each +//! throttle test runs for the three throttle errors a backend can report. +//! The storage double throttles a chosen set of partition key values and +//! records which writes it applied. #[path = "batch_partial/failing_store.rs"] mod failing_store; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; use serde_json::{Value, json}; use extenddb_auth::AuthCacheRegistry; -use extenddb_core::error::{DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE}; +use extenddb_core::error::{DynamoDbError, error_document}; use extenddb_core::limits::LimitsConfig; use extenddb_engine::{ BackupRuntime, DispatchResult, OperationContext, handle_batch_get_item, handle_batch_write_item, @@ -37,6 +39,12 @@ use extenddb_engine::{ use failing_store::*; fn ctx(store: Arc) -> OperationContext { + ctx_naming(store, &[]) +} + +/// A context whose authorization step resolved each request name (a table +/// ARN, say) to the key info of the catalog table it names. +fn ctx_naming(store: Arc, names: &[(&str, &str)]) -> OperationContext { OperationContext { storage: store, backup: Arc::new(BackupRuntime::new(1)), @@ -45,7 +53,10 @@ fn ctx(store: Arc) -> OperationContext { account_id: Arc::from(ACCOUNT), import_paths: Arc::from(Vec::>::new()), export_paths: Arc::from(Vec::>::new()), - authorized_key_info: extenddb_engine::AuthorizedKeyInfo::new(), + authorized_key_info: names + .iter() + .map(|(sent, table)| ((*sent).to_owned(), Some(key_info(table, false)))) + .collect(), auth_cache: AuthCacheRegistry::empty(), table_key_info_lookup: None, item_authorizer: None, @@ -56,12 +67,12 @@ fn keys_json(pks: &[&str]) -> Value { Value::Array(pks.iter().map(|p| json!({"pk": {"S": p}})).collect()) } -/// Partition key values of a JSON list of keys or items. -fn pks(list: &Value) -> BTreeSet { +/// Partition key values of a JSON list of keys or items, in list order. +fn pks(list: &Value) -> Vec<&str> { list.as_array() .expect("list") .iter() - .map(|k| k["pk"]["S"].as_str().expect("pk").to_owned()) + .map(|k| k["pk"]["S"].as_str().expect("pk")) .collect() } @@ -78,13 +89,22 @@ fn err_of(result: Result) -> DynamoDbError { } } -fn assert_throttle(err: &DynamoDbError, reason: &str) { - assert_eq!(err.status_code(), 400); - assert_eq!(err.error_type(), "ProvisionedThroughputExceededException"); - assert_eq!(err.message(), PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE); - let reasons = err.throttling_reasons().expect("reasons"); - assert_eq!(reasons.len(), 1); - assert_eq!(reasons[0].reason, reason); +/// The error is `expected`: the same status and the same body, so the same +/// class, message and reasons list. +fn assert_error(err: &DynamoDbError, expected: &DynamoDbError) { + assert_eq!(err.status_code(), expected.status_code(), "{err:?}"); + assert_eq!(error_document(err), error_document(expected)); +} + +/// Keys or puts of table T, each failing with a different throttle error, +/// rotated so that each error comes first once. +fn rotations(reason: &str) -> impl Iterator> { + let errors = throttle_errors(reason); + (0..errors.len()).map(move |first| { + let mut row = errors.to_vec(); + row.rotate_left(first); + row + }) } // --------------------------------------------------------------------------- @@ -95,67 +115,61 @@ fn assert_throttle(err: &DynamoDbError, reason: &str) { /// `UnprocessedKeys[
]` beside the request's `ConsistentRead` and /// `ProjectionExpression`, sets disjoint and complete, `ConsumedCapacity` for /// the served items only. `ExpressionAttributeNames` is echoed per the API -/// Reference; the sample sent none. +/// Reference; the sample sent none. Both lists keep request order. #[tokio::test] async fn batch_get_partial_echoes_request_fields_and_charges_served_only() { - let store = Arc::new( - FailingStore::throttling() - .with_items(&["k1", "k2", "k3", "k4", "k5"]) - .failing_on(&["k2", "k4"]), - ); - let body = json!({ - "RequestItems": { - "T": { - "Keys": keys_json(&["k1", "k2", "k3", "k4", "k5"]), - "ConsistentRead": true, - "ProjectionExpression": "#p", - "ExpressionAttributeNames": {"#p": "pk"} - } - }, - "ReturnConsumedCapacity": "TOTAL" - }); - - let result = handle_batch_get_item(body, &ctx(store)) - .await - .expect("partial success is a 200"); + for error in throttle_errors("TableReadProvisionedThroughputExceeded") { + let store = Arc::new( + FailingStore::new(error.clone()) + .with_items(&["k1", "k2", "k3", "k4", "k5"]) + .failing_on(&["k2", "k4"]), + ); + let body = json!({ + "RequestItems": { + "T": { + "Keys": keys_json(&["k1", "k2", "k3", "k4", "k5"]), + "ConsistentRead": true, + "ProjectionExpression": "#p", + "ExpressionAttributeNames": {"#p": "pk"} + } + }, + "ReturnConsumedCapacity": "TOTAL" + }); + + let result = handle_batch_get_item(body, &ctx(store)) + .await + .unwrap_or_else(|e| panic!("partial success is a 200, {error:?} gave {e:?}")); + + assert_eq!( + pks(&result.body["Responses"]["T"]), + ["k1", "k3", "k5"], + "{error:?}" + ); + for it in result.body["Responses"]["T"].as_array().expect("items") { + assert!(it.get("v").is_none(), "projection applied to served items"); + } - let served = pks(&result.body["Responses"]["T"]); - assert_eq!(served, ["k1", "k3", "k5"].map(str::to_owned).into()); - for it in result.body["Responses"]["T"].as_array().expect("items") { - assert!(it.get("v").is_none(), "projection applied to served items"); + let unprocessed = &result.body["UnprocessedKeys"]["T"]; + assert_eq!(pks(&unprocessed["Keys"]), ["k2", "k4"], "{error:?}"); + assert_eq!(unprocessed["ConsistentRead"], json!(true)); + assert_eq!(unprocessed["ProjectionExpression"], json!("#p")); + assert_eq!(unprocessed["ExpressionAttributeNames"], json!({"#p": "pk"})); + assert!(unprocessed.get("AttributesToGet").is_none()); + assert_eq!( + unprocessed.as_object().expect("map").len(), + 4, + "Keys plus the three request fields that were sent" + ); + + // Three consistent reads under 4 KB: 1 unit each, nothing for k2 and k4. + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 3.0}]) + ); + assert_eq!(result.metrics.read_capacity_units, 3.0); + assert_eq!(result.metrics.returned_item_count, 3); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); } - - let unprocessed = &result.body["UnprocessedKeys"]["T"]; - assert_eq!( - pks(&unprocessed["Keys"]), - ["k2", "k4"].map(str::to_owned).into() - ); - assert_eq!(unprocessed["ConsistentRead"], json!(true)); - assert_eq!(unprocessed["ProjectionExpression"], json!("#p")); - assert_eq!(unprocessed["ExpressionAttributeNames"], json!({"#p": "pk"})); - assert!(unprocessed.get("AttributesToGet").is_none()); - assert_eq!( - unprocessed.as_object().expect("map").len(), - 4, - "Keys plus the three request fields that were sent" - ); - - // Disjoint and complete. - let unread = pks(&unprocessed["Keys"]); - assert!(served.is_disjoint(&unread)); - let all: BTreeSet = served.union(&unread).cloned().collect(); - assert_eq!( - all, - ["k1", "k2", "k3", "k4", "k5"].map(str::to_owned).into() - ); - - // Three consistent reads under 4 KB: 1 unit each, nothing for k2 and k4. - assert_eq!( - result.body["ConsumedCapacity"], - json!([{"TableName": "T", "CapacityUnits": 3.0}]) - ); - assert_eq!(result.metrics.read_capacity_units, 3.0); - assert_eq!(result.metrics.returned_item_count, 3); } /// Two tables: one throttled on every key, the other fully served. The @@ -182,20 +196,14 @@ async fn batch_get_one_table_throttled_beside_a_served_table() { let unprocessed = result.body["UnprocessedKeys"].as_object().expect("map"); assert_eq!(unprocessed.len(), 1); - assert_eq!( - pks(&unprocessed["T"]["Keys"]), - ["t1", "t2"].map(str::to_owned).into() - ); + assert_eq!(pks(&unprocessed["T"]["Keys"]), ["t1", "t2"]); assert!(unprocessed["T"].get("ConsistentRead").is_none()); // The fully throttled table keeps an empty list under Responses (the // branch's own contract; the service's shape for this case is unmeasured). let responses = result.body["Responses"].as_object().expect("map"); assert_eq!(responses.len(), 2); assert_eq!(responses["T"], json!([])); - assert_eq!( - pks(&result.body["Responses"]["U"]), - ["u1", "u2"].map(str::to_owned).into() - ); + assert_eq!(pks(&result.body["Responses"]["U"]), ["u1", "u2"]); // Eventually consistent reads under 4 KB: 0.5 each; nothing for T. assert_eq!( result.body["ConsumedCapacity"], @@ -205,24 +213,66 @@ async fn batch_get_one_table_throttled_beside_a_served_table() { assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); } -/// Every key of every table throttled: the call fails with the throttle -/// error (API Reference; documented, not measured). +/// A request that names its table by ARN is answered under the ARN, and the +/// server is handed the catalog name, which its metrics carry. #[tokio::test] -async fn batch_get_every_key_throttled_fails_with_the_throttle_error() { +async fn batch_get_by_arn_answers_under_the_arn_and_counts_the_catalog_table() { + let arn = table_arn("T"); let store = Arc::new( FailingStore::throttling() - .with_items(&["t1", "u1"]) - .failing_on(&["t1", "u1"]), + .with_items(&["k1", "k2"]) + .failing_on(&["k2"]), ); - let body = json!({ - "RequestItems": { - "T": {"Keys": keys_json(&["t1"])}, - "U": {"Keys": keys_json(&["u1"])} - } - }); + let mut items = serde_json::Map::new(); + items.insert(arn.clone(), json!({"Keys": keys_json(&["k1", "k2"])})); + let body = json!({"RequestItems": items}); - let err = err_of(handle_batch_get_item(body, &ctx(store)).await); - assert_throttle(&err, "TableReadProvisionedThroughputExceeded"); + let result = handle_batch_get_item(body, &ctx_naming(store, &[(&arn, "T")])) + .await + .expect("one key served is a 200"); + assert_eq!(pks(&result.body["Responses"][&arn]), ["k1"]); + assert_eq!(pks(&result.body["UnprocessedKeys"][&arn]["Keys"]), ["k2"]); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 1)])); +} + +/// Every key of every table throttled: the call fails with the throttle +/// error (API Reference; documented, not measured). +#[tokio::test] +async fn batch_get_every_key_throttled_fails_with_the_throttle_error() { + for error in throttle_errors("TableReadProvisionedThroughputExceeded") { + let store = Arc::new( + FailingStore::new(error.clone()) + .with_items(&["t1", "u1"]) + .failing_on(&["t1", "u1"]), + ); + let body = json!({ + "RequestItems": { + "T": {"Keys": keys_json(&["t1"])}, + "U": {"Keys": keys_json(&["u1"])} + } + }); + + let err = err_of(handle_batch_get_item(body, &ctx(store)).await); + assert_error(&err, &error); + } +} + +/// Keys of one table throttled with different errors: the call fails with +/// the error of the first key in request order. +#[tokio::test] +async fn batch_get_every_key_throttled_fails_with_the_first_throttle_error() { + for errors in rotations("TableReadProvisionedThroughputExceeded") { + let store = Arc::new( + FailingStore::throttling() + .failing_with("k1", errors[0].clone()) + .failing_with("k2", errors[1].clone()) + .failing_with("k3", errors[2].clone()), + ); + let body = json!({"RequestItems": {"T": {"Keys": keys_json(&["k1", "k2", "k3"])}}}); + + let err = err_of(handle_batch_get_item(body, &ctx(store)).await); + assert_error(&err, &errors[0]); + } } /// The boundary of the all-throttled rule: with one key served and every @@ -242,13 +292,10 @@ async fn batch_get_one_served_key_is_a_partial_success() { let result = handle_batch_get_item(body, &ctx(store)) .await .expect("one key served is a 200"); - assert_eq!( - pks(&result.body["Responses"]["T"]), - ["k3".to_owned()].into() - ); + assert_eq!(pks(&result.body["Responses"]["T"]), ["k3"]); assert_eq!( pks(&result.body["UnprocessedKeys"]["T"]["Keys"]), - ["k1", "k2"].map(str::to_owned).into() + ["k1", "k2"] ); assert_eq!( result.body["ConsumedCapacity"], @@ -276,7 +323,7 @@ async fn batch_get_partial_echoes_attributes_to_get() { .expect("map"); assert_eq!(t.len(), 2, "{t:?}"); assert_eq!(t["AttributesToGet"], json!(["pk"])); - assert_eq!(pks(&t["Keys"]), ["k2".to_owned()].into()); + assert_eq!(pks(&t["Keys"]), ["k2"]); } /// Capacity for a served item follows its size: a consistent read of an item @@ -320,10 +367,7 @@ async fn batch_get_nothing_throttled_serializes_empty_unprocessed_keys() { serialized.contains(r#""UnprocessedKeys":{}"#), "body: {serialized}" ); - assert_eq!( - pks(&result.body["Responses"]["T"]), - ["k1"].map(str::to_owned).into() - ); + assert_eq!(pks(&result.body["Responses"]["T"]), ["k1"]); } /// A storage `Service` error that is not a throttle still fails the request. @@ -350,91 +394,134 @@ async fn batch_get_non_throttle_service_error_fails_the_request() { // --------------------------------------------------------------------------- /// Puts and deletes, some throttled: 200, the throttled entries echoed as -/// sent under `UnprocessedItems[
]`, `ConsumedCapacity` and -/// `ItemCollectionMetrics` for the applied entries only, and the backend saw -/// exactly the applied writes. +/// sent under `UnprocessedItems[
]` in request order, `ConsumedCapacity` +/// and `ItemCollectionMetrics` for the applied entries only, and the backend +/// saw exactly the applied writes. #[tokio::test] async fn batch_write_partial_echoes_entries_and_charges_applied_only() { - let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p2", "d2"])); - let body = json!({ - "RequestItems": { - "T": [ - {"PutRequest": {"Item": {"pk": {"S": "p1"}, "v": {"N": "1"}}}}, + for error in throttle_errors("TableWriteProvisionedThroughputExceeded") { + let store = Arc::new(FailingStore::new(error.clone()).failing_on(&["p2", "d2"])); + let body = json!({ + "RequestItems": { + "T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}, "v": {"N": "1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}, "v": {"N": "2"}}}}, + {"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}, + {"DeleteRequest": {"Key": {"pk": {"S": "d2"}}}} + ] + }, + "ReturnConsumedCapacity": "TOTAL", + "ReturnItemCollectionMetrics": "SIZE" + }); + + let result = handle_batch_write_item(body, &ctx(Arc::clone(&store))) + .await + .unwrap_or_else(|e| panic!("partial success is a 200, {error:?} gave {e:?}")); + + assert_eq!( + result.body["UnprocessedItems"], + json!({"T": [ {"PutRequest": {"Item": {"pk": {"S": "p2"}, "v": {"N": "2"}}}}, - {"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}, {"DeleteRequest": {"Key": {"pk": {"S": "d2"}}}} + ]}), + "{error:?}" + ); + + // Two applied writes under 1 KB: 1 unit each. + assert_eq!( + result.body["ConsumedCapacity"], + json!([{"TableName": "T", "CapacityUnits": 2.0}]) + ); + assert_eq!(result.metrics.write_capacity_units, 2.0); + + let icm: Vec<&str> = result.body["ItemCollectionMetrics"]["T"] + .as_array() + .expect("metrics list") + .iter() + .map(|m| m["ItemCollectionKey"]["pk"]["S"].as_str().expect("pk")) + .collect(); + assert_eq!(icm, ["p1", "d1"]); + + assert_eq!( + store.applied(), + vec![ + Applied::Put("p1".to_owned()), + Applied::Delete("d1".to_owned()) ] - }, - "ReturnConsumedCapacity": "TOTAL", - "ReturnItemCollectionMetrics": "SIZE" - }); + ); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); + } +} - let result = handle_batch_write_item(body, &ctx(Arc::clone(&store))) - .await - .expect("partial success is a 200"); - - let unprocessed = result.body["UnprocessedItems"]["T"] - .as_array() - .expect("list"); - assert_eq!(unprocessed.len(), 2); - assert!(unprocessed.contains(&json!({ - "PutRequest": {"Item": {"pk": {"S": "p2"}, "v": {"N": "2"}}} - }))); - assert!(unprocessed.contains(&json!({ - "DeleteRequest": {"Key": {"pk": {"S": "d2"}}} - }))); - assert_eq!( - result.body["UnprocessedItems"] - .as_object() - .expect("map") - .len(), - 1 - ); +/// Every entry throttled: the call fails with the throttle error and nothing +/// was applied. +#[tokio::test] +async fn batch_write_every_entry_throttled_fails_with_the_throttle_error() { + for error in throttle_errors("TableWriteProvisionedThroughputExceeded") { + let store = Arc::new(FailingStore::new(error.clone()).failing_on(&["p1", "d1"])); + let body = json!({ + "RequestItems": { + "T": [{"PutRequest": {"Item": {"pk": {"S": "p1"}}}}], + "U": [{"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}] + } + }); - // Two applied writes under 1 KB: 1 unit each. - assert_eq!( - result.body["ConsumedCapacity"], - json!([{"TableName": "T", "CapacityUnits": 2.0}]) - ); - assert_eq!(result.metrics.write_capacity_units, 2.0); + let err = err_of(handle_batch_write_item(body, &ctx(Arc::clone(&store))).await); + assert_error(&err, &error); + assert!(store.applied().is_empty()); + } +} - let icm: BTreeSet = result.body["ItemCollectionMetrics"]["T"] - .as_array() - .expect("metrics list") - .iter() - .map(|m| { - m["ItemCollectionKey"]["pk"]["S"] - .as_str() - .expect("pk") - .to_owned() - }) - .collect(); - assert_eq!(icm, ["p1", "d1"].map(str::to_owned).into()); +/// Requests of one table throttled with different errors: the call fails +/// with the error of the first request in request order. +#[tokio::test] +async fn batch_write_every_entry_throttled_fails_with_the_first_throttle_error() { + for errors in rotations("TableWriteProvisionedThroughputExceeded") { + let store = Arc::new( + FailingStore::throttling_writes() + .failing_with("p1", errors[0].clone()) + .failing_with("p2", errors[1].clone()) + .failing_with("p3", errors[2].clone()), + ); + let body = json!({ + "RequestItems": { + "T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p3"}}}} + ] + } + }); - assert_eq!( - store.applied(), - vec![ - Applied::Put("p1".to_owned()), - Applied::Delete("d1".to_owned()) - ] - ); + let err = err_of(handle_batch_write_item(body, &ctx(store)).await); + assert_error(&err, &errors[0]); + } } -/// Every entry throttled: the call fails with the throttle error and nothing -/// was applied. +/// A request that names its table by ARN is answered under the ARN, and the +/// server is handed the catalog name, which its metrics carry. #[tokio::test] -async fn batch_write_every_entry_throttled_fails_with_the_throttle_error() { - let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p1", "d1"])); - let body = json!({ - "RequestItems": { - "T": [{"PutRequest": {"Item": {"pk": {"S": "p1"}}}}], - "U": [{"DeleteRequest": {"Key": {"pk": {"S": "d1"}}}}] - } - }); +async fn batch_write_by_arn_answers_under_the_arn_and_counts_the_catalog_table() { + let arn = table_arn("T"); + let store = Arc::new(FailingStore::throttling_writes().failing_on(&["p2"])); + let mut items = serde_json::Map::new(); + items.insert( + arn.clone(), + json!([ + {"PutRequest": {"Item": {"pk": {"S": "p1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}}}} + ]), + ); + let body = json!({"RequestItems": items}); - let err = err_of(handle_batch_write_item(body, &ctx(Arc::clone(&store))).await); - assert_throttle(&err, "TableWriteProvisionedThroughputExceeded"); - assert!(store.applied().is_empty()); + let result = handle_batch_write_item(body, &ctx_naming(store, &[(&arn, "T")])) + .await + .expect("one entry applied is a 200"); + assert_eq!( + result.body["UnprocessedItems"], + json!({arn: [{"PutRequest": {"Item": {"pk": {"S": "p2"}}}}]}) + ); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 1)])); } /// The boundary of the all-throttled rule on writes: one entry applied and @@ -457,10 +544,13 @@ async fn batch_write_one_applied_entry_is_a_partial_success() { .await .expect("one entry applied is a 200"); assert_eq!(store.applied(), vec![Applied::Put("p3".to_owned())]); - let unprocessed = result.body["UnprocessedItems"]["T"] - .as_array() - .expect("list"); - assert_eq!(unprocessed.len(), 2); + assert_eq!( + result.body["UnprocessedItems"], + json!({"T": [ + {"PutRequest": {"Item": {"pk": {"S": "p1"}}}}, + {"PutRequest": {"Item": {"pk": {"S": "p2"}}}} + ]}) + ); assert_eq!( result.body["ConsumedCapacity"], json!([{"TableName": "T", "CapacityUnits": 1.0}]) diff --git a/crates/engine/tests/batch_partial/failing_store.rs b/crates/engine/tests/batch_partial/failing_store.rs index cc49f6e54..ad45d4b77 100644 --- a/crates/engine/tests/batch_partial/failing_store.rs +++ b/crates/engine/tests/batch_partial/failing_store.rs @@ -4,13 +4,14 @@ //! for a chosen set of partition key values and succeed for every other key, //! recording the writes it applied. -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap}; use std::sync::Mutex; use std::time::Duration; use extenddb_core::backup_format::BackupArn; use extenddb_core::error::{ - DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, ThrottlingReason, + DynamoDbError, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, REQUEST_LIMIT_EXCEEDED_MESSAGE, + THROTTLING_EXCEPTION_MESSAGE, ThrottlingReason, }; use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition, UpdateAction}; use extenddb_core::types::{ @@ -53,9 +54,9 @@ pub struct FailingStore { tables: HashMap, /// Items served by `get_item`, by partition key value. items: BTreeMap, - /// Partition key values whose data calls fail with `error`. - failing: HashSet, - /// The error returned for a failing key. + /// Partition key values whose data calls fail, with the error each gets. + failing: HashMap, + /// The error `failing_on` gives a key. error: DynamoDbError, /// Writes that reached the backend, in call order. applied: Mutex>, @@ -66,7 +67,7 @@ impl FailingStore { Self { tables: HashMap::from([("T".to_owned(), true), ("U".to_owned(), false)]), items: BTreeMap::new(), - failing: HashSet::new(), + failing: HashMap::new(), error, applied: Mutex::new(Vec::new()), } @@ -94,12 +95,23 @@ impl FailingStore { } pub fn failing_on(mut self, pks: &[&str]) -> Self { - self.failing = pks.iter().map(|p| (*p).to_owned()).collect(); + for pk in pks { + self.failing.insert((*pk).to_owned(), self.error.clone()); + } + self + } + + /// The data calls for `pk` fail with `error`. + pub fn failing_with(mut self, pk: &str, error: DynamoDbError) -> Self { + self.failing.insert(pk.to_owned(), error); self } - fn fails(&self, key_or_item: &Item) -> bool { - self.failing.contains(&pk_of(key_or_item)) + /// The error the data calls for this key or item fail with, if any. + fn failure(&self, key_or_item: &Item) -> Option { + self.failing + .get(&pk_of(key_or_item)) + .map(|e| StorageError::Service(e.clone())) } pub fn applied(&self) -> Vec { @@ -108,13 +120,31 @@ impl FailingStore { } pub fn throttle_error(reason: &str) -> DynamoDbError { - DynamoDbError::provisioned_throughput_exceeded( - PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + throttle_errors(reason)[0].clone() +} + +pub fn table_arn(table: &str) -> String { + format!("arn:aws:dynamodb:{REGION}:{ACCOUNT}:table/{table}") +} + +/// The three throttle errors a backend can report, each with its service +/// message and one reason naming table T: the provisioned capacity error, +/// the on-demand `ThrottlingException` and the account `RequestLimitExceeded`. +pub fn throttle_errors(reason: &str) -> [DynamoDbError; 3] { + let reasons = || { vec![ThrottlingReason { reason: reason.to_owned(), - resource: format!("arn:aws:dynamodb:{REGION}:{ACCOUNT}:table/T"), - }], - ) + resource: table_arn("T"), + }] + }; + [ + DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + reasons(), + ), + DynamoDbError::throttling(THROTTLING_EXCEPTION_MESSAGE, reasons()), + DynamoDbError::request_limit_exceeded(REQUEST_LIMIT_EXCEEDED_MESSAGE, reasons()), + ] } pub fn pk_of(item: &Item) -> String { @@ -241,8 +271,8 @@ impl DataEngine for FailingStore { _maps: &ExpressionMaps, _stream: Option<&StreamCapture>, ) -> BoxedFuture<'_, Result, StorageError>> { - let result = if self.fails(&item) { - Err(StorageError::Service(self.error.clone())) + let result = if let Some(e) = self.failure(&item) { + Err(e) } else { self.applied .lock() @@ -258,8 +288,8 @@ impl DataEngine for FailingStore { _key_info: &TableKeyInfo, key: &Item, ) -> BoxedFuture<'_, Result, StorageError>> { - let result = if self.fails(key) { - Err(StorageError::Service(self.error.clone())) + let result = if let Some(e) = self.failure(key) { + Err(e) } else { Ok(self.items.get(&pk_of(key)).cloned()) }; @@ -275,8 +305,8 @@ impl DataEngine for FailingStore { _maps: &ExpressionMaps, _stream: Option<&StreamCapture>, ) -> BoxedFuture<'_, Result, StorageError>> { - let result = if self.fails(key) { - Err(StorageError::Service(self.error.clone())) + let result = if let Some(e) = self.failure(key) { + Err(e) } else { self.applied .lock() From 2a0676bd287cafbefc89a84f21a0c7b8a7c23d67 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:47 +0000 Subject: [PATCH 27/33] test(server): drive a backend-throttled batch through handle_request and read the metrics No server test reached the call that records the throttle metrics of a batch a backend served partially. Every handler test ran on SQLite, which never reports a throttle, so the call recorded nothing in any of them. The new test builds the handler state with the engine tests' storage double in place of the SQLite engine for the table and item calls. It sends a partly throttled BatchGetItem, a partly throttled BatchWriteItem and an all-throttled BatchGetItem. Then it reads ReadThrottleEvents, WriteThrottleEvents, ThrottledRequests and UserErrors from the collector. The double is included by path, as the bin crate includes the PostgreSQL catalog check support. --- .../server/src/handler/throttle_wire_tests.rs | 85 ++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 4c90d9a9e..459241bdc 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -3,6 +3,8 @@ //! The server's own throttle refusal, driven through `handle_request` against //! an in-memory engine: the error class, the reasons field and its casing, the //! reason text and the table ARN the body carries for each bucket that refuses. +//! Also the metrics `handle_request` records for a batch a backend throttled, +//! against the engine tests' storage double. use std::sync::Arc; @@ -55,6 +57,15 @@ fn cache_cfg(name: &'static str) -> extenddb_cache::SwrCacheConfig { /// `dev_mode` on. Returns the state and the account id the stub answers with, /// so the expected ARN can be formed. async fn build_state() -> (Arc, String) { + build_state_on(None).await +} + +/// `build_state` with `storage`, when given, in place of the SQLite engine +/// for the table and item calls. The catalog and the authorization stores +/// stay on SQLite. +async fn build_state_on( + storage: Option>, +) -> (Arc, String) { let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); let config = extenddb_storage_sqlite::SqliteConfig { path: ":memory:".to_owned(), @@ -84,8 +95,9 @@ async fn build_state() -> (Arc, String) { session_data: cache_cfg("session_data"), }, )); + let engine = storage.unwrap_or_else(|| components.engine.clone()); let table_key_info_cache = Arc::new(crate::CachedTableKeyInfoStore::pass_through( - components.engine.clone(), + engine.clone(), cache_cfg("table_key_info"), )); let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); @@ -97,7 +109,7 @@ async fn build_state() -> (Arc, String) { )); let state = Arc::new(AppState { - storage: components.engine, + storage: engine, backup_runtime: Arc::new(extenddb_engine::BackupRuntime::new(1)), auth: Arc::new(StubAuth { account_id: account_id.clone(), @@ -477,3 +489,72 @@ async fn requests_with_capacity_are_served() { assert_eq!(status, 200, "{body}"); assert_eq!(body["Item"]["pk"], json!({"S": "k"})); } + +#[path = "../../../engine/tests/batch_partial/failing_store.rs"] +#[allow(dead_code)] +mod failing_store; + +/// The metrics of a batch a backend throttled, read from the collector after +/// `handle_request`. On a 200, one read or write throttle event per throttled +/// entry, one data point per table, and no `ThrottledRequests`. When every +/// entry was throttled, `ThrottledRequests` and no `UserErrors`. Each row: the +/// operation, the request, the status, and the (sum, data points) expected +/// for each metric. +#[tokio::test] +async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { + use extenddb_core::metrics::{MetricName, MetricsQuery, TimeWindow}; + let puts = |pks: &[&str]| -> Value { + pks.iter() + .map(|pk| json!({"PutRequest": {"Item": {"pk": {"S": pk}}}})) + .collect() + }; + let keys = |pks: &[&str]| -> Value { pks.iter().map(|pk| json!({"pk": {"S": pk}})).collect() }; + let rows = [ + ( + "BatchGetItem", + json!({"RequestItems": {"T": {"Keys": keys(&["k1", "k2", "k3"])}}}), + 200, + [(2.0, 1), (0.0, 0), (0.0, 0), (0.0, 0)], + ), + ( + "BatchWriteItem", + json!({"RequestItems": {"T": puts(&["p1", "k2"])}}), + 200, + [(0.0, 0), (1.0, 1), (0.0, 0), (0.0, 0)], + ), + ( + "BatchGetItem", + json!({"RequestItems": {"T": {"Keys": keys(&["k2", "k3"])}}}), + 400, + [(0.0, 0), (0.0, 0), (1.0, 1), (0.0, 0)], + ), + ]; + for (operation, request, status, expected) in rows { + let store = failing_store::FailingStore::throttling() + .with_items(&["k1", "k2", "k3"]) + .failing_on(&["k2", "k3"]); + let (state, account_id) = build_state_on(Some(Arc::new(store))).await; + let (got, body) = call(&state, operation, request).await; + assert_eq!(got, status, "{operation}: {body}"); + for (metric, want) in [ + MetricName::ReadThrottleEvents, + MetricName::WriteThrottleEvents, + MetricName::ThrottledRequests, + MetricName::UserErrors, + ] + .into_iter() + .zip(expected) + { + let points = state.metrics.query(&MetricsQuery { + account_id: Some(account_id.clone()), + metric: Some(metric), + window: Some(TimeWindow::AllTime), + ..Default::default() + }); + let sum_and_count = points + .iter() + .fold((0.0, 0), |(sum, n), p| (sum + p.sum, n + p.count)); + assert_eq!(sum_and_count, want, "{operation} {status}: {metric:?}"); + } + } +} From c9fae6adbdb27b3747952ccdb2990978b6428b97 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:18:08 +0000 Subject: [PATCH 28/33] docs: state the backend rule for a throttle on a batch in the storage contract The storage design said that every engine mapping site returns a Service error to the client unchanged. On BatchGetItem and BatchWriteItem, the engine holds back a throttle error for one entry. The entry goes to UnprocessedKeys or UnprocessedItems and the client sends it again. A backend that reported a throttle for a write that had committed would have the write applied twice, with a second stream record. Only a code comment on is_deferrable said so. The Error Types section of the storage design now states the hold-back and the rule it puts on a backend. A backend reports a throttle for a write only when the write did not commit, and reports a write of unknown commit outcome as Internal. The backend author manual, the security model and ADR-0028 name the hold-back and point at that section. --- docs/adr/0028-backend-classified-client-error.md | 6 +++++- docs/design/04-component-storage.md | 12 ++++++++++++ docs/manuals/10-security-model.md | 2 +- docs/manuals/12-extending-extenddb-storage.md | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/adr/0028-backend-classified-client-error.md b/docs/adr/0028-backend-classified-client-error.md index 2aa9a1c65..9df706781 100644 --- a/docs/adr/0028-backend-classified-client-error.md +++ b/docs/adr/0028-backend-classified-client-error.md @@ -57,10 +57,14 @@ 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 +Three answers outside these functions depend on the error's class. In a `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`). +`BatchGetItem` and `BatchWriteItem` hold back a throttle error for one entry +and return the entry as unprocessed for the client to send again; the storage +design (`docs/design/04-component-storage.md`, Error Types) states the rule +this puts on a backend's writes. 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/design/04-component-storage.md b/docs/design/04-component-storage.md index 0bea19f5c..af7cac104 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -362,6 +362,18 @@ must be service-shaped text with no driver output, host names, connection strings or credentials, and a failure the backend cannot classify stays `Internal`. +`BatchGetItem` and `BatchWriteItem` do not return a throttle error +(`ProvisionedThroughputExceededException`, `ThrottlingException` or +`RequestLimitExceeded` inside `Service`) for one entry to the client at once. +The engine puts that entry in `UnprocessedKeys` or `UnprocessedItems`, goes on +with the other entries, and answers the first throttle error only when every +entry of the batch was throttled. The client sends the unprocessed entries +again. So a backend reports a throttle for a write only when the write did not +commit, and reports a write whose commit outcome it does not know as +`Internal`, which fails the batch with 500. If a backend reported a throttle +for a write that had committed, the client's replay would apply the write a +second time and write a second stream record. + ## 5. PostgreSQL Backend Implementation ### 5.1 Schema Design diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index af6b46b49..6b10fa9cf 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`, 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 +- 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 (on `BatchGetItem` and `BatchWriteItem` a throttle error for one entry is held back and the entry returned as unprocessed, as the [storage design](../design/04-component-storage.md#error-types) states). 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 82ec79506..d1d23f38a 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`, 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`. +- **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). On `BatchGetItem` and `BatchWriteItem` the engine holds back a throttle error for one entry and returns the entry as unprocessed for the client to send again; the [storage design](../design/04-component-storage.md#error-types) states the rule this puts on a backend's writes. 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 5e16c28a5421d00c2838017681facb90f82ee05e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:22:32 +0000 Subject: [PATCH 29/33] test(server): name the row type of the partial batch metrics test Clippy's type_complexity lint refused the inline tuple type of the rows. --- crates/server/src/throttle_helpers.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 5e6e7f28c..634130bed 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -506,7 +506,8 @@ mod partial_batch_throttle_tests { #[test] fn a_partial_batch_records_one_throttle_event_per_throttled_entry() { type Events<'a> = &'a [(&'a str, (f64, u64))]; - let rows: [(&str, &[(&str, u32)], Events, Events); 4] = [ + type Row<'a> = (&'a str, &'a [(&'a str, u32)], Events<'a>, Events<'a>); + let rows: [Row; 4] = [ ( "BatchGetItem", &[("T", 3), ("U", 1)], From 09233710505a1001a90cd389c198de343c7f7fd1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:10:20 +0000 Subject: [PATCH 30/33] fix(server): record the throttle events of a batch whose every entry a backend throttled CloudWatch's metrics page for DynamoDB counts each throttled entry of a BatchGetItem or BatchWriteItem as a ReadThrottleEvents or WriteThrottleEvents event. A batch in which every entry was throttled adds one ThrottledRequests, and its entries still count as events. The server recorded the ThrottledRequests of that batch and no events. The engine answers that batch with the throttle error alone, so the counts did not reach the server. batch_entry_counts counts the entries of each table from the request before the dispatch, by the table name an ARN names. When a batch answers a throttle error, the handler records those counts with record_partial_batch_throttle, one data point per table, as it does on a 200. authz_resource::table_name_only reduces the ARN, and is now pub(crate). A throttle that the backend reports on the catalog read also gives the batch's throttle error, so it also counts every entry. The service has no such failure. --- crates/server/src/authz_resource.rs | 2 +- crates/server/src/handler.rs | 19 +++- .../server/src/handler/throttle_wire_tests.rs | 8 +- crates/server/src/throttle_helpers.rs | 87 +++++++++++++++++-- 4 files changed, 102 insertions(+), 14 deletions(-) diff --git a/crates/server/src/authz_resource.rs b/crates/server/src/authz_resource.rs index 0bb62bf82..edbdb551c 100644 --- a/crates/server/src/authz_resource.rs +++ b/crates/server/src/authz_resource.rs @@ -822,7 +822,7 @@ fn restore_target_actions(input: &Value, region: &str, account_id: &str) -> Vec< } /// The bare table name from a value that may be a name or a table ARN. -fn table_name_only(value: &str) -> String { +pub(crate) fn table_name_only(value: &str) -> String { if value.starts_with("arn:") && let Some(rid) = parse_resource_identity(value) { diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index a92019d2b..1ec5be2ab 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -21,8 +21,9 @@ use crate::request_helpers::{ }; use crate::response::{error_response, record_error_metrics, success_response}; use crate::throttle_helpers::{ - classify_data_operation, extract_partition_value, record_partial_batch_throttle, - table_description_to_throughput, throttle_error, update_throttle_buckets, + batch_entry_counts, classify_data_operation, extract_partition_value, + record_partial_batch_throttle, table_description_to_throughput, throttle_error, + update_throttle_buckets, }; /// Main Virtual `DynamoDB` request handler. @@ -281,6 +282,10 @@ pub(crate) async fn handle_request( let throttle_us = throttle_start.elapsed().as_micros() as f64; // --- Dispatch segment --- + // The entries of a batch, for the throttle events of a batch whose every + // entry a backend throttled: the engine answers that one with the error + // alone (`input` moves into the dispatch). + let batch_entries = batch_entry_counts(&operation, &input); let dispatch_start = std::time::Instant::now(); let dispatch_result = extenddb_engine::dispatch(&operation, input, &ctx, &state.server_addr).await; @@ -394,6 +399,16 @@ pub(crate) async fn handle_request( metric_table.as_deref(), &operation, ); + // A throttle error from a batch is the engine's answer to a batch + // whose every entry a backend throttled: each entry is a throttle + // event, as on a 200. A throttle the backend reports on the catalog + // read also comes out as the batch's throttle error and counts every + // entry; the service has no such failure. + if e.is_throttle() + && let Some(entries) = &batch_entries + { + record_partial_batch_throttle(&state.metrics, &ctx.account_id, &operation, entries); + } error_response(&e, &request_id) } }; diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 459241bdc..094f43350 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -497,9 +497,9 @@ mod failing_store; /// The metrics of a batch a backend throttled, read from the collector after /// `handle_request`. On a 200, one read or write throttle event per throttled /// entry, one data point per table, and no `ThrottledRequests`. When every -/// entry was throttled, `ThrottledRequests` and no `UserErrors`. Each row: the -/// operation, the request, the status, and the (sum, data points) expected -/// for each metric. +/// entry was throttled, the same events, `ThrottledRequests` and no +/// `UserErrors`. Each row: the operation, the request, the status, and the +/// (sum, data points) expected for each metric. #[tokio::test] async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { use extenddb_core::metrics::{MetricName, MetricsQuery, TimeWindow}; @@ -526,7 +526,7 @@ async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { "BatchGetItem", json!({"RequestItems": {"T": {"Keys": keys(&["k2", "k3"])}}}), 400, - [(0.0, 0), (0.0, 0), (1.0, 1), (0.0, 0)], + [(2.0, 1), (0.0, 0), (1.0, 1), (0.0, 0)], ), ]; for (operation, request, status, expected) in rows { diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 634130bed..362c8ef22 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -115,17 +115,19 @@ fn extract_throughput_from_response( )) } -/// Record the throttle events of a batch response a backend served partially. +/// Record the throttle events of a batch whose entries a backend throttled. /// /// A backend throttle that leaves requests or keys unprocessed returns a 200 /// that the server's own bucket never saw. CloudWatch counts each throttled /// entry of a batch as a read or write throttle event, and counts the batch /// in `ThrottledRequests` only when every entry was throttled, which answers -/// the throttle error (`record_error_metrics` counts that one). So this -/// records one data point per table the engine reports -/// (`DispatchMetrics::throttled_tables`), with the number of the table's -/// throttled entries as its value, and the account and the table as the -/// dimensions the bucket's own records carry. The response's +/// the throttle error (`record_error_metrics` counts that one, and the +/// handler records the entry counts from the request for that one). So this +/// records one data point per table in `throttled_tables` +/// (`DispatchMetrics::throttled_tables` on a 200, `batch_entry_counts` for +/// the error), with the number of the table's throttled entries as its value, +/// and the account and the table as the dimensions the bucket's own records +/// carry. The response's /// `UnprocessedItems` is no throttle count: it also holds requests deferred /// for a transient, conflict or connection failure. pub(crate) fn record_partial_batch_throttle( @@ -152,6 +154,31 @@ pub(crate) fn record_partial_batch_throttle( } } +/// The entries of a `BatchGetItem` or `BatchWriteItem` request per table, by +/// the name the metrics carry (a table ARN reduced to its table name by +/// `authz_resource::table_name_only`), and `None` for another operation or a +/// request the engine will refuse. A batch whose every entry a +/// backend throttled answers the throttle error alone, so its throttle events +/// are counted from the request; the engine looked every table up before it +/// could throttle, so each name here is a catalog name. +pub(crate) fn batch_entry_counts( + operation: &str, + input: &Value, +) -> Option> { + let mut counts = std::collections::BTreeMap::new(); + for (sent, entry) in input.get("RequestItems")?.as_object()? { + let entries = match operation { + "BatchGetItem" => entry.get("Keys")?.as_array()?.len(), + "BatchWriteItem" => entry.as_array()?.len(), + _ => return None, + }; + *counts + .entry(crate::authz_resource::table_name_only(sent)) + .or_default() += u32::try_from(entries).ok()?; + } + Some(counts) +} + /// Extract the partition key value from a request body for per-partition throttling. /// /// For item-level operations (`GetItem`, `PutItem`, `DeleteItem`, `UpdateItem`), @@ -480,7 +507,9 @@ mod partial_batch_throttle_tests { use extenddb_core::metrics::{MetricName, MetricsCollector, MetricsQuery, TimeWindow}; - use super::record_partial_batch_throttle; + use serde_json::json; + + use super::{batch_entry_counts, record_partial_batch_throttle}; const ACCOUNT: &str = "111111111111"; @@ -549,4 +578,48 @@ mod partial_batch_throttle_tests { } } } + + /// The entries of each table of a batch request, by the table name an ARN + /// names, and `None` for another operation. Each row: the operation, the + /// request and the expected counts. + #[test] + fn batch_entry_counts_counts_the_entries_of_each_table() { + let arn = "arn:aws:dynamodb:us-east-1:111111111111:table/Orders"; + let key = json!({"pk": {"S": "k"}}); + let put = json!({"PutRequest": {"Item": {"pk": {"S": "k"}}}}); + let rows = [ + ( + "BatchGetItem", + json!({"RequestItems": {arn: {"Keys": [key, key, key]}}}), + Some(vec![("Orders", 3)]), + ), + ( + "BatchGetItem", + json!({"RequestItems": { + "T": {"Keys": [key, key], "ConsistentRead": true}, + "U": {"Keys": [key]} + }}), + Some(vec![("T", 2), ("U", 1)]), + ), + ( + "BatchWriteItem", + json!({"RequestItems": {"T": [put, put], arn: [put]}}), + Some(vec![("Orders", 1), ("T", 2)]), + ), + ( + "GetItem", + json!({"RequestItems": {"T": {"Keys": [key]}}}), + None, + ), + ]; + for (operation, input, expected) in rows { + let expected: Option> = + expected.map(|rows| rows.into_iter().map(|(t, n)| (t.to_owned(), n)).collect()); + assert_eq!( + batch_entry_counts(operation, &input), + expected, + "{operation} {input}" + ); + } + } } From 17dab89494e0b2ac62cbe89cdbd552d723d02cee Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:14:53 +0000 Subject: [PATCH 31/33] refactor(engine): count the throttled entries of a batch only in the per-table map Both batch handlers counted the throttled entries twice: in throttled_count and in the per-table map throttled_tables, incremented in the same arm. The all-throttled checks now compare the sum of the map's values with the number of keys or of requests not applied, and throttled_count is gone. --- crates/engine/src/batch_get_item.rs | 4 +--- crates/engine/src/batch_write_item.rs | 6 ++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index d7b38f2e2..9abad7d34 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -178,7 +178,6 @@ pub async fn handle_batch_get_item( // when every key was throttled the call fails with the throttle error // instead (API Reference; documented, not reached in the sample). let mut unprocessed_keys: HashMap = HashMap::new(); - let mut throttled_count: usize = 0; let mut first_throttle: Option = None; let mut throttled_tables: BTreeMap = BTreeMap::new(); let mut total_rcu: f64 = 0.0; @@ -207,7 +206,6 @@ pub async fn handle_batch_get_item( // error still fails the request. Err(StorageError::Service(e)) if e.is_throttle() => { table_unprocessed.push(key.clone()); - throttled_count += 1; *throttled_tables .entry(key_info.table_name.clone()) .or_default() += 1; @@ -263,7 +261,7 @@ pub async fn handle_batch_get_item( // key was throttled beside a served table keeps an empty `Responses` list; // unmeasured as well. if let Some(e) = first_throttle - && throttled_count == total_keys + && throttled_tables.values().sum::() as usize == total_keys { return Err(e); } diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 419d3b372..d21877853 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -213,8 +213,7 @@ async fn write_batch( // The error of the last request that was not applied, for the warning // logged once per batch below. let mut last_error = String::new(); - // How many requests the backend throttled, and the first throttle error. - let mut throttled_count: usize = 0; + // The first throttle error; `throttled_tables` counts the throttled requests. let mut first_throttle: Option = None; let mut throttled_tables: BTreeMap = BTreeMap::new(); @@ -297,7 +296,6 @@ async fn write_batch( // `is_deferrable` takes a `Service` error only when it is // a throttle. if let StorageError::Service(e) = e { - throttled_count += 1; if first_throttle.is_none() { first_throttle = Some(e); } @@ -345,7 +343,7 @@ async fn write_batch( if !unprocessed.is_empty() { let not_applied: usize = unprocessed.values().map(Vec::len).sum(); - let all_throttled = throttled_count == not_applied; + let all_throttled = throttled_tables.values().sum::() as usize == not_applied; let outcome = if applied == 0 && all_throttled { "every request was throttled and the batch answers the first throttle error" } else if applied == 0 { From cf240c3543be934ee3332aa0bd80dfc6b3fb030d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:16:24 +0000 Subject: [PATCH 32/33] test(server): read the throttle metrics of both batch tests through one helper The recorder's row table and the handler test of the batch throttle metrics each read a metric's sum and data point count from the collector. Each test had its own copy of that query. points in throttle_helpers.rs now takes the account, and both tests call it. --- .../server/src/handler/throttle_wire_tests.rs | 14 ++---- crates/server/src/throttle_helpers.rs | 44 +++++++++++-------- 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 094f43350..2fdaf598b 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -502,7 +502,7 @@ mod failing_store; /// (sum, data points) expected for each metric. #[tokio::test] async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { - use extenddb_core::metrics::{MetricName, MetricsQuery, TimeWindow}; + use extenddb_core::metrics::MetricName; let puts = |pks: &[&str]| -> Value { pks.iter() .map(|pk| json!({"PutRequest": {"Item": {"pk": {"S": pk}}}})) @@ -545,16 +545,8 @@ async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { .into_iter() .zip(expected) { - let points = state.metrics.query(&MetricsQuery { - account_id: Some(account_id.clone()), - metric: Some(metric), - window: Some(TimeWindow::AllTime), - ..Default::default() - }); - let sum_and_count = points - .iter() - .fold((0.0, 0), |(sum, n), p| (sum + p.sum, n + p.count)); - assert_eq!(sum_and_count, want, "{operation} {status}: {metric:?}"); + let got = crate::throttle_helpers::points(&state.metrics, &account_id, metric, None); + assert_eq!(got, want, "{operation} {status}: {metric:?}"); } } } diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 362c8ef22..57ac44520 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -501,32 +501,38 @@ mod throttle_error_tests { } } +/// The sum and the number of data points of `metric` for `account_id` and +/// `table`, or for every table of the account with `None`. +#[cfg(test)] +pub(crate) fn points( + c: &extenddb_core::metrics::MetricsCollector, + account_id: &str, + metric: extenddb_core::metrics::MetricName, + table: Option<&str>, +) -> (f64, u64) { + c.query(&extenddb_core::metrics::MetricsQuery { + account_id: Some(account_id.to_owned()), + table_name: table.map(str::to_owned), + metric: Some(metric), + window: Some(extenddb_core::metrics::TimeWindow::AllTime), + ..Default::default() + }) + .iter() + .fold((0.0, 0), |(sum, count), s| (sum + s.sum, count + s.count)) +} + #[cfg(test)] mod partial_batch_throttle_tests { use std::collections::BTreeMap; - use extenddb_core::metrics::{MetricName, MetricsCollector, MetricsQuery, TimeWindow}; + use extenddb_core::metrics::{MetricName, MetricsCollector}; use serde_json::json; - use super::{batch_entry_counts, record_partial_batch_throttle}; + use super::{batch_entry_counts, points, record_partial_batch_throttle}; const ACCOUNT: &str = "111111111111"; - /// The sum and the number of data points of `metric` for `table`, or for - /// every table with `None`. - fn points(c: &MetricsCollector, metric: MetricName, table: Option<&str>) -> (f64, u64) { - c.query(&MetricsQuery { - account_id: Some(ACCOUNT.to_owned()), - table_name: table.map(str::to_owned), - metric: Some(metric), - window: Some(TimeWindow::AllTime), - ..Default::default() - }) - .iter() - .fold((0.0, 0), |(sum, count), s| (sum + s.sum, count + s.count)) - } - /// CloudWatch counts each throttled entry of a batch as a read or write /// throttle event and leaves a partly served batch out of /// `ThrottledRequests`. Each row: the operation, the throttled entries per @@ -556,7 +562,7 @@ mod partial_batch_throttle_tests { record_partial_batch_throttle(&c, ACCOUNT, operation, &throttled); let row = format!("{operation} {throttled:?}"); assert_eq!( - points(&c, MetricName::ThrottledRequests, None), + points(&c, ACCOUNT, MetricName::ThrottledRequests, None), (0.0, 0), "{row}" ); @@ -567,10 +573,10 @@ mod partial_batch_throttle_tests { let total = expected .iter() .fold((0.0, 0), |(sum, count), (_, (s, n))| (sum + s, count + n)); - assert_eq!(points(&c, metric, None), total, "{row} {metric:?}"); + assert_eq!(points(&c, ACCOUNT, metric, None), total, "{row} {metric:?}"); for (table, sum_and_points) in expected { assert_eq!( - points(&c, metric, Some(table)), + points(&c, ACCOUNT, metric, Some(table)), *sum_and_points, "{row} {metric:?} {table}" ); From f9e372a2946cfb125d6720029492aaddee0c01d9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:18:04 +0000 Subject: [PATCH 33/33] docs: cite the measured all-throttled batch answers in the comments The comments on the all-throttled batch said the answer was documented and not measured. They also said the same of the shape of a fully throttled table in Responses. Measured against the service on 2026-11-24, 24 of 24 BatchGetItem and 3 of 3 BatchWriteItem batches whose every entry was throttled answered 400. In 29 of 29 responses the service left a fully throttled table out of Responses. The comments in both batch handlers and in the batch_partial tests now say so. The tests and the handler still keep that table as an empty list. The comment on record_error_metrics now states the UserErrors rule of the page in two sentences: one for a failed condition, one for a throttled request. --- crates/engine/src/batch_get_item.rs | 13 +++++++------ crates/engine/src/batch_write_item.rs | 7 ++++--- crates/engine/tests/batch_partial.rs | 7 ++++--- crates/server/src/response.rs | 7 ++++--- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index 9abad7d34..bee166c96 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -254,12 +254,13 @@ pub async fn handle_batch_get_item( } // No key of any table could be read: the call fails with the first - // throttle error (API Reference; documented, not measured). "First" is the - // request map's iteration order, so with tables of different billing modes - // either error class can come out; the service's choice for that case is - // not measured (one table per request in the sample). A table whose every - // key was throttled beside a served table keeps an empty `Responses` list; - // unmeasured as well. + // throttle error (API Reference; measured 2026-11-24, 24 of 24 + // all-throttled batches answered 400). "First" is the request map's + // iteration order, so with tables of different billing modes either error + // class can come out; the service's choice for that case is not measured + // (one table per request in the sample). A table whose every key was + // throttled beside a served table keeps an empty `Responses` list; the + // service left it out in 29 of 29 measured responses. if let Some(e) = first_throttle && throttled_tables.values().sum::() as usize == total_keys { diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index d21877853..fb2591e42 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -190,9 +190,10 @@ async fn write_batch( // batch answers the first throttle error instead, with its // ThrottlingReasons: the API reference documents // ProvisionedThroughputExceededException or ThrottlingException for a - // batch that cannot process any item because of throttling (documented, - // not measured). A batch with nothing applied in which a request was - // deferred for another reason answers 503. + // batch that cannot process any item because of throttling (measured + // 2026-11-24, 3 of 3 all-throttled batches answered 400). A batch with + // nothing applied in which a request was deferred for another reason + // answers 503. // // The request faults the same page lists reject the whole batch before // anything is written. `check_batch` finds a missing table, a key that diff --git a/crates/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs index e033e6487..5abe1e65a 100644 --- a/crates/engine/tests/batch_partial.rs +++ b/crates/engine/tests/batch_partial.rs @@ -198,8 +198,8 @@ async fn batch_get_one_table_throttled_beside_a_served_table() { assert_eq!(unprocessed.len(), 1); assert_eq!(pks(&unprocessed["T"]["Keys"]), ["t1", "t2"]); assert!(unprocessed["T"].get("ConsistentRead").is_none()); - // The fully throttled table keeps an empty list under Responses (the - // branch's own contract; the service's shape for this case is unmeasured). + // The fully throttled table keeps an empty list under Responses; the + // service left it out in 29 of 29 measured responses (2026-11-24). let responses = result.body["Responses"].as_object().expect("map"); assert_eq!(responses.len(), 2); assert_eq!(responses["T"], json!([])); @@ -236,7 +236,8 @@ async fn batch_get_by_arn_answers_under_the_arn_and_counts_the_catalog_table() { } /// Every key of every table throttled: the call fails with the throttle -/// error (API Reference; documented, not measured). +/// error (API Reference; measured 2026-11-24, 24 of 24 BatchGetItem and 3 of 3 +/// BatchWriteItem all-throttled batches answered 400). #[tokio::test] async fn batch_get_every_key_throttled_fails_with_the_throttle_error() { for error in throttle_errors("TableReadProvisionedThroughputExceeded") { diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index 6e31dec99..dd233ed48 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -68,9 +68,10 @@ pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Respons /// /// `UserErrors` carries no table name: CloudWatch reports it per account and /// Region only, and a 4xx is often a request whose `TableName` broke the -/// rules. A failed condition counts in `ConditionalCheckFailedRequests` and a -/// throttle error in `ThrottledRequests`, neither in `UserErrors`, as -/// CloudWatch's metrics page says. The server's own bucket records its +/// rules. A failed condition counts in `ConditionalCheckFailedRequests` and not +/// in `UserErrors`, as CloudWatch's metrics page says. A throttle error counts +/// in `ThrottledRequests` and not in `UserErrors`, as the page says of a +/// throttled request. The server's own bucket records its /// refusals before dispatch, so a throttle error here is one a backend /// reported. On `BatchGetItem` and `BatchWriteItem` it answers a batch whose /// every entry was throttled, the one batch CloudWatch counts in