Skip to main content

adk_model/
retry.rs

1use adk_core::{AdkError, ErrorCategory, Result};
2use std::{future::Future, time::Duration};
3
4/// Configuration for automatic retry with exponential backoff.
5#[derive(Clone, Debug)]
6pub struct RetryConfig {
7    /// Whether retries are enabled.
8    pub enabled: bool,
9    /// Maximum number of retry attempts before giving up.
10    pub max_retries: u32,
11    /// Initial delay before the first retry.
12    pub initial_delay: Duration,
13    /// Maximum exponential backoff delay.
14    pub max_delay: Duration,
15    /// Largest server-provided delay this executor will wait for.
16    /// A larger delay returns the original failure without another attempt.
17    pub max_server_delay: Duration,
18    /// Multiplier applied to the delay after each retry.
19    pub backoff_multiplier: f32,
20}
21
22impl Default for RetryConfig {
23    fn default() -> Self {
24        Self {
25            enabled: true,
26            max_retries: 3,
27            initial_delay: Duration::from_millis(250),
28            max_delay: Duration::from_secs(5),
29            max_server_delay: Duration::from_secs(60),
30            backoff_multiplier: 2.0,
31        }
32    }
33}
34
35impl RetryConfig {
36    /// Create a disabled retry configuration (no retries).
37    #[must_use]
38    pub fn disabled() -> Self {
39        Self { enabled: false, ..Self::default() }
40    }
41
42    /// Set the maximum number of retry attempts.
43    #[must_use]
44    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
45        self.max_retries = max_retries;
46        self
47    }
48
49    /// Set the initial delay before the first retry.
50    #[must_use]
51    pub fn with_initial_delay(mut self, initial_delay: Duration) -> Self {
52        self.initial_delay = initial_delay;
53        self
54    }
55
56    /// Set the maximum exponential backoff delay.
57    #[must_use]
58    pub fn with_max_delay(mut self, max_delay: Duration) -> Self {
59        self.max_delay = max_delay;
60        self
61    }
62
63    /// Set the backoff multiplier applied after each retry.
64    #[must_use]
65    pub fn with_backoff_multiplier(mut self, backoff_multiplier: f32) -> Self {
66        self.backoff_multiplier = backoff_multiplier;
67        self
68    }
69
70    /// Set the largest accepted server-provided retry delay.
71    ///
72    /// The default is 60 seconds. A hint above the limit returns the original
73    /// error; an accepted hint is never shortened to [`Self::max_delay`].
74    ///
75    /// # Example
76    ///
77    /// ```rust
78    /// use adk_model::retry::RetryConfig;
79    /// use std::time::Duration;
80    ///
81    /// let retry = RetryConfig::default().with_max_server_delay(Duration::from_secs(30));
82    /// assert_eq!(retry.max_server_delay, Duration::from_secs(30));
83    /// ```
84    #[must_use]
85    pub fn with_max_server_delay(mut self, limit: Duration) -> Self {
86        self.max_server_delay = limit;
87        self
88    }
89}
90
91/// Returns `true` if the HTTP status code indicates a transient error worth retrying.
92#[must_use]
93pub fn is_retryable_status_code(status_code: u16) -> bool {
94    matches!(status_code, 408 | 429 | 500 | 502 | 503 | 504 | 520..=524 | 529)
95}
96
97/// Maps an upstream HTTP error status to the [`ErrorCategory`] provider clients report.
98///
99/// The transient server statuses (500, 502–504, 520–524, and Anthropic's 529) map
100/// to [`ErrorCategory::Unavailable`], which [`execute_with_retry`] retries; every
101/// supported provider documents them as safe to retry after a short wait. 402 Payment
102/// Required maps to [`ErrorCategory::ResourceExhausted`], which is not retried: DeepSeek,
103/// OpenRouter and Anthropic send it when the account cannot pay for the request.
104///
105/// # Example
106///
107/// ```rust
108/// use adk_core::ErrorCategory;
109/// use adk_model::retry::category_for_status_code;
110///
111/// assert_eq!(category_for_status_code(502), ErrorCategory::Unavailable);
112/// assert_eq!(category_for_status_code(429), ErrorCategory::RateLimited);
113/// assert_eq!(category_for_status_code(400), ErrorCategory::InvalidInput);
114/// assert_eq!(category_for_status_code(402), ErrorCategory::ResourceExhausted);
115/// ```
116#[must_use]
117pub fn category_for_status_code(status_code: u16) -> ErrorCategory {
118    match status_code {
119        401 => ErrorCategory::Unauthorized,
120        402 => ErrorCategory::ResourceExhausted,
121        403 => ErrorCategory::Forbidden,
122        404 => ErrorCategory::NotFound,
123        408 => ErrorCategory::Timeout,
124        429 => ErrorCategory::RateLimited,
125        500 | 502 | 503 | 504 | 520..=524 | 529 => ErrorCategory::Unavailable,
126        500..=599 => ErrorCategory::Internal,
127        _ => ErrorCategory::InvalidInput,
128    }
129}
130
131/// Parses a `Retry-After` header value given in seconds or as an HTTP-date.
132///
133/// Delay-seconds follow RFC 9110's non-negative integer grammar. An HTTP-date
134/// in any of its three formats yields the time remaining, or zero when it has
135/// passed. Invalid or overflowing values are ignored so normal backoff applies.
136/// Returns `None` for any other value.
137///
138/// # Example
139///
140/// ```rust
141/// use adk_model::retry::parse_retry_after;
142/// use std::time::Duration;
143///
144/// assert_eq!(parse_retry_after("7"), Some(Duration::from_secs(7)));
145/// assert_eq!(parse_retry_after("1.5"), None);
146/// assert_eq!(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), Some(Duration::ZERO));
147/// assert_eq!(parse_retry_after("soon"), None);
148/// ```
149#[must_use]
150pub fn parse_retry_after(value: &str) -> Option<Duration> {
151    // `RetryHint` stores whole milliseconds as `u64`.
152    let value = value.trim_matches([' ', '\t']);
153    if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
154        let delay = Duration::from_secs(value.parse().ok()?);
155        u64::try_from(delay.as_millis()).ok()?;
156        return Some(delay);
157    }
158    let date = httpdate::parse_http_date(value).ok()?;
159    let delay = date.duration_since(std::time::SystemTime::now()).unwrap_or(Duration::ZERO);
160    // Round up so a retry never starts before the requested date.
161    let millis = delay.as_nanos().div_ceil(1_000_000);
162    u64::try_from(millis).ok().map(Duration::from_millis)
163}
164
165/// Attaches a server-provided `Retry-After` delay to a retryable error.
166///
167/// Errors in a non-retryable category are returned unchanged.
168///
169/// # Example
170///
171/// ```rust
172/// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
173/// use adk_model::retry::with_retry_after;
174/// use std::time::Duration;
175///
176/// let error = AdkError::new(ErrorComponent::Model, ErrorCategory::Unavailable, "m.e", "down");
177/// let error = with_retry_after(error, Some(Duration::from_secs(2)));
178/// assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(2)));
179/// ```
180#[must_use]
181pub fn with_retry_after(error: AdkError, retry_after: Option<Duration>) -> AdkError {
182    match retry_after {
183        Some(delay) if error.retry.should_retry => {
184            let retry = error.retry.clone().with_retry_after(delay);
185            error.with_retry(retry)
186        }
187        _ => error,
188    }
189}
190
191/// Returns `true` if the error message contains patterns indicating a transient failure.
192#[must_use]
193pub fn is_retryable_error_message(message: &str) -> bool {
194    let normalized = message.to_ascii_uppercase();
195    normalized.contains("429")
196        || normalized.contains("408")
197        || normalized.contains("500")
198        || normalized.contains("502")
199        || normalized.contains("503")
200        || normalized.contains("504")
201        || normalized.contains("529")
202        || normalized.contains("RATE LIMIT")
203        || normalized.contains("TOO MANY REQUESTS")
204        || normalized.contains("RESOURCE_EXHAUSTED")
205        || normalized.contains("UNAVAILABLE")
206        || normalized.contains("DEADLINE_EXCEEDED")
207        || normalized.contains("TIMEOUT")
208        || normalized.contains("TIMED OUT")
209        || normalized.contains("CONNECTION RESET")
210        || normalized.contains("OVERLOADED")
211}
212
213/// Returns `true` if the `AdkError` should be retried based on its retry hint or message.
214#[must_use]
215pub fn is_retryable_model_error(error: &AdkError) -> bool {
216    // Primary: use structured retry hint (single source of truth)
217    if error.retry.should_retry {
218        return true;
219    }
220    // Fallback: for backward-compat `.legacy` errors during transition,
221    // check the error message for retryable patterns
222    if error.code.ends_with(".legacy") && error.is_model() {
223        return is_retryable_error_message(&error.message);
224    }
225    false
226}
227
228fn next_retry_delay(current: Duration, retry_config: &RetryConfig) -> Duration {
229    if current >= retry_config.max_delay {
230        return retry_config.max_delay;
231    }
232
233    let multiplier = retry_config.backoff_multiplier.max(1.0) as f64;
234    let scaled = Duration::from_secs_f64(current.as_secs_f64() * multiplier);
235    scaled.min(retry_config.max_delay)
236}
237
238/// Hint from the server about when to retry.
239///
240/// When the server provides a `retry-after` header, this hint overrides the
241/// exponential backoff calculation for the next retry attempt.
242///
243/// # Example
244///
245/// ```rust
246/// use adk_model::retry::ServerRetryHint;
247/// use std::time::Duration;
248///
249/// let hint = ServerRetryHint { retry_after: Some(Duration::from_secs(30)) };
250/// assert_eq!(hint.retry_after, Some(Duration::from_secs(30)));
251/// ```
252#[derive(Debug, Clone, Default)]
253pub struct ServerRetryHint {
254    /// Server-suggested delay before retrying.
255    pub retry_after: Option<Duration>,
256}
257
258/// Execute an operation with automatic retry on transient errors.
259pub async fn execute_with_retry<T, Op, Fut, Classify>(
260    retry_config: &RetryConfig,
261    classify_error: Classify,
262    mut operation: Op,
263) -> Result<T>
264where
265    Op: FnMut() -> Fut,
266    Fut: Future<Output = Result<T>>,
267    Classify: Fn(&AdkError) -> bool,
268{
269    execute_with_retry_hint(retry_config, classify_error, None, &mut operation).await
270}
271
272/// Execute an operation with retry logic, optionally using a server-provided
273/// retry hint to override the backoff delay.
274///
275/// When `server_hint` contains a `retry_after` duration, that duration is used
276/// instead of the exponential backoff calculation. This respects server-provided
277/// timing from `retry-after` headers (Requirement 5.1).
278///
279/// A server-provided delay is honored without shortening it, up to
280/// [`RetryConfig::max_server_delay`]; a larger hint returns the original error.
281pub async fn execute_with_retry_hint<T, Op, Fut, Classify>(
282    retry_config: &RetryConfig,
283    classify_error: Classify,
284    server_hint: Option<&ServerRetryHint>,
285    operation: &mut Op,
286) -> Result<T>
287where
288    Op: FnMut() -> Fut,
289    Fut: Future<Output = Result<T>>,
290    Classify: Fn(&AdkError) -> bool,
291{
292    execute_with_retry_observer(retry_config, classify_error, server_hint, operation, |_, _, _| {
293        std::future::ready(Ok(()))
294    })
295    .await
296}
297
298/// Execute with one retry owner and an asynchronous observation before each backoff.
299///
300/// The observer receives the next retry number, retry limit and actual delay.
301/// An observer error stops recovery before sleeping or invoking the operation again.
302/// Disabled retries and rejected server delays do not call the observer.
303///
304/// # Example
305///
306/// ```rust
307/// use adk_core::AdkError;
308/// use adk_model::retry::{RetryConfig, execute_with_retry_observer};
309///
310/// # tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap().block_on(async {
311/// let mut calls = 0;
312/// let result = execute_with_retry_observer(
313///     &RetryConfig::default(),
314///     AdkError::is_retryable,
315///     None,
316///     &mut || {
317///         calls += 1;
318///         std::future::ready(Err::<(), _>(AdkError::unavailable(adk_core::ErrorComponent::Model, "model.busy", "busy")))
319///     },
320///     |_, _, _| std::future::ready(Err(AdkError::model("retry cancelled"))),
321/// ).await;
322/// assert!(result.is_err());
323/// assert_eq!(calls, 1);
324/// # });
325/// ```
326pub async fn execute_with_retry_observer<T, Op, Fut, Classify, Observe, ObserveFut>(
327    retry_config: &RetryConfig,
328    classify_error: Classify,
329    server_hint: Option<&ServerRetryHint>,
330    operation: &mut Op,
331    mut observe: Observe,
332) -> Result<T>
333where
334    Op: FnMut() -> Fut,
335    Fut: Future<Output = Result<T>>,
336    Classify: Fn(&AdkError) -> bool,
337    Observe: FnMut(u32, u32, Duration) -> ObserveFut,
338    ObserveFut: Future<Output = Result<()>>,
339{
340    if !retry_config.enabled {
341        return operation().await;
342    }
343
344    let mut attempt: u32 = 0;
345    let mut delay = retry_config.initial_delay.min(retry_config.max_delay);
346
347    // If the server provided a retry-after hint, use it for the first retry delay.
348    let server_delay = server_hint.and_then(|h| h.retry_after);
349
350    loop {
351        match operation().await {
352            Ok(value) => return Ok(value),
353            Err(error) if attempt < retry_config.max_retries && classify_error(&error) => {
354                // Priority: error hint, initial server hint, then bounded backoff.
355                let requested = error
356                    .retry
357                    .retry_after()
358                    .or_else(|| (attempt == 0).then_some(server_delay).flatten());
359                if requested.is_some_and(|delay| delay > retry_config.max_server_delay) {
360                    return Err(error);
361                }
362                let effective_delay = requested.unwrap_or(delay);
363                if tokio::time::Instant::now().checked_add(effective_delay).is_none() {
364                    return Err(error);
365                }
366                attempt += 1;
367                observe(attempt, retry_config.max_retries, effective_delay).await?;
368
369                // The message can echo the request, and the client sees no `RunConfig`, so
370                // only the content-free part is logged.
371                adk_telemetry::warn!(
372                    attempt = attempt,
373                    max_retries = retry_config.max_retries,
374                    delay_ms = effective_delay.as_millis(),
375                    error = %error.diagnostics(),
376                    "provider request failed with a retryable error; retrying"
377                );
378                tokio::time::sleep(effective_delay).await;
379                delay = next_retry_delay(delay, retry_config);
380            }
381            Err(error) => return Err(error),
382        }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use std::sync::{
390        Arc,
391        atomic::{AtomicU32, Ordering},
392    };
393
394    #[tokio::test]
395    async fn execute_with_retry_retries_when_classified_retryable() {
396        let retry_config = RetryConfig::default()
397            .with_max_retries(2)
398            .with_initial_delay(Duration::ZERO)
399            .with_max_delay(Duration::ZERO);
400        let attempts = Arc::new(AtomicU32::new(0));
401
402        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
403            let attempts = Arc::clone(&attempts);
404            async move {
405                let attempt = attempts.fetch_add(1, Ordering::SeqCst);
406                if attempt < 2 {
407                    return Err(AdkError::model("HTTP 429 rate limit"));
408                }
409                Ok("ok")
410            }
411        })
412        .await
413        .expect("operation should succeed after retries");
414
415        assert_eq!(result, "ok");
416        assert_eq!(attempts.load(Ordering::SeqCst), 3);
417    }
418
419    #[tokio::test]
420    async fn execute_with_retry_stops_on_non_retryable_error() {
421        let retry_config = RetryConfig::default()
422            .with_max_retries(3)
423            .with_initial_delay(Duration::ZERO)
424            .with_max_delay(Duration::ZERO);
425        let attempts = Arc::new(AtomicU32::new(0));
426
427        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
428            let attempts = Arc::clone(&attempts);
429            async move {
430                attempts.fetch_add(1, Ordering::SeqCst);
431                Err::<(), _>(AdkError::model("HTTP 400 bad request"))
432            }
433        })
434        .await
435        .expect_err("operation should fail without retries");
436
437        assert!(error.is_model());
438        assert_eq!(attempts.load(Ordering::SeqCst), 1);
439    }
440
441    #[tokio::test]
442    async fn execute_with_retry_respects_disabled_config() {
443        let retry_config = RetryConfig::disabled().with_max_retries(10);
444        let attempts = Arc::new(AtomicU32::new(0));
445
446        let error = execute_with_retry(&retry_config, is_retryable_model_error, || {
447            let attempts = Arc::clone(&attempts);
448            async move {
449                attempts.fetch_add(1, Ordering::SeqCst);
450                Err::<(), _>(AdkError::model("HTTP 429 too many requests"))
451            }
452        })
453        .await
454        .expect_err("disabled retries should return first error");
455
456        assert!(error.is_model());
457        assert_eq!(attempts.load(Ordering::SeqCst), 1);
458    }
459
460    #[test]
461    fn retryable_status_code_matches_transient_errors() {
462        assert!(is_retryable_status_code(429));
463        assert!(is_retryable_status_code(503));
464        assert!(is_retryable_status_code(529));
465        assert!(!is_retryable_status_code(400));
466        assert!(!is_retryable_status_code(401));
467    }
468
469    #[tokio::test]
470    async fn refuses_excessive_server_delays() {
471        let retry_config = RetryConfig::default()
472            .with_max_retries(1)
473            .with_initial_delay(Duration::ZERO)
474            .with_max_delay(Duration::from_millis(20));
475        let attempts = Arc::new(AtomicU32::new(0));
476        let started = std::time::Instant::now();
477
478        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
479            let attempts = Arc::clone(&attempts);
480            async move {
481                if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
482                    let error = AdkError::new(
483                        adk_core::ErrorComponent::Model,
484                        ErrorCategory::Unavailable,
485                        "model.test.unavailable",
486                        "overloaded",
487                    );
488                    return Err(with_retry_after(error, Some(Duration::from_secs(3600))));
489                }
490                Ok("ok")
491            }
492        })
493        .await;
494
495        let error = result.expect_err("excessive server delay must not be shortened");
496        assert_eq!(error.category, ErrorCategory::Unavailable);
497        assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(3600)));
498        assert_eq!(attempts.load(Ordering::SeqCst), 1);
499        assert!(started.elapsed() < Duration::from_secs(1));
500    }
501
502    #[tokio::test]
503    async fn refuses_excessive_initial_hints() {
504        let retry_config = RetryConfig::default()
505            .with_max_retries(1)
506            .with_initial_delay(Duration::ZERO)
507            .with_max_delay(Duration::from_millis(20));
508        let hint = ServerRetryHint { retry_after: Some(Duration::from_secs(3600)) };
509        let attempts = Arc::new(AtomicU32::new(0));
510        let started = std::time::Instant::now();
511
512        let result = execute_with_retry_hint(
513            &retry_config,
514            is_retryable_model_error,
515            Some(&hint),
516            &mut || {
517                let attempts = Arc::clone(&attempts);
518                async move {
519                    if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
520                        return Err(AdkError::model("HTTP 503 unavailable"));
521                    }
522                    Ok("ok")
523                }
524            },
525        )
526        .await;
527
528        let error = result.expect_err("excessive initial hint must not be shortened");
529        assert_eq!(error.message, "HTTP 503 unavailable");
530        assert_eq!(attempts.load(Ordering::SeqCst), 1);
531        assert!(started.elapsed() < Duration::from_secs(1));
532    }
533
534    #[test]
535    fn transient_server_statuses_map_to_retryable_unavailable() {
536        for status in [500, 502, 503, 504, 520, 521, 522, 523, 524, 529] {
537            assert_eq!(category_for_status_code(status), ErrorCategory::Unavailable, "{status}");
538        }
539        assert_eq!(category_for_status_code(501), ErrorCategory::Internal);
540        assert_eq!(category_for_status_code(429), ErrorCategory::RateLimited);
541        assert_eq!(category_for_status_code(408), ErrorCategory::Timeout);
542        assert_eq!(category_for_status_code(422), ErrorCategory::InvalidInput);
543        assert_eq!(category_for_status_code(402), ErrorCategory::ResourceExhausted);
544    }
545
546    #[test]
547    fn retry_after_is_attached_only_to_retryable_errors() {
548        let delay = Some(Duration::from_secs(4));
549        let unavailable = AdkError::new(
550            adk_core::ErrorComponent::Model,
551            ErrorCategory::Unavailable,
552            "model.test",
553            "down",
554        );
555        let invalid = AdkError::new(
556            adk_core::ErrorComponent::Model,
557            ErrorCategory::InvalidInput,
558            "model.test",
559            "bad",
560        );
561
562        assert_eq!(
563            with_retry_after(unavailable, delay).retry.retry_after(),
564            Some(Duration::from_secs(4))
565        );
566        assert_eq!(with_retry_after(invalid, delay).retry.retry_after(), None);
567        assert_eq!(parse_retry_after("-1"), None);
568        assert_eq!(parse_retry_after(" 30 "), Some(Duration::from_secs(30)));
569    }
570
571    #[test]
572    fn parses_dates_and_rejects_invalid_seconds() {
573        let future = std::time::SystemTime::now() + Duration::from_secs(30);
574        for date in [
575            httpdate::fmt_http_date(future),
576            "Sunday, 06-Nov-94 08:49:37 GMT".to_string(),
577            "Sun Nov  6 08:49:37 1994".to_string(),
578        ] {
579            let delay = parse_retry_after(&date).expect("HTTP-date should parse");
580            assert!(delay <= Duration::from_secs(30), "{date}");
581        }
582        assert!(parse_retry_after(&httpdate::fmt_http_date(future)).unwrap() > Duration::ZERO);
583
584        assert_eq!(parse_retry_after("61"), Some(Duration::from_secs(61)));
585        assert_eq!(parse_retry_after("3600"), Some(Duration::from_secs(3600)));
586        for invalid in [
587            "",
588            "soon",
589            "inf",
590            "NaN",
591            "-0.5",
592            "-1",
593            "+1",
594            "1.5",
595            "1e300",
596            "18446744073709551616",
597            "18446744073709552",
598            "1\n",
599        ] {
600            assert_eq!(parse_retry_after(invalid), None, "{invalid:?}");
601        }
602    }
603
604    #[tokio::test]
605    async fn observer_receives_accepted_delays() {
606        let config = RetryConfig::default()
607            .with_max_retries(1)
608            .with_max_delay(Duration::ZERO)
609            .with_max_server_delay(Duration::from_millis(30));
610        let mut calls = 0;
611        let mut observations = Vec::new();
612        let started = std::time::Instant::now();
613        let result = execute_with_retry_observer(
614            &config,
615            AdkError::is_retryable,
616            None,
617            &mut || {
618                calls += 1;
619                std::future::ready(if calls == 1 {
620                    Err(with_retry_after(
621                        AdkError::unavailable(
622                            adk_core::ErrorComponent::Model,
623                            "model.busy",
624                            "busy",
625                        ),
626                        Some(Duration::from_millis(30)),
627                    ))
628                } else {
629                    Ok("done")
630                })
631            },
632            |attempt, limit, delay| {
633                observations.push((attempt, limit, delay));
634                std::future::ready(Ok(()))
635            },
636        )
637        .await
638        .unwrap();
639        assert_eq!(result, "done");
640        assert_eq!(calls, 2);
641        assert_eq!(observations, [(1, 1, Duration::from_millis(30))]);
642        assert!(started.elapsed() >= Duration::from_millis(30));
643    }
644
645    #[tokio::test]
646    async fn observer_can_cancel_before_replay() {
647        let mut calls = 0;
648        let mut observations = 0;
649        let error = execute_with_retry_observer(
650            &RetryConfig::default(),
651            AdkError::is_retryable,
652            None,
653            &mut || {
654                calls += 1;
655                std::future::ready(Err::<(), _>(AdkError::unavailable(
656                    adk_core::ErrorComponent::Model,
657                    "model.busy",
658                    "busy",
659                )))
660            },
661            |attempt, limit, delay| {
662                observations += 1;
663                assert_eq!((attempt, limit, delay), (1, 3, Duration::from_millis(250)));
664                std::future::ready(Err(AdkError::model("cancelled")))
665            },
666        )
667        .await
668        .unwrap_err();
669        assert_eq!(error.message, "cancelled");
670        assert_eq!((calls, observations), (1, 1));
671    }
672
673    #[tokio::test]
674    async fn rejected_hints_skip_the_observer() {
675        for seconds in [61, 3600] {
676            let mut calls = 0;
677            let mut observations = 0;
678            let error = execute_with_retry_observer(
679                &RetryConfig::default(),
680                AdkError::is_retryable,
681                None,
682                &mut || {
683                    calls += 1;
684                    std::future::ready(Err::<(), _>(with_retry_after(
685                        AdkError::unavailable(
686                            adk_core::ErrorComponent::Model,
687                            "model.busy",
688                            "original",
689                        ),
690                        Some(Duration::from_secs(seconds)),
691                    )))
692                },
693                |_, _, _| {
694                    observations += 1;
695                    std::future::ready(Ok(()))
696                },
697            )
698            .await
699            .unwrap_err();
700            assert_eq!(error.message, "original");
701            assert_eq!(error.retry.retry_after(), Some(Duration::from_secs(seconds)));
702            assert_eq!((calls, observations), (1, 0));
703        }
704    }
705
706    #[test]
707    fn retryable_error_message_matches_529_and_overloaded() {
708        assert!(is_retryable_error_message("HTTP 529 overloaded"));
709        assert!(is_retryable_error_message("Server OVERLOADED, try again"));
710    }
711
712    #[tokio::test]
713    async fn execute_with_retry_hint_uses_server_delay() {
714        let retry_config = RetryConfig::default()
715            .with_max_retries(2)
716            .with_initial_delay(Duration::ZERO)
717            .with_max_delay(Duration::ZERO);
718        let attempts = Arc::new(AtomicU32::new(0));
719        let hint = ServerRetryHint { retry_after: Some(Duration::ZERO) };
720
721        let result = execute_with_retry_hint(
722            &retry_config,
723            is_retryable_model_error,
724            Some(&hint),
725            &mut || {
726                let attempts = Arc::clone(&attempts);
727                async move {
728                    let attempt = attempts.fetch_add(1, Ordering::SeqCst);
729                    if attempt < 1 {
730                        return Err(AdkError::model("HTTP 429 rate limit"));
731                    }
732                    Ok("ok")
733                }
734            },
735        )
736        .await
737        .expect("operation should succeed after retry with hint");
738
739        assert_eq!(result, "ok");
740        assert_eq!(attempts.load(Ordering::SeqCst), 2);
741    }
742
743    /// Requirement 5.2: HTTP 529 (overloaded) is retried end-to-end.
744    #[tokio::test]
745    async fn status_529_is_retried_end_to_end() {
746        let retry_config = RetryConfig::default()
747            .with_max_retries(2)
748            .with_initial_delay(Duration::ZERO)
749            .with_max_delay(Duration::ZERO);
750        let attempts = Arc::new(AtomicU32::new(0));
751
752        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
753            let attempts = Arc::clone(&attempts);
754            async move {
755                let attempt = attempts.fetch_add(1, Ordering::SeqCst);
756                if attempt == 0 {
757                    return Err(AdkError::model("HTTP 529 overloaded"));
758                }
759                Ok("recovered")
760            }
761        })
762        .await
763        .expect("529 should be retried and succeed on second attempt");
764
765        assert_eq!(result, "recovered");
766        assert_eq!(attempts.load(Ordering::SeqCst), 2);
767    }
768
769    /// Requirement 5.4: Exponential backoff when retry-after is absent.
770    /// With initial_delay=20ms and multiplier=2.0, the delays should be
771    /// ~20ms (attempt 1) then ~40ms (attempt 2). We verify each gap is
772    /// at least the expected delay.
773    #[tokio::test]
774    async fn exponential_backoff_without_retry_after() {
775        let retry_config = RetryConfig::default()
776            .with_max_retries(3)
777            .with_initial_delay(Duration::from_millis(20))
778            .with_max_delay(Duration::from_millis(200))
779            .with_backoff_multiplier(2.0);
780
781        let timestamps: Arc<std::sync::Mutex<Vec<std::time::Instant>>> =
782            Arc::new(std::sync::Mutex::new(Vec::new()));
783
784        let result = execute_with_retry(&retry_config, is_retryable_model_error, || {
785            let timestamps = Arc::clone(&timestamps);
786            async move {
787                let now = std::time::Instant::now();
788                let mut ts = timestamps.lock().unwrap();
789                let attempt = ts.len();
790                ts.push(now);
791                if attempt < 3 {
792                    return Err(AdkError::model("HTTP 429 rate limit"));
793                }
794                Ok("done")
795            }
796        })
797        .await
798        .expect("should succeed after backoff retries");
799
800        assert_eq!(result, "done");
801
802        let ts = timestamps.lock().unwrap();
803        assert_eq!(ts.len(), 4); // initial + 3 retries
804
805        // Gap between attempt 0 and 1 should be >= initial_delay (20ms).
806        let gap1 = ts[1].duration_since(ts[0]);
807        assert!(gap1 >= Duration::from_millis(18), "first backoff gap {gap1:?} should be >= ~20ms");
808
809        // Gap between attempt 1 and 2 should be >= 2 * initial_delay (40ms).
810        let gap2 = ts[2].duration_since(ts[1]);
811        assert!(
812            gap2 >= Duration::from_millis(36),
813            "second backoff gap {gap2:?} should be >= ~40ms"
814        );
815
816        // Gap 2 should be roughly double gap 1 (with tolerance for scheduling).
817        assert!(gap2 >= gap1, "backoff should increase: gap2={gap2:?} should be >= gap1={gap1:?}");
818    }
819}