Skip to main content

eclipse_core/
error.rs

1use crate::router::{Hop, RouteStop};
2use std::path::PathBuf;
3
4pub type Result<T> = std::result::Result<T, Error>;
5
6#[derive(Debug, thiserror::Error)]
7pub enum Error {
8    #[error("config error: {0}")]
9    Config(String),
10    #[error("failed to read {path}: {source}")]
11    Io {
12        path: PathBuf,
13        #[source]
14        source: std::io::Error,
15    },
16    #[error("failed to parse {path}: {message}")]
17    Parse { path: PathBuf, message: String },
18    #[error("provider error: {0}")]
19    Provider(ProviderFailure),
20    #[error("session error: {0}")]
21    Session(String),
22    #[error("agent stopped after {0} iterations without a final answer")]
23    MaxIterations(usize),
24    #[error("cancelled")]
25    Cancelled,
26    /// A hook ended the run. Distinct from cancellation because nobody pressed anything: the
27    /// reason is the point, and a caller that retries a cancelled run should not retry this.
28    #[error("stopped by a hook: {0}")]
29    Stopped(String),
30    /// The turn was not started because it could not carry its pictures (`#346`). The sentence is
31    /// the refusal itself — what cannot be done and what to change — because every surface prints
32    /// it as it is, and two surfaces wording it differently is how a bug gets reported twice.
33    #[error("{0}")]
34    Vision(String),
35    /// The run stopped on an approval nobody has answered: the calls are recorded, the turn is
36    /// not, and any later process can answer them. Not a cancellation — nothing was stopped on
37    /// purpose — and not a denial, which would be a decision made on the user's behalf.
38    #[error("{}", .0.hint())]
39    AwaitingApproval(crate::approvals::Waiting),
40    /// The model answered, and the answer was not the shape the caller asked for — twice: once
41    /// as it came, and once after a retry that carried the parse error back to it. The reply is
42    /// kept because the failure is about what it wrote, and a caller that only gets "invalid
43    /// JSON" has to re-run the whole thing to find out what.
44    #[error("the reply did not match the requested schema: {error}")]
45    Unparsed { error: String, reply: String },
46}
47
48/// A database failure is a failure to store a session — the one thing the caller was
49/// trying to do — so it reports as a session error rather than a new variant callers would
50/// have to match on.
51impl From<rusqlite::Error> for Error {
52    fn from(e: rusqlite::Error) -> Self {
53        Error::Session(e.to_string())
54    }
55}
56
57impl Error {
58    pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
59        Error::Io {
60            path: path.into(),
61            source,
62        }
63    }
64
65    /// A provider failure with nothing but an explanation, for call sites that have no more
66    /// structure to offer than a message.
67    pub fn provider(message: impl Into<String>) -> Self {
68        Error::Provider(ProviderFailure::other(message))
69    }
70
71    /// The provider failure inside this error, when it is one. A caller that cares about the
72    /// status or the retry policy asks here instead of matching the variant itself.
73    pub fn provider_failure(&self) -> Option<&ProviderFailure> {
74        match self {
75            Error::Provider(f) => Some(f),
76            _ => None,
77        }
78    }
79}
80
81/// Which way talking to the model server failed.
82///
83/// Kept as structure rather than a formatted string because two callers need to ask
84/// questions about it: the retry loop wants `is_retryable()`, and the operator wants the
85/// status, the body the server actually sent and the id to quote at support.
86#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87#[non_exhaustive]
88pub enum ProviderFailure {
89    /// No answer at all: DNS, connection refused or reset, TLS, timeout.
90    ///
91    /// `sent` says whether the request had already gone out when this happened, because that is the
92    /// difference between a free retry and a billed one: a connect-stage failure never reached the
93    /// server, while a reset after the body was written may have been read, charged, or half-run.
94    #[error("could not reach {url}: {message}")]
95    Transport {
96        url: String,
97        message: String,
98        sent: bool,
99    },
100
101    /// 401 or 403: the key is missing, wrong, or not allowed to use this model.
102    #[error("unauthorized: {0}")]
103    Unauthorized(HttpFailure),
104
105    /// 400, 404, 405, 422: the request is wrong for this server or this model — an option
106    /// it does not know, a model name it does not serve, a tool schema it cannot parse.
107    #[error("invalid request: {0}")]
108    InvalidRequest(HttpFailure),
109
110    /// Any other non-2xx answer.
111    #[error("{0}")]
112    Http(HttpFailure),
113
114    /// The stream ended before the model said it was done. Retryable, but see
115    /// [`ProviderFailure::is_retryable`] and the rule the provider applies: only when
116    /// nothing has been shown to the reader yet, because replaying text they already read
117    /// is worse than failing.
118    #[error("the reply was cut off before it finished: {message}")]
119    Truncated {
120        message: String,
121        /// How much text had arrived before the cut, for the message.
122        streamed_chars: usize,
123    },
124
125    /// A successful-looking answer that is not a chat completion we can read.
126    #[error("unexpected response: {message}")]
127    Response {
128        message: String,
129        body: Option<String>,
130    },
131
132    /// A failure that came out of a [`Router`](crate::router::Router), carrying the route it
133    /// happened on and the hops taken before it. Every question a caller asks about a failure
134    /// is answered by `cause`; this wrapper only adds *where*.
135    #[error("{}", describe_routed(route, trail, *stop, cause))]
136    Routed {
137        /// The route that was being tried when the run stopped.
138        route: String,
139        /// The hops made before this failure, oldest first.
140        trail: Vec<Hop>,
141        stop: RouteStop,
142        /// Named `cause`, not `source`, so thiserror does not treat it as the error source.
143        cause: Box<ProviderFailure>,
144    },
145}
146
147/// The parts of a non-2xx answer worth keeping.
148#[derive(Debug, Clone, PartialEq, Eq, Default)]
149pub struct HttpFailure {
150    pub status: u16,
151    /// The server's own words, clipped. Usually a JSON error object; sometimes an HTML
152    /// page from a proxy, which is itself the diagnosis.
153    pub body: String,
154    /// `x-request-id` (or `request-id`) if the server sent one — the thing support asks for.
155    pub request_id: Option<String>,
156    /// `Retry-After` in seconds, when the server said how long to wait.
157    pub retry_after_secs: Option<u64>,
158    /// What to do about it, when we can tell. Names the option and the model, because
159    /// "HTTP 400: unknown field" is not something a person can act on.
160    pub hint: Option<String>,
161}
162
163impl std::fmt::Display for HttpFailure {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        write!(f, "HTTP {}", self.status)?;
166        if !self.body.is_empty() {
167            write!(f, ": {}", self.body)?;
168        }
169        if let Some(id) = &self.request_id {
170            write!(f, " [request id {id}]")?;
171        }
172        if let Some(hint) = &self.hint {
173            write!(f, " — {hint}")?;
174        }
175        Ok(())
176    }
177}
178
179/// [`ProviderFailure`] without its payload, for callers that match on the shape of the
180/// failure rather than its contents.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182#[non_exhaustive]
183pub enum ProviderFailureKind {
184    Transport,
185    Unauthorized,
186    InvalidRequest,
187    Http,
188    Truncated,
189    Response,
190}
191
192impl ProviderFailureKind {
193    pub fn as_str(self) -> &'static str {
194        match self {
195            ProviderFailureKind::Transport => "transport",
196            ProviderFailureKind::Unauthorized => "unauthorized",
197            ProviderFailureKind::InvalidRequest => "invalid_request",
198            ProviderFailureKind::Http => "http",
199            ProviderFailureKind::Truncated => "truncated",
200            ProviderFailureKind::Response => "response",
201        }
202    }
203}
204
205impl std::fmt::Display for ProviderFailureKind {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.write_str(self.as_str())
208    }
209}
210
211impl ProviderFailure {
212    /// A failure with nothing but an explanation: a reply we could not read, a test double,
213    /// an error the server put inside a stream.
214    pub fn other(message: impl Into<String>) -> Self {
215        ProviderFailure::Response {
216            message: message.into(),
217            body: None,
218        }
219    }
220
221    pub fn kind(&self) -> ProviderFailureKind {
222        match self {
223            ProviderFailure::Transport { .. } => ProviderFailureKind::Transport,
224            ProviderFailure::Unauthorized(_) => ProviderFailureKind::Unauthorized,
225            ProviderFailure::InvalidRequest(_) => ProviderFailureKind::InvalidRequest,
226            ProviderFailure::Http(_) => ProviderFailureKind::Http,
227            ProviderFailure::Truncated { .. } => ProviderFailureKind::Truncated,
228            ProviderFailure::Response { .. } => ProviderFailureKind::Response,
229            ProviderFailure::Routed { cause, .. } => cause.kind(),
230        }
231    }
232
233    /// A few words for a readout: `timeout`, `HTTP 503`, `stream cut`. The full text is the
234    /// failure's `Display`; this is what fits after an arrow.
235    pub fn short_reason(&self) -> String {
236        match self {
237            ProviderFailure::Transport { message, .. } if message.contains("timed out") => {
238                "timeout".into()
239            }
240            ProviderFailure::Transport { message, .. }
241                if message.contains("could not be established") =>
242            {
243                "unreachable".into()
244            }
245            ProviderFailure::Transport { .. } => "connection error".into(),
246            ProviderFailure::Unauthorized(h)
247            | ProviderFailure::InvalidRequest(h)
248            | ProviderFailure::Http(h) => format!("HTTP {}", h.status),
249            ProviderFailure::Truncated { .. } => "stream cut".into(),
250            ProviderFailure::Response { .. } => "unreadable reply".into(),
251            ProviderFailure::Routed { cause, .. } => cause.short_reason(),
252        }
253    }
254
255    /// Whether the request had already been written to the socket when this failure happened.
256    ///
257    /// `/chat/completions` is not idempotent and it is billed, so a drop after the body went out may
258    /// cost a whole generation that repeating will pay for again. A connect-stage failure costs
259    /// nothing to repeat. Everything that is not a transport failure answers `false`: it has its own
260    /// retry rule.
261    pub fn after_send(&self) -> bool {
262        match self {
263            ProviderFailure::Transport { sent, .. } => *sent,
264            ProviderFailure::Routed { cause, .. } => cause.after_send(),
265            _ => false,
266        }
267    }
268
269    /// Whether repeating the request could plausibly work. Deliberately conservative: a
270    /// wrong key or a rejected option will fail the same way every time, and retrying it
271    /// only wastes the operator's morning.
272    pub fn is_retryable(&self) -> bool {
273        match self {
274            // Both stages are *trouble*, which is what this answers: whether another route is worth
275            // trying. Whether the same request may be repeated is a narrower question, and the
276            // provider answers it with [`Self::after_send`] because only it knows whether repeating
277            // has been allowed.
278            ProviderFailure::Transport { .. } => true,
279            ProviderFailure::Truncated { .. } => true,
280            ProviderFailure::Http(h) => is_retryable_status(h.status),
281            ProviderFailure::Unauthorized(_) | ProviderFailure::InvalidRequest(_) => false,
282            ProviderFailure::Response { .. } => false,
283            ProviderFailure::Routed { cause, .. } => cause.is_retryable(),
284        }
285    }
286
287    pub fn status(&self) -> Option<u16> {
288        match self {
289            ProviderFailure::Unauthorized(h)
290            | ProviderFailure::InvalidRequest(h)
291            | ProviderFailure::Http(h) => Some(h.status),
292            ProviderFailure::Routed { cause, .. } => cause.status(),
293            _ => None,
294        }
295    }
296
297    /// The server's own words, when there were any.
298    pub fn body(&self) -> Option<&str> {
299        match self {
300            ProviderFailure::Unauthorized(h)
301            | ProviderFailure::InvalidRequest(h)
302            | ProviderFailure::Http(h) => Some(&h.body),
303            ProviderFailure::Response { body, .. } => body.as_deref(),
304            ProviderFailure::Routed { cause, .. } => cause.body(),
305            _ => None,
306        }
307    }
308
309    pub fn request_id(&self) -> Option<&str> {
310        match self {
311            ProviderFailure::Unauthorized(h)
312            | ProviderFailure::InvalidRequest(h)
313            | ProviderFailure::Http(h) => h.request_id.as_deref(),
314            ProviderFailure::Routed { cause, .. } => cause.request_id(),
315            _ => None,
316        }
317    }
318
319    /// How long the server asked us to wait, in seconds.
320    pub fn retry_after_secs(&self) -> Option<u64> {
321        match self {
322            ProviderFailure::Unauthorized(h)
323            | ProviderFailure::InvalidRequest(h)
324            | ProviderFailure::Http(h) => h.retry_after_secs,
325            ProviderFailure::Routed { cause, .. } => cause.retry_after_secs(),
326            _ => None,
327        }
328    }
329
330    /// What the operator should do next, when we can say.
331    pub fn hint(&self) -> Option<&str> {
332        match self {
333            ProviderFailure::Unauthorized(h)
334            | ProviderFailure::InvalidRequest(h)
335            | ProviderFailure::Http(h) => h.hint.as_deref(),
336            ProviderFailure::Routed { cause, .. } => cause.hint(),
337            _ => None,
338        }
339    }
340}
341
342fn describe_routed(route: &str, trail: &[Hop], stop: RouteStop, cause: &ProviderFailure) -> String {
343    let hopped = |trail: &[Hop]| {
344        trail
345            .iter()
346            .map(|h| format!("{}: {}", h.from, h.reason))
347            .collect::<Vec<_>>()
348            .join("; ")
349    };
350    match stop {
351        RouteStop::Failed if trail.is_empty() => format!("route `{route}` failed: {cause}"),
352        RouteStop::Failed => format!(
353            "route `{route}` failed: {cause} (earlier: {})",
354            hopped(trail)
355        ),
356        RouteStop::Exhausted => format!(
357            "every route failed ({}; {route}: {}); the last said: {cause}",
358            hopped(trail),
359            cause.short_reason()
360        ),
361        RouteStop::AfterText => format!(
362            "route `{route}` failed after it had started answering: {cause}. The text was \
363             already shown, so the turn was not replayed on the next route"
364        ),
365    }
366}
367
368/// 429 and 5xx are the server's own transient trouble; 408 is a timeout it admits to.
369/// Everything else in 4xx is a mistake in the request that repeating will not fix.
370pub fn is_retryable_status(status: u16) -> bool {
371    status == 408 || status == 429 || (500..600).contains(&status)
372}
373
374/// Keep a string-to-failure conversion available so a plain message is never a compile
375/// error in a hurry — but prefer a real variant where one exists.
376impl From<&str> for ProviderFailure {
377    fn from(s: &str) -> Self {
378        ProviderFailure::other(s)
379    }
380}
381
382impl From<String> for ProviderFailure {
383    fn from(s: String) -> Self {
384        ProviderFailure::other(s)
385    }
386}
387
388impl From<ProviderFailure> for Error {
389    fn from(f: ProviderFailure) -> Self {
390        Error::Provider(f)
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    fn http(status: u16) -> HttpFailure {
399        HttpFailure {
400            status,
401            body: "{\"error\":\"nope\"}".into(),
402            request_id: Some("req-7".into()),
403            retry_after_secs: None,
404            hint: None,
405        }
406    }
407
408    #[test]
409    fn the_retry_policy_is_the_servers_transient_trouble_and_nothing_else() {
410        assert!(is_retryable_status(408));
411        assert!(is_retryable_status(429));
412        assert!(is_retryable_status(500));
413        assert!(is_retryable_status(503));
414        assert!(is_retryable_status(599));
415        assert!(!is_retryable_status(400));
416        assert!(!is_retryable_status(401));
417        assert!(!is_retryable_status(404));
418        assert!(!is_retryable_status(422));
419        assert!(!is_retryable_status(200));
420    }
421
422    #[test]
423    fn each_variant_answers_the_questions_a_caller_asks() {
424        let transport = ProviderFailure::Transport {
425            url: "http://127.0.0.1:9/v1".into(),
426            message: "connection reset by peer".into(),
427            sent: true,
428        };
429        assert_eq!(transport.kind(), ProviderFailureKind::Transport);
430        assert_eq!(transport.kind().as_str(), "transport");
431        assert!(
432            transport.is_retryable(),
433            "an unanswered request is safe to repeat"
434        );
435        assert_eq!(transport.status(), None);
436        assert_eq!(transport.body(), None);
437
438        let auth = ProviderFailure::Unauthorized(http(401));
439        assert_eq!(auth.kind(), ProviderFailureKind::Unauthorized);
440        assert!(
441            !auth.is_retryable(),
442            "a wrong key fails the same way every time"
443        );
444        assert_eq!(auth.status(), Some(401));
445        assert_eq!(auth.body(), Some("{\"error\":\"nope\"}"));
446        assert_eq!(auth.request_id(), Some("req-7"));
447
448        let bad = ProviderFailure::InvalidRequest(http(400));
449        assert!(!bad.is_retryable());
450        assert_eq!(bad.kind(), ProviderFailureKind::InvalidRequest);
451
452        assert!(ProviderFailure::Http(http(503)).is_retryable());
453        assert!(ProviderFailure::Http(http(429)).is_retryable());
454        assert!(!ProviderFailure::Http(http(404)).is_retryable());
455
456        let cut = ProviderFailure::Truncated {
457            message: "stream ended".into(),
458            streamed_chars: 12,
459        };
460        assert!(cut.is_retryable());
461        assert_eq!(cut.kind(), ProviderFailureKind::Truncated);
462        assert_eq!(cut.status(), None);
463
464        let odd = ProviderFailure::other("no choices");
465        assert!(
466            !odd.is_retryable(),
467            "a reply we cannot read will read the same twice"
468        );
469        assert_eq!(odd.kind(), ProviderFailureKind::Response);
470    }
471
472    #[test]
473    fn an_http_failure_displays_the_things_worth_quoting() {
474        let mut f = http(500);
475        f.body = "upstream exploded".into();
476        let rendered = ProviderFailure::Http(f).to_string();
477        assert!(rendered.contains("HTTP 500"), "{rendered}");
478        assert!(rendered.contains("upstream exploded"), "{rendered}");
479        assert!(rendered.contains("req-7"), "{rendered}");
480
481        let hinted = ProviderFailure::InvalidRequest(HttpFailure {
482            status: 400,
483            body: "unknown field".into(),
484            request_id: None,
485            retry_after_secs: None,
486            hint: Some("provider.top_p is not supported by model m".into()),
487        })
488        .to_string();
489        assert!(hinted.contains("provider.top_p"), "{hinted}");
490    }
491
492    #[test]
493    fn a_plain_message_still_becomes_a_provider_error() {
494        let e = Error::provider("script exhausted");
495        assert_eq!(
496            e.to_string(),
497            "provider error: unexpected response: script exhausted"
498        );
499        let from_string: Error = Error::Provider("boom".to_string().into());
500        assert_eq!(
501            from_string.to_string(),
502            "provider error: unexpected response: boom"
503        );
504    }
505}