Skip to main content

dynamo_runtime/
error.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Dynamo's shared semantic error contract.
5//!
6//! A [`DynamoError`] describes **what failed**. It deliberately does not prescribe an HTTP status, retry action, stream action, or worker-health decision. Those decisions belong to the consumer that owns the relevant local state, such as response commitment, retry budget, replayability, deadline, and worker observations.
7//!
8//! The component closest to the cause classifies a failure once. Callers should propagate an existing [`DynamoError`] directly; internal transports preserve its semantic identity, and protocol boundaries render it for their clients. Generic conversion from an error chain recovers a typed non-internal semantic source, but it intentionally treats an unclassified or internal source as `Internal/runtime.unclassified`. See [DEP #14354](https://github.com/ai-dynamo/dynamo/issues/14354) for the architecture and rollout rationale.
9//!
10//! # Error identity
11//!
12//! Every error has two identity fields:
13//!
14//! - [`ErrorClass`] is the coarse, closed category used for exhaustive consumer policy. New producers should select a canonical class such as [`ErrorClass::InvalidRequest`] or [`ErrorClass::Unavailable`]. The older transport-specific variants are retained for compatibility and normalize through [`DynamoError::class`].
15//! - [`ErrorReason`] is a stable, bounded catalog key that identifies the specific cause. A reason belongs to exactly one normalized class. It is safe for low-cardinality policy and metric dimensions; arbitrary exception text and user input are not.
16//!
17//! The builder and deserializer validate the class/reason pair. An unknown, malformed, or mismatched identity fails closed to `Internal/runtime.invalid_error`, and its public details are discarded. Consumers should therefore use [`DynamoError::class`], [`DynamoError::reason`], and [`DynamoError::public_details`] instead of reading the public fields directly. [`DynamoError::error_type`] exists for legacy policy only.
18//!
19//! ## Choosing a canonical class
20//!
21//! | Class | Use when |
22//! |---|---|
23//! | [`ErrorClass::InvalidRequest`] | The caller supplied malformed input or failed request-level validation. |
24//! | [`ErrorClass::Unauthenticated`] | Authentication credentials are missing or invalid. |
25//! | [`ErrorClass::PermissionDenied`] | The authenticated caller is not allowed to perform the operation. |
26//! | [`ErrorClass::NotFound`] | A caller-visible resource does not exist. |
27//! | [`ErrorClass::Conflict`] | The request conflicts with current resource state. |
28//! | [`ErrorClass::PayloadTooLarge`] | The request exceeds an advertised size limit. |
29//! | [`ErrorClass::UnsupportedMedia`] | The request uses an unsupported media type. |
30//! | [`ErrorClass::RateLimited`] | A caller-specific admission or rate limit was exceeded. |
31//! | [`ErrorClass::CapacityExhausted`] | Dynamo, a selected worker, or the eligible worker pool lacks capacity; the reason distinguishes worker overload from pool exhaustion. |
32//! | [`ErrorClass::Cancelled`] | The request was cancelled, usually because the client disconnected. |
33//! | [`ErrorClass::Unavailable`] | A service, worker, pool, or Dynamo-owned dependency is unavailable. |
34//! | [`ErrorClass::BackendProtocol`] | A backend response violates the expected protocol. |
35//! | [`ErrorClass::DeadlineExceeded`] | A request or attempt deadline expired. |
36//! | [`ErrorClass::NotImplemented`] | A valid requested capability is unsupported. |
37//! | [`ErrorClass::Internal`] | A defect, invalid classification, or otherwise unclassified failure occurred. |
38//!
39//! Similar symptoms do not necessarily have the same class. For example, malformed client input is [`ErrorClass::InvalidRequest`], invalid operator configuration is [`ErrorClass::Internal`], caller-specific throttling is [`ErrorClass::RateLimited`], and pool-wide capacity pressure is [`ErrorClass::CapacityExhausted`].
40//!
41//! A worker overload limited to one data-parallel rank is [`ErrorClass::WorkerRankOverloaded`], which carries the rank. Like [`ErrorClass::WorkerOverloaded`], it normalizes to [`ErrorClass::CapacityExhausted`] with the default reason `capacity.worker_overloaded`, and [`match_error_chain`] matches it wherever a set names [`ErrorClass::WorkerOverloaded`]. On the wire, a [`DynamoError`] with it keeps the worker overload's class, legacy type, and reason, and adds the rank as an optional `dp_rank` field, which this reader honors only with that reason. Readers that predate the field decode a whole-worker overload, as this reader does when the field is absent or malformed.
42//!
43//! # Data visibility
44//!
45//! [`Diagnostic`] contains bounded operator-facing context. It may be used in logs and traces, but it must never be copied into a client response or metric label. Do not place secrets, credentials, prompts, generated text, or raw upstream response bodies in a diagnostic.
46//!
47//! [`PublicDetails`] is the only occurrence-specific channel available for client rendering, but the type does not sanitize its values. Producers must populate it only at a boundary that knows the value is safe. A [`PublicDetails::Message`] must contain fixed, cataloged, or explicitly allowlisted text; it must not contain user input, prompts, generated content, secrets, URLs, diagnostics, or raw upstream responses. Never derive public details from a diagnostic or arbitrary backend exception text.
48//!
49//! # Producer guidance
50//!
51//! 1. Classify at the boundary that understands the cause instead of relying on message parsing farther downstream.
52//! 2. Select the canonical class for the failure's meaning, independent of the current transport.
53//! 3. Use a registered reason that belongs to that class. Add new reasons to the catalog with class-consistency tests rather than emitting dynamic strings.
54//! 4. Add a diagnostic only when it improves operator debugging, and add public details only when they are explicitly client-safe.
55//! 5. Propagate an existing [`DynamoError`] directly whenever possible. If a generic wrapper is unavoidable, retain the typed error as its source and remember that generic conversion recovers only non-internal semantic classifications.
56//!
57//! [`DynamoError::msg`], conversion from an unclassified [`std::error::Error`], and conversion from a generic wrapper whose typed source is internal intentionally produce `Internal/runtime.unclassified`; use them as a fallback, not for failures whose meaning is known.
58//!
59//! ```rust,no_run
60//! use dynamo_runtime::error::{DynamoError, ErrorClass, ErrorReason};
61//!
62//! let error = DynamoError::builder()
63//!     .class(ErrorClass::InvalidRequest)
64//!     .reason(ErrorReason::new("request.invalid").expect("registered reason"))
65//!     .diagnostic("messages[2].role failed validation")
66//!     .public_message("The message role is invalid")
67//!     .build();
68//!
69//! assert_eq!(error.class(), ErrorClass::InvalidRequest);
70//! assert_eq!(error.reason().as_str(), "request.invalid");
71//! assert_eq!(error.public_message(), Some("The message role is invalid"));
72//! ```
73//!
74//! Structured details are preferable when the protocol renderer needs machine-readable values:
75//!
76//! ```rust,no_run
77//! use dynamo_runtime::error::{DynamoError, ErrorClass, ErrorReason, PublicDetails};
78//!
79//! let error = DynamoError::builder()
80//!     .class(ErrorClass::PayloadTooLarge)
81//!     .reason(ErrorReason::new("request.payload_too_large").expect("registered reason"))
82//!     .public_details(PublicDetails::SizeLimit {
83//!         limit: 1_048_576,
84//!         actual: Some(1_250_000),
85//!     })
86//!     .build();
87//! ```
88//!
89//! # Consumer guidance
90//!
91//! Consumers apply their own policy to the validated semantic identity:
92//!
93//! - Protocol renderers map [`DynamoError::class`] to a status or legal terminal stream event and expose only approved [`PublicDetails`].
94//! - Retry and migration code owns its reason policy and combines it with locally owned budget, deadline, routing, replay, and continuation state.
95//! - Worker-health code combines the reason with local worker and pool observations rather than inferring health from an HTTP status.
96//! - Metrics use the normalized class and registered reason. Diagnostics, request identifiers, exception types, URLs, and user-controlled values must not become labels.
97//!
98//! A recovered internal attempt is not a final client failure. Terminal failure accounting belongs at the frontend rendering boundary so one propagated error is not counted by every subsystem it crosses.
99
100use serde::{Deserialize, Serialize};
101use std::fmt;
102use std::sync::{Arc, LazyLock};
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
105pub enum ErrorClass {
106    /// The request contains invalid input (e.g., prompt exceeds context length).
107    InvalidArgument,
108    /// Failed to establish a connection to a remote worker.
109    CannotConnect,
110    /// An established connection was lost unexpectedly.
111    Disconnected,
112    /// A connection or request timed out.
113    ConnectionTimeout,
114    /// The backend accepted the request but stopped responding (stream inactivity timeout).
115    ResponseTimeout,
116    /// The request was cancelled (e.g., client disconnected).
117    Cancelled,
118    /// The capacity constraint cannot be relieved by selecting another worker.
119    /// This most commonly means the whole eligible worker pool is exhausted.
120    ResourceExhausted,
121    /// One selected worker is out of capacity while others may still have room.
122    /// Distinct from [`Self::ResourceExhausted`] so a request whose routing
123    /// constraints permit reassignment can migrate; both surface as HTTP 529.
124    WorkerOverloaded,
125    /// A [`Self::WorkerOverloaded`] limited to one data-parallel rank, by its
126    /// global rank ID: the worker's other ranks may still have capacity.
127    WorkerRankOverloaded(u32),
128    /// No backend worker is currently available to handle the request.
129    Unavailable,
130    /// One addressed worker answered that it does not serve this request's
131    /// endpoint instance (stale discovery or a worker shutting down) while
132    /// other workers may. Distinct from [`Self::Unavailable`] so the request
133    /// can migrate; both surface as HTTP 503.
134    WorkerUnavailable,
135    /// Error originating from a backend engine.
136    Backend(BackendError),
137    /// The client request is malformed or fails request-level validation.
138    InvalidRequest,
139    /// Authentication credentials are missing or invalid.
140    Unauthenticated,
141    /// The authenticated caller is not permitted to perform the operation.
142    PermissionDenied,
143    /// The requested resource does not exist.
144    NotFound,
145    /// The request conflicts with current resource state.
146    Conflict,
147    /// The request body exceeds a configured size limit.
148    PayloadTooLarge,
149    /// The request uses an unsupported media type.
150    UnsupportedMedia,
151    /// The caller exceeded an admission or request-rate limit.
152    RateLimited,
153    /// The eligible worker pool has no capacity.
154    CapacityExhausted,
155    /// A backend response violates the expected protocol.
156    BackendProtocol,
157    /// The operation exceeded its deadline.
158    DeadlineExceeded,
159    /// The requested operation is not implemented.
160    NotImplemented,
161    /// An internal defect or unclassified failure occurred.
162    Internal,
163    /// Uncategorized or unknown error.
164    Unknown,
165}
166
167#[derive(Deserialize)]
168#[serde(untagged)]
169#[allow(non_snake_case)]
170enum ErrorClassWire {
171    Named(String),
172    Backend { Backend: BackendError },
173    WorkerRankOverloaded { WorkerRankOverloaded: u32 },
174}
175
176impl ErrorClass {
177    fn from_wire_name(name: &str) -> Self {
178        match name {
179            "InvalidArgument" => Self::InvalidArgument,
180            "CannotConnect" => Self::CannotConnect,
181            "Disconnected" => Self::Disconnected,
182            "ConnectionTimeout" => Self::ConnectionTimeout,
183            "ResponseTimeout" => Self::ResponseTimeout,
184            "Cancelled" => Self::Cancelled,
185            "ResourceExhausted" => Self::ResourceExhausted,
186            "WorkerOverloaded" => Self::WorkerOverloaded,
187            "Unavailable" => Self::Unavailable,
188            "WorkerUnavailable" => Self::WorkerUnavailable,
189            "InvalidRequest" => Self::InvalidRequest,
190            "Unauthenticated" => Self::Unauthenticated,
191            "PermissionDenied" => Self::PermissionDenied,
192            "NotFound" => Self::NotFound,
193            "Conflict" => Self::Conflict,
194            "PayloadTooLarge" => Self::PayloadTooLarge,
195            "UnsupportedMedia" => Self::UnsupportedMedia,
196            "RateLimited" => Self::RateLimited,
197            "CapacityExhausted" => Self::CapacityExhausted,
198            "BackendProtocol" => Self::BackendProtocol,
199            "DeadlineExceeded" => Self::DeadlineExceeded,
200            "NotImplemented" => Self::NotImplemented,
201            "Internal" => Self::Internal,
202            _ => Self::Unknown,
203        }
204    }
205}
206
207impl<'de> Deserialize<'de> for ErrorClass {
208    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
209    where
210        D: serde::Deserializer<'de>,
211    {
212        Ok(match ErrorClassWire::deserialize(deserializer)? {
213            ErrorClassWire::Named(name) => Self::from_wire_name(&name),
214            ErrorClassWire::Backend { Backend: error } => Self::Backend(error),
215            ErrorClassWire::WorkerRankOverloaded {
216                WorkerRankOverloaded: rank,
217            } => Self::WorkerRankOverloaded(rank),
218        })
219    }
220}
221
222impl fmt::Display for ErrorClass {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        match self {
225            ErrorClass::Unknown => write!(f, "Unknown"),
226            ErrorClass::InvalidArgument => write!(f, "InvalidArgument"),
227            ErrorClass::CannotConnect => write!(f, "CannotConnect"),
228            ErrorClass::Disconnected => write!(f, "Disconnected"),
229            ErrorClass::ConnectionTimeout => write!(f, "ConnectionTimeout"),
230            ErrorClass::ResponseTimeout => write!(f, "ResponseTimeout"),
231            ErrorClass::Cancelled => write!(f, "Cancelled"),
232            ErrorClass::ResourceExhausted => write!(f, "ResourceExhausted"),
233            ErrorClass::WorkerOverloaded => write!(f, "WorkerOverloaded"),
234            ErrorClass::WorkerRankOverloaded(rank) => write!(f, "WorkerRankOverloaded({rank})"),
235            ErrorClass::Unavailable => write!(f, "Unavailable"),
236            ErrorClass::WorkerUnavailable => write!(f, "WorkerUnavailable"),
237            ErrorClass::Backend(sub) => write!(f, "Backend{sub}"),
238            ErrorClass::InvalidRequest => write!(f, "InvalidRequest"),
239            ErrorClass::Unauthenticated => write!(f, "Unauthenticated"),
240            ErrorClass::PermissionDenied => write!(f, "PermissionDenied"),
241            ErrorClass::NotFound => write!(f, "NotFound"),
242            ErrorClass::Conflict => write!(f, "Conflict"),
243            ErrorClass::PayloadTooLarge => write!(f, "PayloadTooLarge"),
244            ErrorClass::UnsupportedMedia => write!(f, "UnsupportedMedia"),
245            ErrorClass::RateLimited => write!(f, "RateLimited"),
246            ErrorClass::CapacityExhausted => write!(f, "CapacityExhausted"),
247            ErrorClass::BackendProtocol => write!(f, "BackendProtocol"),
248            ErrorClass::DeadlineExceeded => write!(f, "DeadlineExceeded"),
249            ErrorClass::NotImplemented => write!(f, "NotImplemented"),
250            ErrorClass::Internal => write!(f, "Internal"),
251        }
252    }
253}
254
255impl ErrorClass {
256    /// Return the canonical semantic class for a legacy or backend-specific variant.
257    pub fn as_str(self) -> &'static str {
258        match self {
259            Self::Unknown => "Unknown",
260            Self::InvalidArgument => "InvalidArgument",
261            Self::CannotConnect => "CannotConnect",
262            Self::Disconnected => "Disconnected",
263            Self::ConnectionTimeout => "ConnectionTimeout",
264            Self::ResponseTimeout => "ResponseTimeout",
265            Self::Cancelled => "Cancelled",
266            Self::ResourceExhausted => "ResourceExhausted",
267            Self::WorkerOverloaded => "WorkerOverloaded",
268            Self::WorkerRankOverloaded(_) => "WorkerRankOverloaded",
269            Self::Unavailable => "Unavailable",
270            Self::WorkerUnavailable => "WorkerUnavailable",
271            Self::Backend(BackendError::Unknown) => "BackendUnknown",
272            Self::Backend(BackendError::InvalidArgument) => "BackendInvalidArgument",
273            Self::Backend(BackendError::CannotConnect) => "BackendCannotConnect",
274            Self::Backend(BackendError::Disconnected) => "BackendDisconnected",
275            Self::Backend(BackendError::ConnectionTimeout) => "BackendConnectionTimeout",
276            Self::Backend(BackendError::ResponseTimeout) => "BackendResponseTimeout",
277            Self::Backend(BackendError::Cancelled) => "BackendCancelled",
278            Self::Backend(BackendError::EngineShutdown) => "BackendEngineShutdown",
279            Self::Backend(BackendError::StreamIncomplete) => "BackendStreamIncomplete",
280            Self::Backend(BackendError::WorkerOverloaded) => "BackendWorkerOverloaded",
281            Self::InvalidRequest => "InvalidRequest",
282            Self::Unauthenticated => "Unauthenticated",
283            Self::PermissionDenied => "PermissionDenied",
284            Self::NotFound => "NotFound",
285            Self::Conflict => "Conflict",
286            Self::PayloadTooLarge => "PayloadTooLarge",
287            Self::UnsupportedMedia => "UnsupportedMedia",
288            Self::RateLimited => "RateLimited",
289            Self::CapacityExhausted => "CapacityExhausted",
290            Self::BackendProtocol => "BackendProtocol",
291            Self::DeadlineExceeded => "DeadlineExceeded",
292            Self::NotImplemented => "NotImplemented",
293            Self::Internal => "Internal",
294        }
295    }
296
297    /// Map a legacy or backend-specific variant to its canonical semantic class.
298    ///
299    /// New producers should construct canonical classes directly. [`DynamoError::class`] applies this mapping after validating the class/reason identity and is the normal consumer entry point. Serialization also emits that validated canonical class, while retaining a compatible legacy representation during the migration window.
300    pub fn normalized(self) -> Self {
301        match self {
302            Self::Unknown => Self::Internal,
303            Self::InvalidArgument => Self::InvalidRequest,
304            Self::CannotConnect | Self::Disconnected | Self::WorkerUnavailable => Self::Unavailable,
305            Self::ConnectionTimeout | Self::ResponseTimeout => Self::DeadlineExceeded,
306            Self::ResourceExhausted | Self::WorkerOverloaded | Self::WorkerRankOverloaded(_) => {
307                Self::CapacityExhausted
308            }
309            Self::Backend(error) => match error {
310                BackendError::Unknown => Self::Internal,
311                BackendError::InvalidArgument => Self::InvalidRequest,
312                BackendError::CannotConnect
313                | BackendError::Disconnected
314                | BackendError::EngineShutdown
315                | BackendError::StreamIncomplete => Self::Unavailable,
316                BackendError::ConnectionTimeout | BackendError::ResponseTimeout => {
317                    Self::DeadlineExceeded
318                }
319                BackendError::Cancelled => Self::Cancelled,
320                BackendError::WorkerOverloaded => Self::CapacityExhausted,
321            },
322            canonical @ (Self::Cancelled
323            | Self::Unavailable
324            | Self::InvalidRequest
325            | Self::Unauthenticated
326            | Self::PermissionDenied
327            | Self::NotFound
328            | Self::Conflict
329            | Self::PayloadTooLarge
330            | Self::UnsupportedMedia
331            | Self::RateLimited
332            | Self::CapacityExhausted
333            | Self::BackendProtocol
334            | Self::DeadlineExceeded
335            | Self::NotImplemented
336            | Self::Internal) => canonical,
337        }
338    }
339}
340
341/// Backward-compatible name retained while callers migrate to ErrorClass.
342pub type ErrorType = ErrorClass;
343
344/// Categorizes errors into a fixed set of standard types.
345///
346/// Consumers (e.g., the migration module) inspect the error type to decide
347/// what action to take, rather than the error defining its own behavior.
348/// Backend engine error subcategories.
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
350pub enum BackendError {
351    /// Uncategorized or unknown backend error.
352    Unknown,
353    /// The request contains invalid input (e.g., prompt exceeds context length).
354    InvalidArgument,
355    /// Failed to establish a connection to a remote worker.
356    CannotConnect,
357    /// An established connection was lost unexpectedly.
358    Disconnected,
359    /// A connection or request timed out.
360    ConnectionTimeout,
361    /// The backend accepted the request but stopped responding (stream inactivity timeout).
362    ResponseTimeout,
363    /// The request was cancelled (e.g., client disconnected).
364    Cancelled,
365    /// The engine process has shut down or crashed.
366    EngineShutdown,
367    /// The response stream was terminated before completion (e.g., engine dropped mid-stream).
368    StreamIncomplete,
369    /// The worker's transient admission budget is exhausted.
370    WorkerOverloaded,
371}
372
373impl fmt::Display for BackendError {
374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375        match self {
376            BackendError::Unknown => write!(f, "Unknown"),
377            BackendError::InvalidArgument => write!(f, "InvalidArgument"),
378            BackendError::CannotConnect => write!(f, "CannotConnect"),
379            BackendError::Disconnected => write!(f, "Disconnected"),
380            BackendError::ConnectionTimeout => write!(f, "ConnectionTimeout"),
381            BackendError::ResponseTimeout => write!(f, "ResponseTimeout"),
382            BackendError::Cancelled => write!(f, "Cancelled"),
383            BackendError::EngineShutdown => write!(f, "EngineShutdown"),
384            BackendError::StreamIncomplete => write!(f, "StreamIncomplete"),
385            BackendError::WorkerOverloaded => write!(f, "WorkerOverloaded"),
386        }
387    }
388}
389
390/// Stable, bounded catalog key for a specific failure cause.
391#[derive(Debug, Clone, PartialEq, Eq, Hash)]
392pub struct ErrorReason(String);
393
394impl ErrorReason {
395    pub const MAX_BYTES: usize = 128;
396
397    pub fn new(value: impl Into<String>) -> Result<Self, InvalidErrorReason> {
398        let value = value.into();
399        if value.is_empty() {
400            return Err(InvalidErrorReason::Empty);
401        }
402        if value.len() > Self::MAX_BYTES {
403            return Err(InvalidErrorReason::TooLong);
404        }
405        if !value.bytes().all(|byte| {
406            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"._-".contains(&byte)
407        }) {
408            return Err(InvalidErrorReason::InvalidCharacter);
409        }
410        if Self::catalog_class(&value).is_none() {
411            return Err(InvalidErrorReason::UnknownCatalogKey);
412        }
413        Ok(Self(value))
414    }
415
416    pub fn as_str(&self) -> &str {
417        &self.0
418    }
419
420    fn catalog_class(value: &str) -> Option<ErrorClass> {
421        match value {
422            "runtime.unclassified" | "runtime.invalid_error" | "runtime.internal" => {
423                Some(ErrorClass::Internal)
424            }
425            "request.invalid_argument" | "backend.invalid_argument" | "request.invalid" => {
426                Some(ErrorClass::InvalidRequest)
427            }
428            "transport.cannot_connect"
429            | "transport.disconnected"
430            | "backend.unavailable"
431            | "backend.worker_unavailable"
432            | "backend.cannot_connect"
433            | "backend.disconnected"
434            | "backend.engine_shutdown"
435            | "backend.stream_incomplete" => Some(ErrorClass::Unavailable),
436            "transport.connection_timeout"
437            | "backend.response_timeout"
438            | "backend.connection_timeout"
439            | "request.deadline_exceeded"
440            | "router.queue_deadline_exceeded" => Some(ErrorClass::DeadlineExceeded),
441            "request.cancelled" | "backend.cancelled" => Some(ErrorClass::Cancelled),
442            "capacity.pool_exhausted" | "capacity.worker_overloaded" | "capacity.exhausted" => {
443                Some(ErrorClass::CapacityExhausted)
444            }
445            "backend.unknown" => Some(ErrorClass::Internal),
446            "backend.protocol" => Some(ErrorClass::BackendProtocol),
447            "request.unauthenticated" => Some(ErrorClass::Unauthenticated),
448            "request.permission_denied" => Some(ErrorClass::PermissionDenied),
449            "request.not_found" => Some(ErrorClass::NotFound),
450            "request.conflict" => Some(ErrorClass::Conflict),
451            "request.payload_too_large" => Some(ErrorClass::PayloadTooLarge),
452            "request.unsupported_media" => Some(ErrorClass::UnsupportedMedia),
453            "request.rate_limited" => Some(ErrorClass::RateLimited),
454            "runtime.not_implemented" => Some(ErrorClass::NotImplemented),
455            _ => None,
456        }
457    }
458
459    fn from_static(value: &'static str) -> Self {
460        debug_assert!(!value.is_empty() && value.len() <= Self::MAX_BYTES);
461        debug_assert!(value.bytes().all(|byte| {
462            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"._-".contains(&byte)
463        }));
464        debug_assert!(Self::catalog_class(value).is_some());
465        Self(value.to_owned())
466    }
467
468    fn for_class(class: ErrorClass) -> Self {
469        let value = match class {
470            ErrorClass::Unknown => "runtime.unclassified",
471            ErrorClass::InvalidArgument => "request.invalid_argument",
472            ErrorClass::CannotConnect => "transport.cannot_connect",
473            ErrorClass::Disconnected => "transport.disconnected",
474            ErrorClass::ConnectionTimeout => "transport.connection_timeout",
475            ErrorClass::ResponseTimeout => "backend.response_timeout",
476            ErrorClass::Cancelled => "request.cancelled",
477            ErrorClass::ResourceExhausted => "capacity.pool_exhausted",
478            ErrorClass::WorkerOverloaded | ErrorClass::WorkerRankOverloaded(_) => {
479                "capacity.worker_overloaded"
480            }
481            ErrorClass::Unavailable => "backend.unavailable",
482            ErrorClass::WorkerUnavailable => "backend.worker_unavailable",
483            ErrorClass::Backend(error) => match error {
484                BackendError::Unknown => "backend.unknown",
485                BackendError::InvalidArgument => "backend.invalid_argument",
486                BackendError::CannotConnect => "backend.cannot_connect",
487                BackendError::Disconnected => "backend.disconnected",
488                BackendError::ConnectionTimeout => "backend.connection_timeout",
489                BackendError::ResponseTimeout => "backend.response_timeout",
490                BackendError::Cancelled => "backend.cancelled",
491                BackendError::EngineShutdown => "backend.engine_shutdown",
492                BackendError::StreamIncomplete => "backend.stream_incomplete",
493                BackendError::WorkerOverloaded => "capacity.worker_overloaded",
494            },
495            ErrorClass::InvalidRequest => "request.invalid",
496            ErrorClass::Unauthenticated => "request.unauthenticated",
497            ErrorClass::PermissionDenied => "request.permission_denied",
498            ErrorClass::NotFound => "request.not_found",
499            ErrorClass::Conflict => "request.conflict",
500            ErrorClass::PayloadTooLarge => "request.payload_too_large",
501            ErrorClass::UnsupportedMedia => "request.unsupported_media",
502            ErrorClass::RateLimited => "request.rate_limited",
503            ErrorClass::CapacityExhausted => "capacity.exhausted",
504            ErrorClass::BackendProtocol => "backend.protocol",
505            ErrorClass::DeadlineExceeded => "request.deadline_exceeded",
506            ErrorClass::NotImplemented => "runtime.not_implemented",
507            ErrorClass::Internal => "runtime.internal",
508        };
509        Self::from_static(value)
510    }
511}
512
513static INVALID_ERROR_REASON: LazyLock<ErrorReason> =
514    LazyLock::new(|| ErrorReason::from_static("runtime.invalid_error"));
515
516impl fmt::Display for ErrorReason {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        f.write_str(&self.0)
519    }
520}
521
522impl Serialize for ErrorReason {
523    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
524    where
525        S: serde::Serializer,
526    {
527        serializer.serialize_str(&self.0)
528    }
529}
530
531impl<'de> Deserialize<'de> for ErrorReason {
532    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
533    where
534        D: serde::Deserializer<'de>,
535    {
536        let value = String::deserialize(deserializer)?;
537        Self::new(value).map_err(serde::de::Error::custom)
538    }
539}
540
541#[derive(Debug, Clone, Copy, PartialEq, Eq)]
542pub enum InvalidErrorReason {
543    Empty,
544    TooLong,
545    InvalidCharacter,
546    UnknownCatalogKey,
547}
548
549impl fmt::Display for InvalidErrorReason {
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        match self {
552            Self::Empty => f.write_str("error reason cannot be empty"),
553            Self::TooLong => write!(f, "error reason exceeds {} bytes", ErrorReason::MAX_BYTES),
554            Self::InvalidCharacter => f.write_str(
555                "error reason may contain only lowercase ASCII, digits, '.', '_', or '-'",
556            ),
557            Self::UnknownCatalogKey => f.write_str("error reason is not registered in the catalog"),
558        }
559    }
560}
561
562impl std::error::Error for InvalidErrorReason {}
563
564/// Closed set of structured, client-safe details.
565#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
566#[serde(tag = "type", rename_all = "snake_case")]
567pub enum PublicDetails {
568    Message {
569        message: String,
570    },
571    SizeLimit {
572        limit: u64,
573        actual: Option<u64>,
574    },
575    ContextLength {
576        limit: u64,
577        actual: Option<u64>,
578    },
579    RateLimit {
580        limit: Option<u64>,
581        remaining: Option<u64>,
582    },
583}
584
585impl PublicDetails {
586    /// Returns the client-safe rejection message when one was explicitly captured.
587    pub fn message(&self) -> Option<&str> {
588        match self {
589            Self::Message { message } => Some(message),
590            Self::SizeLimit { .. } | Self::ContextLength { .. } | Self::RateLimit { .. } => None,
591        }
592    }
593}
594
595/// Decode the optional `dp_rank` of a [`ErrorClass::WorkerRankOverloaded`],
596/// treating one that is not a rank ID as absent rather than failing the whole
597/// error.
598fn deserialize_dp_rank<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
599where
600    D: serde::Deserializer<'de>,
601{
602    Ok(Option::<serde_json::Value>::deserialize(deserializer)?
603        .and_then(|rank| rank.as_u64())
604        .and_then(|rank| u32::try_from(rank).ok()))
605}
606
607fn bounded_message(mut message: String) -> String {
608    if message.len() > Diagnostic::MAX_BYTES {
609        let mut end = Diagnostic::MAX_BYTES - Diagnostic::TRUNCATION_SUFFIX.len();
610        while !message.is_char_boundary(end) {
611            end -= 1;
612        }
613        message.truncate(end);
614        message.push_str(Diagnostic::TRUNCATION_SUFFIX);
615    }
616    message
617}
618
619/// Bounded operator-only diagnostic text.
620#[derive(Debug, Clone, Default)]
621pub struct Diagnostic {
622    message: String,
623    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
624}
625
626impl Diagnostic {
627    pub const MAX_BYTES: usize = 4096;
628    pub const TRUNCATION_SUFFIX: &'static str = "...[truncated]";
629
630    pub fn new(value: impl Into<String>) -> Self {
631        Self {
632            message: bounded_message(value.into()),
633            source: None,
634        }
635    }
636
637    fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
638        self.source = Some(Arc::new(source));
639        self
640    }
641
642    pub fn as_str(&self) -> &str {
643        &self.message
644    }
645
646    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
647        self.source
648            .as_deref()
649            .map(|source| source as &(dyn std::error::Error + 'static))
650    }
651}
652
653impl PartialEq for Diagnostic {
654    fn eq(&self, other: &Self) -> bool {
655        self.message == other.message
656    }
657}
658
659impl Eq for Diagnostic {}
660
661impl Serialize for Diagnostic {
662    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
663    where
664        S: serde::Serializer,
665    {
666        serializer.serialize_str(&self.message)
667    }
668}
669
670impl<'de> Deserialize<'de> for Diagnostic {
671    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
672    where
673        D: serde::Deserializer<'de>,
674    {
675        Ok(Self::new(String::deserialize(deserializer)?))
676    }
677}
678
679// ============================================================================
680// DynamoError - The Standardized Error Type
681// ============================================================================
682
683/// The standardized error type for Dynamo.
684///
685/// `DynamoError` is a serializable semantic error that:
686/// - Carries an [`ErrorClass`] for categorization
687/// - Is serializable for network transmission via `Annotated`
688/// - Can be created from any [`std::error::Error`]
689///
690/// # Display
691///
692/// `Display` shows the private diagnostic when present and otherwise the reason.
693///
694/// ```rust,ignore
695/// let err = DynamoError::msg("outer");
696/// println!("{}", err); // "Internal: outer"
697/// ```
698#[derive(Debug, Clone, PartialEq, Eq)]
699pub struct DynamoError {
700    /// Coarse semantic category. This may retain a compatible legacy variant internally; use [`Self::class`] for validated consumer policy.
701    pub class: ErrorClass,
702    /// Registered, bounded cause key that must belong to the normalized class; use [`Self::reason`] for validated consumer policy.
703    pub reason: ErrorReason,
704    /// Optional bounded operator-only context. This is not client-safe and must not be used as a metric label.
705    pub diagnostic: Option<Diagnostic>,
706    /// Optional explicitly client-safe data. The producer remains responsible for ensuring every contained value is safe to expose.
707    pub public: Option<PublicDetails>,
708}
709
710impl Serialize for DynamoError {
711    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
712    where
713        S: serde::Serializer,
714    {
715        use serde::ser::SerializeStruct;
716
717        let public = self.public_details();
718        let dp_rank = match self.error_type() {
719            ErrorClass::WorkerRankOverloaded(rank) => Some(rank),
720            _ => None,
721        };
722        let caused_by = self
723            .diagnostic
724            .as_ref()
725            .and_then(Diagnostic::source)
726            .and_then(|source| source.downcast_ref::<DynamoError>());
727        let mut state = serializer.serialize_struct(
728            "DynamoError",
729            4 + usize::from(self.diagnostic.is_some())
730                + usize::from(public.is_some())
731                + usize::from(dp_rank.is_some())
732                + usize::from(caused_by.is_some()),
733        )?;
734        state.serialize_field("error_type", &self.legacy_wire_error_type())?;
735        state.serialize_field("class", &self.class())?;
736        state.serialize_field("reason", self.reason())?;
737        state.serialize_field("message", &self.message())?;
738        if let Some(diagnostic) = &self.diagnostic {
739            state.serialize_field("diagnostic", diagnostic)?;
740        }
741        if let Some(public) = public {
742            state.serialize_field("public", public)?;
743        }
744        if let Some(dp_rank) = dp_rank {
745            state.serialize_field("dp_rank", &dp_rank)?;
746        }
747        if let Some(caused_by) = caused_by {
748            state.serialize_field("caused_by", caused_by)?;
749        }
750        state.end()
751    }
752}
753
754impl<'de> Deserialize<'de> for DynamoError {
755    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
756    where
757        D: serde::Deserializer<'de>,
758    {
759        #[derive(Deserialize)]
760        struct Representation {
761            #[serde(default)]
762            class: Option<ErrorClass>,
763            #[serde(default)]
764            error_type: Option<ErrorClass>,
765            #[serde(default)]
766            reason: Option<String>,
767            #[serde(default)]
768            diagnostic: Option<Diagnostic>,
769            #[serde(default)]
770            message: Option<Diagnostic>,
771            #[serde(default, rename = "public", alias = "public_details")]
772            public: Option<PublicDetails>,
773            #[serde(default, deserialize_with = "deserialize_dp_rank")]
774            dp_rank: Option<u32>,
775            #[serde(default)]
776            caused_by: Option<Box<DynamoError>>,
777        }
778
779        let representation = Representation::deserialize(deserializer)?;
780        let declared_class = representation.class;
781        let invalid_declared_class = matches!(declared_class, Some(ErrorClass::Unknown));
782        let legacy_error_type = representation.error_type;
783        let source_class = declared_class
784            .or(legacy_error_type)
785            .unwrap_or(ErrorClass::Unknown);
786        let canonical_class = match source_class {
787            ErrorClass::Unknown => ErrorClass::Internal,
788            class => class.normalized(),
789        };
790        let reason = match representation.reason {
791            Some(reason) => ErrorReason::new(reason).ok(),
792            None => Some(ErrorReason::for_class(
793                legacy_error_type.unwrap_or(source_class),
794            )),
795        };
796        let valid_reason = !invalid_declared_class
797            && reason
798                .as_ref()
799                .and_then(|reason| ErrorReason::catalog_class(reason.as_str()))
800                .is_some_and(|class| class == canonical_class);
801        let stored_class = legacy_error_type
802            .filter(|class| *class != ErrorClass::Unknown && class.normalized() == canonical_class)
803            .unwrap_or(canonical_class);
804
805        let (class, reason, public) = match reason {
806            Some(reason) if valid_reason => (
807                // Only a worker overload is limited to a rank. Its legacy type
808                // on the wire is the whole-worker one, so the reason names it.
809                match representation.dp_rank {
810                    Some(rank) if reason.as_str() == "capacity.worker_overloaded" => {
811                        ErrorClass::WorkerRankOverloaded(rank)
812                    }
813                    _ => stored_class,
814                },
815                reason,
816                representation.public,
817            ),
818            _ => (
819                ErrorClass::Internal,
820                ErrorReason::from_static("runtime.invalid_error"),
821                None,
822            ),
823        };
824
825        let diagnostic = match (
826            representation.diagnostic.or(representation.message),
827            representation.caused_by,
828        ) {
829            (Some(diagnostic), Some(caused_by)) => Some(diagnostic.with_source(*caused_by)),
830            (None, Some(caused_by)) => Some(Diagnostic::new("").with_source(*caused_by)),
831            (diagnostic, None) => diagnostic,
832        };
833
834        Ok(Self {
835            class,
836            reason,
837            diagnostic,
838            public,
839        })
840    }
841}
842
843impl DynamoError {
844    /// Create a builder for constructing a `DynamoError`.
845    pub fn builder() -> DynamoErrorBuilder {
846        DynamoErrorBuilder::default()
847    }
848
849    /// Shorthand to create an internal error with a private diagnostic.
850    pub fn msg(message: impl Into<String>) -> Self {
851        Self::builder()
852            .class(ErrorClass::Internal)
853            .reason(ErrorReason::from_static("runtime.unclassified"))
854            .diagnostic(message)
855            .build()
856    }
857
858    /// Returns the validated legacy error type without normalization.
859    ///
860    /// Invalid public-field combinations fail closed so legacy policy callers
861    /// cannot bypass the canonical identity check.
862    pub fn error_type(&self) -> ErrorType {
863        if self.has_valid_identity() {
864            self.class
865        } else {
866            ErrorClass::Internal
867        }
868    }
869
870    fn has_valid_identity(&self) -> bool {
871        ErrorReason::catalog_class(self.reason.as_str())
872            .is_some_and(|class| class == self.class.normalized())
873    }
874
875    /// Returns the canonical semantic error class.
876    pub fn class(&self) -> ErrorClass {
877        if self.has_valid_identity() {
878            self.class.normalized()
879        } else {
880            ErrorClass::Internal
881        }
882    }
883
884    fn legacy_wire_error_type(&self) -> ErrorClass {
885        match self.error_type() {
886            ErrorClass::Unknown
887            | ErrorClass::Internal
888            | ErrorClass::Unauthenticated
889            | ErrorClass::PermissionDenied
890            | ErrorClass::NotFound
891            | ErrorClass::Conflict
892            | ErrorClass::BackendProtocol
893            | ErrorClass::NotImplemented => ErrorClass::Unknown,
894            ErrorClass::InvalidArgument
895            | ErrorClass::InvalidRequest
896            | ErrorClass::PayloadTooLarge
897            | ErrorClass::UnsupportedMedia => ErrorClass::InvalidArgument,
898            ErrorClass::CannotConnect => ErrorClass::CannotConnect,
899            ErrorClass::Disconnected => ErrorClass::Disconnected,
900            ErrorClass::ConnectionTimeout => ErrorClass::ConnectionTimeout,
901            ErrorClass::ResponseTimeout | ErrorClass::DeadlineExceeded => {
902                ErrorClass::ResponseTimeout
903            }
904            ErrorClass::Cancelled => ErrorClass::Cancelled,
905            ErrorClass::ResourceExhausted
906            | ErrorClass::WorkerOverloaded
907            | ErrorClass::WorkerRankOverloaded(_)
908            | ErrorClass::CapacityExhausted
909            | ErrorClass::RateLimited => ErrorClass::ResourceExhausted,
910            ErrorClass::Unavailable => ErrorClass::Unavailable,
911            ErrorClass::WorkerUnavailable => ErrorClass::WorkerUnavailable,
912            ErrorClass::Backend(BackendError::WorkerOverloaded) => ErrorClass::ResourceExhausted,
913            ErrorClass::Backend(error) => ErrorClass::Backend(error),
914        }
915    }
916
917    /// Returns the stable reason key.
918    pub fn reason(&self) -> &ErrorReason {
919        if self.has_valid_identity() {
920            &self.reason
921        } else {
922            &INVALID_ERROR_REASON
923        }
924    }
925
926    /// Returns the optional private diagnostic.
927    pub fn diagnostic(&self) -> Option<&Diagnostic> {
928        self.diagnostic.as_ref()
929    }
930
931    /// Returns structured client-safe details.
932    pub fn public_details(&self) -> Option<&PublicDetails> {
933        self.has_valid_identity()
934            .then_some(self.public.as_ref())
935            .flatten()
936    }
937
938    /// Returns the explicitly captured client-safe rejection message.
939    pub fn public_message(&self) -> Option<&str> {
940        self.public_details().and_then(PublicDetails::message)
941    }
942
943    /// Returns the legacy error message view.
944    pub fn message(&self) -> &str {
945        self.diagnostic
946            .as_ref()
947            .map(Diagnostic::as_str)
948            .unwrap_or_default()
949    }
950}
951
952impl fmt::Display for DynamoError {
953    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954        match self.diagnostic() {
955            Some(diagnostic) if !diagnostic.as_str().is_empty() => {
956                write!(f, "{}: {}", self.class(), diagnostic.as_str())
957            }
958            _ => write!(f, "{}: {}", self.class(), self.reason()),
959        }
960    }
961}
962
963impl std::error::Error for DynamoError {
964    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
965        self.diagnostic.as_ref().and_then(Diagnostic::source)
966    }
967}
968
969/// Convert from a reference to any `std::error::Error`.
970impl<'a> From<&'a (dyn std::error::Error + 'static)> for DynamoError {
971    fn from(err: &'a (dyn std::error::Error + 'static)) -> Self {
972        if let Some(dynamo_err) = err.downcast_ref::<DynamoError>() {
973            return dynamo_err.clone();
974        }
975
976        let diagnostic = Diagnostic::new(err.to_string());
977        let Some(source) = err.source() else {
978            return Self {
979                class: ErrorClass::Internal,
980                reason: ErrorReason::from_static("runtime.unclassified"),
981                diagnostic: Some(diagnostic),
982                public: None,
983            };
984        };
985
986        let source = DynamoError::from(source);
987        let diagnostic = diagnostic.with_source(source.clone());
988        if source.has_valid_identity() && source.class() != ErrorClass::Internal {
989            return Self {
990                class: source.error_type(),
991                reason: source.reason().clone(),
992                diagnostic: Some(diagnostic),
993                public: source.public_details().cloned(),
994            };
995        }
996
997        Self {
998            class: ErrorClass::Internal,
999            reason: ErrorReason::from_static("runtime.unclassified"),
1000            diagnostic: Some(diagnostic),
1001            public: None,
1002        }
1003    }
1004}
1005
1006/// Convert from an owned boxed `std::error::Error`.
1007impl From<Box<dyn std::error::Error + 'static>> for DynamoError {
1008    fn from(err: Box<dyn std::error::Error + 'static>) -> Self {
1009        match err.downcast::<DynamoError>() {
1010            Ok(dynamo_err) => *dynamo_err,
1011            Err(err) => DynamoError::from(&*err as &(dyn std::error::Error + 'static)),
1012        }
1013    }
1014}
1015
1016// ============================================================================
1017// DynamoErrorBuilder
1018// ============================================================================
1019
1020/// Builder for constructing a [`DynamoError`].
1021///
1022/// # Example
1023/// ```rust,ignore
1024/// let err = DynamoError::builder()
1025///     .error_type(ErrorClass::Disconnected)
1026///     .message("worker lost")
1027///     .cause(some_io_error)
1028///     .build();
1029/// ```
1030#[derive(Default)]
1031pub struct DynamoErrorBuilder {
1032    class: Option<ErrorClass>,
1033    reason: Option<ErrorReason>,
1034    diagnostic: Option<Diagnostic>,
1035    public: Option<PublicDetails>,
1036}
1037
1038impl DynamoErrorBuilder {
1039    /// Set the legacy or canonical error class.
1040    pub fn error_type(mut self, error_type: ErrorType) -> Self {
1041        self.class = Some(error_type);
1042        self
1043    }
1044
1045    /// Set the canonical error class.
1046    pub fn class(self, class: ErrorClass) -> Self {
1047        self.error_type(class)
1048    }
1049
1050    /// Set the stable reason key.
1051    pub fn reason(mut self, reason: ErrorReason) -> Self {
1052        self.reason = Some(reason);
1053        self
1054    }
1055
1056    /// Set the private bounded diagnostic.
1057    pub fn diagnostic(mut self, diagnostic: impl Into<String>) -> Self {
1058        self.diagnostic = Some(Diagnostic::new(diagnostic));
1059        self
1060    }
1061
1062    /// Set the legacy error message view.
1063    pub fn message(self, message: impl Into<String>) -> Self {
1064        self.diagnostic(message)
1065    }
1066
1067    /// Set a bounded client-safe rejection message.
1068    pub fn public_message(mut self, message: impl Into<String>) -> Self {
1069        let message = bounded_message(message.into());
1070        self.public = Some(PublicDetails::Message { message });
1071        self
1072    }
1073
1074    /// Set structured client-safe details.
1075    pub fn public_details(mut self, public: PublicDetails) -> Self {
1076        self.public = Some(public);
1077        self
1078    }
1079
1080    /// Preserve compatibility with existing builders while keeping native causes out of the semantic payload.
1081    pub fn cause(mut self, cause: impl std::error::Error + 'static) -> Self {
1082        let message = cause.to_string();
1083        let source = DynamoError::from(&cause as &(dyn std::error::Error + 'static));
1084        let diagnostic = self
1085            .diagnostic
1086            .take()
1087            .unwrap_or_else(|| Diagnostic::new(message));
1088        self.diagnostic = Some(diagnostic.with_source(source));
1089        self
1090    }
1091
1092    /// Build the `DynamoError` and fail closed on a class/reason mismatch.
1093    pub fn build(self) -> DynamoError {
1094        let raw_class = self.class.unwrap_or(ErrorClass::Internal);
1095        let reason = self
1096            .reason
1097            .unwrap_or_else(|| ErrorReason::for_class(raw_class));
1098        let valid_reason = ErrorReason::catalog_class(reason.as_str())
1099            .is_some_and(|class| class == raw_class.normalized());
1100
1101        if valid_reason {
1102            DynamoError {
1103                class: raw_class,
1104                reason,
1105                diagnostic: self.diagnostic,
1106                public: self.public,
1107            }
1108        } else {
1109            DynamoError {
1110                class: ErrorClass::Internal,
1111                reason: ErrorReason::from_static("runtime.invalid_error"),
1112                diagnostic: self.diagnostic,
1113                public: None,
1114            }
1115        }
1116    }
1117}
1118
1119// ============================================================================
1120// Utility Functions
1121// ============================================================================
1122
1123/// Check whether an error chain contains a specific set of error types
1124/// while not containing any of the excluded error types.
1125///
1126/// Walks the chain via `source()`, inspecting each error that can be downcast
1127/// to `DynamoError`. Returns `false` immediately if any error's type is in
1128/// `exclude_set`. Otherwise, returns `true` if at least one error's type is
1129/// in `match_set`. Errors that are not `DynamoError` are skipped. A
1130/// [`ErrorClass::WorkerRankOverloaded`] is in a set that names its own rank or
1131/// [`ErrorClass::WorkerOverloaded`].
1132pub fn match_error_chain(
1133    err: &(dyn std::error::Error + 'static),
1134    match_set: &[ErrorClass],
1135    exclude_set: &[ErrorClass],
1136) -> bool {
1137    let mut found = false;
1138    let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
1139
1140    while let Some(e) = current {
1141        if let Some(dynamo_err) = e.downcast_ref::<DynamoError>() {
1142            let error_type = dynamo_err.error_type();
1143            let in_set = |set: &[ErrorClass]| {
1144                set.contains(&error_type)
1145                    || (matches!(error_type, ErrorClass::WorkerRankOverloaded(_))
1146                        && set.contains(&ErrorClass::WorkerOverloaded))
1147            };
1148            if in_set(exclude_set) {
1149                return false;
1150            }
1151            if in_set(match_set) {
1152                found = true;
1153            }
1154        }
1155        current = e.source();
1156    }
1157
1158    found
1159}
1160
1161// ============================================================================
1162// Tests
1163// ============================================================================
1164
1165#[cfg(test)]
1166mod tests {
1167    use super::*;
1168    use std::error::Error;
1169
1170    // Compile-time assertions that DynamoError is std::error::Error + Send + Sync + 'static.
1171    // These fail at compile time if a future change breaks these guarantees.
1172    const _: () = {
1173        fn assert_stderror<T: std::error::Error>() {}
1174        fn assert_send<T: Send>() {}
1175        fn assert_sync<T: Sync>() {}
1176        fn assert_static<T: 'static>() {}
1177        fn assert_all() {
1178            assert_stderror::<DynamoError>();
1179            assert_send::<DynamoError>();
1180            assert_sync::<DynamoError>();
1181            assert_static::<DynamoError>();
1182        }
1183    };
1184
1185    #[test]
1186    fn test_msg_constructor() {
1187        let err = DynamoError::msg("something failed");
1188        assert_eq!(err.error_type(), ErrorClass::Internal);
1189        assert_eq!(err.reason().as_str(), "runtime.unclassified");
1190        assert_eq!(err.message(), "something failed");
1191        assert!(err.source().is_none());
1192    }
1193
1194    #[test]
1195    fn cause_is_preserved_for_legacy_wire_compatibility() {
1196        let err = DynamoError::builder()
1197            .class(ErrorClass::Internal)
1198            .reason(ErrorReason::new("runtime.internal").unwrap())
1199            .diagnostic("operation failed")
1200            .cause(std::io::Error::other("io error"))
1201            .build();
1202
1203        assert_eq!(err.message(), "operation failed");
1204        assert_eq!(err.source().unwrap().to_string(), "Internal: io error");
1205        let value = serde_json::to_value(&err).unwrap();
1206        assert_eq!(value.as_object().unwrap().len(), 6);
1207        assert!(value.get("caused_by").is_some());
1208
1209        let roundtrip: DynamoError = serde_json::from_value(value).unwrap();
1210        assert_eq!(
1211            roundtrip.source().unwrap().to_string(),
1212            "Internal: io error"
1213        );
1214    }
1215
1216    #[test]
1217    fn display_uses_diagnostic_or_reason() {
1218        let with_diagnostic = DynamoError::builder()
1219            .class(ErrorClass::Internal)
1220            .reason(ErrorReason::new("runtime.internal").unwrap())
1221            .diagnostic("operation failed")
1222            .build();
1223        let without_diagnostic = DynamoError::builder()
1224            .class(ErrorClass::Internal)
1225            .reason(ErrorReason::new("runtime.internal").unwrap())
1226            .build();
1227
1228        assert_eq!(with_diagnostic.to_string(), "Internal: operation failed");
1229        assert_eq!(without_diagnostic.to_string(), "Internal: runtime.internal");
1230    }
1231
1232    #[test]
1233    fn conversion_preserves_nested_semantic_source_locally() {
1234        #[derive(Debug)]
1235        struct OuterError {
1236            source: DynamoError,
1237        }
1238
1239        impl fmt::Display for OuterError {
1240            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1241                f.write_str("outer failure")
1242            }
1243        }
1244
1245        impl std::error::Error for OuterError {
1246            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1247                Some(&self.source)
1248            }
1249        }
1250
1251        let outer = OuterError {
1252            source: DynamoError::builder()
1253                .error_type(ErrorType::InvalidArgument)
1254                .diagnostic("invalid input")
1255                .build(),
1256        };
1257        let converted = DynamoError::from(&outer as &(dyn std::error::Error + 'static));
1258
1259        assert!(match_error_chain(
1260            &converted,
1261            &[ErrorType::InvalidArgument],
1262            &[]
1263        ));
1264        let value = serde_json::to_value(converted).unwrap();
1265        assert!(value.get("caused_by").is_some());
1266    }
1267
1268    #[test]
1269    fn test_from_boxed_std_error() {
1270        let std_err = std::io::Error::other("io error");
1271        let boxed: Box<dyn std::error::Error> = Box::new(std_err);
1272        let dynamo_err = DynamoError::from(boxed);
1273
1274        assert_eq!(dynamo_err.class(), ErrorClass::Internal);
1275        assert_eq!(dynamo_err.reason().as_str(), "runtime.unclassified");
1276        assert_eq!(dynamo_err.message(), "io error");
1277    }
1278
1279    #[test]
1280    fn test_from_boxed_takes_ownership_of_dynamo_error() {
1281        let inner = DynamoError::msg("original");
1282        let boxed: Box<dyn std::error::Error> = Box::new(inner);
1283        let dynamo_err = DynamoError::from(boxed);
1284
1285        assert_eq!(dynamo_err.class(), ErrorClass::Internal);
1286        assert_eq!(dynamo_err.message(), "original");
1287    }
1288
1289    #[test]
1290    fn semantic_metadata_roundtrips() {
1291        let err = DynamoError::builder()
1292            .class(ErrorClass::RateLimited)
1293            .reason(ErrorReason::new("request.rate_limited").unwrap())
1294            .diagnostic("request rate exceeded")
1295            .public_details(PublicDetails::RateLimit {
1296                limit: Some(100),
1297                remaining: Some(0),
1298            })
1299            .build();
1300
1301        let json = serde_json::to_string(&err).unwrap();
1302        let deserialized: DynamoError = serde_json::from_str(&json).unwrap();
1303
1304        assert_eq!(deserialized.class(), ErrorClass::RateLimited);
1305        assert_eq!(deserialized.reason().as_str(), "request.rate_limited");
1306        assert_eq!(
1307            deserialized.diagnostic().map(Diagnostic::as_str),
1308            Some("request rate exceeded")
1309        );
1310        assert_eq!(
1311            deserialized.public_details(),
1312            Some(&PublicDetails::RateLimit {
1313                limit: Some(100),
1314                remaining: Some(0),
1315            })
1316        );
1317    }
1318
1319    #[test]
1320    fn semantic_schema_includes_legacy_compatibility_fields() {
1321        let err = DynamoError::builder()
1322            .class(ErrorClass::RateLimited)
1323            .reason(ErrorReason::new("request.rate_limited").unwrap())
1324            .diagnostic("request rate exceeded")
1325            .public_details(PublicDetails::RateLimit {
1326                limit: Some(100),
1327                remaining: Some(0),
1328            })
1329            .build();
1330
1331        let value = serde_json::to_value(err).unwrap();
1332        let object = value.as_object().unwrap();
1333
1334        assert_eq!(object.len(), 6);
1335        assert_eq!(value["error_type"], "ResourceExhausted");
1336        assert_eq!(value["message"], "request rate exceeded");
1337        assert_eq!(value["class"], "RateLimited");
1338        assert_eq!(value["reason"], "request.rate_limited");
1339        assert_eq!(value["diagnostic"], "request rate exceeded");
1340        assert!(value.get("public").is_some());
1341    }
1342
1343    #[test]
1344    fn optional_semantic_fields_are_omitted() {
1345        let err = DynamoError::builder()
1346            .class(ErrorClass::InvalidRequest)
1347            .reason(ErrorReason::new("request.invalid").unwrap())
1348            .build();
1349
1350        let value = serde_json::to_value(err).unwrap();
1351        let object = value.as_object().unwrap();
1352
1353        assert_eq!(object.len(), 4);
1354        assert_eq!(value["error_type"], "InvalidArgument");
1355        assert_eq!(value["message"], "");
1356        assert_eq!(value["class"], "InvalidRequest");
1357        assert_eq!(value["reason"], "request.invalid");
1358        assert!(value.get("diagnostic").is_none());
1359        assert!(value.get("public").is_none());
1360    }
1361
1362    #[test]
1363    fn unknown_catalog_reason_fails_closed() {
1364        let json = r#"{
1365            "class": "InvalidRequest",
1366            "reason": "request.user_supplied_metric_label",
1367            "diagnostic": "private details"
1368        }"#;
1369        let err: DynamoError = serde_json::from_str(json).unwrap();
1370
1371        assert_eq!(err.class(), ErrorClass::Internal);
1372        assert_eq!(err.reason().as_str(), "runtime.invalid_error");
1373        assert_eq!(
1374            err.diagnostic().map(Diagnostic::as_str),
1375            Some("private details")
1376        );
1377    }
1378
1379    #[test]
1380    fn public_fields_fail_closed_at_consumer_boundaries() {
1381        let err = DynamoError {
1382            class: ErrorClass::InvalidRequest,
1383            reason: ErrorReason::new("request.rate_limited").unwrap(),
1384            diagnostic: Some(Diagnostic::new("private details")),
1385            public: Some(PublicDetails::RateLimit {
1386                limit: Some(10),
1387                remaining: Some(0),
1388            }),
1389        };
1390
1391        assert_eq!(err.class(), ErrorClass::Internal);
1392        assert_eq!(err.error_type(), ErrorClass::Internal);
1393        assert_eq!(err.reason().as_str(), "runtime.invalid_error");
1394        assert!(err.public_details().is_none());
1395        assert_eq!(err.to_string(), "Internal: private details");
1396        assert_eq!(
1397            serde_json::to_value(err).unwrap(),
1398            serde_json::json!({
1399                "error_type": "Unknown",
1400                "message": "private details",
1401                "class": "Internal",
1402                "reason": "runtime.invalid_error",
1403                "diagnostic": "private details"
1404            })
1405        );
1406    }
1407
1408    fn worker_overload(error_type: ErrorClass) -> DynamoError {
1409        DynamoError::builder()
1410            .error_type(error_type)
1411            .message("Server overloaded")
1412            .build()
1413    }
1414
1415    /// A rank's overload is the worker overload on the wire, with the same
1416    /// class, legacy type and reason, plus its rank as one additive field.
1417    /// Without the field, which is all a reader that predates it decodes since
1418    /// no `DynamoError` reader rejects unknown fields, the payload is exactly
1419    /// the whole-worker overload. This reader decodes the rank back.
1420    #[test]
1421    fn a_rank_overload_is_the_worker_overload_on_the_wire_plus_its_rank() {
1422        let whole = serde_json::to_value(worker_overload(ErrorClass::WorkerOverloaded)).unwrap();
1423        assert_eq!(whole["error_type"], "ResourceExhausted");
1424        assert_eq!(whole["class"], "CapacityExhausted");
1425        assert_eq!(whole["reason"], "capacity.worker_overloaded");
1426
1427        for rank in [0, 4, u32::MAX] {
1428            let mut wire =
1429                serde_json::to_value(worker_overload(ErrorClass::WorkerRankOverloaded(rank)))
1430                    .unwrap();
1431            assert_eq!(wire["dp_rank"], rank);
1432
1433            let decoded: DynamoError = serde_json::from_value(wire.clone()).unwrap();
1434            assert_eq!(decoded.error_type(), ErrorClass::WorkerRankOverloaded(rank));
1435            assert_eq!(decoded.class(), ErrorClass::CapacityExhausted);
1436            assert_eq!(decoded.reason().as_str(), "capacity.worker_overloaded");
1437
1438            wire.as_object_mut().unwrap().remove("dp_rank");
1439            assert_eq!(wire, whole, "{rank}");
1440        }
1441    }
1442
1443    /// An older writer's overload has no rank, and a malformed rank, one on an
1444    /// error that is not a worker overload, or one on an invalid identity
1445    /// decodes as absent: never a rank the writer did not mean, and never a
1446    /// failure to decode the error.
1447    #[test]
1448    fn an_absent_malformed_or_misplaced_rank_is_no_rank() {
1449        let decode = |wire: &serde_json::Value, rank: Option<&serde_json::Value>| {
1450            let mut wire = wire.clone();
1451            if let Some(rank) = rank {
1452                wire["dp_rank"] = rank.clone();
1453            }
1454            serde_json::from_value::<DynamoError>(wire).unwrap()
1455        };
1456
1457        let older =
1458            serde_json::json!({"error_type": "WorkerOverloaded", "message": "Server overloaded"});
1459        assert_eq!(
1460            decode(&older, None).error_type(),
1461            ErrorClass::WorkerOverloaded
1462        );
1463
1464        let whole = serde_json::to_value(worker_overload(ErrorClass::WorkerOverloaded)).unwrap();
1465        assert_eq!(
1466            decode(&whole, None).error_type(),
1467            ErrorClass::ResourceExhausted
1468        );
1469        for rank in [
1470            serde_json::json!(-1),
1471            serde_json::json!(u64::from(u32::MAX) + 1),
1472            serde_json::json!(4.5),
1473            serde_json::json!("4"),
1474            serde_json::json!({"dp_rank": 4}),
1475            serde_json::json!(null),
1476        ] {
1477            assert_eq!(decode(&whole, Some(&rank)), decode(&whole, None), "{rank}");
1478        }
1479
1480        let rank = serde_json::json!(4);
1481        for error_type in [ErrorClass::ResourceExhausted, ErrorClass::InvalidRequest] {
1482            let wire = serde_json::to_value(DynamoError::builder().error_type(error_type).build())
1483                .unwrap();
1484            assert_eq!(decode(&wire, Some(&rank)), decode(&wire, None), "{wire}");
1485        }
1486
1487        let mismatched = serde_json::json!({
1488            "class": "InvalidRequest",
1489            "reason": "capacity.worker_overloaded",
1490            "dp_rank": 4
1491        });
1492        let decoded = decode(&mismatched, None);
1493        assert_eq!(decoded.error_type(), ErrorClass::Internal);
1494        assert_eq!(decoded.reason().as_str(), "runtime.invalid_error");
1495        assert!(
1496            serde_json::to_value(decoded)
1497                .unwrap()
1498                .get("dp_rank")
1499                .is_none()
1500        );
1501
1502        // In memory, a mismatched identity fails closed, rank and all.
1503        let mismatched = DynamoError {
1504            class: ErrorClass::WorkerRankOverloaded(4),
1505            reason: ErrorReason::new("request.rate_limited").unwrap(),
1506            diagnostic: None,
1507            public: None,
1508        };
1509        assert_eq!(mismatched.error_type(), ErrorClass::Internal);
1510        assert!(!match_error_chain(
1511            &mismatched,
1512            &[ErrorClass::WorkerOverloaded],
1513            &[]
1514        ));
1515        assert!(
1516            serde_json::to_value(mismatched)
1517                .unwrap()
1518                .get("dp_rank")
1519                .is_none()
1520        );
1521    }
1522
1523    /// Every set that names the worker overload matches a rank's, as a match
1524    /// or an exclusion, while a set naming one rank matches only that rank's.
1525    /// Wrapping keeps the rank, in memory and across the wire.
1526    #[test]
1527    fn a_rank_overload_matches_as_a_worker_overload_and_wrapping_keeps_its_rank() {
1528        let rank = worker_overload(ErrorClass::WorkerRankOverloaded(4));
1529        let whole = worker_overload(ErrorClass::WorkerOverloaded);
1530        assert!(match_error_chain(
1531            &rank,
1532            &[ErrorClass::WorkerOverloaded],
1533            &[]
1534        ));
1535        assert!(match_error_chain(
1536            &rank,
1537            &[ErrorClass::WorkerRankOverloaded(4)],
1538            &[]
1539        ));
1540        assert!(!match_error_chain(
1541            &rank,
1542            &[ErrorClass::WorkerRankOverloaded(5)],
1543            &[]
1544        ));
1545        assert!(!match_error_chain(
1546            &rank,
1547            &[ErrorClass::ResourceExhausted],
1548            &[]
1549        ));
1550        assert!(!match_error_chain(
1551            &whole,
1552            &[ErrorClass::WorkerRankOverloaded(4)],
1553            &[]
1554        ));
1555
1556        let connection = DynamoError::builder()
1557            .error_type(ErrorClass::CannotConnect)
1558            .cause(rank.clone())
1559            .build();
1560        assert!(match_error_chain(
1561            &connection,
1562            &[ErrorClass::WorkerOverloaded],
1563            &[ErrorClass::ResourceExhausted]
1564        ));
1565        assert!(!match_error_chain(
1566            &connection,
1567            &[ErrorClass::CannotConnect],
1568            &[ErrorClass::WorkerOverloaded]
1569        ));
1570
1571        let wrapped = anyhow::Error::from(rank).context("dispatch failed");
1572        let converted = DynamoError::from(wrapped.as_ref() as &(dyn std::error::Error + 'static));
1573        assert_eq!(converted.error_type(), ErrorClass::WorkerRankOverloaded(4));
1574        let decoded: DynamoError =
1575            serde_json::from_value(serde_json::to_value(&converted).unwrap()).unwrap();
1576        assert_eq!(decoded.error_type(), ErrorClass::WorkerRankOverloaded(4));
1577        let cause = decoded.source().unwrap().downcast_ref::<DynamoError>();
1578        assert_eq!(
1579            cause.map(DynamoError::error_type),
1580            Some(ErrorClass::WorkerRankOverloaded(4))
1581        );
1582    }
1583
1584    #[test]
1585    fn diagnostic_is_bounded_at_utf8_boundary() {
1586        let truncation_index = Diagnostic::MAX_BYTES - Diagnostic::TRUNCATION_SUFFIX.len();
1587        let diagnostic = Diagnostic::new(
1588            "x".repeat(truncation_index - 1) + "é" + &"x".repeat(Diagnostic::MAX_BYTES),
1589        );
1590
1591        assert!(diagnostic.as_str().len() <= Diagnostic::MAX_BYTES);
1592        assert!(
1593            diagnostic
1594                .as_str()
1595                .is_char_boundary(diagnostic.as_str().len())
1596        );
1597        assert!(diagnostic.as_str().ends_with(Diagnostic::TRUNCATION_SUFFIX));
1598    }
1599
1600    #[test]
1601    fn public_message_is_bounded_at_utf8_boundary() {
1602        let truncation_index = Diagnostic::MAX_BYTES - Diagnostic::TRUNCATION_SUFFIX.len();
1603        let message = "x".repeat(truncation_index - 1) + "é" + &"x".repeat(Diagnostic::MAX_BYTES);
1604        let error = DynamoError::builder()
1605            .class(ErrorClass::InvalidRequest)
1606            .public_message(message)
1607            .build();
1608        let public_message = error.public_message().unwrap();
1609
1610        assert!(public_message.len() <= Diagnostic::MAX_BYTES);
1611        assert!(public_message.is_char_boundary(public_message.len()));
1612        assert!(public_message.ends_with(Diagnostic::TRUNCATION_SUFFIX));
1613    }
1614
1615    #[test]
1616    fn legacy_builder_derives_semantic_defaults() {
1617        let legacy_type: ErrorType = ErrorType::InvalidArgument;
1618        let err = DynamoError::builder()
1619            .error_type(legacy_type)
1620            .message("bad request")
1621            .build();
1622
1623        assert_eq!(err.error_type(), ErrorType::InvalidArgument);
1624        assert_eq!(err.class(), ErrorClass::InvalidRequest);
1625        assert_eq!(err.reason().as_str(), "request.invalid_argument");
1626        assert_eq!(err.message(), "bad request");
1627    }
1628
1629    #[test]
1630    fn legacy_json_derives_semantic_defaults() {
1631        let json = r#"{"error_type":"InvalidArgument","message":"bad request"}"#;
1632        let err: DynamoError = serde_json::from_str(json).unwrap();
1633
1634        assert_eq!(err.class(), ErrorClass::InvalidRequest);
1635        assert_eq!(err.reason().as_str(), "request.invalid_argument");
1636        assert_eq!(
1637            err.diagnostic().map(Diagnostic::as_str),
1638            Some("bad request")
1639        );
1640        assert!(err.public_details().is_none());
1641    }
1642
1643    #[test]
1644    fn legacy_unknown_preserves_nested_classification_across_the_wire() {
1645        let json = r#"{
1646            "error_type":"Unknown",
1647            "message":"generate failed",
1648            "caused_by":{"error_type":"InvalidArgument","message":"bad request"}
1649        }"#;
1650        let err: DynamoError = serde_json::from_str(json).unwrap();
1651
1652        assert_eq!(err.reason().as_str(), "runtime.unclassified");
1653        assert_eq!(err.class(), ErrorClass::Internal);
1654        assert!(match_error_chain(&err, &[ErrorClass::InvalidArgument], &[]));
1655
1656        let reserialized = serde_json::to_value(&err).unwrap();
1657        assert_eq!(reserialized["caused_by"]["error_type"], "InvalidArgument");
1658    }
1659
1660    #[test]
1661    fn backend_class_roundtrips_as_its_canonical_class() {
1662        let error = DynamoError::builder()
1663            .error_type(ErrorClass::Backend(BackendError::InvalidArgument))
1664            .build();
1665
1666        let serialized = serde_json::to_string(&error).unwrap();
1667        assert!(serialized.contains("\"class\":\"InvalidRequest\""));
1668
1669        let decoded: DynamoError = serde_json::from_str(&serialized).unwrap();
1670        assert_eq!(
1671            decoded.error_type(),
1672            ErrorClass::Backend(BackendError::InvalidArgument)
1673        );
1674        assert_eq!(decoded.class(), ErrorClass::InvalidRequest);
1675        assert_eq!(decoded.reason().as_str(), "backend.invalid_argument");
1676    }
1677
1678    #[test]
1679    fn transport_subtype_roundtrips() {
1680        let error = DynamoError::builder()
1681            .error_type(ErrorClass::CannotConnect)
1682            .build();
1683
1684        let decoded: DynamoError =
1685            serde_json::from_str(&serde_json::to_string(&error).unwrap()).unwrap();
1686
1687        assert_eq!(decoded.error_type(), ErrorClass::CannotConnect);
1688        assert_eq!(decoded.class(), ErrorClass::Unavailable);
1689        assert_eq!(decoded.reason().as_str(), "transport.cannot_connect");
1690    }
1691
1692    #[test]
1693    fn worker_unavailable_roundtrips_with_semantic_identity() {
1694        let error = DynamoError::builder()
1695            .error_type(ErrorClass::WorkerUnavailable)
1696            .build();
1697
1698        let decoded: DynamoError =
1699            serde_json::from_str(&serde_json::to_string(&error).unwrap()).unwrap();
1700
1701        assert_eq!(decoded.error_type(), ErrorClass::WorkerUnavailable);
1702        assert_eq!(decoded.class(), ErrorClass::Unavailable);
1703        assert_eq!(decoded.reason().as_str(), "backend.worker_unavailable");
1704    }
1705
1706    #[test]
1707    fn response_timeout_subtypes_roundtrip() {
1708        for error_type in [
1709            ErrorClass::ResponseTimeout,
1710            ErrorClass::Backend(BackendError::ResponseTimeout),
1711        ] {
1712            let error = DynamoError::builder().error_type(error_type).build();
1713            let decoded: DynamoError =
1714                serde_json::from_str(&serde_json::to_string(&error).unwrap()).unwrap();
1715
1716            assert_eq!(decoded.error_type(), error_type);
1717            assert_eq!(decoded.class(), ErrorClass::DeadlineExceeded);
1718        }
1719    }
1720
1721    #[test]
1722    fn unknown_class_fails_closed_during_deserialization() {
1723        let json = r#"{
1724            "class":"FutureErrorClass",
1725            "reason":"runtime.internal",
1726            "public":{"type":"message","message":"must not escape"}
1727        }"#;
1728        let error: DynamoError = serde_json::from_str(json).unwrap();
1729
1730        assert_eq!(error.error_type(), ErrorClass::Internal);
1731        assert_eq!(error.class(), ErrorClass::Internal);
1732        assert_eq!(error.reason().as_str(), "runtime.invalid_error");
1733        assert!(error.public_details().is_none());
1734    }
1735
1736    #[test]
1737    fn error_class_deserialization_preserves_backend_and_fails_closed() {
1738        let backend: ErrorClass = serde_json::from_str(r#"{"Backend":"InvalidArgument"}"#).unwrap();
1739        assert_eq!(backend, ErrorClass::Backend(BackendError::InvalidArgument));
1740
1741        let unknown: ErrorClass = serde_json::from_str(r#""FutureErrorClass""#).unwrap();
1742        assert_eq!(unknown, ErrorClass::Unknown);
1743
1744        for class in [0, u32::MAX].map(ErrorClass::WorkerRankOverloaded) {
1745            let wire = serde_json::to_string(&class).unwrap();
1746            assert_eq!(
1747                serde_json::from_str::<ErrorClass>(&wire).unwrap(),
1748                class,
1749                "{wire}"
1750            );
1751        }
1752    }
1753
1754    #[test]
1755    fn wrapping_preserves_the_semantic_head_across_the_wire() {
1756        #[derive(Debug)]
1757        struct Wrapper(DynamoError);
1758
1759        impl fmt::Display for Wrapper {
1760            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1761                f.write_str("transport wrapper")
1762            }
1763        }
1764
1765        impl std::error::Error for Wrapper {
1766            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1767                Some(&self.0)
1768            }
1769        }
1770
1771        let wrapped = Wrapper(
1772            DynamoError::builder()
1773                .class(ErrorClass::Unavailable)
1774                .reason(ErrorReason::new("transport.disconnected").unwrap())
1775                .build(),
1776        );
1777        let error = DynamoError::from(&wrapped as &(dyn std::error::Error + 'static));
1778
1779        assert_eq!(error.class(), ErrorClass::Unavailable);
1780        assert_eq!(error.reason().as_str(), "transport.disconnected");
1781        let value = serde_json::to_value(&error).unwrap();
1782        assert!(value.get("caused_by").is_some());
1783        let decoded: DynamoError = serde_json::from_value(value).unwrap();
1784        assert_eq!(decoded.class(), ErrorClass::Unavailable);
1785        assert_eq!(decoded.reason().as_str(), "transport.disconnected");
1786    }
1787
1788    #[test]
1789    fn malformed_semantic_reason_fails_closed() {
1790        let json = r#"{
1791            "class": "InvalidRequest",
1792            "reason": "INVALID REASON",
1793            "diagnostic": "private details",
1794            "public": {"type": "rate_limit", "limit": 10, "remaining": 0}
1795        }"#;
1796        let err: DynamoError = serde_json::from_str(json).unwrap();
1797
1798        assert_eq!(err.error_type(), ErrorClass::Internal);
1799        assert_eq!(err.class(), ErrorClass::Internal);
1800        assert_eq!(err.reason().as_str(), "runtime.invalid_error");
1801        assert!(err.public_details().is_none());
1802    }
1803
1804    #[test]
1805    fn test_error_type_display() {
1806        assert_eq!(ErrorClass::Unknown.to_string(), "Unknown");
1807        assert_eq!(ErrorClass::InvalidArgument.to_string(), "InvalidArgument");
1808        assert_eq!(ErrorClass::CannotConnect.to_string(), "CannotConnect");
1809        assert_eq!(ErrorClass::Disconnected.to_string(), "Disconnected");
1810        assert_eq!(
1811            ErrorClass::ConnectionTimeout.to_string(),
1812            "ConnectionTimeout"
1813        );
1814        assert_eq!(ErrorClass::ResponseTimeout.to_string(), "ResponseTimeout");
1815        assert_eq!(ErrorClass::Cancelled.to_string(), "Cancelled");
1816        assert_eq!(ErrorClass::DeadlineExceeded.to_string(), "DeadlineExceeded");
1817        assert_eq!(
1818            ErrorClass::ResourceExhausted.to_string(),
1819            "ResourceExhausted"
1820        );
1821        assert_eq!(ErrorClass::WorkerOverloaded.to_string(), "WorkerOverloaded");
1822        assert_eq!(
1823            ErrorClass::WorkerRankOverloaded(4).to_string(),
1824            "WorkerRankOverloaded(4)"
1825        );
1826        assert_eq!(ErrorClass::Unavailable.to_string(), "Unavailable");
1827        assert_eq!(
1828            ErrorClass::WorkerUnavailable.to_string(),
1829            "WorkerUnavailable"
1830        );
1831        assert_eq!(
1832            ErrorClass::Backend(BackendError::Unknown).to_string(),
1833            "BackendUnknown"
1834        );
1835        assert_eq!(
1836            ErrorClass::Backend(BackendError::InvalidArgument).to_string(),
1837            "BackendInvalidArgument"
1838        );
1839        assert_eq!(
1840            ErrorClass::Backend(BackendError::CannotConnect).to_string(),
1841            "BackendCannotConnect"
1842        );
1843        assert_eq!(
1844            ErrorClass::Backend(BackendError::Disconnected).to_string(),
1845            "BackendDisconnected"
1846        );
1847        assert_eq!(
1848            ErrorClass::Backend(BackendError::ConnectionTimeout).to_string(),
1849            "BackendConnectionTimeout"
1850        );
1851        assert_eq!(
1852            ErrorClass::Backend(BackendError::Cancelled).to_string(),
1853            "BackendCancelled"
1854        );
1855        assert_eq!(
1856            ErrorClass::Backend(BackendError::EngineShutdown).to_string(),
1857            "BackendEngineShutdown"
1858        );
1859        assert_eq!(
1860            ErrorClass::Backend(BackendError::StreamIncomplete).to_string(),
1861            "BackendStreamIncomplete"
1862        );
1863        assert_eq!(
1864            ErrorClass::Backend(BackendError::WorkerOverloaded).normalized(),
1865            ErrorClass::CapacityExhausted
1866        );
1867        assert_eq!(
1868            ErrorReason::for_class(ErrorClass::Backend(BackendError::WorkerOverloaded)).as_str(),
1869            "capacity.worker_overloaded"
1870        );
1871        assert_eq!(
1872            ErrorClass::Backend(BackendError::ResponseTimeout).to_string(),
1873            "BackendResponseTimeout"
1874        );
1875    }
1876}