Files
hx/crates/hx-core/src/stats.rs
T
hermes 359a5058d7
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats
2026-10-02 11:57:59 +00:00

335 lines
11 KiB
Rust

//! Token report for a session file: API usage per request, cache hit rate, and which tool
//! results are the most expensive to carry (bytes x requests they were resent in).
use crate::session::Session;
use hx_ai::{ContentBlock, Role};
use std::collections::HashMap;
use std::fmt::Write;
/// One line per subagent log in `<session>.sub/` (empty when there are none).
pub fn sub_report(session_path: &std::path::Path) -> String {
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
.collect();
files.sort();
let mut o = String::new();
let mut tot = 0;
for p in &files {
let Ok(s) = Session::open(p) else { continue };
let (mut n, mut inp, mut out) = (0, 0, 0);
for (_, u) in s.usages() {
n += 1;
inp += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
out += u.output_tokens;
}
tot += inp + out;
let _ = writeln!(
o,
" {} requests {n} input {inp} output {out}",
p.file_stem().unwrap_or_default().to_string_lossy()
);
}
if files.is_empty() {
return o;
}
format!(
"subagents ({} runs, {tot} tokens, not in the numbers above):\n{o}",
files.len()
)
}
pub fn report(s: &Session) -> String {
let msgs = s.messages();
let mut o = String::new();
// per-request usage (all entries, so compaction roots are included)
let (mut n, mut inp, mut cr, mut cw, mut out) = (0u64, 0u64, 0u64, 0u64, 0u64);
let mut last_in = 0;
for (_, u) in s.usages() {
n += 1;
inp += u.input_tokens;
cr += u.cache_read_tokens;
cw += u.cache_write_tokens;
out += u.output_tokens;
last_in = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
}
if n == 0 {
return "no usage recorded (session predates usage logging)\n".into();
}
let total_in = inp + cr + cw;
let _ = writeln!(
o,
"requests {n} input {total_in} (fresh {inp}, cache read {cr}, cache write {cw}) output {out}"
);
let _ = writeln!(
o,
"cache hit {:.0}% of input avg input/request {} last request {last_in}",
100.0 * cr as f64 / total_in.max(1) as f64,
total_in / n
);
// Requests that wrote a lot of cache: a regular spacing (every 8th turn) points at masking steps,
// irregular ones at cache expiry (idle > 5 min) or other prefix changes.
let writes: Vec<(usize, u64, u64)> = s
.usages()
.iter()
.enumerate()
.map(|(k, (_, u))| (k + 1, u.cache_write_tokens, u.cache_read_tokens))
.collect();
let avg_w = cw / n;
let mut big_w: Vec<_> = writes.iter().filter(|w| w.1 > 2 * avg_w.max(1)).collect();
big_w.sort_by_key(|w| std::cmp::Reverse(w.1));
let _ = writeln!(
o,
"requests writing > 2x the average cache write ({avg_w}): {} of {n}",
big_w.len()
);
for (k, w, r) in big_w.iter().take(10) {
let _ = writeln!(o, " request {k}: write {w}, read {r}");
}
// assistant side: bytes the model produced that are resent every request
let (mut text_b, mut call_b) = (0usize, 0usize);
for m in msgs.iter().filter(|m| m.role == Role::Assistant) {
for b in &m.content {
match b {
ContentBlock::Text { text } => text_b += text.len(),
ContentBlock::ToolUse { input, .. } => call_b += input.to_string().len(),
_ => {}
}
}
}
let _ = writeln!(
o,
"assistant output kept in history: text {} tok, tool-call arguments {} tok (once)",
text_b / 4,
call_b / 4
);
// carried cost of tool results on the current path
let mut names: HashMap<&str, &str> = HashMap::new();
for m in &msgs {
for b in &m.content {
if let ContentBlock::ToolUse { id, name, .. } = b {
names.insert(id, name);
}
}
}
// Replay the requests: request k sent the messages before the k-th assistant message, masked
// the way the agent masks them. sent[i] = bytes of item i summed over the requests carrying it;
// raw[i] = same without masking.
let len_of = |b: &ContentBlock| match b {
ContentBlock::ToolResult { content, .. } => content.len(),
_ => 0,
};
let masks = s.masks();
let mut sent = vec![0usize; msgs.len()];
let mut raw = vec![0usize; msgs.len()];
for (end, _) in msgs
.iter()
.enumerate()
.filter(|(_, m)| m.role == Role::Assistant)
{
// boundary the agent recorded for this request; older files used the stepwise rule
let b = masks[end].unwrap_or_else(|| crate::mask::target_boundary(&msgs[..end]));
let masked = crate::mask::mask_old_results(msgs[..end].to_vec(), b);
for (i, m) in masked.iter().enumerate() {
let text_len = |m: &hx_ai::Message| {
m.content
.iter()
.map(|b| match b {
ContentBlock::Text { text } if m.role == Role::User && i > 0 => text.len(),
other => len_of(other),
})
.sum::<usize>()
};
sent[i] += text_len(m);
raw[i] += text_len(&msgs[i]);
}
}
// name -> (calls, bytes once, bytes resent as sent, bytes resent unmasked)
let mut by: HashMap<String, (usize, usize, usize, usize)> = HashMap::new();
let mut big: Vec<(usize, usize, String)> = vec![];
for (i, m) in msgs.iter().enumerate() {
for b in &m.content {
let (name, len) = match b {
ContentBlock::ToolResult {
tool_use_id,
content,
..
} => (
names.get(tool_use_id.as_str()).copied().unwrap_or("?"),
content.len(),
),
ContentBlock::Text { text } if m.role == Role::User && i > 0 => {
("(injected text)", text.len())
}
_ => continue,
};
let e = by.entry(name.to_string()).or_default();
e.0 += 1;
e.1 += len;
// a message may hold several results; attribute its total proportionally
let share = |tot: usize| {
let once = m
.content
.iter()
.map(|b| match b {
ContentBlock::Text { text } if m.role == Role::User && i > 0 => text.len(),
other => len_of(other),
})
.sum::<usize>()
.max(1);
tot * len / once
};
e.2 += share(sent[i]);
e.3 += share(raw[i]);
big.push((share(sent[i]), len, format!("msg {i} {name}")));
}
}
let mut rows: Vec<_> = by.into_iter().collect();
rows.sort_by_key(|(_, v)| std::cmp::Reverse(v.3));
let _ = writeln!(
o,
"\ncarried cost on current branch, replaying the request masking (tokens ~ bytes/4):"
);
let _ = writeln!(
o,
"{:<18}{:>6}{:>12}{:>14}{:>16}",
"tool", "calls", "tok once", "resent sent", "resent unmasked"
);
for (k, (c, b, sent, raw)) in rows {
let _ = writeln!(
o,
"{k:<18}{c:>6}{:>12}{:>14}{:>16}",
b / 4,
sent / 4,
raw / 4
);
}
big.sort_by_key(|b| std::cmp::Reverse(b.0));
let _ = writeln!(o, "\ntop 5 single items by resent tokens (as sent):");
for (carried, len, what) in big.into_iter().take(5) {
let _ = writeln!(o, " {what}: {} tok once, {} resent", len / 4, carried / 4);
}
o
}
#[cfg(test)]
mod tests {
use super::*;
use hx_ai::{Message, Usage};
#[test]
fn report_counts() {
let d = tempfile::tempdir().unwrap();
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
s.append(Message::user("go")).unwrap();
let u = Usage {
input_tokens: 10,
output_tokens: 5,
cache_read_tokens: 90,
cache_write_tokens: 0,
};
s.append_full(
Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
id: "t".into(),
name: "read".into(),
input: serde_json::json!({}),
}],
},
None,
Some(u.clone()),
)
.unwrap();
s.append(Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: "t".into(),
content: "x".repeat(4000),
is_error: false,
}],
})
.unwrap();
s.append_full(Message::user("done"), None, Some(u)).unwrap();
let r = report(&s);
assert!(
r.contains("requests 2") && r.contains("cache hit 90%"),
"{r}"
);
assert!(r.contains("read") && r.contains("1000"), "{r}");
}
#[test]
fn replay_applies_masking() {
let d = tempfile::tempdir().unwrap();
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
s.append(Message::user("go")).unwrap();
for i in 0..20 {
s.append(Message {
role: Role::Assistant,
content: vec![ContentBlock::ToolUse {
id: format!("t{i}"),
name: "bash".into(),
input: serde_json::json!({}),
}],
})
.unwrap();
s.append(Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: format!("t{i}"),
content: "x".repeat(8000),
is_error: false,
}],
})
.unwrap();
}
s.append_full(Message::user("end"), None, Some(Default::default()))
.unwrap();
let r = report(&s);
let row = r.lines().find(|l| l.starts_with("bash")).unwrap();
let n: Vec<usize> = row
.split_whitespace()
.skip(1)
.map(|x| x.parse().unwrap())
.collect();
// calls, once, sent, unmasked
assert!(n[2] < n[3] && n[2] > 0, "{row}");
}
#[test]
fn reports_cache_writes_and_assistant_bytes() {
let d = tempfile::tempdir().unwrap();
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
s.append(Message::user("go")).unwrap();
for i in 0..5 {
let u = Usage {
cache_write_tokens: if i == 3 { 10_000 } else { 100 },
..Default::default()
};
s.append_full(
Message {
role: Role::Assistant,
content: vec![ContentBlock::Text {
text: "y".repeat(400),
}],
},
None,
Some(u),
)
.unwrap();
s.append(Message::user("more")).unwrap();
}
let r = report(&s);
assert!(r.contains("request 4: write 10000"), "{r}");
assert!(r.contains("text 500 tok"), "{r}");
}
}