Skip to main content

aither_core/llm/failure/
mod.rs

1//! Classification of language-model failures.
2//!
3//! A provider error says what went wrong in provider terms. [`Classify`] lets a
4//! caller decide what to do about it without parsing a message: wait for the
5//! network, retry after the upstream's requested delay, give up on a quota, or
6//! surface a permanent fault.
7
8use alloc::boxed::Box;
9use core::{convert::Infallible, time::Duration};
10
11#[cfg(feature = "zenwave")]
12pub mod zenwave;
13
14/// What kind of failure a provider error is.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub enum FailureKind {
18    /// No response came back from the network: DNS failure, refused or reset
19    /// connection, TLS failure, stream EOF or reset mid-response, request
20    /// timeout.
21    Network,
22    /// The upstream answered with a temporary fault: 5xx, 529/overloaded, 408,
23    /// or a 429 that is not a quota exhaustion.
24    Transient,
25    /// A quota or usage limit is exhausted; retrying will not help until it
26    /// resets.
27    Quota,
28    /// Everything else: other 4xx, authentication, malformed requests, parse
29    /// errors and local-model errors.
30    Permanent,
31}
32
33/// A classified failure and, when the upstream asked for one, its retry delay.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub struct Failure {
37    /// What kind of failure this is.
38    pub kind: FailureKind,
39    /// The delay the upstream requested before the next attempt, from its
40    /// `Retry-After` header or an equivalent field.
41    pub retry_after: Option<Duration>,
42}
43
44impl Failure {
45    /// A failure of `kind` with no requested retry delay.
46    #[must_use]
47    pub const fn new(kind: FailureKind) -> Self {
48        Self {
49            kind,
50            retry_after: None,
51        }
52    }
53
54    /// A [`FailureKind::Network`] failure.
55    #[must_use]
56    pub const fn network() -> Self {
57        Self::new(FailureKind::Network)
58    }
59
60    /// A [`FailureKind::Transient`] failure.
61    #[must_use]
62    pub const fn transient() -> Self {
63        Self::new(FailureKind::Transient)
64    }
65
66    /// A [`FailureKind::Quota`] failure.
67    #[must_use]
68    pub const fn quota() -> Self {
69        Self::new(FailureKind::Quota)
70    }
71
72    /// A [`FailureKind::Permanent`] failure.
73    #[must_use]
74    pub const fn permanent() -> Self {
75        Self::new(FailureKind::Permanent)
76    }
77
78    /// Sets the retry delay the upstream requested.
79    #[must_use]
80    pub const fn with_retry_after(mut self, retry_after: Option<Duration>) -> Self {
81        self.retry_after = retry_after;
82        self
83    }
84
85    /// Whether the same request may succeed if sent again later
86    /// ([`FailureKind::Network`] or [`FailureKind::Transient`]).
87    #[must_use]
88    pub const fn is_retryable(&self) -> bool {
89        matches!(self.kind, FailureKind::Network | FailureKind::Transient)
90    }
91}
92
93/// Errors that can say what kind of failure they are.
94///
95/// Implementations read the structured data behind the error — HTTP status,
96/// the error type in the response body, the transport error's kind — and never
97/// match on message text when a typed source exists.
98pub trait Classify {
99    /// Classifies this error.
100    fn failure(&self) -> Failure;
101}
102
103impl<T: Classify + ?Sized> Classify for &T {
104    fn failure(&self) -> Failure {
105        T::failure(self)
106    }
107}
108
109impl<T: Classify + ?Sized> Classify for Box<T> {
110    fn failure(&self) -> Failure {
111        T::failure(self)
112    }
113}
114
115impl Classify for Infallible {
116    fn failure(&self) -> Failure {
117        // `Infallible` has no values, so this can never be called.
118        Failure::permanent()
119    }
120}
121
122impl<E: Classify> Classify for super::GenerateError<E> {
123    fn failure(&self) -> Failure {
124        match self {
125            Self::Provider(error) => error.failure(),
126            Self::Parse { .. } => Failure::permanent(),
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn retryable_kinds() {
137        assert!(Failure::network().is_retryable());
138        assert!(Failure::transient().is_retryable());
139        assert!(!Failure::quota().is_retryable());
140        assert!(!Failure::permanent().is_retryable());
141    }
142
143    #[test]
144    fn retry_after_is_carried() {
145        let failure = Failure::transient().with_retry_after(Some(Duration::from_secs(3)));
146        assert_eq!(failure.retry_after, Some(Duration::from_secs(3)));
147    }
148}