use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use futures::StreamExt;
use futures::future::BoxFuture;
use graphrt_core::node::Clock;
use serde::{Deserialize, Serialize};
use crate::error::LlmError;
use crate::types::{ChatDelta, ChatModel, ChatRequest, ChatStream};
pub const BREAKER_THRESHOLD: u32 = 3;
pub const BREAKER_COOLDOWN: Duration = Duration::from_secs(30);
pub const HEADERS_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Clone)]
pub struct Candidate {
pub provider: String,
pub model: String,
pub breaker_key: String,
pub chat: Arc<dyn ChatModel>,
}
impl std::fmt::Debug for Candidate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.provider, self.model)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailedModel {
pub provider: String,
pub model: String,
pub reason: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailoverReport {
pub provider: String,
pub model: String,
pub failed: Vec<FailedModel>,
}
pub fn fails_over(error: &LlmError, last_attempt: bool) -> bool {
match error {
LlmError::Server { .. } | LlmError::Network(_) => true,
LlmError::RateLimit { .. } => last_attempt,
_ => false,
}
}
fn is_outage(error: &LlmError) -> bool {
matches!(error, LlmError::Server { .. } | LlmError::Network(_) | LlmError::RateLimit { .. })
}
#[derive(Debug, Default, Clone, Copy)]
struct BreakerState {
failures: u32,
open_until: Option<Instant>,
}
#[derive(Debug, Default)]
pub struct Breakers {
states: Mutex<HashMap<String, BreakerState>>,
}
impl Breakers {
fn states(&self) -> std::sync::MutexGuard<'_, HashMap<String, BreakerState>> {
self.states.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn allows(&self, provider: &str, now: Instant) -> bool {
self.states().get(provider).and_then(|s| s.open_until).is_none_or(|until| now >= until)
}
pub fn record_success(&self, provider: &str) {
self.states().remove(provider);
}
pub fn record_failure(&self, provider: &str, now: Instant) -> bool {
let mut states = self.states();
let state = states.entry(provider.to_owned()).or_default();
state.failures = state.failures.saturating_add(1);
if state.failures >= BREAKER_THRESHOLD {
state.open_until = Some(now + BREAKER_COOLDOWN);
return true;
}
false
}
}
pub struct FailoverModel {
candidates: Vec<Candidate>,
breakers: Arc<Breakers>,
clock: Arc<dyn Clock>,
last_attempt: bool,
headers_timeout: Duration,
}
impl std::fmt::Debug for FailoverModel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FailoverModel").field("candidates", &self.candidates).finish_non_exhaustive()
}
}
impl FailoverModel {
pub fn new(candidates: Vec<Candidate>, breakers: Arc<Breakers>, clock: Arc<dyn Clock>, last_attempt: bool) -> Self {
Self { candidates, breakers, clock, last_attempt, headers_timeout: HEADERS_TIMEOUT }
}
pub fn with_headers_timeout(mut self, timeout: Duration) -> Self {
self.headers_timeout = timeout;
self
}
async fn start(
&self,
candidate: &Candidate,
request: ChatRequest,
has_next: bool,
) -> Result<(Vec<ChatDelta>, ChatStream), LlmError> {
let call = candidate.chat.chat(request);
let mut stream = if has_next && self.clock.supports_timers() {
let timeout = self.clock.sleep(self.headers_timeout);
match futures::future::select(call, timeout).await {
futures::future::Either::Left((result, _)) => result?,
futures::future::Either::Right(((), _)) => {
return Err(LlmError::Network(format!(
"no answer within {} s",
self.headers_timeout.as_secs_f64()
)));
}
}
} else {
call.await?
};
let mut before = Vec::new();
while let Some(item) = stream.next().await {
let delta = item?;
let token = matches!(delta, ChatDelta::Text(_) | ChatDelta::Reasoning(_) | ChatDelta::ToolCall { .. });
before.push(delta);
if token {
break;
}
}
Ok((before, stream))
}
}
impl ChatModel for FailoverModel {
fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
Box::pin(async move {
let mut failed: Vec<FailedModel> = Vec::new();
let last = self.candidates.len().saturating_sub(1);
for (index, candidate) in self.candidates.iter().enumerate() {
let has_next = index < last;
if has_next && !self.breakers.allows(&candidate.breaker_key, Instant::now()) {
failed.push(FailedModel {
provider: candidate.provider.clone(),
model: candidate.model.clone(),
reason: format!("skipped: `{}` failed repeatedly just before", candidate.provider),
});
continue;
}
let mut attempt = request.clone();
attempt.model.clone_from(&candidate.model);
match self.start(candidate, attempt, has_next).await {
Ok((before, rest)) => {
self.breakers.record_success(&candidate.breaker_key);
let report = (!failed.is_empty()).then(|| {
ChatDelta::Failover(FailoverReport {
provider: candidate.provider.clone(),
model: candidate.model.clone(),
failed: std::mem::take(&mut failed),
})
});
let head = report.into_iter().chain(before).map(Ok);
return Ok(Box::pin(futures::stream::iter(head).chain(rest)) as ChatStream);
}
Err(error) => {
if is_outage(&error) {
self.breakers.record_failure(&candidate.breaker_key, Instant::now());
}
if !has_next || !fails_over(&error, self.last_attempt) {
return Err(explain(error, candidate, &failed));
}
failed.push(FailedModel {
provider: candidate.provider.clone(),
model: candidate.model.clone(),
reason: error.to_string(),
});
}
}
}
Err(LlmError::Config("no model to call".into()))
})
}
fn default_max_tokens(&self) -> Option<u32> {
self.candidates.first().and_then(|c| c.chat.default_max_tokens())
}
}
fn explain(error: LlmError, candidate: &Candidate, failed: &[FailedModel]) -> LlmError {
let mut prefix = format!("{}/{}: ", candidate.provider, candidate.model);
if !failed.is_empty() {
let earlier: Vec<String> =
failed.iter().map(|f| format!("{}/{} ({})", f.provider, f.model, f.reason)).collect();
prefix = format!("after {}; {prefix}", earlier.join("; "));
}
let with = |message: String| format!("{prefix}{message}");
match error {
LlmError::Auth(m) => LlmError::Auth(with(m)),
LlmError::RateLimit { message, retry_after_ms } => {
LlmError::RateLimit { message: with(message), retry_after_ms }
}
LlmError::ContextLength(m) => LlmError::ContextLength(with(m)),
LlmError::BadRequest(m) => LlmError::BadRequest(with(m)),
LlmError::Server { status, message } => LlmError::Server { status, message: with(message) },
LlmError::Network(m) => LlmError::Network(with(m)),
LlmError::Decode(m) => LlmError::Decode(with(m)),
LlmError::Config(m) => LlmError::Config(with(m)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::MockModel;
use crate::types::collect;
use graphrt_core::node::NoTimerClock;
fn candidate(provider: &str, model: &str, chat: Arc<dyn ChatModel>) -> Candidate {
Candidate { provider: provider.into(), model: model.into(), breaker_key: provider.into(), chat }
}
fn failover(candidates: Vec<Candidate>, breakers: &Arc<Breakers>, last_attempt: bool) -> FailoverModel {
FailoverModel::new(candidates, Arc::clone(breakers), Arc::new(NoTimerClock), last_attempt)
}
fn server_error() -> LlmError {
LlmError::Server { status: 503, message: "unavailable".into() }
}
async fn ask(model: &FailoverModel) -> Result<crate::ChatResponse, LlmError> {
let stream = model.chat(ChatRequest::new("ignored", vec![crate::Message::user("hi")])).await?;
collect(stream, |_| {}).await
}
#[tokio::test]
async fn infrastructure_errors_move_on_and_name_the_model_that_answered() {
for error in [server_error(), LlmError::Network("connection refused".into())] {
let primary = Arc::new(MockModel::default());
primary.push_error(error.clone());
let backup = Arc::new(MockModel::new(vec![MockModel::text("from backup")]));
let breakers = Arc::new(Breakers::default());
let model = failover(
vec![
candidate("openai", "gpt-4o-mini", primary.clone()),
candidate("azure-openai", "dep", backup.clone()),
],
&breakers,
false,
);
let response = ask(&model).await.unwrap();
assert_eq!(response.text, "from backup");
let report = response.failover.unwrap();
assert_eq!((report.provider.as_str(), report.model.as_str()), ("azure-openai", "dep"));
assert_eq!(report.failed[0].reason, error.to_string());
assert_eq!(primary.requests()[0].model, "gpt-4o-mini");
assert_eq!(backup.requests()[0].model, "dep");
}
}
#[tokio::test]
async fn request_errors_never_move_on() {
for error in [
LlmError::Auth("invalid api key".into()),
LlmError::BadRequest("invalid schema".into()),
LlmError::ContextLength("too long".into()),
] {
let primary = Arc::new(MockModel::default());
primary.push_error(error.clone());
let backup = Arc::new(MockModel::new(vec![MockModel::text("unused")]));
let breakers = Arc::new(Breakers::default());
let model = failover(
vec![candidate("openai", "m", primary), candidate("anthropic", "c", backup.clone())],
&breakers,
true,
);
let got = ask(&model).await.unwrap_err();
assert_eq!(got.kind(), error.kind());
assert!(got.to_string().contains("openai/m: "), "{got}");
assert!(backup.requests().is_empty());
assert!(breakers.allows("openai", Instant::now()));
}
}
#[tokio::test]
async fn a_rate_limit_moves_on_only_when_the_node_retries_no_more() {
let limited = || LlmError::RateLimit { message: "slow down".into(), retry_after_ms: Some(1000) };
let primary = Arc::new(MockModel::default());
primary.push_error(limited());
let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
let breakers = Arc::new(Breakers::default());
let retried = failover(
vec![candidate("openai", "m", primary.clone()), candidate("b", "m", backup.clone())],
&breakers,
false,
);
let error = ask(&retried).await.unwrap_err();
assert!(matches!(error, LlmError::RateLimit { retry_after_ms: Some(1000), .. }), "{error:?}");
assert!(backup.requests().is_empty());
primary.push_error(limited());
let last = failover(vec![candidate("openai", "m", primary), candidate("b", "m", backup)], &breakers, true);
assert_eq!(ask(&last).await.unwrap().text, "b");
}
#[tokio::test]
async fn every_candidate_failing_names_them_all() {
let primary = Arc::new(MockModel::default());
primary.push_error(server_error());
let backup = Arc::new(MockModel::default());
backup.push_error(LlmError::Network("timed out".into()));
let breakers = Arc::new(Breakers::default());
let model =
failover(vec![candidate("openai", "a", primary), candidate("anthropic", "b", backup)], &breakers, true);
let error = ask(&model).await.unwrap_err();
assert_eq!(error.kind(), "model_network");
let text = error.to_string();
assert!(text.contains("after openai/a (server error (503): unavailable); anthropic/b: timed out"), "{text}");
}
#[tokio::test]
async fn the_breaker_skips_a_failing_provider_until_its_cooldown_ends() {
let breakers = Arc::new(Breakers::default());
let primary = Arc::new(MockModel::default());
let backup = Arc::new(MockModel::default());
for _ in 0..BREAKER_THRESHOLD {
primary.push_error(server_error());
backup.push(MockModel::text("b"));
let model = failover(
vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
&breakers,
true,
);
assert_eq!(ask(&model).await.unwrap().text, "b");
}
assert_eq!(primary.requests().len(), 3);
assert!(!breakers.allows("openai", Instant::now()));
backup.push(MockModel::text("b"));
let model = failover(
vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup.clone())],
&breakers,
true,
);
let response = ask(&model).await.unwrap();
assert_eq!(primary.requests().len(), 3);
assert!(response.failover.unwrap().failed[0].reason.starts_with("skipped"));
assert!(breakers.allows("openai", Instant::now() + BREAKER_COOLDOWN));
breakers.record_success("openai");
primary.push(MockModel::text("a"));
let model =
failover(vec![candidate("openai", "a", primary.clone()), candidate("azure", "b", backup)], &breakers, true);
let response = ask(&model).await.unwrap();
assert_eq!(response.text, "a");
assert!(response.failover.is_none());
}
#[tokio::test]
async fn a_failed_trial_reopens_the_breaker_at_once() {
let breakers = Breakers::default();
let now = Instant::now();
for _ in 0..BREAKER_THRESHOLD {
breakers.record_failure("p", now);
}
let later = now + BREAKER_COOLDOWN;
assert!(breakers.allows("p", later));
assert!(breakers.record_failure("p", later));
assert!(!breakers.allows("p", later + Duration::from_secs(1)));
}
#[tokio::test]
async fn the_last_candidate_is_tried_even_with_its_breaker_open() {
let breakers = Arc::new(Breakers::default());
for _ in 0..BREAKER_THRESHOLD {
breakers.record_failure("openai", Instant::now());
}
let only = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
let model = failover(vec![candidate("openai", "a", only)], &breakers, true);
assert_eq!(ask(&model).await.unwrap().text, "ok");
assert!(breakers.allows("openai", Instant::now()));
}
fn broken_after(deltas: Vec<ChatDelta>) -> Arc<dyn ChatModel> {
#[derive(Debug)]
struct Broken(Mutex<Option<Vec<ChatDelta>>>);
impl ChatModel for Broken {
fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
let deltas = self.0.lock().unwrap().take().unwrap_or_default();
Box::pin(async move {
let items = deltas.into_iter().map(Ok).chain([Err(LlmError::Network("connection reset".into()))]);
Ok(Box::pin(futures::stream::iter(items)) as ChatStream)
})
}
}
Arc::new(Broken(Mutex::new(Some(deltas))))
}
#[tokio::test]
async fn a_stream_cut_before_its_first_token_moves_on() {
let usage = graphrt_core::event::Usage { prompt_tokens: 3, completion_tokens: 0, total_tokens: 3 };
let primary = broken_after(vec![ChatDelta::Usage(usage)]);
let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
let breakers = Arc::new(Breakers::default());
let model = failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup)], &breakers, true);
let mut streamed = Vec::new();
let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
let response = collect(stream, |d| streamed.push(d)).await.unwrap();
assert_eq!(response.text, "b");
assert!(matches!(streamed[0], ChatDelta::Failover(_)));
assert_eq!(response.usage.prompt_tokens, 1);
}
#[tokio::test]
async fn a_stream_cut_after_its_first_token_is_the_calls_error() {
let primary = broken_after(vec![ChatDelta::Text("Hel".into())]);
let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
let breakers = Arc::new(Breakers::default());
let model =
failover(vec![candidate("openai", "a", primary), candidate("azure", "b", backup.clone())], &breakers, true);
let mut streamed = Vec::new();
let stream = model.chat(ChatRequest::new("x", vec![])).await.unwrap();
let error = collect(stream, |d| streamed.push(d)).await.unwrap_err();
assert_eq!(error, LlmError::Network("connection reset".into()));
assert_eq!(streamed, vec![ChatDelta::Text("Hel".into())]);
assert!(backup.requests().is_empty());
}
#[tokio::test]
async fn a_provider_that_does_not_answer_in_time_is_left() {
#[derive(Debug)]
struct Hangs;
impl ChatModel for Hangs {
fn chat(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
Box::pin(futures::future::pending())
}
}
#[derive(Debug)]
struct TokioClock;
impl Clock for TokioClock {
fn now_ms(&self) -> u64 {
0
}
fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
Box::pin(tokio::time::sleep(duration))
}
}
let backup = Arc::new(MockModel::new(vec![MockModel::text("b")]));
let model = FailoverModel::new(
vec![candidate("openai", "a", Arc::new(Hangs)), candidate("azure", "b", backup)],
Arc::new(Breakers::default()),
Arc::new(TokioClock),
true,
)
.with_headers_timeout(Duration::from_millis(20));
let response = ask(&model).await.unwrap();
assert_eq!(response.text, "b");
assert!(response.failover.unwrap().failed[0].reason.contains("no answer within"));
}
}