Skip to main content

tenferro_runtime/
error.rs

1//! Error types for the tenferro runtime crate.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use tenferro_runtime::error::{Error, ErrorPhase};
7//!
8//! let err = Error::invalid_argument(
9//!     "einsum",
10//!     ErrorPhase::GraphBuild,
11//!     "subscripts",
12//!     "bad label",
13//! );
14//! assert!(err.to_string().contains("bad label"));
15//! ```
16
17use std::error::Error as StdError;
18use std::sync::atomic::{AtomicUsize, Ordering};
19
20use tenferro_ops::{dim_expr::DimExprEvalError, ShapeRelation, SymDimConversionError};
21use tenferro_tensor::{DType, ErrorKind, ValidationError, ValidationKind};
22
23use crate::runtime::{PrepareError, UnsupportedReason};
24
25static NEXT_CONTEXT_ID: AtomicUsize = AtomicUsize::new(1);
26
27/// Boxed source used when a runtime registry or compiler subsystem crosses
28/// the runtime error boundary with a concrete error owned by another crate.
29pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
30
31/// Borrowed, stable classification of a runtime preparation or execution failure.
32///
33/// The view retains references to the original error payloads and performs no
34/// message formatting or allocation. Match a wildcard because this enum is
35/// non-exhaustive.
36///
37/// # Examples
38///
39/// ```rust
40/// use tenferro_runtime::{Error, ErrorPhase, RuntimeFailureReasonRef};
41///
42/// let error = Error::unsupported("compare", ErrorPhase::Compile, "not available");
43/// assert!(matches!(
44///     error.reason(),
45///     RuntimeFailureReasonRef::UnsupportedOperation { operation: "compare" }
46/// ));
47/// ```
48#[derive(Clone, Copy, Debug, PartialEq)]
49#[non_exhaustive]
50pub enum RuntimeFailureReasonRef<'a> {
51    /// An operation belongs to an extension family with no installed module.
52    MissingExtension { family: &'a str },
53    /// No prepared engine accepts an input at its physical placement.
54    NoInputIngress {
55        input_index: usize,
56        placement: &'a tenferro_tensor::Placement,
57    },
58    /// A provider or tensor backend does not implement an operation.
59    UnsupportedOperation { operation: &'a str },
60    /// A failure has no stable structured classification.
61    Other,
62}
63
64/// Phase at which a runtime failure was discovered.
65///
66/// The phase is independent from [`ErrorKind`]: the same validation fact can
67/// be discovered while building a graph, compiling it for concrete inputs,
68/// or executing a compiled program.
69///
70/// # Examples
71///
72/// ```rust
73/// use tenferro_runtime::ErrorPhase;
74///
75/// assert_ne!(ErrorPhase::GraphBuild, ErrorPhase::Execution);
76/// ```
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub enum ErrorPhase {
80    /// A caller-controlled graph construction check failed.
81    GraphBuild,
82    /// Shape inference or lowering discovered the failure.
83    Compile,
84    /// Input binding or backend execution discovered the failure.
85    Execution,
86}
87
88/// Typed reason that a symbolic shape constraint could not be evaluated.
89///
90/// # Examples
91///
92/// ```rust
93/// use tenferro_runtime::ShapeConstraintEvalError;
94///
95/// let cause = ShapeConstraintEvalError::MissingInput {
96///     input_idx: 2,
97///     input_count: 1,
98/// };
99/// assert_eq!(
100///     cause.to_string(),
101///     "shape expression references input 2, but only 1 inputs were provided"
102/// );
103/// ```
104#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
105pub enum ShapeConstraintEvalError {
106    /// An expression referenced an input shape that was not supplied.
107    #[error(
108        "shape expression references input {input_idx}, but only {input_count} inputs were provided"
109    )]
110    MissingInput {
111        /// Referenced input index.
112        input_idx: usize,
113        /// Number of supplied input shapes.
114        input_count: usize,
115    },
116    /// An expression referenced an axis outside the selected input's rank.
117    #[error("shape expression references input {input_idx} axis {axis}, but its rank is {rank}")]
118    AxisOutOfBounds {
119        /// Referenced input index.
120        input_idx: usize,
121        /// Referenced axis.
122        axis: usize,
123        /// Rank of the selected input.
124        rank: usize,
125    },
126    /// Checked dimension arithmetic overflowed `usize`.
127    #[error("shape expression arithmetic overflowed")]
128    Overflow,
129    /// Checked dimension subtraction underflowed `usize`.
130    #[error("shape expression subtraction underflowed")]
131    Underflow,
132    /// A floor-division divisor evaluated to zero.
133    #[error("shape expression divided by zero")]
134    DivisionByZero,
135}
136
137impl From<DimExprEvalError> for ShapeConstraintEvalError {
138    fn from(error: DimExprEvalError) -> Self {
139        match error {
140            DimExprEvalError::InputOutOfBounds {
141                input_idx,
142                input_count,
143            } => Self::MissingInput {
144                input_idx,
145                input_count,
146            },
147            DimExprEvalError::AxisOutOfBounds {
148                input_idx,
149                axis,
150                rank,
151            } => Self::AxisOutOfBounds {
152                input_idx,
153                axis,
154                rank,
155            },
156            DimExprEvalError::AddOverflow { .. } | DimExprEvalError::MulOverflow { .. } => {
157                Self::Overflow
158            }
159            DimExprEvalError::SubUnderflow { .. } => Self::Underflow,
160            DimExprEvalError::FloorDivByZero { .. } => Self::DivisionByZero,
161        }
162    }
163}
164
165/// Errors produced by einsum, eval, and other tenferro operations.
166///
167/// # Examples
168///
169/// ```rust
170/// use tenferro_runtime::error::{Error, ErrorPhase};
171///
172/// let err = Error::invalid_argument(
173///     "einsum",
174///     ErrorPhase::GraphBuild,
175///     "subscripts",
176///     "rank mismatch",
177/// );
178/// ```
179#[derive(Debug, thiserror::Error)]
180pub enum Error {
181    /// A shared tensor validation fact, annotated with the runtime phase.
182    #[error("{op} ({phase:?}): {source}")]
183    Validation {
184        /// Public operation name.
185        op: &'static str,
186        /// Phase that discovered the validation fact.
187        phase: ErrorPhase,
188        /// Machine-readable validation payload.
189        #[source]
190        source: ValidationError,
191    },
192
193    /// A required input tensor is missing from the inputs map.
194    #[error("missing input: {0}")]
195    MissingInput(String),
196
197    /// Reverse-mode gradient requires a scalar output.
198    #[error("grad requires a scalar output, got shape {shape:?}")]
199    NonScalarGrad { shape: Vec<usize> },
200
201    /// The operation is known not to support the requested input or
202    /// configuration at the phase where it was requested.
203    #[error("{op} ({phase:?}) is unsupported: {message}")]
204    Unsupported {
205        /// Operation that does not provide the requested behavior.
206        op: &'static str,
207        /// Phase that established the unsupported combination.
208        phase: ErrorPhase,
209        /// Human-readable unsupported-operation detail.
210        message: String,
211    },
212
213    /// Runtime tensor execution failed in the backend layer.
214    ///
215    /// The display text is the wrapped error's text. Unlike a transparent
216    /// wrapper, [`std::error::Error::source`] returns the wrapped
217    /// `tenferro_tensor::Error` itself, so a `source()` walk reaches it and,
218    /// through it, a family error such as `tenferro_linalg::Error` (#2552).
219    #[error("{0}")]
220    TensorRuntime(#[from] tenferro_tensor::Error),
221
222    /// A typed extension-domain error crossed a runtime registry boundary.
223    #[error("extension {family} ({phase:?}) failed for {op}: {source}")]
224    Extension {
225        /// Operation that discovered the extension failure.
226        op: &'static str,
227        /// Phase that discovered the extension failure.
228        phase: ErrorPhase,
229        /// Stable extension family identifier.
230        family: &'static str,
231        /// Coarse classification supplied by the extension owner.
232        kind: ErrorKind,
233        /// Original extension-domain source.
234        #[source]
235        source: BoxError,
236    },
237
238    /// Executor, cache, registry, or device state is unavailable or invalid.
239    #[error("{op} ({phase:?}): runtime state failure: {message}")]
240    RuntimeState {
241        /// Operation whose state was unavailable.
242        op: &'static str,
243        /// Phase that discovered the invalid state.
244        phase: ErrorPhase,
245        /// Human-readable state detail.
246        message: String,
247    },
248
249    /// A runtime-state failure retaining a typed source.
250    #[error("{op} ({phase:?}): runtime state failure: {source}")]
251    RuntimeStateSource {
252        /// Operation whose state was unavailable.
253        op: &'static str,
254        /// Phase that discovered the invalid state.
255        phase: ErrorPhase,
256        /// Typed state source.
257        #[source]
258        source: BoxError,
259    },
260
261    /// A primary error with a second typed error retained as suppressed
262    /// metadata.
263    ///
264    /// The standard error source chain follows `primary`. The suppressed
265    /// error is intentionally exposed through [`Error::suppressed`] because
266    /// [`StdError::source`](std::error::Error::source) can represent only one
267    /// source without losing the primary error's semantics.
268    #[error("primary error: {primary}; suppressed error: {suppressed}")]
269    WithSuppressed {
270        /// The operation's primary failure and the standard error-chain source.
271        #[source]
272        primary: Box<Error>,
273        /// A typed secondary failure retained for diagnostics and recovery.
274        suppressed: Box<Error>,
275    },
276
277    /// A runtime event-domain provenance or admission contract failed.
278    #[error("event-domain operation failed: {source}")]
279    EventDomain {
280        /// Structured event-domain failure with expected/actual provenance.
281        #[from]
282        #[source]
283        source: crate::runtime::EventDomainError,
284    },
285
286    /// A `TracedTensor` supplied as a compiled-graph input binding is not a
287    /// placeholder (has attached data).
288    #[error(
289        "binding #{binding_index} is not a placeholder; \
290         only tensors built via input_concrete_shape / input_symbolic_shape \
291         can be bound"
292    )]
293    UnexpectedBinding { binding_index: usize },
294
295    /// A placeholder appearing in the graph has no binding supplied.
296    #[error("placeholder {input_key} has no runtime input binding")]
297    UnboundPlaceholder { input_key: String },
298
299    /// The number of ordered tensors supplied to a compiled graph is invalid.
300    #[error("compiled graph expects {expected} ordered inputs, got {actual}")]
301    GraphInputCountMismatch { expected: usize, actual: usize },
302
303    /// The same placeholder was bound more than once in the `bindings` slice.
304    #[error("placeholder {input_key} was bound more than once")]
305    DuplicateBinding { input_key: String },
306
307    /// A binding tensor's dtype does not match the placeholder's dtype.
308    #[error("binding dtype mismatch for placeholder: expected {expected:?}, got {actual:?}")]
309    PlaceholderDtypeMismatch { expected: DType, actual: DType },
310
311    /// A binding tensor's shape does not match an `input_concrete_shape`
312    /// placeholder's fixed shape.
313    #[error(
314        "binding shape mismatch for concrete-shape placeholder: \
315         expected {expected:?}, got {actual:?}"
316    )]
317    PlaceholderShapeMismatch {
318        expected: Vec<usize>,
319        actual: Vec<usize>,
320    },
321
322    /// A binding tensor dimension exceeds a semantic input's declared bound.
323    #[error("binding dimension {axis} exceeds semantic input upper bound {bound}: got {actual}")]
324    PlaceholderShapeBoundExceeded {
325        /// Axis whose runtime extent exceeded the bound.
326        axis: usize,
327        /// Evaluated upper bound.
328        bound: usize,
329        /// Runtime extent.
330        actual: usize,
331    },
332
333    /// A binding tensor's rank does not match an `input_symbolic_shape`
334    /// placeholder's declared rank.
335    #[error(
336        "binding rank mismatch for symbolic-shape placeholder: \
337         expected rank {expected}, got rank {actual}"
338    )]
339    PlaceholderRankMismatch { expected: usize, actual: usize },
340
341    /// Operation attempted to mix tensors from different eager contexts.
342    #[error(
343        "tensors belong to different eager AD contexts ({lhs} vs {rhs}); \
344         detach into the target context before combining them"
345    )]
346    ContextMismatch { lhs: ContextId, rhs: ContextId },
347
348    /// An AD transform requires a primitive or extension rule that is not
349    /// registered for the requested operation.
350    #[error("unsupported {transform} AD rule for {op}")]
351    UnsupportedAdRule {
352        /// AD transform that requested the rule, such as `grad` or `backward`.
353        transform: &'static str,
354        /// Operation or extension family identifier that has no applicable rule.
355        op: String,
356    },
357
358    /// A typed AD rule source that crossed an external message-only callback.
359    #[error("{transform} AD rule failed: {source}")]
360    AdRuleSource {
361        /// AD transform that requested the rule.
362        transform: &'static str,
363        /// Original typed source from the AD rule context.
364        #[source]
365        source: BoxError,
366    },
367
368    /// A symbolic extension shape equality evaluated to unequal dimensions.
369    #[error(
370        "extension family {family:?} shape constraint at instruction {instruction_index:?} failed: {lhs_expr} ({lhs_value}) {relation:?} {rhs_expr} ({rhs_value})"
371    )]
372    ShapeConstraintViolation {
373        /// Stable extension family identifier.
374        family: &'static str,
375        /// Stable compiled instruction provenance, when assigned.
376        instruction_index: Option<usize>,
377        /// Shape relation that failed.
378        relation: ShapeRelation,
379        /// Normalized left-hand expression.
380        lhs_expr: String,
381        /// Normalized right-hand expression.
382        rhs_expr: String,
383        /// Concrete left-hand value.
384        lhs_value: usize,
385        /// Concrete right-hand value.
386        rhs_value: usize,
387    },
388
389    /// A symbolic extension shape expression could not be evaluated safely.
390    #[error(
391        "extension family {family:?} shape constraint at instruction {instruction_index:?} could not evaluate {expression} for {relation:?}: {cause}"
392    )]
393    ShapeConstraintEvaluation {
394        /// Stable extension family identifier.
395        family: &'static str,
396        /// Stable compiled instruction provenance, when assigned.
397        instruction_index: Option<usize>,
398        /// Shape relation whose expression failed.
399        relation: ShapeRelation,
400        /// Normalized expression that failed.
401        expression: String,
402        /// Typed evaluation failure.
403        #[source]
404        cause: ShapeConstraintEvalError,
405    },
406
407    /// A symbolic dimension could not be converted into the graph's local
408    /// dimension-expression vocabulary.
409    #[error("{op} ({phase:?}): symbolic shape conversion failed: {source}")]
410    SymbolicShapeConversion {
411        /// Operation that requested the symbolic shape conversion.
412        op: &'static str,
413        /// Phase that discovered the invalid symbolic reference.
414        phase: ErrorPhase,
415        /// Typed symbolic-dimension conversion failure.
416        #[source]
417        source: SymDimConversionError,
418    },
419
420    /// A runtime dimension expression could not be evaluated for concrete
421    /// input shapes.
422    #[error("runtime shape expression {expression} could not evaluate: {cause}")]
423    ShapeExpressionEvaluation {
424        /// Expression that failed during execution.
425        expression: String,
426        /// Typed evaluation failure.
427        #[source]
428        cause: ShapeConstraintEvalError,
429    },
430
431    /// An unexpected internal error.
432    #[error("internal error: {0}")]
433    Internal(String),
434}
435
436impl Error {
437    /// Wrap a shared validation payload with its operation and discovery
438    /// phase.
439    ///
440    /// # Errors
441    ///
442    /// This constructor does not fail; callers receive the returned
443    /// [`Error`] value and can inspect its [`Error::kind`] and
444    /// [`Error::phase`].
445    ///
446    /// # Examples
447    ///
448    /// ```rust
449    /// use tenferro_runtime::{Error, ErrorPhase};
450    /// use tenferro_tensor::{ErrorKind, ShapeMismatch, ValidationKind};
451    ///
452    /// let error = Error::validation(
453    ///     "reshape",
454    ///     ErrorPhase::GraphBuild,
455    ///     ShapeMismatch::ReshapeElementCount { from: 2, to: 3 }.into(),
456    /// );
457    /// assert_eq!(
458    ///     error.kind(),
459    ///     ErrorKind::Validation(ValidationKind::ShapeMismatch)
460    /// );
461    /// assert_eq!(error.phase(), Some(ErrorPhase::GraphBuild));
462    /// ```
463    pub fn validation(op: &'static str, phase: ErrorPhase, source: ValidationError) -> Self {
464        Self::Validation { op, phase, source }
465    }
466
467    /// Construct a validation error for a caller-controlled argument whose
468    /// failure does not have a more specific shared payload.
469    ///
470    /// # Examples
471    ///
472    /// ```rust
473    /// use tenferro_runtime::{Error, ErrorPhase};
474    ///
475    /// let error = Error::invalid_argument(
476    ///     "broadcast_in_dim",
477    ///     ErrorPhase::GraphBuild,
478    ///     "dims",
479    ///     "dimension mapping has the wrong length",
480    /// );
481    /// assert!(matches!(error, Error::Validation { .. }));
482    /// ```
483    pub fn invalid_argument(
484        op: &'static str,
485        phase: ErrorPhase,
486        argument: &'static str,
487        message: impl Into<String>,
488    ) -> Self {
489        Self::validation(
490            op,
491            phase,
492            ValidationError::InvalidArgument {
493                argument,
494                message: message.into(),
495            },
496        )
497    }
498
499    /// Construct a dtype-mismatch validation error using the runtime dtype
500    /// vocabulary.
501    ///
502    /// # Examples
503    ///
504    /// ```rust
505    /// use tenferro_runtime::{DType, Error, ErrorPhase};
506    /// use tenferro_tensor::{ErrorKind, ValidationKind};
507    ///
508    /// let error = Error::dtype_mismatch(
509    ///     "add",
510    ///     ErrorPhase::GraphBuild,
511    ///     DType::F32,
512    ///     DType::F64,
513    /// );
514    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::DTypeMismatch));
515    /// ```
516    pub fn dtype_mismatch(
517        op: &'static str,
518        phase: ErrorPhase,
519        expected: DType,
520        actual: DType,
521    ) -> Self {
522        Self::validation(
523            op,
524            phase,
525            ValidationError::DTypeMismatch { expected, actual },
526        )
527    }
528
529    /// Preserve a typed extension-domain source at the runtime boundary.
530    ///
531    /// # Examples
532    ///
533    /// ```rust
534    /// use std::error::Error as _;
535    /// use tenferro_runtime::{Error, ErrorPhase};
536    /// use tenferro_tensor::ErrorKind;
537    ///
538    /// let source = std::io::Error::new(std::io::ErrorKind::Other, "extension failed");
539    /// let error = Error::extension(
540    ///     "einsum",
541    ///     ErrorPhase::GraphBuild,
542    ///     "example.extension.v1",
543    ///     ErrorKind::RuntimeState,
544    ///     source,
545    /// );
546    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
547    /// assert!(error.source().is_some());
548    /// ```
549    pub fn extension<E>(
550        op: &'static str,
551        phase: ErrorPhase,
552        family: &'static str,
553        kind: ErrorKind,
554        source: E,
555    ) -> Self
556    where
557        E: StdError + Send + Sync + 'static,
558    {
559        Self::Extension {
560            op,
561            phase,
562            family,
563            kind,
564            source: Box::new(source),
565        }
566    }
567
568    /// Construct a runtime-state failure for an unavailable or invalid
569    /// executor, cache, registry, or device state.
570    ///
571    /// # Examples
572    ///
573    /// ```rust
574    /// use tenferro_runtime::{Error, ErrorPhase};
575    /// use tenferro_tensor::ErrorKind;
576    ///
577    /// let error = Error::runtime_state(
578    ///     "executor",
579    ///     ErrorPhase::Execution,
580    ///     "the executor is not initialized",
581    /// );
582    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
583    /// ```
584    pub fn runtime_state(op: &'static str, phase: ErrorPhase, message: impl Into<String>) -> Self {
585        Self::RuntimeState {
586            op,
587            phase,
588            message: message.into(),
589        }
590    }
591
592    /// Preserve a typed source for an unavailable or invalid runtime state.
593    ///
594    /// # Examples
595    ///
596    /// ```rust
597    /// use std::error::Error as _;
598    /// use tenferro_runtime::{Error, ErrorPhase};
599    /// use tenferro_tensor::ErrorKind;
600    ///
601    /// let error = Error::runtime_state_source(
602    ///     "metadata",
603    ///     ErrorPhase::Compile,
604    ///     std::io::Error::other("registry lock poisoned"),
605    /// );
606    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
607    /// assert!(error.source().is_some());
608    /// ```
609    pub fn runtime_state_source<E>(op: &'static str, phase: ErrorPhase, source: E) -> Self
610    where
611        E: StdError + Send + Sync + 'static,
612    {
613        Self::RuntimeStateSource {
614            op,
615            phase,
616            source: Box::new(source),
617        }
618    }
619
620    /// Retain a typed secondary error while preserving the primary error's
621    /// classification and standard source chain.
622    ///
623    /// # Examples
624    ///
625    /// ```rust
626    /// use tenferro_runtime::{Error, ErrorPhase};
627    ///
628    /// let error = Error::with_suppressed(
629    ///     Error::unsupported("backend", ErrorPhase::Execution, "primary"),
630    ///     Error::runtime_state("runtime", ErrorPhase::Execution, "suppressed"),
631    /// );
632    /// assert!(error.primary().is_some());
633    /// assert!(error.suppressed().is_some());
634    /// ```
635    pub fn with_suppressed(primary: Self, suppressed: Self) -> Self {
636        Self::WithSuppressed {
637            primary: Box::new(primary),
638            suppressed: Box::new(suppressed),
639        }
640    }
641
642    /// Return the primary error when this value is a suppressed-error
643    /// aggregate.
644    ///
645    /// # Examples
646    ///
647    /// ```rust
648    /// use tenferro_runtime::{Error, ErrorPhase};
649    ///
650    /// let error = Error::with_suppressed(
651    ///     Error::unsupported("backend", ErrorPhase::Execution, "primary"),
652    ///     Error::runtime_state("runtime", ErrorPhase::Execution, "suppressed"),
653    /// );
654    /// assert_eq!(error.primary().unwrap().phase(), Some(ErrorPhase::Execution));
655    /// ```
656    pub fn primary(&self) -> Option<&Self> {
657        match self {
658            Self::WithSuppressed { primary, .. } => Some(primary),
659            _ => None,
660        }
661    }
662
663    /// Return the typed suppressed error when this value is an aggregate.
664    ///
665    /// # Examples
666    ///
667    /// ```rust
668    /// use tenferro_runtime::{Error, ErrorPhase};
669    ///
670    /// let error = Error::with_suppressed(
671    ///     Error::unsupported("backend", ErrorPhase::Execution, "primary"),
672    ///     Error::runtime_state("runtime", ErrorPhase::Execution, "suppressed"),
673    /// );
674    /// assert_eq!(error.suppressed().unwrap().phase(), Some(ErrorPhase::Execution));
675    /// ```
676    pub fn suppressed(&self) -> Option<&Self> {
677        match self {
678            Self::WithSuppressed { suppressed, .. } => Some(suppressed),
679            _ => None,
680        }
681    }
682
683    /// Preserve a typed source returned by an AD rule through a callback
684    /// protocol that can carry only a rendered message.
685    ///
686    /// # Examples
687    ///
688    /// ```rust
689    /// use std::error::Error as _;
690    /// use tenferro_runtime::Error;
691    ///
692    /// let error = Error::ad_rule_source(
693    ///     "jvp",
694    ///     std::io::Error::other("shape metadata missing"),
695    /// );
696    /// assert!(error.source().is_some());
697    /// ```
698    pub fn ad_rule_source<E>(transform: &'static str, source: E) -> Self
699    where
700        E: StdError + Send + Sync + 'static,
701    {
702        Self::AdRuleSource {
703            transform,
704            source: Box::new(source),
705        }
706    }
707
708    /// Construct an operation-level unsupported error with an explicit
709    /// discovery phase.
710    ///
711    /// # Examples
712    ///
713    /// ```rust
714    /// use tenferro_runtime::{Error, ErrorPhase};
715    /// use tenferro_tensor::ErrorKind;
716    ///
717    /// let error = Error::unsupported(
718    ///     "compare",
719    ///     ErrorPhase::Compile,
720    ///     "complex values have no total order",
721    /// );
722    /// assert_eq!(error.kind(), ErrorKind::Unsupported);
723    /// assert_eq!(error.phase(), Some(ErrorPhase::Compile));
724    /// ```
725    pub fn unsupported(op: &'static str, phase: ErrorPhase, message: impl Into<String>) -> Self {
726        Self::Unsupported {
727            op,
728            phase,
729            message: message.into(),
730        }
731    }
732
733    /// Return a borrowed stable reason for this runtime failure.
734    ///
735    /// Classification checks the primary error of [`Error::WithSuppressed`],
736    /// then walks the standard source chain. It never parses display text and
737    /// does not allocate; the original error, kind, phase, display, and source
738    /// chain remain unchanged.
739    ///
740    /// # Examples
741    ///
742    /// ```rust
743    /// use tenferro_runtime::{Error, ErrorPhase, RuntimeFailureReasonRef};
744    ///
745    /// let error = Error::unsupported("compare", ErrorPhase::Compile, "not available");
746    /// assert_eq!(
747    ///     error.reason(),
748    ///     RuntimeFailureReasonRef::UnsupportedOperation { operation: "compare" }
749    /// );
750    /// assert_eq!(Error::Internal("validation".into()).reason(), RuntimeFailureReasonRef::Other);
751    /// ```
752    pub fn reason(&self) -> RuntimeFailureReasonRef<'_> {
753        if let Self::WithSuppressed { primary, .. } = self {
754            return primary.reason();
755        }
756        if let Some(reason) = direct_reason(self) {
757            return reason;
758        }
759
760        let mut source = StdError::source(self);
761        while let Some(error) = source {
762            if let Some(reason) = error.downcast_ref::<Error>().and_then(direct_reason) {
763                return reason;
764            }
765            if let Some(reason) = prepare_reason(error) {
766                return reason;
767            }
768            source = StdError::source(error);
769        }
770        RuntimeFailureReasonRef::Other
771    }
772
773    /// Return the stable coarse classification of this runtime failure.
774    ///
775    /// # Examples
776    ///
777    /// ```rust
778    /// use tenferro_runtime::{Error, ErrorPhase};
779    /// use tenferro_tensor::{ErrorKind, ValidationError, ValidationKind};
780    ///
781    /// let error = Error::validation(
782    ///     "transpose",
783    ///     ErrorPhase::GraphBuild,
784    ///     ValidationError::AxisOutOfBounds { axis: 2, rank: 2 },
785    /// );
786    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::AxisOutOfBounds));
787    /// ```
788    pub fn kind(&self) -> ErrorKind {
789        match self {
790            Self::Validation { source, .. } => ErrorKind::Validation(source.kind()),
791            Self::MissingInput(_)
792            | Self::UnexpectedBinding { .. }
793            | Self::UnboundPlaceholder { .. }
794            | Self::DuplicateBinding { .. }
795            | Self::ContextMismatch { .. } => ErrorKind::RuntimeState,
796            Self::NonScalarGrad { .. } => ErrorKind::Validation(ValidationKind::InvalidArgument),
797            Self::GraphInputCountMismatch { .. } => {
798                ErrorKind::Validation(ValidationKind::InvalidArgument)
799            }
800            Self::Unsupported { .. } | Self::UnsupportedAdRule { .. } => ErrorKind::Unsupported,
801            Self::AdRuleSource { .. } => ErrorKind::Validation(ValidationKind::InvalidArgument),
802            Self::TensorRuntime(error) => error.kind(),
803            Self::Extension { kind, .. } => *kind,
804            Self::RuntimeState { .. }
805            | Self::RuntimeStateSource { .. }
806            | Self::EventDomain { .. } => ErrorKind::RuntimeState,
807            Self::WithSuppressed { primary, .. } => primary.kind(),
808            Self::PlaceholderDtypeMismatch { .. } => {
809                ErrorKind::Validation(ValidationKind::DTypeMismatch)
810            }
811            Self::PlaceholderShapeMismatch { .. } | Self::PlaceholderShapeBoundExceeded { .. } => {
812                ErrorKind::Validation(ValidationKind::ShapeMismatch)
813            }
814            Self::PlaceholderRankMismatch { .. } => {
815                ErrorKind::Validation(ValidationKind::RankMismatch)
816            }
817            Self::ShapeConstraintViolation { .. } => {
818                ErrorKind::Validation(ValidationKind::ShapeMismatch)
819            }
820            Self::ShapeConstraintEvaluation { .. } => {
821                ErrorKind::Validation(ValidationKind::InvalidArgument)
822            }
823            Self::SymbolicShapeConversion { .. } => {
824                ErrorKind::Validation(ValidationKind::InvalidArgument)
825            }
826            Self::ShapeExpressionEvaluation { .. } => {
827                ErrorKind::Validation(ValidationKind::InvalidArgument)
828            }
829            Self::Internal(_) => ErrorKind::Internal,
830        }
831    }
832
833    /// Return the discovery phase when this error has one.
834    ///
835    /// # Examples
836    ///
837    /// ```rust
838    /// use tenferro_runtime::{Error, ErrorPhase};
839    /// use tenferro_tensor::ValidationError;
840    ///
841    /// let error = Error::validation(
842    ///     "reshape",
843    ///     ErrorPhase::Compile,
844    ///     ValidationError::RankMismatch { expected: 2, actual: 1 },
845    /// );
846    /// assert_eq!(error.phase(), Some(ErrorPhase::Compile));
847    /// ```
848    pub fn phase(&self) -> Option<ErrorPhase> {
849        match self {
850            Self::Validation { phase, .. } => Some(*phase),
851            Self::TensorRuntime(_) => Some(ErrorPhase::Execution),
852            Self::Unsupported { phase, .. } => Some(*phase),
853            Self::Extension { phase, .. } => Some(*phase),
854            Self::RuntimeState { phase, .. } | Self::RuntimeStateSource { phase, .. } => {
855                Some(*phase)
856            }
857            Self::WithSuppressed { primary, .. } => primary.phase(),
858            Self::AdRuleSource { .. } => Some(ErrorPhase::GraphBuild),
859            Self::PlaceholderDtypeMismatch { .. }
860            | Self::PlaceholderShapeMismatch { .. }
861            | Self::PlaceholderRankMismatch { .. }
862            | Self::GraphInputCountMismatch { .. }
863            | Self::UnexpectedBinding { .. }
864            | Self::UnboundPlaceholder { .. }
865            | Self::DuplicateBinding { .. } => Some(ErrorPhase::Execution),
866            Self::EventDomain { .. } => Some(ErrorPhase::Execution),
867            Self::SymbolicShapeConversion { phase, .. } => Some(*phase),
868            Self::ShapeExpressionEvaluation { .. } => Some(ErrorPhase::Execution),
869            _ => None,
870        }
871    }
872}
873
874fn direct_reason(error: &Error) -> Option<RuntimeFailureReasonRef<'_>> {
875    match error {
876        Error::Unsupported { op, .. } => {
877            Some(RuntimeFailureReasonRef::UnsupportedOperation { operation: op })
878        }
879        Error::UnsupportedAdRule { op, .. } => {
880            Some(RuntimeFailureReasonRef::UnsupportedOperation { operation: op })
881        }
882        Error::TensorRuntime(error) => tensor_reason(error),
883        Error::Extension { family, kind, .. } if *kind == ErrorKind::Unsupported => {
884            Some(RuntimeFailureReasonRef::UnsupportedOperation { operation: family })
885        }
886        _ => None,
887    }
888}
889
890fn tensor_reason(error: &tenferro_tensor::Error) -> Option<RuntimeFailureReasonRef<'_>> {
891    match error {
892        tenferro_tensor::Error::Unsupported { op, .. }
893        | tenferro_tensor::Error::UnsupportedDType { op, .. }
894        | tenferro_tensor::Error::UnsupportedDTypeConversion { op, .. } => {
895            Some(RuntimeFailureReasonRef::UnsupportedOperation { operation: op })
896        }
897        _ => None,
898    }
899}
900
901fn prepare_reason<'a>(error: &'a (dyn StdError + 'static)) -> Option<RuntimeFailureReasonRef<'a>> {
902    let prepare = error.downcast_ref::<PrepareError>()?;
903    Some(match prepare {
904        PrepareError::MissingExtension { family_id } => {
905            RuntimeFailureReasonRef::MissingExtension { family: family_id }
906        }
907        PrepareError::NoInputIngress {
908            input_index,
909            placement,
910        } => RuntimeFailureReasonRef::NoInputIngress {
911            input_index: *input_index,
912            placement,
913        },
914        PrepareError::Unsupported {
915            reason: UnsupportedReason::Operation { operation },
916        } => RuntimeFailureReasonRef::UnsupportedOperation { operation },
917        _ => return None,
918    })
919}
920
921/// Opaque identifier for an eager AD runtime, used in [`Error::ContextMismatch`].
922#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
923pub struct ContextId(usize);
924
925impl ContextId {
926    /// Generate a fresh opaque runtime context identifier.
927    ///
928    /// Runtime implementations use this when constructing a new execution
929    /// context. The value is intentionally opaque and is only useful in error
930    /// reporting and equality checks.
931    pub fn fresh() -> Self {
932        let id = NEXT_CONTEXT_ID.fetch_add(1, Ordering::Relaxed);
933        Self(id)
934    }
935}
936
937impl std::fmt::Display for ContextId {
938    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
939        write!(f, "ctx@{:x}", self.0)
940    }
941}
942
943/// Result type alias for tenferro operations.
944pub type Result<T> = std::result::Result<T, Error>;
945
946#[cfg(test)]
947mod tests;