From 9050cefe20206e6dccb8e690471fc5d11c7be846 Mon Sep 17 00:00:00 2001 From: Matthew Busel Date: Fri, 20 Nov 2026 22:38:42 -0500 Subject: [PATCH] learn: stop retrying into a provider outage with a shared circuit breaker The learn pass retried every unit three times with 2s/4s sleeps even when the provider was down, so an outage cost every unit's retries. A breaker from llm-resilience shared across the pass opens after two units in a row use up their retries; later units are skipped without a call and stay unlearned for the next run. Fatal errors and context overflows do not count. Adds llm-resilience 0.2.1 (default features off), which brings in parking_lot plus lock_api and parking_lot_core; tokio and tracing are already in the tree. Disclosure: I maintain llm-resilience. --- Cargo.lock | 53 +++++++++++++++++++++++++++++++++++++ crates/learn/Cargo.toml | 2 ++ crates/learn/src/distill.rs | 46 +++++++++++++++++++++++++++++--- crates/learn/src/lib.rs | 16 ++++++++--- crates/learn/src/tests.rs | 52 ++++++++++++++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e859cac3..d1480bcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -507,6 +507,7 @@ dependencies = [ "gitagent-loader", "gitagent-provider", "gitagent-record", + "llm-resilience", "serde", "serde_json", "tempfile", @@ -953,6 +954,26 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "llm-resilience" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4fafca5201b2933a00b87b97c03a73d0e577e504cd53a50781b05be9d119b3c" +dependencies = [ + "parking_lot", + "tokio", + "tracing", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -1021,6 +1042,29 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1169,6 +1213,15 @@ dependencies = [ "rand_core", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "regex" version = "1.13.1" diff --git a/crates/learn/Cargo.toml b/crates/learn/Cargo.toml index 415a4a6b..ef92c0ee 100644 --- a/crates/learn/Cargo.toml +++ b/crates/learn/Cargo.toml @@ -13,9 +13,11 @@ anyhow.workspace = true gitagent-loader.workspace = true gitagent-provider.workspace = true gitagent-record.workspace = true +llm-resilience = { version = "0.2.1", default-features = false } serde.workspace = true serde_json.workspace = true tokio.workspace = true [dev-dependencies] tempfile = "3.27.0" +tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/learn/src/distill.rs b/crates/learn/src/distill.rs index b3d51355..75e9e792 100644 --- a/crates/learn/src/distill.rs +++ b/crates/learn/src/distill.rs @@ -5,6 +5,7 @@ use std::time::Duration; use anyhow::{bail, Result}; use gitagent_loader::AgentSpec; use gitagent_provider::{CachePlan, ChatRequest, Message, Provider, ProviderError}; +use llm_resilience::CircuitBreaker; use serde::Deserialize; use crate::store::{Op, Store}; @@ -13,6 +14,32 @@ use crate::trace::Trial; const LEARNER_PROMPT: &str = include_str!("../../../prompts/learner.md"); const RETRIES: u32 = 3; +/// Consecutive transient or rate-limit failures, across every call of one +/// learning pass, that mark the provider as down: two units in a row that +/// used up all their retries. +const BREAKER_FAILURES: usize = (2 * RETRIES) as usize; +/// How long the provider counts as down before one call probes it again. +const BREAKER_COOLDOWN: Duration = Duration::from_secs(60); + +/// The breaker one learning pass shares across its model calls, so an +/// outage costs the retries of two units instead of every unit's. +pub fn breaker() -> CircuitBreaker { + CircuitBreaker::new(BREAKER_FAILURES, 1.0, BREAKER_COOLDOWN) +} + +/// The provider kept failing with transient errors and the breaker is open: +/// the call was not made. +#[derive(Debug)] +pub struct ProviderDown; + +impl std::fmt::Display for ProviderDown { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the provider keeps failing; skipped without calling it") + } +} + +impl std::error::Error for ProviderDown {} + /// The learner's instructions without their header comment. pub fn learner_prompt() -> &'static str { let text = LEARNER_PROMPT.trim_start(); @@ -52,6 +79,7 @@ pub fn request_text(store: &Store, attempts: &[&Trial]) -> String { pub async fn propose( spec: &AgentSpec, provider: &dyn Provider, + breaker: &CircuitBreaker, store: &Store, attempts: &[&Trial], ) -> Result> { @@ -70,14 +98,24 @@ pub async fn propose( let mut attempt = 0; let resp = loop { attempt += 1; + let Some(permit) = breaker.try_acquire() else { + return Err(ProviderDown.into()); + }; match provider.complete(&req).await { - Ok(r) => break r, - Err(ProviderError::Transient(e) | ProviderError::RateLimited(e)) - if attempt < RETRIES => - { + Ok(r) => { + permit.success(); + break r; + } + Err(e @ (ProviderError::Transient(_) | ProviderError::RateLimited(_))) => { + permit.failure(); + if attempt >= RETRIES { + return Err(e.into()); + } eprintln!("gitagent learn: retrying after a provider error: {e}"); tokio::time::sleep(Duration::from_secs(2u64.pow(attempt))).await; } + // Fatal errors and context overflows say nothing about whether + // the provider is up, so the breaker records nothing. Err(e) => return Err(e.into()), } }; diff --git a/crates/learn/src/lib.rs b/crates/learn/src/lib.rs index a6e68ce5..ee769de3 100644 --- a/crates/learn/src/lib.rs +++ b/crates/learn/src/lib.rs @@ -18,6 +18,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use gitagent_loader::AgentSpec; use gitagent_provider::Provider; +use llm_resilience::CircuitBreaker; use serde::Serialize; pub use audit::check as audit_lesson; @@ -55,6 +56,9 @@ pub struct LearnReport { pub trials_learned: usize, pub model_calls: usize, pub model_errors: usize, + /// Units skipped without a call because the provider kept failing + /// (also counted in `model_errors`; their trials stay unlearned). + pub provider_down_skips: usize, pub ops_proposed: usize, pub ops_rejected: usize, pub lessons_added: usize, @@ -116,9 +120,10 @@ pub async fn learn( } } + let breaker = distill::breaker(); for trials in by_task.values() { for unit in units(trials) { - learn_unit(spec, provider, &mut store, &unit, &mut report).await; + learn_unit(spec, provider, &breaker, &mut store, &unit, &mut report).await; } } report.lessons_total = store.lessons.len(); @@ -137,15 +142,19 @@ pub async fn learn( async fn learn_unit( spec: &AgentSpec, provider: &dyn Provider, + breaker: &CircuitBreaker, store: &mut Store, unit: &[&Trial], report: &mut LearnReport, ) { report.model_calls += 1; - let ops = match distill::propose(spec, provider, store, unit).await { + let ops = match distill::propose(spec, provider, breaker, store, unit).await { Ok(ops) => ops, Err(e) => { report.model_errors += 1; + if e.is::() { + report.provider_down_skips += 1; + } eprintln!("gitagent learn: {}: {e:#}", ids(unit)); return; } @@ -232,7 +241,8 @@ pub async fn learn_from_run( trials_read: 1, ..Default::default() }; - learn_unit(spec, provider, &mut store, &[&trial], &mut report).await; + let breaker = distill::breaker(); + learn_unit(spec, provider, &breaker, &mut store, &[&trial], &mut report).await; report.lessons_total = store.lessons.len(); report.rendered = store.render(PROJECT_MAX_CHARS, 2); report.lessons_shown = report.rendered.lines().count(); diff --git a/crates/learn/src/tests.rs b/crates/learn/src/tests.rs index 31eac72b..0eb22277 100644 --- a/crates/learn/src/tests.rs +++ b/crates/learn/src/tests.rs @@ -156,6 +156,58 @@ async fn a_failed_call_leaves_the_trials_for_next_time() { assert!(Store::load(&s.opts.store_path).unwrap().learned.is_empty()); } +#[tokio::test(start_paused = true)] +async fn a_provider_outage_stops_the_pass_after_two_units() { + let mut s = setup(); + // Every trial is learnable: three units (heldout, other, serve pair). + s.opts.dev_tasks = None; + let provider = ScriptedProvider::from_yaml( + &"- error: transient +" + .repeat(9), + ) + .unwrap(); + let report = learn(&spec(), &provider, &s.opts).await.unwrap(); + // Two units use up their retries; the third is skipped without a call + // instead of retrying into the same outage. + assert_eq!(provider.requests().len(), 6); + assert_eq!( + ( + report.model_calls, + report.model_errors, + report.provider_down_skips, + report.trials_learned + ), + (3, 3, 1, 0) + ); + assert!(Store::load(&s.opts.store_path).unwrap().learned.is_empty()); +} + +#[tokio::test(start_paused = true)] +async fn a_recovered_call_keeps_the_pass_going() { + let mut s = setup(); + s.opts.min_tasks = 1; + s.opts.dev_tasks = Some(["other-thing".to_string()].into()); + let script = "- error: rate_limited +- error: transient +" + .to_string() + + &reply(&format!( + r#"{{"ops": [{{"op": "add", "text": "{NOHUP}"}}]}}"# + )); + let provider = ScriptedProvider::from_yaml(&script).unwrap(); + let report = learn(&spec(), &provider, &s.opts).await.unwrap(); + assert_eq!(provider.requests().len(), 3); + assert_eq!( + ( + report.model_errors, + report.provider_down_skips, + report.lessons_added + ), + (0, 0, 1) + ); +} + #[tokio::test] async fn dry_run_writes_nothing() { let mut s = setup();