diff --git a/crates/storage-mongodb/src/error_class.rs b/crates/storage-mongodb/src/error_class.rs new file mode 100644 index 000000000..d4f5702f6 --- /dev/null +++ b/crates/storage-mongodb/src/error_class.rs @@ -0,0 +1,245 @@ +// 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), 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. +//! +//! 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. +/// 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(_) + | 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. +pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { + if is_unreachable(e) { + StorageError::Transient(e.to_string()) + } else { + StorageError::Internal(e.to_string()) + } +} + +/// 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"; + +#[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::{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}; + 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 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(CLOSED_PORT_URI) + .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}"); + } + + /// 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. + /// + /// 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 = engine_on_a_closed_port().await; + + 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 ab9750f95..59b515dcc 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 management_store_secrets; mod metadata_engine; diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index 09f7eabb6..60454b051 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -1299,7 +1299,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 @@ -1320,7 +1320,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 @@ -1388,12 +1388,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)?); } @@ -1451,7 +1451,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 @@ -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:?}" + ); + } } diff --git a/tests/test_mongodb_backend_unreachable.py b/tests/test_mongodb_backend_unreachable.py new file mode 100644 index 000000000..cbee017f9 --- /dev/null +++ b/tests/test_mongodb_backend_unreachable.py @@ -0,0 +1,165 @@ +# 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 ``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 +--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 -- \\ + --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 +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 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. +""" + +from __future__ import annotations + +import concurrent.futures +import os +import subprocess +import time +import uuid + +import pytest + +from conftest import scoped_table + +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_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"], + error.get("Code", ""), + error.get("Message", ""), + ) + return response["ResponseMetadata"]["HTTPStatusCode"], "OK", "" + + +def test_backend_unreachable_is_service_unavailable( + dynamodb_client, no_retry_client, mongodb_container +): + """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: + # 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"}}, + ), + "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_code_message, 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) + + # 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" + )