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/core/src/metrics/types.rs b/crates/core/src/metrics/types.rs index dbee5f9f8..d68089aff 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/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/batch_get_item.rs b/crates/engine/src/batch_get_item.rs index 263ce6c0b..bee166c96 100755 --- a/crates/engine/src/batch_get_item.rs +++ b/crates/engine/src/batch_get_item.rs @@ -3,14 +3,17 @@ //! `BatchGetItem` operation handler. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; 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 @@ -166,6 +171,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 first_throttle: Option = None; + 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; @@ -180,16 +194,29 @@ 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_tables + .entry(key_info.table_name.clone()) + .or_default() += 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); @@ -205,9 +232,41 @@ 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; 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 + { + 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)), @@ -218,7 +277,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)?; @@ -228,6 +287,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 3806e0e44..fb2591e42 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; @@ -172,7 +172,12 @@ async fn write_batch( // item answered 200 with that request in UnprocessedItems and the other // request applied, whichever came first. So every request is tried, and // the answer to one contended request does not depend on where it sat in - // the batch. + // the batch. A request the backend throttled is deferred the same way and + // echoed as sent (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). The service's + // lists came back in neither request nor sorted order; this server keeps + // request order. // // A batch of which no request applied is an error. The same measurement // answered 500 InternalServerError for batches whose requests were all on @@ -181,7 +186,14 @@ async fn write_batch( // retry with backoff, so a client's UnprocessedItems loop cannot spin on a // batch that makes no progress. Each failed request spends its own retry // budget first, so a batch of 25 contended requests can spend 25 budgets - // before it answers. + // before it answers. When every request of the batch was throttled, the + // 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 (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 @@ -202,6 +214,9 @@ 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(); + // The first throttle error; `throttled_tables` counts the throttled requests. + let mut first_throttle: Option = None; + let mut throttled_tables: BTreeMap = BTreeMap::new(); 'tables: for (table_index, ((table_name, reqs), key_info)) in tables.iter().zip(&key_infos).enumerate() @@ -279,6 +294,16 @@ async fn write_batch( } break 'tables; } + // `is_deferrable` takes a `Service` error only when it is + // a throttle. + if let StorageError::Service(e) = e { + if first_throttle.is_none() { + first_throttle = Some(e); + } + *throttled_tables + .entry(key_info.table_name.clone()) + .or_default() += 1; + } unprocessed .entry(table_name.to_owned()) .or_default() @@ -319,7 +344,10 @@ async fn write_batch( if !unprocessed.is_empty() { let not_applied: usize = unprocessed.values().map(Vec::len).sum(); - let outcome = if applied == 0 { + 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 { "no request applied and the batch answers 503" } else { "they are returned in UnprocessedItems" @@ -331,6 +359,11 @@ async fn write_batch( "BatchWriteItem: {not_applied} request(s) of the batch not applied; {outcome}" ); if applied == 0 { + if let Some(e) = first_throttle + && all_throttled + { + return Err(e); + } return Err(DynamoDbError::ServiceUnavailable( "Service is temporarily unavailable".to_owned(), )); @@ -370,10 +403,17 @@ async fn write_batch( let output = BatchWriteItemOutput { unprocessed_items: unprocessed, 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)?; @@ -381,6 +421,7 @@ async fn write_batch( body, metrics: DispatchMetrics { write_capacity_units: wcu, + throttled_tables, ..Default::default() }, }) @@ -401,6 +442,11 @@ async fn write_batch( /// would spin on it. An internal error keeps answering HTTP 500, which is /// what it answered before this handler deferred anything. /// +/// A `Service` error that carries a throttle error (`is_throttle`) is +/// deferred as well: the backend throttled the request, which is the first +/// cause of UnprocessedItems the documentation lists. Every other `Service` +/// error fails the batch with that error. +/// /// The handler assumes that a deferred request was not applied. The client /// replays it, and the replay of a request that had committed would apply it /// a second time and write a second stream record. So a backend must return @@ -424,7 +470,7 @@ fn is_deferrable(e: &StorageError) -> bool { StorageError::TransactionConflict(_) | StorageError::Transient(_) | StorageError::Connection(_) - ) + ) || matches!(e, StorageError::Service(e) if e.is_throttle()) } /// The requests from `tables[table_index][request_index]` on, in batch order: 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 6add08c26..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 @@ -17,6 +17,13 @@ fn conflict() -> StorageError { StorageError::TransactionConflict("held".to_owned()) } +fn throttle() -> StorageError { + StorageError::Service(DynamoDbError::provisioned_throughput_exceeded( + extenddb_core::error::PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + vec![], + )) +} + /// A failed request does not stop the ones after it. The service answered 200 /// with only the held item's request unprocessed and the other request applied /// whichever came first (the neighbouring test has the held item second). @@ -29,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 @@ -67,21 +76,27 @@ async fn unprocessed_items_hold_only_the_failed_requests_and_capacity_the_applie /// A batch of which no request applied is an error, not a 200 whose client /// replays it at full speed. Every request is tried first. The service /// answered 500 InternalServerError for such a batch; this server answers 503, -/// which the SDKs retry with backoff. +/// which the SDKs retry with backoff. A throttle beside a failure of another +/// kind answers 503 too: only a batch of which every request was throttled +/// answers the throttle error. #[tokio::test] async fn a_batch_where_nothing_applied_answers_503_after_trying_every_request() { - for failure in [transient(), conflict()] { - let data = Scripted::new(vec![Err(failure.clone()), Err(failure.clone())]); + for (first, second) in [ + (transient(), transient()), + (conflict(), conflict()), + (throttle(), conflict()), + ] { + let data = Scripted::new(vec![Err(first.clone()), Err(second.clone())]); let items = json!({"t": [put("a"), put("b")]}); let err = rejected(run(&data, items, &["t"], found(&["t"])).await); assert!( matches!(err, DynamoDbError::ServiceUnavailable(_)), - "{failure:?} gave {err:?}" + "{first:?}, {second:?} gave {err:?}" ); assert_eq!(err.status_code(), 503); - assert_eq!(data.writes(), ["t/a", "t/b"], "{failure:?}"); + assert_eq!(data.writes(), ["t/a", "t/b"], "{first:?}, {second:?}"); } } 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..ae55ba3aa 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()) } @@ -370,6 +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 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. @@ -640,3 +654,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..f101b45c9 100644 --- a/crates/engine/src/partiql/common/tests.rs +++ b/crates/engine/src/partiql/common/tests.rs @@ -183,6 +183,52 @@ 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::provisioned_throughput_exceeded( + "The level of configured provisioned throughput for the table was exceeded.", + vec![], + ), + "ProvisionedThroughputExceeded", + ), + ( + DynamoDbError::throttling("Throughput exceeds the current capacity.", vec![]), + "ThrottlingError", + ), + ( + DynamoDbError::request_limit_exceeded("Throughput exceeds the account quota.", vec![]), + "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..bf5058290 --- /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::provisioned_throughput_exceeded(capacity, vec![]), + 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/engine/tests/batch_partial.rs b/crates/engine/tests/batch_partial.rs new file mode 100644 index 000000000..5abe1e65a --- /dev/null +++ b/crates/engine/tests/batch_partial.rs @@ -0,0 +1,632 @@ +// 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 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; +use std::path::PathBuf; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use extenddb_auth::AuthCacheRegistry; +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, +}; + +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)), + 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: 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, + } +} + +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, in list order. +fn pks(list: &Value) -> Vec<&str> { + list.as_array() + .expect("list") + .iter() + .map(|k| k["pk"]["S"].as_str().expect("pk")) + .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 { + Err(e) => e, + Ok(ok) => panic!("expected an error, got a response: {}", ok.body), + } +} + +/// 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 + }) +} + +// --------------------------------------------------------------------------- +// 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. Both lists keep request order. +#[tokio::test] +async fn batch_get_partial_echoes_request_fields_and_charges_served_only() { + 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 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)])); + } +} + +/// 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"]); + assert!(unprocessed["T"].get("ConsistentRead").is_none()); + // 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!([])); + 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"], + json!([{"TableName": "U", "CapacityUnits": 1.0}]) + ); + assert_eq!(result.metrics.read_capacity_units, 1.0); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); +} + +/// 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_by_arn_answers_under_the_arn_and_counts_the_catalog_table() { + let arn = table_arn("T"); + let store = Arc::new( + FailingStore::throttling() + .with_items(&["k1", "k2"]) + .failing_on(&["k2"]), + ); + let mut items = serde_json::Map::new(); + items.insert(arn.clone(), json!({"Keys": keys_json(&["k1", "k2"])})); + let body = json!({"RequestItems": items}); + + 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; 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") { + 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 +/// 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"]); + assert_eq!( + pks(&result.body["UnprocessedKeys"]["T"]["Keys"]), + ["k1", "k2"] + ); + 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"]); +} + +/// 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"]); +} + +/// 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[
]` 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() { + 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": "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()) + ] + ); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); + } +} + +/// 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"}}}}] + } + }); + + let err = err_of(handle_batch_write_item(body, &ctx(Arc::clone(&store))).await); + assert_error(&err, &error); + assert!(store.applied().is_empty()); + } +} + +/// 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"}}}} + ] + } + }); + + let err = err_of(handle_batch_write_item(body, &ctx(store)).await); + assert_error(&err, &errors[0]); + } +} + +/// 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_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 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 +/// 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())]); + 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}]) + ); + assert_eq!(result.metrics.throttled_tables, counts(&[("T", 2)])); +} + +/// 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..ad45d4b77 --- /dev/null +++ b/crates/engine/tests/batch_partial/failing_store.rs @@ -0,0 +1,895 @@ +// 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}; +use std::sync::Mutex; +use std::time::Duration; + +use extenddb_core::backup_format::BackupArn; +use extenddb_core::error::{ + 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::{ + AttributeDefinition, AttributeValue, BackupDescription, BackupDetails, BackupSummary, + 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::{ + 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"; + +/// 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 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>, +} + +impl FailingStore { + pub fn new(error: DynamoDbError) -> Self { + Self { + tables: HashMap::from([("T".to_owned(), true), ("U".to_owned(), false)]), + items: BTreeMap::new(), + failing: HashMap::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 { + 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 + } + + /// 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 { + self.applied.lock().expect("applied lock").clone() + } +} + +pub fn throttle_error(reason: &str) -> DynamoDbError { + 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: 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 { + 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 let Some(e) = self.failure(&item) { + Err(e) + } 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 let Some(e) = self.failure(key) { + Err(e) + } 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 let Some(e) = self.failure(key) { + Err(e) + } 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, + _stream_arn: &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") + } + fn first_sequence_number_at_or_after( + &self, + _shard_id: &str, + _at_ms: i64, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } +} + +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( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn list( + &self, + _account_id: &str, + _table_name: Option<&str>, + ) -> BoxedFuture<'_, Result, StorageError>> { + unimplemented!("not exercised") + } + fn delete( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn restore_source( + &self, + _account_id: &str, + _backup_arn: &str, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + fn restore( + &self, + _account_id: &str, + _request: RestoreRequest, + _permit: JobPermit, + ) -> BoxedFuture<'_, Result> { + unimplemented!("not exercised") + } + 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, + _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") + } +} + +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, + ) -> 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/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 8f5036cc2..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, 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; @@ -323,6 +328,14 @@ 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, + &ctx.account_id, + &operation, + &result.metrics.throttled_tables, + ); let m = &result.metrics; if let Some(ref tn) = metric_table { @@ -386,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 4c90d9a9e..2fdaf598b 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,64 @@ 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, 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; + 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, + [(2.0, 1), (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 got = crate::throttle_helpers::points(&state.metrics, &account_id, metric, None); + assert_eq!(got, want, "{operation} {status}: {metric:?}"); + } + } +} 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/server/src/response.rs b/crates/server/src/response.rs index 8ea195307..dd233ed48 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -69,7 +69,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 +/// 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 +/// `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 +97,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 +187,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 e6b353141..57ac44520 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -115,6 +115,70 @@ fn extract_throughput_from_response( )) } +/// 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, 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( + metrics: &extenddb_core::metrics::MetricsCollector, + account_id: &str, + operation: &str, + throttled_tables: &std::collections::BTreeMap, +) { + use extenddb_core::metrics::MetricName; + let event = match operation { + "BatchGetItem" => MetricName::ReadThrottleEvents, + "BatchWriteItem" => MetricName::WriteThrottleEvents, + _ => return, + }; + for (table, entries) in throttled_tables { + metrics.record( + event, + f64::from(*entries), + Some(account_id), + Some(table), + None, + Some(operation), + ); + } +} + +/// 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`), @@ -436,3 +500,132 @@ 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}; + + use serde_json::json; + + use super::{batch_entry_counts, points, record_partial_batch_throttle}; + + const ACCOUNT: &str = "111111111111"; + + /// 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_records_one_throttle_event_per_throttled_entry() { + type Events<'a> = &'a [(&'a str, (f64, u64))]; + type Row<'a> = (&'a str, &'a [(&'a str, u32)], Events<'a>, Events<'a>); + let rows: [Row; 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, ACCOUNT, 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, ACCOUNT, metric, None), total, "{row} {metric:?}"); + for (table, sum_and_points) in expected { + assert_eq!( + points(&c, ACCOUNT, metric, Some(table)), + *sum_and_points, + "{row} {metric:?} {table}" + ); + } + } + } + } + + /// 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}" + ); + } + } +} 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..9df706781 --- /dev/null +++ b/docs/adr/0028-backend-classified-client-error.md @@ -0,0 +1,118 @@ +# 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`. + +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 +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..af7cac104 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -346,8 +346,33 @@ 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`. + +`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 diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 7d2c4717e..598d6a80a 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) @@ -211,6 +211,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 throttle covers GetItem, PutItem, UpdateItem, DeleteItem, Query and Scan, the operations whose request names one table in `TableName`, and sends the same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. BatchGetItem, BatchWriteItem, TransactGetItems, TransactWriteItems and the PartiQL operations are not throttled. 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. 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 | ## Transactions diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index ef52ae945..6b10fa9cf 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 (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 34434148c..d1d23f38a 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). 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 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