From f1aaa95dba26534984f6c8f43e070d87a6fa4723 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 00:58:34 +0000 Subject: [PATCH 1/8] fix(mongodb): classify an unreachable backend in the key-info lookups as transient The key-info and index-info lookups in the MongoDB backend mapped every driver error from the catalog read to StorageError::Internal, which storage_err_to_dynamo answers as InternalServerError. A deployment that could not be reached therefore returned 500 on a retryable condition, on both the server's authorization path and the engine's own lookup, where the SQL backends classify the same fault as transient and answer 503. catalog_read_err classifies a driver error that means the read could not reach a server as StorageError::Transient: ServerSelection, Io, ConnectionPoolCleared, DnsResolve, and the server codes in the driver's own retryable-read set. Everything else stays Internal, erring narrow for the reason map_sqlx_err gives: a permanent fault called transient is retried by a client that cannot succeed, and holds a queue row forever. Transient rather than Connection, because that is the variant the SQL backends produce for a runtime read fault and the variant the queue workers read. Both reach ServiceUnavailable at the engine boundary. Measured against a stopped mongod with the credential cache warm: GetItem, PutItem, Query and BatchGetItem answered 500 InternalServerError before and 503 ServiceUnavailable after. Fixes #441 --- crates/storage-mongodb/src/error_class.rs | 242 +++++++++++++++++++++ crates/storage-mongodb/src/lib.rs | 1 + crates/storage-mongodb/src/table_engine.rs | 12 +- tests/test_mongodb_backend_unreachable.py | 167 ++++++++++++++ 4 files changed, 416 insertions(+), 6 deletions(-) create mode 100644 crates/storage-mongodb/src/error_class.rs create mode 100644 tests/test_mongodb_backend_unreachable.py diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs new file mode 100644 index 000000000..93ab98e6f --- /dev/null +++ b/crates/storage-mongodb/src/error_class.rs @@ -0,0 +1,242 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Classification of mongodb driver errors raised by catalog reads. +//! +//! A read that cannot reach the deployment is [`StorageError::Transient`], +//! which `storage_err_to_dynamo` answers as `ServiceUnavailable` (503, +//! retryable by the SDKs). Everything else stays [`StorageError::Internal`] +//! and answers as `InternalServerError` (500). This matches what the SQL +//! backends do for the same faults: `map_sqlx_err` in the SQLite backend and +//! `read_err` in the PostgreSQL backend both classify I/O errors, pool +//! trouble and the server's own connection-class replies as `Transient`. +//! +//! The driver has predicates for this (`is_network_error`, `is_read_retryable`) +//! but they are `pub(crate)` to the driver, so the classification is written +//! out here against `ErrorKind` and the driver's documented retryable-read +//! code set. + +use extenddb_storage::error::StorageError; +use mongodb::error::{Error as DriverError, ErrorKind}; + +/// Server error codes that make a read retryable, from the driver's own +/// `RETRYABLE_READ_CODES` (mongodb 3.8.0 `src/error.rs`): HostUnreachable, +/// HostNotFound, NetworkTimeout, ShutdownInProgress, PrimarySteppedDown, +/// ExceededTimeLimit, SocketException, NotWritablePrimary, +/// InterruptedAtShutdown, InterruptedDueToReplStateChange, +/// NotPrimaryNoSecondaryOk, NotPrimaryOrSecondary, and +/// ReadConcernMajorityNotAvailableYet. +const RETRYABLE_READ_CODES: [i32; 13] = [ + 6, 7, 89, 91, 134, 189, 262, 9001, 10107, 11600, 11602, 13435, 13436, +]; + +/// Whether `e` means the read could not reach a server that could serve it. +/// +/// `ServerSelection` is the one a stopped or unreachable deployment produces: +/// the driver marks the server Unknown and server selection then times out. +/// Its own label set is empty, because the `RetryableError` label sits on the +/// inner per-server error, so a label check does not see it; the kind does. +/// `Io` and `ConnectionPoolCleared` are what the driver itself calls a network +/// error. `DnsResolve` is a name lookup that did not answer. +/// +/// The classification errs narrow, for the reason `map_sqlx_err` gives: a +/// fault wrongly called transient is retried by a client that cannot succeed, +/// and the GSI and TTL queue workers retry a `Transient` row instead of +/// dropping it, so a permanent fault called transient stalls a queue. +fn is_unreachable(e: &DriverError) -> bool { + match &*e.kind { + ErrorKind::Io(_) + | ErrorKind::ConnectionPoolCleared { .. } + | ErrorKind::ServerSelection { .. } + | ErrorKind::DnsResolve { .. } => true, + ErrorKind::Command(command) => RETRYABLE_READ_CODES.contains(&command.code), + _ => false, + } +} + +/// Map a driver error from a catalog read to a `StorageError`. +/// +/// Used by the key-info and index-info lookups, whose result decides the wire +/// status on two paths: the server's authorization path reads key info before +/// dispatch (`key_info_for_authz`) and the engine reads it again for the +/// operation itself. Both run the result through `storage_err_to_dynamo`, so +/// this classification is what the client sees (#441). +pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { + if is_unreachable(e) { + StorageError::Transient(e.to_string()) + } else { + StorageError::Internal(e.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::{RETRYABLE_READ_CODES, catalog_read_err}; + use extenddb_storage::error::StorageError; + use mongodb::bson::doc; + use mongodb::error::{Error as DriverError, ErrorKind}; + use std::sync::Arc; + + /// A labelless server command error with the given code. The struct + /// variants of `ErrorKind` are `#[non_exhaustive]`, so a synthetic one is + /// built through deserialization, as the data-engine tests do. + fn command(code: i32) -> DriverError { + let command_error: mongodb::error::CommandError = bson::from_document(doc! { + "code": code, + "codeName": "SyntheticTestError", + "errmsg": "synthetic command error", + }) + .expect("static CommandError document deserializes"); + ErrorKind::Command(command_error).into() + } + + /// The error #441 is about, taken from the driver rather than built by + /// hand: a client whose only server is not listening answers a catalog + /// read with `ErrorKind::ServerSelection`. Port 1 on loopback refuses the + /// connection, and `serverSelectionTimeoutMS` is short so the test costs + /// milliseconds. `ErrorKind::ServerSelection` is `#[non_exhaustive]` and + /// cannot be constructed outside the driver, so this is the only way to + /// assert on the real thing. + #[tokio::test] + async fn a_deployment_that_is_not_listening_is_transient() { + let client = mongodb::Client::with_uri_str( + "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50", + ) + .await + .expect("a syntactically valid connection string"); + let error = client + .database("extenddb_catalog") + .collection::("tables") + .find_one(doc! { "table_id": "whatever" }) + .await + .expect_err("no server is listening on port 1"); + assert!( + matches!(*error.kind, ErrorKind::ServerSelection { .. }), + "driver reported {:?}, the test's premise no longer holds", + error.kind + ); + assert!( + matches!(catalog_read_err(&error), StorageError::Transient(_)), + "a deployment that cannot be reached must be Transient, got {:?}", + catalog_read_err(&error) + ); + } + + #[test] + fn a_dropped_socket_is_transient() { + let e: DriverError = ErrorKind::Io(Arc::new(std::io::Error::new( + std::io::ErrorKind::ConnectionReset, + "reset by peer", + ))) + .into(); + assert!(matches!(catalog_read_err(&e), StorageError::Transient(_))); + } + + /// A node that is shutting down, stepping down or recovering answers the + /// read with one of these codes. The deployment is reachable, so the + /// driver does not call it a network error, but the read can succeed on + /// retry once a new primary is elected. + #[test] + fn a_node_that_cannot_serve_the_read_is_transient() { + for code in RETRYABLE_READ_CODES { + assert!( + matches!(catalog_read_err(&command(code)), StorageError::Transient(_)), + "code {code} must be Transient" + ); + } + } + + /// Anything not positively identified as unreachable stays Internal, so a + /// permanent fault is not retried forever by a client, and the GSI and TTL + /// queue workers do not hold a row that can never be applied. + #[test] + fn other_faults_stay_internal() { + // Unauthorized (13), NamespaceNotFound (26), BadValue (2), + // WriteConflict (112). + for code in [13, 26, 2, 112] { + assert!( + matches!(catalog_read_err(&command(code)), StorageError::Internal(_)), + "code {code} must be Internal" + ); + } + for e in [ + DriverError::from(ErrorKind::SessionsNotSupported), + DriverError::from(ErrorKind::MissingResumeToken), + DriverError::from(ErrorKind::Shutdown), + ] { + let what = e.to_string(); + assert!( + matches!(catalog_read_err(&e), StorageError::Internal(_)), + "{what} must be Internal" + ); + } + } + + /// The driver's message is kept whichever way the error is classified, so + /// the log line and the server's diagnostics do not lose it. + #[test] + fn the_driver_message_survives_classification() { + let e: DriverError = ErrorKind::Io(Arc::new(std::io::Error::new( + std::io::ErrorKind::ConnectionRefused, + "connection refused", + ))) + .into(); + let StorageError::Transient(message) = catalog_read_err(&e) else { + panic!("expected Transient"); + }; + assert!(message.contains("connection refused"), "{message}"); + } + + /// #441 through the production lookups rather than the classifier alone. + /// + /// `MongoEngine::new` builds client options and a lazy client and performs + /// no I/O, so an engine can be pointed at a port nothing listens on and + /// the key-info lookups then fail the way an unreachable deployment makes + /// them fail. `key_info_for_authz` in the server and the engine both run + /// the result through `storage_err_to_dynamo`, which answers `Transient` + /// as `ServiceUnavailable`; that mapping has its own test in + /// `crates/server/src/request_helpers.rs`, so what is asserted here is the + /// classification this backend produces. + /// + /// Needs no MongoDB, so it runs in `cargo test --workspace` on every job. + #[tokio::test] + async fn an_unreachable_deployment_makes_the_key_info_lookups_transient() { + use extenddb_storage::TableEngine; + + let engine = crate::MongoEngine::new( + "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50", + "us-east-1", + None, + mongodb::options::ReadConcern::local(), + ) + .await + .expect("building the engine performs no I/O"); + + let by_name = engine + .table_key_info("123456789012", "any-table") + .await + .expect_err("no server is listening on port 1"); + assert!( + matches!(by_name, StorageError::Transient(_)), + "table_key_info must report an unreachable deployment as Transient, got {by_name:?}" + ); + + let by_id = engine + .table_key_info_by_table_id_impl("any-table-id") + .await + .expect_err("no server is listening on port 1"); + assert!( + matches!(by_id, StorageError::Transient(_)), + "table_key_info_by_table_id must report it as Transient, got {by_id:?}" + ); + + let index = engine + .index_info_by_table_id("any-table-id", "any-index") + .await + .expect_err("no server is listening on port 1"); + assert!( + matches!(index, StorageError::Transient(_)), + "index_info_by_table_id must report it as Transient, got {index:?}" + ); + } +} diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index c1d28882f..8b9b7c121 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -17,6 +17,7 @@ pub mod config; mod credential_store; mod data; mod data_engine; +mod error_class; mod management_store; mod metadata_engine; mod operations; diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index aa8c5272c..b90c8b8d5 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -1144,7 +1144,7 @@ impl MongoEngine { let table_doc = tables_coll .find_one(filter.clone()) .await - .map_err(|e| StorageError::Internal(e.to_string()))? + .map_err(|e| crate::error_class::catalog_read_err(&e))? .ok_or_else(|| StorageError::TableNotFound(table_name.to_owned()))?; if table_doc.get_str("table_status").unwrap_or("ACTIVE") != "ACTIVE" { return Err(StorageError::TableNotActive(table_name.to_owned())); @@ -1163,7 +1163,7 @@ impl MongoEngine { let table_doc = tables_coll .find_one(doc! { "_id": { "account_id": account_id, "table_name": table_name } }) .await - .map_err(|e| StorageError::Internal(e.to_string()))? + .map_err(|e| crate::error_class::catalog_read_err(&e))? .ok_or_else(|| StorageError::TableNotFound(table_name.to_string()))?; self.table_key_info_from_doc(&table_doc, true).await @@ -1184,7 +1184,7 @@ impl MongoEngine { let table_doc = tables_coll .find_one(doc! { "table_id": table_id }) .await - .map_err(|e| StorageError::Internal(e.to_string()))? + .map_err(|e| crate::error_class::catalog_read_err(&e))? .ok_or_else(|| StorageError::TableNotFound(table_id.to_string()))?; self.table_key_info_from_doc(&table_doc, false).await @@ -1252,12 +1252,12 @@ impl MongoEngine { let mut idx_cursor = indexes_coll .find(doc! { "_id.table_id": &table_id }) .await - .map_err(|e| StorageError::Internal(e.to_string()))?; + .map_err(|e| crate::error_class::catalog_read_err(&e))?; let mut infos = Vec::new(); while let Some(idx_doc) = idx_cursor .try_next() .await - .map_err(|e| StorageError::Internal(e.to_string()))? + .map_err(|e| crate::error_class::catalog_read_err(&e))? { infos.push(index_info_from_doc(&idx_doc)?); } @@ -1315,7 +1315,7 @@ impl MongoEngine { let index_doc = indexes_coll .find_one(doc! { "_id": { "table_id": table_id, "index_name": index_name } }) .await - .map_err(|e| StorageError::Internal(e.to_string()))? + .map_err(|e| crate::error_class::catalog_read_err(&e))? .ok_or_else(|| StorageError::IndexNotFound(index_name.to_string()))?; let index_id = index_doc diff --git a/tests/test_mongodb_backend_unreachable.py b/tests/test_mongodb_backend_unreachable.py new file mode 100644 index 000000000..d8cd22c8e --- /dev/null +++ b/tests/test_mongodb_backend_unreachable.py @@ -0,0 +1,167 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""MongoDB-specific check: a backend that cannot be reached answers 503. + +A data-plane request resolves the table's key schema before it runs: the +server's authorization path reads it to evaluate ``dynamodb:LeadingKeys``, and +the engine reads it again for the operation itself. A MongoDB deployment that +cannot be reached makes that read fail, and the status the client sees is +whatever the backend classified the driver error as. A transient backend fault +is a retryable ``ServiceUnavailable`` (503), which is what the SQL backends +produce for the same fault; before the fix this backend answered 500 +``InternalServerError``, so a client saw a non-retryable error for a retryable +condition (#441). + +The fault is induced by stopping the MongoDB container, so every other request +to the same server fails while this test runs. ``devtools/run-tests +--parallel`` distributes test FILES across workers, which would put other +files' requests inside this window, so the test only runs when +``EXTENDDB_TEST_BACKEND_FAULT=1`` is set: + + EXTENDDB_TEST_BACKEND_FAULT=1 devtools/run-mongodb-tests \\ + --filter backend_unreachable + +The credential cache and the key-info cache share one hard TTL of 60 seconds. +One request before the fault leaves the access key cached, so authentication is +served from cache and the faulted requests reach the key-info lookup rather +than failing authentication first. Each faulted request costs the driver's +30 second server-selection timeout, so the three run concurrently to finish +inside that window, and they name tables the key-info cache has never seen so +no cached entry answers for them. +""" + +from __future__ import annotations + +import concurrent.futures +import os +import subprocess +import time +import uuid + +import pytest + +from conftest import wait_for_active, wait_for_deleted + +pytestmark = pytest.mark.skipif( + os.environ.get("EXTENDDB_TEST_BACKEND_FAULT", "") != "1", + reason="stops the shared MongoDB container; set EXTENDDB_TEST_BACKEND_FAULT=1 to run", +) + + +@pytest.fixture() +def mongodb_container() -> str: + container = os.environ.get("EXTENDDB_TEST_MONGODB_CONTAINER", "").strip() + if not container: + pytest.skip("requires devtools/run-mongodb-tests") + return container + + +@pytest.fixture() +def no_retry_client(dynamodb_client): + """A client that reports the first response rather than retrying it. + + 503 is retryable, so the shared session client retries it: four attempts + at the driver's 30 second server-selection timeout outlast the 60 second + credential cache, and the attempt that finally reports back has failed + authentication instead, with a 500. One attempt per operation keeps every + request inside the window this test sets up. + """ + import boto3 + from botocore.config import Config + + endpoint = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() + if not endpoint: + pytest.skip("requires EXTENDDB_TEST_ENDPOINT") + return boto3.client( + "dynamodb", + endpoint_url=endpoint, + region_name=dynamodb_client.meta.region_name, + verify=False, + config=Config(retries={"max_attempts": 0}, read_timeout=120, connect_timeout=20), + ) + + +def _docker(container: str, *args: str) -> None: + subprocess.run(["docker", *args, container], check=True, capture_output=True) + + +def _wait_primary(container: str) -> None: + for _ in range(60): + probe = subprocess.run( + ["docker", "exec", container, "mongosh", "--quiet", "--eval", + "rs.status().members[0].stateStr"], + capture_output=True, + text=True, + ) + if probe.stdout.strip().splitlines()[-1:] == ["PRIMARY"]: + return + time.sleep(1) + pytest.fail("mongod did not return to PRIMARY; later tests would fail too") + + +def _status_and_code(client, call) -> tuple[int, str]: + try: + response = call() + except client.exceptions.ClientError as exc: + return ( + exc.response["ResponseMetadata"]["HTTPStatusCode"], + exc.response["Error"].get("Code", ""), + ) + return response["ResponseMetadata"]["HTTPStatusCode"], "OK" + + +def test_backend_unreachable_is_service_unavailable( + dynamodb_client, no_retry_client, unique_table_name, mongodb_container +): + """GetItem, PutItem and Query answer 503 while the backend is unreachable.""" + dynamodb_client.create_table( + TableName=unique_table_name, + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + ) + wait_for_active(dynamodb_client, unique_table_name) + + # Leaves the access key in the credential cache, so the faulted requests + # below fail on the key-info lookup rather than on authentication. + no_retry_client.get_item(TableName=unique_table_name, Key={"pk": {"S": "warmup"}}) + + cold = f"extenddb-cold-{uuid.uuid4().hex[:12]}" + calls = { + "GetItem": lambda: no_retry_client.get_item( + TableName=f"{cold}-g", Key={"pk": {"S": "a"}} + ), + "PutItem": lambda: no_retry_client.put_item( + TableName=f"{cold}-p", Item={"pk": {"S": "a"}} + ), + "Query": lambda: no_retry_client.query( + TableName=f"{cold}-q", + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": {"S": "a"}}, + ), + } + + try: + _docker(mongodb_container, "stop") + with concurrent.futures.ThreadPoolExecutor(max_workers=len(calls)) as pool: + futures = { + name: pool.submit(_status_and_code, no_retry_client, call) + for name, call in calls.items() + } + observed = {name: future.result() for name, future in futures.items()} + finally: + _docker(mongodb_container, "start") + _wait_primary(mongodb_container) + + for name, (status, code) in observed.items(): + assert (status, code) == (503, "ServiceUnavailable"), ( + f"{name} answered {status} {code} while the backend was unreachable; " + "a transient backend fault must be a retryable ServiceUnavailable" + ) + + try: + dynamodb_client.delete_table(TableName=unique_table_name) + wait_for_deleted(dynamodb_client, unique_table_name) + except dynamodb_client.exceptions.ResourceNotFoundException: + pass From 1b7430daca653b1d7621cdd293285312a2bbf938 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 03:08:30 +0000 Subject: [PATCH 2/8] docs(mongodb): say which backend's queue workers retry a transient row The classifier comment said the GSI and TTL queue workers retry a Transient row instead of dropping it. That is the SQLite worker. This backend's workers log every error and continue, so the comment now says so. --- crates/storage-mongodb/src/error_class.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs index 93ab98e6f..ef83dbb39 100644 --- a/crates/storage-mongodb/src/error_class.rs +++ b/crates/storage-mongodb/src/error_class.rs @@ -40,9 +40,10 @@ const RETRYABLE_READ_CODES: [i32; 13] = [ /// error. `DnsResolve` is a name lookup that did not answer. /// /// The classification errs narrow, for the reason `map_sqlx_err` gives: a -/// fault wrongly called transient is retried by a client that cannot succeed, -/// and the GSI and TTL queue workers retry a `Transient` row instead of -/// dropping it, so a permanent fault called transient stalls a queue. +/// fault wrongly called transient is retried by a client that cannot succeed. +/// On the SQLite backend the queue workers also retry a `Transient` row +/// instead of dropping it, so a permanent fault called transient stalls that +/// queue; this backend's GSI and TTL workers log every error and continue. fn is_unreachable(e: &DriverError) -> bool { match &*e.kind { ErrorKind::Io(_) From 2ed233e1dd168f1993533226b30c0a0987789340 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:31:12 +0000 Subject: [PATCH 3/8] fix(mongodb): leave the UpdateTable guard's catalog read on Internal require_active_table runs only inside update_table_impl, and that path answers through update_table_err_to_dynamo. The mapper has no Transient arm: its catch-all turns Transient into the same 500 InternalServerError as Internal. So the substitution at this read changed nothing on the wire, and UpdateTable answers 500 with the deployment stopped before and after. The read goes back to Internal. The change now covers the five key-info and index-info reads, which answer through storage_err_to_dynamo and its Transient arm. UpdateTable's own answer on an unreachable deployment is tracked in #1451. --- crates/storage-mongodb/src/table_engine.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index 14f8c16f5..4e1701c69 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -1280,7 +1280,7 @@ impl MongoEngine { let table_doc = tables_coll .find_one(filter.clone()) .await - .map_err(|e| crate::error_class::catalog_read_err(&e))? + .map_err(|e| StorageError::Internal(e.to_string()))? .ok_or_else(|| StorageError::TableNotFound(table_name.to_owned()))?; if table_doc.get_str("table_status").unwrap_or("ACTIVE") != "ACTIVE" { return Err(StorageError::TableNotActive(table_name.to_owned())); From 8ba7e56031cbbd270836b967b26ab9dc1699e949 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:37:29 +0000 Subject: [PATCH 4/8] test(mongodb): cover the index list read of table_key_info_from_doc The closed-port engine fails at the first tables read. The test of the key-info lookups therefore never reached the indexes find in table_key_info_from_doc. That site could go back to Internal with every test passing. The new test hands the function a catalog document as create_table writes one, so the index list is the first read that reaches the driver. It asserts that the read comes back Transient. With the find site reverted the test fails with Internal("Kind: Server selection timeout..."). The closed-port connection string and the engine built on it move into one place in error_class.rs, where the three tests that need them share them. --- crates/storage-mongodb/src/error_class.rs | 66 ++++++++++++---------- crates/storage-mongodb/src/table_engine.rs | 26 ++++++++- 2 files changed, 62 insertions(+), 30 deletions(-) diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs index ef83dbb39..d909faa12 100644 --- a/crates/storage-mongodb/src/error_class.rs +++ b/crates/storage-mongodb/src/error_class.rs @@ -70,9 +70,31 @@ pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { } } +/// A connection string nothing listens on. Port 1 on loopback refuses the +/// connection, and `serverSelectionTimeoutMS` is short so a read that waits +/// for a server costs milliseconds. `MongoEngine::new` performs no I/O, so an +/// engine built on it fails at its first read the way an unreachable +/// deployment makes it fail, with `ErrorKind::ServerSelection` from the +/// driver. +#[cfg(test)] +pub(crate) const CLOSED_PORT_URI: &str = + "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50"; + +#[cfg(test)] +pub(crate) async fn engine_on_a_closed_port() -> crate::MongoEngine { + crate::MongoEngine::new( + CLOSED_PORT_URI, + "us-east-1", + None, + mongodb::options::ReadConcern::local(), + ) + .await + .expect("building the engine performs no I/O") +} + #[cfg(test)] mod tests { - use super::{RETRYABLE_READ_CODES, catalog_read_err}; + use super::{CLOSED_PORT_URI, RETRYABLE_READ_CODES, catalog_read_err, engine_on_a_closed_port}; use extenddb_storage::error::StorageError; use mongodb::bson::doc; use mongodb::error::{Error as DriverError, ErrorKind}; @@ -91,20 +113,16 @@ mod tests { ErrorKind::Command(command_error).into() } - /// The error #441 is about, taken from the driver rather than built by - /// hand: a client whose only server is not listening answers a catalog - /// read with `ErrorKind::ServerSelection`. Port 1 on loopback refuses the - /// connection, and `serverSelectionTimeoutMS` is short so the test costs - /// milliseconds. `ErrorKind::ServerSelection` is `#[non_exhaustive]` and - /// cannot be constructed outside the driver, so this is the only way to - /// assert on the real thing. + /// The error a stopped deployment produces, taken from the driver rather + /// than built by hand: a client whose only server is not listening answers + /// a catalog read with `ErrorKind::ServerSelection`. The variant is + /// `#[non_exhaustive]` and cannot be constructed outside the driver, so + /// this is the only way to assert on the real thing. #[tokio::test] async fn a_deployment_that_is_not_listening_is_transient() { - let client = mongodb::Client::with_uri_str( - "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50", - ) - .await - .expect("a syntactically valid connection string"); + let client = mongodb::Client::with_uri_str(CLOSED_PORT_URI) + .await + .expect("a syntactically valid connection string"); let error = client .database("extenddb_catalog") .collection::("tables") @@ -188,14 +206,11 @@ mod tests { assert!(message.contains("connection refused"), "{message}"); } - /// #441 through the production lookups rather than the classifier alone. - /// - /// `MongoEngine::new` builds client options and a lazy client and performs - /// no I/O, so an engine can be pointed at a port nothing listens on and - /// the key-info lookups then fail the way an unreachable deployment makes - /// them fail. `key_info_for_authz` in the server and the engine both run - /// the result through `storage_err_to_dynamo`, which answers `Transient` - /// as `ServiceUnavailable`; that mapping has its own test in + /// The key-info lookups themselves, not only the classifier. Each fails at + /// its first read on the closed-port engine. `key_info_for_authz` in the + /// server and the engine both run the result through + /// `storage_err_to_dynamo`, which answers `Transient` as + /// `ServiceUnavailable`; that mapping has its own test in /// `crates/server/src/request_helpers.rs`, so what is asserted here is the /// classification this backend produces. /// @@ -204,14 +219,7 @@ mod tests { async fn an_unreachable_deployment_makes_the_key_info_lookups_transient() { use extenddb_storage::TableEngine; - let engine = crate::MongoEngine::new( - "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50", - "us-east-1", - None, - mongodb::options::ReadConcern::local(), - ) - .await - .expect("building the engine performs no I/O"); + let engine = engine_on_a_closed_port().await; let by_name = engine .table_key_info("123456789012", "any-table") diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index 4e1701c69..60454b051 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -2004,7 +2004,7 @@ fn active_table_filter(filter: &Document) -> Document { #[cfg(test)] mod tests { - use super::active_table_filter; + use super::{StorageError, active_table_filter}; use mongodb::bson::doc; #[test] @@ -2015,4 +2015,28 @@ mod tests { assert_eq!(active.get_document("_id"), filter.get_document("_id")); assert_eq!(active.len(), 2); } + + /// The `indexes` read of `table_key_info_from_doc`. Through the lookups + /// the closed-port engine fails at the `tables` read before it, so this + /// test hands the function a catalog document as `create_table` writes + /// one, and the index list is then the first read that reaches the driver. + #[tokio::test] + async fn an_unreachable_deployment_makes_the_index_list_read_transient() { + let engine = crate::error_class::engine_on_a_closed_port().await; + let table_doc = doc! { + "_id": { "account_id": "444455556666", "table_name": "t" }, + "table_id": "t-id", + "table_status": "ACTIVE", + "key_schema": [{ "AttributeName": "pk", "KeyType": "HASH" }], + "attribute_definitions": [{ "AttributeName": "pk", "AttributeType": "S" }], + }; + let err = engine + .table_key_info_from_doc(&table_doc, true) + .await + .expect_err("no server is listening on port 1"); + assert!( + matches!(err, StorageError::Transient(_)), + "the index list read must report an unreachable deployment as Transient, got {err:?}" + ); + } } From 828ffe44b9f41f15b3dbda086a5984f75f6788e9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:39:29 +0000 Subject: [PATCH 5/8] test(wire): take the unreachable-backend table from scoped_table and fix the run command devtools/run-mongodb-tests takes --filter only after --, as an argument it passes to devtools/run-tests. On its own it exits 1 with "unknown option: --filter". The docstring now gives the command that runs the file: EXTENDDB_TEST_BACKEND_FAULT=1 devtools/run-mongodb-tests -- --pytest --filter backend_unreachable. The test created its table by hand and deleted it after the assertion loop, so a failed assertion left the table behind. The table now comes from the scoped_table helper in conftest.py, which deletes it on exit whichever way the block ends. The container restart stays in the inner finally, so the delete runs with the backend up. --- tests/test_mongodb_backend_unreachable.py | 98 ++++++++++------------- 1 file changed, 44 insertions(+), 54 deletions(-) diff --git a/tests/test_mongodb_backend_unreachable.py b/tests/test_mongodb_backend_unreachable.py index d8cd22c8e..6bd35a230 100644 --- a/tests/test_mongodb_backend_unreachable.py +++ b/tests/test_mongodb_backend_unreachable.py @@ -19,8 +19,8 @@ files' requests inside this window, so the test only runs when ``EXTENDDB_TEST_BACKEND_FAULT=1`` is set: - EXTENDDB_TEST_BACKEND_FAULT=1 devtools/run-mongodb-tests \\ - --filter backend_unreachable + EXTENDDB_TEST_BACKEND_FAULT=1 devtools/run-mongodb-tests -- \\ + --pytest --filter backend_unreachable The credential cache and the key-info cache share one hard TTL of 60 seconds. One request before the fault leaves the access key cached, so authentication is @@ -41,7 +41,7 @@ import pytest -from conftest import wait_for_active, wait_for_deleted +from conftest import scoped_table pytestmark = pytest.mark.skipif( os.environ.get("EXTENDDB_TEST_BACKEND_FAULT", "") != "1", @@ -112,56 +112,46 @@ def _status_and_code(client, call) -> tuple[int, str]: def test_backend_unreachable_is_service_unavailable( - dynamodb_client, no_retry_client, unique_table_name, mongodb_container + dynamodb_client, no_retry_client, mongodb_container ): """GetItem, PutItem and Query answer 503 while the backend is unreachable.""" - dynamodb_client.create_table( - TableName=unique_table_name, - AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], - KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], - BillingMode="PAY_PER_REQUEST", - ) - wait_for_active(dynamodb_client, unique_table_name) - - # Leaves the access key in the credential cache, so the faulted requests - # below fail on the key-info lookup rather than on authentication. - no_retry_client.get_item(TableName=unique_table_name, Key={"pk": {"S": "warmup"}}) - - cold = f"extenddb-cold-{uuid.uuid4().hex[:12]}" - calls = { - "GetItem": lambda: no_retry_client.get_item( - TableName=f"{cold}-g", Key={"pk": {"S": "a"}} - ), - "PutItem": lambda: no_retry_client.put_item( - TableName=f"{cold}-p", Item={"pk": {"S": "a"}} - ), - "Query": lambda: no_retry_client.query( - TableName=f"{cold}-q", - KeyConditionExpression="pk = :p", - ExpressionAttributeValues={":p": {"S": "a"}}, - ), - } - - try: - _docker(mongodb_container, "stop") - with concurrent.futures.ThreadPoolExecutor(max_workers=len(calls)) as pool: - futures = { - name: pool.submit(_status_and_code, no_retry_client, call) - for name, call in calls.items() - } - observed = {name: future.result() for name, future in futures.items()} - finally: - _docker(mongodb_container, "start") - _wait_primary(mongodb_container) - - for name, (status, code) in observed.items(): - assert (status, code) == (503, "ServiceUnavailable"), ( - f"{name} answered {status} {code} while the backend was unreachable; " - "a transient backend fault must be a retryable ServiceUnavailable" - ) - - try: - dynamodb_client.delete_table(TableName=unique_table_name) - wait_for_deleted(dynamodb_client, unique_table_name) - except dynamodb_client.exceptions.ResourceNotFoundException: - pass + # scoped_table deletes the table on exit, a failed assertion included; the + # container is back by then, because the inner finally restarts it. + with scoped_table(dynamodb_client) as table_name: + # Leaves the access key in the credential cache, so the faulted + # requests below fail on the key-info lookup rather than on + # authentication. + no_retry_client.get_item(TableName=table_name, Key={"pk": {"S": "warmup"}}) + + cold = f"extenddb-cold-{uuid.uuid4().hex[:12]}" + calls = { + "GetItem": lambda: no_retry_client.get_item( + TableName=f"{cold}-g", Key={"pk": {"S": "a"}} + ), + "PutItem": lambda: no_retry_client.put_item( + TableName=f"{cold}-p", Item={"pk": {"S": "a"}} + ), + "Query": lambda: no_retry_client.query( + TableName=f"{cold}-q", + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": {"S": "a"}}, + ), + } + + try: + _docker(mongodb_container, "stop") + with concurrent.futures.ThreadPoolExecutor(max_workers=len(calls)) as pool: + futures = { + name: pool.submit(_status_and_code, no_retry_client, call) + for name, call in calls.items() + } + observed = {name: future.result() for name, future in futures.items()} + finally: + _docker(mongodb_container, "start") + _wait_primary(mongodb_container) + + for name, (status, code) in observed.items(): + assert (status, code) == (503, "ServiceUnavailable"), ( + f"{name} answered {status} {code} while the backend was unreachable; " + "a transient backend fault must be a retryable ServiceUnavailable" + ) From a6bdd007addb33f740c0c80d96ab547ac29e6ea9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:40:58 +0000 Subject: [PATCH 6/8] test(wire): compare the message too, and add BatchGetItem to the faulted set The assertion compared status and code only. A credential lookup that runs into the stopped deployment answers 500 "Internal error during authentication". A key-info lookup that goes back to Internal answers 500 "Internal server error". Both failed the test with the same text, so a failure could not say which one it was. The helper now returns the message as well. The loop compares the full triple against (503, "ServiceUnavailable", "Service is temporarily unavailable"), the answer the engine's Transient arm gives. BatchGetItem resolves the key info through the engine's own lookup rather than the authorization path, and the body measures it. It joins the four requests that run concurrently while the container is down. --- tests/test_mongodb_backend_unreachable.py | 29 +++++++++++++++-------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/tests/test_mongodb_backend_unreachable.py b/tests/test_mongodb_backend_unreachable.py index 6bd35a230..9cbbacf9c 100644 --- a/tests/test_mongodb_backend_unreachable.py +++ b/tests/test_mongodb_backend_unreachable.py @@ -26,7 +26,7 @@ One request before the fault leaves the access key cached, so authentication is served from cache and the faulted requests reach the key-info lookup rather than failing authentication first. Each faulted request costs the driver's -30 second server-selection timeout, so the three run concurrently to finish +30 second server-selection timeout, so the four run concurrently to finish inside that window, and they name tables the key-info cache has never seen so no cached entry answers for them. """ @@ -100,21 +100,24 @@ def _wait_primary(container: str) -> None: pytest.fail("mongod did not return to PRIMARY; later tests would fail too") -def _status_and_code(client, call) -> tuple[int, str]: +def _status_code_message(client, call) -> tuple[int, str, str]: try: response = call() except client.exceptions.ClientError as exc: + error = exc.response["Error"] return ( exc.response["ResponseMetadata"]["HTTPStatusCode"], - exc.response["Error"].get("Code", ""), + error.get("Code", ""), + error.get("Message", ""), ) - return response["ResponseMetadata"]["HTTPStatusCode"], "OK" + return response["ResponseMetadata"]["HTTPStatusCode"], "OK", "" def test_backend_unreachable_is_service_unavailable( dynamodb_client, no_retry_client, mongodb_container ): - """GetItem, PutItem and Query answer 503 while the backend is unreachable.""" + """GetItem, PutItem, Query and BatchGetItem answer 503 while the backend + is unreachable.""" # scoped_table deletes the table on exit, a failed assertion included; the # container is back by then, because the inner finally restarts it. with scoped_table(dynamodb_client) as table_name: @@ -136,13 +139,16 @@ def test_backend_unreachable_is_service_unavailable( KeyConditionExpression="pk = :p", ExpressionAttributeValues={":p": {"S": "a"}}, ), + "BatchGetItem": lambda: no_retry_client.batch_get_item( + RequestItems={f"{cold}-b": {"Keys": [{"pk": {"S": "a"}}]}} + ), } try: _docker(mongodb_container, "stop") with concurrent.futures.ThreadPoolExecutor(max_workers=len(calls)) as pool: futures = { - name: pool.submit(_status_and_code, no_retry_client, call) + name: pool.submit(_status_code_message, no_retry_client, call) for name, call in calls.items() } observed = {name: future.result() for name, future in futures.items()} @@ -150,8 +156,11 @@ def test_backend_unreachable_is_service_unavailable( _docker(mongodb_container, "start") _wait_primary(mongodb_container) - for name, (status, code) in observed.items(): - assert (status, code) == (503, "ServiceUnavailable"), ( - f"{name} answered {status} {code} while the backend was unreachable; " - "a transient backend fault must be a retryable ServiceUnavailable" + # The message tells a key-info 500 ("Internal server error") from an + # authentication 500 ("Internal error during authentication"), which + # the status and code alone cannot. + expected = (503, "ServiceUnavailable", "Service is temporarily unavailable") + for name, answer in observed.items(): + assert answer == expected, ( + f"{name} answered {answer} while the backend was unreachable" ) From 19c531403ddf0a7064a7bae03b3e2c208b313f2e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:42:51 +0000 Subject: [PATCH 7/8] docs(mongodb): describe the change as a classification and name the SQL reads it matches botocore retries a 500 InternalServerError as it retries a 503, so the test docstring's "non-retryable error for a retryable condition" did not hold. The docstring and the module comment now say what the two statuses mean. 503 is the status of a fault that clears when the deployment comes back, and 500 the status of a server fault. The module comment also said the SQL backends classify the same faults as Transient. Only two of their classifiers do: map_sqlx_err on the SQLite index paths and read_err on the PostgreSQL DescribeBackup definition read. Their key-info reads map every driver error to Internal, and the comment now says so. The comments carry no issue numbers any more. --- crates/storage-mongodb/src/error_class.rs | 15 ++++++++------- tests/test_mongodb_backend_unreachable.py | 7 +++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs index d909faa12..1bb679327 100644 --- a/crates/storage-mongodb/src/error_class.rs +++ b/crates/storage-mongodb/src/error_class.rs @@ -4,12 +4,13 @@ //! Classification of mongodb driver errors raised by catalog reads. //! //! A read that cannot reach the deployment is [`StorageError::Transient`], -//! which `storage_err_to_dynamo` answers as `ServiceUnavailable` (503, -//! retryable by the SDKs). Everything else stays [`StorageError::Internal`] -//! and answers as `InternalServerError` (500). This matches what the SQL -//! backends do for the same faults: `map_sqlx_err` in the SQLite backend and -//! `read_err` in the PostgreSQL backend both classify I/O errors, pool -//! trouble and the server's own connection-class replies as `Transient`. +//! which `storage_err_to_dynamo` answers as `ServiceUnavailable` (503), the +//! status of a fault that clears when the deployment comes back. Everything +//! else stays [`StorageError::Internal`] and answers as `InternalServerError` +//! (500), the status of a server fault. Two SQL classifiers answer the same +//! fault the same way: `map_sqlx_err` on the SQLite index paths and `read_err` +//! on the PostgreSQL DescribeBackup definition read. The SQL backends' own +//! key-info reads map every driver error to `Internal`. //! //! The driver has predicates for this (`is_network_error`, `is_read_retryable`) //! but they are `pub(crate)` to the driver, so the classification is written @@ -61,7 +62,7 @@ fn is_unreachable(e: &DriverError) -> bool { /// status on two paths: the server's authorization path reads key info before /// dispatch (`key_info_for_authz`) and the engine reads it again for the /// operation itself. Both run the result through `storage_err_to_dynamo`, so -/// this classification is what the client sees (#441). +/// this classification is what the client sees. pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { if is_unreachable(e) { StorageError::Transient(e.to_string()) diff --git a/tests/test_mongodb_backend_unreachable.py b/tests/test_mongodb_backend_unreachable.py index 9cbbacf9c..cbee017f9 100644 --- a/tests/test_mongodb_backend_unreachable.py +++ b/tests/test_mongodb_backend_unreachable.py @@ -8,10 +8,9 @@ the engine reads it again for the operation itself. A MongoDB deployment that cannot be reached makes that read fail, and the status the client sees is whatever the backend classified the driver error as. A transient backend fault -is a retryable ``ServiceUnavailable`` (503), which is what the SQL backends -produce for the same fault; before the fix this backend answered 500 -``InternalServerError``, so a client saw a non-retryable error for a retryable -condition (#441). +is a ``ServiceUnavailable`` (503), the status of a fault that clears when the +deployment comes back. Before the fix this backend answered 500 +``InternalServerError``, the status of a server fault. The fault is induced by stopping the MongoDB container, so every other request to the same server fails while this test runs. ``devtools/run-tests From 84b3a79943873f06c05a3bd05bf136f0ad0d767b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:08:35 +0000 Subject: [PATCH 8/8] docs(mongodb): drop the SQL comparison from the classifier's module doc The module doc named read_err as the PostgreSQL DescribeBackup definition read. After the merge of main, read_err serves five backup and restore reads in backup_engine.rs, and the definition read does not use it. The comparison with the SQL backends stays in the pull request description. The doc of CLOSED_PORT_URI keeps the two facts the tests use. This corrects the message of a6bdd007a. devtools/run-mongodb-tests builds the server without the dev-mode feature. So BatchGetItem's first key-info read is the authorization path's, as for the other three requests. Both paths pass the storage error through storage_err_to_dynamo, so the 503 holds on each. --- crates/storage-mongodb/src/error_class.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs index 1bb679327..d4f5702f6 100644 --- a/crates/storage-mongodb/src/error_class.rs +++ b/crates/storage-mongodb/src/error_class.rs @@ -7,10 +7,7 @@ //! which `storage_err_to_dynamo` answers as `ServiceUnavailable` (503), the //! status of a fault that clears when the deployment comes back. Everything //! else stays [`StorageError::Internal`] and answers as `InternalServerError` -//! (500), the status of a server fault. Two SQL classifiers answer the same -//! fault the same way: `map_sqlx_err` on the SQLite index paths and `read_err` -//! on the PostgreSQL DescribeBackup definition read. The SQL backends' own -//! key-info reads map every driver error to `Internal`. +//! (500), the status of a server fault. //! //! The driver has predicates for this (`is_network_error`, `is_read_retryable`) //! but they are `pub(crate)` to the driver, so the classification is written @@ -71,12 +68,8 @@ pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { } } -/// A connection string nothing listens on. Port 1 on loopback refuses the -/// connection, and `serverSelectionTimeoutMS` is short so a read that waits -/// for a server costs milliseconds. `MongoEngine::new` performs no I/O, so an -/// engine built on it fails at its first read the way an unreachable -/// deployment makes it fail, with `ErrorKind::ServerSelection` from the -/// driver. +/// A connection string nothing listens on: port 1 on loopback refuses the +/// connection, and a read fails within the 50 ms server-selection timeout. #[cfg(test)] pub(crate) const CLOSED_PORT_URI: &str = "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50";