Skip to main content

strands/retry/
model_retry_strategy.rs

1//! The model retry strategy trait and the retry orchestration around it.
2
3use std::time::Duration;
4
5use async_trait::async_trait;
6use futures::future::{Either, select};
7
8use super::retry_strategy::RetryDecision;
9use crate::cancel::CancelSignal;
10use crate::error::{Error, Result};
11
12/// What a [`ModelRetryStrategy`] sees of a failed model call.
13///
14/// The SDK builds it; fields may be added.
15#[derive(Debug, Clone, Copy)]
16#[non_exhaustive]
17pub struct ModelRetryContext<'a> {
18    /// The error the call failed with.
19    pub error: &'a Error,
20    /// The 1-based number of the attempt that failed, within the current retry budget.
21    pub attempt_count: u32,
22}
23
24impl<'a> ModelRetryContext<'a> {
25    /// Creates the context, for example to test a strategy.
26    pub fn new(error: &'a Error, attempt_count: u32) -> Self {
27        Self { error, attempt_count }
28    }
29}
30
31/// A policy for retrying failed model calls (`ModelRetryStrategy`).
32///
33/// An implementation answers whether to retry and how long to wait; the agent handles the rest:
34/// it skips the strategy when another hook already asked for a retry or the call succeeded, calls
35/// [`on_first_model_attempt`](ModelRetryStrategy::on_first_model_attempt) when a fresh retry
36/// budget starts, waits for the returned delay (ending early on cancellation) and then retries.
37///
38/// Instances usually carry per-budget state, so one instance belongs to one agent.
39#[async_trait]
40pub trait ModelRetryStrategy: Send + Sync + 'static {
41    /// A stable identifier for the strategy (`name`).
42    fn name(&self) -> &str;
43
44    /// The implementing type's name, such as `DefaultModelRetryStrategy`, which messages use. Provided;
45    /// implementors keep the default.
46    fn type_name(&self) -> &'static str {
47        short_type_name(std::any::type_name::<Self>())
48    }
49
50    /// Decides whether to retry the failed model call and how long to wait first.
51    ///
52    /// Called only for failed calls no other hook has already marked for retry.
53    ///
54    /// # Errors
55    ///
56    /// An error ends the invocation with it.
57    async fn compute_retry_decision(&self, context: &ModelRetryContext<'_>) -> Result<RetryDecision>;
58
59    /// Called when `attempt_count` is 1, at the start of a fresh retry budget: a new turn, or a
60    /// model router switching candidates. Strategies with per-budget state
61    /// clear it here; the default does nothing.
62    fn on_first_model_attempt(&self) {}
63}
64
65/// Waits between retry attempts.
66#[async_trait]
67pub(crate) trait Sleeper: Send + Sync {
68    /// Waits for `duration`.
69    async fn sleep(&self, duration: Duration);
70}
71
72/// The default [`Sleeper`], on the tokio timer.
73#[derive(Debug, Clone, Copy, Default)]
74pub(crate) struct TokioSleeper;
75
76#[async_trait]
77impl Sleeper for TokioSleeper {
78    async fn sleep(&self, duration: Duration) {
79        tokio::time::sleep(duration).await;
80    }
81}
82
83/// The outcome of one model attempt, as the retry orchestration sees it.
84#[derive(Debug, Clone, Copy)]
85pub(crate) struct ModelAttempt<'a> {
86    /// The error the call failed with; `None` on success.
87    pub(crate) error: Option<&'a Error>,
88    /// The 1-based number of this attempt within the current retry budget.
89    pub(crate) attempt_count: u32,
90    /// Whether another hook already asked for a retry.
91    pub(crate) retry: bool,
92    /// The invocation's cancel signal; cancellation ends the wait early.
93    pub(crate) cancel_signal: Option<&'a CancelSignal>,
94}
95
96/// Runs `strategy` for one model attempt and returns whether to retry.
97///
98/// Resets per-budget state on the first attempt before any short-circuit, leaves an existing retry
99/// request and successes alone, and waits for the decided delay before answering `true`.
100pub(crate) async fn retry_model(
101    strategy: &dyn ModelRetryStrategy,
102    attempt: ModelAttempt<'_>,
103    sleeper: &dyn Sleeper,
104) -> Result<bool> {
105    if attempt.attempt_count == 1 {
106        strategy.on_first_model_attempt();
107    }
108    if attempt.retry {
109        return Ok(true);
110    }
111    let Some(error) = attempt.error else {
112        return Ok(false);
113    };
114    let context = ModelRetryContext::new(error, attempt.attempt_count);
115    let RetryDecision::Retry { wait, .. } = strategy.compute_retry_decision(&context).await? else {
116        return Ok(false);
117    };
118    sleep(sleeper, wait, attempt.cancel_signal).await;
119    Ok(true)
120}
121
122/// Waits for `duration`, or until `cancel_signal` fires, so the loop can recheck cancellation
123/// before another attempt.
124async fn sleep(sleeper: &dyn Sleeper, duration: Duration, cancel_signal: Option<&CancelSignal>) {
125    let Some(signal) = cancel_signal else {
126        sleeper.sleep(duration).await;
127        return;
128    };
129    if signal.is_cancelled() {
130        return;
131    }
132    let wait = sleeper.sleep(duration);
133    let cancelled = signal.cancelled();
134    futures::pin_mut!(cancelled);
135    if let Either::Right(((), _)) = select(wait, cancelled).await {
136        tracing::debug!("retry wait ended early | cancellation requested");
137    }
138}
139
140/// The last path segment of a type name, without generic arguments.
141fn short_type_name(full: &'static str) -> &'static str {
142    let base = full.split('<').next().unwrap_or(full);
143    base.rsplit("::").next().unwrap_or(base)
144}
145
146#[cfg(test)]
147mod tests {
148    #[test]
149    fn type_names_drop_the_module_path_and_generics() {
150        assert_eq!(
151            super::short_type_name("strands::retry::DefaultModelRetryStrategy"),
152            "DefaultModelRetryStrategy"
153        );
154        assert_eq!(super::short_type_name("a::Wrap<b::Inner>"), "Wrap");
155    }
156
157    use super::*;
158
159    #[tokio::test(start_paused = true)]
160    async fn the_tokio_sleeper_waits_on_the_tokio_timer() {
161        let started = tokio::time::Instant::now();
162        TokioSleeper.sleep(Duration::from_secs(30)).await;
163        assert!(started.elapsed() >= Duration::from_secs(30));
164    }
165}