From 7df40b70f3af6009fa119ccf88625b9ec937928b Mon Sep 17 00:00:00 2001 From: maia Date: Mon, 30 Nov 2026 22:04:15 +0100 Subject: [PATCH] take the hand-rolled backoffs from backon --- Cargo.lock | 1 + hive-agent/src/main.rs | 23 +++- hive-c0re/src/swarm_queue.rs | 69 +++++++---- swarm-agent-verify/Cargo.toml | 2 + swarm-agent-verify/src/retry.rs | 139 ++++++++++++----------- swarm-secret-client/src/stored_secret.rs | 62 +++++++--- 6 files changed, 191 insertions(+), 105 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4ccd29c2..4b9280536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5399,6 +5399,7 @@ name = "swarm-agent-verify" version = "0.1.0" dependencies = [ "anyhow", + "backon", "serde", "subtle", "swarm-secret-client", diff --git a/hive-agent/src/main.rs b/hive-agent/src/main.rs index 2734a08f2..dc7c413cb 100644 --- a/hive-agent/src/main.rs +++ b/hive-agent/src/main.rs @@ -106,6 +106,7 @@ use std::time::Duration; use crate::events::{Bus, LiveEvent, TurnState}; use crate::login::LoginState; use anyhow::Result; +use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder}; use clap::Parser; use hive_core_agent_sock::{Request, Response}; use hive_sh4re::manager::SYSTEM_SENDER; @@ -647,17 +648,22 @@ fn share_session_handles(bus: &Bus, session: &turn::AgentSession) { struct RecvBackoff { /// Failed `Recv`s since the last one that succeeded. failures: u32, + /// The waits of the run of failures in progress, `None` between runs. + waits: Option, /// No `Recv` goes out before this. A deadline rather than a duration, /// so a local wake that cancels the wait doesn't restart it. retry_at: Option, } impl RecvBackoff { - /// The wait after the `failures`-th failure in a row. - fn delay(failures: u32) -> Duration { - RECV_RETRY_FLOOR - .saturating_mul(2u32.saturating_pow(failures.saturating_sub(1))) - .min(RECV_RETRY_CAP) + /// The waits after a run of failures: [`RECV_RETRY_FLOOR`], doubling, at + /// most [`RECV_RETRY_CAP`], and no limit on the tries. + fn waits() -> ExponentialBackoff { + ExponentialBuilder::default() + .with_min_delay(RECV_RETRY_FLOOR) + .with_max_delay(RECV_RETRY_CAP) + .without_max_times() + .build() } /// Wait out the backoff, run `recv`, and record whether it failed. @@ -668,7 +674,12 @@ impl RecvBackoff { let outcome = recv.await; if matches!(outcome, RecvOutcome::TransportError) { self.failures = self.failures.saturating_add(1); - self.retry_at = Some(tokio::time::Instant::now() + Self::delay(self.failures)); + let wait = self + .waits + .get_or_insert_with(Self::waits) + .next() + .unwrap_or(RECV_RETRY_CAP); + self.retry_at = Some(tokio::time::Instant::now() + wait); } else { if self.failures > 0 { tracing::info!(failures = self.failures, "recv succeeded again"); diff --git a/hive-c0re/src/swarm_queue.rs b/hive-c0re/src/swarm_queue.rs index 1e9b61c06..602907683 100644 --- a/hive-c0re/src/swarm_queue.rs +++ b/hive-c0re/src/swarm_queue.rs @@ -28,6 +28,7 @@ use std::path::PathBuf; use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; +use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder}; use swarm_queue_client::{ClientSecret, QueueConfig}; use swarm_secret_client::queue::{self, HiveClientCredential}; use swarm_secret_client::stored_secret::StoredSecret; @@ -95,10 +96,12 @@ enum Outcome { enum Slot { Off, Ready(T), - /// `failures` consecutive attempts have failed. `warning` holds the - /// dashboard warning until the slot leaves this state. + /// `failures` consecutive attempts have failed, and `backoff` holds the + /// waits still to come. `warning` holds the dashboard warning until the + /// slot leaves this state. Failing { failures: u32, + backoff: ExponentialBackoff, not_before: Instant, warning: Option, }, @@ -158,25 +161,31 @@ impl Retrying { Outcome::Ready(value) } Attempt::Failed(e) => { + // The waits already taken are in the slot an earlier failure + // left; a first failure starts a new run. + let (mut backoff, held) = match slot.take() { + Some(Slot::Failing { + backoff, warning, .. + }) => (backoff, warning), + _ => (self.backoff(), None), + }; let failures = failures.saturating_add(1); - let delay = self.delay_after(failures); + let delay = backoff.next().unwrap_or(self.max_delay); let not_before = Instant::now() + delay; let message = format!("swarm queue is off, retrying in {delay:?}: {e:#}"); tracing::warn!(failures, "{message}"); // Updating the held guard keeps the warning up without a // moment where it is cleared and re-raised. - let warning = match slot.take() { - Some(Slot::Failing { - warning: Some(warning), - .. - }) => { + let warning = match held { + Some(warning) => { warning.update("warn", message); warning } - _ => crate::warnings::set_warning(WARNING_KIND, "warn", message), + None => crate::warnings::set_warning(WARNING_KIND, "warn", message), }; *slot = Some(Slot::Failing { failures, + backoff, not_before, warning: Some(warning), }); @@ -185,13 +194,14 @@ impl Retrying { } } - /// `first_delay` doubled per failure after the first, capped at - /// `max_delay`. - fn delay_after(&self, failures: u32) -> Duration { - let doublings = failures.saturating_sub(1).min(16); - self.first_delay - .saturating_mul(1 << doublings) - .min(self.max_delay) + /// The waits after a run of failures: `first_delay`, doubled per failure + /// after the first, capped at `max_delay`, and never giving up. + fn backoff(&self) -> ExponentialBackoff { + ExponentialBuilder::default() + .with_min_delay(self.first_delay) + .with_max_delay(self.max_delay) + .without_max_times() + .build() } } @@ -400,9 +410,30 @@ mod tests { #[test] fn the_backoff_doubles_up_to_its_cap() { let shared = Retrying::::new(Duration::from_secs(5), Duration::from_mins(5)); - let delays: Vec = (1..=8).map(|n| shared.delay_after(n).as_secs()).collect(); - assert_eq!(delays, [5, 10, 20, 40, 80, 160, 300, 300]); - assert_eq!(shared.delay_after(u32::MAX), Duration::from_mins(5)); + let mut waits = shared.backoff(); + let first: Vec = waits.by_ref().take(8).map(|d| d.as_secs()).collect(); + assert_eq!(first, [5, 10, 20, 40, 80, 160, 300, 300]); + // `backon`'s own default stops after three; this one never does. + assert_eq!(waits.take(10_000).count(), 10_000); + } + + /// The waits a run of failed attempts is given, through `get`: each + /// failure takes the next wait of the run the slot holds. + #[tokio::test(start_paused = true)] + async fn a_run_of_failures_is_given_the_waits_of_one_backoff() { + let shared = Retrying::::new(Duration::from_secs(5), Duration::from_mins(5)); + let mut waits = Vec::new(); + for _ in 0..8 { + let Outcome::NotBefore(at) = shared + .get(|| async { Attempt::Failed(anyhow!("down")) }) + .await + else { + panic!("a failure backs off"); + }; + waits.push((at - Instant::now()).as_secs()); + tokio::time::advance(at - Instant::now()).await; + } + assert_eq!(waits, [5, 10, 20, 40, 80, 160, 300, 300]); } #[tokio::test] diff --git a/swarm-agent-verify/Cargo.toml b/swarm-agent-verify/Cargo.toml index 7e9d26264..5d714fc83 100644 --- a/swarm-agent-verify/Cargo.toml +++ b/swarm-agent-verify/Cargo.toml @@ -5,6 +5,8 @@ edition.workspace = true [dependencies] anyhow.workspace = true +# The waits between the retried tries (`retry::waits`). +backon.workspace = true serde.workspace = true # Comparing an agent's presented secret with the stored one. subtle.workspace = true diff --git a/swarm-agent-verify/src/retry.rs b/swarm-agent-verify/src/retry.rs index 298c73412..4c7771acf 100644 --- a/swarm-agent-verify/src/retry.rs +++ b/swarm-agent-verify/src/retry.rs @@ -15,6 +15,7 @@ use std::time::Duration; use anyhow::bail; +use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder}; /// Tries at one request, the first included. pub const MAX_TRIES: u32 = 3; @@ -44,29 +45,19 @@ pub fn parse_retry_after(value: &str) -> Option { value.trim().parse::().ok().map(Duration::from_secs) } -/// What a retrying client waits on: time and a jitter. +/// What a retrying client waits on: time. pub trait Pause { /// Blocks for `wait`. fn sleep(&mut self, wait: Duration); - /// A value in `[0, 1)` that spreads the waits of agents that failed - /// together. - fn jitter(&mut self) -> f64; } -/// The wall clock, and the sub-second part of it as the jitter. +/// The wall clock. pub struct Clock; impl Pause for Clock { fn sleep(&mut self, wait: Duration) { std::thread::sleep(wait); } - - fn jitter(&mut self) -> f64 { - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |since| since.subsec_nanos()); - f64::from(nanos) / 1e9 - } } /// Why a try is repeated. @@ -93,19 +84,20 @@ impl Cause { } } -/// The wait before try number `next` (2 or later): the `Retry-After` when the -/// reply carried one, else the doubling backoff scaled by the jitter into -/// `[0.5, 1)` of itself. `None` when a `Retry-After` is past [`MAX_WAIT`]. -fn wait_before(next: u32, retry_after: Option, jitter: f64) -> Option { - if let Some(asked) = retry_after { - return (asked <= MAX_WAIT).then_some(asked); - } - let doubling = BASE_WAIT * 2u32.pow(next.saturating_sub(2)); - Some( - doubling - .min(MAX_WAIT) - .mul_f64(0.5 + 0.5 * jitter.clamp(0.0, 1.0)), - ) +/// The waits between the tries, without jitter: [`BASE_WAIT`], doubling, at most +/// [`MAX_WAIT`], one fewer than [`MAX_TRIES`]. It ends after the last, which is +/// how [`send_waiting`] knows the tries are spent. +fn plain_waits() -> ExponentialBuilder { + ExponentialBuilder::default() + .with_min_delay(BASE_WAIT) + .with_max_delay(MAX_WAIT) + .with_max_times(MAX_TRIES as usize - 1) +} + +/// [`plain_waits`] with `backon`'s jitter, which adds up to the wait again, to +/// spread agents that failed together. +fn waits() -> ExponentialBackoff { + plain_waits().with_jitter().build() } /// Calls `try_once` until its status is not one that is retried, at most @@ -120,6 +112,17 @@ fn wait_before(next: u32, retry_after: Option, jitter: f64) -> Option< pub fn send( what: &str, pause: &mut impl Pause, + try_once: impl FnMut() -> anyhow::Result>, +) -> anyhow::Result { + send_waiting(what, pause, waits(), try_once) +} + +/// [`send`] with the waits between the tries given, so a test runs it without +/// jitter. A `Retry-After` replaces the wait of its try. +fn send_waiting( + what: &str, + pause: &mut impl Pause, + mut waits: impl Iterator, mut try_once: impl FnMut() -> anyhow::Result>, ) -> anyhow::Result { let mut tries = 0; @@ -129,9 +132,10 @@ pub fn send( let Some(cause) = Cause::of(attempt.status) else { return Ok(attempt.response); }; - let wait = (tries < MAX_TRIES) - .then(|| wait_before(tries + 1, attempt.retry_after, pause.jitter())) - .flatten(); + let wait = waits.next().and_then(|planned| match attempt.retry_after { + Some(asked) => (asked <= MAX_WAIT).then_some(asked), + None => Some(planned), + }); let Some(wait) = wait else { bail!( "the {what} is {} ({}) after {tries} {}", @@ -149,27 +153,29 @@ pub fn send( mod tests { use super::*; - /// Records the waits instead of sleeping, and jitters by a fixed value. + /// Records the waits instead of sleeping. struct Recorded { waits: Vec, - jitter: f64, } impl Pause for Recorded { fn sleep(&mut self, wait: Duration) { self.waits.push(wait); } - - fn jitter(&mut self) -> f64 { - self.jitter - } } fn pause() -> Recorded { - Recorded { - waits: Vec::new(), - jitter: 0.0, - } + Recorded { waits: Vec::new() } + } + + /// [`super::send`] with the waits of [`plain_waits`], so a test sees them + /// exactly. + fn send( + what: &str, + pause: &mut impl Pause, + try_once: impl FnMut() -> anyhow::Result>, + ) -> anyhow::Result { + send_waiting(what, pause, plain_waits().build(), try_once) } /// Answers with each status in turn, counting the tries. @@ -246,21 +252,29 @@ mod tests { assert!(p.waits.is_empty()); } - /// The waits double, and the jitter scales each into `[0.5, 1)` of it. #[test] - fn the_waits_double_and_are_jittered() { - let mut full = Recorded { - waits: Vec::new(), - jitter: 0.999_999, - }; - send("store", &mut full, replies(&[503, 503, 200], None)).expect("succeeds"); - assert_eq!(full.waits.len(), 2); - assert!(full.waits[0] < BASE_WAIT && full.waits[0] > BASE_WAIT.mul_f64(0.99)); - assert!(full.waits[1] < BASE_WAIT * 2 && full.waits[1] > (BASE_WAIT * 2).mul_f64(0.99)); + fn the_waits_double_from_the_base() { + let mut p = pause(); + send("store", &mut p, replies(&[503, 503, 200], None)).expect("succeeds"); + assert_eq!(p.waits, [BASE_WAIT, BASE_WAIT * 2]); + } - let mut none = pause(); - send("store", &mut none, replies(&[503, 503, 200], None)).expect("succeeds"); - assert_eq!(none.waits, [BASE_WAIT.mul_f64(0.5), BASE_WAIT]); + /// The jitter adds to a wait and never takes from it, at most the wait + /// again, and it does spread. + #[test] + fn the_jitter_adds_up_to_the_wait_again() { + let plain: Vec<_> = plain_waits().build().collect(); + assert_eq!(plain, [BASE_WAIT, BASE_WAIT * 2]); + let mut spread = false; + for _ in 0..200 { + let jittered: Vec<_> = waits().collect(); + assert_eq!(jittered.len(), plain.len()); + for (plain, jittered) in plain.iter().zip(&jittered) { + assert!(jittered >= plain && *jittered <= *plain * 2, "{jittered:?}"); + spread |= jittered != plain; + } + } + assert!(spread, "no wait was jittered"); } #[test] @@ -292,14 +306,16 @@ mod tests { #[test] fn the_waits_stay_under_ten_seconds() { - for jitter in [0.0, 0.5, 0.999_999] { + for _ in 0..200 { for retry_after in [None, Some(MAX_WAIT)] { - let mut p = Recorded { - waits: Vec::new(), - jitter, - }; - send("store", &mut p, replies(&[503, 503, 503], retry_after)) - .expect_err("gives up"); + let mut p = pause(); + send_waiting( + "store", + &mut p, + waits(), + replies(&[503, 503, 503], retry_after), + ) + .expect_err("gives up"); assert!(p.waits.iter().sum::() < Duration::from_secs(10)); } } @@ -313,11 +329,4 @@ mod tests { assert_eq!(parse_retry_after("-1"), None); assert_eq!(parse_retry_after(""), None); } - - /// `Clock`'s jitter stays in `[0, 1)`. - #[test] - fn the_clock_jitters_within_the_unit_interval() { - let jitter = Clock.jitter(); - assert!((0.0..1.0).contains(&jitter), "{jitter}"); - } } diff --git a/swarm-secret-client/src/stored_secret.rs b/swarm-secret-client/src/stored_secret.rs index d4f51b47c..21b1e1e36 100644 --- a/swarm-secret-client/src/stored_secret.rs +++ b/swarm-secret-client/src/stored_secret.rs @@ -20,6 +20,7 @@ use std::pin::Pin; use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; +use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder}; use futures_util::FutureExt as _; use futures_util::future::{BoxFuture, Shared}; use tokio::task::AbortHandle; @@ -63,8 +64,9 @@ struct Inner { #[derive(Default)] struct Rereads { running: Option<(AbortHandle, Reread)>, - /// Re-reads in a row that brought no new secret. - fruitless: u32, + /// The waits of the re-reads in a row that brought no new secret, `None` + /// between runs. + waits: Option, /// No re-read starts before this. not_before: Option, } @@ -182,7 +184,7 @@ impl Inner { let failure = match outcome { Ok(Ok(secret)) if secret != before => { *self.current.write().expect("unpoisoned") = secret; - rereads.fruitless = 0; + rereads.waits = None; rereads.not_before = None; tracing::info!( client_id = %self.client_id, @@ -194,8 +196,11 @@ impl Inner { Ok(Err(e)) => format!("could not re-read the client secret: {}", chain(&*e)), Err(_) => format!("re-reading the client secret timed out after {REREAD_TIMEOUT:?}"), }; - rereads.fruitless = rereads.fruitless.saturating_add(1); - let delay = delay_after(rereads.fruitless); + let delay = rereads + .waits + .get_or_insert_with(reread_waits) + .next() + .unwrap_or(MAX_REREAD_DELAY); rereads.not_before = Some(Instant::now() + delay); tracing::warn!( client_id = %self.client_id, @@ -228,13 +233,14 @@ pub fn is_credential_refusal(status: reqwest::StatusCode) -> bool { ) } -/// [`FIRST_REREAD_DELAY`] doubled per fruitless re-read after the first, -/// capped at [`MAX_REREAD_DELAY`]. -fn delay_after(fruitless: u32) -> Duration { - let doublings = fruitless.saturating_sub(1).min(16); - FIRST_REREAD_DELAY - .saturating_mul(1 << doublings) - .min(MAX_REREAD_DELAY) +/// The waits between fruitless re-reads: [`FIRST_REREAD_DELAY`], doubling, at +/// most [`MAX_REREAD_DELAY`], and no limit on the tries. +fn reread_waits() -> ExponentialBackoff { + ExponentialBuilder::default() + .with_min_delay(FIRST_REREAD_DELAY) + .with_max_delay(MAX_REREAD_DELAY) + .without_max_times() + .build() } #[cfg(test)] @@ -400,6 +406,30 @@ pub(crate) mod tests { assert_eq!(store.reads(), 2); } + /// A re-read that finds a new secret ends the run of fruitless ones: the + /// next fruitless one waits the first delay again, not the next of the run. + #[tokio::test(start_paused = true)] + async fn a_changed_secret_starts_the_backoff_over() { + let store = Fake::holding("old"); + let secret = store.secret("hive-alpha", "old"); + assert_eq!(secret.after_refusal("old").await, None); + tokio::time::sleep(FIRST_REREAD_DELAY).await; + assert_eq!(secret.after_refusal("old").await, None); + assert_eq!(store.reads(), 2, "two fruitless reads, the next waits 10 s"); + + *store.secret.lock().expect("unpoisoned") = Some("new"); + tokio::time::sleep(FIRST_REREAD_DELAY * 2).await; + assert_eq!(secret.after_refusal("old").await.as_deref(), Some("new")); + assert_eq!(store.reads(), 3); + + // The IdP refuses the new one too, and the store holds no other. + assert_eq!(secret.after_refusal("new").await, None); + assert_eq!(store.reads(), 4); + tokio::time::sleep(FIRST_REREAD_DELAY).await; + assert_eq!(secret.after_refusal("new").await, None); + assert_eq!(store.reads(), 5, "the wait was the first delay again"); + } + #[tokio::test] async fn a_failed_re_read_keeps_the_secret_in_use() { Logs::capture(); @@ -467,9 +497,11 @@ pub(crate) mod tests { #[test] fn the_backoff_doubles_up_to_its_cap() { - assert_eq!(delay_after(1), FIRST_REREAD_DELAY); - assert_eq!(delay_after(2), FIRST_REREAD_DELAY * 2); - assert_eq!(delay_after(40), MAX_REREAD_DELAY); + let mut waits = reread_waits(); + let first: Vec = waits.by_ref().take(8).map(|d| d.as_secs()).collect(); + assert_eq!(first, [5, 10, 20, 40, 80, 160, 300, 300]); + // `backon`'s own default stops after three; this one never does. + assert_eq!(waits.take(10_000).count(), 10_000); } #[tokio::test]