Skip to main content

a2a_protocol_server/tool_loop/
retry.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`ModelRetry`]: sending a rate-limited turn again, after the provider's
5//! `Retry-After`, inside the caller's budget (audit H17, ADR 0048).
6
7use std::time::{Duration, SystemTime};
8
9use a2a_protocol_types::budget::BudgetHandle;
10
11/// The longest `Retry-After` read from a provider. A header asking for more
12/// is read as this, and then refused by any [`ModelRetry::max_delay`] below
13/// it, so a hostile or broken header cannot park a turn. The client crate
14/// clamps the same header to the same hour.
15const RETRY_AFTER_CEILING: Duration = Duration::from_secs(3600);
16
17/// How a loop retries a turn the provider refused as rate limited
18/// ([`ModelError::RateLimited`](super::ModelError::RateLimited)); set with
19/// [`ToolLoop::with_model_retry`](super::ToolLoop::with_model_retry).
20///
21/// No other failure is retried. Each wait is:
22///
23/// * the provider's `Retry-After`, lengthened by up to a quarter at random,
24///   so loops refused together do not come back together, and never more
25///   than [`max_delay`](Self::max_delay); a `Retry-After` longer than
26///   `max_delay` is not waited for, and the run fails with the 429;
27/// * with no `Retry-After`, `base_delay` doubled for each retry already made,
28///   at most `max_delay`, and then between half and all of that at random.
29///
30/// A wait longer than the budget's remaining time (ADR 0023) is not made
31/// either: the run fails with the 429 then, rather than after the deadline.
32///
33/// ```rust
34/// use std::time::Duration;
35/// use a2a_protocol_server::tool_loop::ModelRetry;
36///
37/// let retry = ModelRetry::new()
38///     .with_max_retries(5)
39///     .with_max_delay(Duration::from_secs(10));
40/// assert_eq!(retry.max_retries(), 5);
41/// assert_eq!(retry.base_delay(), Duration::from_millis(500));
42/// ```
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct ModelRetry {
45    max_retries: u32,
46    base_delay: Duration,
47    max_delay: Duration,
48}
49
50impl ModelRetry {
51    /// Three retries, from 500 ms, waiting at most 30 s each.
52    #[must_use]
53    pub const fn new() -> Self {
54        Self {
55            max_retries: 3,
56            base_delay: Duration::from_millis(500),
57            max_delay: Duration::from_secs(30),
58        }
59    }
60
61    /// Sets how many times one turn may be sent again.
62    #[must_use]
63    pub const fn with_max_retries(mut self, max_retries: u32) -> Self {
64        self.max_retries = max_retries;
65        self
66    }
67
68    /// Sets the first wait when the provider gave no `Retry-After`.
69    #[must_use]
70    pub const fn with_base_delay(mut self, base_delay: Duration) -> Self {
71        self.base_delay = base_delay;
72        self
73    }
74
75    /// Sets the longest wait.
76    #[must_use]
77    pub const fn with_max_delay(mut self, max_delay: Duration) -> Self {
78        self.max_delay = max_delay;
79        self
80    }
81
82    /// How many times one turn may be sent again.
83    #[must_use]
84    pub const fn max_retries(&self) -> u32 {
85        self.max_retries
86    }
87
88    /// The first wait when the provider gave no `Retry-After`.
89    #[must_use]
90    pub const fn base_delay(&self) -> Duration {
91        self.base_delay
92    }
93
94    /// The longest wait.
95    #[must_use]
96    pub const fn max_delay(&self) -> Duration {
97        self.max_delay
98    }
99
100    /// The wait before retry number `retries + 1`, or `None` when the turn
101    /// is not to be sent again: the retries are spent, the provider asked
102    /// for longer than `max_delay`, or the budget ends before the wait
103    /// would.
104    pub(super) fn next_wait(
105        &self,
106        retries: u32,
107        retry_after: Option<Duration>,
108        budget: Option<&BudgetHandle>,
109    ) -> Option<Duration> {
110        let wait = self.wait_for(retries, retry_after, random_bits())?;
111        // Not a wait that ends at the deadline either: the turn would start
112        // with nothing left of the budget.
113        let left = budget.and_then(BudgetHandle::remaining_time);
114        if left.is_some_and(|left| wait >= left) {
115            return None;
116        }
117        Some(wait)
118    }
119
120    /// [`next_wait`](Self::next_wait) without the budget, with the random
121    /// draw given, so the arithmetic is tested exactly.
122    fn wait_for(&self, retries: u32, retry_after: Option<Duration>, bits: u64) -> Option<Duration> {
123        if retries >= self.max_retries {
124            return None;
125        }
126        if let Some(after) = retry_after {
127            if after > self.max_delay {
128                return None;
129            }
130            let spread = portion(after / 4, draw(bits));
131            return Some(after.saturating_add(spread).min(self.max_delay));
132        }
133        let doubled = self
134            .base_delay
135            .checked_mul(1u32.checked_shl(retries).unwrap_or(u32::MAX))
136            .unwrap_or(self.max_delay)
137            .min(self.max_delay);
138        let half = doubled / 2;
139        Some(half + portion(doubled.saturating_sub(half), draw(bits)))
140    }
141}
142
143impl Default for ModelRetry {
144    /// [`ModelRetry::new`].
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150/// The high 32 bits of a 64-bit draw.
151const fn draw(bits: u64) -> u32 {
152    let [a, b, c, d, ..] = bits.to_be_bytes();
153    u32::from_be_bytes([a, b, c, d])
154}
155
156/// `draw / u32::MAX` of `d`, rounded down to the nanosecond: none of it at
157/// a draw of `0`, all of it at `u32::MAX`. Integer arithmetic, so the
158/// jitter is exact and needs no float cast. The product cannot overflow:
159/// `Duration::MAX` is under 2^94 nanoseconds and the draw under 2^32.
160fn portion(d: Duration, draw: u32) -> Duration {
161    let nanos = d.as_nanos() * u128::from(draw) / u128::from(u32::MAX);
162    u64::try_from(nanos).map_or(d, Duration::from_nanos)
163}
164
165/// A random draw, from the standard library's per-process hasher keys, as
166/// the client's backoff jitter draws one.
167fn random_bits() -> u64 {
168    use std::hash::{BuildHasher, Hasher};
169    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
170    hasher.write_u8(0);
171    hasher.finish()
172}
173
174/// A `Retry-After` header as a delay: delta-seconds, or the time until an
175/// HTTP date (zero once it has passed), at most an hour; `None` when absent
176/// or unreadable (RFC 9110 ยง10.2.3).
177pub(super) fn parse_retry_after(headers: &hyper::HeaderMap, now: SystemTime) -> Option<Duration> {
178    let raw = headers
179        .get(hyper::header::RETRY_AFTER)?
180        .to_str()
181        .ok()?
182        .trim();
183    let delay = match raw.parse::<u64>() {
184        Ok(secs) => Duration::from_secs(secs),
185        Err(_) => httpdate::parse_http_date(raw)
186            .ok()?
187            .duration_since(now)
188            .unwrap_or(Duration::ZERO),
189    };
190    Some(delay.min(RETRY_AFTER_CEILING))
191}
192
193#[cfg(test)]
194#[path = "retry_tests.rs"]
195mod tests;