Skip to main content

a2a_protocol_server/tool_loop/
run_retried.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A rate-limited turn sent again (audit H17, ADR 0048): the loop's side of
5//! [`ModelRetry`]. Moved out of `run.rs`, which it took past 500 lines.
6
7use a2a_protocol_types::budget::BudgetHandle;
8use tokio_util::sync::CancellationToken;
9
10use super::super::model::{ChatRequest, ModelError, ModelTurn, TextSink};
11use super::super::retry::ModelRetry;
12use super::{LoopError, ToolLoop};
13
14impl ToolLoop {
15    /// Sends a turn the provider refused as rate limited
16    /// ([`ModelError::RateLimited`]) again, as `retry` says, instead of
17    /// ending the run on it (audit H17, ADR 0048). Off by default: without
18    /// it a 429 ends the run, and the task ends `transient`.
19    ///
20    /// The wait honours the provider's `Retry-After`, is never longer than
21    /// what remains of the run's budget, and is abandoned when the run is
22    /// cancelled. A [`LimitedModel`](super::super::LimitedModel)'s slot is not held
23    /// while the loop waits.
24    #[must_use]
25    pub const fn with_model_retry(mut self, retry: ModelRetry) -> Self {
26        self.model_retry = Some(retry);
27        self
28    }
29
30    /// [`turn`](Self::turn), sent again after a rate-limited answer for as
31    /// long as [`with_model_retry`](Self::with_model_retry)'s policy and the
32    /// budget allow. Each attempt has its own span.
33    pub(super) async fn retried_turn(
34        &self,
35        request: ChatRequest<'_>,
36        cancel: &CancellationToken,
37        sink: Option<&TextSink>,
38        budget: Option<&BudgetHandle>,
39    ) -> Result<ModelTurn, LoopError> {
40        let mut retries = 0;
41        loop {
42            let result = self.turn(request, cancel, sink).await;
43            let Err(LoopError::Model(ModelError::RateLimited { retry_after, .. })) = &result else {
44                return result;
45            };
46            let Some(wait) = self
47                .model_retry
48                .and_then(|policy| policy.next_wait(retries, *retry_after, budget))
49            else {
50                return result;
51            };
52            trace_info!(
53                retry = retries + 1,
54                wait_ms = u64::try_from(wait.as_millis()).unwrap_or(u64::MAX),
55                "tool loop: the model provider is rate limiting; sending the turn again"
56            );
57            tokio::select! {
58                biased;
59                () = cancel.cancelled() => return Err(LoopError::Cancelled),
60                () = tokio::time::sleep(wait) => {}
61            }
62            retries += 1;
63        }
64    }
65}