Skip to main content

strands/models/routing/
fallback_strategy.rs

1//! The default routing strategy.
2
3use async_trait::async_trait;
4
5use super::router::RoutingCandidate;
6use super::strategy::{RoutingAttempt, RoutingContext, RoutingStrategy};
7use crate::error::BoxError;
8
9/// Selects the healthiest candidate not yet tried since the last success (`FallbackStrategy`):
10/// the fewest failures, ties broken by declaration order. A success clears that candidate's
11/// failure count.
12#[derive(Debug, Clone, Copy, Default)]
13#[non_exhaustive]
14pub struct FallbackStrategy;
15
16impl FallbackStrategy {
17    /// The strategy.
18    #[must_use]
19    pub fn new() -> Self {
20        Self
21    }
22}
23
24fn attempts_since_success(attempts: &[RoutingAttempt]) -> &[RoutingAttempt] {
25    match attempts.iter().rposition(|attempt| attempt.exception.is_none()) {
26        Some(index) => &attempts[index + 1..],
27        None => attempts,
28    }
29}
30
31#[async_trait]
32impl RoutingStrategy for FallbackStrategy {
33    async fn select(&self, context: &RoutingContext) -> Result<Option<RoutingCandidate>, BoxError> {
34        let mut failures: Vec<(&RoutingCandidate, usize)> = Vec::new();
35        for attempt in &context.attempts {
36            let position = failures
37                .iter()
38                .position(|(candidate, _)| *candidate == &attempt.candidate);
39            match (attempt.exception.is_some(), position) {
40                (false, Some(index)) => {
41                    failures.remove(index);
42                }
43                (true, Some(index)) => failures[index].1 += 1,
44                (true, None) => failures.push((&attempt.candidate, 1)),
45                (false, None) => {}
46            }
47        }
48        let failures_of = |candidate: &RoutingCandidate| {
49            failures
50                .iter()
51                .find(|(failed, _)| *failed == candidate)
52                .map_or(0, |(_, count)| *count)
53        };
54        let tried = attempts_since_success(&context.attempts);
55        let best = context
56            .candidates
57            .iter()
58            .filter(|candidate| !tried.iter().any(|attempt| &attempt.candidate == *candidate))
59            .fold(None, |best: Option<&RoutingCandidate>, candidate| match best {
60                Some(best) if failures_of(candidate) >= failures_of(best) => Some(best),
61                _ => Some(candidate),
62            });
63        Ok(best.cloned())
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use std::sync::Arc;
70
71    use super::*;
72    use crate::models::routing::RoutingFailure;
73    use crate::testing::MockModel;
74
75    fn candidates(count: usize) -> Vec<RoutingCandidate> {
76        (0..count)
77            .map(|_| RoutingCandidate::from(Arc::new(MockModel::new()) as Arc<dyn crate::models::Model>))
78            .collect()
79    }
80
81    fn failed(candidate: &RoutingCandidate) -> RoutingAttempt {
82        RoutingAttempt::failure(candidate.clone(), RoutingFailure::new("Error", "down"))
83    }
84
85    fn succeeded(candidate: &RoutingCandidate) -> RoutingAttempt {
86        RoutingAttempt::success(candidate.clone())
87    }
88
89    async fn select(candidates: &[RoutingCandidate], attempts: Vec<RoutingAttempt>) -> Option<RoutingCandidate> {
90        let context = RoutingContext::new(candidates.to_vec()).with_attempts(attempts);
91        FallbackStrategy.select(&context).await.unwrap()
92    }
93
94    #[tokio::test]
95    async fn uses_declaration_order_before_any_attempt() {
96        let all = candidates(2);
97        assert_eq!(select(&all, vec![]).await, Some(all[0].clone()));
98    }
99
100    #[tokio::test]
101    async fn advances_through_each_candidate_once_in_a_failure_round() {
102        let all = candidates(2);
103        assert_eq!(select(&all, vec![failed(&all[0])]).await, Some(all[1].clone()));
104        assert_eq!(select(&all, vec![failed(&all[0]), failed(&all[1])]).await, None);
105    }
106
107    #[tokio::test]
108    async fn rearms_after_success_while_retaining_other_candidates_failure_history() {
109        let all = candidates(3);
110        let attempts = vec![failed(&all[0]), succeeded(&all[1]), failed(&all[1])];
111        assert_eq!(select(&all, attempts).await, Some(all[2].clone()));
112    }
113
114    #[tokio::test]
115    async fn clears_a_successful_candidate_s_own_accumulated_failure_count() {
116        let all = candidates(3);
117        let attempts = vec![
118            failed(&all[0]),
119            failed(&all[0]),
120            failed(&all[1]),
121            succeeded(&all[0]),
122            failed(&all[2]),
123        ];
124        assert_eq!(select(&all, attempts).await, Some(all[0].clone()));
125    }
126
127    #[tokio::test]
128    async fn rearms_the_other_candidate_after_a_fallback_succeeds_and_later_fails() {
129        let all = candidates(2);
130        let attempts = vec![failed(&all[0]), succeeded(&all[1]), failed(&all[1])];
131        assert_eq!(select(&all, attempts).await, Some(all[0].clone()));
132    }
133}