Skip to main content

zenpsy_api/
error.rs

1//! The unified metric error: one concrete envelope, located with whereat.
2//!
3//! Metrics return [`MetricResult<T>`] = `Result<T, At<MetricError>>`, the
4//! same shape zencodec uses for `At<CodecError>`. The `At` carries the
5//! location trace; [`MetricError`] carries a coarse [`ErrorKind`] fixed at
6//! construction, the originating metric family, an optional static
7//! message, and the metric's own error boxed as [`MetricError::detail`]
8//! (reachable through `source()`).
9//!
10//! Cancellation interop: `MetricError` implements `From<StopReason>` and
11//! [`how_far::AsStopReason`], so how-far / enough code classifies it.
12//! Rust's orphan rules forbid implementing `AsStopReason` for the located
13//! `At<MetricError>` here; pass [`stop_reason`] to how-far's
14//! `*_classified` entry points, or call `.error().as_stop_reason()`.
15
16use alloc::borrow::Cow;
17use alloc::boxed::Box;
18use core::fmt;
19
20use how_far::{AsStopReason, StopReason};
21use whereat::At;
22
23/// `Result<T, At<MetricError>>` — the return type of every fallible
24/// generic-surface call.
25pub type MetricResult<T> = Result<T, At<MetricError>>;
26
27/// Coarse, metric-agnostic classification of a failure. Fixed when the
28/// error is created, so routing (retry, skip cell, alert) never parses
29/// messages.
30#[non_exhaustive]
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum ErrorKind {
33    /// The input's pixel format/layout/transfer isn't one the metric
34    /// accepts natively.
35    UnsupportedInput,
36    /// Reference and distorted (or successive frames, or a warm reference
37    /// and a candidate) disagree on dimensions.
38    DimensionMismatch,
39    /// The image is below the metric's minimum size.
40    TooSmall,
41    /// Input values the metric can't score (non-finite samples, a buffer
42    /// shorter than its declared geometry).
43    InvalidInput,
44    /// Well-formed input whose content the metric can't characterise —
45    /// e.g. a featureless image that makes a fitted statistic NaN where
46    /// the reference implementation raises.
47    Degenerate,
48    /// The metric's configuration or a request parameter is invalid
49    /// (a zero subsample factor, a non-positive p-norm).
50    InvalidConfig,
51    /// A map was requested from a metric that publishes none.
52    NoMap,
53    /// A well-formed request this metric doesn't implement (an unknown
54    /// diagnostic request).
55    UnsupportedRequest,
56    /// Stopped through the caller's `Stop`/`Pulse` — cancelled or past
57    /// its deadline.
58    Stopped(StopReason),
59    /// Allocation failure or a resource ceiling.
60    Resource,
61    /// A compute backend (GPU device, thread pool) failed.
62    Backend,
63    /// A broken invariant inside the metric. Always a code defect.
64    Internal,
65}
66
67impl ErrorKind {
68    /// Stable lowercase name — `"unsupported_input"`, `"stopped"`, … —
69    /// for ledgers and logs.
70    pub const fn as_str(self) -> &'static str {
71        match self {
72            ErrorKind::UnsupportedInput => "unsupported_input",
73            ErrorKind::DimensionMismatch => "dimension_mismatch",
74            ErrorKind::TooSmall => "too_small",
75            ErrorKind::InvalidInput => "invalid_input",
76            ErrorKind::Degenerate => "degenerate",
77            ErrorKind::InvalidConfig => "invalid_config",
78            ErrorKind::NoMap => "no_map",
79            ErrorKind::UnsupportedRequest => "unsupported_request",
80            ErrorKind::Stopped(_) => "stopped",
81            ErrorKind::Resource => "resource",
82            ErrorKind::Backend => "backend",
83            ErrorKind::Internal => "internal",
84        }
85    }
86
87    /// `true` when the same call with the same input will fail again —
88    /// everything except `Stopped`, `Resource` and `Backend`.
89    pub const fn is_deterministic(self) -> bool {
90        !matches!(
91            self,
92            ErrorKind::Stopped(_) | ErrorKind::Resource | ErrorKind::Backend
93        )
94    }
95}
96
97impl fmt::Display for ErrorKind {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            ErrorKind::Stopped(r) => write!(f, "stopped: {r}"),
101            other => f.write_str(other.as_str()),
102        }
103    }
104}
105
106/// The error every generic-surface call returns, inside `At<…>`.
107///
108/// One word wide (the fields live behind a `Box`), so
109/// `At<MetricError>` is two words and `MetricResult<T>` stays cheap on
110/// the `?` path.
111#[non_exhaustive]
112pub struct MetricError(Box<Repr>);
113
114struct Repr {
115    kind: ErrorKind,
116    metric: Option<&'static str>,
117    message: Option<Cow<'static, str>>,
118    detail: Option<Box<dyn core::error::Error + Send + Sync>>,
119}
120
121impl MetricError {
122    /// Transfer an existing native location trace into this envelope.
123    #[track_caller]
124    pub fn from_located<E>(kind: ErrorKind, detail: At<E>) -> At<Self>
125    where
126        E: core::error::Error + Send + Sync + 'static,
127    {
128        detail.map_error(|e| Self::from_detail(kind, e)).at()
129    }
130
131    /// An error of `kind` with no detail.
132    pub fn new(kind: ErrorKind) -> Self {
133        MetricError(Box::new(Repr {
134            kind,
135            metric: None,
136            message: None,
137            detail: None,
138        }))
139    }
140
141    /// An error of `kind` wrapping the metric's own error.
142    pub fn from_detail<E>(kind: ErrorKind, detail: E) -> Self
143    where
144        E: core::error::Error + Send + Sync + 'static,
145    {
146        Self::new(kind).with_detail(detail)
147    }
148
149    /// The `Stopped` error for `reason`.
150    pub fn stopped(reason: StopReason) -> Self {
151        Self::new(ErrorKind::Stopped(reason))
152    }
153
154    /// Attach the metric's own error (boxed; reachable via `source()`).
155    #[must_use]
156    pub fn with_detail<E>(mut self, detail: E) -> Self
157    where
158        E: core::error::Error + Send + Sync + 'static,
159    {
160        self.0.detail = Some(Box::new(detail));
161        self
162    }
163
164    /// Attach an already-boxed detail error.
165    #[must_use]
166    pub fn with_boxed_detail(mut self, detail: Box<dyn core::error::Error + Send + Sync>) -> Self {
167        self.0.detail = Some(detail);
168        self
169    }
170
171    /// Stamp the originating metric family (`"fsim"`, `"cvvdp"`).
172    #[must_use]
173    pub fn with_metric(mut self, family: &'static str) -> Self {
174        self.0.metric = Some(family);
175        self
176    }
177
178    /// Attach a human-readable message (shown when there is no detail).
179    #[must_use]
180    pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
181        self.0.message = Some(message.into());
182        self
183    }
184
185    /// The coarse classification.
186    pub fn kind(&self) -> ErrorKind {
187        self.0.kind
188    }
189
190    /// The originating metric family, if stamped.
191    pub fn metric(&self) -> Option<&'static str> {
192        self.0.metric
193    }
194
195    /// The attached message, if any.
196    pub fn message(&self) -> Option<&str> {
197        self.0.message.as_deref()
198    }
199
200    /// The metric's own error, if any.
201    pub fn detail(&self) -> Option<&(dyn core::error::Error + 'static)> {
202        self.0
203            .detail
204            .as_deref()
205            .map(|d| d as &(dyn core::error::Error + 'static))
206    }
207}
208
209impl fmt::Debug for MetricError {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        f.debug_struct("MetricError")
212            .field("kind", &self.0.kind)
213            .field("metric", &self.0.metric)
214            .field("message", &self.0.message)
215            .field("detail", &self.0.detail)
216            .finish()
217    }
218}
219
220impl fmt::Display for MetricError {
221    /// `"{metric}: {kind}: {message}: {detail}"`, omitting absent parts.
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        if let Some(m) = self.0.metric {
224            write!(f, "{m}: ")?;
225        }
226        write!(f, "{}", self.0.kind)?;
227        if let Some(msg) = &self.0.message {
228            write!(f, ": {msg}")?;
229        }
230        if let Some(d) = &self.0.detail {
231            write!(f, ": {d}")?;
232        }
233        Ok(())
234    }
235}
236
237impl core::error::Error for MetricError {
238    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
239        self.detail()
240    }
241}
242
243impl From<StopReason> for MetricError {
244    fn from(reason: StopReason) -> Self {
245        MetricError::stopped(reason)
246    }
247}
248
249impl AsStopReason for MetricError {
250    fn as_stop_reason(&self) -> Option<StopReason> {
251        match self.0.kind {
252            ErrorKind::Stopped(r) => Some(r),
253            _ => None,
254        }
255    }
256}
257
258/// The stop reason of a located error, if it is a stop (orphan rules keep
259/// `AsStopReason` off `At<MetricError>` itself).
260pub fn stop_reason(error: &At<MetricError>) -> Option<StopReason> {
261    error.error().as_stop_reason()
262}
263
264/// The how-far classifier: pass `is_stopped` to `Stages::run_classified`
265/// and friends so a stopped metric records `Outcome::Stopped`, not a
266/// failure.
267pub fn is_stopped(error: &At<MetricError>) -> bool {
268    stop_reason(error).is_some()
269}
270
271/// Recover the [`MetricError`] from any error chain — after erasure to
272/// `Box<dyn Error>` or wrapping by a consumer. Looks for `At<MetricError>`,
273/// `MetricError` and one `Box` layer at every level of `source()`.
274pub fn find_metric_error<'a>(
275    error: &'a (dyn core::error::Error + 'static),
276) -> Option<&'a MetricError> {
277    let mut cur: Option<&'a (dyn core::error::Error + 'static)> = Some(error);
278    while let Some(e) = cur {
279        if let Some(at) = e.downcast_ref::<At<MetricError>>() {
280            return Some(at.error());
281        }
282        if let Some(m) = e.downcast_ref::<MetricError>() {
283            return Some(m);
284        }
285        if let Some(b) = e.downcast_ref::<Box<At<MetricError>>>() {
286            return Some(b.error());
287        }
288        cur = e.source();
289    }
290    None
291}
292
293/// Locate a new error at the caller.
294#[track_caller]
295pub fn fail<T>(error: MetricError) -> MetricResult<T> {
296    Err(whereat::at(error))
297}
298
299/// Convert a metric crate's own `Result` into a [`MetricResult`],
300/// locating the error at the caller.
301pub trait ResultMetricExt<T> {
302    /// Wrap the error as the detail of a `kind` [`MetricError`] stamped
303    /// with `family`.
304    #[track_caller]
305    fn metric_err(self, family: &'static str, kind: ErrorKind) -> MetricResult<T>;
306
307    /// Like [`Self::metric_err`], choosing the kind from the error value.
308    #[track_caller]
309    fn metric_err_with(
310        self,
311        family: &'static str,
312        classify: impl FnOnce(&Self::Error) -> ErrorKind,
313    ) -> MetricResult<T>
314    where
315        Self: Sized;
316
317    /// The wrapped error type.
318    type Error;
319}
320
321impl<T, E> ResultMetricExt<T> for Result<T, E>
322where
323    E: core::error::Error + Send + Sync + 'static,
324{
325    type Error = E;
326
327    #[track_caller]
328    fn metric_err(self, family: &'static str, kind: ErrorKind) -> MetricResult<T> {
329        match self {
330            Ok(v) => Ok(v),
331            Err(e) => Err(whereat::at(
332                MetricError::from_detail(kind, e).with_metric(family),
333            )),
334        }
335    }
336
337    #[track_caller]
338    fn metric_err_with(
339        self,
340        family: &'static str,
341        classify: impl FnOnce(&E) -> ErrorKind,
342    ) -> MetricResult<T> {
343        match self {
344            Ok(v) => Ok(v),
345            Err(e) => {
346                let kind = classify(&e);
347                Err(whereat::at(
348                    MetricError::from_detail(kind, e).with_metric(family),
349                ))
350            }
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use alloc::string::ToString;
359
360    #[derive(Debug)]
361    struct Leaf;
362    impl fmt::Display for Leaf {
363        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364            f.write_str("leaf failed")
365        }
366    }
367    impl core::error::Error for Leaf {}
368
369    #[test]
370    fn display_kind_detail_and_source() {
371        let e = MetricError::from_detail(ErrorKind::TooSmall, Leaf).with_metric("gmsd");
372        assert_eq!(e.to_string(), "gmsd: too_small: leaf failed");
373        assert!(core::error::Error::source(&e).is_some());
374        assert_eq!(e.kind(), ErrorKind::TooSmall);
375        assert!(e.kind().is_deterministic());
376    }
377
378    #[test]
379    fn stop_reason_round_trips_through_as_stop_reason() {
380        let e: MetricError = StopReason::Cancelled.into();
381        assert_eq!(e.as_stop_reason(), Some(StopReason::Cancelled));
382        assert!(!e.kind().is_deterministic());
383        let located = whereat::at(e);
384        assert_eq!(stop_reason(&located), Some(StopReason::Cancelled));
385        let other = whereat::at(MetricError::new(ErrorKind::NoMap));
386        assert_eq!(stop_reason(&other), None);
387    }
388
389    #[test]
390    fn recoverable_after_erasure() {
391        let r: Result<(), Leaf> = Err(Leaf);
392        let err = r.metric_err("fsim", ErrorKind::InvalidInput).unwrap_err();
393        let boxed: Box<dyn core::error::Error + Send + Sync> = Box::new(err);
394        let found = find_metric_error(&*boxed).expect("envelope recoverable");
395        assert_eq!(found.kind(), ErrorKind::InvalidInput);
396        assert_eq!(found.metric(), Some("fsim"));
397    }
398
399    #[test]
400    fn located_at_the_caller() {
401        let r: Result<(), Leaf> = Err(Leaf);
402        let line = line!() + 1;
403        let err = r.metric_err("fsim", ErrorKind::InvalidInput).unwrap_err();
404        let frame = err.frames().next().expect("one frame");
405        let loc = frame.location().expect("location recorded");
406        assert_eq!(loc.line(), line);
407        assert!(loc.file().ends_with("error.rs"));
408    }
409
410    #[test]
411    fn error_types_are_send_sync() {
412        fn assert_send_sync<T: Send + Sync>() {}
413        assert_send_sync::<MetricError>();
414        assert_send_sync::<At<MetricError>>();
415    }
416}