Count cache tokens in telemetry, budget and report (#16)

This commit was merged in pull request #16.
This commit is contained in:
hermes committed 2026-11-13 18:30:06 +00:00
1 parent 67a5bdedb9
commit 374cf28aed
7 files changed
+90 -13

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,