Count cache tokens in telemetry, budget and report #16

Merged
hermes merged 1 commits from cache-tokens into main 2026-11-13 18:30:07 +00:00
7 changed files with 90 additions and 13 deletions

No files matched your search

+2 -1
View File
@@ -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,
}})
}
+1 -1
View File
@@ -227,7 +227,7 @@ fn main() -> Result<std::process::ExitCode> {
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()
);
+42 -3
View File
@@ -20,14 +20,22 @@ pub struct Rec {
pub reason: Option<String>,
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<u64>,
}
@@ -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<f64> {
(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<f64> {
(self.input_all > 0).then(|| self.cache_read as f64 * 100.0 / self.input_all as f64)
}
pub fn tok_per_run(&self) -> Option<u64> {
(self.finished() > 0).then(|| self.tokens / self.finished())
}
@@ -191,7 +209,7 @@ fn pct(v: Option<f64>) -> 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);
+22 -4
View File
@@ -65,6 +65,8 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
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<Item = (String, String)>, 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 {
+14
View File
@@ -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<u64>,
pub hx_exit: Option<i32>,
pub gate_exit: Option<i32>,
/// 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<String>,
/// 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,
+7 -2
View File
@@ -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
+2 -2
View File
@@ -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"})