Files
orch/src/budget.rs
T
johannesandClaude Sonnet 5.5 e50f90d299
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 4m5s
build / build (x86_64-unknown-linux-musl) (push) Successful in 3m34s
build / release (push) Successful in 16s
feat: restart a failed or escalated session at the state where it stopped
Adds orch session --restart sN and R in the TUI. A restart event gives the
session fresh budgets and retry counts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 22:36:10 +01:00

301 lines
9.5 KiB
Rust

//! Budgets and the loop detector (ORCHESTRATOR.md section 4), as pure functions over a session's events.
//! The runner uses them to stop a session; the session screen uses them to show how close it is.
use crate::db::Event;
use crate::machine::BudgetCfg;
use std::collections::{BTreeSet, HashMap};
/// Seconds the session spent working: from its first event to its end (or now), minus the time it sat in the
/// Needs-you queue. Waiting for you must not eat the wall-time budget.
pub fn active_secs(evs: &[&Event], now_ms: u64) -> u64 {
// work starts with the first state; time blocked on dependencies before that is not work
let Some(first) = evs.iter().find(|e| e.kind == "state") else {
return 0;
};
let end = match evs.last() {
Some(e) if e.kind == "end" => e.at,
_ => now_ms,
};
let mut open: HashMap<i64, u64> = HashMap::new(); // need id -> when it was put in the queue
let mut waited = 0;
for e in evs {
let id = e.payload["id"].as_i64().unwrap_or(-1);
match e.kind.as_str() {
"need" => {
open.insert(id, e.at);
}
"answer" => {
if let Some(at) = open.remove(&id) {
waited += e.at.saturating_sub(at);
}
}
_ => {}
}
}
waited += open.values().map(|at| end.saturating_sub(*at)).sum::<u64>();
end.saturating_sub(first.at).saturating_sub(waited) / 1000
}
/// Cost so far: the last `usage` event carries the running total.
pub fn cost(evs: &[&Event]) -> f64 {
evs.iter()
.rev()
.find(|e| e.kind == "usage")
.and_then(|e| e.payload["cost"].as_f64())
.unwrap_or(0.0)
}
/// Context window use in percent, from the last `usage` event.
pub fn ctx_pct(evs: &[&Event]) -> Option<u8> {
let e = evs.iter().rev().find(|e| e.kind == "usage")?;
let (used, limit) = (
e.payload["ctx_used"].as_u64()?,
e.payload["ctx_limit"].as_u64()?,
);
Some((used * 100).checked_div(limit)?.min(100) as u8)
}
#[derive(Debug, PartialEq)]
pub struct Exceeded {
pub what: &'static str,
pub used: String,
pub limit: String,
}
/// A restarted session gets a fresh budget: only the events from its last `restart` count.
pub fn exceeded(all: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option<Exceeded> {
let restarted = all.iter().rposition(|e| e.kind == "restart");
let evs = &all[restarted.unwrap_or(0)..];
if let Some(limit) = cfg.wall_secs {
let used = active_secs(evs, now_ms);
if used > limit {
return Some(Exceeded {
what: "wall time",
used: format!("{}m", used / 60),
limit: format!("{}m", limit / 60),
});
}
}
if let Some(limit) = cfg.cost {
// usage after a restart belongs to the new hx, whose total starts again
let used = if restarted.is_some() {
cost(&evs[1..])
} else {
cost(evs)
};
if used > limit {
return Some(Exceeded {
what: "cost",
used: format!("${used:.2}"),
limit: format!("${limit:.2}"),
});
}
}
None
}
#[derive(Debug, PartialEq)]
pub struct LoopInfo {
/// Test runs in a row that failed on exactly the same tests.
pub runs: usize,
/// How many tests that is.
pub tests: usize,
/// The file the agent edited most since the loop began.
pub file: Option<String>,
}
fn failing(e: &Event) -> BTreeSet<String> {
e.payload["failures"]
.as_array()
.into_iter()
.flatten()
.filter_map(|f| f["name"].as_str().map(String::from))
.collect()
}
/// After a failed test run: do the last runs fail on the same set of tests? Two in a row is a loop (the agent
/// tried a fix and got the same failures), a run that passes or fails differently ends it.
pub fn looping(evs: &[&Event]) -> Option<LoopInfo> {
let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect();
let last = failing(runs.last()?);
if last.is_empty() {
return None;
}
let n = runs.iter().rev().take_while(|r| failing(r) == last).count();
if n < 2 {
return None;
}
let since = runs[runs.len() - n].id;
let mut edits: HashMap<&str, u64> = HashMap::new();
for e in evs.iter().filter(|e| e.kind == "edit" && e.id > since) {
let touched =
e.payload["added"].as_u64().unwrap_or(0) + e.payload["removed"].as_u64().unwrap_or(0);
*edits
.entry(e.payload["path"].as_str().unwrap_or_default())
.or_default() += touched.max(1);
}
let file = edits
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0)))
.map(|(p, _)| p.to_string());
Some(LoopInfo {
runs: n,
tests: last.len(),
file,
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ev(id: i64, at: u64, kind: &str, payload: serde_json::Value) -> Event {
Event {
id,
session: "s1".into(),
at,
kind: kind.into(),
payload,
}
}
fn refs(v: &[Event]) -> Vec<&Event> {
v.iter().collect()
}
fn test_run(id: i64, names: &[&str]) -> Event {
let f: Vec<_> = names.iter().map(|n| json!({"name": n})).collect();
ev(
id,
id as u64 * 1000,
"test",
json!({"passed": 3, "failed": names.len(), "failures": f}),
)
}
#[test]
fn time_in_the_queue_does_not_count_as_work() {
let evs = [
ev(1, 0, "state", json!({})),
ev(2, 60_000, "need", json!({"id": 5})),
ev(3, 660_000, "answer", json!({"id": 5})), // waited ten minutes
ev(4, 720_000, "step", json!({})),
];
assert_eq!(active_secs(&refs(&evs), 720_000), 120);
// still waiting: the open item counts as waiting until now
assert_eq!(active_secs(&refs(&evs[..2]), 3_600_000), 60);
// a finished session stops at its end, not at now
let done = [
ev(1, 0, "state", json!({})),
ev(2, 30_000, "end", json!({})),
];
assert_eq!(active_secs(&refs(&done), 9_999_999), 30);
assert_eq!(active_secs(&[], 5), 0);
}
#[test]
fn limits_trip_on_time_and_cost() {
let evs = [
ev(1, 0, "state", json!({})),
ev(
2,
10_000,
"usage",
json!({"cost": 5.25, "ctx_used": 142, "ctx_limit": 200}),
),
];
let r = refs(&evs);
assert_eq!(cost(&r), 5.25);
assert_eq!(ctx_pct(&r), Some(71));
let none = BudgetCfg::default();
assert_eq!(
exceeded(&r, &none, 999_999_999),
None,
"no limits, no budget stop"
);
let cost_cap = BudgetCfg {
cost: Some(5.0),
..none.clone()
};
assert_eq!(
exceeded(&r, &cost_cap, 0),
Some(Exceeded {
what: "cost",
used: "$5.25".into(),
limit: "$5.00".into()
})
);
let wall = BudgetCfg {
wall_secs: Some(60),
..none
};
assert_eq!(exceeded(&r, &wall, 30_000), None);
let e = exceeded(&r, &wall, 600_000).unwrap();
assert_eq!(
(e.what, e.used.as_str(), e.limit.as_str()),
("wall time", "10m", "1m")
);
}
#[test]
fn same_failing_tests_twice_is_a_loop() {
let evs = [
ev(
0,
0,
"edit",
json!({"path": "src/old.rs", "added": 50, "removed": 0}),
), // before the first of the identical runs: not part of the loop
test_run(1, &["a::x", "a::y"]),
test_run(3, &["a::y", "a::x"]),
ev(
4,
4000,
"edit",
json!({"path": "src/token.rs", "added": 6, "removed": 2}),
),
ev(
5,
5000,
"edit",
json!({"path": "src/token.rs", "added": 1, "removed": 1}),
),
ev(
6,
6000,
"edit",
json!({"path": "src/mod.rs", "added": 1, "removed": 0}),
),
test_run(7, &["a::x", "a::y"]),
];
let l = looping(&refs(&evs)).expect("loop");
assert_eq!((l.runs, l.tests), (3, 2));
assert_eq!(
l.file.as_deref(),
Some("src/token.rs"),
"edits before the loop do not count"
);
}
#[test]
fn different_or_fixed_failures_are_no_loop() {
// fix 1 changed which tests fail: progress, not a loop
let evs = [test_run(1, &["a::x", "a::y"]), test_run(2, &["a::x"])];
assert_eq!(looping(&refs(&evs)), None);
// the last run passed
let evs = [
test_run(1, &["a::x"]),
test_run(2, &["a::x"]),
test_run(3, &[]),
];
assert_eq!(looping(&refs(&evs)), None);
// only one run so far
assert_eq!(looping(&refs(&[test_run(1, &["a::x"])])), None);
assert_eq!(looping(&[]), None);
// a loop without edits has no file to blame
let evs = [test_run(1, &["a::x"]), test_run(2, &["a::x"])];
assert_eq!(looping(&refs(&evs)).unwrap().file, None);
}
}