use anyhow::Result;
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
pub struct InitRetryPolicy {
max_attempts: u32,
base_backoff: Duration,
max_backoff: Duration,
}
impl Default for InitRetryPolicy {
fn default() -> Self {
Self {
max_attempts: 5,
base_backoff: Duration::from_millis(750),
max_backoff: Duration::from_secs(15),
}
}
}
fn is_transient_init_error(err: &anyhow::Error) -> bool {
let msg = format!("{err:#}").to_ascii_lowercase();
const TRANSIENT: &[&str] = &[
"status: 429",
"lock acquisition failed",
"too many requests",
"rate limit",
"status: 500",
"status: 502",
"status: 503",
"status: 504",
"timed out",
"timeout: ",
"connection reset",
"too many retries",
"host not found",
"connection failed",
"connection refused",
"body data reading stalled",
"failed to lookup address information",
"network is unreachable",
"no route to host",
];
TRANSIENT.iter().any(|needle| msg.contains(needle))
}
fn backoff_for(policy: InitRetryPolicy, attempt: u32) -> Duration {
if policy.base_backoff.is_zero() {
return Duration::ZERO;
}
let factor = 1u32 << (attempt.saturating_sub(1)).min(16);
let raw = policy
.base_backoff
.saturating_mul(factor)
.min(policy.max_backoff);
raw + Duration::from_millis(u64::from(std::process::id() % 500))
}
pub fn retry_transient_init<T>(
policy: InitRetryPolicy,
mut attempt: impl FnMut(u32) -> Result<T>,
) -> Result<T> {
let max = policy.max_attempts.max(1);
let mut n = 1u32;
loop {
match attempt(n) {
Ok(value) => return Ok(value),
Err(err) => {
if n >= max || !is_transient_init_error(&err) {
return Err(err);
}
let wait = backoff_for(policy, n);
tracing::warn!(
attempt = n,
max_attempts = max,
backoff_ms = wait.as_millis() as u64,
error = %format!("{err:#}"),
"transient embedder init failure; retrying"
);
if !wait.is_zero() {
std::thread::sleep(wait);
}
n += 1;
}
}
}
}
pub(super) fn init_or_fallback<T>(
policy: InitRetryPolicy,
model: &str,
attempt: impl FnMut(u32) -> Result<T>,
on_terminal: impl FnOnce(anyhow::Error) -> Result<T>,
) -> Result<T> {
match retry_transient_init(policy, attempt) {
Err(err) if is_transient_init_error(&err) => Err(anyhow::anyhow!(
"embedder init failed: {model} still hit a transient error after {} attempts; \
refusing to load a different model, whose vectors would not compare (#10662): {err:#}",
policy.max_attempts.max(1)
)),
Err(err) => on_terminal(err),
ok => ok,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum InitOutcome {
Success,
FastError,
Hung,
}
pub(super) fn decide_fallback(outcome: InitOutcome) -> (bool, bool) {
match outcome {
InitOutcome::Success => (false, false),
InitOutcome::FastError => (true, false),
InitOutcome::Hung => (true, true),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn instant_policy(max_attempts: u32) -> InitRetryPolicy {
InitRetryPolicy {
max_attempts,
base_backoff: Duration::ZERO,
max_backoff: Duration::ZERO,
}
}
const GATE_429: &str = "Failed to retrieve model.onnx: request error: http status: 429";
const GATE_LOCK: &str = "Failed to retrieve model.onnx: Lock acquisition failed: \
/home/runner/.cache/trusty-agents/models/models--Qdrant--all-MiniLM-L6-v2-onnx/blobs/9bbecc17.lock";
#[test]
fn a_transient_lock_error_never_reaches_the_fallback_model() {
let attempts = Cell::new(0u32);
let got = init_or_fallback(
instant_policy(5),
"fp32",
|n| {
attempts.set(n);
if n < 3 {
Err(anyhow::anyhow!(GATE_LOCK))
} else {
Ok("fp32")
}
},
|_| Ok("int8"),
)
.expect("a lock that frees must yield the primary model");
assert_eq!(got, "fp32", "a transient lock error changed the model");
assert_eq!(attempts.get(), 3);
}
#[test]
fn exhausted_transient_retries_fail_by_name_without_advancing() {
let attempts = Cell::new(0u32);
let advanced = Cell::new(false);
let err = init_or_fallback(
instant_policy(4),
"fp32",
|n| {
attempts.set(n);
Err::<&str, _>(anyhow::anyhow!(GATE_LOCK))
},
|_| {
advanced.set(true);
Ok("int8")
},
)
.expect_err("exhausted retries must not produce a model");
assert!(
!advanced.get(),
"exhausted retries advanced to the fallback"
);
assert_eq!(attempts.get(), 4, "expected the attempt budget to be spent");
let msg = format!("{err:#}");
for needle in ["embedder init failed", "fp32", "4 attempts", "refusing"] {
assert!(msg.contains(needle), "missing {needle:?} in: {msg}");
}
assert!(msg.contains("Lock acquisition failed"), "cause lost: {msg}");
}
#[test]
fn a_terminal_error_still_reaches_the_fallback() {
let attempts = Cell::new(0u32);
let seen = Cell::new(false);
let got = init_or_fallback(
instant_policy(5),
"fp32",
|n| {
attempts.set(n);
Err::<&str, _>(anyhow::anyhow!("invalid ONNX protobuf"))
},
|err| {
seen.set(format!("{err:#}").contains("invalid ONNX protobuf"));
Ok("int8")
},
)
.expect("a terminal error must reach the fallback");
assert_eq!(got, "int8");
assert_eq!(attempts.get(), 1, "a terminal error must not be retried");
assert!(seen.get(), "the fallback must receive the terminal error");
}
#[test]
fn a_coreml_hang_stays_terminal() {
assert_terminal_reaches_fallback(
"CoreML EP init did not complete within 60s (issue #2111) — presumed hung; \
the stuck OS thread is abandoned and CoreML will be skipped for the rest of \
this process (falling back to CPU). Set TRUSTY_COREML_INIT_TIMEOUT_SECS \
to raise the bound if this host's CoreML cold-compile legitimately needs more time.",
);
}
#[track_caller]
fn assert_transient_never_falls_back(text: &str) {
let attempts = Cell::new(0u32);
let got = init_or_fallback(
instant_policy(3),
"fp32",
|n| {
attempts.set(n);
Err::<&str, _>(anyhow::anyhow!(text.to_string()))
},
|_| Ok("int8"),
);
let Err(err) = got else {
panic!("{text:?} was classified terminal and loaded the other model");
};
assert_eq!(attempts.get(), 3, "{text:?} did not spend its retries");
assert!(
format!("{err:#}").contains("embedder init failed"),
"{text:?} did not fail by name: {err:#}"
);
}
#[track_caller]
fn assert_terminal_reaches_fallback(text: &str) {
let attempts = Cell::new(0u32);
let got = init_or_fallback(
instant_policy(3),
"fp32",
|n| {
attempts.set(n);
Err::<&str, _>(anyhow::anyhow!(text.to_string()))
},
|_| Ok("int8"),
);
assert_eq!(attempts.get(), 1, "{text:?} was retried");
assert_eq!(
got.ok(),
Some("int8"),
"{text:?} did not reach the fallback"
);
}
#[test]
fn ureq_connect_timeout_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: timeout: connect",
);
}
#[test]
fn ureq_host_not_found_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: host not found",
);
}
#[test]
fn ureq_failed_lookup_macos_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: io: failed to lookup address \
information: nodename nor servname provided, or not known",
);
}
#[test]
fn ureq_failed_lookup_linux_unknown_name_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: io: failed to lookup address \
information: Name or service not known",
);
}
#[test]
fn ureq_failed_lookup_linux_offline_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: io: failed to lookup address \
information: Temporary failure in name resolution",
);
}
#[test]
fn ureq_failed_lookup_any_detail_or_casing_is_transient() {
for text in [
"Failed to retrieve model.onnx: request error: io: failed to lookup address \
information: a detail no libc has shipped yet",
"FAILED TO RETRIEVE MODEL.ONNX: REQUEST ERROR: IO: FAILED TO LOOKUP ADDRESS \
INFORMATION: NAME OR SERVICE NOT KNOWN",
] {
assert_transient_never_falls_back(text);
}
}
#[test]
fn ureq_network_unreachable_is_transient() {
for text in [
"Failed to retrieve model.onnx: request error: io: Network is unreachable",
"Failed to retrieve model.onnx: request error: io: Network is unreachable (os error 101)",
"Failed to retrieve model.onnx: request error: io: Network is unreachable (os error 51)",
"failed to retrieve model.onnx: request error: io: network is unreachable",
] {
assert_transient_never_falls_back(text);
}
}
#[test]
fn ureq_no_route_to_host_is_transient() {
for text in [
"Failed to retrieve model.onnx: request error: io: No route to host",
"Failed to retrieve model.onnx: request error: io: No route to host (os error 113)",
"Failed to retrieve model.onnx: request error: io: No route to host (os error 65)",
"failed to retrieve model.onnx: request error: io: no route to host",
] {
assert_transient_never_falls_back(text);
}
}
#[test]
fn ureq_connection_failed_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: connection failed",
);
}
#[test]
fn ureq_http_500_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: http status: 500",
);
}
#[test]
fn ureq_connection_refused_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: request error: io: Connection refused",
);
}
#[test]
fn ureq_body_stall_is_transient() {
assert_transient_never_falls_back(
"Failed to retrieve model.onnx: I/O error body data reading stalled",
);
}
#[test]
fn ureq_http_401_stays_terminal() {
assert_terminal_reaches_fallback(
"Failed to retrieve model.onnx: request error: http status: 401",
);
}
#[test]
fn ureq_http_403_stays_terminal() {
assert_terminal_reaches_fallback(
"Failed to retrieve model.onnx: request error: http status: 403",
);
}
#[test]
fn ureq_http_404_stays_terminal() {
assert_terminal_reaches_fallback(
"Failed to retrieve model.onnx: request error: http status: 404",
);
}
#[test]
fn default_policy_sleeps_a_bounded_total() {
let policy = InitRetryPolicy::default();
assert_eq!(policy.max_attempts, 5);
let slept: Duration = (1..policy.max_attempts)
.map(|n| backoff_for(policy, n))
.sum();
assert!(slept >= Duration::from_millis(11_250), "got {slept:?}");
assert!(slept < Duration::from_millis(13_250), "got {slept:?}");
}
#[test]
fn transient_classifier_matches_observed_signatures() {
for msg in [
GATE_429,
GATE_LOCK,
"hub returned 429 Too Many Requests",
"request error: http status: 503",
"operation timed out",
"Too many retries: connection reset by peer",
] {
assert!(
is_transient_init_error(&anyhow::anyhow!(msg.to_string())),
"expected transient classification for: {msg}"
);
}
}
#[test]
fn transient_classifier_rejects_terminal_errors() {
for msg in [
"No such file or directory (os error 2)",
"request error: http status: 404",
"invalid ONNX protobuf: unexpected end of stream",
"corrupt blob 429004299142 (429 bytes)",
] {
assert!(
!is_transient_init_error(&anyhow::anyhow!(msg.to_string())),
"expected terminal classification for: {msg}"
);
}
}
#[test]
fn transient_classifier_reads_the_whole_anyhow_chain() {
let err = anyhow::anyhow!(GATE_429)
.context("failed to initialize fastembed TextEmbedding (AllMiniLML6V2)")
.context("init FastEmbedder");
assert!(is_transient_init_error(&err));
}
#[test]
fn retry_recovers_after_transient_failures() {
let attempts = Cell::new(0u32);
let got = retry_transient_init(instant_policy(5), |n| {
attempts.set(n);
if n < 3 {
Err(anyhow::anyhow!(GATE_LOCK))
} else {
Ok("model")
}
})
.expect("a transient failure must not be fatal");
assert_eq!(got, "model");
assert_eq!(attempts.get(), 3, "expected exactly three attempts");
}
#[test]
fn retry_stops_at_max_attempts() {
let attempts = Cell::new(0u32);
let err = retry_transient_init(instant_policy(4), |n| {
attempts.set(n);
Err::<(), _>(anyhow::anyhow!(GATE_429))
})
.expect_err("an always-429 init must eventually give up");
assert_eq!(attempts.get(), 4, "expected the attempt budget to be spent");
assert!(
format!("{err:#}").contains("429"),
"the final attempt's own error must survive, got: {err:#}"
);
}
#[test]
fn retry_does_not_retry_a_terminal_error() {
let attempts = Cell::new(0u32);
let err = retry_transient_init(instant_policy(5), |n| {
attempts.set(n);
Err::<(), _>(anyhow::anyhow!("No such file or directory (os error 2)"))
})
.expect_err("a terminal error must propagate");
assert_eq!(attempts.get(), 1, "a terminal error must not be retried");
assert!(format!("{err:#}").contains("No such file"));
}
#[test]
fn retry_runs_at_least_once_with_a_zero_attempt_budget() {
let attempts = Cell::new(0u32);
let policy = InitRetryPolicy {
max_attempts: 0,
..instant_policy(0)
};
retry_transient_init(policy, |n| {
attempts.set(n);
Ok::<_, anyhow::Error>(())
})
.expect("a zero budget must still attempt once");
assert_eq!(attempts.get(), 1);
}
#[test]
fn backoff_grows_and_is_capped() {
let policy = InitRetryPolicy {
max_attempts: 8,
base_backoff: Duration::from_millis(100),
max_backoff: Duration::from_millis(400),
};
let a1 = backoff_for(policy, 1);
let a3 = backoff_for(policy, 3);
assert!(a1 >= Duration::from_millis(100) && a1 < Duration::from_millis(600));
assert!(a3 >= a1, "backoff must not shrink as attempts grow");
for n in 3..=8 {
assert!(
backoff_for(policy, n) < Duration::from_millis(900),
"attempt {n} exceeded max_backoff + max jitter"
);
}
}
#[test]
fn zero_base_backoff_never_sleeps() {
for n in 1..=10 {
assert_eq!(backoff_for(instant_policy(10), n), Duration::ZERO);
}
}
}