Skip to main content

vortex_error/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4#![deny(missing_docs)]
5
6//! This crate defines error & result types for Vortex.
7//! It also contains a variety of useful macros for error handling.
8//!
9//! A [`VortexError`] is a human-readable message, not one enum variant per library that Vortex
10//! happens to depend on. An error from a dependency is attached as the [`Error::source`] of a
11//! [`VortexError`] and is recovered by downcasting that source.
12
13use std::backtrace::Backtrace;
14use std::backtrace::BacktraceStatus;
15use std::borrow::Cow;
16use std::convert::Infallible;
17use std::env;
18use std::error::Error;
19use std::fmt;
20use std::fmt::Debug;
21use std::fmt::Display;
22use std::fmt::Formatter;
23use std::io;
24use std::num::TryFromIntError;
25use std::ops::Deref;
26use std::sync::Arc;
27use std::sync::LazyLock;
28
29/// A string that can be used as an error message.
30#[derive(Debug, Clone)]
31pub struct ErrString(Cow<'static, str>);
32
33#[expect(
34    clippy::fallible_impl_from,
35    reason = "intentionally panic in debug mode when VORTEX_PANIC_ON_ERR is set"
36)]
37impl<T> From<T> for ErrString
38where
39    T: Into<Cow<'static, str>>,
40{
41    #[expect(
42        clippy::panic,
43        reason = "intentionally panic in debug mode when VORTEX_PANIC_ON_ERR is set"
44    )]
45    fn from(msg: T) -> Self {
46        if panic_on_err() {
47            panic!("{}\nBacktrace:\n{}", msg.into(), Backtrace::capture());
48        } else {
49            Self(msg.into())
50        }
51    }
52}
53
54fn panic_on_err() -> bool {
55    static PANIC_ON_ERR: LazyLock<bool> =
56        LazyLock::new(|| env::var("VORTEX_PANIC_ON_ERR").is_ok_and(|v| v == "1"));
57    *PANIC_ON_ERR
58}
59
60impl AsRef<str> for ErrString {
61    fn as_ref(&self) -> &str {
62        &self.0
63    }
64}
65
66impl Deref for ErrString {
67    type Target = str;
68
69    fn deref(&self) -> &Self::Target {
70        &self.0
71    }
72}
73
74impl Display for ErrString {
75    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
76        Display::fmt(&self.0, f)
77    }
78}
79
80/// The top-level error type for Vortex.
81///
82/// An error is a message, an optional underlying error, and a backtrace captured at
83/// construction. Cloning is cheap: the payload is shared, never copied.
84///
85/// The payload sits behind one pointer, so a `VortexResult<T>` costs the same as `T` plus at
86/// most a word on the success path. Most results fit in two registers and are returned in them,
87/// rather than through a stack slot the caller must reserve and read back. Constructing an error
88/// is no more expensive for it: the payload's allocation is the one the backtrace needed anyway.
89#[derive(Clone)]
90pub struct VortexError(Arc<ErrorInner>);
91
92const _: () = assert!(size_of::<VortexError>() == size_of::<usize>());
93const _: () = assert!(size_of::<VortexResult<()>>() == size_of::<usize>());
94
95struct ErrorInner {
96    /// `None` defers the message to the source, keeping the `?` conversion path allocation-free.
97    message: Option<ErrString>,
98    origin: Origin,
99}
100
101/// Where an error's source and backtrace come from.
102enum Origin {
103    /// Captured when this error was created.
104    Own {
105        source: Option<Box<dyn Error + Send + Sync + 'static>>,
106        backtrace: Backtrace,
107    },
108    /// Shared with the error this one adds context to.
109    ///
110    /// Context is normally added in place. This is only for an error that has been cloned, whose
111    /// payload the other clones still see.
112    Context(VortexError),
113}
114
115impl VortexError {
116    /// Creates an error carrying `message`.
117    pub fn new<T: Into<ErrString>>(message: T) -> Self {
118        Self::from_parts(Some(message.into()), None)
119    }
120
121    /// Wraps an underlying error as a Vortex error.
122    ///
123    /// The wrapped error is preserved as the [`Error::source`], so callers that care about the
124    /// concrete type can recover it with [`Error::source`] and `downcast_ref`.
125    pub fn external<E>(source: E) -> Self
126    where
127        E: Into<Box<dyn Error + Send + Sync + 'static>>,
128    {
129        Self::from_parts(None, Some(source.into()))
130    }
131
132    fn from_parts(
133        message: Option<ErrString>,
134        source: Option<Box<dyn Error + Send + Sync + 'static>>,
135    ) -> Self {
136        Self(Arc::new(ErrorInner {
137            message,
138            origin: Origin::Own {
139                source,
140                backtrace: Backtrace::capture(),
141            },
142        }))
143    }
144
145    /// Adds additional context to an error, preserving its source and backtrace.
146    pub fn with_context<T: Into<ErrString>>(mut self, msg: T) -> Self {
147        let msg: ErrString = msg.into();
148        // Build the combined string directly: `msg` has already been through the
149        // `VORTEX_PANIC_ON_ERR` check and must not trip it a second time.
150        let message = ErrString(Cow::Owned(format!("{msg}:\n  {}", self.message_body())));
151        if let Some(inner) = Arc::get_mut(&mut self.0) {
152            inner.message = Some(message);
153            return self;
154        }
155        Self(Arc::new(ErrorInner {
156            message: Some(message),
157            origin: Origin::Context(self),
158        }))
159    }
160
161    /// The error message, falling back to the underlying error when none was provided.
162    fn message_body(&self) -> Cow<'_, str> {
163        match (&self.0.message, self.source_ref()) {
164            (Some(message), _) => Cow::Borrowed(message.as_ref()),
165            (None, Some(source)) => Cow::Owned(source.to_string()),
166            (None, None) => Cow::Borrowed(""),
167        }
168    }
169
170    fn source_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
171        match &self.0.origin {
172            Origin::Own { source, .. } => source.as_deref(),
173            Origin::Context(error) => error.source_ref(),
174        }
175    }
176
177    fn backtrace(&self) -> &Backtrace {
178        match &self.0.origin {
179            Origin::Own { backtrace, .. } => backtrace,
180            Origin::Context(error) => error.backtrace(),
181        }
182    }
183}
184
185impl Display for VortexError {
186    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
187        match (&self.0.message, self.source_ref()) {
188            (Some(message), _) => Display::fmt(message, f)?,
189            (None, Some(source)) => Display::fmt(source, f)?,
190            (None, None) => {}
191        }
192        let backtrace = self.backtrace();
193        if backtrace.status() == BacktraceStatus::Captured {
194            write!(f, "\nBacktrace:\n{backtrace}")?;
195        }
196        Ok(())
197    }
198}
199
200impl Debug for VortexError {
201    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
202        write!(f, "{self}")
203    }
204}
205
206impl Error for VortexError {
207    fn source(&self) -> Option<&(dyn Error + 'static)> {
208        self.source_ref()
209            .map(|source| source as &(dyn Error + 'static))
210    }
211}
212
213/// A type alias for Results that return VortexErrors as their error type.
214pub type VortexResult<T> = Result<T, VortexError>;
215
216/// A vortex result that can be shared or cloned.
217pub type SharedVortexResult<T> = Result<T, Arc<VortexError>>;
218
219impl From<Arc<VortexError>> for VortexError {
220    fn from(value: Arc<VortexError>) -> Self {
221        Arc::try_unwrap(value).unwrap_or_else(|value| (*value).clone())
222    }
223}
224
225impl From<&Arc<VortexError>> for VortexError {
226    fn from(value: &Arc<VortexError>) -> Self {
227        (**value).clone()
228    }
229}
230
231/// A trait for expect-ing a VortexResult or an Option.
232pub trait VortexExpect {
233    /// The type of the value being expected.
234    type Output;
235
236    /// Returns the value of the result if it is Ok, otherwise panics with the error.
237    /// Should be called only in contexts where the error condition represents a bug (programmer error).
238    ///
239    /// # `&'static` message lifetime
240    ///
241    /// The panic string argument should be a string literal, hence the `&'static` lifetime. If
242    /// you'd like to panic with a dynamic format string, consider using `unwrap_or_else` combined
243    /// with the `vortex_panic!` macro instead.
244    fn vortex_expect(self, msg: &'static str) -> Self::Output;
245}
246
247impl<T, E> VortexExpect for Result<T, E>
248where
249    E: Into<VortexError>,
250{
251    type Output = T;
252
253    #[allow(clippy::inline_always)]
254    #[inline(always)]
255    fn vortex_expect(self, msg: &'static str) -> Self::Output {
256        match self {
257            Ok(value) => value,
258            Err(err) => __private::result_expect_failed(err, msg),
259        }
260    }
261}
262
263impl<T> VortexExpect for Option<T> {
264    type Output = T;
265
266    #[allow(clippy::inline_always)]
267    #[inline(always)]
268    fn vortex_expect(self, msg: &'static str) -> Self::Output {
269        match self {
270            Some(value) => value,
271            None => __private::option_expect_failed(msg),
272        }
273    }
274}
275
276/// A convenient macro for creating a VortexError.
277///
278/// ```
279/// use vortex_error::vortex_err;
280///
281/// let err = vortex_err!("negative length {}", -1);
282/// assert!(err.to_string().starts_with("negative length -1"));
283/// ```
284#[macro_export]
285macro_rules! vortex_err {
286    (Context: $msg:literal, $err:expr) => {
287        $crate::__private::context($msg, $err)
288    };
289    (External: $err:expr $(,)?) => {
290        $crate::__private::external($err)
291    };
292    ($fmt:literal $(, $arg:expr)* $(,)?) => {
293        $crate::__private::fmt_err(&format_args!($fmt $(, $arg)*))
294    };
295    ($err:expr $(,)?) => {
296        $crate::__private::fmt_err(&format_args!("{}", $err))
297    };
298}
299
300/// A convenience macro for returning a VortexError.
301#[macro_export]
302macro_rules! vortex_bail {
303    ($($tt:tt)+) => {
304        return Err($crate::vortex_err!($($tt)+))
305    };
306}
307
308/// A macro that mirrors `assert!` but instead of panicking on a failed condition,
309/// it will immediately return an erroneous `VortexResult` to the calling context.
310///
311/// Without a message the error names the condition.
312#[macro_export]
313macro_rules! vortex_ensure {
314    ($cond:expr) => {
315        $crate::vortex_ensure!($cond, "{}", stringify!($cond));
316    };
317    ($cond:expr, $($tt:tt)*) => {
318        if !$cond {
319            $crate::vortex_bail!($($tt)*);
320        }
321    };
322}
323
324/// A macro that mirrors `assert_eq!` but instead of panicking when `left != right`, it will
325/// immediately return an erroneous `VortexResult` to the calling context.
326///
327/// Both values must implement [`PartialEq`] and [`Display`], and each is
328/// evaluated exactly once. Use [`vortex_ensure!`] for values that do not implement `Display`.
329///
330/// By default the error shows both expressions and their values, so most callers do not need a
331/// message:
332///
333/// ```
334/// # use vortex_error::{VortexResult, vortex_ensure_eq};
335/// fn check(len: usize) -> VortexResult<()> {
336///     vortex_ensure_eq!(len, 2);
337///     Ok(())
338/// }
339///
340/// let err = check(3).unwrap_err().to_string();
341/// assert!(err.starts_with("`len == 2`\n  left: 3\n right: 2"));
342/// ```
343///
344/// A message replaces the expressions. The values are still appended, so the message does not
345/// need to repeat them:
346///
347/// ```
348/// # use vortex_error::{VortexResult, vortex_ensure_eq};
349/// fn check(len: usize) -> VortexResult<()> {
350///     vortex_ensure_eq!(len, 2, "map entries must have {} fields", 2);
351///     Ok(())
352/// }
353///
354/// let err = check(3).unwrap_err().to_string();
355/// assert!(err.starts_with("map entries must have 2 fields\n  left: 3\n right: 2"));
356/// ```
357#[macro_export]
358macro_rules! vortex_ensure_eq {
359    ($left:expr, $right:expr $(,)?) => {
360        match (&$left, &$right) {
361            (left_val, right_val) => {
362                if *left_val != *right_val {
363                    $crate::vortex_bail!(
364                        "`{} == {}`\n  left: {}\n right: {}",
365                        stringify!($left),
366                        stringify!($right),
367                        left_val,
368                        right_val
369                    );
370                }
371            }
372        }
373    };
374    ($left:expr, $right:expr, $fmt:literal $(, $arg:expr)* $(,)?) => {
375        match (&$left, &$right) {
376            (left_val, right_val) => {
377                if *left_val != *right_val {
378                    $crate::vortex_bail!(
379                        "{}\n  left: {}\n right: {}",
380                        format_args!($fmt $(, $arg)*),
381                        left_val,
382                        right_val
383                    );
384                }
385            }
386        }
387    };
388}
389
390/// A convenient macro for panicking with a VortexError in the presence of a programmer error
391/// (e.g., an invariant has been violated).
392///
393/// It takes a message like [`vortex_err!`], or an existing error with an optional message to add
394/// as context.
395#[macro_export]
396macro_rules! vortex_panic {
397    (Context: $msg:literal, $err:expr) => {{
398        $crate::vortex_panic!($crate::vortex_err!(Context: $msg, $err))
399    }};
400    // Before the `$err:expr` arms, which a bare message would otherwise match.
401    ($fmt:literal $(, $arg:expr)* $(,)?) => {
402        $crate::vortex_panic!($crate::vortex_err!($fmt $(, $arg)*))
403    };
404    ($err:expr, $fmt:literal $(, $arg:expr)* $(,)?) => {
405        $crate::__private::panic_err_ctx($err, &format_args!($fmt $(, $arg)*))
406    };
407    ($err:expr) => {
408        $crate::__private::panic_err($err)
409    };
410}
411
412impl From<Infallible> for VortexError {
413    fn from(_: Infallible) -> Self {
414        unreachable!()
415    }
416}
417
418impl From<arrow_schema::ArrowError> for VortexError {
419    fn from(value: arrow_schema::ArrowError) -> Self {
420        VortexError::external(value)
421    }
422}
423
424#[cfg(feature = "flatbuffers")]
425impl From<flatbuffers::InvalidFlatbuffer> for VortexError {
426    fn from(value: flatbuffers::InvalidFlatbuffer) -> Self {
427        VortexError::external(value)
428    }
429}
430
431impl From<io::Error> for VortexError {
432    fn from(value: io::Error) -> Self {
433        VortexError::external(value)
434    }
435}
436
437#[cfg(feature = "object_store")]
438impl From<object_store::Error> for VortexError {
439    fn from(value: object_store::Error) -> Self {
440        VortexError::external(value)
441    }
442}
443
444impl From<jiff::Error> for VortexError {
445    fn from(value: jiff::Error) -> Self {
446        VortexError::external(value)
447    }
448}
449
450#[cfg(feature = "tokio")]
451impl From<tokio::task::JoinError> for VortexError {
452    fn from(value: tokio::task::JoinError) -> Self {
453        if value.is_panic() {
454            std::panic::resume_unwind(value.into_panic())
455        } else {
456            VortexError::external(value)
457        }
458    }
459}
460
461impl From<TryFromIntError> for VortexError {
462    fn from(value: TryFromIntError) -> Self {
463        VortexError::external(value)
464    }
465}
466
467impl From<prost::EncodeError> for VortexError {
468    fn from(value: prost::EncodeError) -> Self {
469        VortexError::external(value)
470    }
471}
472
473impl From<prost::DecodeError> for VortexError {
474    fn from(value: prost::DecodeError) -> Self {
475        VortexError::external(value)
476    }
477}
478
479impl From<prost::UnknownEnumValue> for VortexError {
480    fn from(value: prost::UnknownEnumValue) -> Self {
481        VortexError::external(value)
482    }
483}
484
485/// We want our error handlers to be fast in the happy path, so we inline them.
486/// However, if we inline them as is, the call site gets the cold branch with
487/// panic! macros which gets expanded into backtrace collection and throwing.
488/// LLVM inliner/vectoriser in turn doesn't vectorize some code.
489/// So we inline only the happy path, the error path gets to a cold handler which
490/// is never inlined and thus doesn't prevent vectorization.
491#[doc(hidden)]
492#[expect(
493    clippy::panic,
494    reason = "cold handlers for vortex_panic!/vortex_expect intentionally panic"
495)]
496pub mod __private {
497
498    use std::error::Error;
499    use std::fmt::Arguments;
500
501    use crate::VortexError;
502
503    #[doc(hidden)]
504    #[inline]
505    #[cold]
506    #[must_use]
507    pub const fn must_use(error: VortexError) -> VortexError {
508        error
509    }
510
511    #[doc(hidden)]
512    #[cold]
513    #[inline(never)]
514    #[must_use]
515    pub fn fmt_err(args: &Arguments<'_>) -> VortexError {
516        VortexError::new(args.to_string())
517    }
518
519    #[doc(hidden)]
520    #[cold]
521    #[inline(never)]
522    #[must_use]
523    pub fn context(msg: &'static str, err: VortexError) -> VortexError {
524        err.with_context(msg)
525    }
526
527    #[doc(hidden)]
528    #[cold]
529    #[inline(never)]
530    #[must_use]
531    pub fn external(err: impl Into<Box<dyn Error + Send + Sync + 'static>>) -> VortexError {
532        VortexError::external(err)
533    }
534
535    #[doc(hidden)]
536    #[cold]
537    #[inline(never)]
538    pub fn panic_err(err: VortexError) -> ! {
539        panic!("{err}")
540    }
541
542    #[doc(hidden)]
543    #[cold]
544    #[inline(never)]
545    pub fn panic_err_ctx(err: VortexError, args: &Arguments<'_>) -> ! {
546        panic!("{}", err.with_context(args.to_string()))
547    }
548
549    #[doc(hidden)]
550    #[cold]
551    #[inline(never)]
552    pub fn result_expect_failed(err: impl Into<VortexError>, msg: &'static str) -> ! {
553        panic!("{}", err.into().with_context(msg))
554    }
555
556    #[doc(hidden)]
557    #[cold]
558    #[inline(never)]
559    pub fn option_expect_failed(msg: &'static str) -> ! {
560        panic!("{}", VortexError::new(msg))
561    }
562}