Skip to main content

canton_core/
retry.rs

1//! Opt-in retry with exponential backoff.
2//!
3//! Retries fire only on [`crate::Error::is_retriable`] errors, up to a bounded
4//! number of attempts. Callers build the request once (so a retried command
5//! keeps the same `command_id` and stays de-duplication-safe) and pass an
6//! operation that re-runs the RPC.
7
8use std::future::Future;
9use std::time::Duration;
10
11use crate::Result;
12
13/// Retry policy for unary calls.
14///
15/// Start from [`RetryConfig::default`] and adjust with the fluent setters;
16/// `#[non_exhaustive]` so fields can be added without a breaking change.
17#[derive(Clone, Debug)]
18#[non_exhaustive]
19pub struct RetryConfig {
20    /// Maximum number of attempts (including the first). `1` disables retrying.
21    pub max_attempts: u32,
22    /// Backoff before the first retry.
23    pub initial_backoff: Duration,
24    /// Upper bound the backoff doubles towards.
25    pub max_backoff: Duration,
26    /// Optional per-attempt timeout. When set, an attempt that exceeds it is
27    /// cancelled and treated as a retriable timeout (bounding a hung call
28    /// independently of the channel-level timeout).
29    pub attempt_timeout: Option<Duration>,
30}
31
32impl Default for RetryConfig {
33    fn default() -> Self {
34        Self {
35            max_attempts: 3,
36            initial_backoff: Duration::from_millis(100),
37            max_backoff: Duration::from_secs(5),
38            attempt_timeout: None,
39        }
40    }
41}
42
43impl RetryConfig {
44    /// Set the maximum number of attempts (including the first).
45    #[must_use]
46    pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
47        self.max_attempts = max_attempts;
48        self
49    }
50
51    /// Set the initial backoff before the first retry.
52    #[must_use]
53    pub fn with_initial_backoff(mut self, initial_backoff: Duration) -> Self {
54        self.initial_backoff = initial_backoff;
55        self
56    }
57
58    /// Set the ceiling the backoff doubles towards.
59    #[must_use]
60    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
61        self.max_backoff = max_backoff;
62        self
63    }
64
65    /// Set a per-attempt timeout: an attempt exceeding it is cancelled and
66    /// retried (as a timeout) rather than blocking on the channel-level timeout.
67    #[must_use]
68    pub fn with_attempt_timeout(mut self, attempt_timeout: Duration) -> Self {
69        self.attempt_timeout = Some(attempt_timeout);
70        self
71    }
72}
73
74/// Run `op`, retrying on retriable errors per `config`. With no `config`, runs
75/// `op` exactly once.
76///
77/// # Errors
78/// Returns the last error from `op` once attempts are exhausted or a
79/// non-retriable error is hit.
80pub async fn run_with_retry<T, F, Fut>(config: Option<&RetryConfig>, mut op: F) -> Result<T>
81where
82    F: FnMut() -> Fut,
83    Fut: Future<Output = Result<T>>,
84{
85    let Some(config) = config else {
86        return op().await;
87    };
88
89    let mut attempt = 1u32;
90    let mut backoff = config.initial_backoff;
91    loop {
92        // Bound the attempt if a per-attempt timeout is configured; a timeout is
93        // a retriable outcome (the op is retried like any transient failure).
94        let outcome = match config.attempt_timeout {
95            Some(timeout) => match tokio::time::timeout(timeout, op()).await {
96                Ok(result) => result,
97                Err(_) => Err(crate::Error::Timeout),
98            },
99            None => op().await,
100        };
101        match outcome {
102            Ok(value) => return Ok(value),
103            Err(err) if err.is_retriable() && attempt < config.max_attempts => {
104                // Canton attaches a `RetryInfo` recommendation to retryable
105                // errors; when the server asks for a longer pause than the
106                // local schedule, honour it (it knows why it rejected us).
107                //
108                // Jitter then spreads the herd — but only upwards. A server
109                // recommendation is a *minimum*: `RESOURCE_EXHAUSTED` with
110                // "retry in 3s" means the participant will refuse again before
111                // then, so coming back at 1.5s spends an attempt on a rejection
112                // that was guaranteed. Without a recommendation the local
113                // backoff is ours to scatter in either direction.
114                //
115                // The recommendation is bounded: a participant that asks for a
116                // year is not scheduling a retry, it is parking the caller
117                // (and whatever the call holds) in a sleep nobody can see.
118                let recommended = err.retry_delay().map(|server| {
119                    if server > MAX_SERVER_DELAY {
120                        tracing::warn!(
121                            recommended = ?server,
122                            cap = ?MAX_SERVER_DELAY,
123                            "the participant recommended a retry delay above the cap; capping it"
124                        );
125                    }
126                    server.min(MAX_SERVER_DELAY)
127                });
128                let delay = recommended.map_or(backoff, |server| server.max(backoff));
129                let delay = match recommended {
130                    Some(minimum) => with_jitter(delay).max(minimum),
131                    None => with_jitter(delay),
132                };
133                tokio::time::sleep(delay).await;
134                backoff = next_backoff(backoff, config.max_backoff);
135                attempt += 1;
136            }
137            Err(err) => return Err(err),
138        }
139    }
140}
141
142/// The backoff after `backoff`: twice it, up to `max`.
143///
144/// Saturating, because `Duration * u32` panics when the product does not fit:
145/// with a `max_backoff` near `Duration::MAX`, which is how "no cap" is
146/// written, the doubling would otherwise bring the caller's task down on the
147/// attempt where it overflowed.
148fn next_backoff(backoff: Duration, max: Duration) -> Duration {
149    backoff.saturating_mul(2).min(max)
150}
151
152/// Equal jitter (×0.5–1.5) on a backoff delay, so retries from many clients
153/// failing at once do not re-arrive in lockstep (thundering herd). Uses the
154/// clock's sub-second nanos as a cheap entropy source — no RNG dependency.
155fn with_jitter(backoff: Duration) -> Duration {
156    let nanos = std::time::SystemTime::now()
157        .duration_since(std::time::UNIX_EPOCH)
158        .map_or(0, |d| d.subsec_nanos());
159    let factor = 0.5 + f64::from(nanos % 1024) / 1024.0;
160    // `mul_f64` panics when the product does not fit a `Duration`; the input
161    // may come from the server, so the fallible form, and the unjittered
162    // delay when it cannot be stretched.
163    Duration::try_from_secs_f64(backoff.as_secs_f64() * factor).unwrap_or(backoff)
164}
165
166/// The longest server-recommended retry delay honoured. Canton's own
167/// recommendations are seconds; anything above this is capped (and logged),
168/// so a hostile or confused participant cannot park a caller in a sleep.
169pub const MAX_SERVER_DELAY: Duration = Duration::from_secs(60);
170
171#[cfg(test)]
172#[allow(clippy::unwrap_used)]
173mod tests {
174    use super::*;
175    use crate::Error;
176    use std::cell::Cell;
177
178    /// The backoff doubles up to the cap, and a cap near the largest duration
179    /// (how "no cap" is written) does not make the doubling overflow.
180    #[test]
181    fn the_backoff_doubles_up_to_the_cap_and_never_overflows() {
182        let cap = Duration::from_millis(80);
183        assert_eq!(
184            next_backoff(Duration::from_millis(10), cap),
185            Duration::from_millis(20)
186        );
187        assert_eq!(next_backoff(Duration::from_millis(50), cap), cap);
188        assert_eq!(next_backoff(Duration::MAX, Duration::MAX), Duration::MAX);
189        assert_eq!(
190            next_backoff(Duration::from_secs(u64::MAX - 1), Duration::MAX),
191            Duration::MAX
192        );
193    }
194
195    fn fast() -> RetryConfig {
196        RetryConfig::default()
197            .with_initial_backoff(Duration::from_millis(1))
198            .with_max_backoff(Duration::from_millis(1))
199    }
200
201    #[tokio::test]
202    async fn retries_retriable_errors_then_succeeds() {
203        let calls = Cell::new(0);
204        let result: Result<u32> = run_with_retry(Some(&fast()), || {
205            calls.set(calls.get() + 1);
206            let n = calls.get();
207            async move { if n < 3 { Err(Error::Timeout) } else { Ok(n) } }
208        })
209        .await;
210
211        assert_eq!(result.unwrap(), 3);
212        assert_eq!(calls.get(), 3);
213    }
214
215    #[tokio::test(start_paused = true)]
216    async fn the_backoff_doubles_each_attempt_up_to_the_cap() {
217        // A schedule with room to grow: 10ms initial, 80ms cap, 5 attempts.
218        // Expected sleeps between attempts, before jitter: 10, 20, 40, 80, 80
219        // (doubling, then clamped). Jitter scales 0.5-1.5, so assert each
220        // observed gap lands in that band around the expected pre-jitter value
221        // - which pins the doubling and the cap, the two things a `* -> /` or a
222        // missing `.min()` would break.
223        let cfg = RetryConfig::default()
224            .with_max_attempts(6)
225            .with_initial_backoff(Duration::from_millis(10))
226            .with_max_backoff(Duration::from_millis(80));
227
228        let starts = std::cell::RefCell::new(Vec::new());
229        let calls = Cell::new(0u32);
230        let _: Result<u32> = run_with_retry(Some(&cfg), || {
231            starts.borrow_mut().push(tokio::time::Instant::now());
232            calls.set(calls.get() + 1);
233            async move { Err::<u32, _>(Error::Timeout) }
234        })
235        .await;
236
237        let t = starts.borrow();
238        let gaps: Vec<u64> = t
239            .windows(2)
240            .map(|w| u64::try_from((w[1] - w[0]).as_millis()).unwrap_or(u64::MAX))
241            .collect();
242        let expected = [10u64, 20, 40, 80, 80];
243        assert_eq!(gaps.len(), expected.len(), "one gap per retry: {gaps:?}");
244        for (g, e) in gaps.iter().zip(expected) {
245            // Jitter scales 0.5-1.5; keep the check in integer arithmetic to
246            // pin the doubling and the cap without a float cast.
247            assert!(
248                *g * 2 >= e && *g * 2 <= e * 3,
249                "gap {g}ms outside jitter band of expected {e}ms; gaps={gaps:?}"
250            );
251        }
252    }
253
254    #[tokio::test(start_paused = true)]
255    async fn it_stops_after_max_attempts_rather_than_looping() {
256        // The mutation pass flagged loop-termination mutants as *hangs*, not
257        // clean failures - nothing bounded the attempt count in time. This
258        // asserts the exact number of calls, so a broken stop fails loudly
259        // instead of spinning until the harness kills it.
260        let cfg = RetryConfig::default()
261            .with_max_attempts(4)
262            .with_initial_backoff(Duration::from_millis(1))
263            .with_max_backoff(Duration::from_millis(1));
264        let calls = Cell::new(0u32);
265        let result: Result<u32> = run_with_retry(Some(&cfg), || {
266            calls.set(calls.get() + 1);
267            async move { Err::<u32, _>(Error::Timeout) }
268        })
269        .await;
270        assert!(result.is_err());
271        assert_eq!(
272            calls.get(),
273            4,
274            "exactly max_attempts calls, no more, no fewer"
275        );
276    }
277
278    #[tokio::test(start_paused = true)]
279    async fn a_server_recommended_delay_stretches_the_backoff() {
280        // The op fails once with a Canton-style status carrying
281        // `RetryInfo { retry_delay: 3s }`, far above the local 1ms schedule.
282        // With the paused clock, the elapsed time measures the actual sleep.
283        let delay = Duration::from_secs(3);
284        let status = {
285            use tonic_types::{ErrorDetails, StatusExt as _};
286            let mut details = ErrorDetails::new();
287            details.set_retry_info(Some(delay));
288            tonic::Status::with_error_details(tonic::Code::Unavailable, "wait", details)
289        };
290
291        let started = tokio::time::Instant::now();
292        let calls = Cell::new(0);
293        let result: Result<u32> = run_with_retry(Some(&fast()), || {
294            calls.set(calls.get() + 1);
295            let n = calls.get();
296            let err = Error::from(status.clone());
297            async move { if n == 1 { Err(err) } else { Ok(n) } }
298        })
299        .await;
300
301        assert_eq!(result.unwrap(), 2);
302        // The recommendation is a floor, not a target: jitter may stretch the
303        // wait but must never bring the retry back before the participant said
304        // it would answer.
305        assert!(
306            started.elapsed() >= delay,
307            "the server's delay is a minimum, slept only {:?}",
308            started.elapsed()
309        );
310    }
311
312    #[tokio::test(start_paused = true)]
313    async fn a_server_recommended_delay_is_capped() {
314        // A participant "recommending" a year is capped to MAX_SERVER_DELAY
315        // (plus jitter), not slept through.
316        let status = {
317            use tonic_types::{ErrorDetails, StatusExt as _};
318            let mut details = ErrorDetails::new();
319            details.set_retry_info(Some(Duration::from_secs(365 * 86_400)));
320            tonic::Status::with_error_details(tonic::Code::Unavailable, "wait", details)
321        };
322        let started = tokio::time::Instant::now();
323        let calls = Cell::new(0);
324        let result: Result<u32> = run_with_retry(Some(&fast()), || {
325            calls.set(calls.get() + 1);
326            let n = calls.get();
327            let err = Error::from(status.clone());
328            async move { if n == 1 { Err(err) } else { Ok(n) } }
329        })
330        .await;
331        assert_eq!(result.unwrap(), 2);
332        assert!(
333            started.elapsed() >= MAX_SERVER_DELAY,
334            "{:?}",
335            started.elapsed()
336        );
337        assert!(
338            started.elapsed() <= MAX_SERVER_DELAY.mul_f64(1.5) + Duration::from_secs(1),
339            "slept {:?}",
340            started.elapsed()
341        );
342    }
343
344    #[tokio::test(start_paused = true)]
345    async fn an_absurd_json_retry_info_neither_panics_nor_hangs() {
346        // The value survives parsing (it is below Duration::MAX) but would
347        // overflow the jitter arithmetic: the case that panicked the task.
348        for body in [
349            r#"{"errorCategory":1,"retryInfo":"1.8e19 seconds"}"#,
350            r#"{"errorCategory":1,"retryInfo":"1.3e19 seconds"}"#,
351            r#"{"cause":"busy","retryInfo":"18000000000000000000 seconds"}"#,
352        ] {
353            let started = tokio::time::Instant::now();
354            let calls = Cell::new(0);
355            let result: Result<u32> = run_with_retry(Some(&fast()), || {
356                calls.set(calls.get() + 1);
357                let n = calls.get();
358                let err = Error::Http {
359                    status: 503,
360                    body: body.to_string(),
361                    url: None,
362                };
363                async move { if n == 1 { Err(err) } else { Ok(n) } }
364            })
365            .await;
366            assert_eq!(result.unwrap(), 2, "{body}");
367            assert!(
368                started.elapsed() <= MAX_SERVER_DELAY.mul_f64(1.5) + Duration::from_secs(1),
369                "{body}: slept {:?}",
370                started.elapsed()
371            );
372        }
373    }
374
375    #[test]
376    fn jitter_never_panics() {
377        for backoff in [Duration::ZERO, Duration::from_millis(1), Duration::MAX] {
378            let jittered = with_jitter(backoff);
379            assert!(jittered <= Duration::MAX);
380        }
381    }
382
383    #[tokio::test]
384    async fn does_not_retry_non_retriable_errors() {
385        let calls = Cell::new(0);
386        let result: Result<u32> = run_with_retry(Some(&fast()), || {
387            calls.set(calls.get() + 1);
388            async move { Err(Error::InvalidRequest("nope".to_string())) }
389        })
390        .await;
391
392        assert!(result.is_err());
393        assert_eq!(calls.get(), 1, "non-retriable errors are not retried");
394    }
395
396    #[tokio::test]
397    async fn gives_up_after_max_attempts() {
398        let calls = Cell::new(0);
399        let result: Result<u32> = run_with_retry(Some(&fast()), || {
400            calls.set(calls.get() + 1);
401            async move { Err(Error::Timeout) }
402        })
403        .await;
404
405        assert!(result.is_err());
406        assert_eq!(calls.get(), 3, "stops at max_attempts");
407    }
408
409    #[tokio::test]
410    async fn attempt_timeout_bounds_a_hung_attempt() {
411        let calls = Cell::new(0);
412        let config = fast()
413            .with_max_attempts(2)
414            .with_attempt_timeout(Duration::from_millis(5));
415        let result: Result<u32> = run_with_retry(Some(&config), || {
416            calls.set(calls.get() + 1);
417            async move {
418                // Hangs well past the per-attempt timeout, so each attempt is
419                // cancelled and retried as a timeout.
420                tokio::time::sleep(Duration::from_secs(30)).await;
421                Ok(1)
422            }
423        })
424        .await;
425
426        assert!(result.is_err(), "every attempt times out");
427        assert_eq!(calls.get(), 2, "the hung attempt is bounded and retried");
428    }
429
430    #[tokio::test]
431    async fn without_config_runs_exactly_once() {
432        let calls = Cell::new(0);
433        let result: Result<u32> = run_with_retry(None, || {
434            calls.set(calls.get() + 1);
435            async move { Err(Error::Timeout) }
436        })
437        .await;
438
439        assert!(result.is_err());
440        assert_eq!(calls.get(), 1);
441    }
442}