diff --git a/Cargo.lock b/Cargo.lock index caa5863c1..7d087b1a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1898,6 +1898,7 @@ dependencies = [ "tokio", "tokio-util", "tracing", + "tracing-subscriber", "uuid", "web-time", ] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index fbf55e345..66e95023f 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -69,6 +69,8 @@ tokio = { workspace = true, features = ["test-util"] } extenddb-storage-sqlite = { path = "../storage-sqlite" } # Scratch directories that are removed when a test panics. tempfile = "3" +# A subscriber that counts the fault log lines the error mappings write. +tracing-subscriber = { workspace = true } # `tests/private_modes.rs` sets umask 0. [target.'cfg(unix)'.dev-dependencies] diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 5f0286d47..65d703eaf 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -1633,6 +1633,8 @@ mod overrides; pub mod reconciler; mod restore; mod runtime; +#[cfg(test)] +mod service_error_tests; pub mod store_identity; pub mod store_maintenance; pub mod sync; 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..a6f6c9301 --- /dev/null +++ b/crates/engine/src/backup/service_error_tests.rs @@ -0,0 +1,21 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! 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::error_document; +use extenddb_storage::error::StorageError; + +use super::{create_backup_storage_err_to_dynamo, restore_storage_err_to_dynamo}; + +#[test] +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/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/backup_requests.rs b/crates/engine/src/backup_requests.rs index 8da9f4748..267173ee4 100644 --- a/crates/engine/src/backup_requests.rs +++ b/crates/engine/src/backup_requests.rs @@ -576,6 +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), + 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 ff81d2a02..08325fdfb 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -229,6 +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()) } + 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) + } + other => other, } } @@ -253,16 +273,26 @@ pub(crate) fn storage_err_to_dynamo_with_ccf( 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), } } #[cfg(test)] mod storage_error_mapping_tests { - 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::json; - use super::storage_err_to_dynamo; + use super::{storage_err_to_dynamo, storage_err_to_dynamo_with_ccf}; /// A snapshot the backend discarded is retryable, like a transient error. #[test] @@ -273,4 +303,29 @@ mod storage_error_mapping_tests { "{err:?}" ); } + + /// Only this mapper reads `ReturnValuesOnConditionCheckFailure`: a + /// 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())); + 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/lib.rs b/crates/engine/src/lib.rs index 89a17ce65..3637e2fd3 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -62,11 +62,15 @@ mod read_helpers; mod request_limits; mod scan; mod search_vectors; +#[cfg(test)] +mod service_error_log_tests; mod start_key; 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; @@ -200,7 +204,13 @@ 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 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 create_table::service_err_to_dynamo(e); + } tracing::error!(internal_error = %e, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } @@ -640,3 +650,27 @@ 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; + + // 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/partiql/common.rs b/crates/engine/src/partiql/common.rs index 4e73cee80..06a395553 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,26 @@ 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 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 { .. } => { + "ProvisionedThroughputExceeded" + } + DynamoDbError::ThrottlingException { .. } => "ThrottlingError", + DynamoDbError::RequestLimitExceeded { .. } => "RequestLimitExceeded", + DynamoDbError::ItemCollectionSizeLimitExceededException { .. } => { + "ItemCollectionSizeLimitExceeded" + } + DynamoDbError::InternalServerError { .. } => "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..6a7aa5086 100644 --- a/crates/engine/src/partiql/common/tests.rs +++ b/crates/engine/src/partiql/common/tests.rs @@ -183,6 +183,54 @@ 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 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 [ + ( + 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::ItemCollectionSizeLimitExceededException( + "Item collection size limit exceeded.".to_owned(), + ), + "ItemCollectionSizeLimitExceeded", + ), + ( + DynamoDbError::InternalServerError( + "The server encountered an internal error.".to_owned(), + ), + "InternalServerError", + ), + ] { + 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( 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..97e721b05 --- /dev/null +++ b/crates/engine/src/service_error_log_tests.rs @@ -0,0 +1,176 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! 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, 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}; + +/// 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` 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); + let _guard = tracing::subscriber::set_default(subscriber); + f(); + *count.lock().unwrap() +} + +/// 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); + +/// 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 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![ + ( + "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, + ), + ("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_reaches_the_client_as_classified_and_is_not_logged_at_any_site() { + for (name, map) in sites() { + 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 redact an unclassified failure behind the +// fixed text and log it once. +#[test] +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(|| { + 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" + ); + } +} + +/// 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/streams.rs b/crates/engine/src/streams.rs index 28fbb7b6f..0a7759cc9 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -540,10 +540,11 @@ 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), + 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 47f6ef771..3af3635d7 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -310,3 +310,21 @@ fn a_token_without_a_stream_arn_gets_the_answer_the_authorization_layer_gives() ); } } + +// 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/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); + }); +} diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index 4b9548679..2ee75d209 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -219,7 +219,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 @@ -231,6 +231,7 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::TableNotActive(name) => { DynamoDbError::ResourceInUseException(format!("Table {name} is not in ACTIVE state")) } + 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.rs b/crates/engine/src/update_table.rs index fdc2191ab..f397a29e9 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -361,7 +361,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 { @@ -391,6 +391,7 @@ 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), + 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/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] diff --git a/crates/storage/src/error.rs b/crates/storage/src/error.rs index 4da6b694d..58e7e1ddc 100755 --- a/crates/storage/src/error.rs +++ b/crates/storage/src/error.rs @@ -98,4 +98,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), } diff --git a/docs/adr/0028-backend-classified-client-error.md b/docs/adr/0028-backend-classified-client-error.md new file mode 100644 index 000000000..2aa9a1c65 --- /dev/null +++ b/docs/adr/0028-backend-classified-client-error.md @@ -0,0 +1,114 @@ +# ADR-0028: 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` 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 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`, +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 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, 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 +backend's not-found. + +## 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. 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 + +- 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 7febe92df..8af407ad8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -54,6 +54,7 @@ decision, write a new ADR. | [0023](0023-catalog-migrations.md) | One list of catalog migrations for every backend, with a ledger in every store | 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 | --- diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index c82acbbfc..0bea19f5c 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -346,8 +346,21 @@ Storage backends write stream records atomically with data writes when `stream` - `IdempotentMismatch`: idempotency token exists with a different fingerprint (the items or a Return field) - `IndexNotFound` — secondary index does not exist - `Internal(String)` — backend-specific error - -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 b3569ef53..a60e77b10 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -367,6 +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 +- 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 34434148c..82ec79506 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 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 diff --git a/docs/rfcs/0002-backend-plugin-policy.md b/docs/rfcs/0002-backend-plugin-policy.md index 1e611c055..07ea9bd51 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 1a007bf71..8d2692b52 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