Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/learn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
46 changes: 42 additions & 4 deletions crates/learn/src/distill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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();
Expand Down Expand Up @@ -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<Vec<Op>> {
Expand All @@ -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()),
}
};
Expand Down
16 changes: 13 additions & 3 deletions crates/learn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand All @@ -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::<distill::ProviderDown>() {
report.provider_down_skips += 1;
}
eprintln!("gitagent learn: {}: {e:#}", ids(unit));
return;
}
Expand Down Expand Up @@ -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();
Expand Down
52 changes: 52 additions & 0 deletions crates/learn/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down