Skip to main content

gadk_model/rest/
policy.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The retry policy of the official Anthropic and OpenAI SDKs: whether a response is retried,
17//! the `x-should-retry` header, retrying a dropped body, `Retry-After` handling and the
18//! backoff delay.
19
20use std::time::Duration;
21
22use chrono::{DateTime, NaiveDateTime, Utc};
23use http::{HeaderMap, StatusCode};
24
25/// Both SDKs' default retry count (2 retries: up to 3 attempts).
26pub const DEFAULT_MAX_RETRIES: u32 = 2;
27
28/// Both SDKs' backoff cap (8 seconds).
29pub const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(8);
30
31/// The OpenAI SDK's limit on a server-directed wait (2 minutes).
32pub const DEFAULT_MAX_RETRY_AFTER: Duration = Duration::from_secs(120);
33
34/// The first backoff (0.5 seconds).
35const INITIAL_BACKOFF: Duration = Duration::from_millis(500);
36
37/// How a server-directed wait (`Retry-After-Ms`, `Retry-After`) is honoured.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum RetryAfterRule {
40    /// Anthropic SDK rule: any parsed wait is honoured (a negative or NaN one is zero, `+Inf`
41    /// saturates); an unparsable value falls through to the next header, then to backoff.
42    Unbounded,
43    /// OpenAI SDK rule: a wait above the limit, or a numeric overflow (`1e400`), stops retrying
44    /// and the response is returned; `NaN`, `±Inf` and negative numbers are skipped (the next
45    /// header is tried); a past RFC 1123 date waits zero. `StopAbove(Duration::ZERO)` means
46    /// [`DEFAULT_MAX_RETRY_AFTER`].
47    StopAbove(Duration),
48}
49
50/// The server-directed decision for one retry.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum RetryAfter {
53    /// Wait this long, then retry.
54    Wait(Duration),
55    /// Do not retry: the response that asked for the wait ends the call.
56    Stop,
57}
58
59/// A retry policy: how many retries, the backoff cap, the `Retry-After` rule, and whether a
60/// body that fails to read is retried.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RetryPolicy {
63    /// Retries after the first attempt.
64    pub max_retries: u32,
65    /// The backoff cap: retry `n` waits `min(0.5s·2ⁿ, max_backoff)` minus a jitter in
66    /// `[0, delay/4)`.
67    pub max_backoff: Duration,
68    /// How `Retry-After-Ms` / `Retry-After` are honoured.
69    pub retry_after: RetryAfterRule,
70    /// Whether a body that fails while being read (a non-streaming reply, or a final error
71    /// status) is retried per [`should_retry_dropped_body`] (the Anthropic SDK) or returned as
72    /// it is (the OpenAI SDK reads bodies only after its loop).
73    pub retry_dropped_body: bool,
74}
75
76impl RetryPolicy {
77    /// The Anthropic SDK's policy: 2 retries, 8 s backoff cap, any server wait honoured, a
78    /// dropped body retried.
79    pub const ANTHROPIC: Self = Self {
80        max_retries: DEFAULT_MAX_RETRIES,
81        max_backoff: DEFAULT_MAX_BACKOFF,
82        retry_after: RetryAfterRule::Unbounded,
83        retry_dropped_body: true,
84    };
85
86    /// The OpenAI SDK's policy: 2 retries, 8 s backoff cap, server waits up to 2 minutes, a dropped
87    /// body never retried.
88    pub const OPENAI: Self = Self {
89        max_retries: DEFAULT_MAX_RETRIES,
90        max_backoff: DEFAULT_MAX_BACKOFF,
91        retry_after: RetryAfterRule::StopAbove(DEFAULT_MAX_RETRY_AFTER),
92        retry_dropped_body: false,
93    };
94
95    /// The delay before retry number `retry_count` (0-based): the server's decision
96    /// when [`parse_retry_after`] finds one (`headers` is `None` after a connection error or a
97    /// timed-out attempt), else `min(0.5s·2^retry_count, max_backoff)` minus a uniform jitter
98    /// in `[0, delay/4)` (`rand`).
99    pub fn retry_delay(&self, headers: Option<&HeaderMap>, retry_count: u32) -> RetryAfter {
100        if let Some(decision) =
101            headers.and_then(|h| parse_retry_after(h, Utc::now(), self.retry_after))
102        {
103            return decision;
104        }
105        let delay = INITIAL_BACKOFF
106            .checked_mul(2u32.checked_pow(retry_count).unwrap_or(u32::MAX))
107            .map_or(self.max_backoff, |d| d.min(self.max_backoff));
108        let quarter = u64::try_from(delay.as_nanos() / 4).unwrap_or(u64::MAX);
109        if quarter == 0 {
110            return RetryAfter::Wait(delay);
111        }
112        RetryAfter::Wait(delay - Duration::from_nanos(rand::random_range(0..quarter)))
113    }
114}
115
116/// The first value of `name`, `""` when absent (or not visible ASCII, which
117/// none of the values compared or reported here can match anyway).
118pub fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
119    headers
120        .get(name)
121        .and_then(|v| v.to_str().ok())
122        .unwrap_or("")
123}
124
125/// `Some(true)` / `Some(false)` for `x-should-retry: true` / `false`, else
126/// `None`.
127pub fn retry_header(headers: &HeaderMap) -> Option<bool> {
128    match header_str(headers, "x-should-retry") {
129        "true" => Some(true),
130        "false" => Some(false),
131        _ => None,
132    }
133}
134
135/// Whether a received response is retried: the `x-should-retry` header wins, else 408, 409,
136/// 429 and every status ≥ 500. (A connection error, with no response, is always retried: the
137/// request body is a `Bytes`, which can always be resent.)
138pub fn should_retry(status: StatusCode, headers: &HeaderMap) -> bool {
139    if let Some(retry) = retry_header(headers) {
140        return retry;
141    }
142    status == StatusCode::REQUEST_TIMEOUT
143        || status == StatusCode::CONFLICT
144        || status == StatusCode::TOO_MANY_REQUESTS
145        || status.as_u16() >= 500
146}
147
148/// Whether a body that could not be read is retried: like a
149/// connection error unless the response said `x-should-retry: false`.
150pub fn should_retry_dropped_body(headers: &HeaderMap) -> bool {
151    retry_header(headers) != Some(false)
152}
153
154/// Why [`go_parse_float`] rejected its input.
155#[derive(Debug, Clone, Copy, PartialEq)]
156pub enum GoParseFloatError {
157    /// The input is not a valid number.
158    Syntax,
159    /// The value overflows `f64`; `value` is `±Inf`.
160    Range {
161        /// `f64::INFINITY` or `f64::NEG_INFINITY`.
162        value: f64,
163    },
164}
165
166/// Parses an `f64` with the number syntax of the retry headers: decimal and hexadecimal
167/// (`0x1.8p1`) forms with underscore digit separators (`1_000`), and `inf`/`infinity` (any
168/// case, optional sign) and `nan` (any case, no sign). An out-of-range value (`1e400`) is
169/// [`GoParseFloatError::Range`] with `±Inf`; an underflow is `±0` without an error.
170/// Nothing is trimmed.
171pub fn go_parse_float(s: &str) -> Result<f64, GoParseFloatError> {
172    if let Some(v) = go_special_float(s) {
173        return Ok(v);
174    }
175    let r = go_read_float(s.as_bytes()).ok_or(GoParseFloatError::Syntax)?;
176    let v = if r.hex {
177        go_atof_hex(r.mantissa, r.exp, r.neg, r.trunc)
178    } else {
179        // The accepted grammar (sign, digits with at most one dot, at least
180        // one digit, optional exponent) is the grammar of Rust's `f64::from_str` once the
181        // validated underscores are gone, and both round correctly.
182        let digits: String = s.chars().filter(|&c| c != '_').collect();
183        digits.parse().map_err(|_| GoParseFloatError::Syntax)?
184    };
185    if v.is_infinite() {
186        return Err(GoParseFloatError::Range { value: v });
187    }
188    Ok(v)
189}
190
191/// `inf`, `infinity` and `nan`, matched against the whole input.
192fn go_special_float(s: &str) -> Option<f64> {
193    let lower = s.to_ascii_lowercase();
194    let (sign, word) = match lower.as_bytes().first() {
195        Some(b'+') => (1.0, &lower[1..]),
196        Some(b'-') => (-1.0, &lower[1..]),
197        _ => {
198            if lower == "nan" {
199                return Some(f64::NAN);
200            }
201            (1.0, lower.as_str())
202        }
203    };
204    (word == "inf" || word == "infinity").then_some(sign * f64::INFINITY)
205}
206
207/// What [`go_read_float`] read from a whole, valid input.
208struct GoReadFloat {
209    mantissa: u64,
210    exp: i64,
211    neg: bool,
212    trunc: bool,
213    hex: bool,
214}
215
216/// Reads a float literal, requiring the whole input to be consumed; `None` is a syntax error.
217fn go_read_float(s: &[u8]) -> Option<GoReadFloat> {
218    let mut i = 0;
219    let mut neg = false;
220    let mut underscores = false;
221    match s.first()? {
222        b'+' => i += 1,
223        b'-' => {
224            i += 1;
225            neg = true;
226        }
227        _ => {}
228    }
229    let mut base: u64 = 10;
230    let mut max_mant_digits = 19;
231    let mut exp_char = b'e';
232    let mut hex = false;
233    if i + 2 < s.len() && s[i] == b'0' && s[i + 1].eq_ignore_ascii_case(&b'x') {
234        base = 16;
235        max_mant_digits = 16;
236        i += 2;
237        exp_char = b'p';
238        hex = true;
239    }
240    let (mut sawdot, mut sawdigits) = (false, false);
241    let (mut nd, mut nd_mant, mut dp): (i64, i64, i64) = (0, 0, 0);
242    let mut mantissa: u64 = 0;
243    let mut trunc = false;
244    while i < s.len() {
245        let c = s[i];
246        let lc = c.to_ascii_lowercase();
247        if c == b'_' {
248            underscores = true;
249        } else if c == b'.' {
250            if sawdot {
251                break;
252            }
253            sawdot = true;
254            dp = nd;
255        } else if c.is_ascii_digit() {
256            sawdigits = true;
257            if c == b'0' && nd == 0 {
258                dp -= 1;
259            } else {
260                nd += 1;
261                if nd_mant < max_mant_digits {
262                    mantissa = mantissa * base + u64::from(c - b'0');
263                    nd_mant += 1;
264                } else if c != b'0' {
265                    trunc = true;
266                }
267            }
268        } else if base == 16 && (b'a'..=b'f').contains(&lc) {
269            sawdigits = true;
270            nd += 1;
271            if nd_mant < max_mant_digits {
272                mantissa = mantissa * 16 + u64::from(lc - b'a' + 10);
273                nd_mant += 1;
274            } else {
275                trunc = true;
276            }
277        } else {
278            break;
279        }
280        i += 1;
281    }
282    if !sawdigits {
283        return None;
284    }
285    if !sawdot {
286        dp = nd;
287    }
288    if base == 16 {
289        dp *= 4;
290        nd_mant *= 4;
291    }
292    if i < s.len() && s[i].to_ascii_lowercase() == exp_char {
293        i += 1;
294        let mut esign = 1;
295        match s.get(i)? {
296            b'+' => i += 1,
297            b'-' => {
298                i += 1;
299                esign = -1;
300            }
301            _ => {}
302        }
303        if !s.get(i)?.is_ascii_digit() {
304            return None;
305        }
306        let mut e: i64 = 0;
307        while i < s.len() && (s[i].is_ascii_digit() || s[i] == b'_') {
308            if s[i] == b'_' {
309                underscores = true;
310            } else if e < 10000 {
311                e = e * 10 + i64::from(s[i] - b'0');
312            }
313            i += 1;
314        }
315        dp += e * esign;
316    } else if base == 16 {
317        // A hexadecimal mantissa must have an exponent.
318        return None;
319    }
320    let exp = if mantissa != 0 { dp - nd_mant } else { 0 };
321    if underscores && !go_underscore_ok(&s[..i]) {
322        return None;
323    }
324    (i == s.len()).then_some(GoReadFloat {
325        mantissa,
326        exp,
327        neg,
328        trunc,
329        hex,
330    })
331}
332
333/// Underscores are allowed only between digits (or after a base prefix).
334fn go_underscore_ok(s: &[u8]) -> bool {
335    let mut s = s;
336    if let Some(b'-' | b'+') = s.first() {
337        s = &s[1..];
338    }
339    let mut saw = b'^';
340    let mut i = 0;
341    let mut hex = false;
342    if s.len() >= 2 && s[0] == b'0' && matches!(s[1].to_ascii_lowercase(), b'b' | b'o' | b'x') {
343        i = 2;
344        saw = b'0';
345        hex = s[1].eq_ignore_ascii_case(&b'x');
346    }
347    for &c in &s[i..] {
348        if c.is_ascii_digit() || hex && (b'a'..=b'f').contains(&c.to_ascii_lowercase()) {
349            saw = b'0';
350            continue;
351        }
352        if c == b'_' {
353            if saw != b'0' {
354                return false;
355            }
356            saw = b'_';
357            continue;
358        }
359        if saw == b'_' {
360            return false;
361        }
362        saw = b'!';
363    }
364    saw != b'_'
365}
366
367/// Builds an `f64` from a hexadecimal float (52 mantissa bits, 11 exponent bits, bias -1023):
368/// `mantissa * 2^exp`, rounded half to even; an overflow is `±Inf`.
369fn go_atof_hex(mut mantissa: u64, exp: i64, neg: bool, trunc: bool) -> f64 {
370    const MANTBITS: u32 = 52;
371    const BIAS: i64 = -1023;
372    const MAX_EXP: i64 = (1 << 11) + BIAS - 2;
373    const MIN_EXP: i64 = BIAS + 1;
374    let mut exp = exp + i64::from(MANTBITS);
375    while mantissa != 0 && mantissa >> (MANTBITS + 2) == 0 {
376        mantissa <<= 1;
377        exp -= 1;
378    }
379    if trunc {
380        mantissa |= 1;
381    }
382    while mantissa >> (1 + MANTBITS + 2) != 0 {
383        mantissa = (mantissa >> 1) | (mantissa & 1);
384        exp += 1;
385    }
386    while mantissa > 1 && exp < MIN_EXP - 2 {
387        mantissa = (mantissa >> 1) | (mantissa & 1);
388        exp += 1;
389    }
390    let mut round = mantissa & 3;
391    mantissa >>= 2;
392    round |= mantissa & 1;
393    exp += 2;
394    if round == 3 {
395        mantissa += 1;
396        if mantissa == 1 << (1 + MANTBITS) {
397            mantissa >>= 1;
398            exp += 1;
399        }
400    }
401    if mantissa >> MANTBITS == 0 {
402        exp = BIAS;
403    }
404    if exp > MAX_EXP {
405        mantissa = 1 << MANTBITS;
406        exp = MAX_EXP + 1;
407    }
408    let mut bits = mantissa & ((1 << MANTBITS) - 1);
409    bits |= (((exp - BIAS) & ((1 << 11) - 1)) as u64) << MANTBITS;
410    if neg {
411        bits |= 1 << 63;
412    }
413    f64::from_bits(bits)
414}
415
416/// Converts nanoseconds to a [`Duration`]: NaN and
417/// negative waits are zero; a wait past `i64::MAX` nanoseconds saturates there.
418fn duration_from_nanos(nanos: f64) -> Duration {
419    if nanos.is_nan() || nanos <= 0.0 {
420        return Duration::ZERO;
421    }
422    // `i64::MAX as f64` rounds up to 2^63; anything at or above it saturates.
423    if nanos >= i64::MAX as f64 {
424        return Duration::from_nanos(i64::MAX.unsigned_abs());
425    }
426    // In range: `as` truncates the fraction.
427    Duration::from_nanos(nanos as u64)
428}
429
430/// Parses an RFC 1123 date (`Mon, 02 Jan 2006 15:04:05 MST`) leniently: the weekday is checked
431/// for syntax only (one of `Mon`..`Sun`, case-sensitive, not against the date), and the zone is
432/// any 3 to 5 ASCII letters, in any case, read as UTC whatever it names. Numeric offsets and
433/// zone shapes like `GMT+3` are rejected.
434fn parse_rfc1123(v: &str) -> Option<DateTime<Utc>> {
435    const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
436    let (weekday, rest) = v.split_at_checked(3)?;
437    if !WEEKDAYS.contains(&weekday) {
438        return None;
439    }
440    let rest = rest.strip_prefix(", ")?;
441    let (stamp, zone) = rest.rsplit_once(' ')?;
442    if !(3..=5).contains(&zone.len()) || !zone.bytes().all(|b| b.is_ascii_alphabetic()) {
443        return None;
444    }
445    let naive = NaiveDateTime::parse_from_str(stamp, "%d %b %Y %H:%M:%S").ok()?;
446    Some(naive.and_utc())
447}
448
449/// Parses the server-directed wait: `Retry-After-Ms` (float milliseconds), then `Retry-After`
450/// (float seconds, or an RFC 1123 date measured from `now`), under `rule`. `None` when neither
451/// header gives a decision (the caller backs off).
452///
453/// - [`RetryAfterRule::Unbounded`] (Anthropic SDK): the first header that parses as a float
454///   wins (negative or NaN → zero, `+Inf` saturates at `i64::MAX` ns); a `Retry-After` that is
455///   not a float is read as a date (a past date → zero).
456/// - [`RetryAfterRule::StopAbove`] (OpenAI SDK): an overflowing number (`+Inf` with
457///   [`GoParseFloatError::Range`]) → [`RetryAfter::Stop`]; `NaN`, `±Inf` and negative numbers
458///   are skipped; a number above the limit → `Stop`, equal to it → the limit; a date at or
459///   before `now` → zero, beyond the limit → `Stop`.
460pub fn parse_retry_after(
461    headers: &HeaderMap,
462    now: DateTime<Utc>,
463    rule: RetryAfterRule,
464) -> Option<RetryAfter> {
465    match rule {
466        RetryAfterRule::Unbounded => parse_unbounded(headers, now),
467        RetryAfterRule::StopAbove(limit) => parse_stop_above(headers, now, limit),
468    }
469}
470
471fn parse_unbounded(headers: &HeaderMap, now: DateTime<Utc>) -> Option<RetryAfter> {
472    let ms = header_str(headers, "retry-after-ms");
473    if !ms.is_empty()
474        && let Ok(v) = go_parse_float(ms)
475    {
476        return Some(RetryAfter::Wait(duration_from_nanos(v * 1e6)));
477    }
478    let secs = header_str(headers, "retry-after");
479    if secs.is_empty() {
480        return None;
481    }
482    if let Ok(v) = go_parse_float(secs) {
483        return Some(RetryAfter::Wait(duration_from_nanos(v * 1e9)));
484    }
485    let at = parse_rfc1123(secs)?;
486    Some(RetryAfter::Wait(
487        (at - now).to_std().unwrap_or(Duration::ZERO),
488    ))
489}
490
491fn parse_stop_above(
492    headers: &HeaderMap,
493    now: DateTime<Utc>,
494    limit: Duration,
495) -> Option<RetryAfter> {
496    let limit = if limit.is_zero() {
497        DEFAULT_MAX_RETRY_AFTER
498    } else {
499        limit
500    };
501    // (header, nanoseconds per unit, whether a date is accepted)
502    for (name, unit, date) in [("retry-after-ms", 1e6, false), ("retry-after", 1e9, true)] {
503        let v = header_str(headers, name);
504        if v.is_empty() {
505            continue;
506        }
507        match go_parse_float(v) {
508            Err(GoParseFloatError::Range { value }) if value == f64::INFINITY => {
509                return Some(RetryAfter::Stop);
510            }
511            Ok(n) => {
512                if n.is_nan() || n.is_infinite() || n < 0.0 {
513                    continue;
514                }
515                let maximum = limit.as_nanos() as f64 / unit;
516                if n > maximum {
517                    return Some(RetryAfter::Stop);
518                }
519                if n == maximum {
520                    return Some(RetryAfter::Wait(limit));
521                }
522                return Some(RetryAfter::Wait(Duration::from_nanos((n * unit) as u64)));
523            }
524            Err(_) => {}
525        }
526        if date && let Some(at) = parse_rfc1123(v) {
527            let Ok(wait) = (at - now).to_std() else {
528                return Some(RetryAfter::Wait(Duration::ZERO));
529            };
530            if wait > limit {
531                return Some(RetryAfter::Stop);
532            }
533            return Some(RetryAfter::Wait(wait));
534        }
535    }
536    None
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use chrono::TimeZone;
543    use http::HeaderValue;
544
545    /// Header name/value pairs.
546    type Pairs = &'static [(&'static str, &'static str)];
547
548    const OPENAI_RULE: RetryAfterRule = RetryAfterRule::StopAbove(DEFAULT_MAX_RETRY_AFTER);
549
550    fn headers(pairs: Pairs) -> HeaderMap {
551        let mut h = HeaderMap::new();
552        for (k, v) in pairs {
553            h.append(*k, HeaderValue::from_static(v));
554        }
555        h
556    }
557
558    fn now() -> DateTime<Utc> {
559        Utc.with_ymd_and_hms(2026, 11, 7, 12, 0, 0).unwrap()
560    }
561
562    fn wait(d: Duration) -> Option<RetryAfter> {
563        Some(RetryAfter::Wait(d))
564    }
565
566    #[test]
567    fn retry_header_cases() {
568        let cases: [(&str, Pairs, Option<bool>); 6] = [
569            ("true", &[("x-should-retry", "true")], Some(true)),
570            ("false", &[("x-should-retry", "false")], Some(false)),
571            (
572                "capitalised_value_is_unset",
573                &[("x-should-retry", "True")],
574                None,
575            ),
576            ("one_is_unset", &[("x-should-retry", "1")], None),
577            ("empty_is_unset", &[("x-should-retry", "")], None),
578            ("absent", &[], None),
579        ];
580        for (name, h, want) in cases {
581            assert_eq!(retry_header(&headers(h)), want, "{name}");
582        }
583    }
584
585    #[test]
586    fn retry_header_reads_the_first_value() {
587        let h = headers(&[("x-should-retry", "false"), ("x-should-retry", "true")]);
588        assert_eq!(retry_header(&h), Some(false));
589    }
590
591    #[test]
592    fn should_retry_statuses_and_header_override() {
593        let none: Pairs = &[];
594        let yes: Pairs = &[("x-should-retry", "true")];
595        let no: Pairs = &[("x-should-retry", "false")];
596        let cases: [(&str, u16, Pairs, bool); 16] = [
597            ("200", 200, none, false),
598            ("201", 201, none, false),
599            ("400", 400, none, false),
600            ("401", 401, none, false),
601            ("403", 403, none, false),
602            ("404", 404, none, false),
603            ("408_request_timeout", 408, none, true),
604            ("409_conflict", 409, none, true),
605            ("429_too_many_requests", 429, none, true),
606            ("500", 500, none, true),
607            ("503", 503, none, true),
608            ("529_overloaded", 529, none, true),
609            ("500_with_false", 500, no, false),
610            ("429_with_false", 429, no, false),
611            ("400_with_true", 400, yes, true),
612            ("200_with_true", 200, yes, true),
613        ];
614        for (name, status, h, want) in cases {
615            let status = StatusCode::from_u16(status).unwrap();
616            assert_eq!(should_retry(status, &headers(h)), want, "{name}");
617        }
618    }
619
620    #[test]
621    fn should_retry_dropped_body_cases() {
622        assert!(should_retry_dropped_body(&headers(&[])), "no header");
623        assert!(
624            should_retry_dropped_body(&headers(&[("x-should-retry", "true")])),
625            "true"
626        );
627        assert!(
628            !should_retry_dropped_body(&headers(&[("x-should-retry", "false")])),
629            "false"
630        );
631        assert!(
632            should_retry_dropped_body(&headers(&[("x-should-retry", "maybe")])),
633            "unrecognised value"
634        );
635    }
636
637    #[test]
638    fn go_parse_float_cases() {
639        let cases: [(&str, Result<f64, GoParseFloatError>); 12] = [
640            ("2", Ok(2.0)),
641            ("1.5", Ok(1.5)),
642            ("1e1", Ok(10.0)),
643            ("-3", Ok(-3.0)),
644            (".5", Ok(0.5)),
645            ("inf", Ok(f64::INFINITY)),
646            ("+Inf", Ok(f64::INFINITY)),
647            ("-Infinity", Ok(f64::NEG_INFINITY)),
648            (
649                "1e400",
650                Err(GoParseFloatError::Range {
651                    value: f64::INFINITY,
652                }),
653            ),
654            (
655                "-1e400",
656                Err(GoParseFloatError::Range {
657                    value: f64::NEG_INFINITY,
658                }),
659            ),
660            ("soon", Err(GoParseFloatError::Syntax)),
661            ("", Err(GoParseFloatError::Syntax)),
662        ];
663        for (input, want) in cases {
664            assert_eq!(go_parse_float(input), want, "{input}");
665        }
666        assert!(go_parse_float("NaN").unwrap().is_nan());
667        assert_eq!(go_parse_float("-nan"), Err(GoParseFloatError::Syntax));
668    }
669
670    /// Go `strconv.ParseFloat(s, 64)` on each input, as recorded from Go: the error kind and
671    /// the returned value's bits (`ErrSyntax` returns 0, `ErrRange` ±Inf).
672    #[test]
673    fn go_parse_float_matches_go_strconv() {
674        let cases: &[(&str, &str, u64)] = &[
675            ("2", "ok", 0x4000000000000000),
676            ("1.5", "ok", 0x3ff8000000000000),
677            ("1e1", "ok", 0x4024000000000000),
678            ("-3", "ok", 0xc008000000000000),
679            (".5", "ok", 0x3fe0000000000000),
680            ("1.", "ok", 0x3ff0000000000000),
681            ("+2.5", "ok", 0x4004000000000000),
682            (" 2.5", "syntax", 0x0000000000000000),
683            ("inf", "ok", 0x7ff0000000000000),
684            ("+Inf", "ok", 0x7ff0000000000000),
685            ("-Infinity", "ok", 0xfff0000000000000),
686            ("infin", "syntax", 0x0000000000000000),
687            ("NaN", "ok", 0x7ff8000000000001),
688            ("-nan", "syntax", 0x0000000000000000),
689            ("+nan", "syntax", 0x0000000000000000),
690            ("nan", "ok", 0x7ff8000000000001),
691            ("1e400", "range", 0x7ff0000000000000),
692            ("-1e400", "range", 0xfff0000000000000),
693            ("1e-400", "ok", 0x0000000000000000),
694            ("soon", "syntax", 0x0000000000000000),
695            ("", "syntax", 0x0000000000000000),
696            ("1_0", "ok", 0x4024000000000000),
697            ("1__0", "syntax", 0x0000000000000000),
698            ("_1", "syntax", 0x0000000000000000),
699            ("1_", "syntax", 0x0000000000000000),
700            ("1_.5", "syntax", 0x0000000000000000),
701            ("1._5", "syntax", 0x0000000000000000),
702            ("1e1_0", "ok", 0x4202a05f20000000),
703            ("0x1p-2", "ok", 0x3fd0000000000000),
704            ("0X1P+2", "ok", 0x4010000000000000),
705            ("0x1.8p1", "ok", 0x4008000000000000),
706            ("0x_1p0", "ok", 0x3ff0000000000000),
707            ("0x1", "syntax", 0x0000000000000000),
708            ("0x", "syntax", 0x0000000000000000),
709            ("0xp1", "syntax", 0x0000000000000000),
710            ("0x.8p1", "ok", 0x3ff0000000000000),
711            ("-0x1p-1074", "ok", 0x8000000000000001),
712            ("0x1p-1075", "ok", 0x0000000000000000),
713            ("0x1.8p-1075", "ok", 0x0000000000000001),
714            ("0x1.0000000000001p0", "ok", 0x3ff0000000000001),
715            ("0x1.00000000000008p0", "ok", 0x3ff0000000000000),
716            ("0x1.00000000000018p0", "ok", 0x3ff0000000000002),
717            ("0x1.000000000000081p0", "ok", 0x3ff0000000000001),
718            ("0x1fffffffffffffp971", "ok", 0x7fefffffffffffff),
719            ("0x1fffffffffffffp972", "range", 0x7ff0000000000000),
720            ("0x1.fffffffffffff8p1023", "range", 0x7ff0000000000000),
721            ("0x123456789abcdef0123p-10", "ok", 0x43d23456789abcdf),
722            ("0x0p0", "ok", 0x0000000000000000),
723            ("-0x0p0", "ok", 0x8000000000000000),
724            ("0x1p-1022", "ok", 0x0010000000000000),
725            ("0x1.fffffffffffffp-1023", "ok", 0x0010000000000000),
726            ("0x0.0000000000001p-1022", "ok", 0x0000000000000001),
727            ("0x3p-1076", "ok", 0x0000000000000001),
728            ("00012", "ok", 0x4028000000000000),
729            ("1e", "syntax", 0x0000000000000000),
730            ("1e+", "syntax", 0x0000000000000000),
731            ("e5", "syntax", 0x0000000000000000),
732            (".", "syntax", 0x0000000000000000),
733            ("-", "syntax", 0x0000000000000000),
734            ("+", "syntax", 0x0000000000000000),
735            ("1.2.3", "syntax", 0x0000000000000000),
736            ("0x1p1e", "syntax", 0x0000000000000000),
737            ("0x1.p1", "ok", 0x4000000000000000),
738            ("0x.p1", "syntax", 0x0000000000000000),
739            ("1e100000", "range", 0x7ff0000000000000),
740            ("0x1p100000", "range", 0x7ff0000000000000),
741            ("0x1p-100000", "ok", 0x0000000000000000),
742            ("0b101", "syntax", 0x0000000000000000),
743            ("0o17", "syntax", 0x0000000000000000),
744            ("1e-5_0", "ok", 0x358dee7a4ad4b81f),
745            ("1_000.000_1", "ok", 0x408f4000346dc5d6),
746            ("0x_1_p_1", "syntax", 0x0000000000000000),
747        ];
748        for &(input, kind, bits) in cases {
749            let (got_kind, got) = match go_parse_float(input) {
750                Ok(v) => ("ok", v),
751                Err(GoParseFloatError::Syntax) => ("syntax", 0.0),
752                Err(GoParseFloatError::Range { value }) => ("range", value),
753            };
754            assert_eq!(got_kind, kind, "{input:?}");
755            if got.is_nan() {
756                assert!(f64::from_bits(bits).is_nan(), "{input:?}");
757            } else {
758                assert_eq!(got.to_bits(), bits, "{input:?}: {got}");
759            }
760        }
761    }
762
763    #[test]
764    fn anthropic_parse_retry_after_cases() {
765        let cases: [(&str, Pairs, Option<RetryAfter>); 17] = [
766            ("absent", &[], None),
767            (
768                "ms_integer",
769                &[("retry-after-ms", "1500")],
770                wait(Duration::from_millis(1500)),
771            ),
772            (
773                "ms_fraction",
774                &[("retry-after-ms", "0.5")],
775                wait(Duration::from_micros(500)),
776            ),
777            (
778                "ms_wins_over_seconds",
779                &[("retry-after-ms", "10"), ("retry-after", "30")],
780                wait(Duration::from_millis(10)),
781            ),
782            (
783                "ms_unparsable_falls_back_to_seconds",
784                &[("retry-after-ms", "soon"), ("retry-after", "3")],
785                wait(Duration::from_secs(3)),
786            ),
787            (
788                "ms_empty_falls_back_to_seconds",
789                &[("retry-after-ms", ""), ("retry-after", "3")],
790                wait(Duration::from_secs(3)),
791            ),
792            (
793                "seconds_integer",
794                &[("retry-after", "2")],
795                wait(Duration::from_secs(2)),
796            ),
797            (
798                "seconds_fraction",
799                &[("retry-after", "1.5")],
800                wait(Duration::from_millis(1500)),
801            ),
802            (
803                "seconds_exponent",
804                &[("retry-after", "1e1")],
805                wait(Duration::from_secs(10)),
806            ),
807            (
808                "seconds_negative_is_zero",
809                &[("retry-after", "-3")],
810                wait(Duration::ZERO),
811            ),
812            (
813                "ms_negative_is_zero",
814                &[("retry-after-ms", "-1")],
815                wait(Duration::ZERO),
816            ),
817            (
818                "seconds_nan_is_zero",
819                &[("retry-after", "NaN")],
820                wait(Duration::ZERO),
821            ),
822            (
823                "seconds_out_of_range_is_unparsable",
824                &[("retry-after", "1e400")],
825                None,
826            ),
827            (
828                "date_in_ten_seconds",
829                &[("retry-after", "Sat, 07 Nov 2026 12:00:10 GMT")],
830                wait(Duration::from_secs(10)),
831            ),
832            (
833                "date_weekday_is_syntax_only",
834                &[("retry-after", "Mon, 07 Nov 2026 12:01:00 GMT")],
835                wait(Duration::from_secs(60)),
836            ),
837            (
838                "date_in_the_past_is_zero",
839                &[("retry-after", "Sat, 07 Nov 2026 11:59:00 GMT")],
840                wait(Duration::ZERO),
841            ),
842            ("garbage", &[("retry-after", "later")], None),
843        ];
844        for (name, h, want) in cases {
845            assert_eq!(
846                parse_retry_after(&headers(h), now(), RetryAfterRule::Unbounded),
847                want,
848                "{name}"
849            );
850        }
851    }
852
853    #[test]
854    fn anthropic_parse_retry_after_infinity_saturates() {
855        let h = headers(&[("retry-after", "+Inf")]);
856        assert_eq!(
857            parse_retry_after(&h, now(), RetryAfterRule::Unbounded),
858            wait(Duration::from_nanos(i64::MAX.unsigned_abs()))
859        );
860    }
861
862    #[test]
863    fn openai_parse_retry_after_cases() {
864        let stop = Some(RetryAfter::Stop);
865        let cases: [(&str, Pairs, Option<RetryAfter>); 26] = [
866            ("absent", &[], None),
867            (
868                "ms_integer",
869                &[("retry-after-ms", "1500")],
870                wait(Duration::from_millis(1500)),
871            ),
872            (
873                "ms_fraction",
874                &[("retry-after-ms", "0.5")],
875                wait(Duration::from_micros(500)),
876            ),
877            (
878                "ms_wins_over_seconds",
879                &[("retry-after-ms", "10"), ("retry-after", "30")],
880                wait(Duration::from_millis(10)),
881            ),
882            (
883                "ms_unparsable_falls_back_to_seconds",
884                &[("retry-after-ms", "soon"), ("retry-after", "3")],
885                wait(Duration::from_secs(3)),
886            ),
887            (
888                "seconds_integer",
889                &[("retry-after", "2")],
890                wait(Duration::from_secs(2)),
891            ),
892            (
893                "seconds_at_the_limit_waits_the_limit",
894                &[("retry-after", "120")],
895                wait(Duration::from_secs(120)),
896            ),
897            (
898                "seconds_above_the_limit_stop",
899                &[("retry-after", "121")],
900                stop,
901            ),
902            (
903                "ms_at_the_limit_waits_the_limit",
904                &[("retry-after-ms", "120000")],
905                wait(Duration::from_secs(120)),
906            ),
907            (
908                "ms_above_the_limit_stop",
909                &[("retry-after-ms", "120001"), ("retry-after", "1")],
910                stop,
911            ),
912            ("seconds_overflow_stops", &[("retry-after", "1e400")], stop),
913            (
914                "ms_overflow_stops_before_seconds",
915                &[("retry-after-ms", "1e400"), ("retry-after", "1")],
916                stop,
917            ),
918            (
919                "seconds_negative_overflow_is_unparsable",
920                &[("retry-after", "-1e400")],
921                None,
922            ),
923            ("seconds_inf_is_skipped", &[("retry-after", "inf")], None),
924            (
925                "seconds_plus_inf_is_skipped",
926                &[("retry-after", "+Inf")],
927                None,
928            ),
929            ("seconds_nan_is_skipped", &[("retry-after", "NaN")], None),
930            (
931                "seconds_negative_is_skipped",
932                &[("retry-after", "-3")],
933                None,
934            ),
935            (
936                "ms_inf_falls_through_to_seconds",
937                &[("retry-after-ms", "inf"), ("retry-after", "3")],
938                wait(Duration::from_secs(3)),
939            ),
940            (
941                "ms_nan_falls_through_to_seconds",
942                &[("retry-after-ms", "NaN"), ("retry-after", "3")],
943                wait(Duration::from_secs(3)),
944            ),
945            (
946                "ms_negative_falls_through_to_seconds",
947                &[("retry-after-ms", "-1"), ("retry-after", "2")],
948                wait(Duration::from_secs(2)),
949            ),
950            (
951                "date_in_ten_seconds",
952                &[("retry-after", "Sat, 07 Nov 2026 12:00:10 GMT")],
953                wait(Duration::from_secs(10)),
954            ),
955            (
956                "date_in_the_past_is_zero",
957                &[("retry-after", "Sat, 07 Nov 2026 11:59:00 GMT")],
958                wait(Duration::ZERO),
959            ),
960            (
961                "date_at_the_limit_waits",
962                &[("retry-after", "Sat, 07 Nov 2026 12:02:00 GMT")],
963                wait(Duration::from_secs(120)),
964            ),
965            (
966                "date_beyond_the_limit_stops",
967                &[("retry-after", "Sat, 07 Nov 2026 12:02:01 GMT")],
968                stop,
969            ),
970            (
971                "ms_date_is_not_accepted",
972                &[("retry-after-ms", "Sat, 07 Nov 2026 12:00:10 GMT")],
973                None,
974            ),
975            ("garbage", &[("retry-after", "later")], None),
976        ];
977        for (name, h, want) in cases {
978            assert_eq!(
979                parse_retry_after(&headers(h), now(), OPENAI_RULE),
980                want,
981                "{name}"
982            );
983        }
984    }
985
986    #[test]
987    fn openai_zero_limit_is_the_default_limit() {
988        let rule = RetryAfterRule::StopAbove(Duration::ZERO);
989        let h = headers(&[("retry-after", "120")]);
990        assert_eq!(
991            parse_retry_after(&h, now(), rule),
992            wait(Duration::from_secs(120))
993        );
994        let h = headers(&[("retry-after", "121")]);
995        assert_eq!(parse_retry_after(&h, now(), rule), Some(RetryAfter::Stop));
996    }
997
998    #[test]
999    fn parse_retry_after_rejects_non_rfc1123_dates() {
1000        for rule in [RetryAfterRule::Unbounded, OPENAI_RULE] {
1001            for v in [
1002                "2026-11-07T12:00:10Z",
1003                "Sat, 07 Nov 2026 12:00:10",
1004                "Sat, 07 Nov 2026 12:00:10 +0000",
1005                "Xyz, 07 Nov 2026 12:00:10 GMT",
1006                "Saturday, 07-Nov-26 12:00:10 GMT",
1007            ] {
1008                let h = HeaderMap::from_iter([(
1009                    http::header::RETRY_AFTER,
1010                    HeaderValue::from_str(v).unwrap(),
1011                )]);
1012                assert_eq!(parse_retry_after(&h, now(), rule), None, "{rule:?} {v}");
1013            }
1014        }
1015    }
1016
1017    #[test]
1018    fn retry_delay_uses_the_servers_wait() {
1019        let h = headers(&[("retry-after-ms", "250")]);
1020        for policy in [RetryPolicy::ANTHROPIC, RetryPolicy::OPENAI] {
1021            for n in 0..4 {
1022                assert_eq!(
1023                    policy.retry_delay(Some(&h), n),
1024                    RetryAfter::Wait(Duration::from_millis(250)),
1025                    "retry {n}"
1026                );
1027            }
1028        }
1029        let zero = headers(&[("retry-after", "0")]);
1030        assert_eq!(
1031            RetryPolicy::ANTHROPIC.retry_delay(Some(&zero), 3),
1032            RetryAfter::Wait(Duration::ZERO)
1033        );
1034    }
1035
1036    #[test]
1037    fn retry_delay_stops_or_waits_per_rule() {
1038        let long = headers(&[("retry-after", "121")]);
1039        assert_eq!(
1040            RetryPolicy::ANTHROPIC.retry_delay(Some(&long), 0),
1041            RetryAfter::Wait(Duration::from_secs(121))
1042        );
1043        assert_eq!(
1044            RetryPolicy::OPENAI.retry_delay(Some(&long), 0),
1045            RetryAfter::Stop
1046        );
1047    }
1048
1049    fn assert_backoff(policy: RetryPolicy, headers: Option<&HeaderMap>) {
1050        let bases_ms = [500u64, 1000, 2000, 4000, 8000, 8000, 8000];
1051        for (n, base_ms) in bases_ms.into_iter().enumerate() {
1052            let base = Duration::from_millis(base_ms);
1053            let floor = base - base / 4;
1054            let n = u32::try_from(n).unwrap();
1055            let mut distinct = std::collections::HashSet::new();
1056            for _ in 0..200 {
1057                let RetryAfter::Wait(d) = policy.retry_delay(headers, n) else {
1058                    panic!("retry {n}: want a wait");
1059                };
1060                assert!(
1061                    d > floor && d <= base,
1062                    "retry {n}: {d:?} not in ({floor:?}, {base:?}]"
1063                );
1064                distinct.insert(d);
1065            }
1066            assert!(distinct.len() > 1, "retry {n}: no jitter");
1067        }
1068    }
1069
1070    #[test]
1071    fn retry_delay_backoff_bounds_with_jitter() {
1072        let no_wait = headers(&[("x-should-retry", "true")]);
1073        for policy in [RetryPolicy::ANTHROPIC, RetryPolicy::OPENAI] {
1074            assert_backoff(policy, None);
1075            assert_backoff(policy, Some(&no_wait));
1076        }
1077    }
1078
1079    #[test]
1080    fn openai_skipped_waits_fall_back_to_backoff() {
1081        for v in ["inf", "+Inf", "NaN", "-5"] {
1082            let h =
1083                HeaderMap::from_iter([(http::header::RETRY_AFTER, HeaderValue::from_static(v))]);
1084            assert_backoff(RetryPolicy::OPENAI, Some(&h));
1085        }
1086    }
1087
1088    #[test]
1089    fn retry_delay_caps_huge_retry_counts() {
1090        let RetryAfter::Wait(d) = RetryPolicy::ANTHROPIC.retry_delay(None, u32::MAX) else {
1091            panic!("want a wait");
1092        };
1093        assert!(
1094            d > Duration::from_secs(6) && d <= DEFAULT_MAX_BACKOFF,
1095            "{d:?}"
1096        );
1097    }
1098
1099    #[test]
1100    fn retry_delay_small_backoff_cap_has_no_jitter_panic() {
1101        let policy = RetryPolicy {
1102            max_backoff: Duration::ZERO,
1103            ..RetryPolicy::OPENAI
1104        };
1105        assert_eq!(
1106            policy.retry_delay(None, 0),
1107            RetryAfter::Wait(Duration::ZERO)
1108        );
1109        let policy = RetryPolicy {
1110            max_backoff: Duration::from_nanos(3),
1111            ..RetryPolicy::OPENAI
1112        };
1113        assert_eq!(
1114            policy.retry_delay(None, 5),
1115            RetryAfter::Wait(Duration::from_nanos(3))
1116        );
1117    }
1118
1119    #[test]
1120    fn policy_constants() {
1121        assert_eq!(DEFAULT_MAX_RETRIES, 2);
1122        assert_eq!(
1123            RetryPolicy::ANTHROPIC,
1124            RetryPolicy {
1125                max_retries: 2,
1126                max_backoff: Duration::from_secs(8),
1127                retry_after: RetryAfterRule::Unbounded,
1128                retry_dropped_body: true,
1129            }
1130        );
1131        assert_eq!(
1132            RetryPolicy::OPENAI,
1133            RetryPolicy {
1134                max_retries: 2,
1135                max_backoff: Duration::from_secs(8),
1136                retry_after: RetryAfterRule::StopAbove(Duration::from_secs(120)),
1137                retry_dropped_body: false,
1138            }
1139        );
1140    }
1141}