From 75eae2c551990ea2db9a8726044780b9093aa8d3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 10:35:45 +0000 Subject: [PATCH 01/12] feat(server): carry the request id and operation in a task-local request scope from authentication through dispatch Add extenddb_storage::request_scope: a RequestScope holding the request id the client receives in x-amzn-RequestId, the operation name from X-Amz-Target, and the amz-sdk-invocation-id and amz-sdk-request headers when the client sent them, kept in a Tokio task-local with with_scope, with_scope_opt, current, with_current and log_fields. The struct is non_exhaustive and built through RequestScope::new and with_sdk_headers, so it can gain fields in a minor release. A header value is carried only when it is visible ASCII of at most 256 bytes; anything else reads as absent. The server runs each request from the start of authentication through the end of dispatch inside the scope. The segments between (authorization, with its key-schema lookup through the catalog, and throttle registration) make the request's storage reads before dispatch, so they are inside the span too. That span is one function, serve_request, which the handler calls inside with_scope; the early returns before it touch no storage and the response segment after it runs outside the scope. The engine's fault log sites write through one macro, log_storage_fault!, which expands at the call site (so each line keeps its own target, file and line) and adds request_id and operation from the scope. The sites: the five "storage internal error" arms in create_table, update_table, streams, ttl and sanitize_storage_error; the "backup storage error" arm in backup; and the three create_table arms that return a 500 for CatalogVersionMismatch, CatalogNotInitialized and an idempotency error reaching the generic mapper. Each site keeps its message text, the catalog version arm included (its expected and found values stay in the message and also appear in internal_error through the error's Display). Outside a request the two fields are not recorded, so the line carries neither. RestoreTableFromBackup runs its restore in a task of its own, which does not inherit the scope; the engine reads the scope before the spawn and re-enters it inside the task with with_scope_opt. extenddb_engine::dispatch writes one trace event at entry, under the target extenddb_engine::dispatch, inside the scope. Cost on the request path: two String clones (request id and operation) plus the two header copies when the headers are present; one more clone of the scope on RestoreTableFromBackup. Tests: nine in the storage crate (none outside a scope; equal inside; the constructors; visible through nested awaits and a boxed future; not inherited by a spawned task; re-entered by a spawned task through with_scope_opt; with_scope_opt without a scope; two concurrent scopes each see their own value; log_fields inside and outside). Three in the engine crate: every mapping arm inside and outside a scope under a capturing subscriber, checking request_id, operation, message and target per site; the detached restore under a scope against a backup engine whose source lookup faults, checking the "backup storage error" line names the request. Seven in the server crate, three driven through handle_request against an in-memory engine: no scope on the handler's task before a request or after its response; the scope current when the auth provider runs carries the response's request id, the operation and both SDK headers; the same at the dispatch entry event, and no scope at the "request complete" event the response segment writes. The others check request_scope_for and header_string: both headers carried; absent headers read as None; a value that is not visible ASCII reads as None; a value over 256 bytes reads as None and one at 256 is kept. --- crates/engine/src/backup.rs | 24 +- crates/engine/src/create_table.rs | 20 +- crates/engine/src/fault_log.rs | 31 ++ crates/engine/src/lib.rs | 13 +- crates/engine/src/request_scope_log_tests.rs | 355 ++++++++++++++++++ crates/engine/src/streams.rs | 2 +- crates/engine/src/ttl.rs | 2 +- crates/engine/src/update_table.rs | 2 +- crates/server/src/handler.rs | 327 ++++++++++------ .../server/src/handler/request_scope_tests.rs | 271 +++++++++++++ .../server/src/handler/throttle_wire_tests.rs | 16 +- crates/storage/src/lib.rs | 2 + crates/storage/src/request_scope.rs | 219 +++++++++++ 13 files changed, 1139 insertions(+), 145 deletions(-) create mode 100644 crates/engine/src/fault_log.rs create mode 100644 crates/engine/src/request_scope_log_tests.rs create mode 100644 crates/server/src/handler/request_scope_tests.rs create mode 100644 crates/storage/src/request_scope.rs diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 2670643a3..8a7b8882b 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -999,7 +999,7 @@ pub(crate) async fn handle_restore_table_from_backup( /// drops only the wait, so the restore is not cancelled part-way. Without /// this, a disconnect while the backup was being read (step 4 below) dropped /// the request before the backend registered the restore, and no restore ran. -async fn restore_table_from_backup_detached( +pub(crate) async fn restore_table_from_backup_detached( storage: Arc, account_id: Arc, region: Arc, @@ -1012,12 +1012,20 @@ where F: FnOnce(Arc, String) -> Fut + Send + 'static, Fut: std::future::Future + Send, { - tokio::spawn(async move { - let (target_table_name, response) = - restore_table_from_backup(&*storage, &account_id, ®ion, &limits, &body).await?; - after(account_id, target_table_name).await; - Ok(response) - }) + // The restore runs in a task of its own so a client disconnect does not + // cancel it part-way. A spawned task does not inherit the request scope, + // so it is carried across by hand: the task's fault lines then name the + // request id the client received. + let scope = extenddb_storage::request_scope::current(); + tokio::spawn(extenddb_storage::request_scope::with_scope_opt( + scope, + async move { + let (target_table_name, response) = + restore_table_from_backup(&*storage, &account_id, ®ion, &limits, &body).await?; + after(account_id, target_table_name).await; + Ok(response) + }, + )) .await .map_err(|e| { tracing::error!("RestoreTableFromBackup task failed: {e}"); @@ -1282,7 +1290,7 @@ pub(crate) fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError { // the catch-all that reports a storage fault. StorageError::Service(e) => e, other => { - tracing::error!(internal_error = %other, "backup storage error"); + log_storage_fault!(other, "backup storage error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 7241bd630..ec4ea50ae 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -174,12 +174,18 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo // "unsupported" error class, and the request is invalid against this // deployment rather than a server failure. StorageError::Unsupported(msg) => DynamoDbError::ValidationException(msg), - StorageError::CatalogVersionMismatch { expected, found } => { - tracing::error!("Catalog version mismatch: expected {expected}, found {found}"); + ref e @ StorageError::CatalogVersionMismatch { + ref expected, + ref found, + } => { + log_storage_fault!( + e, + "Catalog version mismatch: expected {expected}, found {found}" + ); DynamoDbError::InternalServerError("Internal server error".to_owned()) } - StorageError::CatalogNotInitialized => { - tracing::error!("Catalog not initialized"); + e @ StorageError::CatalogNotInitialized => { + log_storage_fault!(e, "Catalog not initialized"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } // Generic path: discard the old item (callers that need it use @@ -200,10 +206,10 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo } StorageError::Validation(msg) => DynamoDbError::ValidationException(msg), StorageError::NoOpUpdate(msg) => DynamoDbError::ValidationException(msg), - StorageError::IdempotentReplay | StorageError::IdempotentMismatch => { + e @ (StorageError::IdempotentReplay | StorageError::IdempotentMismatch) => { // These are handled directly by the transact_write_items caller. // If they reach here, it's a programming error. - tracing::error!("Unexpected idempotency error in generic error handler"); + log_storage_fault!(e, "Unexpected idempotency error in generic error handler"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } StorageError::TransactionConflict(msg) => { @@ -217,7 +223,7 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo // Log the raw message for debugging but do not expose storage // backend details (e.g. PostgreSQL error text) to the client. // REQ-ERR: tenet 4 — only DynamoDB-shaped errors cross the wire. - tracing::error!(internal_error = %msg, "storage internal error"); + log_storage_fault!(msg, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } // The backend already classified this failure into the service error diff --git a/crates/engine/src/fault_log.rs b/crates/engine/src/fault_log.rs new file mode 100644 index 000000000..660fd310e --- /dev/null +++ b/crates/engine/src/fault_log.rs @@ -0,0 +1,31 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The log line for a storage fault the client sees as a redacted 500. +//! +//! `log_storage_fault!` expands at its call site, so the event keeps the +//! site's own `target`, `module_path`, `file` and `line`; an operator who +//! filters on `extenddb_engine::backup` still matches the backup mapper's +//! line. The macro adds `request_id` and `operation` from the request scope +//! the server sets around the request (see `extenddb_storage::request_scope`), +//! so the line can be matched to the `x-amzn-RequestId` the client received. +//! Outside a request both are `None`, and `tracing` records nothing for a +//! `None`, so the line carries neither field. + +/// Write an error-level event for a storage fault. +/// +/// `log_storage_fault!(error, "message")` records `internal_error` from +/// `error` (by `Display`) with the message literal. The message may carry +/// format arguments: `log_storage_fault!(error, "catalog version mismatch: +/// expected {expected}, found {found}")`. +macro_rules! log_storage_fault { + ($error:expr, $($message:tt)+) => {{ + let (request_id, operation) = extenddb_storage::request_scope::log_fields(); + tracing::error!( + internal_error = %$error, + request_id = request_id.as_deref(), + operation = operation.as_deref(), + $($message)+ + ); + }}; +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8550b0d13..4b5227386 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,8 @@ //! inputs, dispatches operations by name, and translates storage errors into //! `DynamoDB`-format error responses. +#[macro_use] +mod fault_log; mod backup; mod batch_get_item; mod batch_write_item; @@ -29,6 +31,8 @@ mod put_item; mod query; mod read_helpers; mod request_limits; +#[cfg(test)] +mod request_scope_log_tests; mod scan; mod search_vectors; #[cfg(test)] @@ -154,7 +158,7 @@ pub(crate) fn sanitize_storage_error(e: extenddb_storage::error::StorageError) - if let extenddb_storage::error::StorageError::Service(e) = e { return e; } - tracing::error!(internal_error = %e, "storage internal error"); + log_storage_fault!(e, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } @@ -437,12 +441,19 @@ impl OperationContext { /// Dispatch an operation by name. /// /// Returns the JSON response body and sideband metrics for the metrics collector. +/// +/// The server calls this inside the request scope +/// (`extenddb_storage::request_scope`), so everything reached from here on the +/// same task, including the storage backend and the error mappers, can read +/// the request id and operation. The trace event at entry, under the target +/// `extenddb_engine::dispatch`, is written inside that scope too. pub async fn dispatch( operation: &str, body: serde_json::Value, ctx: &OperationContext, server_addr: &str, ) -> Result { + tracing::trace!(target: "extenddb_engine::dispatch", operation, "dispatch"); match operation { "CreateTable" => handle_create_table(body, ctx) .await diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs new file mode 100644 index 000000000..be3e304b2 --- /dev/null +++ b/crates/engine/src/request_scope_log_tests.rs @@ -0,0 +1,355 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The fault log line names the request it belongs to. Each engine mapping +//! arm that turns a `StorageError` into a redacted 500 writes the line through +//! `log_storage_fault!`, which reads the request id and operation from the +//! request scope the server sets around the request. Inside a scope the two +//! fields carry the request's values; outside one the line carries neither. +//! The macro expands at its call site, so each line keeps the site's own +//! target. The detached restore re-enters the scope in its spawned task. + +use std::sync::{Arc, Mutex}; + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::error::StorageError; +use extenddb_storage::request_scope::{RequestScope, with_scope}; +use tracing::field::{Field, Visit}; +use tracing::{Event, Level, Subscriber}; +use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + +/// What the subscriber saw of one error-level event: the `request_id` and +/// `operation` fields (`None` when the field was not recorded), the message +/// and the event's static target. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Seen { + request_id: Option, + operation: Option, + message: String, + target: String, +} + +impl Visit for Seen { + fn record_str(&mut self, field: &Field, value: &str) { + match field.name() { + "request_id" => self.request_id = Some(value.to_owned()), + "operation" => self.operation = Some(value.to_owned()), + _ => {} + } + } + + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.message = format!("{value:?}"); + } + } +} + +#[derive(Default)] +struct Captured(Arc>>); + +impl Layer for Captured { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + if *event.metadata().level() == Level::ERROR { + let mut seen = Seen { + target: event.metadata().target().to_owned(), + ..Seen::default() + }; + event.record(&mut seen); + self.0.lock().unwrap().push(seen); + } + } +} + +/// Runs `f` under a fresh subscriber and returns every error event it logged. +fn error_events_during(f: impl FnOnce()) -> Vec { + let captured = Captured::default(); + let events = Arc::clone(&captured.0); + let subscriber = tracing_subscriber::registry().with(captured); + let _guard = tracing::subscriber::set_default(subscriber); + f(); + events.lock().unwrap().clone() +} + +/// Runs `fut` under a fresh subscriber and returns every error event it logged. +async fn error_events_during_async(fut: F) -> Vec { + let captured = Captured::default(); + let events = Arc::clone(&captured.0); + let subscriber = tracing_subscriber::registry().with(captured); + let _guard = tracing::subscriber::set_default(subscriber); + fut.await; + events.lock().unwrap().clone() +} + +fn scope() -> RequestScope { + RequestScope::new("req-0f2a".to_owned(), "CreateTable".to_owned()) +} + +/// A mapping arm: its name, the error that reaches it, the function, the +/// message text its line has always carried, and the target of the module +/// that owns the arm. +struct Site { + name: &'static str, + error: fn() -> StorageError, + map: fn(StorageError) -> DynamoDbError, + message: &'static str, + target: &'static str, +} + +fn internal() -> StorageError { + StorageError::Internal("driver text".to_owned()) +} + +/// Every engine arm that maps a `StorageError` to a redacted 500. +fn sites() -> Vec { + vec![ + Site { + name: "create_table::storage_err_to_dynamo, Internal", + error: internal, + map: crate::create_table::storage_err_to_dynamo, + message: "storage internal error", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, CatalogVersionMismatch", + error: || StorageError::CatalogVersionMismatch { + expected: "3".to_owned(), + found: "2".to_owned(), + }, + map: crate::create_table::storage_err_to_dynamo, + message: "Catalog version mismatch: expected 3, found 2", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, CatalogNotInitialized", + error: || StorageError::CatalogNotInitialized, + map: crate::create_table::storage_err_to_dynamo, + message: "Catalog not initialized", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, IdempotentReplay", + error: || StorageError::IdempotentReplay, + map: crate::create_table::storage_err_to_dynamo, + message: "Unexpected idempotency error in generic error handler", + target: "extenddb_engine::create_table", + }, + Site { + name: "backup::storage_err_to_dynamo", + error: internal, + map: crate::backup::storage_err_to_dynamo, + message: "backup storage error", + target: "extenddb_engine::backup", + }, + Site { + name: "update_table::update_table_err_to_dynamo", + error: internal, + map: |e| crate::update_table::update_table_err_to_dynamo(e, "t"), + message: "storage internal error", + target: "extenddb_engine::update_table", + }, + Site { + name: "streams::storage_to_dynamo", + error: internal, + map: crate::streams::storage_to_dynamo, + message: "storage internal error", + target: "extenddb_engine::streams", + }, + Site { + name: "ttl::storage_to_dynamo", + error: internal, + map: crate::ttl::storage_to_dynamo, + message: "storage internal error", + target: "extenddb_engine::ttl", + }, + Site { + name: "sanitize_storage_error", + error: internal, + map: crate::sanitize_storage_error, + message: "storage internal error", + target: "extenddb_engine", + }, + ] +} + +#[tokio::test] +async fn the_fault_line_names_the_request_inside_a_scope_at_every_site() { + for site in sites() { + let logged = with_scope(scope(), async { + error_events_during(|| { + let err = (site.map)((site.error)()); + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{}", + site.name + ); + }) + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-0f2a".to_owned()), + operation: Some("CreateTable".to_owned()), + message: site.message.to_owned(), + target: site.target.to_owned(), + }], + "{}: the fault line did not carry the scope's request id and operation", + site.name + ); + } +} + +#[tokio::test] +async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site() { + for site in sites() { + let logged = error_events_during(|| { + let err = (site.map)((site.error)()); + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{}", + site.name + ); + }); + assert_eq!( + logged, + vec![Seen { + request_id: None, + operation: None, + message: site.message.to_owned(), + target: site.target.to_owned(), + }], + "{}: a fault outside a request carried a request id or operation", + site.name + ); + } +} + +/// A backup engine whose source lookup fails with a storage fault. The other +/// methods are never reached: the restore reads the source first. +struct FaultingBackups; + +impl extenddb_storage::BackupEngine for FaultingBackups { + fn create_backup( + &self, + _: &str, + _: &str, + _: &str, + ) -> extenddb_storage::BoxedFuture<'_, Result> + { + unreachable!("not reached by the restore") + } + fn describe_backup( + &self, + _: &str, + _: &str, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + unreachable!("not reached by the restore") + } + fn list_backups( + &self, + _: &str, + _: Option<&str>, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, StorageError>, + > { + unreachable!("not reached by the restore") + } + fn delete_backup( + &self, + _: &str, + _: &str, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + unreachable!("not reached by the restore") + } + fn backup_restore_source( + &self, + _: &str, + _: &str, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + Box::pin(async { Err(internal()) }) + } + fn restore_table_from_backup( + &self, + _: &str, + _: extenddb_storage::RestoreRequest, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + unreachable!("not reached by the restore") + } + fn describe_continuous_backups( + &self, + _: &str, + _: &str, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + unreachable!("not reached by the restore") + } + fn update_continuous_backups( + &self, + _: &str, + _: &str, + _: bool, + ) -> extenddb_storage::BoxedFuture< + '_, + Result, + > { + unreachable!("not reached by the restore") + } +} + +/// `RestoreTableFromBackup` runs its restore in a task of its own. The task +/// does not inherit the request scope, so the engine carries it across; the +/// `backup storage error` line written inside the task names the request. +#[tokio::test] +async fn the_detached_restore_carries_the_scope_into_its_task() { + let body = serde_json::json!({ + "BackupArn": "arn:aws:dynamodb:us-east-1:123456789012:table/src/backup/01700000000000-abcdef12", + "TargetTableName": "restored", + }); + let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); + let logged = with_scope( + RequestScope::new( + "req-restore".to_owned(), + "RestoreTableFromBackup".to_owned(), + ), + error_events_during_async(async { + let result = crate::backup::restore_table_from_backup_detached( + Arc::new(FaultingBackups), + Arc::from("123456789012"), + Arc::from("us-east-1"), + limits, + body, + |_, _| async {}, + ) + .await; + assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); + }), + ) + .await; + assert_eq!( + logged.len(), + 1, + "one fault line for the failed source lookup" + ); + assert_eq!(logged[0].request_id.as_deref(), Some("req-restore")); + assert_eq!( + logged[0].operation.as_deref(), + Some("RestoreTableFromBackup") + ); + assert_eq!(logged[0].message, "backup storage error"); + assert_eq!(logged[0].target, "extenddb_engine::backup"); +} diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 527fac740..c2eb44516 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -358,7 +358,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { // unchanged; it is not a storage fault, so it is not logged as one. StorageError::Service(e) => e, other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index 902575181..d5aa8cc9d 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -231,7 +231,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { // unchanged; it is not a storage fault, so it is not logged as one. StorageError::Service(e) => e, other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(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 c11dcb7ee..4526bee9e 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -344,7 +344,7 @@ pub(crate) fn update_table_err_to_dynamo( // unchanged; it is not a storage fault, so it is not logged as one. StorageError::Service(e) => e, other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 5c2f19cbb..9ffa58e16 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -89,12 +89,159 @@ pub(crate) async fn handle_request( } }; - // --- Auth segment --- - let auth_start = std::time::Instant::now(); - let identity = match state.auth.authenticate(&headers, &body).await { - Ok(id) => id, + // --- Authentication through dispatch, inside the request scope --- + // The scope carries the request id and operation (and the two SDK + // correlation headers when the client sent them) to every storage read + // the request makes and to the engine's error mappers, so a fault log line + // can name the x-amzn-RequestId the client received. The early returns + // above touch no storage and the response building below runs outside it. + let Served { + account_id, + table_name, + partition_value, + dispatch_result, + auth_us, + authz_us, + throttle_us, + dispatch_us, + } = match extenddb_storage::request_scope::with_scope( + request_scope_for(&request_id, &operation, &headers), + serve_request(&state, &headers, &body, peer_addr, &operation, input), + ) + .await + { + Ok(served) => served, Err(e) => return error_response(&e, &request_id), }; + + // --- Response segment --- + let response_start = std::time::Instant::now(); + let response = match dispatch_result { + Ok(result) => { + update_throttle_buckets( + &state.throttle, + &operation, + &account_id, + table_name.as_deref(), + &result.body, + ); + + let m = &result.metrics; + if let Some(ref tn) = table_name { + if m.read_capacity_units > 0.0 { + state.metrics.record( + extenddb_core::metrics::MetricName::ConsumedReadCapacityUnits, + m.read_capacity_units, + Some(tn), + m.index_name.as_deref(), + Some(&operation), + ); + } + if m.write_capacity_units > 0.0 { + state.metrics.record( + extenddb_core::metrics::MetricName::ConsumedWriteCapacityUnits, + m.write_capacity_units, + Some(tn), + m.index_name.as_deref(), + Some(&operation), + ); + } + if m.returned_item_count > 0 { + state + .metrics + .record_returned_items(tn, &operation, m.returned_item_count); + } + if m.returned_bytes > 0 { + state + .metrics + .record_returned_bytes(tn, &operation, m.returned_bytes); + } + state.throttle.consume_with_partition( + &account_id, + tn, + m.read_capacity_units, + m.write_capacity_units, + partition_value.as_deref(), + ); + } + + success_response(&result.body, &request_id) + } + Err(e) => { + record_error_metrics(&state.metrics, &e, table_name.as_deref(), &operation); + error_response(&e, &request_id) + } + }; + #[allow(clippy::cast_precision_loss)] + let response_us = response_start.elapsed().as_micros() as f64; + + // Record per-segment latency breakdown and total latency. + #[allow(clippy::cast_precision_loss)] + let total_us = handler_start.elapsed().as_micros() as f64; + state + .metrics + .record_latency(table_name.as_deref(), &operation, total_us); + state.metrics.record_request_count(&operation); + state.metrics.record_segments( + &operation, + table_name.as_deref(), + extenddb_core::metrics::LatencySegments { + auth_us, + authz_us, + throttle_us, + dispatch_us, + response_us, + total_us, + }, + ); + + // P79: Request-level trace logging. + tracing::debug!( + request_id = %request_id, + operation = %operation, + table = table_name.as_deref().unwrap_or("-"), + auth_us = auth_us, + authz_us = authz_us, + throttle_us = throttle_us, + dispatch_us = dispatch_us, + response_us = response_us, + total_us = total_us, + "request complete" + ); + + response +} + +/// What the request produced between authentication and the end of dispatch: +/// the dispatch result and what the response segment needs to account for it. +struct Served { + account_id: Arc, + table_name: Option, + partition_value: Option, + dispatch_result: Result, + auth_us: f64, + authz_us: f64, + throttle_us: f64, + dispatch_us: f64, +} + +/// Authenticate, authorize, throttle and dispatch one request. Every storage +/// read the request makes happens here, so `handle_request` runs this whole +/// future inside the request scope. A refusal before dispatch returns `Err`; +/// a dispatch error is inside `Served::dispatch_result`, because the response +/// segment accounts for it differently. +#[allow(clippy::too_many_lines)] // sequential request pipeline +async fn serve_request( + state: &Arc, + headers: &HeaderMap, + body: &Bytes, + peer_addr: std::net::SocketAddr, + operation: &str, + input: Value, +) -> Result { + // --- Auth segment --- + let auth_start = std::time::Instant::now(); + let identity = state.auth.authenticate(headers, body).await?; #[allow(clippy::cast_precision_loss)] let auth_us = auth_start.elapsed().as_micros() as f64; @@ -111,12 +258,9 @@ pub(crate) async fn handle_request( { if state.catalog_store.is_none() { tracing::error!("Authorization required but catalog_store is not configured"); - return error_response( - &DynamoDbError::AccessDeniedException( - "User: is not authorized to perform this operation".to_owned(), - ), - &request_id, - ); + return Err(DynamoDbError::AccessDeniedException( + "User: is not authorized to perform this operation".to_owned(), + )); } // aws:SourceIp is the connection peer address; aws:UserAgent is the // User-Agent header. Behind a proxy only the peer address is trusted, @@ -126,20 +270,16 @@ pub(crate) async fn handle_request( .get("user-agent") .and_then(|v| v.to_str().ok()) .map(ToOwned::to_owned); - match authorize_request( - &state, + authorized_key_info = authorize_request( + state, &identity, &input, - &operation, + operation, &account_id, Some(source_ip.as_str()), user_agent.as_deref(), ) - .await - { - Ok(ki) => authorized_key_info = ki, - Err(e) => return error_response(&e, &request_id), - } + .await?; } #[allow(clippy::cast_precision_loss)] let authz_us = authz_start.elapsed().as_micros() as f64; @@ -163,8 +303,8 @@ pub(crate) async fn handle_request( // --- Throttle segment --- let throttle_start = std::time::Instant::now(); - let (is_read_op, is_write_op) = classify_data_operation(&operation); - let partition_value = extract_partition_value(&input, &operation); + let (is_read_op, is_write_op) = classify_data_operation(operation); + let partition_value = extract_partition_value(&input, operation); if let Some(ref tn) = table_name && (is_read_op || is_write_op) { @@ -204,13 +344,13 @@ pub(crate) async fn handle_request( }; state .metrics - .record(metric, 1.0, Some(tn), None, Some(&operation)); + .record(metric, 1.0, Some(tn), None, Some(operation)); state.metrics.record( extenddb_core::metrics::MetricName::ThrottledRequests, 1.0, Some(tn), None, - Some(&operation), + Some(operation), ); // The service names the throttled resource and the limit on a // throttle: one reason with the table ARN, the same string @@ -224,10 +364,7 @@ pub(crate) async fn handle_request( let table_arn = extenddb_core::validation::validate_table_name_chars(&name) .is_ok() .then(|| extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name)); - return error_response( - &throttle_error(cause, throttled_read, table_arn), - &request_id, - ); + return Err(throttle_error(cause, throttled_read, table_arn)); } } #[allow(clippy::cast_precision_loss)] @@ -236,11 +373,11 @@ pub(crate) async fn handle_request( // --- Dispatch segment --- let dispatch_start = std::time::Instant::now(); let dispatch_result = - extenddb_engine::dispatch(&operation, input, &ctx, &state.server_addr).await; + extenddb_engine::dispatch(operation, input, &ctx, &state.server_addr).await; #[allow(clippy::cast_precision_loss)] let dispatch_us = dispatch_start.elapsed().as_micros() as f64; // P120c: Record storage query metrics for the request's dispatch phase. - let category = match operation.as_str() { + let category = match operation { "CreateTable" | "DeleteTable" | "DescribeTable" @@ -264,103 +401,51 @@ pub(crate) async fn handle_request( dispatch_us, ); - // --- Response segment --- - let response_start = std::time::Instant::now(); - let response = match dispatch_result { - Ok(result) => { - update_throttle_buckets( - &state.throttle, - &operation, - &ctx.account_id, - table_name.as_deref(), - &result.body, - ); - - let m = &result.metrics; - if let Some(ref tn) = table_name { - if m.read_capacity_units > 0.0 { - state.metrics.record( - extenddb_core::metrics::MetricName::ConsumedReadCapacityUnits, - m.read_capacity_units, - Some(tn), - m.index_name.as_deref(), - Some(&operation), - ); - } - if m.write_capacity_units > 0.0 { - state.metrics.record( - extenddb_core::metrics::MetricName::ConsumedWriteCapacityUnits, - m.write_capacity_units, - Some(tn), - m.index_name.as_deref(), - Some(&operation), - ); - } - if m.returned_item_count > 0 { - state - .metrics - .record_returned_items(tn, &operation, m.returned_item_count); - } - if m.returned_bytes > 0 { - state - .metrics - .record_returned_bytes(tn, &operation, m.returned_bytes); - } - state.throttle.consume_with_partition( - &ctx.account_id, - tn, - m.read_capacity_units, - m.write_capacity_units, - partition_value.as_deref(), - ); - } - - success_response(&result.body, &request_id) - } - Err(e) => { - record_error_metrics(&state.metrics, &e, table_name.as_deref(), &operation); - error_response(&e, &request_id) - } - }; - #[allow(clippy::cast_precision_loss)] - let response_us = response_start.elapsed().as_micros() as f64; + Ok(Served { + account_id: ctx.account_id, + table_name, + partition_value, + dispatch_result, + auth_us, + authz_us, + throttle_us, + dispatch_us, + }) +} - // Record per-segment latency breakdown and total latency. - #[allow(clippy::cast_precision_loss)] - let total_us = handler_start.elapsed().as_micros() as f64; - state - .metrics - .record_latency(table_name.as_deref(), &operation, total_us); - state.metrics.record_request_count(&operation); - state.metrics.record_segments( - &operation, - table_name.as_deref(), - extenddb_core::metrics::LatencySegments { - auth_us, - authz_us, - throttle_us, - dispatch_us, - response_us, - total_us, - }, - ); +/// The scope the request runs inside from authentication through dispatch: +/// the request id the response will carry in `x-amzn-RequestId`, the +/// operation from `X-Amz-Target`, and the two SDK correlation headers when the +/// client sent them. Cost: two `String` clones per request plus the header +/// copies. +fn request_scope_for( + request_id: &str, + operation: &str, + headers: &HeaderMap, +) -> extenddb_storage::RequestScope { + extenddb_storage::RequestScope::new(request_id.to_owned(), operation.to_owned()) + .with_sdk_headers( + header_string(headers, "amz-sdk-invocation-id"), + header_string(headers, "amz-sdk-request"), + ) +} - // P79: Request-level trace logging. - tracing::debug!( - request_id = %request_id, - operation = %operation, - table = table_name.as_deref().unwrap_or("-"), - auth_us = auth_us, - authz_us = authz_us, - throttle_us = throttle_us, - dispatch_us = dispatch_us, - response_us = response_us, - total_us = total_us, - "request complete" - ); +/// The longest SDK correlation header value the scope carries. The SDKs send +/// a UUID and a short attempt counter; a longer value is read as absent, so a +/// client cannot place arbitrary text of any length in a backend's log line. +const MAX_SDK_HEADER_LEN: usize = 256; - response +/// The value of header `name` as an owned string, or `None` when the header is +/// absent, is not visible ASCII, or is longer than [`MAX_SDK_HEADER_LEN`]. +fn header_string(headers: &HeaderMap, name: &str) -> Option { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .filter(|s| s.len() <= MAX_SDK_HEADER_LEN) + .map(str::to_owned) } +#[cfg(test)] +mod request_scope_tests; #[cfg(test)] mod throttle_wire_tests; diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs new file mode 100644 index 000000000..129ee31fa --- /dev/null +++ b/crates/server/src/handler/request_scope_tests.rs @@ -0,0 +1,271 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The request scope the handler sets from authentication through dispatch. +//! Three tests drive a request through `handle_request` against an in-memory +//! engine: one checks the bounds (no scope on the task before the request, +//! none after the response, none at the `request complete` event the response +//! segment writes); one reads the scope current when the auth provider runs, +//! the first call inside the span; one reads it at the engine's dispatch entry +//! event, the last segment inside the span, and checks it carries the request +//! id the response returned in `x-amzn-RequestId`, the operation and both SDK +//! correlation headers. The remaining tests check `request_scope_for` and +//! `header_string` on their own. That every `.await` reached inside the span +//! sees the scope, including the engine's error mappers and the detached +//! restore, is tested in the storage crate (`request_scope`) and the engine +//! crate (`request_scope_log_tests`). + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::State; +use axum::http::HeaderMap; +use extenddb_auth::{AuthIdentity, AuthProvider}; +use extenddb_core::error::DynamoDbError; +use extenddb_storage::request_scope::{RequestScope, current}; +use tracing::{Event, Subscriber}; +use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + +use super::throttle_wire_tests::{build_state, build_state_with}; +use super::{MAX_SDK_HEADER_LEN, header_string, request_scope_for}; +use crate::AppState; + +/// Records the scope current on the task at two events: the engine's dispatch +/// entry (target `extenddb_engine::dispatch`, the last segment inside the +/// span) and the handler's `request complete` (the response segment, outside +/// the span). +#[derive(Default)] +struct ScopeAtEvents { + at_dispatch: Arc>>>, + at_complete: Arc>>>, +} + +impl Layer for ScopeAtEvents { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + if event.metadata().target() == "extenddb_engine::dispatch" { + self.at_dispatch.lock().unwrap().push(current()); + return; + } + let mut message = Message::default(); + event.record(&mut message); + if message.0 == "request complete" { + self.at_complete.lock().unwrap().push(current()); + } + } +} + +#[derive(Default)] +struct Message(String); + +impl tracing::field::Visit for Message { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.0 = format!("{value:?}"); + } + } +} + +/// An auth provider that records the scope current when it runs, then answers +/// with the default account like the fixture's stub. +struct ScopeAtAuth { + account_id: String, + seen: Arc>>>, +} + +#[async_trait::async_trait] +impl AuthProvider for ScopeAtAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + _body: &[u8], + ) -> Result { + self.seen.lock().unwrap().push(current()); + Ok(AuthIdentity::User { + account_id: self.account_id.clone(), + user_name: "dev".to_owned(), + }) + } +} + +const INVOCATION_ID: &str = "11111111-2222-3333-4444-555555555555"; +const SDK_REQUEST: &str = "attempt=2; max=4"; + +async fn fire( + state: Arc, + operation: &str, + body: &'static str, + extra: &[(&'static str, &str)], +) -> (u16, String) { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + format!("DynamoDB_20120810.{operation}") + .parse() + .expect("target header"), + ); + for (name, value) in extra { + headers.insert(*name, value.parse().expect("header value")); + } + let response = super::handle_request( + State(state), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40001))), + headers, + Ok(Bytes::from(body)), + ) + .await; + let status = response.status().as_u16(); + let request_id = response + .headers() + .get("x-amzn-requestid") + .and_then(|v| v.to_str().ok()) + .expect("response carries x-amzn-RequestId") + .to_owned(); + (status, request_id) +} + +fn expect_scope(seen: &Option, request_id: &str, operation: &str) { + let scope = seen + .as_ref() + .expect("the segment ran inside the request scope"); + assert_eq!(scope.request_id, request_id); + assert_eq!(scope.operation, operation); + assert_eq!(scope.sdk_invocation_id.as_deref(), Some(INVOCATION_ID)); + assert_eq!(scope.sdk_request.as_deref(), Some(SDK_REQUEST)); +} + +#[tokio::test] +async fn no_scope_on_the_task_before_the_request_or_after_the_response() { + assert_eq!(current(), None, "ambient scope before the request"); + let (state, _) = build_state().await; + let (status, _) = fire(state, "ListTables", "{}", &[]).await; + assert_eq!(status, 200); + assert_eq!(current(), None, "the scope leaked past the handler"); +} + +#[tokio::test] +async fn the_scope_is_current_when_the_auth_provider_runs() { + let seen = Arc::new(Mutex::new(Vec::new())); + let recorded = Arc::clone(&seen); + let (state, _) = build_state_with(move |account_id| { + Arc::new(ScopeAtAuth { + account_id, + seen: recorded, + }) + }) + .await; + + let (status, request_id) = fire( + state, + "ListTables", + "{}", + &[ + ("amz-sdk-invocation-id", INVOCATION_ID), + ("amz-sdk-request", SDK_REQUEST), + ], + ) + .await; + assert_eq!(status, 200); + + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 1, "one authenticate call per request"); + expect_scope(&seen[0], &request_id, "ListTables"); +} + +#[tokio::test] +async fn the_scope_is_current_at_dispatch_entry_and_gone_at_request_complete() { + let (state, _) = build_state().await; + let layer = ScopeAtEvents::default(); + let at_dispatch = Arc::clone(&layer.at_dispatch); + let at_complete = Arc::clone(&layer.at_complete); + let subscriber = tracing_subscriber::registry().with(layer); + let _guard = tracing::subscriber::set_default(subscriber); + + let (status, request_id) = fire( + state, + "ListTables", + "{}", + &[ + ("amz-sdk-invocation-id", INVOCATION_ID), + ("amz-sdk-request", SDK_REQUEST), + ], + ) + .await; + assert_eq!(status, 200); + + let at_dispatch = at_dispatch.lock().unwrap(); + assert_eq!(at_dispatch.len(), 1, "one dispatch entry event per request"); + expect_scope(&at_dispatch[0], &request_id, "ListTables"); + + // The response segment runs outside the span: the `request complete` + // event it writes sees no scope. + let at_complete = at_complete.lock().unwrap(); + assert_eq!( + at_complete.as_slice(), + &[None], + "the scope reached the response segment" + ); +} + +#[test] +fn the_scope_carries_the_request_id_operation_and_both_sdk_headers() { + let mut headers = HeaderMap::new(); + headers.insert( + "amz-sdk-invocation-id", + INVOCATION_ID.parse().expect("header value"), + ); + headers.insert( + "amz-sdk-request", + SDK_REQUEST.parse().expect("header value"), + ); + + let scope = request_scope_for("req-7c1d", "PutItem", &headers); + + assert_eq!(scope.request_id, "req-7c1d"); + assert_eq!(scope.operation, "PutItem"); + assert_eq!(scope.sdk_invocation_id.as_deref(), Some(INVOCATION_ID)); + assert_eq!(scope.sdk_request.as_deref(), Some(SDK_REQUEST)); +} + +#[test] +fn the_sdk_headers_are_absent_from_the_scope_when_the_client_sent_none() { + let scope = request_scope_for("req-9a0b", "Query", &HeaderMap::new()); + + assert_eq!(scope.request_id, "req-9a0b"); + assert_eq!(scope.operation, "Query"); + assert_eq!(scope.sdk_invocation_id, None); + assert_eq!(scope.sdk_request, None); +} + +#[test] +fn a_header_that_is_not_visible_ascii_reads_as_absent() { + let mut headers = HeaderMap::new(); + headers.insert( + "amz-sdk-request", + axum::http::HeaderValue::from_bytes(&[0xff, 0xfe]).expect("opaque header bytes"), + ); + // `HeaderValue::to_str` accepts visible ASCII only; UTF-8 above 0x7e is + // refused as well, so a value with an accented letter also reads as absent. + headers.insert( + "amz-sdk-invocation-id", + axum::http::HeaderValue::from_bytes("caf\u{e9}".as_bytes()).expect("utf8 header bytes"), + ); + assert_eq!(header_string(&headers, "amz-sdk-request"), None); + assert_eq!(header_string(&headers, "amz-sdk-invocation-id"), None); +} + +#[test] +fn a_header_longer_than_the_cap_reads_as_absent() { + let mut headers = HeaderMap::new(); + let at_cap = "a".repeat(MAX_SDK_HEADER_LEN); + let over_cap = "a".repeat(MAX_SDK_HEADER_LEN + 1); + headers.insert( + "amz-sdk-invocation-id", + at_cap.parse().expect("header value"), + ); + headers.insert("amz-sdk-request", over_cap.parse().expect("header value")); + assert_eq!( + header_string(&headers, "amz-sdk-invocation-id").as_deref(), + Some(at_cap.as_str()) + ); + assert_eq!(header_string(&headers, "amz-sdk-request"), None); +} diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index dc0b3772e..b4caeea02 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -54,7 +54,15 @@ fn cache_cfg(name: &'static str) -> extenddb_cache::SwrCacheConfig { /// catalog, the stub auth bound to the default account, throttling on, and /// `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) { +pub(super) async fn build_state() -> (Arc, String) { + build_state_with(|account_id| Arc::new(StubAuth { account_id })).await +} + +/// `build_state` with the auth provider built by `auth` from the bootstrapped +/// default account id, for a test that needs its own provider. +pub(super) async fn build_state_with( + auth: impl FnOnce(String) -> Arc, +) -> (Arc, String) { let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); let config = extenddb_storage_sqlite::SqliteConfig { path: ":memory:".to_owned(), @@ -98,9 +106,7 @@ async fn build_state() -> (Arc, String) { let state = Arc::new(AppState { storage: components.engine, - auth: Arc::new(StubAuth { - account_id: account_id.clone(), - }), + auth: auth(account_id.clone()), throttle, limits, region: Arc::from("us-east-1"), @@ -121,7 +127,7 @@ async fn build_state() -> (Arc, String) { (state, account_id) } -async fn call(state: &Arc, operation: &str, body: Value) -> (u16, Value) { +pub(super) async fn call(state: &Arc, operation: &str, body: Value) -> (u16, Value) { let mut headers = HeaderMap::new(); headers.insert( "x-amz-target", diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index c760583a6..e5e55959d 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -20,6 +20,7 @@ pub mod management_store; pub mod management_store_factory; pub mod operations; pub mod policy_migration; +pub mod request_scope; pub mod server_components; pub mod settings_store; pub mod transact; @@ -28,6 +29,7 @@ pub mod vector_lifecycle; pub use backend::{Backend, BackendAlreadySet, backend_name, set_backend, try_backend}; pub use backup_definition::{BackupRestoreSource, RestoreRequest, RestoreTableOverrides}; +pub use request_scope::RequestScope; pub use transact::{IdempotencyKey, TransactGetOp, TransactWriteOp}; diff --git a/crates/storage/src/request_scope.rs b/crates/storage/src/request_scope.rs new file mode 100644 index 000000000..78cc8a64d --- /dev/null +++ b/crates/storage/src/request_scope.rs @@ -0,0 +1,219 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Request-scoped correlation data for storage backends and the engine. +//! +//! The server sets a [`RequestScope`] from the start of authentication to the +//! end of dispatch for each client request. A storage backend or an engine +//! error mapper running inside that span reads it with [`current`] or +//! [`with_current`] to put the request id the client received in +//! `x-amzn-RequestId` on its own log lines. +//! +//! The scope is a Tokio task-local. It is visible to every `.await` reached +//! inline on the request's task, including nested and boxed futures. A task +//! started with `tokio::spawn` or `spawn_blocking` does not inherit it, so +//! [`current`] returns `None` there, as it does in queue workers, in tests and +//! in any task running outside a request. Code that spawns a task on behalf of +//! a request and wants the task's log lines correlated reads [`current`] +//! before the spawn and re-enters the scope inside it with +//! [`with_scope_opt`]. The engine makes its storage calls inline on the +//! request task, so a backend serving the request sees the scope. +//! +//! The two SDK fields are header values the client chose. Treat them as +//! untrusted text: write them to a log line if useful, never into a query, a +//! key or a file name. + +/// Correlation data for the client request a task is serving. +/// +/// Construct it with [`RequestScope::new`] and [`RequestScope::with_sdk_headers`]; +/// the struct may gain fields in a minor release. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct RequestScope { + /// The server's request id, the value returned to the client in + /// `x-amzn-RequestId`. + pub request_id: String, + /// The DynamoDB operation name from `X-Amz-Target`, for example `PutItem`. + pub operation: String, + /// `amz-sdk-invocation-id` when the client sent it. The AWS SDKs set one + /// value per call and resend it on each retry of that call. + pub sdk_invocation_id: Option, + /// `amz-sdk-request` when the client sent it. The AWS SDKs send their + /// attempt counter here, in the form `attempt=2; max=4`. + pub sdk_request: Option, +} + +impl RequestScope { + /// A scope for `request_id` and `operation` with no SDK headers. + #[must_use] + pub fn new(request_id: String, operation: String) -> Self { + Self { + request_id, + operation, + sdk_invocation_id: None, + sdk_request: None, + } + } + + /// The same scope with the two SDK correlation headers set. + #[must_use] + pub fn with_sdk_headers( + mut self, + sdk_invocation_id: Option, + sdk_request: Option, + ) -> Self { + self.sdk_invocation_id = sdk_invocation_id; + self.sdk_request = sdk_request; + self + } +} + +tokio::task_local! { + static SCOPE: RequestScope; +} + +/// Run `fut` with `scope` visible to every [`current`] and [`with_current`] +/// call made from inside it on the same task. +pub async fn with_scope(scope: RequestScope, fut: F) -> F::Output { + SCOPE.scope(scope, fut).await +} + +/// Run `fut` inside `scope` when there is one, plainly when there is none. +/// For a task spawned on behalf of a request: read [`current`] before the +/// spawn and pass it here inside the task. +pub async fn with_scope_opt( + scope: Option, + fut: F, +) -> F::Output { + match scope { + Some(scope) => SCOPE.scope(scope, fut).await, + None => fut.await, + } +} + +/// The scope of the request this task is serving, cloned, or `None` outside a +/// request (workers, tests, spawned tasks). +pub fn current() -> Option { + SCOPE.try_with(RequestScope::clone).ok() +} + +/// Borrow the scope without cloning and map it with `f`; `None` outside a +/// request. +pub fn with_current(f: impl FnOnce(&RequestScope) -> R) -> Option { + SCOPE.try_with(f).ok() +} + +/// The request id and operation of the current request, for a log line. Both +/// are `None` outside a request; `tracing` records nothing for a `None`, so a +/// line written from a worker carries neither field rather than a fabricated +/// value. +pub fn log_fields() -> (Option, Option) { + with_current(|s| (s.request_id.clone(), s.operation.clone())).unzip() +} + +#[cfg(test)] +mod tests { + use super::{RequestScope, current, log_fields, with_current, with_scope, with_scope_opt}; + + fn scope(request_id: &str) -> RequestScope { + RequestScope::new(request_id.to_owned(), "PutItem".to_owned()) + .with_sdk_headers(Some("inv-1".to_owned()), None) + } + + #[tokio::test] + async fn current_is_none_outside_a_scope() { + assert_eq!(current(), None); + assert_eq!(with_current(|s| s.request_id.clone()), None); + assert_eq!(log_fields(), (None, None)); + } + + #[tokio::test] + async fn current_is_some_and_equal_inside_a_scope() { + let expected = scope("req-eq"); + let seen = with_scope(expected.clone(), async { current() }).await; + assert_eq!(seen, Some(expected)); + } + + #[tokio::test] + async fn the_constructors_set_the_fields_they_name() { + let plain = RequestScope::new("req-c".to_owned(), "Query".to_owned()); + assert_eq!(plain.request_id, "req-c"); + assert_eq!(plain.operation, "Query"); + assert_eq!(plain.sdk_invocation_id, None); + assert_eq!(plain.sdk_request, None); + let full = + plain.with_sdk_headers(Some("inv".to_owned()), Some("attempt=1; max=3".to_owned())); + assert_eq!(full.sdk_invocation_id.as_deref(), Some("inv")); + assert_eq!(full.sdk_request.as_deref(), Some("attempt=1; max=3")); + } + + #[tokio::test] + async fn log_fields_carry_the_id_and_operation_inside_a_scope() { + let seen = with_scope(scope("req-log"), async { log_fields() }).await; + assert_eq!( + seen, + (Some("req-log".to_owned()), Some("PutItem".to_owned())) + ); + } + + #[tokio::test] + async fn visible_through_nested_awaits_and_a_boxed_future() { + async fn inner() -> Option { + tokio::task::yield_now().await; + with_current(|s| s.request_id.clone()) + } + let boxed: std::pin::Pin>>> = + Box::pin(inner()); + let seen = with_scope(scope("req-nested"), boxed).await; + assert_eq!(seen.as_deref(), Some("req-nested")); + } + + #[tokio::test] + async fn a_spawned_task_does_not_inherit_the_scope() { + let seen = with_scope(scope("req-spawn"), async { + tokio::spawn(async { current() }) + .await + .expect("spawned task joins") + }) + .await; + assert_eq!(seen, None); + } + + #[tokio::test] + async fn a_spawned_task_re_enters_the_scope_it_was_handed() { + let seen = with_scope(scope("req-carry"), async { + let carried = current(); + tokio::spawn(with_scope_opt(carried, async { current() })) + .await + .expect("spawned task joins") + }) + .await; + assert_eq!(seen, Some(scope("req-carry"))); + } + + #[tokio::test] + async fn with_scope_opt_without_a_scope_runs_plainly() { + let seen = with_scope_opt(None, async { current() }).await; + assert_eq!(seen, None); + } + + #[tokio::test] + async fn two_concurrent_scopes_each_see_their_own_value() { + async fn observe(id: &str) -> String { + // Yield between reads so the two futures interleave on the task. + let first = with_current(|s| s.request_id.clone()).expect("scope present"); + tokio::task::yield_now().await; + let second = with_current(|s| s.request_id.clone()).expect("scope present"); + assert_eq!(first, second, "scope stayed stable across the yield"); + assert_eq!(first, id); + first + } + let a = with_scope(scope("req-a"), observe("req-a")); + let b = with_scope(scope("req-b"), observe("req-b")); + let (ra, rb) = tokio::join!(a, b); + assert_eq!(ra, "req-a"); + assert_eq!(rb, "req-b"); + // Outside both scopes again. + assert_eq!(current(), None); + } +} From 8d8a5eeca07d295b44f942452030f2e481059bc0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 10:35:45 +0000 Subject: [PATCH 02/12] docs: describe the request scope for operators and backend authors Architecture guide: a Request scope subsection under Pluggable Architecture stating the span (authentication through dispatch), what the scope carries, where it is absent, that the detached restore carries it across, that the engine's fault lines carry request_id and operation from it and carry neither field outside a request, and the trace event at dispatch entry. Storage extension manual: a Request Correlation subsection under Design Constraints for New Backends: the accessors, what to put on a backend's own fault line, where the scope is absent and how a request-started task carries it, the two SDK fields as untrusted text, and construction through the constructors only. RFC-0003: criterion 10.4, request correlation, pointing at the manual. RFC-0002: RequestScope may gain fields in a minor release; backends construct it through RequestScope::new. --- docs/manuals/01-architecture-guide.md | 6 ++++++ docs/manuals/12-extending-extenddb-storage.md | 8 ++++++++ docs/rfcs/0002-backend-plugin-policy.md | 2 +- docs/rfcs/0003-backend-acceptance-criteria.md | 2 ++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index c709f3de5..352beb167 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -186,6 +186,12 @@ Storage backends implement thirteen traits (see **storage** section above). The Auth providers implement the `AuthProvider` trait using `#[async_trait]` for object safety. The provider is selected at startup and stored as `Arc`. The `BuiltinAuthProvider` uses a `CredentialStore` trait (also `#[async_trait]`) for credential lookup, with a database-backed implementation. +### Request scope + +The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`; the one request-started task in the engine, the detached restore of `RestoreTableFromBackup`, carries it across by hand. + +The engine's fault log lines (`storage internal error`, `backup storage error`, and the three create_table arms for a catalog or idempotency fault) carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. + ## Security Architecture ### Authentication diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index 7e0eb5ac8..af95fa052 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -392,6 +392,14 @@ Stream sequence numbers must be monotonically increasing within a shard. Your ba Account deletion must cascade to all child resources (users, groups, roles, policies, access keys, sessions) atomically. Your backend must provide equivalent cascade logic. +### Request Correlation + +The server sets `extenddb_storage::request_scope::RequestScope` around each client request, from authentication through dispatch. It holds the request id the client receives in `x-amzn-RequestId`, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A backend method running inline on the request task reads it with `request_scope::current()` (a clone) or `request_scope::with_current(|s| ...)` (a borrow). Put `s.request_id` on a log line the backend writes for a failure it is about to return as `StorageError::Internal`, `Connection` or `Transient`, so an operator can match the line to the client's request id. + +The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of visible ASCII; treat them as untrusted text and do not use them in a query, a key or a file name. + +Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own `storage internal error` and `backup storage error` lines already carry `request_id` and `operation`, so a backend that returns an error without logging still gets one correlated line. + ## PostgreSQL-isms in the Default Backend The PostgreSQL implementation makes backend-specific choices. These are implementation details inside `storage-postgres`, not leaks in the trait abstraction: diff --git a/docs/rfcs/0002-backend-plugin-policy.md b/docs/rfcs/0002-backend-plugin-policy.md index 409012146..f03985b47 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. 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. +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. Fields may be added to `RequestScope` in a minor release; a backend crate constructs it through `RequestScope::new`, never a struct literal. 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 f5dc37e96..a58db579f 100644 --- a/docs/rfcs/0003-backend-acceptance-criteria.md +++ b/docs/rfcs/0003-backend-acceptance-criteria.md @@ -135,6 +135,8 @@ If implementing pushdown, numeric comparisons must be numeric (not string-lexico **10.3. UpdateTable idempotency.** Repeated `UpdateTable` calls with the same specification must not corrupt state (duplicate shards, broken ARNs, phantom index entries). Either reject the redundant call with the appropriate error, or make it a no-op. +**10.4. Request correlation.** A log line the backend writes for a failure it returns as `StorageError::Internal`, `Connection` or `Transient` carries the request id from `extenddb_storage::request_scope` when one is current, so an operator can match the line to the `x-amzn-RequestId` the client received. See the Request Correlation section of the storage extension manual for the accessors and the cases where no scope is current. + ## Conformance Verification ### Required test suites From ca72ba136e524dbe46bb8ddaa28a9ba9d13695a4 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sun, 25 Oct 2026 11:48:09 +0000 Subject: [PATCH 03/12] test(server): register the scope probe's callsites before installing its subscriber the_scope_is_current_at_dispatch_entry_and_gone_at_request_complete failed about one run in three when run beside its sibling: while exactly one scoped subscriber exists, tracing computes a newly hit callsite's interest from the hitting thread's dispatcher, so the sibling's request, with no subscriber on its thread, cached the request complete callsite as skipped for the process. The test now fires one request before set_default so both callsites are registered, and set_default's rebuild computes them against the probe layer. Twenty runs of the pair, none failed; four to six of twelve before. --- crates/server/src/handler/request_scope_tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs index 129ee31fa..1ca13c402 100644 --- a/crates/server/src/handler/request_scope_tests.rs +++ b/crates/server/src/handler/request_scope_tests.rs @@ -174,6 +174,15 @@ async fn the_scope_is_current_when_the_auth_provider_runs() { #[tokio::test] async fn the_scope_is_current_at_dispatch_entry_and_gone_at_request_complete() { let (state, _) = build_state().await; + // Register the two callsites this test reads before the subscriber goes + // in. While exactly one scoped subscriber exists, `tracing` computes a + // newly hit callsite's interest from the hitting thread's own dispatcher, + // so a sibling test with no subscriber first-hitting `request complete` + // would cache it as skipped for the whole process. Hitting both here + // registers them; `set_default` then recomputes every registered callsite + // against this layer. + let (status, _) = fire(Arc::clone(&state), "ListTables", "{}", &[]).await; + assert_eq!(status, 200); let layer = ScopeAtEvents::default(); let at_dispatch = Arc::clone(&layer.at_dispatch); let at_complete = Arc::clone(&layer.at_complete); From 1fab11af57d9ea0c04869afe1c29653d86ed76c1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:45:21 +0000 Subject: [PATCH 04/12] test(engine): run the request scope log tests on the merged storage interfaces feat/partial-batch-throttle brings two changes from main that the request scope log tests did not build against. StorageError has no CatalogVersionMismatch or CatalogNotInitialized variant since the migration runner change, and create_table maps neither, so the two catalog sites leave the site list. BackupEngine is gone, and the detached restore takes a backup runtime and a storage that implements BackupCatalog, LegacyBackupReader, TableEngine, DataEngine and RestoreEngine. The detached restore test now uses the Fake of the backup tests, which implements those traits, and the runtime of those tests. The Fake answers the source read with the same internal fault as before. The backup tests module, Fake, its source_error field and runtime become pub(crate) for this. The test checks the same fault line as before. --- crates/engine/src/backup.rs | 2 +- crates/engine/src/backup/tests.rs | 6 +- crates/engine/src/request_scope_log_tests.rs | 111 +------------------ 3 files changed, 10 insertions(+), 109 deletions(-) diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index f95daf496..56f4f5dde 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -2195,7 +2195,7 @@ pub mod store_identity; pub mod store_maintenance; pub mod sync; #[cfg(test)] -mod tests; +pub(crate) mod tests; pub use pitr::refuse_before_authorization as refuse_point_in_time_recovery; pub(crate) use pitr::{ diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index 073fced63..0e1e632ef 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -57,7 +57,7 @@ fn source_arn() -> String { // --- double ----------------------------------------------------------------- #[derive(Default)] -struct Fake { +pub(crate) struct Fake { /// Cancelled by `list_dead_restore_jobs`: a token that fires in the /// middle of a cycle, after its store check. cancel_on_list_dead: Mutex>, @@ -66,7 +66,7 @@ struct Fake { summaries: Mutex>, restore_error: Mutex>, /// Returned (once) by `restore_source` instead of the stored source. - source_error: Mutex>, + pub(crate) source_error: Mutex>, restores: Mutex>, /// The permits the legacy restore and create were handed, held as the /// backend would hold them for the job's life. @@ -1009,7 +1009,7 @@ fn unused() -> BoxedFuture<'static, Result> } /// The runtime the tests run with: four slots, no configured store. -fn runtime() -> BackupRuntime { +pub(crate) fn runtime() -> BackupRuntime { BackupRuntime::new(4) } diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs index be3e304b2..69ea87221 100644 --- a/crates/engine/src/request_scope_log_tests.rs +++ b/crates/engine/src/request_scope_log_tests.rs @@ -109,23 +109,6 @@ fn sites() -> Vec { message: "storage internal error", target: "extenddb_engine::create_table", }, - Site { - name: "create_table::storage_err_to_dynamo, CatalogVersionMismatch", - error: || StorageError::CatalogVersionMismatch { - expected: "3".to_owned(), - found: "2".to_owned(), - }, - map: crate::create_table::storage_err_to_dynamo, - message: "Catalog version mismatch: expected 3, found 2", - target: "extenddb_engine::create_table", - }, - Site { - name: "create_table::storage_err_to_dynamo, CatalogNotInitialized", - error: || StorageError::CatalogNotInitialized, - map: crate::create_table::storage_err_to_dynamo, - message: "Catalog not initialized", - target: "extenddb_engine::create_table", - }, Site { name: "create_table::storage_err_to_dynamo, IdempotentReplay", error: || StorageError::IdempotentReplay, @@ -224,93 +207,6 @@ async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site( } } -/// A backup engine whose source lookup fails with a storage fault. The other -/// methods are never reached: the restore reads the source first. -struct FaultingBackups; - -impl extenddb_storage::BackupEngine for FaultingBackups { - fn create_backup( - &self, - _: &str, - _: &str, - _: &str, - ) -> extenddb_storage::BoxedFuture<'_, Result> - { - unreachable!("not reached by the restore") - } - fn describe_backup( - &self, - _: &str, - _: &str, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - unreachable!("not reached by the restore") - } - fn list_backups( - &self, - _: &str, - _: Option<&str>, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, StorageError>, - > { - unreachable!("not reached by the restore") - } - fn delete_backup( - &self, - _: &str, - _: &str, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - unreachable!("not reached by the restore") - } - fn backup_restore_source( - &self, - _: &str, - _: &str, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - Box::pin(async { Err(internal()) }) - } - fn restore_table_from_backup( - &self, - _: &str, - _: extenddb_storage::RestoreRequest, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - unreachable!("not reached by the restore") - } - fn describe_continuous_backups( - &self, - _: &str, - _: &str, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - unreachable!("not reached by the restore") - } - fn update_continuous_backups( - &self, - _: &str, - _: &str, - _: bool, - ) -> extenddb_storage::BoxedFuture< - '_, - Result, - > { - unreachable!("not reached by the restore") - } -} - /// `RestoreTableFromBackup` runs its restore in a task of its own. The task /// does not inherit the request scope, so the engine carries it across; the /// `backup storage error` line written inside the task names the request. @@ -321,6 +217,10 @@ async fn the_detached_restore_carries_the_scope_into_its_task() { "TargetTableName": "restored", }); let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); + // A backup engine whose source lookup fails with a storage fault. It has + // no catalog row for the ARN, so the restore reads the source next. + let backups = crate::backup::tests::Fake::default(); + *backups.source_error.lock().unwrap() = Some(internal()); let logged = with_scope( RequestScope::new( "req-restore".to_owned(), @@ -328,7 +228,8 @@ async fn the_detached_restore_carries_the_scope_into_its_task() { ), error_events_during_async(async { let result = crate::backup::restore_table_from_backup_detached( - Arc::new(FaultingBackups), + Arc::new(backups), + Arc::new(crate::backup::tests::runtime()), Arc::from("123456789012"), Arc::from("us-east-1"), limits, From 119d67cc52e766aa7d00f2531174198c0a33c3b3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:45:21 +0000 Subject: [PATCH 05/12] docs: name the one create_table fault arm that carries the request fields The architecture guide said that three create_table arms, for a catalog or an idempotency fault, carry request_id and operation. Main removed the two catalog errors with the migration runner change, so only the idempotency arm remains. The sentence now names that arm. --- docs/manuals/01-architecture-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index 21703a05c..a941fd2e3 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -226,7 +226,7 @@ Auth providers implement the `AuthProvider` trait using `#[async_trait]` for obj The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`; the one request-started task in the engine, the detached restore of `RestoreTableFromBackup`, carries it across by hand. -The engine's fault log lines (`storage internal error`, `backup storage error`, and the three create_table arms for a catalog or idempotency fault) carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. +The engine's fault log lines (`storage internal error`, `backup storage error`, and the create_table arm for an idempotency fault) carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. ## Security Architecture From 0a9e9cd1e6735cc0fb8f848df12e66ee1dc9abfb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:17:11 +0000 Subject: [PATCH 06/12] test: keep parallel tests from disabling the request scope test events The dispatch entry test in crates/server/src/handler/request_scope_tests.rs failed in 1 of 8 full runs of the server library tests. While the binary has one registered subscriber, tracing takes the interest of a newly hit callsite from the subscriber of the hitting thread. Tracing then caches that interest. A parallel test with no subscriber can hit the request complete event or the dispatch entry event first. That callsite then stays disabled, and the test sees no event. The test sent one request before it set its subscriber. That request registered neither callsite, because no other test in the binary enables DEBUG or TRACE. The test now registers a second subscriber in place of that request, as crates/server/src/authorization/arn_value_tests.rs does. With two registered subscribers, tracing computes the interest from all of them. With a parallel request forced into the window, the old test failed 2 of 2 runs and the new test passed 2 of 2. The new test passed 6 of 6 full runs. The engine helpers error_events_during and error_events_during_async get the same second subscriber. --- crates/engine/src/request_scope_log_tests.rs | 8 +++++++- crates/server/src/handler/request_scope_tests.rs | 16 +++++++--------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs index 69ea87221..36e7db12a 100644 --- a/crates/engine/src/request_scope_log_tests.rs +++ b/crates/engine/src/request_scope_log_tests.rs @@ -61,7 +61,11 @@ impl Layer for Captured { } /// Runs `f` under a fresh subscriber and returns every error event it logged. +/// A second registered subscriber makes `tracing` compute a newly hit +/// callsite's interest from every registered subscriber, so a parallel test +/// with none cannot leave an error callsite disabled for this one. fn error_events_during(f: impl FnOnce()) -> Vec { + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); let captured = Captured::default(); let events = Arc::clone(&captured.0); let subscriber = tracing_subscriber::registry().with(captured); @@ -70,8 +74,10 @@ fn error_events_during(f: impl FnOnce()) -> Vec { events.lock().unwrap().clone() } -/// Runs `fut` under a fresh subscriber and returns every error event it logged. +/// Runs `fut` under a fresh subscriber and returns every error event it +/// logged, with the second subscriber of [`error_events_during`]. async fn error_events_during_async(fut: F) -> Vec { + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); let captured = Captured::default(); let events = Arc::clone(&captured.0); let subscriber = tracing_subscriber::registry().with(captured); diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs index 1ca13c402..101b4b41c 100644 --- a/crates/server/src/handler/request_scope_tests.rs +++ b/crates/server/src/handler/request_scope_tests.rs @@ -174,15 +174,13 @@ async fn the_scope_is_current_when_the_auth_provider_runs() { #[tokio::test] async fn the_scope_is_current_at_dispatch_entry_and_gone_at_request_complete() { let (state, _) = build_state().await; - // Register the two callsites this test reads before the subscriber goes - // in. While exactly one scoped subscriber exists, `tracing` computes a - // newly hit callsite's interest from the hitting thread's own dispatcher, - // so a sibling test with no subscriber first-hitting `request complete` - // would cache it as skipped for the whole process. Hitting both here - // registers them; `set_default` then recomputes every registered callsite - // against this layer. - let (status, _) = fire(Arc::clone(&state), "ListTables", "{}", &[]).await; - assert_eq!(status, 200); + // While only one subscriber is registered, `tracing` computes a newly hit + // callsite's interest from the hitting thread's own subscriber and caches + // it, so a parallel test with none that first hits `request complete` or + // the dispatch entry event leaves it disabled for this test. A second + // registered subscriber makes `tracing` compute the interest from every + // registered subscriber, this test's included. + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); let layer = ScopeAtEvents::default(); let at_dispatch = Arc::clone(&layer.at_dispatch); let at_complete = Arc::clone(&layer.at_complete); From 0e39ea85e1af94c4f1001b5cfbf4e812ad3bf9eb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:17:11 +0000 Subject: [PATCH 07/12] docs: name the TTL index backfill as a task that runs without the request scope The architecture guide called the detached restore of RestoreTableFromBackup the one task that a request starts in the engine. UpdateTimeToLive also spawns a task when the backend reports Enabling: the TTL index backfill, which runs without the request scope. The guide now names both tasks. --- docs/manuals/01-architecture-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index a941fd2e3..025e7c61d 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -224,7 +224,7 @@ Auth providers implement the `AuthProvider` trait using `#[async_trait]` for obj ### Request scope -The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`; the one request-started task in the engine, the detached restore of `RestoreTableFromBackup`, carries it across by hand. +The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`. The detached restore of `RestoreTableFromBackup` carries it across by hand, and the TTL index backfill that `UpdateTimeToLive` spawns runs without it. The engine's fault log lines (`storage internal error`, `backup storage error`, and the create_table arm for an idempotency fault) carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. From ad5e11ade54ad5401c70433be9a2a3eddffec349 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:38:19 +0000 Subject: [PATCH 08/12] fix(engine): carry the request id on the 503 fault lines and the restore's store read line Four arms of the shared storage error mapper wrote their line with a plain tracing call, so the line had no request_id or operation. These are the AlreadyExists arm, which answers a redacted 500, and the Transient, SnapshotExpired and Connection arms, which answer a 503. The restore request reads the manifest and its checksum sidecar from the backup store, on the task the engine re-enters the scope for. When that read failed, its line had no request fields either, so the client's 500 could not be matched to the line. All five lines now go through log_storage_fault!. The macro gains a warn form, log_storage_fault!(warn, field = error, "message"), for the two lines that have always been warn level. Both keep their field names (transient_error, snapshot_error), their message text and their target. The error text of the restore's line moves from the message into the internal_error field, as on the other sites. The request scope log tests list the four arms with the status each answers and the level of its line. They capture warn events as well as error events. A new test runs RestoreTableFromBackup against a store that refuses every read under the backup's prefix. It checks that the one line names the request. The architecture guide and the storage extension manual name the lines that carry the fields. --- crates/engine/src/backup/restore.rs | 2 +- crates/engine/src/backup/tests.rs | 14 ++ crates/engine/src/create_table.rs | 8 +- crates/engine/src/fault_log.rs | 31 ++- crates/engine/src/request_scope_log_tests.rs | 196 +++++++++++++----- docs/manuals/01-architecture-guide.md | 2 +- docs/manuals/12-extending-extenddb-storage.md | 2 +- 7 files changed, 185 insertions(+), 70 deletions(-) diff --git a/crates/engine/src/backup/restore.rs b/crates/engine/src/backup/restore.rs index 31cfedd58..820d1d6f3 100644 --- a/crates/engine/src/backup/restore.rs +++ b/crates/engine/src/backup/restore.rs @@ -227,7 +227,7 @@ where if let Some(metrics) = runtime.metrics() { metrics.record_backup_store_error("get"); } - tracing::error!("backup {arn_text}: reading {name} from the store failed: {e}"); + log_storage_fault!(e, "backup {arn_text}: reading {name} from the store failed"); Err(DynamoDbError::InternalServerError( "Internal server error".to_owned(), )) diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index 0e1e632ef..d7b3d9da1 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -1822,6 +1822,20 @@ fn runtime_on(mem: &Arc, identity: StoreIdentity) -> BackupRuntime { )) } +/// A `RestoreTableFromBackup` whose backup row is AVAILABLE on the configured +/// store, and whose store refuses every read under the backup's prefix: the +/// request's read of the manifest's sidecar fails. The catalog, the runtime +/// and the request body. +pub(crate) fn restore_from_an_unreadable_store() -> (Arc, BackupRuntime, Value) { + let mem = Arc::new(MemStore::default()); + let fake = Arc::new(Fake::default()); + let runtime = runtime_on(&mem, store()); + let arn = arn(ACCOUNT); + seed_rows(&fake, &[row(&arn, BackupStatus::Available)]); + *mem.fail_gets_under.lock().unwrap() = Some(prefix_of(&arn)); + (fake, runtime, restore_body(json!({}))) +} + /// A runtime whose configured store (`store()`'s kind and root) failed its /// startup check with `problem`: the id is unknown. fn runtime_unhealthy(mem: &Arc, problem: StoreProblem) -> BackupRuntime { diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 111df207a..cb88f2764 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -154,7 +154,7 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo // Raised by the backup catalog's claim alone, whose caller handles // it; here it is a programming error, reported without the row. StorageError::AlreadyExists(msg) => { - tracing::error!(internal_error = %msg, "unexpected already-exists storage error"); + log_storage_fault!(msg, "unexpected already-exists storage error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } // The resource exists and the request is well formed; its current state @@ -166,21 +166,21 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo StorageError::LimitExceeded(msg) => DynamoDbError::LimitExceededException(msg), // Retryable by definition, so it maps like Connection: a 503 the SDKs // retry, rather than a 500 they surface. StorageError::Transient(msg) => { - tracing::warn!(transient_error = %msg, "transient storage error"); + log_storage_fault!(warn, transient_error = msg, "transient storage error"); DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned()) } // Only backup and export jobs hold snapshots; a request that reaches // this arm lost one mid-operation. The job owner restarts it; the // client sees the same retryable 503 as a transient fault. StorageError::SnapshotExpired(msg) => { - tracing::warn!(snapshot_error = %msg, "storage snapshot expired"); + log_storage_fault!(warn, snapshot_error = msg, "storage snapshot expired"); DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned()) } StorageError::DeletionProtected(arn) => DynamoDbError::ValidationException(format!( "Resource '{arn}' cannot be deleted as it is currently protected against deletion. Disable deletion protection first then try again." )), StorageError::Connection(msg) => { - tracing::error!(internal_error = %msg, "storage connection error"); + log_storage_fault!(msg, "storage connection error"); DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned()) } // Not a fault, so deliberately not logged at error level: the backend diff --git a/crates/engine/src/fault_log.rs b/crates/engine/src/fault_log.rs index 660fd310e..1a0b856dc 100644 --- a/crates/engine/src/fault_log.rs +++ b/crates/engine/src/fault_log.rs @@ -1,7 +1,8 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The log line for a storage fault the client sees as a redacted 500. +//! The log line for a storage fault the client sees as a redacted 500 or as +//! a retryable 503. //! //! `log_storage_fault!` expands at its call site, so the event keeps the //! site's own `target`, `module_path`, `file` and `line`; an operator who @@ -12,20 +13,32 @@ //! Outside a request both are `None`, and `tracing` records nothing for a //! `None`, so the line carries neither field. -/// Write an error-level event for a storage fault. +/// Write an event for a storage fault. /// -/// `log_storage_fault!(error, "message")` records `internal_error` from -/// `error` (by `Display`) with the message literal. The message may carry -/// format arguments: `log_storage_fault!(error, "catalog version mismatch: -/// expected {expected}, found {found}")`. +/// `log_storage_fault!(error, "message")` writes an error-level event that +/// records `internal_error` from `error` (by `Display`) with the message +/// literal. The message may carry format arguments: +/// `log_storage_fault!(error, "backup {arn_text}: reading {name} from the +/// store failed")`. +/// +/// `log_storage_fault!(warn, field = error, "message")` writes the same +/// event at warn level, with the error recorded under `field`: the form for +/// a fault the client sees as a 503 it retries, such as a transient error. macro_rules! log_storage_fault { - ($error:expr, $($message:tt)+) => {{ + (@event $level:expr, $field:ident, $error:expr, $($message:tt)+) => {{ let (request_id, operation) = extenddb_storage::request_scope::log_fields(); - tracing::error!( - internal_error = %$error, + tracing::event!( + $level, + $field = %$error, request_id = request_id.as_deref(), operation = operation.as_deref(), $($message)+ ); }}; + (warn, $field:ident = $error:expr, $($message:tt)+) => { + log_storage_fault!(@event tracing::Level::WARN, $field, $error, $($message)+) + }; + ($error:expr, $($message:tt)+) => { + log_storage_fault!(@event tracing::Level::ERROR, internal_error, $error, $($message)+) + }; } diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs index 36e7db12a..6f5d89a66 100644 --- a/crates/engine/src/request_scope_log_tests.rs +++ b/crates/engine/src/request_scope_log_tests.rs @@ -1,12 +1,14 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 //! The fault log line names the request it belongs to. Each engine mapping -//! arm that turns a `StorageError` into a redacted 500 writes the line through -//! `log_storage_fault!`, which reads the request id and operation from the -//! request scope the server sets around the request. Inside a scope the two -//! fields carry the request's values; outside one the line carries neither. -//! The macro expands at its call site, so each line keeps the site's own -//! target. The detached restore re-enters the scope in its spawned task. +//! arm that turns a `StorageError` into a redacted 500 or a retryable 503 +//! writes the line through `log_storage_fault!`, which reads the request id +//! and operation from the request scope the server sets around the request. +//! Inside a scope the two fields carry the request's values; outside one the +//! line carries neither. The macro expands at its call site, so each line +//! keeps the site's own target and level. The detached restore re-enters the +//! scope in its spawned task, so the store read its request makes there +//! names the request too. use std::sync::{Arc, Mutex}; @@ -17,15 +19,16 @@ use tracing::field::{Field, Visit}; use tracing::{Event, Level, Subscriber}; use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; -/// What the subscriber saw of one error-level event: the `request_id` and -/// `operation` fields (`None` when the field was not recorded), the message -/// and the event's static target. +/// What the subscriber saw of one error- or warn-level event: the +/// `request_id` and `operation` fields (`None` when the field was not +/// recorded), the message, the event's static target and its level. #[derive(Clone, Debug, Default, PartialEq, Eq)] struct Seen { request_id: Option, operation: Option, message: String, target: String, + level: String, } impl Visit for Seen { @@ -49,9 +52,10 @@ struct Captured(Arc>>); impl Layer for Captured { fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { - if *event.metadata().level() == Level::ERROR { + if *event.metadata().level() <= Level::WARN { let mut seen = Seen { target: event.metadata().target().to_owned(), + level: event.metadata().level().to_string(), ..Seen::default() }; event.record(&mut seen); @@ -60,8 +64,8 @@ impl Layer for Captured { } } -/// Runs `f` under a fresh subscriber and returns every error event it logged. -/// A second registered subscriber makes `tracing` compute a newly hit +/// Runs `f` under a fresh subscriber and returns every error and warn event +/// it logged. A second registered subscriber makes `tracing` compute a newly hit /// callsite's interest from every registered subscriber, so a parallel test /// with none cannot leave an error callsite disabled for this one. fn error_events_during(f: impl FnOnce()) -> Vec { @@ -74,8 +78,8 @@ fn error_events_during(f: impl FnOnce()) -> Vec { events.lock().unwrap().clone() } -/// Runs `fut` under a fresh subscriber and returns every error event it -/// logged, with the second subscriber of [`error_events_during`]. +/// Runs `fut` under a fresh subscriber and returns every error and warn +/// event it logged, with the second subscriber of [`error_events_during`]. async fn error_events_during_async(fut: F) -> Vec { let _second = tracing::Dispatch::new(tracing_subscriber::registry()); let captured = Captured::default(); @@ -91,13 +95,15 @@ fn scope() -> RequestScope { } /// A mapping arm: its name, the error that reaches it, the function, the -/// message text its line has always carried, and the target of the module -/// that owns the arm. +/// status the client gets, the message text and the level its line has +/// always carried, and the target of the module that owns the arm. struct Site { name: &'static str, error: fn() -> StorageError, map: fn(StorageError) -> DynamoDbError, + status: u16, message: &'static str, + level: &'static str, target: &'static str, } @@ -105,56 +111,107 @@ fn internal() -> StorageError { StorageError::Internal("driver text".to_owned()) } -/// Every engine arm that maps a `StorageError` to a redacted 500. +/// Every engine arm that maps a `StorageError` to a redacted 500 or to a +/// retryable 503 and logs the fault. fn sites() -> Vec { vec![ Site { name: "create_table::storage_err_to_dynamo, Internal", error: internal, map: crate::create_table::storage_err_to_dynamo, + status: 500, message: "storage internal error", + level: "ERROR", target: "extenddb_engine::create_table", }, Site { name: "create_table::storage_err_to_dynamo, IdempotentReplay", error: || StorageError::IdempotentReplay, map: crate::create_table::storage_err_to_dynamo, + status: 500, message: "Unexpected idempotency error in generic error handler", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, AlreadyExists", + error: || StorageError::AlreadyExists("row text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 500, + message: "unexpected already-exists storage error", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, Transient", + error: || StorageError::Transient("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "transient storage error", + level: "WARN", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, SnapshotExpired", + error: || StorageError::SnapshotExpired("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "storage snapshot expired", + level: "WARN", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, Connection", + error: || StorageError::Connection("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "storage connection error", + level: "ERROR", target: "extenddb_engine::create_table", }, Site { name: "backup::storage_err_to_dynamo", error: internal, map: crate::backup::storage_err_to_dynamo, + status: 500, message: "backup storage error", + level: "ERROR", target: "extenddb_engine::backup", }, Site { name: "update_table::update_table_err_to_dynamo", error: internal, map: |e| crate::update_table::update_table_err_to_dynamo(e, "t"), + status: 500, message: "storage internal error", + level: "ERROR", target: "extenddb_engine::update_table", }, Site { name: "streams::storage_to_dynamo", error: internal, map: crate::streams::storage_to_dynamo, + status: 500, message: "storage internal error", + level: "ERROR", target: "extenddb_engine::streams", }, Site { name: "ttl::storage_to_dynamo", error: internal, map: crate::ttl::storage_to_dynamo, + status: 500, message: "storage internal error", + level: "ERROR", target: "extenddb_engine::ttl", }, Site { name: "sanitize_storage_error", error: internal, map: crate::sanitize_storage_error, + status: 500, message: "storage internal error", + level: "ERROR", target: "extenddb_engine", }, ] @@ -166,11 +223,7 @@ async fn the_fault_line_names_the_request_inside_a_scope_at_every_site() { let logged = with_scope(scope(), async { error_events_during(|| { let err = (site.map)((site.error)()); - assert!( - matches!(err, DynamoDbError::InternalServerError(_)), - "{}", - site.name - ); + assert_eq!(err.status_code(), site.status, "{}", site.name); }) }) .await; @@ -181,6 +234,7 @@ async fn the_fault_line_names_the_request_inside_a_scope_at_every_site() { operation: Some("CreateTable".to_owned()), message: site.message.to_owned(), target: site.target.to_owned(), + level: site.level.to_owned(), }], "{}: the fault line did not carry the scope's request id and operation", site.name @@ -193,11 +247,7 @@ async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site( for site in sites() { let logged = error_events_during(|| { let err = (site.map)((site.error)()); - assert!( - matches!(err, DynamoDbError::InternalServerError(_)), - "{}", - site.name - ); + assert_eq!(err.status_code(), site.status, "{}", site.name); }); assert_eq!( logged, @@ -206,6 +256,7 @@ async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site( operation: None, message: site.message.to_owned(), target: site.target.to_owned(), + level: site.level.to_owned(), }], "{}: a fault outside a request carried a request id or operation", site.name @@ -213,6 +264,35 @@ async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site( } } +/// Runs `RestoreTableFromBackup` through its detached entry point inside a +/// scope for `request_id`, checks that the client gets a redacted 500, and +/// returns the error and warn lines written meanwhile. +async fn detached_restore_fault_lines( + backups: Arc, + runtime: crate::backup::BackupRuntime, + body: serde_json::Value, + request_id: &str, +) -> Vec { + let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); + with_scope( + RequestScope::new(request_id.to_owned(), "RestoreTableFromBackup".to_owned()), + error_events_during_async(async { + let result = crate::backup::restore_table_from_backup_detached( + backups, + Arc::new(runtime), + Arc::from("123456789012"), + Arc::from("us-east-1"), + limits, + body, + |_, _| async {}, + ) + .await; + assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); + }), + ) + .await +} + /// `RestoreTableFromBackup` runs its restore in a task of its own. The task /// does not inherit the request scope, so the engine carries it across; the /// `backup storage error` line written inside the task names the request. @@ -222,41 +302,49 @@ async fn the_detached_restore_carries_the_scope_into_its_task() { "BackupArn": "arn:aws:dynamodb:us-east-1:123456789012:table/src/backup/01700000000000-abcdef12", "TargetTableName": "restored", }); - let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); // A backup engine whose source lookup fails with a storage fault. It has // no catalog row for the ARN, so the restore reads the source next. let backups = crate::backup::tests::Fake::default(); *backups.source_error.lock().unwrap() = Some(internal()); - let logged = with_scope( - RequestScope::new( - "req-restore".to_owned(), - "RestoreTableFromBackup".to_owned(), - ), - error_events_during_async(async { - let result = crate::backup::restore_table_from_backup_detached( - Arc::new(backups), - Arc::new(crate::backup::tests::runtime()), - Arc::from("123456789012"), - Arc::from("us-east-1"), - limits, - body, - |_, _| async {}, - ) - .await; - assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); - }), + let logged = detached_restore_fault_lines( + Arc::new(backups), + crate::backup::tests::runtime(), + body, + "req-restore", ) .await; assert_eq!( - logged.len(), - 1, - "one fault line for the failed source lookup" + logged, + vec![Seen { + request_id: Some("req-restore".to_owned()), + operation: Some("RestoreTableFromBackup".to_owned()), + message: "backup storage error".to_owned(), + target: "extenddb_engine::backup".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the failed source lookup, naming the request" ); - assert_eq!(logged[0].request_id.as_deref(), Some("req-restore")); +} + +/// Inside the same task, the restore request reads the manifest's checksum +/// sidecar and the manifest from the backup store. A read that fails answers +/// the client a redacted 500, and its line names the request. +#[tokio::test] +async fn the_restore_tasks_failed_store_read_names_the_request() { + let (backups, runtime, body) = crate::backup::tests::restore_from_an_unreadable_store(); + let logged = detached_restore_fault_lines(backups, runtime, body, "req-store").await; assert_eq!( - logged[0].operation.as_deref(), - Some("RestoreTableFromBackup") + logged, + vec![Seen { + request_id: Some("req-store".to_owned()), + operation: Some("RestoreTableFromBackup".to_owned()), + message: "backup arn:aws:dynamodb:us-east-1:123456789012:table/Music/backup/\ + 01791976431438-73d8d5bc: reading extenddb-manifest.sha256 from the store \ + failed" + .to_owned(), + target: "extenddb_engine::backup::restore".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the failed store read, naming the request" ); - assert_eq!(logged[0].message, "backup storage error"); - assert_eq!(logged[0].target, "extenddb_engine::backup"); } diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index 025e7c61d..a3eabd255 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -226,7 +226,7 @@ Auth providers implement the `AuthProvider` trait using `#[async_trait]` for obj The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`. The detached restore of `RestoreTableFromBackup` carries it across by hand, and the TTL index backfill that `UpdateTimeToLive` spawns runs without it. -The engine's fault log lines (`storage internal error`, `backup storage error`, and the create_table arm for an idempotency fault) carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. +The engine's fault log lines carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received: `storage internal error` and `backup storage error`, the shared error mapper's lines for an unexpected already-exists error, an idempotency fault, a transient error, an expired snapshot and a connection error, and the restore's line for a backup store read that fails. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. ## Security Architecture diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index f13d44e6f..97a8a574b 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -433,7 +433,7 @@ The server sets `extenddb_storage::request_scope::RequestScope` around each clie The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of visible ASCII; treat them as untrusted text and do not use them in a query, a key or a file name. -Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own `storage internal error` and `backup storage error` lines already carry `request_id` and `operation`, so a backend that returns an error without logging still gets one correlated line. +Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own fault lines carry `request_id` and `operation`: `storage internal error` and `backup storage error`, the `storage connection error` and `transient storage error` lines of the shared error mapper, and the line for a backup store read that fails during a restore. A backend that returns `Internal`, `Connection` or `Transient` without logging still gets one correlated line. ## PostgreSQL-isms in the Default Backend From e30d83b7765f5e5c03bb39f3de08abc5def7d39b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:41:43 +0000 Subject: [PATCH 09/12] docs: state what the request scope's header values and task coverage are The header rule said that a value that is not visible ASCII reads as absent. HeaderValue::to_str accepts printable ASCII (space through tilde) and tab, so "a\tb c" reads as present. The handler doc, the header test's comment and the storage extension manual now say so. The test checks that a value with a tab and a space reads as sent. A header value cannot hold CR or LF, so a value that reads as present cannot split a log line. The SDKs' own form of amz-sdk-request holds spaces, so a rule that refused spaces would read every SDK's header as absent. The amz-sdk-request doc gave the form `attempt=2; max=4`. botocore 1.43 writes ttl, attempt and max joined by `"; "`, with ttl present on each attempt that follows a response. That is `attempt=1; max=3` on the first attempt and `ttl=20261124T190559Z; attempt=2; max=3` on a retry. The doc gives both. The request scope module doc said that the engine makes its storage calls inline on the request task. The backup and restore jobs call storage from tasks of their own, without the scope, and so does the TTL index backfill that UpdateTimeToLive spawns. The detached restore re-enters the scope. The doc names these tasks, as the architecture guide does. The handler's module doc claimed a 500-line limit that no document or check in the repository states. The commit removes the sentence. --- crates/server/src/handler.rs | 6 +++--- crates/server/src/handler/request_scope_tests.rs | 12 ++++++++++-- crates/storage/src/request_scope.rs | 12 +++++++++--- docs/manuals/12-extending-extenddb-storage.md | 2 +- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 82b5076e5..e7c0cf87a 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -2,8 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 //! Main `DynamoDB` request handler with per-segment latency instrumentation. -//! -//! Extracted from `lib.rs` to keep both files under the 500-line limit. use std::sync::Arc; @@ -532,7 +530,9 @@ fn request_scope_for( const MAX_SDK_HEADER_LEN: usize = 256; /// The value of header `name` as an owned string, or `None` when the header is -/// absent, is not visible ASCII, or is longer than [`MAX_SDK_HEADER_LEN`]. +/// absent, holds a byte outside printable ASCII (space through tilde) and tab, +/// or is longer than [`MAX_SDK_HEADER_LEN`]. A header value cannot hold CR or +/// LF, so a value that reads as present cannot split a log line. fn header_string(headers: &HeaderMap, name: &str) -> Option { headers .get(name) diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs index 101b4b41c..0145eefa7 100644 --- a/crates/server/src/handler/request_scope_tests.rs +++ b/crates/server/src/handler/request_scope_tests.rs @@ -250,14 +250,22 @@ fn a_header_that_is_not_visible_ascii_reads_as_absent() { "amz-sdk-request", axum::http::HeaderValue::from_bytes(&[0xff, 0xfe]).expect("opaque header bytes"), ); - // `HeaderValue::to_str` accepts visible ASCII only; UTF-8 above 0x7e is - // refused as well, so a value with an accented letter also reads as absent. + // `HeaderValue::to_str` accepts printable ASCII (space through tilde) and + // tab only; a byte above 0x7e is refused, so a value with an accented + // letter also reads as absent. headers.insert( "amz-sdk-invocation-id", axum::http::HeaderValue::from_bytes("caf\u{e9}".as_bytes()).expect("utf8 header bytes"), ); assert_eq!(header_string(&headers, "amz-sdk-request"), None); assert_eq!(header_string(&headers, "amz-sdk-invocation-id"), None); + // A space and a tab are within what `to_str` accepts, so the value reads + // as sent. + headers.insert("amz-sdk-request", "a\tb c".parse().expect("header value")); + assert_eq!( + header_string(&headers, "amz-sdk-request").as_deref(), + Some("a\tb c") + ); } #[test] diff --git a/crates/storage/src/request_scope.rs b/crates/storage/src/request_scope.rs index 78cc8a64d..e186359e3 100644 --- a/crates/storage/src/request_scope.rs +++ b/crates/storage/src/request_scope.rs @@ -16,8 +16,12 @@ //! in any task running outside a request. Code that spawns a task on behalf of //! a request and wants the task's log lines correlated reads [`current`] //! before the spawn and re-enters the scope inside it with -//! [`with_scope_opt`]. The engine makes its storage calls inline on the -//! request task, so a backend serving the request sees the scope. +//! [`with_scope_opt`]. The engine makes most of its storage calls inline on +//! the request task, so a backend serving the request sees the scope. The +//! calls made from a task the request starts do not see it, except in the +//! detached restore of `RestoreTableFromBackup`, which re-enters the scope: +//! the backup and restore jobs and the TTL index backfill that +//! `UpdateTimeToLive` spawns on a backend reporting ENABLING run without it. //! //! The two SDK fields are header values the client chose. Treat them as //! untrusted text: write them to a log line if useful, never into a query, a @@ -39,7 +43,9 @@ pub struct RequestScope { /// value per call and resend it on each retry of that call. pub sdk_invocation_id: Option, /// `amz-sdk-request` when the client sent it. The AWS SDKs send their - /// attempt counter here, in the form `attempt=2; max=4`. + /// attempt counter here: `attempt=1; max=3` on the first attempt, and on + /// a retry a `ttl` field first, `ttl=20261124T190559Z; attempt=2; max=3`, + /// the time after which the client no longer waits for the answer. pub sdk_request: Option, } diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index 97a8a574b..314f2171e 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -431,7 +431,7 @@ runs it. The server sets `extenddb_storage::request_scope::RequestScope` around each client request, from authentication through dispatch. It holds the request id the client receives in `x-amzn-RequestId`, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A backend method running inline on the request task reads it with `request_scope::current()` (a clone) or `request_scope::with_current(|s| ...)` (a borrow). Put `s.request_id` on a log line the backend writes for a failure it is about to return as `StorageError::Internal`, `Connection` or `Transient`, so an operator can match the line to the client's request id. -The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of visible ASCII; treat them as untrusted text and do not use them in a query, a key or a file name. +The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of printable ASCII (space through tilde) or tab, which cannot hold a line break; treat them as untrusted text and do not use them in a query, a key or a file name. Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own fault lines carry `request_id` and `operation`: `storage internal error` and `backup storage error`, the `storage connection error` and `transient storage error` lines of the shared error mapper, and the line for a backup store read that fails during a restore. A backend that returns `Internal`, `Connection` or `Transient` without logging still gets one correlated line. From 3b3116f920631aa6087b71cf639317ad93fea487 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:07:14 +0000 Subject: [PATCH 10/12] fix(engine): carry the request id on DeleteBackup's catalog read line and BatchWriteItem's unapplied line Two more lines answered a storage fault without the request id. DeleteBackup answers a redacted 500 when the deletion fence cannot read the catalog's id, and wrote its line with a plain error call. BatchWriteItem answers 503 when a Connection or Transient error leaves no request applied, and its one line, at warn level, carried no request fields either. Both lines go through log_storage_fault!. The DeleteBackup line moves the error text from the message into the internal_error field, as on the other sites. The BatchWriteItem line uses the warn form and keeps its fields applied, not_applied and last_error. The macro's doc names the lines that use the warn form and says that more fields may follow the error. Two tests cover the lines: a DeleteBackup against a catalog whose id cannot be read, and a batch whose first write meets a connection error. Both run through one runner, which the detached restore test uses as well. The batch fixture is the one the deferral test for that 503 now uses too. The storage manual, the request scope module doc and the architecture guide name the two lines. They also say that a store-backed CreateBackup and the registration of RestoreTableFromBackup answer the request from a job task that runs without the scope. The amz-sdk-request doc states the ttl rule as botocore's: the field appears once the client has received a response. --- crates/engine/src/backup.rs | 5 +- crates/engine/src/backup/tests.rs | 15 +++ crates/engine/src/batch_write_item.rs | 7 +- .../engine/src/batch_write_item/scripted.rs | 12 +++ .../write_batch_deferral_tests.rs | 9 +- crates/engine/src/fault_log.rs | 4 +- crates/engine/src/request_scope_log_tests.rs | 102 +++++++++++++++--- crates/storage/src/request_scope.rs | 20 ++-- docs/manuals/01-architecture-guide.md | 4 +- docs/manuals/12-extending-extenddb-storage.md | 2 +- 10 files changed, 141 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 56f4f5dde..ef0412809 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -1386,7 +1386,10 @@ async fn delete_catalog_backup( return Err(refusal); } if let StoreProblem::Catalog(e) = &problem { - tracing::error!("DeleteBackup {arn_text}: the catalog id could not be read: {e}"); + log_storage_fault!( + e, + "DeleteBackup {arn_text}: the catalog id could not be read" + ); return Err(DynamoDbError::InternalServerError( "Internal server error".to_owned(), )); diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index d7b3d9da1..2420c8882 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -1836,6 +1836,21 @@ pub(crate) fn restore_from_an_unreadable_store() -> (Arc, BackupRuntime, V (fake, runtime, restore_body(json!({}))) } +/// A `DeleteBackup` of a backup whose row is AVAILABLE on the configured +/// store, run against a catalog whose id cannot be read, so the deletion +/// fence fails before the DELETING write: the client's error. +pub(crate) async fn delete_backup_with_an_unreadable_catalog() -> DynamoDbError { + let mem = Arc::new(MemStore::default()); + let fake = Arc::new(Fake::default()); + let runtime = runtime_on(&mem, store()); + let arn = arn(ACCOUNT); + seed_rows(&fake, &[row(&arn, BackupStatus::Available)]); + *fake.catalog_id_error.lock().unwrap() = true; + delete_backup(&*fake, &runtime, ACCOUNT, REGION, &own(&arn)) + .await + .unwrap_err() +} + /// A runtime whose configured store (`store()`'s kind and root) failed its /// startup check with `problem`: the id is unknown. fn runtime_unhealthy(mem: &Arc, problem: StoreProblem) -> BackupRuntime { diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index 07f57d5ba..50787411b 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -353,10 +353,11 @@ async fn write_batch( } else { "they are returned in UnprocessedItems" }; - tracing::warn!( + log_storage_fault!( + warn, + last_error = last_error, applied, not_applied, - last_error = %last_error, "BatchWriteItem: {not_applied} request(s) of the batch not applied; {outcome}" ); if applied == 0 { @@ -626,7 +627,7 @@ fn collect_icm_if_needed( } #[cfg(test)] -mod scripted; +pub(crate) mod scripted; #[cfg(test)] mod write_batch_deferral_tests; #[cfg(test)] diff --git a/crates/engine/src/batch_write_item/scripted.rs b/crates/engine/src/batch_write_item/scripted.rs index 687be8981..8eedc0720 100644 --- a/crates/engine/src/batch_write_item/scripted.rs +++ b/crates/engine/src/batch_write_item/scripted.rs @@ -256,6 +256,18 @@ pub(super) fn rejected(result: Result) -> DynamoD } } +/// A batch of two puts whose first write fails with a connection error, so +/// nothing is applied and the batch is rejected: the client's error and the +/// `table/pk` of the writes the double received. +pub(crate) async fn batch_that_applies_nothing_after_a_connection_error() +-> (DynamoDbError, Vec) { + let down = StorageError::Connection("refused".to_owned()); + let data = Scripted::new(vec![Err(down)]); + let items = json!({"t": [put("a"), put("b")]}); + let err = rejected(run(&data, items, &["t"], found(&["t"])).await); + (err, data.writes()) +} + /// The body of a batch that must have been answered with a 200. pub(super) fn answered(result: Result) -> DispatchResult { result.unwrap_or_else(|e| panic!("the batch must answer 200: {e:?}")) 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 5a190d8e7..cbec6935f 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 @@ -120,14 +120,11 @@ async fn a_connection_error_leaves_the_rest_of_the_batch_unattempted() { /// A connection error with nothing applied answers 503 after one attempt. #[tokio::test] async fn a_connection_error_with_nothing_applied_answers_503_after_one_attempt() { - let down = StorageError::Connection("refused".to_owned()); - let data = Scripted::new(vec![Err(down)]); - let items = json!({"t": [put("a"), put("b")]}); - - let err = rejected(run(&data, items, &["t"], found(&["t"])).await); + let (err, writes) = + super::scripted::batch_that_applies_nothing_after_a_connection_error().await; assert_eq!(err.status_code(), 503, "{err:?}"); - assert_eq!(data.writes(), ["t/a"]); + assert_eq!(writes, ["t/a"]); } /// An error a replay would not clear fails the batch with 500, also after an diff --git a/crates/engine/src/fault_log.rs b/crates/engine/src/fault_log.rs index 1a0b856dc..b0c2e6119 100644 --- a/crates/engine/src/fault_log.rs +++ b/crates/engine/src/fault_log.rs @@ -23,7 +23,9 @@ /// /// `log_storage_fault!(warn, field = error, "message")` writes the same /// event at warn level, with the error recorded under `field`: the form for -/// a fault the client sees as a 503 it retries, such as a transient error. +/// the lines that have always been warn level, the transient error, the +/// expired snapshot and the BatchWriteItem line for the requests a batch did +/// not apply. More fields may follow the error, before the message. macro_rules! log_storage_fault { (@event $level:expr, $field:ident, $error:expr, $($message:tt)+) => {{ let (request_id, operation) = extenddb_storage::request_scope::log_fields(); diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs index 6f5d89a66..17bf52bea 100644 --- a/crates/engine/src/request_scope_log_tests.rs +++ b/crates/engine/src/request_scope_log_tests.rs @@ -8,7 +8,9 @@ //! line carries neither. The macro expands at its call site, so each line //! keeps the site's own target and level. The detached restore re-enters the //! scope in its spawned task, so the store read its request makes there -//! names the request too. +//! names the request too. DeleteBackup's line for a catalog id that cannot +//! be read and BatchWriteItem's line for the requests a batch did not apply +//! go through the macro as well. use std::sync::{Arc, Mutex}; @@ -264,6 +266,20 @@ async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site( } } +/// Runs `fut` inside a scope for `request_id` and `operation` under a fresh +/// subscriber and returns the error and warn lines written meanwhile. +async fn scoped_fault_lines( + request_id: &str, + operation: &str, + fut: F, +) -> Vec { + with_scope( + RequestScope::new(request_id.to_owned(), operation.to_owned()), + error_events_during_async(fut), + ) + .await +} + /// Runs `RestoreTableFromBackup` through its detached entry point inside a /// scope for `request_id`, checks that the client gets a redacted 500, and /// returns the error and warn lines written meanwhile. @@ -274,22 +290,19 @@ async fn detached_restore_fault_lines( request_id: &str, ) -> Vec { let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); - with_scope( - RequestScope::new(request_id.to_owned(), "RestoreTableFromBackup".to_owned()), - error_events_during_async(async { - let result = crate::backup::restore_table_from_backup_detached( - backups, - Arc::new(runtime), - Arc::from("123456789012"), - Arc::from("us-east-1"), - limits, - body, - |_, _| async {}, - ) - .await; - assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); - }), - ) + scoped_fault_lines(request_id, "RestoreTableFromBackup", async { + let result = crate::backup::restore_table_from_backup_detached( + backups, + Arc::new(runtime), + Arc::from("123456789012"), + Arc::from("us-east-1"), + limits, + body, + |_, _| async {}, + ) + .await; + assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); + }) .await } @@ -348,3 +361,58 @@ async fn the_restore_tasks_failed_store_read_names_the_request() { "one fault line for the failed store read, naming the request" ); } + +/// DeleteBackup runs its deletion fence on the request task. When the +/// catalog's id cannot be read, the client gets a redacted 500 and the line +/// names the request. +#[tokio::test] +async fn the_delete_backup_line_for_an_unreadable_catalog_names_the_request() { + let logged = scoped_fault_lines("req-delete", "DeleteBackup", async { + let err = crate::backup::tests::delete_backup_with_an_unreadable_catalog().await; + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{err:?}" + ); + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-delete".to_owned()), + operation: Some("DeleteBackup".to_owned()), + message: "DeleteBackup arn:aws:dynamodb:us-east-1:123456789012:table/Music/backup/\ + 01791976431438-73d8d5bc: the catalog id could not be read" + .to_owned(), + target: "extenddb_engine::backup".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the catalog id that could not be read, naming the request" + ); +} + +/// A BatchWriteItem whose first write meets a connection error applies +/// nothing and answers 503. Its one line, at warn level, names the request. +#[tokio::test] +async fn the_batch_write_item_line_for_a_batch_that_applied_nothing_names_the_request() { + let logged = scoped_fault_lines("req-batch", "BatchWriteItem", async { + let (err, _) = + crate::batch_write_item::scripted::batch_that_applies_nothing_after_a_connection_error( + ) + .await; + assert_eq!(err.status_code(), 503, "{err:?}"); + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-batch".to_owned()), + operation: Some("BatchWriteItem".to_owned()), + message: "BatchWriteItem: 2 request(s) of the batch not applied; no request applied \ + and the batch answers 503" + .to_owned(), + target: "extenddb_engine::batch_write_item".to_owned(), + level: "WARN".to_owned(), + }], + "one warn line for the batch that applied nothing, naming the request" + ); +} diff --git a/crates/storage/src/request_scope.rs b/crates/storage/src/request_scope.rs index e186359e3..57ce390b6 100644 --- a/crates/storage/src/request_scope.rs +++ b/crates/storage/src/request_scope.rs @@ -17,11 +17,14 @@ //! a request and wants the task's log lines correlated reads [`current`] //! before the spawn and re-enters the scope inside it with //! [`with_scope_opt`]. The engine makes most of its storage calls inline on -//! the request task, so a backend serving the request sees the scope. The -//! calls made from a task the request starts do not see it, except in the -//! detached restore of `RestoreTableFromBackup`, which re-enters the scope: -//! the backup and restore jobs and the TTL index backfill that -//! `UpdateTimeToLive` spawns on a backend reporting ENABLING run without it. +//! the request task, so a backend serving the request sees the scope. A task +//! the request starts does not see it unless the engine carries it in: the +//! detached restore of `RestoreTableFromBackup` re-enters the scope. The job +//! tasks of a store-backed `CreateBackup` and of `RestoreTableFromBackup`'s +//! registration answer the request from a task without the scope, so a +//! storage fault there carries no request id. The backup and restore jobs +//! after the answer and the TTL index backfill that `UpdateTimeToLive` +//! spawns on a backend reporting ENABLING run without it as well. //! //! The two SDK fields are header values the client chose. Treat them as //! untrusted text: write them to a log line if useful, never into a query, a @@ -43,9 +46,10 @@ pub struct RequestScope { /// value per call and resend it on each retry of that call. pub sdk_invocation_id: Option, /// `amz-sdk-request` when the client sent it. The AWS SDKs send their - /// attempt counter here: `attempt=1; max=3` on the first attempt, and on - /// a retry a `ttl` field first, `ttl=20261124T190559Z; attempt=2; max=3`, - /// the time after which the client no longer waits for the answer. + /// attempt counter here, as in `attempt=1; max=3`. Once botocore has + /// received a response, it puts a `ttl` field first, as in + /// `ttl=20261124T190559Z; attempt=2; max=3`: the time after which the + /// client no longer waits for the answer. pub sdk_request: Option, } diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index a3eabd255..70d3ce61a 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -224,9 +224,9 @@ Auth providers implement the `AuthProvider` trait using `#[async_trait]` for obj ### Request scope -The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`. The detached restore of `RestoreTableFromBackup` carries it across by hand, and the TTL index backfill that `UpdateTimeToLive` spawns runs without it. +The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`. The detached restore of `RestoreTableFromBackup` carries it across by hand. The job tasks of a store-backed `CreateBackup` and of `RestoreTableFromBackup`'s registration answer the request from a task without it, and the TTL index backfill that `UpdateTimeToLive` spawns runs without it. -The engine's fault log lines carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received: `storage internal error` and `backup storage error`, the shared error mapper's lines for an unexpected already-exists error, an idempotency fault, a transient error, an expired snapshot and a connection error, and the restore's line for a backup store read that fails. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. +The engine's fault log lines carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received: `storage internal error` and `backup storage error`, the shared error mapper's lines for an unexpected already-exists error, an idempotency fault, a transient error, an expired snapshot and a connection error, the restore's line for a backup store read that fails, DeleteBackup's line for a catalog id that cannot be read and the BatchWriteItem line for the requests a batch did not apply. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. ## Security Architecture diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index 314f2171e..db28888b4 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -433,7 +433,7 @@ The server sets `extenddb_storage::request_scope::RequestScope` around each clie The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of printable ASCII (space through tilde) or tab, which cannot hold a line break; treat them as untrusted text and do not use them in a query, a key or a file name. -Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own fault lines carry `request_id` and `operation`: `storage internal error` and `backup storage error`, the `storage connection error` and `transient storage error` lines of the shared error mapper, and the line for a backup store read that fails during a restore. A backend that returns `Internal`, `Connection` or `Transient` without logging still gets one correlated line. +Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own fault lines carry `request_id` and `operation`: `storage internal error` and `backup storage error`, the `storage connection error` and `transient storage error` lines of the shared error mapper, the line for a backup store read that fails during a restore, DeleteBackup's line for a catalog id that cannot be read, and the BatchWriteItem line for the requests a batch did not apply. A backend that returns `Internal`, `Connection` or `Transient` without logging gets one correlated line, except where the engine answers from a task without the scope: a store-backed CreateBackup, and the registration of RestoreTableFromBackup. ## PostgreSQL-isms in the Default Backend From ca2692999298043002bf68c7bf3284c7aa0fbf9d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:59:41 +0000 Subject: [PATCH 11/12] test(engine): name the backup mapper by the module the merge moved it to The merge of feat/partial-batch-throttle brings main's move of the backup mapper storage_err_to_dynamo out of backup.rs into backup_requests.rs. The request scope log test still named the mapper and its event target by the old module. The engine's test build failed on a private import. The test's site table and the restore test now name backup_requests, and the log_storage_fault! module doc names the same module in its example of a target filter. --- crates/engine/src/fault_log.rs | 13 +++++++------ crates/engine/src/request_scope_log_tests.rs | 8 ++++---- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/fault_log.rs b/crates/engine/src/fault_log.rs index b0c2e6119..ee7e018f7 100644 --- a/crates/engine/src/fault_log.rs +++ b/crates/engine/src/fault_log.rs @@ -6,12 +6,13 @@ //! //! `log_storage_fault!` expands at its call site, so the event keeps the //! site's own `target`, `module_path`, `file` and `line`; an operator who -//! filters on `extenddb_engine::backup` still matches the backup mapper's -//! line. The macro adds `request_id` and `operation` from the request scope -//! the server sets around the request (see `extenddb_storage::request_scope`), -//! so the line can be matched to the `x-amzn-RequestId` the client received. -//! Outside a request both are `None`, and `tracing` records nothing for a -//! `None`, so the line carries neither field. +//! filters on `extenddb_engine::backup_requests` still matches the backup +//! mapper's line. The macro adds `request_id` and `operation` from the +//! request scope the server sets around the request (see +//! `extenddb_storage::request_scope`), so the line can be matched to the +//! `x-amzn-RequestId` the client received. Outside a request both are +//! `None`, and `tracing` records nothing for a `None`, so the line carries +//! neither field. /// Write an event for a storage fault. /// diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs index 17bf52bea..aa376bd71 100644 --- a/crates/engine/src/request_scope_log_tests.rs +++ b/crates/engine/src/request_scope_log_tests.rs @@ -172,13 +172,13 @@ fn sites() -> Vec { target: "extenddb_engine::create_table", }, Site { - name: "backup::storage_err_to_dynamo", + name: "backup_requests::storage_err_to_dynamo", error: internal, - map: crate::backup::storage_err_to_dynamo, + map: crate::backup_requests::storage_err_to_dynamo, status: 500, message: "backup storage error", level: "ERROR", - target: "extenddb_engine::backup", + target: "extenddb_engine::backup_requests", }, Site { name: "update_table::update_table_err_to_dynamo", @@ -332,7 +332,7 @@ async fn the_detached_restore_carries_the_scope_into_its_task() { request_id: Some("req-restore".to_owned()), operation: Some("RestoreTableFromBackup".to_owned()), message: "backup storage error".to_owned(), - target: "extenddb_engine::backup".to_owned(), + target: "extenddb_engine::backup_requests".to_owned(), level: "ERROR".to_owned(), }], "one fault line for the failed source lookup, naming the request" From 099d3c1238abcbe8c46c31da463a7a5766528d3e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:00:32 +0000 Subject: [PATCH 12/12] test(server): name the header test for the printable ASCII and tab rule The test name said visible ASCII, a range without the space and the tab. The test also checks that "a\tb c" reads as sent. The new name gives the rule that the handler applies: printable ASCII (space through tilde) or tab. --- crates/server/src/handler/request_scope_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs index 5d78b412e..44464e438 100644 --- a/crates/server/src/handler/request_scope_tests.rs +++ b/crates/server/src/handler/request_scope_tests.rs @@ -244,7 +244,7 @@ fn the_sdk_headers_are_absent_from_the_scope_when_the_client_sent_none() { } #[test] -fn a_header_that_is_not_visible_ascii_reads_as_absent() { +fn a_header_reads_as_absent_unless_it_is_printable_ascii_or_tab() { let mut headers = HeaderMap::new(); headers.insert( "amz-sdk-request",