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    pub(crate) fn into_parts(self) -> (T, Error) {
166        (*self.owner, self.error)
167    }
168}
169
170impl<T: std::fmt::Debug> std::fmt::Display for ReinterpretError<T> {
171    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        write!(formatter, "tensor reinterpretation failed: {}", self.error)
173    }
174}
175
176impl<T: std::fmt::Debug + 'static> std::error::Error for ReinterpretError<T> {}
177
178impl Error {
179    /// Construct an incompatible-shapes validation error.
180    ///
181    /// # Examples
182    ///
183    /// ```rust
184    /// use tenferro_tensor::Error;
185    ///
186    /// let error = Error::shape_mismatch("add", [2, 3], [2, 4]);
187    /// assert!(matches!(error, Error::Validation { .. }));
188    /// ```
189    pub fn shape_mismatch(
190        op: &'static str,
191        lhs: impl Into<Vec<usize>>,
192        rhs: impl Into<Vec<usize>>,
193    ) -> Self {
194        Self::validation(
195            op,
196            tenferro_tensor_core::ShapeMismatch::IncompatibleShapes {
197                lhs: tenferro_tensor_core::ShapeVec::from_vec(lhs.into()),
198                rhs: tenferro_tensor_core::ShapeVec::from_vec(rhs.into()),
199            }
200            .into(),
201        )
202    }
203
204    /// Construct a rank-mismatch validation error.
205    ///
206    /// # Examples
207    ///
208    /// ```rust
209    /// use tenferro_tensor::Error;
210    ///
211    /// let error = Error::rank_mismatch("transpose", 2, 3);
212    /// assert!(matches!(error, Error::Validation { .. }));
213    /// ```
214    pub fn rank_mismatch(op: &'static str, expected: usize, actual: usize) -> Self {
215        Self::validation(op, ValidationError::RankMismatch { expected, actual })
216    }
217
218    /// Construct an axis-out-of-bounds validation error.
219    ///
220    /// # Examples
221    ///
222    /// ```rust
223    /// use tenferro_tensor::Error;
224    ///
225    /// let error = Error::axis_out_of_bounds("sum", 2, 2);
226    /// assert!(matches!(error, Error::Validation { .. }));
227    /// ```
228    pub fn axis_out_of_bounds(op: &'static str, axis: usize, rank: usize) -> Self {
229        Self::validation(op, ValidationError::AxisOutOfBounds { axis, rank })
230    }
231
232    /// Construct a duplicate-axis validation error.
233    ///
234    /// # Examples
235    ///
236    /// ```rust
237    /// use tenferro_tensor::Error;
238    ///
239    /// let error = Error::duplicate_axis("transpose", 1, "permutation");
240    /// assert!(matches!(error, Error::Validation { .. }));
241    /// ```
242    pub fn duplicate_axis(op: &'static str, axis: usize, role: &'static str) -> Self {
243        Self::validation(op, ValidationError::DuplicateAxis { axis, role })
244    }
245
246    /// Construct a dtype-mismatch validation error.
247    ///
248    /// # Examples
249    ///
250    /// ```rust
251    /// use tenferro_tensor::{DType, Error};
252    ///
253    /// let error = Error::dtype_mismatch("add", DType::F32, DType::F64);
254    /// assert!(matches!(error, Error::Validation { .. }));
255    /// ```
256    pub fn dtype_mismatch(op: &'static str, expected: crate::DType, actual: crate::DType) -> Self {
257        Self::validation(op, ValidationError::DTypeMismatch { expected, actual })
258    }
259
260    /// Wrap shared tensor validation with the operation that requested it.
261    ///
262    /// # Examples
263    ///
264    /// ```rust
265    /// use tenferro_tensor::{Error, ValidationError};
266    ///
267    /// let error = Error::validation(
268    ///     "transpose",
269    ///     ValidationError::AxisOutOfBounds { axis: 2, rank: 2 },
270    /// );
271    /// assert!(matches!(error, Error::Validation { op: "transpose", .. }));
272    /// ```
273    pub fn validation(op: &'static str, source: ValidationError) -> Self {
274        Self::Validation { op, source }
275    }
276
277    /// Construct a structured invalid-argument validation error.
278    ///
279    /// # Examples
280    ///
281    /// ```rust
282    /// use tenferro_tensor::{Error, ErrorKind, ValidationKind};
283    ///
284    /// let error = Error::invalid_argument("slice", "step", "must be non-zero");
285    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::InvalidArgument));
286    /// ```
287    pub fn invalid_argument(
288        op: &'static str,
289        argument: &'static str,
290        message: impl Into<String>,
291    ) -> Self {
292        Self::validation(
293            op,
294            ValidationError::InvalidArgument {
295                argument,
296                message: message.into(),
297            },
298        )
299    }
300
301    /// Construct an unsupported dtype conversion error.
302    ///
303    /// # Examples
304    ///
305    /// ```rust
306    /// let error = tenferro_tensor::Error::unsupported_dtype_conversion(
307    ///     "convert",
308    ///     tenferro_tensor::DType::F64,
309    ///     tenferro_tensor::DType::I32,
310    ///     "lossy conversion is disabled",
311    /// );
312    /// assert!(matches!(
313    ///     error,
314    ///     tenferro_tensor::Error::UnsupportedDTypeConversion { .. }
315    /// ));
316    /// ```
317    pub fn unsupported_dtype_conversion(
318        op: &'static str,
319        from: crate::DType,
320        to: crate::DType,
321        message: impl Into<String>,
322    ) -> Self {
323        Self::UnsupportedDTypeConversion {
324            op,
325            from,
326            to,
327            message: message.into(),
328        }
329    }
330
331    /// Construct an operation-level unsupported-dtype error.
332    ///
333    /// This is for an operation that cannot run for the supplied dtype. It is
334    /// deliberately distinct from [`Error::unsupported_dtype_conversion`],
335    /// which is reserved for an actual from-dtype to to-dtype conversion.
336    ///
337    /// # Examples
338    ///
339    /// ```rust
340    /// let error = tenferro_tensor::Error::unsupported_dtype(
341    ///     "exp",
342    ///     tenferro_tensor::DType::I64,
343    ///     "integer exponentials are not implemented",
344    /// );
345    /// assert!(matches!(
346    ///     error,
347    ///     tenferro_tensor::Error::UnsupportedDType {
348    ///         op: "exp",
349    ///         dtype: tenferro_tensor::DType::I64,
350    ///         ..
351    ///     }
352    /// ));
353    /// ```
354    pub fn unsupported_dtype(
355        op: &'static str,
356        dtype: crate::DType,
357        message: impl Into<String>,
358    ) -> Self {
359        Self::UnsupportedDType {
360            op,
361            dtype,
362            message: message.into(),
363        }
364    }
365
366    /// Construct a structured unsupported-operation error.
367    ///
368    /// Use this for an operation or execution surface that is not implemented
369    /// by the selected backend. Dtype conversion failures use
370    /// [`Error::unsupported_dtype_conversion`] instead, and operation-specific
371    /// typed reasons should use [`Error::extension`] with `ErrorKind::Unsupported`.
372    ///
373    /// # Examples
374    ///
375    /// ```rust
376    /// let error = tenferro_tensor::Error::unsupported(
377    ///     "full_piv_lu",
378    ///     "backend has no implementation",
379    /// );
380    /// assert!(matches!(
381    ///     error,
382    ///     tenferro_tensor::Error::Unsupported { op: "full_piv_lu", .. }
383    /// ));
384    /// ```
385    pub fn unsupported(op: &'static str, message: impl Into<String>) -> Self {
386        Self::Unsupported {
387            op,
388            message: message.into(),
389        }
390    }
391
392    /// Construct a text-only backend failure.
393    ///
394    /// Use [`Error::backend_source`] when a typed source is available.
395    ///
396    /// # Examples
397    ///
398    /// ```rust
399    /// let error = tenferro_tensor::Error::backend_failure(
400    ///     "matmul",
401    ///     "backend rejected launch",
402    /// );
403    /// assert!(matches!(
404    ///     error,
405    ///     tenferro_tensor::Error::BackendFailure { op: "matmul", .. }
406    /// ));
407    /// ```
408    pub fn backend_failure(op: &'static str, message: impl Into<String>) -> Self {
409        Self::BackendFailure {
410            op,
411            message: message.into(),
412        }
413    }
414
415    /// Construct a backend failure while preserving its typed source.
416    ///
417    /// # Examples
418    ///
419    /// ```rust
420    /// let error = tenferro_tensor::Error::backend_source(
421    ///     "load",
422    ///     std::io::Error::other("read failed"),
423    /// );
424    /// assert!(std::error::Error::source(&error).is_some());
425    /// ```
426    pub fn backend_source<E>(op: &'static str, source: E) -> Self
427    where
428        E: StdError + Send + Sync + 'static,
429    {
430        Self::BackendSource {
431            op,
432            source: Box::new(source),
433        }
434    }
435
436    /// Construct an I/O failure while preserving its typed source.
437    ///
438    /// I/O errors are intentionally separate from backend failures: callers
439    /// can classify them as [`ErrorKind::Io`] without parsing a message.
440    ///
441    /// # Examples
442    ///
443    /// ```rust
444    /// use tenferro_tensor::{Error, ErrorKind};
445    ///
446    /// let error = Error::io_source("load", std::io::Error::other("read failed"));
447    /// assert_eq!(error.kind(), ErrorKind::Io);
448    /// assert!(std::error::Error::source(&error).is_some());
449    /// ```
450    pub fn io_source<E>(op: &'static str, source: E) -> Self
451    where
452        E: StdError + Send + Sync + 'static,
453    {
454        Self::IoSource {
455            op,
456            source: Box::new(source),
457        }
458    }
459
460    /// Construct a runtime-state failure when no typed source exists.
461    ///
462    /// Use this for missing, uninitialized, or invalid execution state. It is
463    /// distinct from [`Error::backend_failure`], which is reserved for
464    /// vendor/backend status text.
465    ///
466    /// # Examples
467    ///
468    /// ```rust
469    /// use tenferro_tensor::{Error, ErrorKind};
470    ///
471    /// let error = Error::runtime_state("execute", "backend session is not initialized");
472    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
473    /// ```
474    pub fn runtime_state(op: &'static str, message: impl Into<String>) -> Self {
475        Self::RuntimeState {
476            op,
477            message: message.into(),
478        }
479    }
480
481    /// Construct a runtime-state failure while preserving a typed source.
482    ///
483    /// # Examples
484    ///
485    /// ```rust
486    /// use tenferro_tensor::{Error, ErrorKind};
487    ///
488    /// let error = Error::runtime_state_source(
489    ///     "execute",
490    ///     std::io::Error::other("executor lock poisoned"),
491    /// );
492    /// assert_eq!(error.kind(), ErrorKind::RuntimeState);
493    /// assert!(std::error::Error::source(&error).is_some());
494    /// ```
495    pub fn runtime_state_source<E>(op: &'static str, source: E) -> Self
496    where
497        E: StdError + Send + Sync + 'static,
498    {
499        Self::RuntimeStateSource {
500            op,
501            source: Box::new(source),
502        }
503    }
504
505    /// Construct an extension failure while preserving its typed source and
506    /// coarse classification.
507    ///
508    /// # Examples
509    ///
510    /// ```rust
511    /// use std::error::Error as _;
512    /// use tenferro_tensor::{Error, ErrorKind};
513    ///
514    /// let error = Error::extension(
515    ///     "einsum",
516    ///     "einsum",
517    ///     ErrorKind::Internal,
518    ///     std::io::Error::other("planner failed"),
519    /// );
520    /// assert!(error.source().is_some());
521    /// ```
522    pub fn extension<E>(op: &'static str, family: &'static str, kind: ErrorKind, source: E) -> Self
523    where
524        E: StdError + Send + Sync + 'static,
525    {
526        Self::Extension {
527            op,
528            family,
529            kind,
530            source: Box::new(source),
531        }
532    }
533
534    /// Preserve a typed guarded-host-access failure.
535    ///
536    /// # Examples
537    ///
538    /// ```rust
539    /// use tenferro_tensor::{Error, HostAccessError};
540    ///
541    /// let error = Error::host_access(
542    ///     "map",
543    ///     HostAccessError::Unsupported { backend: "opaque" },
544    /// );
545    /// assert!(matches!(error, Error::HostAccess { .. }));
546    /// ```
547    pub fn host_access(op: &'static str, source: crate::HostAccessError) -> Self {
548        Self::HostAccess { op, source }
549    }
550
551    /// Return the stable coarse classification for this tensor failure.
552    ///
553    /// # Examples
554    ///
555    /// ```rust
556    /// use tenferro_tensor::{Error, ErrorKind, ValidationError, ValidationKind};
557    /// use tenferro_tensor::core::DType;
558    ///
559    /// let error = Error::validation(
560    ///     "add",
561    ///     ValidationError::DTypeMismatch {
562    ///         expected: DType::F32,
563    ///         actual: DType::F64,
564    ///     },
565    /// );
566    /// assert_eq!(error.kind(), ErrorKind::Validation(ValidationKind::DTypeMismatch));
567    /// ```
568    pub fn kind(&self) -> ErrorKind {
569        match self {
570            Self::Validation { source, .. } => ErrorKind::Validation(source.kind()),
571            Self::UnsupportedDTypeConversion { .. }
572            | Self::UnsupportedDType { .. }
573            | Self::Unsupported { .. } => ErrorKind::Unsupported,
574            Self::BackendFailure { .. } | Self::BackendSource { .. } => ErrorKind::BackendFailure,
575            Self::IoSource { .. } => ErrorKind::Io,
576            Self::RuntimeState { .. }
577            | Self::RuntimeStateSource { .. }
578            | Self::HostAccess { .. } => ErrorKind::RuntimeState,
579            Self::Extension { kind, .. } => *kind,
580            Self::MissingValue { .. } => ErrorKind::RuntimeState,
581            Self::Internal(_) => ErrorKind::Internal,
582        }
583    }
584}
585
586/// Result type alias for runtime tensor operations.
587pub type Result<T> = std::result::Result<T, Error>;