From 374cf28aedb98cef0b5534a0af781ce948650636 Mon Sep 17 00:00:00 2001 From: hermes <3+hermes@noreply.localhost> Date: Fri, 13 Nov 2026 18:30:06 +0000 Subject: [PATCH] Count cache tokens in telemetry, budget and report (#16) --- src/adapter.rs | 3 ++- src/main.rs | 2 +- src/report.rs | 45 ++++++++++++++++++++++++++++++++++++++++++--- src/run.rs | 26 ++++++++++++++++++++++---- src/state.rs | 14 ++++++++++++++ tests/e2e.py | 9 +++++++-- tests/fake_hx.py | 4 ++-- 7 files changed, 90 insertions(+), 13 deletions(-) diff --git a/src/adapter.rs b/src/adapter.rs index f63d1f2..88038e9 100644 --- a/src/adapter.rs +++ b/src/adapter.rs @@ -218,7 +218,8 @@ fn run_json(t: &Task, r: &Run) -> Value { json!({"task": t, "run": { "id": r.id, "status": r.status, "reason": r.reason, "branch": r.branch, "repo": r.repo, "worktree": r.worktree, "attempts": r.attempts, "input_tokens": r.input_tokens, - "output_tokens": r.output_tokens, "published": r.published, + "output_tokens": r.output_tokens, "cache_read_tokens": r.cache_read_tokens, + "cache_write_tokens": r.cache_write_tokens, "published": r.published, }}) } diff --git a/src/main.rs b/src/main.rs index 416acf4..deb400b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -227,7 +227,7 @@ fn main() -> Result { r.id, st.as_str().unwrap(), end.saturating_sub(r.started), - r.input_tokens + r.output_tokens, + r.total_tokens(), r.title, r.reason.map(|x| format!(" [{x}]")).unwrap_or_default() ); diff --git a/src/report.rs b/src/report.rs index 8f56c31..fe40b91 100644 --- a/src/report.rs +++ b/src/report.rs @@ -20,14 +20,22 @@ pub struct Rec { pub reason: Option, pub attempts: u32, pub turns: u64, + /// Fresh (uncached) input; old lines without the cache fields count them as 0. pub input_tokens: u64, pub output_tokens: u64, + #[serde(default)] + pub cache_read_tokens: u64, + #[serde(default)] + pub cache_write_tokens: u64, pub seconds: u64, } impl Rec { pub fn tokens(&self) -> u64 { - self.input_tokens + self.output_tokens + self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens + } + pub fn input_all(&self) -> u64 { + self.input_tokens + self.cache_read_tokens + self.cache_write_tokens } } @@ -55,6 +63,8 @@ pub fn rec(r: &crate::state::Run, hx_version: &str) -> Rec { turns: r.turns, input_tokens: r.input_tokens, output_tokens: r.output_tokens, + cache_read_tokens: r.cache_read_tokens, + cache_write_tokens: r.cache_write_tokens, seconds: r .ended .unwrap_or_else(crate::state::now) @@ -132,6 +142,8 @@ pub struct Agg { pub retries: u64, pub tokens: u64, pub tokens_done: u64, + pub cache_read: u64, + pub input_all: u64, pub secs: Vec, } @@ -150,6 +162,8 @@ impl Agg { } _ => self.failed += 1, } + self.cache_read += r.cache_read_tokens; + self.input_all += r.input_all(); self.retries += u64::from(r.attempts.saturating_sub(1)); self.tokens += r.tokens(); self.secs.push(r.seconds); @@ -160,6 +174,10 @@ impl Agg { pub fn rate(&self) -> Option { (self.finished() > 0).then(|| self.done as f64 * 100.0 / self.finished() as f64) } + /// Share of input served from the prompt cache. + pub fn cache_pct(&self) -> Option { + (self.input_all > 0).then(|| self.cache_read as f64 * 100.0 / self.input_all as f64) + } pub fn tok_per_run(&self) -> Option { (self.finished() > 0).then(|| self.tokens / self.finished()) } @@ -191,7 +209,7 @@ fn pct(v: Option) -> String { pub fn report(recs: &[Rec]) -> String { let mut out = format!( - "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6}\n", + "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", "profile", "hx-version", "runs", @@ -202,11 +220,12 @@ pub fn report(recs: &[Rec]) -> String { "requeue", "tok/run", "tok/done", + "cache", "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", + "{:<14} {:<22} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n", a, b, g.runs, @@ -217,6 +236,7 @@ pub fn report(recs: &[Rec]) -> String { g.requeued, n(g.tok_per_run()), n(g.tok_per_done()), + pct(g.cache_pct()), n(g.median_secs()) )); }; @@ -383,6 +403,8 @@ mod tests { turns: 1, input_tokens: tok, output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, seconds: secs, } } @@ -408,6 +430,23 @@ mod tests { assert_eq!(Agg::default().rate(), None); } + #[test] + fn cache_tokens_count_and_old_lines_parse() { + let mut x = r("a", "done", 1, 2, 5); + x.output_tokens = 161; + x.cache_read_tokens = 39375; + x.cache_write_tokens = 142; + assert_eq!((x.tokens(), x.input_all()), (39680, 39519)); // the numbers from a real `hx stats` + let mut g = Agg::default(); + g.add(&x); + assert_eq!(g.cache_pct().map(|p| p.round()), Some(100.0)); + assert_eq!(g.tok_per_run(), Some(39680)); + // telemetry written before the cache fields existed still loads, cache counts as 0 + let old: Rec = serde_json::from_str(r#"{"ts":1,"run":"r","task":"t","profile":"p","hx_version":"v","status":"done","reason":null,"attempts":1,"turns":1,"input_tokens":134,"output_tokens":0,"seconds":1}"#).unwrap(); + assert_eq!((old.tokens(), old.cache_read_tokens), (134, 0)); + assert_eq!(Agg::default().cache_pct(), None); + } + #[test] fn report_groups_by_profile_and_version() { let mut b = r("a", "done", 1, 100, 5); diff --git a/src/run.rs b/src/run.rs index 6c51282..ebaf2a1 100644 --- a/src/run.rs +++ b/src/run.rs @@ -65,6 +65,8 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result { gate_exit: None, input_tokens: 0, output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, session: None, attempts: 0, turns: 0, @@ -96,6 +98,20 @@ pub fn hx_env(vars: impl Iterator, p: &Profile) -> Vec< .collect() } +/// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input +/// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude. +fn usage_total(u: &Value) -> u64 { + [ + "input_tokens", + "output_tokens", + "cache_read_tokens", + "cache_write_tokens", + ] + .iter() + .map(|k| u[*k].as_u64().unwrap_or(0)) + .sum() +} + /// hx surfaces provider rejections as `api 429: ...`; also match the usual wording. fn is_rate_limit(reason: &str) -> bool { let r = reason.to_lowercase(); @@ -343,8 +359,7 @@ fn run_hx( } Some("stream") if ev["event"]["type"] == "done" => { let u = &ev["event"]["usage"]; - r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0) - + u["output_tokens"].as_u64().unwrap_or(0); + r.spent_tokens += usage_total(u); if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) { killed = Some("budget:tokens".to_string()); } @@ -372,8 +387,11 @@ fn run_hx( r.hx_pid = None; if let Some(d) = &done { let u = &d["usage"]; - r.input_tokens = u["input_tokens"].as_u64().unwrap_or(0); - r.output_tokens = u["output_tokens"].as_u64().unwrap_or(0); + let f = |k: &str| u[k].as_u64().unwrap_or(0); + r.input_tokens = f("input_tokens"); + r.output_tokens = f("output_tokens"); + r.cache_read_tokens = f("cache_read_tokens"); + r.cache_write_tokens = f("cache_write_tokens"); r.session = d["session"].as_str().map(String::from); } if let Some(k) = killed { diff --git a/src/state.rs b/src/state.rs index f6ab507..de929c1 100644 --- a/src/state.rs +++ b/src/state.rs @@ -19,6 +19,13 @@ pub enum Status { NeedsHuman, } +impl Run { + /// Everything the model processed: fresh + cached input + output. + pub fn total_tokens(&self) -> u64 { + self.input_tokens + self.cache_read_tokens + self.cache_write_tokens + self.output_tokens + } +} + impl Status { pub fn active(self) -> bool { matches!(self, Status::Queued | Status::Running | Status::Gating) @@ -45,8 +52,13 @@ pub struct Run { pub ended: Option, pub hx_exit: Option, pub gate_exit: Option, + /// Fresh (uncached) input only; with the cache fields below this is everything hx sent. pub input_tokens: u64, pub output_tokens: u64, + #[serde(default)] + pub cache_read_tokens: u64, + #[serde(default)] + pub cache_write_tokens: u64, pub session: Option, /// hx runs so far (1 + retries). #[serde(default)] @@ -169,6 +181,8 @@ mod tests { gate_exit: None, input_tokens: 0, output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, session: None, attempts: 0, turns: 0, diff --git a/tests/e2e.py b/tests/e2e.py index a6ee040..b372665 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -51,6 +51,7 @@ def check(p, st, reason=None): profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n') s = check(run("ok", body="WRITE"), "done") assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s +assert (s["cache_read_tokens"], s["cache_write_tokens"]) == (1000, 10), s assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout s = check(run("nowrite", body="NEVERFIX", env={"MODE": "NEVER"}), "needs-human", "gate-failed") assert s["attempts"] == 3 and s["gate_exit"] != 0, s # 1 + 2 retries @@ -73,8 +74,10 @@ profile("t", "[budget]\nwall_secs = 1\n") check(run("slow", "t", body="HANG"), "failed", "timeout") profile("m", "[budget]\nmax_turns = 2\n") check(run("turns", "m", body="TURNS=5"), "failed", "budget:turns") -profile("k", "[budget]\nmax_tokens = 200\n") -check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens") +# 1160 tokens per turn incl. cache (fresh-only counting would be 150/turn and never reach 2000 in 5 turns) +profile("k", "[budget]\nmax_tokens = 2000\n") +s = check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens") +assert s["turns"] == 2 and s["spent_tokens"] == 2320, s # yolo without sandbox is refused at load time profile("y", "yolo = true\n") @@ -274,11 +277,13 @@ recs = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()] assert len(recs) >= 30, len(recs) ok_rec = next(r for r in recs if r["task"] == "ok") assert (ok_rec["status"], ok_rec["profile"], ok_rec["hx_version"], ok_rec["input_tokens"], ok_rec["attempts"]) == ("done", "p", "hx 9.9.9", 100, 1), ok_rec +assert (ok_rec["cache_read_tokens"], ok_rec["cache_write_tokens"]) == (1000, 10), ok_rec assert next(r for r in recs if r["task"] == "nowrite")["status"] == "needs-human" assert next(r for r in recs if r["task"] == "nowrite")["attempts"] == 3 assert any(r["status"] == "requeued" for r in recs) rep = subprocess.run([orch, "report"], env=env, capture_output=True, text=True).stdout assert "hx 9.9.9" in rep and "profile" in rep and rep.splitlines()[-1].startswith("retries"), rep +assert "cache" in rep.splitlines()[0], rep allrow = next(l for l in rep.splitlines() if l.startswith("all")) assert allrow.split()[1] == str(len([r for r in recs])), (allrow, len(recs)) # a half-written line (crash) is skipped and does not hide the next record diff --git a/tests/fake_hx.py b/tests/fake_hx.py index bdb1fb2..98ec9dd 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -53,9 +53,9 @@ if "QUOTA" in body: e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}}) for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): e({"type": "turn_start"}) - e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) + e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50, "cache_read_tokens": 1000, "cache_write_tokens": 10}}}) if "WRITE" in body: open("out.txt", "w").write("x") if "--session" in sys.argv: open("retry-prompt.txt", "w").write(body) if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") -e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) +e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50, "cache_read_tokens": 1000, "cache_write_tokens": 10}, "session": "/s.jsonl"})