O6: telemetry report and eval task set (#14)

This commit was merged in pull request #14.
This commit is contained in:
hermes committed 2026-11-13 00:19:52 +00:00
1 parent bea07e82bb
commit b2d72f2dc9
31 files changed
+809 -3

No files matched your search

+140 -2
View File
@@ -2,6 +2,7 @@ mod adapter;
mod lock;
mod policy;
mod profile;
mod report;
mod run;
mod state;
@@ -37,6 +38,30 @@ enum Cmd {
#[arg(long)]
limit: Option<usize>,
},
/// Success rate, tokens, retries and duration per profile and hx version, from the telemetry log.
Report {
/// Telemetry file (default: <state>/telemetry.jsonl).
file: Option<PathBuf>,
},
/// Compare two telemetry files per case; exit 1 when B's success rate is below A's.
Eval { a: PathBuf, b: PathBuf },
/// Run the eval cases in DIR (task.md, files/, gate.sh each) through a profile; writes telemetry to --out.
Bench {
dir: PathBuf,
#[arg(long, default_value = "default")]
profile: String,
#[arg(long)]
out: Option<PathBuf>,
/// Runs per case.
#[arg(long, default_value_t = 1)]
repeat: u32,
/// Only this case.
#[arg(long)]
case: Option<String>,
/// No hx: check that every case fails untouched and passes with its solution/ overlay.
#[arg(long)]
check: bool,
},
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
#[command(hide = true)]
Guard { policy: PathBuf },
@@ -82,7 +107,7 @@ fn main() -> Result<std::process::ExitCode> {
let p = profile::Profile::load(&profile)?;
let id = task.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
let t = adapter::parse_task_md(id, &std::fs::read_to_string(&task)?);
let r = process(&t, &repo, &profile, &p, None)?;
let r = process(&t, &repo, &profile, &p, None, &report::default_path())?;
Ok(code(r.status == state::Status::Done))
}
Cmd::Pull { profile, limit } => {
@@ -125,7 +150,14 @@ fn main() -> Result<std::process::ExitCode> {
if !src.claim(&t)? {
continue;
}
let r = process(&t, &repo, &profile, &p, Some(src.as_ref()))?;
let r = process(
&t,
&repo,
&profile,
&p,
Some(src.as_ref()),
&report::default_path(),
)?;
if r.status != state::Status::Done
&& r.status != state::Status::Requeued
{
@@ -142,6 +174,31 @@ fn main() -> Result<std::process::ExitCode> {
});
Ok(code(ok.load(Ordering::SeqCst)))
}
Cmd::Report { file } => {
print!(
"{}",
report::report(&report::load(&file.unwrap_or_else(report::default_path))?)
);
Ok(0.into())
}
Cmd::Eval { a, b } => {
let (text, regressed) = report::compare(
&report::load(&a)?,
&report::load(&b)?,
&a.to_string_lossy(),
&b.to_string_lossy(),
);
print!("{text}");
Ok(code(!regressed))
}
Cmd::Bench {
dir,
profile,
out,
repeat,
case,
check,
} => bench(&dir, &profile, out, repeat, case.as_deref(), check),
Cmd::Guard { policy } => {
policy::guard(&policy)?;
Ok(0.into())
@@ -195,6 +252,7 @@ fn process(
profile: &str,
p: &profile::Profile,
src: Option<&dyn adapter::Source>,
telemetry: &Path,
) -> Result<state::Run> {
let mut r = run::new_run(t, repo, profile)?;
if p.allow.is_none() && !p.sandbox {
@@ -213,6 +271,10 @@ fn process(
"run_end",
serde_json::json!({"status": r.status, "reason": r.reason, "attempts": r.attempts}),
);
// a telemetry failure must not lose the run
if let Err(e) = report::append(telemetry, &report::rec(&r, &report::hx_version(p))) {
eprintln!("{}: telemetry: {e:#}", r.id);
}
if r.status == state::Status::Done {
match adapter::sink(p.sink.as_ref()).and_then(|s| s.publish(t, &r)) {
Ok(note) => r.published = note,
@@ -243,3 +305,79 @@ fn process(
);
Ok(r)
}
/// `orch bench`: every case gets a fresh git repo of its files and its own gate (`gate.sh`); the profile decides
/// everything else (hx, allowlist, retries, budget). Sink and source are ignored: nothing is published.
fn bench(
dir: &Path,
profile: &str,
out: Option<PathBuf>,
repeat: u32,
only: Option<&str>,
check: bool,
) -> Result<std::process::ExitCode> {
let mut cases = report::cases(dir)?;
if let Some(o) = only {
cases.retain(|c| c.name == o);
anyhow::ensure!(!cases.is_empty(), "no case named {o:?}");
}
if check {
return bench_check(&cases);
}
let mut p = profile::Profile::load(profile)?;
(p.source, p.sink) = (None, None);
let out = out.unwrap_or_else(|| state_dir().join("bench.jsonl"));
let mut ok = true;
for c in &cases {
for _ in 0..repeat {
let repo = report::fixture(c)?;
let gate = c.dir.join("gate.sh").canonicalize()?;
p.gate = Some(format!("sh {}", gate.display()));
let t =
adapter::parse_task_md(&c.name, &std::fs::read_to_string(c.dir.join("task.md"))?);
ok &= process(&t, &repo, profile, &p, None, &out)?.status == state::Status::Done;
}
}
println!("telemetry: {}", out.display());
Ok(code(ok))
}
/// Case-set sanity without an agent: the gate must fail on the untouched files and pass after `solution/`.
fn bench_check(cases: &[report::Case]) -> Result<std::process::ExitCode> {
let gate = |dir: &Path, g: &Path| -> Result<bool> {
Ok(std::process::Command::new("sh")
.arg(g)
.current_dir(dir)
.output()?
.status
.success())
};
let mut ok = true;
for c in cases {
let g = c.dir.join("gate.sh").canonicalize()?;
let repo = report::fixture(c)?;
let before = gate(&repo, &g)?;
let sol = c.dir.join("solution");
let after = if sol.is_dir() {
std::process::Command::new("cp")
.arg("-R")
.arg(format!("{}/.", sol.display()))
.arg(&repo)
.status()?;
Some(gate(&repo, &g)?)
} else {
None
};
let good = !before && after != Some(false);
let solved = match after {
None => "no solution/",
Some(true) => "pass",
Some(false) => "FAIL (bad)",
};
let untouched = if before { "PASS (bad)" } else { "fail" };
let flag = if good { "" } else { " <-- broken case" };
println!("{:<20} untouched={untouched} solved={solved}{flag}", c.name);
ok &= good;
}
Ok(code(ok))
}
+471
View File
@@ -0,0 +1,471 @@
//! Telemetry (one JSONL line per finished run), `orch report`, `orch eval A B` and the `orch bench` case runner.
use crate::profile::Profile;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Rec {
pub ts: u64,
pub run: String,
/// Task id (eval: case name).
pub task: String,
pub profile: String,
pub hx_version: String,
/// done | failed | needs-human | requeued
pub status: String,
pub reason: Option<String>,
pub attempts: u32,
pub turns: u64,
pub input_tokens: u64,
pub output_tokens: u64,
pub seconds: u64,
}
impl Rec {
pub fn tokens(&self) -> u64 {
self.input_tokens + self.output_tokens
}
}
pub fn default_path() -> PathBuf {
crate::state_dir().join("telemetry.jsonl")
}
pub fn rec(r: &crate::state::Run, hx_version: &str) -> Rec {
let mut reason = r.reason.clone();
if let Some(s) = &mut reason {
*s = s.chars().take(200).collect(); // keep every line far below PIPE_BUF: appends stay atomic
}
Rec {
ts: crate::state::now(),
run: r.id.clone(),
task: r.task.clone(),
profile: r.profile.clone(),
hx_version: hx_version.into(),
status: serde_json::to_value(r.status)
.ok()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default(),
reason,
attempts: r.attempts,
turns: r.turns,
input_tokens: r.input_tokens,
output_tokens: r.output_tokens,
seconds: r
.ended
.unwrap_or_else(crate::state::now)
.saturating_sub(r.started),
}
}
pub fn append(path: &Path, r: &Rec) -> Result<()> {
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
// leading newline: a line cut short by a crash must not swallow this record (load skips blank lines)
let mut line = format!("\n{}", serde_json::to_string(r)?);
line.push('\n');
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?
.write_all(line.as_bytes())?;
Ok(())
}
/// Unparseable lines are skipped and counted on stderr (a half-written line must not kill the report).
pub fn load(path: &Path) -> Result<Vec<Rec>> {
let s =
std::fs::read_to_string(path).with_context(|| format!("telemetry {}", path.display()))?;
let (mut v, mut bad) = (vec![], 0);
for l in s.lines().filter(|l| !l.trim().is_empty()) {
match serde_json::from_str(l) {
Ok(r) => v.push(r),
Err(_) => bad += 1,
}
}
if bad > 0 {
eprintln!("{}: skipped {bad} unreadable line(s)", path.display());
}
Ok(v)
}
/// `hx --version` with the same cleared environment hx runs with. "unknown" when it cannot be told.
/// ponytail: no timeout; clap's --version returns at once. Add one if a wrapper script ever hangs here.
pub fn hx_version(p: &Profile) -> String {
let mut parts = p.hx.split_whitespace();
let Some(bin) = parts.next() else {
return "unknown".into();
};
let mut cmd = std::process::Command::new(bin);
cmd.args(parts)
.arg("--version")
.env_clear()
.envs(crate::run::hx_env(std::env::vars(), p));
if let Some(h) = &p.home {
cmd.env("HOME", h);
}
cmd.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
match cmd.output() {
Ok(o) if o.status.success() => {
let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
if s.is_empty() { "unknown".into() } else { s }
}
_ => "unknown".into(),
}
}
// ---- aggregation -----------------------------------------------------------------------------
#[derive(Default, Debug, PartialEq)]
pub struct Agg {
pub runs: u64,
pub done: u64,
pub needs_human: u64,
pub failed: u64,
pub requeued: u64,
pub retries: u64,
pub tokens: u64,
pub tokens_done: u64,
pub secs: Vec<u64>,
}
impl Agg {
pub fn add(&mut self, r: &Rec) {
self.runs += 1;
match r.status.as_str() {
"done" => {
self.done += 1;
self.tokens_done += r.tokens();
}
"needs-human" => self.needs_human += 1,
"requeued" => {
self.requeued += 1;
return; // never attempted to completion: no quality or cost signal
}
_ => self.failed += 1,
}
self.retries += u64::from(r.attempts.saturating_sub(1));
self.tokens += r.tokens();
self.secs.push(r.seconds);
}
pub fn finished(&self) -> u64 {
self.runs - self.requeued
}
pub fn rate(&self) -> Option<f64> {
(self.finished() > 0).then(|| self.done as f64 * 100.0 / self.finished() as f64)
}
pub fn tok_per_run(&self) -> Option<u64> {
(self.finished() > 0).then(|| self.tokens / self.finished())
}
pub fn tok_per_done(&self) -> Option<u64> {
(self.done > 0).then(|| self.tokens_done / self.done)
}
pub fn median_secs(&self) -> Option<u64> {
let mut s = self.secs.clone();
s.sort_unstable();
(!s.is_empty()).then(|| s[s.len() / 2])
}
}
fn group<'a, K: Ord>(recs: &'a [Rec], key: impl Fn(&'a Rec) -> K) -> BTreeMap<K, Agg> {
let mut m: BTreeMap<K, Agg> = BTreeMap::new();
for r in recs {
m.entry(key(r)).or_default().add(r);
}
m
}
fn n(v: Option<u64>) -> String {
v.map_or("-".into(), |v| v.to_string())
}
fn pct(v: Option<f64>) -> String {
v.map_or("-".into(), |v| format!("{v:.0}%"))
}
pub fn report(recs: &[Rec]) -> String {
let mut out = format!(
"{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6}\n",
"profile",
"hx-version",
"runs",
"done",
"rate",
"human",
"failed",
"requeue",
"tok/run",
"tok/done",
"med-s"
);
let mut line = |a: &str, b: &str, g: &Agg| {
out.push_str(&format!(
"{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6}\n",
a,
b,
g.runs,
g.done,
pct(g.rate()),
g.needs_human,
g.failed,
g.requeued,
n(g.tok_per_run()),
n(g.tok_per_done()),
n(g.median_secs())
));
};
for ((p, v), g) in group(recs, |r| (r.profile.clone(), r.hx_version.clone())) {
line(&p, &v, &g);
}
let mut all = Agg::default();
recs.iter().for_each(|r| all.add(r));
line("all", "", &all);
out.push_str(&format!(
"retries (extra hx attempts after a red gate): {}\n",
all.retries
));
out
}
/// Per case: done/finished and tokens per run, A vs B, plus a verdict. Returns (text, regressed).
pub fn compare(a: &[Rec], b: &[Rec], a_name: &str, b_name: &str) -> (String, bool) {
let (ga, gb) = (group(a, |r| r.task.clone()), group(b, |r| r.task.clone()));
let mut cases: Vec<&String> = ga.keys().chain(gb.keys()).collect();
cases.sort();
cases.dedup();
let cell = |g: Option<&Agg>| match g {
Some(g) if g.finished() > 0 => format!("{}/{}", g.done, g.finished()),
_ => "-".into(),
};
let delta = |x: Option<u64>, y: Option<u64>| match (x, y) {
(Some(x), Some(y)) if x > 0 => format!("{:+.0}%", (y as f64 - x as f64) * 100.0 / x as f64),
_ => "-".into(),
};
let mut out = format!("A = {a_name}\nB = {b_name}\n\n");
out.push_str(&format!(
"{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n",
"case", "A done", "B done", "A tok/run", "B tok/run", "tokens"
));
for c in cases {
let (x, y) = (ga.get(c), gb.get(c));
let (tx, ty) = (x.and_then(Agg::tok_per_run), y.and_then(Agg::tok_per_run));
out.push_str(&format!(
"{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n",
c,
cell(x),
cell(y),
n(tx),
n(ty),
delta(tx, ty)
));
}
let (mut ta, mut tb) = (Agg::default(), Agg::default());
a.iter().for_each(|r| ta.add(r));
b.iter().for_each(|r| tb.add(r));
out.push_str(&format!(
"{:<24} {:>7} {:>7} {:>9} {:>9} {:>7}\n",
"total",
cell(Some(&ta)),
cell(Some(&tb)),
n(ta.tok_per_run()),
n(tb.tok_per_run()),
delta(ta.tok_per_run(), tb.tok_per_run())
));
let regressed = matches!((ta.rate(), tb.rate()), (Some(x), Some(y)) if y < x - 1e-9);
let diff = match (ta.rate(), tb.rate()) {
(Some(x), Some(y)) => format!("{:+.0} pp", y - x),
_ => "n/a".into(),
};
out.push_str(&format!(
"\nsuccess rate A {} -> B {} ({diff}){}\n",
pct(ta.rate()),
pct(tb.rate()),
if regressed { " REGRESSION" } else { "" }
));
(out, regressed)
}
// ---- bench -----------------------------------------------------------------------------------
/// Case dir: `task.md`, `files/` (initial repo content), `gate.sh` (exit 0 = solved). Optional `solution/` overlay
/// (used by the case-set self-check, never shown to the agent).
pub struct Case {
pub name: String,
pub dir: PathBuf,
}
pub fn cases(dir: &Path) -> Result<Vec<Case>> {
let mut v = vec![];
for e in std::fs::read_dir(dir)
.with_context(|| format!("eval dir {}", dir.display()))?
.flatten()
{
let d = e.path();
if d.join("task.md").is_file() {
for need in ["files", "gate.sh"] {
if !d.join(need).exists() {
bail!("case {} lacks {need}", d.display());
}
}
v.push(Case {
name: e.file_name().to_string_lossy().into(),
dir: d,
});
}
}
v.sort_by(|a, b| a.name.cmp(&b.name));
if v.is_empty() {
bail!("no cases (dirs with task.md) in {}", dir.display());
}
Ok(v)
}
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for e in std::fs::read_dir(from)?.flatten() {
let (src, dst) = (e.path(), to.join(e.file_name()));
if src.is_dir() {
copy_tree(&src, &dst)?;
} else {
std::fs::copy(&src, &dst)?;
}
}
Ok(())
}
/// Fresh git repo with the case's initial files, returns its path.
pub fn fixture(c: &Case) -> Result<PathBuf> {
let repo =
crate::state_dir()
.join("bench")
.join(format!("{}-{}", c.name, crate::state::now_ms()));
copy_tree(&c.dir.join("files"), &repo)?;
for args in [
vec!["init", "-q", "-b", "main"],
vec!["add", "-A"],
vec!["commit", "-qm", "case"],
] {
let st = std::process::Command::new("git")
.args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"])
.args(&args)
.current_dir(&repo)
.status()?;
anyhow::ensure!(
st.success(),
"git {} failed in {}",
args.join(" "),
repo.display()
);
}
Ok(repo)
}
#[cfg(test)]
mod tests {
use super::*;
fn r(task: &str, status: &str, attempts: u32, tok: u64, secs: u64) -> Rec {
Rec {
ts: 1,
run: format!("{task}-1"),
task: task.into(),
profile: "p".into(),
hx_version: "v1".into(),
status: status.into(),
reason: None,
attempts,
turns: 1,
input_tokens: tok,
output_tokens: 0,
seconds: secs,
}
}
#[test]
fn aggregation() {
let mut g = Agg::default();
for x in [
r("a", "done", 1, 100, 10),
r("b", "done", 3, 300, 30),
r("c", "needs-human", 3, 500, 20),
r("d", "failed", 1, 0, 1),
r("e", "requeued", 1, 999, 99),
] {
g.add(&x);
}
assert_eq!((g.runs, g.finished(), g.done, g.retries), (5, 4, 2, 4));
assert_eq!(g.rate(), Some(50.0));
assert_eq!(
(g.tok_per_run(), g.tok_per_done(), g.median_secs()),
(Some(225), Some(200), Some(20))
);
assert_eq!(Agg::default().rate(), None);
}
#[test]
fn report_groups_by_profile_and_version() {
let mut b = r("a", "done", 1, 100, 5);
b.hx_version = "v2".into();
let t = report(&[r("a", "done", 1, 200, 5), r("b", "failed", 1, 0, 5), b]);
assert!(
t.contains("v1") && t.contains("v2") && t.contains("50%") && t.contains("100%"),
"{t}"
);
assert!(t.lines().last().unwrap().starts_with("retries"), "{t}");
}
#[test]
fn compare_flags_regressions_only() {
let a = [r("x", "done", 1, 100, 1), r("y", "done", 1, 100, 1)];
let b_bad = [r("x", "done", 1, 150, 1), r("y", "failed", 1, 80, 1)];
let (t, reg) = compare(&a, &b_bad, "A", "B");
assert!(
reg && t.contains("REGRESSION") && t.contains("-50 pp") && t.contains("+50%"),
"{t}"
);
let (t, reg) = compare(&b_bad, &a, "A", "B");
assert!(!reg && t.contains("+50 pp"), "{t}");
// a case only in B shows up with "-" for A; requeued runs do not count
let (t, reg) = compare(
&a,
&[
r("x", "done", 1, 100, 1),
r("z", "done", 1, 1, 1),
r("y", "requeued", 1, 0, 0),
],
"A",
"B",
);
assert!(
!reg && t.lines().any(|l| l.starts_with('z') && l.contains(" - ")),
"{t}"
);
}
#[test]
fn roundtrip_and_bad_lines() {
let d = std::env::temp_dir().join(format!("orch-tel-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let p = d.join("t.jsonl");
append(&p, &r("a", "done", 1, 1, 1)).unwrap();
std::fs::OpenOptions::new()
.append(true)
.open(&p)
.unwrap()
.write_all(b"{half a li")
.unwrap();
append(&p, &r("b", "done", 1, 1, 1)).unwrap();
assert_eq!(
load(&p).unwrap().len(),
2,
"garbage line skipped, neighbours kept"
);
let _ = std::fs::remove_dir_all(&d);
}
}
+1
View File
@@ -52,6 +52,7 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
worktree: crate::state_dir().join("worktrees").join(&id),
id,
title: task.title.clone(),
task: task.id.clone(),
profile: profile.into(),
repo,
status: Status::Queued,
+4
View File
@@ -29,6 +29,9 @@ impl Status {
pub struct Run {
pub id: String,
pub title: String,
/// Task id from the source (eval: case name).
#[serde(default)]
pub task: String,
pub profile: String,
pub repo: PathBuf,
pub branch: String,
@@ -151,6 +154,7 @@ mod tests {
Run {
id: id.into(),
title: "t".into(),
task: "t".into(),
profile: "p".into(),
repo: "/r".into(),
branch: "b".into(),