Skip to main content

graphrt_llm/
failover.rs

1//! Failing over to fallback models when a provider is down.
2//!
3//! A node's `model` may list `fallbacks`, tried in order when a call fails for
4//! a reason of the provider's infrastructure:
5//!
6//! ```yaml
7//! model:
8//!   provider: openai
9//!   name: gpt-4o-mini
10//!   fallbacks:
11//!     - { provider: azure-openai, name: gpt-4o-mini }   # deployment name
12//!     - { provider: anthropic, name: claude-haiku-4-5 }
13//! ```
14//!
15//! - **What fails over** ([`fails_over`]): server errors (5xx), network errors
16//!   (connection refused, TLS, timeouts, a stream cut before its first token)
17//!   and a provider that does not answer within [`HEADERS_TIMEOUT`]. A rate
18//!   limit (429) fails over only on the node's last attempt, after the node's
19//!   own retries (`retry.max_retries`) are spent. Authentication, invalid
20//!   requests, context length and content filtering never fail over: the
21//!   caller gets that error, naming the model that gave it.
22//! - **Streaming**: a candidate is only left before it streamed its first
23//!   token (text, reasoning or a tool call). An error after that is the
24//!   call's error, so nothing the user already saw is answered twice.
25//! - **Circuit breaker** ([`Breakers`]): after [`BREAKER_THRESHOLD`] such
26//!   failures in a row a provider is skipped for [`BREAKER_COOLDOWN`], then
27//!   tried again (one success closes it). The last candidate is always tried.
28//! - **Report**: the stream of a call that did not end at the first candidate
29//!   starts with [`ChatDelta::Failover`], naming the model that answered and
30//!   why each one before it was left (error texts are the providers' own,
31//!   already scrubbed of credentials). Nodes charge the response at the price
32//!   of the model that answered and report it as `model_failover` progress.
33
34use std::collections::HashMap;
35use std::sync::{Arc, Mutex};
36use std::time::{Duration, Instant};
37
38use futures::StreamExt;
39use futures::future::BoxFuture;
40use graphrt_core::node::Clock;
41use serde::{Deserialize, Serialize};
42
43use crate::error::LlmError;
44use crate::types::{ChatDelta, ChatModel, ChatRequest, ChatStream};
45
46/// Failures in a row after which a provider is skipped.
47pub const BREAKER_THRESHOLD: u32 = 3;
48/// How long a provider is skipped once its breaker opened.
49pub const BREAKER_COOLDOWN: Duration = Duration::from_secs(30);
50/// How long a candidate with a fallback after it may take to answer a
51/// request (its response headers) before the next one is tried. Streamed
52/// tokens may take longer: reasoning models think before the first one.
53pub const HEADERS_TIMEOUT: Duration = Duration::from_secs(30);
54
55/// One model a call may be made with.
56#[derive(Clone)]
57pub struct Candidate {
58    /// The provider name as configured (`model.provider`).
59    pub provider: String,
60    /// The model (or deployment) name sent to it.
61    pub model: String,
62    /// The provider's name in the registry, keying its breaker.
63    pub breaker_key: String,
64    pub chat: Arc<dyn ChatModel>,
65}
66
67impl std::fmt::Debug for Candidate {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        write!(f, "{}/{}", self.provider, self.model)
70    }
71}
72
73/// A model left during a call, and why.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75pub struct FailedModel {
76    pub provider: String,
77    pub model: String,
78    pub reason: String,
79}
80
81/// Which model answered a call that failed over, and the ones left before it.
82#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83pub struct FailoverReport {
84    pub provider: String,
85    pub model: String,
86    pub failed: Vec<FailedModel>,
87}
88
89/// Whether `error` moves a call on to the next candidate. A rate limit does
90/// only when no retry of the node follows (`last_attempt`).
91pub fn fails_over(error: &LlmError, last_attempt: bool) -> bool {
92    match error {
93        LlmError::Server { .. } | LlmError::Network(_) => true,
94        LlmError::RateLimit { .. } => last_attempt,
95        _ => false,
96    }
97}
98
99/// Whether `error` counts against the provider's breaker (its service, not
100/// the request, failed).
101fn is_outage(error: &LlmError) -> bool {
102    matches!(error, LlmError::Server { .. } | LlmError::Network(_) | LlmError::RateLimit { .. })
103}
104
105#[derive(Debug, Default, Clone, Copy)]
106struct BreakerState {
107    failures: u32,
108    open_until: Option<Instant>,
109}
110
111/// Per-provider circuit breakers, shared by every clone of a
112/// [`crate::ModelRegistry`] (so by every run of a process).
113#[derive(Debug, Default)]
114pub struct Breakers {
115    states: Mutex<HashMap<String, BreakerState>>,
116}
117
118impl Breakers {
119    fn states(&self) -> std::sync::MutexGuard<'_, HashMap<String, BreakerState>> {
120        self.states.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
121    }
122
123    /// Whether `provider` may be called at `now`: its breaker is closed, or
124    /// its cooldown ended (the next call is the trial).
125    pub fn allows(&self, provider: &str, now: Instant) -> bool {
126        self.states().get(provider).and_then(|s| s.open_until).is_none_or(|until| now >= until)
127    }
128
129    /// A call to `provider` succeeded: its breaker closes.
130    pub fn record_success(&self, provider: &str) {
131        self.states().remove(provider);
132    }
133
134    /// A call to `provider` failed for an outage. Returns whether its breaker
135    /// is open now.
136    pub fn record_failure(&self, provider: &str, now: Instant) -> bool {
137        let mut states = self.states();
138        let state = states.entry(provider.to_owned()).or_default();
139        state.failures = state.failures.saturating_add(1);
140        if state.failures >= BREAKER_THRESHOLD {
141            state.open_until = Some(now + BREAKER_COOLDOWN);
142            return true;
143        }
144        false
145    }
146}
147
148/// A chat model that tries its candidates in order (see the module docs).
149/// `request.model` is replaced by each candidate's model.
150pub struct FailoverModel {
151    candidates: Vec<Candidate>,
152    breakers: Arc<Breakers>,
153    clock: Arc<dyn Clock>,
154    last_attempt: bool,
155    headers_timeout: Duration,
156}
157
158impl std::fmt::Debug for FailoverModel {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.debug_struct("FailoverModel").field("candidates", &self.candidates).finish_non_exhaustive()
161    }
162}
163
164impl FailoverModel {
165    /// `candidates`: the primary first. `last_attempt`: whether the node
166    /// retries no more after this attempt (rate limits then fail over).
167    pub fn new(candidates: Vec<Candidate>, breakers: Arc<Breakers>, clock: Arc<dyn Clock>, last_attempt: bool) -> Self {
168        Self { candidates, breakers, clock, last_attempt, headers_timeout: HEADERS_TIMEOUT }
169    }
170
171    /// Change how long a candidate may take to answer (tests).
172    pub fn with_headers_timeout(mut self, timeout: Duration) -> Self {
173        self.headers_timeout = timeout;
174        self
175    }
176
177    /// Start the call on `candidate`, up to its first token. `Ok` holds the
178    /// deltas seen before it (usage, warnings) and the rest of the stream.
179    async fn start(
180        &self,
181        candidate: &Candidate,
182        request: ChatRequest,
183        has_next: bool,
184    ) -> Result<(Vec<ChatDelta>, ChatStream), LlmError> {
185        let call = candidate.chat.chat(request);
186        let mut stream = if has_next && self.clock.supports_timers() {
187            let timeout = self.clock.sleep(self.headers_timeout);
188            match futures::future::select(call, timeout).await {
189                futures::future::Either::Left((result, _)) => result?,
190                futures::future::Either::Right(((), _)) => {
191                    return Err(LlmError::Network(format!(
192                        "no answer within {} s",
193                        self.headers_timeout.as_secs_f64()
194                    )));
195                }
196            }
197        } else {
198            call.await?
199        };
200        let mut before = Vec::new();
201        while let Some(item) = stream.next().await {
202            let delta = item?;
203            let token = matches!(delta, ChatDelta::Text(_) | ChatDelta::Reasoning(_) | ChatDelta::ToolCall { .. });
204            before.push(delta);
205            if token {
206                break;
207            }
208        }
209        Ok((before, stream))
210    }
211}
212
213impl ChatModel for FailoverModel {
214    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
215        Box::pin(async move {
216            let mut failed: Vec<FailedModel> = Vec::new();
217            let last = self.candidates.len().saturating_sub(1);
218            for (index, candidate) in self.candidates.iter().enumerate() {
219                let has_next = index < last;
220                if has_next && !self.breakers.allows(&candidate.breaker_key, Instant::now()) {
221                    failed.push(FailedModel {
222                        provider: candidate.provider.clone(),
223                        model: candidate.model.clone(),
224                        reason: format!("skipped: `{}` failed repeatedly just before", candidate.provider),
225                    });
226                    continue;
227                }
228                let mut attempt = request.clone();
229                attempt.model.clone_from(&candidate.model);
230                match self.start(candidate, attempt, has_next).await {
231                    Ok((before, rest)) => {
232                        self.breakers.record_success(&candidate.breaker_key);
233                        let report = (!failed.is_empty()).then(|| {
234                            ChatDelta::Failover(FailoverReport {
235                                provider: candidate.provider.clone(),
236                                model: candidate.model.clone(),
237                                failed: std::mem::take(&mut failed),
238                            })
239                        });
240                        let head = report.into_iter().chain(before).map(Ok);
241                        return Ok(Box::pin(futures::stream::iter(head).chain(rest)) as ChatStream);
242                    }
243                    Err(error) => {
244                        if is_outage(&error) {
245                            self.breakers.record_failure(&candidate.breaker_key, Instant::now());
246                        }
247                        if !has_next || !fails_over(&error, self.last_attempt) {
248                            return Err(explain(error, candidate, &failed));
249                        }
250                        failed.push(FailedModel {
251                            provider: candidate.provider.clone(),
252                            model: candidate.model.clone(),
253                            reason: error.to_string(),
254                        });
255                    }
256                }
257            }
258            Err(LlmError::Config("no model to call".into()))
259        })
260    }
261
262    fn default_max_tokens(&self) -> Option<u32> {
263        self.candidates.first().and_then(|c| c.chat.default_max_tokens())
264    }
265}
266
267/// `error` of `candidate`, naming it and the models left before it.
268fn explain(error: LlmError, candidate: &Candidate, failed: &[FailedModel]) -> LlmError {
269    let mut prefix = format!("{}/{}: ", candidate.provider, candidate.model);
270    if !failed.is_empty() {
271        let earlier: Vec<String> =
272            failed.iter().map(|f| format!("{}/{} ({})", f.provider, f.model, f.reason)).collect();
273        prefix = format!("after {}; {prefix}", earlier.join("; "));
274    }
275    let with = |message: String| format!("{prefix}{message}");
276    match error {
277        LlmError::Auth(m) => LlmError::Auth(with(m)),
278        LlmError::RateLimit { message, retry_after_ms } => {
279            LlmError::RateLimit { message: with(message), retry_after_ms }
280        }
281        LlmError::ContextLength(m) => LlmError::ContextLength(with(m)),
282        LlmError::BadRequest(m) => LlmError::BadRequest(with(m)),
283        LlmError::Server { status, message } => LlmError::Server { status, message: with(message) },
284        LlmError::Network(m) => LlmError::Network(with(m)),
285        LlmError::Decode(m) => LlmError::Decode(with(m)),
286        LlmError::Config(m) => LlmError::Config(with(m)),
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use crate::mock::MockModel;
294    use crate::types::collect;
295    use graphrt_core::node::NoTimerClock;
296
297    fn candidate(provider: &str, model: &str, chat: Arc<dyn ChatModel>) -> Candidate {
298        Candidate { provider: provider.into(), model: model.into(), breaker_key: provider.into(), chat }
299    }
300
301    fn failover(candidates: Vec<Candidate>, breakers: &Arc<Breakers>, last_attempt: bool) -> FailoverModel {
302        FailoverModel::new(candidates, Arc::clone(breakers), Arc::new(NoTimerClock), last_attempt)
303    }
304
305    fn server_error() -> LlmError {
306        LlmError::Server { status: 503, message: "unavailable".into() }
307    }
308
309    async fn ask(model: &FailoverModel) -> Result<crate::ChatResponse, LlmError> {
310        let stream = model.chat(ChatRequest::new("ignored", vec![crate::Message::user("hi")])).await?;
311        collect(stream, |_| {}).await
312    }
313
314    #[tokio::test]
315    async fn infrastructure_errors_move_on_and_name_the_model_that_answered() {
316        for error in [server_error(), LlmError::Network("connection refused".into())] {
317            let primary = Arc::new(MockModel::default());
318            primary.push_error(error.clone());
319            let backup = Arc::new(MockModel::new(vec![MockModel::text("from backup")]));
320            let breakers = Arc::new(Breakers::default());
321            let model = failover(
322                vec![
323                    candidate("openai", "gpt-4o-mini", primary.clone()),
324                    candidate("azure-openai", "dep", backup.clone()),
325                ],
326                &breakers,
327                false,
328            );
329            let response = ask(&model).await.unwrap();
330            assert_eq!(response.text, "from backup");
331            let report = response.failover.unwrap();
332            assert_eq!((report.provider.as_str(), report.model.as_str()), ("azure-openai", "dep"));
333            assert_eq!(report.failed[0].reason, error.to_string());
334            assert_eq!(primary.requests()[0].model, "gpt-4o-mini");
335            assert_eq!(backup.requests()[0].model, "dep");
336        }
337    }
338
339    #[tokio::test]
340    async fn request_errors_never_move_on() {
341        for error in [
342            LlmError::Auth("invalid api key".into()),
343            LlmError::BadRequest("invalid schema".into()),
344            LlmError::ContextLength("too long".into()),
345        ] {
346            let primary = Arc::new(MockModel::default());
347            primary.push_error(error.clone());
348            let backup = Arc::new(MockModel::new(vec![MockModel::text("unused")]));
349            let breakers = Arc::new(Breakers::default());
350            let model = failover(
351                vec![candidate("openai", "m", primary), candidate("anthropic", "c", backup.clone())],
352                &breakers,
353                true,
354            );
355            let got = ask(&model).await.unwrap_err();
356            assert_eq!(got.kind(), error.kind());
357            assert!(got.to_string().contains("openai/m: "), "{got}");
358            assert!(backup.requests().is_empty());
359            assert!(breakers.allows("openai", Instant::now()));
360        }
361    }
362
363    #[tokio::test]
364    async fn a_rate_limit_moves_on_only_when_the_node_retries_no_more() {
365        let limited = || LlmError::RateLimit { message: "slow down".into(), retry_after_ms: Some(1000) };
366        let primary = Arc::new(MockModel::default());
367        primary.push_error(limited());
368        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
369        let breakers = Arc::new(Breakers::default());
370        let retried = failover(
371            vec![candidate("openai", "m", primary.clone()), candidate("b", "m", backup.clone())],
372            &breakers,
373            false,
374        );
375        let error = ask(&retried).await.unwrap_err();
376        assert!(matches!(error, LlmError::RateLimit { retry_after_ms: Some(1000), .. }), "{error:?}");
377        assert!(backup.requests().is_empty());
378
379        primary.push_error(limited());
380        let last = failover(vec![candidate("openai", "m", primary), candidate("b", "m", backup)], &breakers, true);
381        assert_eq!(ask(&last).await.unwrap().text, "b");
382    }
383
384    #[tokio::test]
385    async fn every_candidate_failing_names_them_all() {
386        let primary = Arc::new(MockModel::default());
387        primary.push_error(server_error());
388        let backup = Arc::new(MockModel::default());
389        backup.push_error(LlmError::Network("timed out".into()));
390        let breakers = Arc::new(Breakers::default());
391        let model =
392            failover(vec![candidate("openai", "a", primary), candidate("anthropic", "b", backup)], &breakers, true);
393        let error = ask(&model).await.unwrap_err();
394        assert_eq!(error.kind(), "model_network");
395        let text = error.to_string();
396        assert!(text.contains("after openai/a (server error (503): unavailable); anthropic/b: timed out"), "{text}");
397    }
398
399    #[tokio::test]
400    async fn the_breaker_skips_a_failing_provider_until_its_cooldown_ends() {
401        let breakers = Arc::new(Breakers::default());
402        let primary = Arc::new(MockModel::default());
403        let backup = Arc::new(MockModel::default());
404        for _ in 0..BREAKER_THRESHOLD {
405            primary.push_error(server_error());
406            backup.push(MockModel::text("b"));
407            let model = failover(
408                vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
409                &breakers,
410                true,
411            );
412            assert_eq!(ask(&model).await.unwrap().text, "b");
413        }
414        assert_eq!(primary.requests().len(), 3);
415        assert!(!breakers.allows("openai", Instant::now()));
416
417        // Open: the primary is not called at all.
418        backup.push(MockModel::text("b"));
419        let model = failover(
420            vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
421            &breakers,
422            true,
423        );
424        let response = ask(&model).await.unwrap();
425        assert_eq!(primary.requests().len(), 3);
426        assert!(response.failover.unwrap().failed[0].reason.starts_with("skipped"));
427
428        // After the cooldown one trial is let through; a success closes the breaker.
429        assert!(breakers.allows("openai", Instant::now() + BREAKER_COOLDOWN));
430        breakers.record_success("openai");
431        primary.push(MockModel::text("a"));
432        let model =
433            failover(vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup)], &breakers, true);
434        let response = ask(&model).await.unwrap();
435        assert_eq!(response.text, "a");
436        assert!(response.failover.is_none());
437    }
438
439    #[tokio::test]
440    async fn a_failed_trial_reopens_the_breaker_at_once() {
441        let breakers = Breakers::default();
442        let now = Instant::now();
443        for _ in 0..BREAKER_THRESHOLD {
444            breakers.record_failure("p", now);
445        }
446        let later = now + BREAKER_COOLDOWN;
447        assert!(breakers.allows("p", later));
448        assert!(breakers.record_failure("p", later));
449        assert!(!breakers.allows("p", later + Duration::from_secs(1)));
450    }
451
452    #[tokio::test]
453    async fn the_last_candidate_is_tried_even_with_its_breaker_open() {
454        let breakers = Arc::new(Breakers::default());
455        for _ in 0..BREAKER_THRESHOLD {
456            breakers.record_failure("openai", Instant::now());
457        }
458        let only = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
459        let model = failover(vec![candidate("openai", "a", only)], &breakers, true);
460        assert_eq!(ask(&model).await.unwrap().text, "ok");
461        assert!(breakers.allows("openai", Instant::now()));
462    }
463
464    fn broken_after(deltas: Vec<ChatDelta>) -> Arc<dyn ChatModel> {
465        #[derive(Debug)]
466        struct Broken(Mutex<Option<Vec<ChatDelta>>>);
467        impl ChatModel for Broken {
468            fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
469                let deltas = self.0.lock().unwrap().take().unwrap_or_default();
470                Box::pin(async move {
471                    let items = deltas.into_iter().map(Ok).chain([Err(LlmError::Network("connection reset".into()))]);
472                    Ok(Box::pin(futures::stream::iter(items)) as ChatStream)
473                })
474            }
475        }
476        Arc::new(Broken(Mutex::new(Some(deltas))))
477    }
478
479    #[tokio::test]
480    async fn a_stream_cut_before_its_first_token_moves_on() {
481        let usage = graphrt_core::event::Usage { prompt_tokens: 3, completion_tokens: 0, total_tokens: 3 };
482        let primary = broken_after(vec![ChatDelta::Usage(usage)]);
483        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
484        let breakers = Arc::new(Breakers::default());
485        let model = failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup)], &breakers, true);
486        let mut streamed = Vec::new();
487        let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
488        let response = collect(stream, |d| streamed.push(d)).await.unwrap();
489        assert_eq!(response.text, "b");
490        // Nothing of the cut stream reached the caller.
491        assert!(matches!(streamed[0], ChatDelta::Failover(_)));
492        assert_eq!(response.usage.prompt_tokens, 1);
493    }
494
495    #[tokio::test]
496    async fn a_stream_cut_after_its_first_token_is_the_calls_error() {
497        let primary = broken_after(vec![ChatDelta::Text("Hel".into())]);
498        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
499        let breakers = Arc::new(Breakers::default());
500        let model =
501            failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup.clone())], &breakers, true);
502        let mut streamed = Vec::new();
503        let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
504        let error = collect(stream, |d| streamed.push(d)).await.unwrap_err();
505        assert_eq!(error, LlmError::Network("connection reset".into()));
506        assert_eq!(streamed, vec![ChatDelta::Text("Hel".into())]);
507        assert!(backup.requests().is_empty());
508    }
509
510    #[tokio::test]
511    async fn a_provider_that_does_not_answer_in_time_is_left() {
512        #[derive(Debug)]
513        struct Hangs;
514        impl ChatModel for Hangs {
515            fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
516                Box::pin(futures::future::pending())
517            }
518        }
519        #[derive(Debug)]
520        struct TokioClock;
521        impl Clock for TokioClock {
522            fn now_ms(&self) -> u64 {
523                0
524            }
525            fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
526                Box::pin(tokio::time::sleep(duration))
527            }
528        }
529        let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
530        let model = FailoverModel::new(
531            vec![candidate("openai", "a", Arc::new(Hangs)), candidate("azure", "b", backup)],
532            Arc::new(Breakers::default()),
533            Arc::new(TokioClock),
534            true,
535        )
536        .with_headers_timeout(Duration::from_millis(20));
537        let response = ask(&model).await.unwrap();
538        assert_eq!(response.text, "b");
539        assert!(response.failover.unwrap().failed[0].reason.contains("no answer within"));
540    }
541}