Skip to main content

aws_durable_execution_sdk/
error.rs

1//! Error types for durable operations.
2//!
3//! All error types are hand-written (no `thiserror`), `#[non_exhaustive]`,
4//! and implement [`std::error::Error`]. Use the `kind()` accessor pattern
5//! for matching error variants, and [`source()`](std::error::Error::source)
6//! to reach the underlying cause.
7//!
8//! # `Display` convention
9//!
10//! Each layer's `Display` writes **one frame**: its own description, never
11//! its source's text. Walking [`source()`](std::error::Error::source)
12//! therefore never repeats text. To print the whole chain in one line, use
13//! the alternate form `{:#}`, which walks the source chain from that layer
14//! down. The message recorded on the wire is the message of the operation
15//! failure that the error propagates, when it propagates one, and is
16//! otherwise the chain's frames joined with `": "`, without the frame of a
17//! [`TypedError`], whose type name the record carries as its type (see
18//! [`wire_message`]).
19//!
20//! # Kinds classify, `source()` carries
21//!
22//! The `*ErrorKind` enums are pure classification: empty variants are unit
23//! variants, and variants that retain structural facts (an attempt count,
24//! a failed index) are newtype variants wrapping a payload struct with
25//! accessors. The escaping error that caused the failure is never
26//! stringified into a kind: it is carried by the error struct and
27//! returned from `source()`.
28
29use std::error::Error;
30use std::fmt;
31
32/// The boxed source type every error struct carries.
33///
34/// The `Send + Sync` bounds are load-bearing: all public error types are
35/// `Send + Sync` (asserted at compile time below), and a bare
36/// `Box<dyn Error>` would silently revoke that.
37pub(crate) type Source = Box<dyn Error + Send + Sync + 'static>;
38
39/// Maximum number of source-chain links walked when extracting wire
40/// identity (the `TypedError` type name, `error_data`, `stack_trace`)
41/// from an escaping error.
42///
43/// The walk reads the error itself and up to 10 causes, as the JS SDK
44/// does: it checks the error's own data, then up to 10 causes. So a
45/// payload survives the same nesting depth across SDKs.
46const CHAIN_WALK_LIMIT: usize = 11;
47
48/// Writes `frame` followed by every frame of `source`'s chain, separated
49/// by `": "`.
50///
51/// This is the full-chain renderer: every alternate (`{:#}`) `Display`
52/// implementation in this module funnels through it, and it writes every
53/// frame, a [`TypedError`]'s type name included. The recorded message
54/// uses [`chain_string`] instead, which omits the type names.
55pub(crate) fn write_chain(
56    f: &mut fmt::Formatter<'_>,
57    frame: &dyn fmt::Display,
58    mut source: Option<&(dyn Error + 'static)>,
59) -> fmt::Result {
60    write!(f, "{frame}")?;
61    while let Some(s) = source {
62        write!(f, ": {s}")?;
63        source = s.source();
64    }
65    Ok(())
66}
67
68/// Flattens an error's chain into one line for a recorded message: the
69/// `Display` frame of every error in the chain, in source order, joined
70/// with `": "`, except the frame of each [`TypedError`].
71///
72/// A `TypedError`'s frame is its type name, which the record carries as
73/// its `ErrorType`, so the message holds the wrapped error's text alone,
74/// as JS records an error's `name` and `message` in separate fields.
75/// `TypedError::with_type("PaymentError", "declined")` flattens to
76/// `declined`. A `TypedError` always has a source, so the last frame of
77/// a chain is never a `TypedError`'s and the result names every other
78/// error.
79pub(crate) fn chain_string(err: &(dyn Error + 'static)) -> String {
80    let mut frames = Vec::new();
81    let mut link = Some(err);
82    while let Some(e) = link {
83        if !e.is::<TypedError>() {
84            frames.push(e.to_string());
85        }
86        link = e.source();
87    }
88    frames.join(": ")
89}
90
91/// The failure fields of a wire `ErrorObject`, as a named record.
92///
93/// Carries the four wire error fields: `error_type`, `error_message`,
94/// `error_data`, and `stack_trace`. Reachable from a failed operation via
95/// [`OperationError::wire`], and from a replayed failure's synthetic
96/// source via [`ReplayedFailure::wire`].
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98#[non_exhaustive]
99pub struct WireError {
100    error_type: Option<String>,
101    error_message: Option<String>,
102    error_data: Option<String>,
103    stack_trace: Vec<String>,
104}
105
106impl WireError {
107    /// Creates a wire error record from its type and message fields.
108    pub(crate) fn new(
109        error_type: Option<impl Into<String>>,
110        error_message: Option<impl Into<String>>,
111    ) -> Self {
112        Self {
113            error_type: error_type.map(Into::into),
114            error_message: error_message.map(Into::into),
115            error_data: None,
116            stack_trace: Vec::new(),
117        }
118    }
119
120    /// Sets the human-readable message.
121    pub(crate) fn with_error_message(mut self, error_message: Option<impl Into<String>>) -> Self {
122        self.error_message = error_message.map(Into::into);
123        self
124    }
125
126    /// Sets the opaque `error_data` payload.
127    pub(crate) fn with_error_data(mut self, error_data: Option<impl Into<String>>) -> Self {
128        self.error_data = error_data.map(Into::into);
129        self
130    }
131
132    /// Sets the stack trace frames.
133    pub(crate) fn with_stack_trace(mut self, stack_trace: Vec<String>) -> Self {
134        self.stack_trace = stack_trace;
135        self
136    }
137
138    /// The wire `ErrorType`: the name of the error type that failed the
139    /// operation, as recorded in the execution history.
140    pub fn error_type(&self) -> Option<&str> {
141        self.error_type.as_deref()
142    }
143
144    /// The wire `ErrorMessage`: the human-readable message.
145    ///
146    /// A failure that propagates another operation's failure records that
147    /// operation's message. Any other failure records its error's chain,
148    /// flattened into one line. Neither includes the name of a
149    /// [`TypedError`], which the record carries as its type: a failure
150    /// with `TypedError::with_type("PaymentError", "declined")` records the
151    /// message `declined`.
152    pub fn error_message(&self) -> Option<&str> {
153        self.error_message.as_deref()
154    }
155
156    /// The wire `ErrorData`: an opaque payload attached to the failure.
157    ///
158    /// The SDK writes this field and passes it through boundaries, and
159    /// **never dispatches on it**: the wire error fields can be supplied
160    /// by an external caller (via `SendDurableExecutionCallbackFailure`),
161    /// so typed reconstruction from an attacker-influenced payload is
162    /// decode surface the SDK refuses to have. Interpret it yourself if
163    /// you know its shape. The one record the SDK decodes is its own
164    /// `select_ok` `AllFailed` aggregate, whose `error_data` is
165    /// SDK-authored (never pass-through) and holds the losers' recorded
166    /// failure fields; combinator replay decodes it defensively and only
167    /// stores and re-exposes the decoded strings, never branching on them.
168    pub fn error_data(&self) -> Option<&str> {
169        self.error_data.as_deref()
170    }
171
172    /// The wire `StackTrace` frames, stored and exposed verbatim.
173    ///
174    /// The SDK never captures frames. This field exposes the frames a
175    /// recorded record already carries: an external callback failure, a
176    /// remote invoke, or a replayed record. A failure the SDK records
177    /// live carries frames only when an error in its source chain
178    /// already carried them. A Rust [`std::backtrace::Backtrace`] cannot
179    /// be reconstructed from recorded frames, so these are
180    /// store-and-expose only.
181    pub fn stack_trace(&self) -> &[String] {
182        &self.stack_trace
183    }
184
185    /// Converts this record into the SDK `ErrorObject` wire shape
186    /// (internal).
187    pub(crate) fn to_error_object(&self) -> aws_sdk_lambda::types::ErrorObject {
188        let mut builder = aws_sdk_lambda::types::ErrorObject::builder();
189        if let Some(t) = self.error_type() {
190            builder = builder.error_type(t);
191        }
192        if let Some(m) = self.error_message() {
193            builder = builder.error_message(m);
194        }
195        if let Some(d) = self.error_data() {
196            builder = builder.error_data(d);
197        }
198        for frame in self.stack_trace() {
199            builder = builder.stack_trace(frame);
200        }
201        builder.build()
202    }
203}
204
205impl fmt::Display for WireError {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match (self.error_type.as_deref(), self.error_message.as_deref()) {
208            (Some(t), Some(m)) => write!(f, "{t}: {m}"),
209            (None, Some(m)) => write!(f, "{m}"),
210            (Some(t), None) => write!(f, "{t}"),
211            (None, None) => write!(f, "unknown error"),
212        }
213    }
214}
215
216/// The synthetic source attached to an error rebuilt from a checkpointed
217/// failure on replay.
218///
219/// On the live path an operation error's `source()` is the escaping error
220/// itself; after a replay only the wire record survives, so `source()`
221/// returns this type carrying the recorded `error_type` and
222/// `error_message` (plus `error_data` and `stack_trace` when recorded).
223/// Downcast to it to read the wire fields programmatically.
224#[derive(Debug, Clone)]
225#[non_exhaustive]
226pub struct ReplayedFailure {
227    wire: WireError,
228}
229
230impl ReplayedFailure {
231    /// Creates a replayed failure from the recorded wire fields.
232    pub(crate) fn new(wire: WireError) -> Self {
233        Self { wire }
234    }
235
236    /// Boxes a replayed failure as an error source.
237    pub(crate) fn source_from(wire: WireError) -> Source {
238        Box::new(Self::new(wire))
239    }
240
241    /// The recorded wire `ErrorType`.
242    pub fn error_type(&self) -> Option<&str> {
243        self.wire.error_type()
244    }
245
246    /// The recorded wire `ErrorMessage`.
247    pub fn error_message(&self) -> Option<&str> {
248        self.wire.error_message()
249    }
250
251    /// The full recorded wire failure record.
252    pub fn wire(&self) -> &WireError {
253        &self.wire
254    }
255}
256
257impl fmt::Display for ReplayedFailure {
258    /// Writes the recorded message as this frame.
259    ///
260    /// A recorded `error_type` is not prefixed to a recorded message: the
261    /// type is data, answered by [`error_type()`](Self::error_type). When no
262    /// message was recorded, the frame is the recorded type, and without
263    /// either it is `unknown error`.
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        match (self.wire.error_message(), self.wire.error_type()) {
266            (Some(m), _) => write!(f, "{m}"),
267            (None, Some(t)) => write!(f, "{t}"),
268            (None, None) => write!(f, "unknown error"),
269        }
270    }
271}
272
273impl Error for ReplayedFailure {}
274
275/// Crate-internal error that adds one context frame on top of a cause,
276/// without stringifying the cause into the frame.
277#[derive(Debug)]
278pub(crate) struct ContextualError {
279    context: String,
280    source: Source,
281}
282
283impl ContextualError {
284    /// Boxes a context frame over `source` as an error source.
285    pub(crate) fn source_from(context: impl Into<String>, source: impl Into<Source>) -> Source {
286        Box::new(Self {
287            context: context.into(),
288            source: source.into(),
289        })
290    }
291}
292
293impl fmt::Display for ContextualError {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        if f.alternate() {
296            write_chain(f, &self.context, self.source())
297        } else {
298            write!(f, "{}", self.context)
299        }
300    }
301}
302
303impl Error for ContextualError {
304    fn source(&self) -> Option<&(dyn Error + 'static)> {
305        Some(&*self.source as &(dyn Error + 'static))
306    }
307}
308
309/// An error wrapper that records its inner error's concrete type name for
310/// the wire `ErrorType`.
311///
312/// Rust erases an error's concrete type the moment it is boxed into a
313/// [`BoxError`](crate::BoxError): inside the SDK there is no runtime name
314/// to recover, so an unwrapped error is recorded with the generic type
315/// `"Error"`. Wrapping the error at the one place its type is still known
316/// (its creation site) is the explicit alternative:
317///
318/// ```
319/// use aws_durable_execution_sdk::{BoxError, TypedError};
320///
321/// #[derive(Debug)]
322/// struct PaymentDeclined;
323/// # impl std::fmt::Display for PaymentDeclined {
324/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325/// #         write!(f, "payment declined")
326/// #     }
327/// # }
328/// # impl std::error::Error for PaymentDeclined {}
329///
330/// let err: BoxError = Box::new(TypedError::new(PaymentDeclined));
331/// // The step that fails with `err` records ErrorType "PaymentDeclined".
332/// ```
333///
334/// [`with_error_data`](Self::with_error_data) attaches an opaque payload,
335/// recorded as the wire `ErrorData`. The SDK never parses it, and it
336/// never appears in the recorded message:
337///
338/// ```
339/// use aws_durable_execution_sdk::TypedError;
340///
341/// let err = TypedError::with_type("PaymentError", "declined").with_error_data(r#"{"code":42}"#);
342/// assert_eq!(err.error_type(), "PaymentError");
343/// assert_eq!(err.error_data(), Some(r#"{"code":42}"#));
344/// ```
345///
346/// The wrapper is one chain layer: its `Display` frame is the recorded
347/// type name, and its [`source()`](std::error::Error::source) is the
348/// wrapped error itself, so the concrete error stays reachable through
349/// the ordinary `source()` downcast walk, and the alternate form `{:#}`
350/// reads `"TransientError: temporary failure"`.
351///
352/// The recorded message never includes the type name, because the record
353/// carries it as its type, as JS records an error's `name` and `message`
354/// apart. A failure with `TypedError::with_type("PaymentError", "declined")`
355/// records the type `PaymentError` and the message `declined`. When the
356/// wrapped error propagates another operation's failure, the message is
357/// that failure's recorded message.
358#[derive(Debug)]
359#[non_exhaustive]
360pub struct TypedError {
361    error_type: String,
362    inner: Source,
363    error_data: Option<String>,
364}
365
366impl TypedError {
367    /// Wraps `err`, recording its concrete type's name (without module
368    /// path) as the wire `ErrorType`.
369    #[must_use]
370    pub fn new<E: Error + Send + Sync + 'static>(err: E) -> Self {
371        Self {
372            error_type: short_type_name(std::any::type_name::<E>()),
373            inner: Box::new(err),
374            error_data: None,
375        }
376    }
377
378    /// Wraps `err` under an explicitly chosen wire `ErrorType`.
379    #[must_use]
380    pub fn with_type(error_type: impl Into<String>, err: impl Into<Source>) -> Self {
381        Self {
382            error_type: error_type.into(),
383            inner: err.into(),
384            error_data: None,
385        }
386    }
387
388    /// Attaches an opaque payload, recorded as the wire `ErrorData`.
389    ///
390    /// The SDK passes the payload through unparsed. It does not appear in
391    /// this error's `Display` or in the recorded `ErrorMessage`.
392    #[must_use]
393    pub fn with_error_data(mut self, error_data: impl Into<String>) -> Self {
394        self.error_data = Some(error_data.into());
395        self
396    }
397
398    /// The payload attached with [`with_error_data`](Self::with_error_data),
399    /// if any.
400    pub fn error_data(&self) -> Option<&str> {
401        self.error_data.as_deref()
402    }
403
404    /// The wire `ErrorType` recorded for this error.
405    pub fn error_type(&self) -> &str {
406        &self.error_type
407    }
408
409    /// The wrapped error.
410    pub fn inner(&self) -> &(dyn Error + 'static) {
411        &*self.inner
412    }
413}
414
415impl fmt::Display for TypedError {
416    /// Writes the recorded type name as this layer's frame; the wrapped
417    /// error is the next frame in the chain.
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        if f.alternate() {
420            write_chain(f, &self.error_type, self.source())
421        } else {
422            write!(f, "{}", self.error_type)
423        }
424    }
425}
426
427impl Error for TypedError {
428    fn source(&self) -> Option<&(dyn Error + 'static)> {
429        Some(&*self.inner as &(dyn Error + 'static))
430    }
431}
432
433/// Reduces `std::any::type_name` output to bare type names: every module
434/// path segment is dropped, including inside generic arguments
435/// (`a::B<c::D>` becomes `B<D>`).
436fn short_type_name(full: &str) -> String {
437    let mut result = String::with_capacity(full.len());
438    let mut segment = String::new();
439    for c in full.chars() {
440        match c {
441            ':' => segment.clear(),
442            '<' | '>' | ',' | ' ' | '(' | ')' | '[' | ']' | '&' | ';' => {
443                result.push_str(&segment);
444                segment.clear();
445                result.push(c);
446            }
447            _ => segment.push(c),
448        }
449    }
450    result.push_str(&segment);
451    result
452}
453
454/// Derives the wire failure record for an escaping error explicitly,
455/// with no `Debug` scraping.
456///
457/// - `error_message` is the error's recorded message ([`wire_message`]):
458///   the message of the first operation record its chain reaches through
459///   the SDK's propagation carriers and [`TypedError`]s, else its
460///   flattened source chain without the frames of [`TypedError`]s
461///   ([`chain_string`]).
462/// - `error_type` is taken from structured identity when the error *is*
463///   one: an [`OperationError`] re-records its attached wire record's
464///   type when it carries one (or a [`TypedError`]'s name from its
465///   chain), falling back to its kind's registry name, so an explicitly
466///   supplied user type survives re-recording across child-context and
467///   map boundaries. A [`ReplayedFailure`] re-records its original type.
468///   A plain user error has no recoverable type name in Rust (the
469///   concrete type is erased when the caller boxes it), so it records
470///   `fallback_type`.
471/// - `error_data` is passed through from the first error in the source
472///   chain (up to [`CHAIN_WALK_LIMIT`] links) that carries one: an
473///   [`OperationError`] or [`ReplayedFailure`] whose record has data, or
474///   a [`TypedError`] with [`TypedError::error_data`] set. So a payload
475///   survives child-context and map boundaries. It is never synthesized
476///   and never parsed.
477/// - `stack_trace` is passed through from the first [`OperationError`] or
478///   [`ReplayedFailure`] in the chain that carries frames. The SDK never
479///   captures frames, so a chain with no recorded frames records none.
480pub(crate) fn wire_error_for(err: &(dyn Error + 'static), fallback_type: &str) -> WireError {
481    let error_type = if let Some(op) = err.downcast_ref::<OperationError>() {
482        // An operation error's own recorded identity wins: the attached
483        // wire record already names the user's type when one was
484        // supplied, and a `TypedError` still in the chain names it
485        // directly. Only an error with neither records its kind's
486        // registry name.
487        op.wire()
488            .and_then(WireError::error_type)
489            .map(str::to_owned)
490            .or_else(|| typed_error_name(err))
491            .unwrap_or_else(|| op.kind().wire_type_name().to_owned())
492    } else if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
493        // Re-recording a replayed failure preserves its original type.
494        replayed.error_type().unwrap_or(fallback_type).to_owned()
495    } else {
496        // A `TypedError` anywhere in the chain names the user's type
497        // explicitly: the one non-erased source of a concrete name.
498        typed_error_name(err).unwrap_or_else(|| fallback_type.to_owned())
499    };
500    wire_error_with_type(err, &error_type)
501}
502
503/// Walks the source chain (up to [`CHAIN_WALK_LIMIT`] links) for the first
504/// [`TypedError`] and returns its recorded type name.
505fn typed_error_name(err: &(dyn Error + 'static)) -> Option<String> {
506    let mut link: Option<&(dyn Error + 'static)> = Some(err);
507    for _ in 0..CHAIN_WALK_LIMIT {
508        let e = link?;
509        if let Some(typed) = e.downcast_ref::<TypedError>() {
510            return Some(typed.error_type().to_owned());
511        }
512        link = e.source();
513    }
514    None
515}
516
517/// Like [`wire_error_for`], but with a caller-fixed wire `error_type`
518/// (used where the type is a protocol discriminator, e.g. the combinator
519/// replay markers). The message ([`wire_message`]) and the
520/// `error_data`/`stack_trace` chain walk are identical.
521pub(crate) fn wire_error_with_type(err: &(dyn Error + 'static), error_type: &str) -> WireError {
522    let mut error_data = None;
523    let mut stack_trace = Vec::new();
524    let mut link: Option<&(dyn Error + 'static)> = Some(err);
525    let mut walked = 0;
526    while let Some(e) = link {
527        if walked >= CHAIN_WALK_LIMIT {
528            break;
529        }
530        if let Some(w) = wire_identity(e) {
531            if error_data.is_none() {
532                error_data = w.error_data().map(str::to_owned);
533            }
534            if stack_trace.is_empty() {
535                stack_trace = w.stack_trace().to_vec();
536            }
537        } else if let Some(typed) = e.downcast_ref::<TypedError>()
538            && error_data.is_none()
539        {
540            // A `TypedError` supplies data only; it carries no frames.
541            error_data = typed.error_data().map(str::to_owned);
542        }
543        if error_data.is_some() && !stack_trace.is_empty() {
544            break;
545        }
546        link = e.source();
547        walked += 1;
548    }
549
550    WireError::new(Some(error_type), Some(wire_message(err)))
551        .with_error_data(error_data)
552        .with_stack_trace(stack_trace)
553}
554
555/// The recorded message of an escaping error.
556///
557/// An error that propagates another operation's failure records that
558/// failure's recorded message, as JS does: the walk follows `source()`
559/// through the SDK's propagation carriers ([`OperationError`] without a
560/// record, the per-operation error structs, [`ChildFnError`],
561/// [`ContextualError`] and [`TypedError`]) and returns the message of the
562/// first record it reaches, an [`OperationError`] with a record or a
563/// [`ReplayedFailure`], verbatim. It examines at most
564/// [`CHAIN_WALK_LIMIT`] errors, counting `err`, and each [`TypedError`]
565/// is one of them.
566///
567/// Every other case returns the flattened chain of `err`
568/// ([`chain_string`]), which omits each [`TypedError`]'s type name: a
569/// record without a message, which ends the walk, any other error on the
570/// way (a serde error or a user wrapper, whose text the message keeps), a
571/// carrier without a source, and a record past the limit.
572pub(crate) fn wire_message(err: &(dyn Error + 'static)) -> String {
573    let mut link = err;
574    for _ in 0..CHAIN_WALK_LIMIT {
575        if let Some(wire) = wire_identity(link) {
576            return wire
577                .error_message()
578                .map_or_else(|| chain_string(err), str::to_owned);
579        }
580        if !is_propagation_carrier(link) {
581            break;
582        }
583        match link.source() {
584            Some(source) => link = source,
585            None => break,
586        }
587    }
588    chain_string(err)
589}
590
591/// Whether `err` only carries another error on its way to a record, so the
592/// recorded-message walk follows its `source()`. An [`OperationError`]
593/// with a record never reaches this check.
594fn is_propagation_carrier(err: &(dyn Error + 'static)) -> bool {
595    err.is::<OperationError>()
596        || err.is::<StepError>()
597        || err.is::<WaitError>()
598        || err.is::<InvokeError>()
599        || err.is::<CallbackError>()
600        || err.is::<WaitForConditionError>()
601        || err.is::<ChildContextError>()
602        || err.is::<CombinatorError>()
603        || err.is::<ChildFnError>()
604        || err.is::<ContextualError>()
605        || err.is::<TypedError>()
606}
607
608/// The error type of the fault that a retryable checkpoint failure records.
609/// It ends the invocation, and the next invocation can recover. JS throws an
610/// error of this class in the same case.
611pub(crate) const CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE: &str =
612    "CheckpointUnrecoverableInvocationError";
613
614/// The error type of the fault that a retryable serdes failure records. JS
615/// throws an error of this class in the same case.
616pub(crate) const SERDES_FAILED_ERROR_TYPE: &str = "SerdesFailedError";
617
618/// The wire `ErrorType` recorded on the `FAILED` envelope when the
619/// execution client fails permanently before the handler runs: a
620/// non-retryable error of the bootstrap state read. It is the type JS
621/// records for its `DurableExecutionClientError`.
622pub(crate) const EXECUTION_CLIENT_ERROR_TYPE: &str = "DurableExecutionClientError";
623
624/// The wire `ErrorType` recorded on the terminal `FAIL` an operation
625/// persists when its result (or carried state) failed LOCAL serialization
626/// before the outcome write (issue #43).
627///
628/// This type is the replay discriminator for the serialization
629/// classification: the live path yields a `SerializationFailed`-kinded
630/// error after persisting this record, and replay reconstructs the SAME
631/// kind by matching this type, so a handler that branches on the kind
632/// takes the same path live and replayed. It is a protocol discriminator
633/// written via [`wire_error_with_type`], never derived from a user error's
634/// own identity.
635pub(crate) const SERIALIZATION_FAILED_ERROR_TYPE: &str = "SerializationError";
636
637/// Builds the wire record a terminal `FAIL` carries when the operation's
638/// result failed local serialization before its outcome write (issue #43).
639///
640/// The fixed [`SERIALIZATION_FAILED_ERROR_TYPE`] is what lets replay
641/// reconstruct the serialization classification (see the constant's doc);
642/// the message ([`wire_message`]) and the `error_data`/`stack_trace` chain
643/// walk are the standard [`wire_error_with_type`] behavior.
644pub(crate) fn serialization_failure_wire(err: &(dyn Error + 'static)) -> WireError {
645    wire_error_with_type(err, SERIALIZATION_FAILED_ERROR_TYPE)
646}
647
648/// The wire `ErrorType` recorded on the terminal `FAIL` a
649/// wait-for-condition operation persists when its wait strategy
650/// exhausted (returned [`WaitDecision::Exhausted`]).
651///
652/// This type is the replay discriminator for the exhaustion
653/// classification: the live path yields a
654/// [`WaitForConditionErrorKind::MaxChecksExceeded`]-kinded error after
655/// persisting this record, and replay reconstructs the SAME kind (with
656/// the check count derived from the checkpoint record's attempt field)
657/// by matching this type, so a handler that branches on the kind (or
658/// reads [`MaxChecksExceeded::checks`]) takes the same path live and
659/// replayed. It is a protocol discriminator written via
660/// [`WireError::new`], never derived from a user error's own identity.
661///
662/// [`WaitDecision::Exhausted`]: crate::builders::wait_for_condition::WaitDecision::Exhausted
663pub(crate) const WFC_EXHAUSTED_ERROR_TYPE: &str = "WaitForCondition.MaxChecksExceeded";
664
665/// The wire `ErrorType` of the execution's `FAILED` record after a
666/// non-retryable checkpoint failure. It is the type JS records for its
667/// `CheckpointUnrecoverableExecutionError`. The SDK writes no further
668/// update for any operation after the failure, so each operation's record
669/// stays at the last update the service accepted.
670pub(crate) const CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE: &str =
671    "CheckpointUnrecoverableExecutionError";
672
673/// Builds the execution's `FAILED` record after a non-retryable
674/// checkpoint failure: [`CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE`] and the
675/// message `[Unrecoverable Execution] Checkpoint failed: {m}`, as JS
676/// writes. `{m}` is the record message of
677/// [`client_error_record_message`](crate::client::client_error_record_message).
678pub(crate) fn checkpoint_execution_failure_wire(
679    err: &crate::client::ExecutionClientError,
680) -> WireError {
681    WireError::new(
682        Some(CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE),
683        Some(format!(
684            "[Unrecoverable Execution] Checkpoint failed: {}",
685            crate::client::client_error_record_message(err)
686        )),
687    )
688}
689
690/// The message of the fault that a retryable checkpoint failure records:
691/// `[Unrecoverable Invocation] Checkpoint failed: {m}`, as JS gives its
692/// `CheckpointUnrecoverableInvocationError`. `{m}` is the record message
693/// of [`client_error_record_message`](crate::client::client_error_record_message),
694/// the text the non-retryable record of
695/// [`checkpoint_execution_failure_wire`] uses.
696pub(crate) fn checkpoint_invocation_failure_message(
697    err: &crate::client::ExecutionClientError,
698) -> String {
699    format!(
700        "[Unrecoverable Invocation] Checkpoint failed: {}",
701        crate::client::client_error_record_message(err)
702    )
703}
704
705/// Returns the wire record carried by `err`, when `err` is one of the
706/// SDK's own wire-record-carrying types.
707fn wire_identity<'a>(err: &'a (dyn Error + 'static)) -> Option<&'a WireError> {
708    if let Some(op) = err.downcast_ref::<OperationError>() {
709        return op.wire();
710    }
711    if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
712        return Some(replayed.wire());
713    }
714    None
715}
716
717/// The top-level error type returned by [`DurableFuture`](crate::DurableFuture).
718///
719/// Wraps a typed per-operation cause accessible via [`kind()`](Self::kind).
720/// Match on the kind to determine the specific failure mode, and walk
721/// [`source()`](std::error::Error::source) to reach the underlying cause:
722/// on the live path that is the escaping error itself (downcastable to its
723/// concrete type), and after a replay it is a [`ReplayedFailure`] carrying
724/// the recorded wire fields.
725///
726/// # Examples
727///
728/// ```
729/// use aws_durable_execution_sdk::{OperationError, OperationErrorKind};
730///
731/// fn handle_error(err: &OperationError) {
732///     match err.kind() {
733///         OperationErrorKind::Step(step_err) => {
734///             // The step's escaping error is reachable through source().
735///             if let Some(cause) = std::error::Error::source(step_err) {
736///                 tracing::error!(%cause, "step failed");
737///             }
738///         }
739///         // `{:#}` prints the full chain; `{}` prints one frame.
740///         _ => tracing::error!(error = format!("{err:#}"), "operation failed"),
741///     }
742/// }
743/// ```
744#[derive(Debug)]
745#[non_exhaustive]
746pub struct OperationError {
747    kind: OperationErrorKind,
748    /// Boxed so the failure context does not widen every
749    /// `Result<_, OperationError>` on the happy path.
750    context: Option<Box<OperationContext>>,
751}
752
753/// The failure's wire context: the operation it belongs to and the wire
754/// record it produced or replayed.
755#[derive(Debug, Default)]
756struct OperationContext {
757    operation_id: Option<String>,
758    status: Option<String>,
759    wire: Option<WireError>,
760}
761
762impl OperationError {
763    /// Returns the specific error kind for this operation failure.
764    ///
765    /// # Examples
766    ///
767    /// ```
768    /// use aws_durable_execution_sdk::{OperationError, OperationErrorKind, StepErrorKind};
769    ///
770    /// let err = OperationError::__test_error();
771    /// if let OperationErrorKind::Step(step_err) = err.kind() {
772    ///     assert!(matches!(step_err.kind(), StepErrorKind::ExecutionFailed { .. }));
773    /// }
774    /// ```
775    pub fn kind(&self) -> &OperationErrorKind {
776        &self.kind
777    }
778
779    /// The wire ID of the operation that failed, when known.
780    pub fn operation_id(&self) -> Option<&str> {
781        self.context.as_ref()?.operation_id.as_deref()
782    }
783
784    /// The operation's wire status (for example `FAILED` or `TIMED_OUT`),
785    /// when known.
786    pub fn status(&self) -> Option<&str> {
787        self.context.as_ref()?.status.as_deref()
788    }
789
790    /// The wire failure record for this error, when one exists.
791    ///
792    /// On a replayed failure this is the record read back from the
793    /// execution history; on a live failure it is the record the SDK
794    /// wrote. `None` for errors that never reached the wire (for example
795    /// a serialization failure before checkpointing).
796    pub fn wire(&self) -> Option<&WireError> {
797        self.context.as_ref()?.wire.as_ref()
798    }
799
800    /// Creates an `OperationError` from its kind (internal).
801    pub(crate) fn from_kind(kind: OperationErrorKind) -> Self {
802        Self {
803            kind,
804            context: None,
805        }
806    }
807
808    /// Attaches the failing operation's wire ID and status (internal).
809    pub(crate) fn with_operation(
810        mut self,
811        operation_id: impl Into<String>,
812        status: impl Into<String>,
813    ) -> Self {
814        let context = self.context.get_or_insert_default();
815        context.operation_id = Some(operation_id.into());
816        context.status = Some(status.into());
817        self
818    }
819
820    /// Attaches the wire failure record (internal).
821    pub(crate) fn with_wire(mut self, wire: WireError) -> Self {
822        self.context.get_or_insert_default().wire = Some(wire);
823        self
824    }
825
826    /// Creates a test error (doc-hidden, for doctests only).
827    #[doc(hidden)]
828    #[must_use]
829    pub fn __test_error() -> Self {
830        Self::from_kind(OperationErrorKind::Step(StepError::new(
831            StepErrorKind::ExecutionFailed,
832            Some(Source::from("test")),
833        )))
834    }
835
836    /// The operation family name used in this error's `Display` frame.
837    fn family(&self) -> &'static str {
838        match &self.kind {
839            OperationErrorKind::Step(_) => "step",
840            OperationErrorKind::Wait(_) => "wait",
841            OperationErrorKind::Invoke(_) => "invoke",
842            OperationErrorKind::Callback(_) => "callback",
843            OperationErrorKind::WaitForCondition(_) => "wait_for_condition",
844            OperationErrorKind::ChildContext(_) => "child_context",
845            OperationErrorKind::Combinator(_) => "combinator",
846            OperationErrorKind::NonDeterministicExecution(_) => "non_deterministic_execution",
847        }
848    }
849}
850
851impl fmt::Display for OperationError {
852    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853        struct Frame<'a>(&'a OperationError);
854        impl fmt::Display for Frame<'_> {
855            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856                write!(f, "operation error: {}", self.0.family())
857            }
858        }
859        if f.alternate() {
860            write_chain(f, &Frame(self), self.source())
861        } else {
862            write!(f, "{}", Frame(self))
863        }
864    }
865}
866
867impl Error for OperationError {
868    fn source(&self) -> Option<&(dyn Error + 'static)> {
869        match &self.kind {
870            OperationErrorKind::Step(e) => Some(e),
871            OperationErrorKind::Wait(e) => Some(e),
872            OperationErrorKind::Invoke(e) => Some(e),
873            OperationErrorKind::Callback(e) => Some(e),
874            OperationErrorKind::WaitForCondition(e) => Some(e),
875            OperationErrorKind::ChildContext(e) => Some(e),
876            OperationErrorKind::Combinator(e) => Some(e),
877            OperationErrorKind::NonDeterministicExecution(e) => Some(e),
878        }
879    }
880}
881
882/// Classification of operation errors by operation type.
883///
884/// # Examples
885///
886/// ```
887/// use aws_durable_execution_sdk::{OperationError, OperationErrorKind};
888///
889/// fn is_retryable(err: &OperationError) -> bool {
890///     // Callback timeouts are external; everything else is treated as
891///     // internal in this example.
892///     matches!(err.kind(), OperationErrorKind::Callback(_))
893/// }
894/// ```
895#[derive(Debug)]
896#[non_exhaustive]
897pub enum OperationErrorKind {
898    /// A step operation failed.
899    Step(StepError),
900    /// A wait operation failed.
901    Wait(WaitError),
902    /// An invoke operation failed.
903    Invoke(InvokeError),
904    /// A callback operation failed.
905    Callback(CallbackError),
906    /// A wait-for-condition operation failed.
907    WaitForCondition(WaitForConditionError),
908    /// A child context operation failed.
909    ChildContext(ChildContextError),
910    /// A combinator operation failed.
911    Combinator(CombinatorError),
912    /// The handler produced operations in a different order than the
913    /// checkpointed history: the execution is non-deterministic.
914    NonDeterministicExecution(NonDeterministicExecutionError),
915}
916
917impl OperationErrorKind {
918    /// The wire `ErrorType` name recorded for this kind when the failing
919    /// error carries no more specific identity.
920    pub(crate) fn wire_type_name(&self) -> &'static str {
921        match self {
922            Self::Step(_) => "StepError",
923            Self::Wait(_) => "WaitError",
924            Self::Invoke(_) => "InvokeError",
925            Self::Callback(_) => "CallbackError",
926            Self::WaitForCondition(_) => "WaitForConditionError",
927            Self::ChildContext(_) => "ChildContextError",
928            Self::Combinator(_) => "PromiseCombinatorError",
929            Self::NonDeterministicExecution(_) => "NonDeterministicExecutionError",
930        }
931    }
932}
933
934impl fmt::Display for OperationErrorKind {
935    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
936        match self {
937            Self::Step(e) => write!(f, "step: {e}"),
938            Self::Wait(e) => write!(f, "wait: {e}"),
939            Self::Invoke(e) => write!(f, "invoke: {e}"),
940            Self::Callback(e) => write!(f, "callback: {e}"),
941            Self::WaitForCondition(e) => write!(f, "wait_for_condition: {e}"),
942            Self::ChildContext(e) => write!(f, "child_context: {e}"),
943            Self::Combinator(e) => write!(f, "combinator: {e}"),
944            Self::NonDeterministicExecution(e) => write!(f, "non_deterministic_execution: {e}"),
945        }
946    }
947}
948
949/// The wire `ErrorMessage` recorded for an interrupted `AtMostOncePerRetry`
950/// attempt, and the `source()` text of [`StepError::interrupted`]. It is the
951/// message the JS SDK records.
952pub(crate) const STEP_INTERRUPTED_MESSAGE: &str = "The step execution process was initiated but failed to reach completion due to an interruption.";
953
954/// Error from a step operation.
955///
956/// Use [`kind()`](Self::kind) to determine the failure mode and
957/// [`source()`](std::error::Error::source) to reach the escaping error.
958///
959/// # Examples
960///
961/// ```
962/// use aws_durable_execution_sdk::{StepError, StepErrorKind};
963///
964/// fn describe(err: &StepError) -> String {
965///     match err.kind() {
966///         // The body's error, also when the retry strategy stopped. Its
967///         // `source()` is that error, and `{:#}` flattens the chain.
968///         StepErrorKind::ExecutionFailed { .. } => format!("body failed: {err:#}"),
969///         _ => format!("{err:#}"),
970///     }
971/// }
972/// ```
973#[derive(Debug)]
974#[non_exhaustive]
975pub struct StepError {
976    kind: StepErrorKind,
977    source: Option<Source>,
978}
979
980impl StepError {
981    /// Returns the specific kind of step error.
982    pub fn kind(&self) -> &StepErrorKind {
983        &self.kind
984    }
985
986    /// Creates the error a retry strategy receives for a step body, a
987    /// `wait_for_callback` submitter or a `with_retry` attempt that
988    /// returned `source`.
989    ///
990    /// Its kind is [`StepErrorKind::ExecutionFailed`], and its
991    /// [`source()`](std::error::Error::source) is `source`. A test uses it
992    /// to call a retry strategy with the error the SDK passes.
993    ///
994    /// # Examples
995    ///
996    /// ```
997    /// use std::time::Duration;
998    ///
999    /// use aws_durable_execution_sdk::{RetryDecision, StepError, StepErrorKind};
1000    ///
1001    /// /// Retries a body error twice, one second apart, and never retries an
1002    /// /// interrupted attempt.
1003    /// fn strategy(err: &StepError, attempt: u32) -> RetryDecision {
1004    ///     if matches!(err.kind(), StepErrorKind::Interrupted { .. }) || attempt >= 3 {
1005    ///         RetryDecision::Stop
1006    ///     } else {
1007    ///         RetryDecision::retry(Duration::from_secs(1))
1008    ///     }
1009    /// }
1010    ///
1011    /// assert_eq!(
1012    ///     strategy(&StepError::execution_failed("throttled"), 1),
1013    ///     RetryDecision::retry(Duration::from_secs(1))
1014    /// );
1015    /// assert_eq!(strategy(&StepError::execution_failed("throttled"), 3), RetryDecision::Stop);
1016    /// assert_eq!(strategy(&StepError::interrupted(), 1), RetryDecision::Stop);
1017    /// ```
1018    #[must_use]
1019    pub fn execution_failed(source: impl Into<crate::BoxError>) -> Self {
1020        Self::new(StepErrorKind::ExecutionFailed, Some(source.into()))
1021    }
1022
1023    /// Creates the error a retry strategy receives for an interrupted
1024    /// `AtMostOncePerRetry` attempt.
1025    ///
1026    /// Its kind is [`StepErrorKind::Interrupted`], and its
1027    /// [`source()`](std::error::Error::source) displays the message the SDK
1028    /// records for an interrupted attempt: `The step execution process was
1029    /// initiated but failed to reach completion due to an interruption.`
1030    #[must_use]
1031    pub fn interrupted() -> Self {
1032        Self::new(
1033            StepErrorKind::Interrupted,
1034            Some(STEP_INTERRUPTED_MESSAGE.into()),
1035        )
1036    }
1037
1038    /// Creates a `StepError` from its kind and source (internal).
1039    pub(crate) fn new(kind: StepErrorKind, source: Option<Source>) -> Self {
1040        Self { kind, source }
1041    }
1042
1043    /// Moves the source out of this error (internal).
1044    pub(crate) fn into_source(self) -> Option<Source> {
1045        self.source
1046    }
1047}
1048
1049impl fmt::Display for StepError {
1050    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051        if f.alternate() {
1052            write_chain(f, &self.kind, self.source())
1053        } else {
1054            write!(f, "{}", self.kind)
1055        }
1056    }
1057}
1058
1059impl Error for StepError {
1060    fn source(&self) -> Option<&(dyn Error + 'static)> {
1061        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1062    }
1063}
1064
1065/// Specific kinds of step failures.
1066///
1067/// Kinds classify; the escaping error is carried by [`StepError`] and
1068/// returned from its [`source()`](std::error::Error::source).
1069///
1070/// # Examples
1071///
1072/// ```
1073/// use aws_durable_execution_sdk::StepErrorKind;
1074///
1075/// fn body_failed(kind: &StepErrorKind) -> bool {
1076///     // Unit kind variants are `#[non_exhaustive]`: match them with
1077///     // `{ .. }` so a future field cannot break the pattern.
1078///     matches!(kind, StepErrorKind::ExecutionFailed { .. })
1079/// }
1080/// ```
1081#[derive(Debug)]
1082#[non_exhaustive]
1083pub enum StepErrorKind {
1084    /// The step body returned an error. A retry strategy receives this kind
1085    /// for the body's error, and the step returns it once the strategy
1086    /// stops. The error's `source()` is the body's error.
1087    #[non_exhaustive]
1088    ExecutionFailed,
1089    /// A serialization or deserialization error occurred.
1090    #[non_exhaustive]
1091    SerializationFailed,
1092    /// An `AtMostOncePerRetry` attempt started but recorded no outcome.
1093    ///
1094    /// The SDK did not run the body again. It recorded the attempt as a
1095    /// failure with error type `StepInterruptedError` and asked the retry
1096    /// strategy whether to schedule another attempt.
1097    #[non_exhaustive]
1098    Interrupted,
1099}
1100
1101impl fmt::Display for StepErrorKind {
1102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103        match self {
1104            Self::ExecutionFailed => write!(f, "execution failed"),
1105            Self::SerializationFailed => write!(f, "serialization failed"),
1106            Self::Interrupted => write!(f, "step interrupted"),
1107        }
1108    }
1109}
1110
1111/// Error from a wait operation.
1112///
1113/// Use [`kind()`](Self::kind) to determine the failure mode.
1114///
1115/// # Examples
1116///
1117/// ```
1118/// use aws_durable_execution_sdk::{WaitError, WaitErrorKind};
1119///
1120/// fn describe(err: &WaitError) -> String {
1121///     match err.kind() {
1122///         WaitErrorKind::UnexpectedStatus(details) => {
1123///             format!("cannot resume from status {}", details.status())
1124///         }
1125///         _ => format!("{err:#}"),
1126///     }
1127/// }
1128/// ```
1129#[derive(Debug)]
1130#[non_exhaustive]
1131pub struct WaitError {
1132    kind: WaitErrorKind,
1133    source: Option<Source>,
1134}
1135
1136impl WaitError {
1137    /// Returns the specific kind of wait error.
1138    pub fn kind(&self) -> &WaitErrorKind {
1139        &self.kind
1140    }
1141
1142    /// Creates a `WaitError` from its kind and source (internal).
1143    pub(crate) fn new(kind: WaitErrorKind, source: Option<Source>) -> Self {
1144        Self { kind, source }
1145    }
1146}
1147
1148impl fmt::Display for WaitError {
1149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150        if f.alternate() {
1151            write_chain(f, &self.kind, self.source())
1152        } else {
1153            write!(f, "{}", self.kind)
1154        }
1155    }
1156}
1157
1158impl Error for WaitError {
1159    fn source(&self) -> Option<&(dyn Error + 'static)> {
1160        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1161    }
1162}
1163
1164/// Specific kinds of wait failures.
1165///
1166/// A checkpoint write failure is deliberately NOT a kind here: a failed
1167/// wait START write unwinds the handler through the unrecoverable path
1168/// (issue #43), so user code never observes it as a `WaitError`.
1169///
1170/// # Examples
1171///
1172/// ```
1173/// use aws_durable_execution_sdk::WaitErrorKind;
1174///
1175/// fn is_unexpected_status(kind: &WaitErrorKind) -> bool {
1176///     matches!(kind, WaitErrorKind::UnexpectedStatus(_))
1177/// }
1178/// ```
1179#[derive(Debug)]
1180#[non_exhaustive]
1181pub enum WaitErrorKind {
1182    /// The wait's checkpointed record carries a status the SDK cannot
1183    /// resume from.
1184    UnexpectedStatus(UnexpectedStatus),
1185}
1186
1187impl fmt::Display for WaitErrorKind {
1188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189        match self {
1190            Self::UnexpectedStatus(details) => write!(f, "{details}"),
1191        }
1192    }
1193}
1194
1195/// Details of a [`WaitErrorKind::UnexpectedStatus`] failure.
1196#[derive(Debug)]
1197#[non_exhaustive]
1198pub struct UnexpectedStatus {
1199    status: String,
1200}
1201
1202impl UnexpectedStatus {
1203    /// Creates the payload (internal).
1204    pub(crate) fn new(status: impl Into<String>) -> Self {
1205        Self {
1206            status: status.into(),
1207        }
1208    }
1209
1210    /// The unexpected status found in the checkpoint log.
1211    pub fn status(&self) -> &str {
1212        &self.status
1213    }
1214}
1215
1216impl fmt::Display for UnexpectedStatus {
1217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1218        write!(f, "unexpected checkpointed status: {}", self.status)
1219    }
1220}
1221
1222/// Error from an invoke operation.
1223///
1224/// # Examples
1225///
1226/// ```
1227/// use std::error::Error as _;
1228///
1229/// use aws_durable_execution_sdk::{InvokeError, InvokeErrorKind, ReplayedFailure};
1230///
1231/// fn remote_error_type(err: &InvokeError) -> Option<&str> {
1232///     match err.kind() {
1233///         InvokeErrorKind::FunctionFailed { .. } => err
1234///             .source()?
1235///             .downcast_ref::<ReplayedFailure>()?
1236///             .error_type(),
1237///         _ => None,
1238///     }
1239/// }
1240/// ```
1241#[derive(Debug)]
1242#[non_exhaustive]
1243pub struct InvokeError {
1244    kind: InvokeErrorKind,
1245    source: Option<Source>,
1246}
1247
1248impl InvokeError {
1249    /// Returns the specific kind of invoke error.
1250    pub fn kind(&self) -> &InvokeErrorKind {
1251        &self.kind
1252    }
1253
1254    /// Creates an `InvokeError` from its kind and source (internal).
1255    pub(crate) fn new(kind: InvokeErrorKind, source: Option<Source>) -> Self {
1256        Self { kind, source }
1257    }
1258}
1259
1260impl fmt::Display for InvokeError {
1261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262        if f.alternate() {
1263            write_chain(f, &self.kind, self.source())
1264        } else {
1265            write!(f, "{}", self.kind)
1266        }
1267    }
1268}
1269
1270impl Error for InvokeError {
1271    fn source(&self) -> Option<&(dyn Error + 'static)> {
1272        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1273    }
1274}
1275
1276/// Specific kinds of invoke failures.
1277///
1278/// # Examples
1279///
1280/// ```
1281/// use aws_durable_execution_sdk::InvokeErrorKind;
1282///
1283/// fn failed_in_function(kind: &InvokeErrorKind) -> bool {
1284///     // Unit kind variants are `#[non_exhaustive]`: match them with
1285///     // `{ .. }` so a future field cannot break the pattern.
1286///     matches!(kind, InvokeErrorKind::FunctionFailed { .. })
1287/// }
1288/// ```
1289#[derive(Debug)]
1290#[non_exhaustive]
1291pub enum InvokeErrorKind {
1292    /// The invoke's record ended `FAILED`, `TIMED_OUT`, `STOPPED` or
1293    /// `CANCELLED`.
1294    ///
1295    /// The error's [`wire()`](crate::OperationError::wire) and its
1296    /// [`ReplayedFailure`] source carry the record's error type, message,
1297    /// data and stack trace. A record without a message, or with an empty
1298    /// one, gives the message `Invoke failed`.
1299    #[non_exhaustive]
1300    FunctionFailed,
1301    /// A serialization or deserialization error occurred.
1302    #[non_exhaustive]
1303    SerializationFailed,
1304}
1305
1306impl fmt::Display for InvokeErrorKind {
1307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1308        match self {
1309            Self::FunctionFailed => write!(f, "function failed"),
1310            Self::SerializationFailed => write!(f, "serialization failed"),
1311        }
1312    }
1313}
1314
1315/// Error from a callback operation.
1316///
1317/// Follows the graded external/internal split: external errors are
1318/// caused by the caller's system (timeout, invalid data), and internal
1319/// errors are SDK or service failures. For an
1320/// [`ExternalFailure`](CallbackErrorKind::ExternalFailure), the wire
1321/// record is reachable through the error's
1322/// [`source()`](std::error::Error::source) (a [`ReplayedFailure`]) and
1323/// through [`OperationError::wire`]. From `create_callback`, it keeps
1324/// the callback record's error type, error data and stack trace. From
1325/// `wait_for_callback`, it has the type `Callback.ExternalFailure` and
1326/// keeps the callback record's error data. Both keep a nonempty message
1327/// and otherwise use `Callback failed`.
1328///
1329/// # Examples
1330///
1331/// ```
1332/// use aws_durable_execution_sdk::{CallbackError, CallbackErrorKind};
1333///
1334/// fn describe(err: &CallbackError) -> String {
1335///     match err.kind() {
1336///         CallbackErrorKind::TimedOut { .. } => "timed out".to_owned(),
1337///         // The failure record travels on `source()`. Its type is the
1338///         // external caller's from `create_callback`, and
1339///         // `Callback.ExternalFailure` from `wait_for_callback`.
1340///         CallbackErrorKind::ExternalFailure { .. } => format!("{err:#}"),
1341///         _ => format!("{err:#}"),
1342///     }
1343/// }
1344/// ```
1345#[derive(Debug)]
1346#[non_exhaustive]
1347pub struct CallbackError {
1348    kind: CallbackErrorKind,
1349    source: Option<Source>,
1350}
1351
1352impl CallbackError {
1353    /// Returns the specific kind of callback error.
1354    pub fn kind(&self) -> &CallbackErrorKind {
1355        &self.kind
1356    }
1357
1358    /// Creates a `CallbackError` from its kind and source (internal).
1359    pub(crate) fn new(kind: CallbackErrorKind, source: Option<Source>) -> Self {
1360        Self { kind, source }
1361    }
1362}
1363
1364impl fmt::Display for CallbackError {
1365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1366        if f.alternate() {
1367            write_chain(f, &self.kind, self.source())
1368        } else {
1369            write!(f, "{}", self.kind)
1370        }
1371    }
1372}
1373
1374impl Error for CallbackError {
1375    fn source(&self) -> Option<&(dyn Error + 'static)> {
1376        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1377    }
1378}
1379
1380/// Specific kinds of callback failures.
1381///
1382/// The external/internal split separates user-attributable errors
1383/// (timeout, invalid payload) from SDK/service failures.
1384///
1385/// # Examples
1386///
1387/// ```
1388/// use aws_durable_execution_sdk::CallbackErrorKind;
1389///
1390/// fn is_external(kind: &CallbackErrorKind) -> bool {
1391///     matches!(
1392///         kind,
1393///         CallbackErrorKind::TimedOut { .. }
1394///             | CallbackErrorKind::HeartbeatTimedOut { .. }
1395///             | CallbackErrorKind::ExternalFailure { .. }
1396///             | CallbackErrorKind::SubmitterFailed { .. }
1397///     )
1398/// }
1399/// ```
1400#[derive(Debug)]
1401#[non_exhaustive]
1402pub enum CallbackErrorKind {
1403    /// The callback timed out waiting for completion.
1404    ///
1405    /// The enclosing error's [`OperationError::wire`] record keeps the
1406    /// callback record's message and error data. An absent or empty message
1407    /// becomes `Callback timed out`. From `wait_for_callback`, the wire
1408    /// record has type `Callback.Timeout`.
1409    #[non_exhaustive]
1410    TimedOut,
1411    /// The callback heartbeat timed out (no keep-alive received in time).
1412    ///
1413    /// The service records a heartbeat timeout as a `TIMED_OUT` callback
1414    /// with the error type `Callback.Heartbeat`. Both `create_callback`
1415    /// and `wait_for_callback` report it with this kind. The enclosing
1416    /// error's [`OperationError::wire`] record keeps the callback record's
1417    /// message and error data. An absent or empty message becomes
1418    /// `Callback timed out`. From `wait_for_callback`, the wire record has
1419    /// type `Callback.Heartbeat`.
1420    #[non_exhaustive]
1421    HeartbeatTimedOut,
1422    /// The callback record is `FAILED`, `CANCELLED` or `STOPPED`, whatever
1423    /// its error type: an external system failed the callback, or the
1424    /// service cancelled or stopped it.
1425    ///
1426    /// The failure fields travel as wire data. Read them from the error's
1427    /// [`source()`](std::error::Error::source) (a [`ReplayedFailure`]) or
1428    /// from [`OperationError::wire`]. From `create_callback`, the wire
1429    /// record keeps the callback record's error type, error data and stack
1430    /// trace. It keeps a nonempty message and otherwise uses
1431    /// `Callback failed`. From `wait_for_callback`, the wire record has the
1432    /// type `Callback.ExternalFailure`. It keeps the callback record's error
1433    /// data and the same normalized message. The callback operation's
1434    /// stored record keeps the external type and original message field.
1435    #[non_exhaustive]
1436    ExternalFailure,
1437    /// The callback payload could not be deserialized.
1438    ///
1439    /// This is a payload decode failure that the serdes did not mark with
1440    /// [`RetryableSerdesError`](crate::serdes::RetryableSerdesError); a
1441    /// marked failure ends the invocation instead. From `create_callback`,
1442    /// `create_callback(..).await` succeeds, and
1443    /// [`Callback::result`](crate::builders::callback::Callback::result) or
1444    /// [`Callback::spawn_result`](crate::builders::callback::Callback::spawn_result) returns
1445    /// this permanent error, live and on replay. From
1446    /// `wait_for_callback`, the outer operation's record has already
1447    /// succeeded with the raw payload, and this error is the decode of that
1448    /// payload with the operation's serdes. So every invocation that reads
1449    /// the record fails the same way.
1450    #[non_exhaustive]
1451    DeserializationFailed,
1452    /// An internal SDK or service error occurred.
1453    #[non_exhaustive]
1454    Internal,
1455    /// The `wait_for_callback` submitter failed and its retry strategy stopped.
1456    ///
1457    /// Live, `source()` is the submitter step's `OperationError`. On replay,
1458    /// `source()` is a `ReplayedFailure` holding the recorded outer failure.
1459    #[non_exhaustive]
1460    SubmitterFailed,
1461}
1462
1463impl fmt::Display for CallbackErrorKind {
1464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1465        match self {
1466            Self::TimedOut => write!(f, "callback timed out"),
1467            Self::HeartbeatTimedOut => write!(f, "callback heartbeat timed out"),
1468            Self::ExternalFailure => write!(f, "external failure"),
1469            Self::DeserializationFailed => write!(f, "deserialization failed"),
1470            Self::Internal => write!(f, "internal error"),
1471            Self::SubmitterFailed => write!(f, "submitter failed"),
1472        }
1473    }
1474}
1475
1476/// Error from a wait-for-condition operation.
1477///
1478/// # Examples
1479///
1480/// ```
1481/// use aws_durable_execution_sdk::{WaitForConditionError, WaitForConditionErrorKind};
1482///
1483/// fn checks_used(err: &WaitForConditionError) -> Option<u32> {
1484///     match err.kind() {
1485///         WaitForConditionErrorKind::MaxChecksExceeded(details) => Some(details.checks()),
1486///         _ => None,
1487///     }
1488/// }
1489/// ```
1490#[derive(Debug)]
1491#[non_exhaustive]
1492pub struct WaitForConditionError {
1493    kind: WaitForConditionErrorKind,
1494    source: Option<Source>,
1495}
1496
1497impl WaitForConditionError {
1498    /// Returns the specific kind of wait-for-condition error.
1499    pub fn kind(&self) -> &WaitForConditionErrorKind {
1500        &self.kind
1501    }
1502
1503    /// Creates a `WaitForConditionError` from its kind and source (internal).
1504    pub(crate) fn new(kind: WaitForConditionErrorKind, source: Option<Source>) -> Self {
1505        Self { kind, source }
1506    }
1507}
1508
1509impl fmt::Display for WaitForConditionError {
1510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1511        if f.alternate() {
1512            write_chain(f, &self.kind, self.source())
1513        } else {
1514            write!(f, "{}", self.kind)
1515        }
1516    }
1517}
1518
1519impl Error for WaitForConditionError {
1520    fn source(&self) -> Option<&(dyn Error + 'static)> {
1521        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1522    }
1523}
1524
1525/// Specific kinds of wait-for-condition failures.
1526///
1527/// # Examples
1528///
1529/// ```
1530/// use aws_durable_execution_sdk::WaitForConditionErrorKind;
1531///
1532/// fn check_function_failed(kind: &WaitForConditionErrorKind) -> bool {
1533///     matches!(kind, WaitForConditionErrorKind::CheckFailed { .. })
1534/// }
1535/// ```
1536#[derive(Debug)]
1537#[non_exhaustive]
1538pub enum WaitForConditionErrorKind {
1539    /// The check function returned an error.
1540    #[non_exhaustive]
1541    CheckFailed,
1542    /// The maximum number of checks was exceeded.
1543    MaxChecksExceeded(MaxChecksExceeded),
1544    /// A serialization error occurred on the state.
1545    #[non_exhaustive]
1546    SerializationFailed,
1547}
1548
1549impl fmt::Display for WaitForConditionErrorKind {
1550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1551        match self {
1552            Self::CheckFailed => write!(f, "check failed"),
1553            Self::MaxChecksExceeded(details) => write!(f, "{details}"),
1554            Self::SerializationFailed => write!(f, "serialization failed"),
1555        }
1556    }
1557}
1558
1559/// Details of a [`WaitForConditionErrorKind::MaxChecksExceeded`] failure.
1560#[derive(Debug)]
1561#[non_exhaustive]
1562pub struct MaxChecksExceeded {
1563    checks: u32,
1564}
1565
1566impl MaxChecksExceeded {
1567    /// Creates the payload (internal).
1568    pub(crate) fn new(checks: u32) -> Self {
1569        Self { checks }
1570    }
1571
1572    /// The number of checks performed.
1573    pub fn checks(&self) -> u32 {
1574        self.checks
1575    }
1576}
1577
1578impl fmt::Display for MaxChecksExceeded {
1579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1580        write!(f, "max checks exceeded: {}", self.checks)
1581    }
1582}
1583
1584/// Error from a child context (sub-orchestration) operation.
1585///
1586/// # Examples
1587///
1588/// ```
1589/// use aws_durable_execution_sdk::{ChildContextError, ChildContextErrorKind};
1590///
1591/// fn child_body_failed(err: &ChildContextError) -> bool {
1592///     matches!(err.kind(), ChildContextErrorKind::ChildFailed { .. })
1593/// }
1594/// ```
1595#[derive(Debug)]
1596#[non_exhaustive]
1597pub struct ChildContextError {
1598    kind: ChildContextErrorKind,
1599    source: Option<Source>,
1600}
1601
1602impl ChildContextError {
1603    /// Returns the specific kind of child context error.
1604    pub fn kind(&self) -> &ChildContextErrorKind {
1605        &self.kind
1606    }
1607
1608    /// Creates a `ChildContextError` from its kind and source (internal).
1609    pub(crate) fn new(kind: ChildContextErrorKind, source: Option<Source>) -> Self {
1610        Self { kind, source }
1611    }
1612}
1613
1614impl fmt::Display for ChildContextError {
1615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616        if f.alternate() {
1617            write_chain(f, &self.kind, self.source())
1618        } else {
1619            write!(f, "{}", self.kind)
1620        }
1621    }
1622}
1623
1624impl Error for ChildContextError {
1625    fn source(&self) -> Option<&(dyn Error + 'static)> {
1626        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
1627    }
1628}
1629
1630/// Specific kinds of child context failures.
1631///
1632/// # Examples
1633///
1634/// ```
1635/// use aws_durable_execution_sdk::ChildContextErrorKind;
1636///
1637/// fn is_internal(kind: &ChildContextErrorKind) -> bool {
1638///     matches!(kind, ChildContextErrorKind::Internal { .. })
1639/// }
1640/// ```
1641#[derive(Debug)]
1642#[non_exhaustive]
1643pub enum ChildContextErrorKind {
1644    /// The child function returned an error.
1645    #[non_exhaustive]
1646    ChildFailed,
1647    /// An internal error occurred setting up the child context.
1648    #[non_exhaustive]
1649    Internal,
1650    /// A map or parallel completion predicate completed the batch as failed
1651    /// (`CUSTOM_COMPLETION_FAILED`), and no item failed.
1652    #[non_exhaustive]
1653    BatchCompletionFailed,
1654    /// A [`BranchHandle`](crate::BranchHandle) has no result: the
1655    /// `parallel_mixed` operation that owns its branch has not returned, the
1656    /// branch never started, or the batch completed while the branch still
1657    /// ran.
1658    #[non_exhaustive]
1659    NotCompleted,
1660}
1661
1662impl fmt::Display for ChildContextErrorKind {
1663    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1664        match self {
1665            Self::ChildFailed => write!(f, "child failed"),
1666            Self::Internal => write!(f, "internal error"),
1667            Self::BatchCompletionFailed => write!(f, "batch completed as failed"),
1668            Self::NotCompleted => write!(f, "branch has no result"),
1669        }
1670    }
1671}
1672
1673/// Error from a combinator operation (`try_join_all`, `join_all`,
1674/// `select_ok`, `race`).
1675///
1676/// The combinator preserves the losing futures' errors as errors:
1677/// [`source()`](std::error::Error::source) returns the first loser, and
1678/// [`failures()`](Self::failures) returns every loser (in input order for
1679/// [`CombinatorErrorKind::AllFailed`]).
1680///
1681/// # Examples
1682///
1683/// ```
1684/// use aws_durable_execution_sdk::{CombinatorError, CombinatorErrorKind};
1685///
1686/// fn report(err: &CombinatorError) {
1687///     if let CombinatorErrorKind::AllFailed { .. } = err.kind() {
1688///         for loser in err.failures() {
1689///             tracing::error!(error = format!("{loser}"), "branch failed");
1690///         }
1691///     }
1692/// }
1693/// ```
1694#[derive(Debug)]
1695#[non_exhaustive]
1696pub struct CombinatorError {
1697    kind: CombinatorErrorKind,
1698    failures: Vec<Source>,
1699}
1700
1701impl CombinatorError {
1702    /// Creates a `CombinatorError` from a kind and its losing errors
1703    /// (internal).
1704    pub(crate) fn new(kind: CombinatorErrorKind, failures: Vec<Source>) -> Self {
1705        Self { kind, failures }
1706    }
1707
1708    /// Returns the specific kind of combinator error.
1709    pub fn kind(&self) -> &CombinatorErrorKind {
1710        &self.kind
1711    }
1712
1713    /// The underlying failures, preserved as errors.
1714    ///
1715    /// For [`CombinatorErrorKind::JoinFailed`] and
1716    /// [`CombinatorErrorKind::FirstSettledFailed`] this holds the single
1717    /// losing error; for [`CombinatorErrorKind::AllFailed`] it holds every
1718    /// loser in input order. After a replay, each entry is a
1719    /// [`ReplayedFailure`] rebuilt from the recorded wire fields.
1720    pub fn failures(&self) -> &[Box<dyn Error + Send + Sync + 'static>] {
1721        &self.failures
1722    }
1723}
1724
1725impl fmt::Display for CombinatorError {
1726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1727        if f.alternate() {
1728            write_chain(f, &self.kind, self.source())
1729        } else {
1730            write!(f, "{}", self.kind)
1731        }
1732    }
1733}
1734
1735impl Error for CombinatorError {
1736    fn source(&self) -> Option<&(dyn Error + 'static)> {
1737        self.failures
1738            .first()
1739            .map(|s| &**s as &(dyn Error + 'static))
1740    }
1741}
1742
1743/// Specific kinds of combinator failures.
1744///
1745/// # Examples
1746///
1747/// ```
1748/// use aws_durable_execution_sdk::CombinatorErrorKind;
1749///
1750/// fn first_failed_index(kind: &CombinatorErrorKind) -> Option<usize> {
1751///     match kind {
1752///         CombinatorErrorKind::JoinFailed(details) => Some(details.failed_index()),
1753///         _ => None,
1754///     }
1755/// }
1756/// ```
1757#[derive(Debug)]
1758#[non_exhaustive]
1759pub enum CombinatorErrorKind {
1760    /// One or more futures in `try_join_all` failed.
1761    JoinFailed(JoinFailed),
1762    /// All futures in `select_ok` failed.
1763    ///
1764    /// Every loser's error is reachable through
1765    /// [`CombinatorError::failures`].
1766    #[non_exhaustive]
1767    AllFailed,
1768    /// The first settled future in `race` was a failure.
1769    ///
1770    /// `race` propagates the first outcome to settle, success or failure.
1771    /// When that outcome is a failure, the losing future's error is
1772    /// carried as the error's source.
1773    #[non_exhaustive]
1774    FirstSettledFailed,
1775    /// The combinator was called with no futures.
1776    ///
1777    /// Returned by `race` and `select_ok`, which cannot produce a winner
1778    /// from an empty input. `try_join_all` and `join_all` instead resolve
1779    /// successfully to an empty collection.
1780    #[non_exhaustive]
1781    EmptyInput,
1782    /// An internal error occurred.
1783    #[non_exhaustive]
1784    Internal,
1785}
1786
1787impl fmt::Display for CombinatorErrorKind {
1788    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1789        match self {
1790            Self::JoinFailed(details) => write!(f, "{details}"),
1791            Self::AllFailed => write!(f, "all futures failed"),
1792            Self::FirstSettledFailed => write!(f, "first settled future failed"),
1793            Self::EmptyInput => write!(f, "combinator called with no futures"),
1794            Self::Internal => write!(f, "internal error"),
1795        }
1796    }
1797}
1798
1799/// Details of a [`CombinatorErrorKind::JoinFailed`] failure.
1800#[derive(Debug)]
1801#[non_exhaustive]
1802pub struct JoinFailed {
1803    failed_index: usize,
1804}
1805
1806impl JoinFailed {
1807    /// Creates the payload (internal).
1808    pub(crate) fn new(failed_index: usize) -> Self {
1809        Self { failed_index }
1810    }
1811
1812    /// The index of the first failed future in the combinator's input.
1813    pub fn failed_index(&self) -> usize {
1814        self.failed_index
1815    }
1816}
1817
1818impl fmt::Display for JoinFailed {
1819    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1820        write!(f, "join failed at index {}", self.failed_index)
1821    }
1822}
1823
1824/// Error raised when replay cannot faithfully reproduce the checkpointed
1825/// history: the claimed operation does not match the record at its slot
1826/// (the handler produced operations in a different order between
1827/// invocations), or the record carries a status this SDK version cannot
1828/// interpret.
1829///
1830/// This is a fatal, non-recoverable error: the execution must be failed and
1831/// cannot be retried without resetting the checkpoint log.
1832///
1833/// There is no foreign cause to carry (the report *is* the
1834/// error), so this type has no source; its structural facts live behind
1835/// the kind payload's accessors (see [`OperationMismatch`] and
1836/// [`UnrecognizedStatus`]).
1837///
1838/// # Examples
1839///
1840/// ```
1841/// use aws_durable_execution_sdk::{
1842///     NonDeterministicExecutionError, NonDeterministicExecutionErrorKind,
1843/// };
1844///
1845/// fn report(err: &NonDeterministicExecutionError) {
1846///     match err.kind() {
1847///         NonDeterministicExecutionErrorKind::OperationMismatch(details) => {
1848///             tracing::error!(
1849///                 wire_id = details.wire_id(),
1850///                 expected = details.expected(),
1851///                 actual = details.actual(),
1852///                 "non-deterministic replay detected"
1853///             );
1854///         }
1855///         // The enum is `#[non_exhaustive]`: new mismatch kinds may be
1856///         // added without a major version bump.
1857///         _ => tracing::error!("non-deterministic replay detected"),
1858///     }
1859/// }
1860/// ```
1861#[derive(Debug)]
1862#[non_exhaustive]
1863pub struct NonDeterministicExecutionError {
1864    kind: NonDeterministicExecutionErrorKind,
1865}
1866
1867impl NonDeterministicExecutionError {
1868    /// Returns the specific kind of non-determinism error.
1869    pub fn kind(&self) -> &NonDeterministicExecutionErrorKind {
1870        &self.kind
1871    }
1872
1873    /// Creates a `NonDeterministicExecutionError` from its kind (internal).
1874    pub(crate) fn from_kind(kind: NonDeterministicExecutionErrorKind) -> Self {
1875        Self { kind }
1876    }
1877}
1878
1879impl fmt::Display for NonDeterministicExecutionError {
1880    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1881        write!(f, "{}", self.kind)
1882    }
1883}
1884
1885impl Error for NonDeterministicExecutionError {}
1886
1887/// Specific kinds of non-deterministic execution failures.
1888///
1889/// # Examples
1890///
1891/// ```
1892/// use aws_durable_execution_sdk::NonDeterministicExecutionErrorKind;
1893///
1894/// fn mismatch_slot(kind: &NonDeterministicExecutionErrorKind) -> Option<&str> {
1895///     match kind {
1896///         NonDeterministicExecutionErrorKind::OperationMismatch(details) => {
1897///             Some(details.wire_id())
1898///         }
1899///         _ => None,
1900///     }
1901/// }
1902/// ```
1903#[derive(Debug)]
1904#[non_exhaustive]
1905pub enum NonDeterministicExecutionErrorKind {
1906    /// The claimed operation's identity (type, sub-type, or name) does not
1907    /// match the checkpointed record at the same positional slot.
1908    OperationMismatch(OperationMismatch),
1909    /// The operation's checkpoint record carries a status the SDK does not
1910    /// recognize, so the recorded outcome cannot be interpreted.
1911    ///
1912    /// Guessing is unsafe in both directions: treating a possibly-terminal
1913    /// operation as re-runnable can repeat completed work, and fabricating a
1914    /// terminal outcome can return a result the service never recorded. The
1915    /// execution fails and names the raw status.
1916    UnrecognizedStatus(UnrecognizedStatus),
1917}
1918
1919impl fmt::Display for NonDeterministicExecutionErrorKind {
1920    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1921        match self {
1922            Self::OperationMismatch(details) => write!(f, "{details}"),
1923            Self::UnrecognizedStatus(details) => write!(f, "{details}"),
1924        }
1925    }
1926}
1927
1928/// Details of a [`NonDeterministicExecutionErrorKind::OperationMismatch`]
1929/// failure.
1930#[derive(Debug)]
1931#[non_exhaustive]
1932pub struct OperationMismatch {
1933    wire_id: String,
1934    expected: String,
1935    actual: String,
1936}
1937
1938impl OperationMismatch {
1939    /// Creates the payload (internal).
1940    pub(crate) fn new(
1941        wire_id: impl Into<String>,
1942        expected: impl Into<String>,
1943        actual: impl Into<String>,
1944    ) -> Self {
1945        Self {
1946            wire_id: wire_id.into(),
1947            expected: expected.into(),
1948            actual: actual.into(),
1949        }
1950    }
1951
1952    /// The wire ID (SHA-256 hex) of the positional slot that mismatched.
1953    pub fn wire_id(&self) -> &str {
1954        &self.wire_id
1955    }
1956
1957    /// Human-readable description of what the checkpoint log expected.
1958    pub fn expected(&self) -> &str {
1959        &self.expected
1960    }
1961
1962    /// Human-readable description of what the handler claimed.
1963    pub fn actual(&self) -> &str {
1964        &self.actual
1965    }
1966}
1967
1968impl fmt::Display for OperationMismatch {
1969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1970        write!(
1971            f,
1972            "operation at wire id {} does not match checkpoint: \
1973             expected {}, got {}",
1974            self.wire_id, self.expected, self.actual
1975        )
1976    }
1977}
1978
1979/// Details of a [`NonDeterministicExecutionErrorKind::UnrecognizedStatus`]
1980/// failure.
1981#[derive(Debug)]
1982#[non_exhaustive]
1983pub struct UnrecognizedStatus {
1984    wire_id: String,
1985    status: String,
1986}
1987
1988impl UnrecognizedStatus {
1989    /// Creates the payload (internal).
1990    pub(crate) fn new(wire_id: impl Into<String>, status: impl Into<String>) -> Self {
1991        Self {
1992            wire_id: wire_id.into(),
1993            status: status.into(),
1994        }
1995    }
1996
1997    /// The wire ID (SHA-256 hex) of the operation whose record carries the
1998    /// unrecognized status.
1999    pub fn wire_id(&self) -> &str {
2000        &self.wire_id
2001    }
2002
2003    /// The raw status value the service reported, verbatim.
2004    pub fn status(&self) -> &str {
2005        &self.status
2006    }
2007}
2008
2009impl fmt::Display for UnrecognizedStatus {
2010    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2011        write!(
2012            f,
2013            "operation at wire id {} has unrecognized status {:?}: \
2014             the SDK cannot interpret the recorded outcome",
2015            self.wire_id, self.status
2016        )
2017    }
2018}
2019
2020/// Crate-internal error carrier for `run_in_child_context`, `parallel`, and
2021/// `map` closure bodies.
2022///
2023/// Public closure boundaries take [`crate::BoxError`]; the SDK converts a
2024/// `BoxError` into this type at the boundary and grades it into
2025/// [`ChildContextErrorKind::ChildFailed`] when a child body fails. It
2026/// carries the escaping error as its source rather than flattening it, so
2027/// the child-boundary pass-through guarantee (`error_data`, downcastable
2028/// cause) holds. It is not part of the public API.
2029#[derive(Debug)]
2030pub(crate) struct ChildFnError {
2031    source: Source,
2032}
2033
2034impl ChildFnError {
2035    /// Creates a new `ChildFnError` carrying the given source.
2036    #[must_use]
2037    pub(crate) fn new(source: impl Into<Source>) -> Self {
2038        Self {
2039            source: source.into(),
2040        }
2041    }
2042
2043    /// Moves the carried error out (internal).
2044    pub(crate) fn into_source(self) -> Source {
2045        self.source
2046    }
2047
2048    /// The wire record a failed child, map item or branch writes: derived
2049    /// from the error the body returned, with fallback type `"Error"`.
2050    ///
2051    /// The record is derived from the body error, not from this carrier.
2052    /// The carrier is an internal Rust type. Deriving from it would record
2053    /// its name as the type and prefix its own text to the message. So the
2054    /// record follows [`wire_error_for`]'s rule applied to the body error:
2055    /// a body that propagates an operation failure records that failure's
2056    /// recorded message ([`wire_message`]).
2057    pub(crate) fn failure_wire(&self) -> WireError {
2058        wire_error_for(&*self.source, "Error")
2059    }
2060}
2061
2062impl fmt::Display for ChildFnError {
2063    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064        if f.alternate() {
2065            write_chain(f, &"child function error", self.source())
2066        } else {
2067            write!(f, "child function error")
2068        }
2069    }
2070}
2071
2072impl Error for ChildFnError {
2073    fn source(&self) -> Option<&(dyn Error + 'static)> {
2074        Some(&*self.source as &(dyn Error + 'static))
2075    }
2076}
2077
2078impl From<OperationError> for ChildFnError {
2079    fn from(err: OperationError) -> Self {
2080        Self {
2081            source: Box::new(err),
2082        }
2083    }
2084}
2085
2086impl From<crate::BoxError> for ChildFnError {
2087    /// Converts a user-facing [`crate::BoxError`] into the internal
2088    /// carrier, preserving the error itself as the source.
2089    fn from(err: crate::BoxError) -> Self {
2090        Self { source: err }
2091    }
2092}
2093
2094// Static assertions: all public error types must be Send + Sync + 'static.
2095// These compile-time checks prevent accidental regressions: the `source`
2096// fields' `Send + Sync` bounds are what keep them true. The helper is
2097// genuinely called during const evaluation, so no dead-code override is
2098// needed (and `#[expect(dead_code)]` here diverges across toolchains).
2099const _: () = {
2100    const fn assert_send_sync_static<T: Send + Sync + 'static>() {}
2101    assert_send_sync_static::<OperationError>();
2102    assert_send_sync_static::<OperationErrorKind>();
2103    assert_send_sync_static::<StepError>();
2104    assert_send_sync_static::<StepErrorKind>();
2105    assert_send_sync_static::<WaitError>();
2106    assert_send_sync_static::<WaitErrorKind>();
2107    assert_send_sync_static::<UnexpectedStatus>();
2108    assert_send_sync_static::<InvokeError>();
2109    assert_send_sync_static::<InvokeErrorKind>();
2110    assert_send_sync_static::<CallbackError>();
2111    assert_send_sync_static::<CallbackErrorKind>();
2112    assert_send_sync_static::<WaitForConditionError>();
2113    assert_send_sync_static::<WaitForConditionErrorKind>();
2114    assert_send_sync_static::<MaxChecksExceeded>();
2115    assert_send_sync_static::<ChildContextError>();
2116    assert_send_sync_static::<ChildContextErrorKind>();
2117    assert_send_sync_static::<CombinatorError>();
2118    assert_send_sync_static::<CombinatorErrorKind>();
2119    assert_send_sync_static::<JoinFailed>();
2120    assert_send_sync_static::<NonDeterministicExecutionError>();
2121    assert_send_sync_static::<NonDeterministicExecutionErrorKind>();
2122    assert_send_sync_static::<OperationMismatch>();
2123    assert_send_sync_static::<WireError>();
2124    assert_send_sync_static::<TypedError>();
2125    assert_send_sync_static::<ReplayedFailure>();
2126    assert_send_sync_static::<ContextualError>();
2127    assert_send_sync_static::<ChildFnError>();
2128    assert_send_sync_static::<crate::serdes::FileSystemSerdesError>();
2129};
2130
2131/// A failed step's error as an operation returns it: a
2132/// `Step(ExecutionFailed)` [`OperationError`] carrying `wire` as its record,
2133/// whose source is a [`ReplayedFailure`] of the same record (test helper).
2134#[cfg(test)]
2135pub(crate) fn recorded_step_error(wire: WireError) -> OperationError {
2136    OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2137        StepErrorKind::ExecutionFailed,
2138        Some(ReplayedFailure::source_from(wire.clone())),
2139    )))
2140    .with_wire(wire)
2141}
2142
2143#[cfg(test)]
2144mod tests {
2145    use super::*;
2146
2147    /// The retryable checkpoint failure's message is JS's: the prefix
2148    /// `[Unrecoverable Invocation] Checkpoint failed: ` and the error's
2149    /// record message.
2150    #[test]
2151    fn checkpoint_invocation_failure_message_is_js_form() {
2152        let err = crate::client::ExecutionClientError::new(
2153            crate::client::ExecutionClientErrorScope::Invocation,
2154            "throttled",
2155        );
2156        assert_eq!(
2157            checkpoint_invocation_failure_message(&err),
2158            "[Unrecoverable Invocation] Checkpoint failed: throttled"
2159        );
2160    }
2161    /// A concrete user error type for downcast tests.
2162    #[derive(Debug)]
2163    struct UserBoom {
2164        detail: &'static str,
2165    }
2166    impl fmt::Display for UserBoom {
2167        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2168            write!(f, "user boom: {}", self.detail)
2169        }
2170    }
2171    impl Error for UserBoom {}
2172
2173    fn step_error_with_user_source() -> OperationError {
2174        OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2175            StepErrorKind::ExecutionFailed,
2176            Some(Box::new(UserBoom { detail: "flaky" })),
2177        )))
2178    }
2179
2180    /// Walks the full `source()` chain and returns each layer's display.
2181    fn causal_chain(err: &dyn Error) -> Vec<String> {
2182        let mut chain = vec![err.to_string()];
2183        let mut current: &dyn Error = err;
2184        while let Some(next) = current.source() {
2185            chain.push(next.to_string());
2186            current = next;
2187        }
2188        chain
2189    }
2190
2191    // Acceptance: live-path downcast
2192
2193    #[test]
2194    fn live_failure_exposes_concrete_error_type_through_source_downcast() {
2195        let err = step_error_with_user_source();
2196        // Walk the chain until the caller's concrete type is found.
2197        let mut current: Option<&(dyn Error + 'static)> = err.source();
2198        let mut found = None;
2199        while let Some(e) = current {
2200            if let Some(user) = e.downcast_ref::<UserBoom>() {
2201                found = Some(user);
2202                break;
2203            }
2204            current = e.source();
2205        }
2206        let user = found.expect("caller's concrete error must be reachable via source()");
2207        assert_eq!(user.detail, "flaky");
2208    }
2209
2210    // Acceptance: Display frames, alternate chain, no repeats
2211
2212    #[test]
2213    fn display_writes_one_frame_and_alternate_walks_chain() {
2214        let err = step_error_with_user_source();
2215
2216        // `{}` yields one frame, no cause text.
2217        let plain = format!("{err}");
2218        assert_eq!(plain, "operation error: step");
2219
2220        // `{:#}` yields the chain.
2221        let alternate = format!("{err:#}");
2222        assert_eq!(
2223            alternate,
2224            "operation error: step: execution failed: user boom: flaky"
2225        );
2226    }
2227
2228    #[test]
2229    fn walking_source_does_not_repeat_text() {
2230        let err = step_error_with_user_source();
2231        let chain = causal_chain(&err);
2232        // OperationError -> StepError -> UserBoom.
2233        assert_eq!(
2234            chain,
2235            vec![
2236                "operation error: step".to_owned(),
2237                "execution failed".to_owned(),
2238                "user boom: flaky".to_owned(),
2239            ]
2240        );
2241        // No frame's text appears in another frame.
2242        for (i, frame) in chain.iter().enumerate() {
2243            for (j, other) in chain.iter().enumerate() {
2244                if i != j {
2245                    assert!(
2246                        !other.contains(frame.as_str()),
2247                        "frame {i} ({frame:?}) repeats inside frame {j} ({other:?})"
2248                    );
2249                }
2250            }
2251        }
2252    }
2253
2254    // Replay source
2255
2256    #[test]
2257    fn replayed_failure_carries_wire_fields() {
2258        let wire = WireError::new(Some("NotApproved"), Some("request was denied"))
2259            .with_error_data(Some("{\"code\":42}"));
2260        let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2261            StepErrorKind::ExecutionFailed,
2262            Some(ReplayedFailure::source_from(wire)),
2263        )));
2264        // kind() is meaningful after a replay.
2265        let OperationErrorKind::Step(step_err) = err.kind() else {
2266            unreachable!("constructed as a step error");
2267        };
2268        assert!(matches!(step_err.kind(), StepErrorKind::ExecutionFailed));
2269        // The synthetic source carries the wire error_type and message.
2270        let source = Error::source(step_err).expect("replay attaches a source");
2271        let replayed = source
2272            .downcast_ref::<ReplayedFailure>()
2273            .expect("replay source must be a ReplayedFailure");
2274        assert_eq!(replayed.error_type(), Some("NotApproved"));
2275        assert_eq!(replayed.error_message(), Some("request was denied"));
2276        assert_eq!(replayed.wire().error_data(), Some("{\"code\":42}"));
2277    }
2278
2279    // Wire derivation
2280
2281    #[test]
2282    fn wire_error_for_flattens_chain_once_and_uses_fallback_type() {
2283        let err = step_error_with_user_source();
2284        let wire = wire_error_for(&err, "Error");
2285        // The message is the flattened chain (single flattening site).
2286        assert_eq!(
2287            wire.error_message(),
2288            Some("operation error: step: execution failed: user boom: flaky")
2289        );
2290        // No structured identity in the chain: falls back to the kind's
2291        // wire name because the top error is an OperationError.
2292        assert_eq!(wire.error_type(), Some("StepError"));
2293        // No link carries frames, and the SDK captures none.
2294        assert_eq!(wire.stack_trace(), [] as [String; 0]);
2295        // No error_data anywhere in the chain: none synthesized.
2296        assert_eq!(wire.error_data(), None);
2297    }
2298
2299    #[test]
2300    fn wire_error_passes_through_recorded_frames() {
2301        let err = ContextualError::source_from(
2302            "ctx",
2303            ReplayedFailure::source_from(
2304                WireError::new(Some("T"), Some("m"))
2305                    .with_stack_trace(vec!["frame-a".into(), "frame-b".into()]),
2306            ),
2307        );
2308        let wire = wire_error_for(&*err, "Error");
2309        assert_eq!(
2310            wire.stack_trace(),
2311            &["frame-a".to_owned(), "frame-b".to_owned()]
2312        );
2313    }
2314
2315    #[test]
2316    fn typed_error_error_data_precedence() {
2317        fn boom() -> UserBoom {
2318            UserBoom { detail: "x" }
2319        }
2320        fn replayed(d: &str) -> Source {
2321            ReplayedFailure::source_from(
2322                WireError::new(Some("Inner"), Some("inner")).with_error_data(Some(d)),
2323            )
2324        }
2325        fn row1() -> Source {
2326            Box::new(TypedError::with_type("PaymentError", boom()).with_error_data("data-a"))
2327        }
2328        fn layered(layers: usize) -> Source {
2329            let mut inner = row1();
2330            for i in 0..layers {
2331                inner = ContextualError::source_from(format!("layer {i}"), inner);
2332            }
2333            inner
2334        }
2335
2336        let rows: Vec<(usize, Source, Option<&str>)> = vec![
2337            (1, row1(), Some("data-a")),
2338            (
2339                2,
2340                Box::new(TypedError::with_type("P", replayed("data-b")).with_error_data("data-a")),
2341                Some("data-a"),
2342            ),
2343            (
2344                3,
2345                Box::new(TypedError::with_type("P", replayed("data-b"))),
2346                Some("data-b"),
2347            ),
2348            (4, layered(1), Some("data-a")),
2349            (5, Box::new(TypedError::with_type("P", boom())), None),
2350            // The `TypedError` is link 10.
2351            (6, layered(9), Some("data-a")),
2352            // The `TypedError` is link 11, the last error the walk reads.
2353            (7, layered(10), Some("data-a")),
2354            // The `TypedError` is link 12, past the walk.
2355            (8, layered(11), None),
2356        ];
2357        for (row, err, expected) in &rows {
2358            let wire = wire_error_for(&**err, "Error");
2359            assert_eq!(wire.error_data(), *expected, "row {row}");
2360            if *row == 1 {
2361                assert_eq!(wire.error_type(), Some("PaymentError"));
2362                assert!(
2363                    !wire.error_message().unwrap_or_default().contains("data-a"),
2364                    "the data never appears in the message: {:?}",
2365                    wire.error_message()
2366                );
2367            }
2368        }
2369    }
2370
2371    #[test]
2372    fn step_error_constructors_build_strategy_inputs() {
2373        let failed = StepError::execution_failed("throttled");
2374        assert!(matches!(failed.kind(), StepErrorKind::ExecutionFailed));
2375        assert_eq!(
2376            failed.source().map(ToString::to_string).as_deref(),
2377            Some("throttled")
2378        );
2379
2380        let interrupted = StepError::interrupted();
2381        assert!(matches!(interrupted.kind(), StepErrorKind::Interrupted));
2382        assert_eq!(
2383            interrupted.source().map(ToString::to_string).as_deref(),
2384            Some(
2385                "The step execution process was initiated but failed to reach completion due to an interruption."
2386            )
2387        );
2388    }
2389
2390    #[test]
2391    fn wire_error_for_plain_user_error_uses_fallback() {
2392        let err = UserBoom { detail: "plain" };
2393        let wire = wire_error_for(&err, "Error");
2394        assert_eq!(wire.error_type(), Some("Error"));
2395        assert_eq!(wire.error_message(), Some("user boom: plain"));
2396    }
2397
2398    #[test]
2399    fn error_data_survives_child_boundary_via_cause_chain() {
2400        // An inner failure that carries wire data (e.g. an external
2401        // callback failure read back from the wire)...
2402        let inner_wire = WireError::new(Some("VendorError"), Some("denied"))
2403            .with_error_data(Some("opaque-payload"));
2404        let inner = OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
2405            CallbackErrorKind::ExternalFailure,
2406            Some(ReplayedFailure::source_from(inner_wire.clone())),
2407        )))
2408        .with_wire(inner_wire);
2409
2410        // ...escapes through a child-context boundary.
2411        let child_fn = ChildFnError::from(inner);
2412        let wire = child_fn.failure_wire();
2413
2414        // The opaque payload survives the boundary via the cause chain.
2415        assert_eq!(wire.error_data(), Some("opaque-payload"));
2416        // It is passed through, never parsed: the value is byte-identical.
2417        assert_eq!(wire.error_data(), Some("opaque-payload"));
2418    }
2419
2420    #[test]
2421    fn wire_error_re_records_replayed_failure_type() {
2422        // Re-recording a replayed failure directly preserves its type...
2423        let recorded = WireError::new(Some("MyDomainError"), Some("原因"));
2424        let replayed = ReplayedFailure::new(recorded.clone());
2425        let wire = wire_error_for(&replayed, "Error");
2426        assert_eq!(wire.error_type(), Some("MyDomainError"));
2427
2428        // ...and an operation error wrapping it re-records its attached
2429        // wire identity: the explicitly supplied type survives the
2430        // boundary instead of degrading to the kind's registry name.
2431        let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2432            StepErrorKind::ExecutionFailed,
2433            Some(ReplayedFailure::source_from(recorded.clone())),
2434        )))
2435        .with_wire(recorded);
2436        let wire = wire_error_for(&err, "Error");
2437        assert_eq!(wire.error_type(), Some("MyDomainError"));
2438        assert_eq!(
2439            err.wire().and_then(WireError::error_type),
2440            Some("MyDomainError")
2441        );
2442
2443        // An operation error with no attached wire and no typed identity
2444        // in its chain still falls back to the kind's registry name.
2445        let bare = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2446            StepErrorKind::ExecutionFailed,
2447            Some(Source::from("plain failure")),
2448        )));
2449        let wire = wire_error_for(&bare, "Error");
2450        assert_eq!(wire.error_type(), Some("StepError"));
2451    }
2452
2453    // Structural facts behind accessors
2454
2455    #[test]
2456    fn step_error_kind_accessor() {
2457        let err = StepError::new(StepErrorKind::ExecutionFailed, Some(Source::from("fail")));
2458        match err.kind() {
2459            StepErrorKind::ExecutionFailed => {}
2460            other => unreachable!("unexpected kind: {other:?}"),
2461        }
2462    }
2463
2464    #[test]
2465    fn operation_mismatch_accessors() {
2466        let details = OperationMismatch::new("abc123", "Step/Step", "Wait/Wait");
2467        assert_eq!(details.wire_id(), "abc123");
2468        assert_eq!(details.expected(), "Step/Step");
2469        assert_eq!(details.actual(), "Wait/Wait");
2470        let err = NonDeterministicExecutionError::from_kind(
2471            NonDeterministicExecutionErrorKind::OperationMismatch(details),
2472        );
2473        // The mismatch report is the error: no source to carry.
2474        assert!(Error::source(&err).is_none());
2475        assert!(err.to_string().contains("abc123"));
2476    }
2477
2478    // Combinators keep every loser
2479
2480    #[test]
2481    fn combinator_all_failed_keeps_every_loser() {
2482        let losers: Vec<Source> = vec![
2483            Box::new(UserBoom { detail: "a" }),
2484            Box::new(UserBoom { detail: "b" }),
2485        ];
2486        let err = CombinatorError::new(CombinatorErrorKind::AllFailed, losers);
2487        assert_eq!(err.failures().len(), 2);
2488        // source() returns the first loser.
2489        let first = Error::source(&err).expect("has a source");
2490        assert!(first.downcast_ref::<UserBoom>().is_some());
2491        // Every loser is reachable, as an error, not a string.
2492        let details: Vec<&str> = err
2493            .failures()
2494            .iter()
2495            .filter_map(|l| l.downcast_ref::<UserBoom>().map(|u| u.detail))
2496            .collect();
2497        assert_eq!(details, vec!["a", "b"]);
2498    }
2499
2500    #[test]
2501    fn combinator_join_failed_keeps_loser_and_index() {
2502        let err = CombinatorError::new(
2503            CombinatorErrorKind::JoinFailed(JoinFailed::new(2)),
2504            vec![Box::new(UserBoom { detail: "loser" })],
2505        );
2506        match err.kind() {
2507            CombinatorErrorKind::JoinFailed(details) => assert_eq!(details.failed_index(), 2),
2508            other => unreachable!("unexpected kind: {other:?}"),
2509        }
2510        let source = Error::source(&err).expect("loser preserved");
2511        assert!(source.downcast_ref::<UserBoom>().is_some());
2512    }
2513
2514    // ChildFnError carries the error
2515
2516    #[test]
2517    fn child_fn_error_preserves_operation_error() {
2518        let op = step_error_with_user_source();
2519        let child_err = ChildFnError::from(op);
2520        let source = Error::source(&child_err).expect("carries the error");
2521        assert!(source.downcast_ref::<OperationError>().is_some());
2522        // Frame stays clean; the chain is reachable via {:#}.
2523        assert_eq!(child_err.to_string(), "child function error");
2524        assert!(format!("{child_err:#}").contains("user boom: flaky"));
2525    }
2526
2527    // Display conventions across variants
2528
2529    #[test]
2530    fn every_operation_family_displays_its_frame() {
2531        let cases: Vec<(OperationError, &str)> = vec![
2532            (
2533                OperationError::from_kind(OperationErrorKind::Step(StepError::new(
2534                    StepErrorKind::ExecutionFailed,
2535                    None,
2536                ))),
2537                "step",
2538            ),
2539            (
2540                OperationError::from_kind(OperationErrorKind::Wait(WaitError::new(
2541                    WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("Failed")),
2542                    None,
2543                ))),
2544                "wait",
2545            ),
2546            (
2547                OperationError::from_kind(OperationErrorKind::Invoke(InvokeError::new(
2548                    InvokeErrorKind::FunctionFailed,
2549                    None,
2550                ))),
2551                "invoke",
2552            ),
2553            (
2554                OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
2555                    CallbackErrorKind::TimedOut,
2556                    None,
2557                ))),
2558                "callback",
2559            ),
2560            (
2561                OperationError::from_kind(OperationErrorKind::WaitForCondition(
2562                    WaitForConditionError::new(
2563                        WaitForConditionErrorKind::MaxChecksExceeded(MaxChecksExceeded::new(2)),
2564                        None,
2565                    ),
2566                )),
2567                "wait_for_condition",
2568            ),
2569            (
2570                OperationError::from_kind(OperationErrorKind::ChildContext(
2571                    ChildContextError::new(ChildContextErrorKind::ChildFailed, None),
2572                )),
2573                "child_context",
2574            ),
2575            (
2576                OperationError::from_kind(OperationErrorKind::Combinator(CombinatorError::new(
2577                    CombinatorErrorKind::Internal,
2578                    vec![Box::new(UserBoom { detail: "x" })],
2579                ))),
2580                "combinator",
2581            ),
2582            (
2583                OperationError::from_kind(OperationErrorKind::NonDeterministicExecution(
2584                    NonDeterministicExecutionError::from_kind(
2585                        NonDeterministicExecutionErrorKind::OperationMismatch(
2586                            OperationMismatch::new("abc123", "Step/Step", "Wait/Wait"),
2587                        ),
2588                    ),
2589                )),
2590                "non_deterministic_execution",
2591            ),
2592        ];
2593        for (err, family) in &cases {
2594            assert_eq!(format!("{err}"), format!("operation error: {family}"));
2595            // The chain never repeats text across frames.
2596            let chain = causal_chain(err);
2597            for (i, frame) in chain.iter().enumerate() {
2598                for (j, other) in chain.iter().enumerate() {
2599                    if i != j {
2600                        assert!(
2601                            !other.contains(frame.as_str()),
2602                            "family {family}: frame {i} repeats in frame {j}: {chain:?}"
2603                        );
2604                    }
2605                }
2606            }
2607        }
2608    }
2609
2610    #[test]
2611    fn callback_submitter_failed_displays_its_kind() {
2612        let err = CallbackError::new(
2613            CallbackErrorKind::SubmitterFailed,
2614            Some(Source::from("submission failed")),
2615        );
2616        assert_eq!(err.to_string(), "submitter failed");
2617        assert_eq!(format!("{err:#}"), "submitter failed: submission failed");
2618    }
2619
2620    #[test]
2621    fn callback_error_graded_split() {
2622        let timed_out = CallbackError::new(CallbackErrorKind::TimedOut, None);
2623        assert!(matches!(timed_out.kind(), CallbackErrorKind::TimedOut));
2624
2625        let heartbeat = CallbackError::new(CallbackErrorKind::HeartbeatTimedOut, None);
2626        assert!(matches!(
2627            heartbeat.kind(),
2628            CallbackErrorKind::HeartbeatTimedOut
2629        ));
2630
2631        let wire = WireError::new(Some("UserError"), Some("denied"));
2632        let external = CallbackError::new(
2633            CallbackErrorKind::ExternalFailure,
2634            Some(ReplayedFailure::source_from(wire)),
2635        );
2636        assert!(matches!(
2637            external.kind(),
2638            CallbackErrorKind::ExternalFailure
2639        ));
2640        // The wire fields the external caller reported are on the source.
2641        let source = Error::source(&external).expect("external carries wire source");
2642        let replayed = source.downcast_ref::<ReplayedFailure>().expect("replayed");
2643        assert_eq!(replayed.error_type(), Some("UserError"));
2644
2645        let internal = CallbackError::new(CallbackErrorKind::Internal, Some(Source::from("oops")));
2646        assert!(matches!(internal.kind(), CallbackErrorKind::Internal));
2647    }
2648
2649    #[test]
2650    fn operation_context_is_reachable() {
2651        let wire = WireError::new(Some("StepError"), Some("execution failed: boom"));
2652        let err = step_error_with_user_source()
2653            .with_operation("abc123", "FAILED")
2654            .with_wire(wire);
2655        assert_eq!(err.operation_id(), Some("abc123"));
2656        assert_eq!(err.status(), Some("FAILED"));
2657        assert_eq!(
2658            err.wire().and_then(WireError::error_type),
2659            Some("StepError")
2660        );
2661    }
2662
2663    #[test]
2664    fn typed_error_names_the_users_type_on_the_wire() {
2665        let err = TypedError::new(UserBoom { detail: "typed" });
2666        assert_eq!(err.error_type(), "UserBoom");
2667
2668        // The wire record derives the user's type from the wrapper...
2669        let wire = wire_error_for(&err, "Error");
2670        assert_eq!(wire.error_type(), Some("UserBoom"));
2671        assert_eq!(wire.error_message(), Some("user boom: typed"));
2672
2673        // ...including through intermediate carriers (a child boundary).
2674        let child =
2675            ChildFnError::new(Box::new(TypedError::new(UserBoom { detail: "deep" })) as Source);
2676        let wire = child.failure_wire();
2677        assert_eq!(wire.error_type(), Some("UserBoom"));
2678    }
2679
2680    #[test]
2681    fn typed_error_keeps_concrete_error_downcastable() {
2682        let err = TypedError::with_type("TransientError", UserBoom { detail: "x" });
2683        // The wrapped error is the next chain link: downcast reaches it.
2684        let source = Error::source(&err).expect("wraps the error");
2685        assert!(source.downcast_ref::<UserBoom>().is_some());
2686        // `Display` writes the type name alone, and the alternate form
2687        // names the type once, then the error's own frame.
2688        assert_eq!(err.to_string(), "TransientError");
2689        assert_eq!(format!("{err:#}"), "TransientError: user boom: x");
2690    }
2691
2692    #[test]
2693    fn short_type_name_strips_module_paths() {
2694        assert_eq!(
2695            short_type_name("my_crate::errors::TransientError"),
2696            "TransientError"
2697        );
2698        assert_eq!(short_type_name("TransientError"), "TransientError");
2699        assert_eq!(
2700            short_type_name("wrapper::Holder<inner::Thing, other::T>"),
2701            "Holder<Thing, T>"
2702        );
2703    }
2704
2705    #[test]
2706    fn contextual_error_adds_frame_without_flattening() {
2707        let source = ContextualError::source_from("checkpoint succeed", UserBoom { detail: "io" });
2708        assert_eq!(source.to_string(), "checkpoint succeed");
2709        let inner = source.source().expect("keeps cause");
2710        assert_eq!(inner.to_string(), "user boom: io");
2711    }
2712
2713    /// The recorded step of the `wire_message` tests: message `inner`.
2714    fn recorded_step() -> OperationError {
2715        recorded_step_error(WireError::new(Some("InnerType"), Some("inner")))
2716    }
2717
2718    /// The flattened chain of [`recorded_step`].
2719    const RECORDED_STEP_CHAIN: &str = "operation error: step: execution failed: inner";
2720
2721    #[test]
2722    fn recorded_step_flattens_to_its_frames() {
2723        assert_eq!(chain_string(&recorded_step()), RECORDED_STEP_CHAIN);
2724    }
2725
2726    #[test]
2727    fn wire_message_uses_the_first_record() {
2728        assert_eq!(wire_message(&recorded_step()), "inner");
2729
2730        let contextual = ContextualError::source_from(
2731            "ctx",
2732            ReplayedFailure::source_from(WireError::new(Some("T"), Some("m"))),
2733        );
2734        assert_eq!(wire_message(&*contextual), "m");
2735
2736        let outer_with_message =
2737            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
2738                ChildContextErrorKind::ChildFailed,
2739                Some(Box::new(recorded_step())),
2740            )))
2741            .with_wire(WireError::new(Some("OuterType"), Some("outer")));
2742        assert_eq!(wire_message(&outer_with_message), "outer");
2743
2744        // A record without a message stops the walk: the deeper record's
2745        // message is not used.
2746        let outer_without_message =
2747            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
2748                ChildContextErrorKind::ChildFailed,
2749                Some(Box::new(recorded_step())),
2750            )))
2751            .with_wire(WireError::new(Some("OuterType"), None::<String>));
2752        assert_eq!(
2753            wire_message(&outer_without_message),
2754            "operation error: child_context: child failed: operation error: step: execution failed: inner"
2755        );
2756
2757        let replayed_without_message =
2758            ReplayedFailure::new(WireError::new(Some("T"), None::<String>));
2759        assert_eq!(wire_message(&replayed_without_message), "T");
2760
2761        let empty = recorded_step_error(WireError::new(Some("T"), Some("")));
2762        assert_eq!(wire_message(&empty), "");
2763    }
2764
2765    /// A test wrapper of another crate's kind: not a propagation carrier.
2766    #[derive(Debug)]
2767    struct Wrapper(Source);
2768    impl fmt::Display for Wrapper {
2769        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2770            write!(f, "wrapper")
2771        }
2772    }
2773    impl Error for Wrapper {
2774        fn source(&self) -> Option<&(dyn Error + 'static)> {
2775            Some(&*self.0 as &(dyn Error + 'static))
2776        }
2777    }
2778
2779    #[test]
2780    #[expect(clippy::too_many_lines)] // reason: one row per carrier and per stopping case
2781    fn wire_message_walks_only_transparent_carriers() {
2782        let boxed = || -> Source { Box::new(recorded_step()) };
2783        let carriers: Vec<(&str, Box<dyn Error + 'static>)> = vec![
2784            (
2785                "OperationError without a record",
2786                Box::new(OperationError::from_kind(OperationErrorKind::ChildContext(
2787                    ChildContextError::new(ChildContextErrorKind::ChildFailed, Some(boxed())),
2788                ))),
2789            ),
2790            (
2791                "StepError",
2792                Box::new(StepError::new(
2793                    StepErrorKind::ExecutionFailed,
2794                    Some(boxed()),
2795                )),
2796            ),
2797            (
2798                "WaitError",
2799                Box::new(WaitError::new(
2800                    WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("FAILED")),
2801                    Some(boxed()),
2802                )),
2803            ),
2804            (
2805                "InvokeError",
2806                Box::new(InvokeError::new(
2807                    InvokeErrorKind::FunctionFailed,
2808                    Some(boxed()),
2809                )),
2810            ),
2811            (
2812                "CallbackError",
2813                Box::new(CallbackError::new(
2814                    CallbackErrorKind::SubmitterFailed,
2815                    Some(boxed()),
2816                )),
2817            ),
2818            (
2819                "WaitForConditionError",
2820                Box::new(WaitForConditionError::new(
2821                    WaitForConditionErrorKind::CheckFailed,
2822                    Some(boxed()),
2823                )),
2824            ),
2825            (
2826                "ChildContextError",
2827                Box::new(ChildContextError::new(
2828                    ChildContextErrorKind::ChildFailed,
2829                    Some(boxed()),
2830                )),
2831            ),
2832            (
2833                "CombinatorError",
2834                Box::new(CombinatorError::new(
2835                    CombinatorErrorKind::FirstSettledFailed,
2836                    vec![boxed()],
2837                )),
2838            ),
2839            ("ChildFnError", Box::new(ChildFnError::new(boxed()))),
2840            (
2841                "ContextualError",
2842                ContextualError::source_from("ctx", boxed()),
2843            ),
2844        ];
2845        for (name, carrier) in &carriers {
2846            assert_eq!(wire_message(&**carrier), "inner", "{name}");
2847        }
2848
2849        // A carrier without a source ends the walk.
2850        let sourceless = StepError::new(StepErrorKind::ExecutionFailed, None);
2851        assert_eq!(wire_message(&sourceless), "execution failed");
2852
2853        // A `TypedError` is a carrier too: the walk passes through it.
2854        let typed = TypedError::with_type("OuterType", recorded_step());
2855        assert_eq!(wire_message(&typed), "inner");
2856
2857        // Any other error stops the walk, and the message is the
2858        // flattened chain.
2859        let wrapper = Wrapper(boxed());
2860        assert_eq!(
2861            wire_message(&wrapper),
2862            format!("wrapper: {RECORDED_STEP_CHAIN}")
2863        );
2864        let client = crate::client::ExecutionClientError::with_source(
2865            crate::client::ExecutionClientErrorScope::Invocation,
2866            "checkpoint failed",
2867            recorded_step(),
2868        );
2869        assert_eq!(
2870            wire_message(&client),
2871            format!("durable: client: checkpoint failed: {RECORDED_STEP_CHAIN}")
2872        );
2873        let serde_error = match serde_json::from_str::<u32>("x") {
2874            Err(e) => e,
2875            Ok(v) => unreachable!("`x` is not a u32: {v}"),
2876        };
2877        let serialization = StepError::new(
2878            StepErrorKind::SerializationFailed,
2879            Some(Box::new(serde_error)),
2880        );
2881        assert_eq!(
2882            wire_message(&serialization),
2883            "serialization failed: expected value at line 1 column 1"
2884        );
2885
2886        // The walk examines at most `CHAIN_WALK_LIMIT` errors.
2887        let layered = |layers: usize| -> Source {
2888            (0..layers).fold(boxed(), |source, _| {
2889                ContextualError::source_from("ctx", source)
2890            })
2891        };
2892        assert_eq!(wire_message(&*layered(10)), "inner");
2893        let past_the_limit = layered(11);
2894        assert_eq!(
2895            wire_message(&*past_the_limit),
2896            chain_string(&*past_the_limit)
2897        );
2898        assert_ne!(wire_message(&*past_the_limit), "inner");
2899    }
2900
2901    /// A `TypedError` is one examined link of the recorded-message walk:
2902    /// nine contextual layers and a `TypedError` reach the record at the
2903    /// eleventh link, and ten layers and a `TypedError` do not.
2904    #[test]
2905    fn wire_message_counts_a_typed_error_as_one_link() {
2906        let typed_over = |layers: usize| -> Source {
2907            let typed: Source = Box::new(TypedError::with_type("T", recorded_step()));
2908            (0..layers).fold(typed, |source, _| {
2909                ContextualError::source_from("ctx", source)
2910            })
2911        };
2912        assert_eq!(wire_message(&*typed_over(9)), "inner");
2913        assert_eq!(
2914            wire_message(&*typed_over(10)),
2915            "ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: \
2916             operation error: step: execution failed: inner"
2917        );
2918    }
2919
2920    /// A `TypedError` around a record without a message: the walk stops
2921    /// at that record and the message is the original error's flattened
2922    /// chain, without the type name.
2923    #[test]
2924    fn wire_message_typed_record_without_message_flattens_the_chain() {
2925        let typed = TypedError::with_type(
2926            "Typed",
2927            recorded_step_error(WireError::new(Some("RecordType"), None::<String>)),
2928        );
2929        assert_eq!(
2930            wire_message(&typed),
2931            "operation error: step: execution failed: RecordType"
2932        );
2933        let empty = TypedError::with_type(
2934            "Typed",
2935            recorded_step_error(WireError::new(Some("RecordType"), Some(""))),
2936        );
2937        assert_eq!(wire_message(&empty), "");
2938    }
2939
2940    /// A test error with one frame and an optional source.
2941    #[derive(Debug)]
2942    struct Frame(&'static str, Option<Source>);
2943    impl fmt::Display for Frame {
2944        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2945            write!(f, "{}", self.0)
2946        }
2947    }
2948    impl Error for Frame {
2949        fn source(&self) -> Option<&(dyn Error + 'static)> {
2950            self.1.as_deref().map(|s| s as &(dyn Error + 'static))
2951        }
2952    }
2953
2954    #[derive(Debug)]
2955    struct PaymentDeclined;
2956    impl fmt::Display for PaymentDeclined {
2957        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2958            write!(f, "payment declined")
2959        }
2960    }
2961    impl Error for PaymentDeclined {}
2962
2963    /// Each row of the issue's table: the recorded type and message of a
2964    /// `TypedError` chain, and its flattened chain without type names.
2965    #[test]
2966    fn chain_string_omits_typed_error_frames() {
2967        let failed_step = || recorded_step_error(WireError::new(Some("StepType"), Some("boom")));
2968        let rows: Vec<(Box<dyn Error + 'static>, &str, &str, &str)> = vec![
2969            (
2970                Box::new(TypedError::with_type("PaymentError", "declined")),
2971                "PaymentError",
2972                "declined",
2973                "declined",
2974            ),
2975            (
2976                Box::new(TypedError::new(PaymentDeclined)),
2977                "PaymentDeclined",
2978                "payment declined",
2979                "payment declined",
2980            ),
2981            (
2982                Box::new(TypedError::with_type("PaymentError", failed_step())),
2983                "PaymentError",
2984                "boom",
2985                "operation error: step: execution failed: boom",
2986            ),
2987            (
2988                Box::new(Frame(
2989                    "charging",
2990                    Some(Box::new(TypedError::with_type("PaymentError", "declined"))),
2991                )),
2992                "PaymentError",
2993                "charging: declined",
2994                "charging: declined",
2995            ),
2996            (
2997                Box::new(TypedError::with_type("A", TypedError::with_type("B", "x"))),
2998                "A",
2999                "x",
3000                "x",
3001            ),
3002            (
3003                Box::new(TypedError::with_type(
3004                    "Typed",
3005                    Frame("a", Some(Box::new(Frame("b", None)))),
3006                )),
3007                "Typed",
3008                "a: b",
3009                "a: b",
3010            ),
3011        ];
3012        for (err, error_type, message, chain) in &rows {
3013            let wire = wire_error_for(&**err, "Error");
3014            assert_eq!(wire.error_type(), Some(*error_type), "{err:#}");
3015            assert_eq!(wire.error_message(), Some(*message), "{err:#}");
3016            assert_eq!(chain_string(&**err), *chain, "{err:#}");
3017        }
3018    }
3019
3020    #[test]
3021    fn wire_message_preserves_non_message_fields() {
3022        let inner_wire = || {
3023            WireError::new(Some("InnerType"), Some("inner"))
3024                .with_error_data(Some("inner-data"))
3025                .with_stack_trace(vec!["inner-frame".to_owned()])
3026        };
3027        let child =
3028            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
3029                ChildContextErrorKind::ChildFailed,
3030                Some(Box::new(recorded_step_error(inner_wire()))),
3031            )));
3032        let wire = wire_error_for(&child, "Error");
3033        assert_eq!(wire.error_type(), Some("ChildContextError"));
3034        assert_eq!(wire.error_message(), Some("inner"));
3035        assert_eq!(wire.error_data(), Some("inner-data"));
3036        assert_eq!(wire.stack_trace(), ["inner-frame"]);
3037
3038        let contextual =
3039            ContextualError::source_from("serialize", recorded_step_error(inner_wire()));
3040        let wire = serialization_failure_wire(&*contextual);
3041        assert_eq!(wire.error_type(), Some("SerializationError"));
3042        assert_eq!(wire.error_message(), Some("inner"));
3043        assert_eq!(wire.error_data(), Some("inner-data"));
3044        assert_eq!(wire.stack_trace(), ["inner-frame"]);
3045
3046        // A `TypedError` names the type, and the record below it still
3047        // supplies the message, data and stack.
3048        let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()));
3049        let wire = wire_error_for(&typed, "Error");
3050        assert_eq!(wire.error_type(), Some("Typed"));
3051        assert_eq!(wire.error_message(), Some("inner"));
3052        assert_eq!(wire.error_data(), Some("inner-data"));
3053        assert_eq!(wire.stack_trace(), ["inner-frame"]);
3054
3055        // Its own data wins over the record's.
3056        let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()))
3057            .with_error_data("typed-data");
3058        let wire = wire_error_for(&typed, "Error");
3059        assert_eq!(wire.error_type(), Some("Typed"));
3060        assert_eq!(wire.error_message(), Some("inner"));
3061        assert_eq!(wire.error_data(), Some("typed-data"));
3062        assert_eq!(wire.stack_trace(), ["inner-frame"]);
3063    }
3064}