Skip to main content

tenferro_tensor/
error.rs

1//! Runtime error types for tensor execution.
2//!
3//! # Examples
4//!
5//! ```rust
6//! let error = tenferro_tensor::Error::shape_mismatch("add", [2], [3]);
7//! assert!(matches!(
8//!     error,
9//!     tenferro_tensor::Error::Validation { op: "add", .. }
10//! ));
11//! ```
12
13use std::error::Error as StdError;
14
15use tenferro_tensor_core::{ErrorKind, ValidationError};
16
17/// Boxed source used for backend and extension failures whose concrete type is
18/// owned by another crate or a vendor API.
19pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
20
21/// Runtime failures produced by tensor execution backends and helpers.
22///
23/// Validation failures retain the shared tensor-core payload as a typed source.
24/// Backend and extension failures retain opaque typed sources when one exists;
25/// text-only vendor failures use [`Error::BackendFailure`].
26///
27/// # Examples
28///
29/// ```rust
30/// let error = tenferro_tensor::Error::rank_mismatch("reshape", 2, 1);
31/// assert!(matches!(
32///     error,
33///     tenferro_tensor::Error::Validation { op: "reshape", .. }
34/// ));
35/// ```
36#[derive(Debug, thiserror::Error)]
37#[non_exhaustive]
38pub enum Error {
39    #[error("{op}: {source}")]
40    Validation {
41        op: &'static str,
42        #[source]
43        source: ValidationError,
44    },
45    #[error("{op}: unsupported dtype conversion from {from:?} to {to:?}: {message}")]
46    UnsupportedDTypeConversion {
47        op: &'static str,
48        from: crate::DType,
49        to: crate::DType,
50        message: String,
51    },
52    #[error("{op}: unsupported dtype {dtype:?}: {message}")]
53    UnsupportedDType {
54        op: &'static str,
55        dtype: crate::DType,
56        message: String,
57    },
58    #[error("{op}: unsupported operation: {message}")]
59    Unsupported { op: &'static str, message: String },
60    #[error("{op}: backend failure: {message}")]
61    BackendFailure { op: &'static str, message: String },
62    #[error("{op}: backend failure: {source}")]
63    BackendSource {
64        op: &'static str,
65        #[source]
66        source: BoxError,
67    },
68    #[error("{op}: I/O failure: {source}")]
69    IoSource {
70        op: &'static str,
71        #[source]
72        source: BoxError,
73    },
74    #[error("{op}: runtime state failure: {message}")]
75    RuntimeState { op: &'static str, message: String },
76    #[error("{op}: runtime state failure: {source}")]
77    RuntimeStateSource {
78        op: &'static str,
79        #[source]
80        source: BoxError,
81    },
82    #[error("{op}: host access failed: {source}")]
83    HostAccess {
84        op: &'static str,
85        #[source]
86        source: crate::HostAccessError,
87    },
88    #[error("{op}: extension {family} failed: {source}")]
89    Extension {
90        op: &'static str,
91        family: &'static str,
92        kind: ErrorKind,
93        #[source]
94        source: BoxError,
95    },
96    #[error("missing runtime value for slot {slot}")]
97    MissingValue { slot: usize },
98    #[error("internal tensor error: {0}")]
99    Internal(String),
100}
101
102/// Owns the original tensor when a consuming representation reinterpretation
103/// cannot publish its checked descriptor.
104///
105/// Reinterpretation never falls back to an allocation or a copy.  Call
106/// [`Self::into_owner`] to recover the unchanged input and [`Self::error`] to
107/// inspect the typed failure.
108///
109/// # Examples
110///
111/// ```
112/// use tenferro_tensor::TypedTensor;
113///
114/// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
115/// let Err(failure) = tensor.into_complex() else { return Ok(()); };
116/// assert!(!failure.error().to_string().is_empty());
117/// # Ok::<(), tenferro_tensor::Error>(())
118/// ```
119#[derive(Debug)]
120pub struct ReinterpretError<T> {
121    owner: Box<T>,
122    error: Error,
123}
124
125impl<T> ReinterpretError<T> {
126    pub(crate) fn new(owner: T, error: Error) -> Self {
127        Self {
128            owner: Box::new(owner),
129            error,
130        }
131    }
132
133    /// Recover the unchanged original owner.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use tenferro_tensor::TypedTensor;
139    ///
140    /// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
141    /// let Err(failure) = tensor.into_complex() else { return Ok(()); };
142    /// let _owner = failure.into_owner();
143    /// # Ok::<(), tenferro_tensor::Error>(())
144    /// ```
145    pub fn into_owner(self) -> T {
146        *self.owner
147    }
148
149    /// Borrow the typed failure without consuming the owner.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use tenferro_tensor::TypedTensor;
155    ///
156    /// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
157    /// let Err(failure) = tensor.into_complex() else { return Ok(()); };
158    /// assert!(!failure.error().to_string().is_empty());
159    /// # Ok::<(), tenferro_tensor::Error>(())
160    /// ```
161    pub fn error(&self) -> &Error {
162        &self.error
163    }
164
165    /// Consume the failure and return the retained owner with its typed cause.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use tenferro_tensor::TypedTensor;
171    ///
172    /// let tensor = TypedTensor::<f32>::from_vec_col_major(vec![1], vec![1.0])?;
173    /// let Err(failure) = tensor.into_complex() else { return Ok(()); };
174    /// let (owner, error) = failure.into_parts();
175    /// assert!(!error.to_string().is_empty());
176    /// assert_eq!(owner.shape(), &[1]);
177    /// # Ok::<(), tenferro_tensor::Error>(())
178    /// ```
179    #[must_use]
180    pub fn into_parts(self) -> (T, Error) {
181        (*self.owner, self.error)
182    }
183}
184
185impl<T: std::fmt::Debug> std::fmt::Display for ReinterpretError<T> {
186    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        write!(formatter, "tensor reinterpretation failed: {}", self.error)
188    }
189}
190
191impl<T: std::fmt::Debug + 'static> std::error::Error for ReinterpretError<T> {}
192
193impl Error {
194    /// Construct an incompatible-shapes validation error.
195    ///
196    /// # Examples
197    ///
198    /// ```rust
199    /// use tenferro_tensor::Error;
200    ///
201    /// let error = Error::shape_mismatch("add", [2, 3], [2, 4]);
202    /// assert!(matches!(error, Error::Validation { .. }));
203    /// ```
204    pub fn shape_mismatch(
205        op: &'static str,
206        lhs: impl Into<Vec<usize>>,
207        rhs: impl Into<Vec<usize>>,
208    ) -> Self {
209        Self::validation(
210            op,
211            tenferro_tensor_core::ShapeMismatch::IncompatibleShapes {
212                lhs: lhs.into().into_iter().collect(),
213                rhs: rhs.into().into_iter().collect(),
214            }
215            .into(),
216        )
217    }
218
219    /// Construct a rank-mismatch validation error.
220    ///
221    /// # Examples
222    ///
223    /// ```rust
224    /// use tenferro_tensor::Error;
225    ///
226    /// let error = Error::rank_mismatch("transpose", 2, 3);
227    /// assert!(matches!(error, Error::Validation { .. }));
228    /// ```
229    pub fn rank_mismatch(op: &'static str, expected: usize, actual: usize) -> Self {
230        Self::validation(op, ValidationError::RankMismatch { expected, actual })
231    }
232
233    /// Construct an axis-out-of-bounds validation error.
234    ///
235    /// # Examples
236    ///
237    /// ```rust
238    /// use tenferro_tensor::Error;
239    ///
240    /// let error = Error::axis_out_of_bounds("sum", 2, 2);
241    /// assert!(matches!(error, Error::Validation { .. }));
242    /// ```
243    pub fn axis_out_of_bounds(op: &'static str, axis: usize, rank: usize) -> Self {
244        Self::validation(
245            op,
246            ValidationError::AxisOutOfBounds {
247                axis: isize::try_from(axis).unwrap_or(isize::MAX),
248                rank,
249            },
250        )
251    }
252
253    /// Construct a duplicate-axis validation error.
254    ///
255    /// # Examples
256    ///
257    /// ```rust
258    /// use tenferro_tensor::Error;
259    ///
260    /// let error = Error::duplicate_axis("transpose", 1, "permutation");
261    /// assert!(matches!(error, Error::Validation { .. }));
262    /// ```
263    pub fn duplicate_axis(op: &'static str, axis: usize, role: &'static str) -> Self {
264        Self::validation(op, ValidationError::DuplicateAxis { axis, role })
265    }
266
267    /// Construct a dtype-mismatch validation error.
268    ///
269    /// # Examples
270    ///
271    /// ```rust
272    /// use tenferro_tensor::{DType, Error};
273    ///
274    /// let error = Error::dtype_mismatch("add", DType::F32, DType::F64);
275    /// assert!(matches!(error, Error::Validation { .. }));
276    /// ```
277    pub fn dtype_mismatch(op: &'static str, expected: crate::DType, actual: crate::DType) -> Self {
278        Self::validation(op, ValidationError::DTypeMismatch { expected, actual })
279    }
280
281    /// Wrap shared tensor validation with the operation that requested it.
282    ///
283    /// # Examples
284    ///
285    /// ```rust
286    /// use tenferro_tensor::{Error, ValidationError};
287    ///
288    /// let error = Error::validation(
289    ///     "transpose",
290    ///     ValidationError::AxisOutOfBounds { axis: 2, rank: 2 },
291    /// );
292    /// assert!(matches!(error, Error::Validation { op: "transpose", .. }));
293    /// ```
294    pub fn validation(op: &'static str, source: ValidationError) -> Self {
295        Self::Validation { op, source }
296    }
297
298    /// Construct a structured invalid-argument validation error.
299    ///
300    /// # Examples
301    ///
302    /// ```rust
303    /// use tenferro_tensor::{Error, ErrorKind, ValidationKind};
304    ///
305    /// let error = Error::invalid_argument("slice", "step", "must be non-zero");
306    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::InvalidArgument));
307    /// ```
308    pub fn invalid_argument(
309        op: &'static str,
310        argument: &'static str,
311        message: impl Into<String>,
312    ) -> Self {
313        Self::validation(
314            op,
315            ValidationError::InvalidArgument {
316                argument,
317                message: message.into(),
318            },
319        )
320    }
321
322    /// Construct an unsupported dtype conversion error.
323    ///
324    /// # Examples
325    ///
326    /// ```rust
327    /// let error = tenferro_tensor::Error::unsupported_dtype_conversion(
328    ///     "convert",
329    ///     tenferro_tensor::DType::F64,
330    ///     tenferro_tensor::DType::I32,
331    ///     "lossy conversion is disabled",
332    /// );
333    /// assert!(matches!(
334    ///     error,
335    ///     tenferro_tensor::Error::UnsupportedDTypeConversion { .. }
336    /// ));
337    /// ```
338    pub fn unsupported_dtype_conversion(
339        op: &'static str,
340        from: crate::DType,
341        to: crate::DType,
342        message: impl Into<String>,
343    ) -> Self {
344        Self::UnsupportedDTypeConversion {
345            op,
346            from,
347            to,
348            message: message.into(),
349        }
350    }
351
352    /// Construct an operation-level unsupported-dtype error.
353    ///
354    /// This is for an operation that cannot run for the supplied dtype. It is
355    /// deliberately distinct from [`Error::unsupported_dtype_conversion`],
356    /// which is reserved for an actual from-dtype to to-dtype conversion.
357    ///
358    /// # Examples
359    ///
360    /// ```rust
361    /// let error = tenferro_tensor::Error::unsupported_dtype(
362    ///     "exp",
363    ///     tenferro_tensor::DType::I64,
364    ///     "integer exponentials are not implemented",
365    /// );
366    /// assert!(matches!(
367    ///     error,
368    ///     tenferro_tensor::Error::UnsupportedDType {
369    ///         op: "exp",
370    ///         dtype: tenferro_tensor::DType::I64,
371    ///         ..
372    ///     }
373    /// ));
374    /// ```
375    pub fn unsupported_dtype(
376        op: &'static str,
377        dtype: crate::DType,
378        message: impl Into<String>,
379    ) -> Self {
380        Self::UnsupportedDType {
381            op,
382            dtype,
383            message: message.into(),
384        }
385    }
386
387    /// Construct a structured unsupported-operation error.
388    ///
389    /// Use this for an operation or execution surface that is not implemented
390    /// by the selected backend. Dtype conversion failures use
391    /// [`Error::unsupported_dtype_conversion`] instead, and operation-specific
392    /// typed reasons should use [`Error::extension`] with `ErrorKind::Unsupported`.
393    ///
394    /// # Examples
395    ///
396    /// ```rust
397    /// let error = tenferro_tensor::Error::unsupported(
398    ///     "full_piv_lu",
399    ///     "backend has no implementation",
400    /// );
401    /// assert!(matches!(
402    ///     error,
403    ///     tenferro_tensor::Error::Unsupported { op: "full_piv_lu", .. }
404    /// ));
405    /// ```
406    pub fn unsupported(op: &'static str, message: impl Into<String>) -> Self {
407        Self::Unsupported {
408            op,
409            message: message.into(),
410        }
411    }
412
413    /// Construct a text-only backend failure.
414    ///
415    /// Use [`Error::backend_source`] when a typed source is available.
416    ///
417    /// # Examples
418    ///
419    /// ```rust
420    /// let error = tenferro_tensor::Error::backend_failure(
421    ///     "matmul",
422    ///     "backend rejected launch",
423    /// );
424    /// assert!(matches!(
425    ///     error,
426    ///     tenferro_tensor::Error::BackendFailure { op: "matmul", .. }
427    /// ));
428    /// ```
429    pub fn backend_failure(op: &'static str, message: impl Into<String>) -> Self {
430        Self::BackendFailure {
431            op,
432            message: message.into(),
433        }
434    }
435
436    /// Construct a backend failure while preserving its typed source.
437    ///
438    /// # Examples
439    ///
440    /// ```rust
441    /// let error = tenferro_tensor::Error::backend_source(
442    ///     "load",
443    ///     std::io::Error::other("read failed"),
444    /// );
445    /// assert!(std::error::Error::source(&error).is_some());
446    /// ```
447    pub fn backend_source<E>(op: &'static str, source: E) -> Self
448    where
449        E: StdError + Send + Sync + 'static,
450    {
451        Self::BackendSource {
452            op,
453            source: Box::new(source),
454        }
455    }
456
457    /// Construct an I/O failure while preserving its typed source.
458    ///
459    /// I/O errors are intentionally separate from backend failures: callers
460    /// can classify them as [`ErrorKind::Io`] without parsing a message.
461    ///
462    /// # Examples
463    ///
464    /// ```rust
465    /// use tenferro_tensor::{Error, ErrorKind};
466    ///
467    /// let error = Error::io_source("load", std::io::Error::other("read failed"));
468    /// assert_eq!(error.kind(), ErrorKind::Io);
469    /// assert!(std::error::Error::source(&error).is_some());
470    /// ```
471    pub fn io_source<E>(op: &'static str, source: E) -> Self
472    where
473        E: StdError + Send + Sync + 'static,
474    {
475        Self::IoSource {
476            op,
477            source: Box::new(source),
478        }
479    }
480
481    /// Construct a runtime-state failure when no typed source exists.
482    ///
483    /// Use this for missing, uninitialized, or invalid execution state. It is
484    /// distinct from [`Error::backend_failure`], which is reserved for
485    /// vendor/backend status text.
486    ///
487    /// # Examples
488    ///
489    /// ```rust
490    /// use tenferro_tensor::{Error, ErrorKind};
491    ///
492    /// let error = Error::runtime_state("execute", "backend session is not initialized");
493    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
494    /// ```
495    pub fn runtime_state(op: &'static str, message: impl Into<String>) -> Self {
496        Self::RuntimeState {
497            op,
498            message: message.into(),
499        }
500    }
501
502    /// Construct a runtime-state failure while preserving a typed source.
503    ///
504    /// # Examples
505    ///
506    /// ```rust
507    /// use tenferro_tensor::{Error, ErrorKind};
508    ///
509    /// let error = Error::runtime_state_source(
510    ///     "execute",
511    ///     std::io::Error::other("executor lock poisoned"),
512    /// );
513    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
514    /// assert!(std::error::Error::source(&error).is_some());
515    /// ```
516    pub fn runtime_state_source<E>(op: &'static str, source: E) -> Self
517    where
518        E: StdError + Send + Sync + 'static,
519    {
520        Self::RuntimeStateSource {
521            op,
522            source: Box::new(source),
523        }
524    }
525
526    /// Construct an extension failure while preserving its typed source and
527    /// coarse classification.
528    ///
529    /// # Examples
530    ///
531    /// ```rust
532    /// use std::error::Error as _;
533    /// use tenferro_tensor::{Error, ErrorKind};
534    ///
535    /// let error = Error::extension(
536    ///     "einsum",
537    ///     "einsum",
538    ///     ErrorKind::Internal,
539    ///     std::io::Error::other("planner failed"),
540    /// );
541    /// assert!(error.source().is_some());
542    /// ```
543    pub fn extension<E>(op: &'static str, family: &'static str, kind: ErrorKind, source: E) -> Self
544    where
545        E: StdError + Send + Sync + 'static,
546    {
547        Self::Extension {
548            op,
549            family,
550            kind,
551            source: Box::new(source),
552        }
553    }
554
555    /// Preserve a typed guarded-host-access failure.
556    ///
557    /// # Examples
558    ///
559    /// ```rust
560    /// use tenferro_tensor::{Error, HostAccessError};
561    ///
562    /// let error = Error::host_access(
563    ///     "map",
564    ///     HostAccessError::Unsupported { backend: "opaque" },
565    /// );
566    /// assert!(matches!(error, Error::HostAccess { .. }));
567    /// ```
568    pub fn host_access(op: &'static str, source: crate::HostAccessError) -> Self {
569        Self::HostAccess { op, source }
570    }
571
572    /// Return the stable coarse classification for this tensor failure.
573    ///
574    /// # Examples
575    ///
576    /// ```rust
577    /// use tenferro_tensor::{Error, ErrorKind, ValidationError, ValidationKind};
578    /// use tenferro_tensor::core::DType;
579    ///
580    /// let error = Error::validation(
581    ///     "add",
582    ///     ValidationError::DTypeMismatch {
583    ///         expected: DType::F32,
584    ///         actual: DType::F64,
585    ///     },
586    /// );
587    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::DTypeMismatch));
588    /// ```
589    pub fn kind(&self) -> ErrorKind {
590        match self {
591            Self::Validation { source, .. } => ErrorKind::Validation(source.kind()),
592            Self::UnsupportedDTypeConversion { .. }
593            | Self::UnsupportedDType { .. }
594            | Self::Unsupported { .. } => ErrorKind::Unsupported,
595            Self::BackendFailure { .. } | Self::BackendSource { .. } => ErrorKind::BackendFailure,
596            Self::IoSource { .. } => ErrorKind::Io,
597            Self::RuntimeState { .. }
598            | Self::RuntimeStateSource { .. }
599            | Self::HostAccess { .. } => ErrorKind::RuntimeState,
600            Self::Extension { kind, .. } => *kind,
601            Self::MissingValue { .. } => ErrorKind::RuntimeState,
602            Self::Internal(_) => ErrorKind::Internal,
603        }
604    }
605}
606
607/// Result type alias for runtime tensor operations.
608pub type Result<T> = std::result::Result<T, Error>;