a2a_protocol_client/retry/budget.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A budget for retries: retries as a bounded fraction of calls (audit H6).
5//!
6//! A client that retries multiplies the load on a peer that is already
7//! refusing it: with three retries, a saturated worker sees up to four times
8//! the calls it was sent. A [`RetryBudget`] bounds that. Each call earns the
9//! client a fraction of a retry, time earns a little more, and a retry spends
10//! one; a retry the budget cannot pay for is not made, and the error that
11//! called for it is returned.
12//!
13//! The budget is per client (per `ClientBuilder::build`). A thousand clients
14//! in one process each have their own, so the amplification towards one peer
15//! across clients is not bounded by this; a budget shared by the clients of a
16//! pool is the pool's business (ADR 0032).
17
18use std::sync::{Mutex, PoisonError};
19
20use tokio::time::Instant;
21
22/// How many retries a client may make, as a fraction of the calls it makes.
23///
24/// `RetryBudget::new(0.1, 1.0)` allows one retry for every ten calls, and one
25/// a second besides, so that a client that makes a call a minute can still
26/// retry it. Up to [`reserve`](Self::reserve) retries are saved up for a burst
27/// of failures.
28///
29/// `#[non_exhaustive]`: build it with [`new`](Self::new) and
30/// [`with_reserve`](Self::with_reserve).
31#[derive(Debug, Clone, Copy, PartialEq)]
32#[non_exhaustive]
33pub struct RetryBudget {
34 /// Retries earned by each call. `0.1` is one retry per ten calls.
35 pub ratio: f64,
36 /// Retries earned per second, whatever the calls, so that a client that
37 /// makes few can still retry them.
38 pub min_per_sec: f64,
39 /// The most retries that can be saved up, and the number a new client
40 /// starts with: the size of the burst it can make before the rate above
41 /// is all there is. At least `1.0`, since less could never pay for one.
42 pub reserve: f64,
43}
44
45/// The default [`RetryBudget::reserve`].
46pub const DEFAULT_RESERVE: f64 = 10.0;
47
48/// A rate that is not a finite, positive number earns nothing. (`max` and not a
49/// comparison: zero is zero either way, so a `>` against zero has no behaviour
50/// for a test to tell from `>=`.)
51const fn rate(value: f64) -> f64 {
52 if value.is_finite() {
53 value.max(0.0)
54 } else {
55 0.0
56 }
57}
58
59impl RetryBudget {
60 /// A budget earning `ratio` retries per call and `min_per_sec` per second,
61 /// with a reserve of 10. A rate that is negative,
62 /// infinite or not a number earns nothing.
63 #[must_use]
64 pub const fn new(ratio: f64, min_per_sec: f64) -> Self {
65 Self {
66 ratio: rate(ratio),
67 min_per_sec: rate(min_per_sec),
68 reserve: DEFAULT_RESERVE,
69 }
70 }
71
72 /// Sets the most retries that can be saved up. Less than `1.0`, or not a
73 /// number, becomes `1.0`: a retry costs one.
74 #[must_use]
75 pub const fn with_reserve(mut self, reserve: f64) -> Self {
76 self.reserve = if reserve.is_nan() {
77 1.0
78 } else {
79 reserve.clamp(1.0, f64::MAX)
80 };
81 self
82 }
83}
84
85/// What the budget has earned and spent. Fractions of a retry are summed in
86/// floating point, so a retry is affordable from `1 - EPSILON`: ten calls at
87/// `0.1` must pay for one although their sum is `0.9999999999999999`.
88const EPSILON: f64 = 1e-9;
89
90struct State {
91 tokens: f64,
92 /// The instant up to which time has been counted.
93 at: Instant,
94}
95
96/// A [`RetryBudget`] with its balance.
97pub struct Ledger {
98 budget: RetryBudget,
99 state: Mutex<State>,
100}
101
102impl Ledger {
103 pub(crate) fn new(budget: RetryBudget) -> Self {
104 Self {
105 budget,
106 state: Mutex::new(State {
107 tokens: budget.reserve,
108 at: Instant::now(),
109 }),
110 }
111 }
112
113 /// Counts the time that has passed since the last call into the balance.
114 fn earn_time(&self, state: &mut State) {
115 let now = Instant::now();
116 let elapsed = now.saturating_duration_since(state.at).as_secs_f64();
117 state.tokens = elapsed
118 .mul_add(self.budget.min_per_sec, state.tokens)
119 .min(self.budget.reserve);
120 state.at = now;
121 }
122
123 /// A call was made: it earns its fraction of a retry.
124 pub(crate) fn deposit(&self) {
125 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
126 self.earn_time(&mut state);
127 state.tokens = (state.tokens + self.budget.ratio).min(self.budget.reserve);
128 }
129
130 /// Gives back one retry spent on a retry that was not made. Not capped
131 /// here: every use of the balance caps it at the reserve first.
132 pub(crate) fn refund(&self) {
133 self.state
134 .lock()
135 .unwrap_or_else(PoisonError::into_inner)
136 .tokens += 1.0;
137 }
138
139 /// Spends one retry if there is one to spend.
140 pub(crate) fn withdraw(&self) -> bool {
141 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
142 self.earn_time(&mut state);
143 if state.tokens >= 1.0 - EPSILON {
144 state.tokens = (state.tokens - 1.0).max(0.0);
145 true
146 } else {
147 false
148 }
149 }
150}
151
152#[cfg(test)]
153mod tests;