From 1c69c8ed3431cb3728da748f623828e59a31a9ce Mon Sep 17 00:00:00 2001 From: hermes Date: Thu, 1 Oct 2026 20:52:42 +0000 Subject: [PATCH] stats: log per-request usage in session, add 'hx stats ' token report --- crates/hx-cli/src/main.rs | 6 ++ crates/hx-core/src/agent.rs | 8 +- crates/hx-core/src/lib.rs | 1 + crates/hx-core/src/session.rs | 22 +++++ crates/hx-core/src/stats.rs | 153 ++++++++++++++++++++++++++++++++++ 5 files changed, 188 insertions(+), 2 deletions(-) create mode 100644 crates/hx-core/src/stats.rs diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index c322733..dfcfc37 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -53,6 +53,8 @@ enum Cmd { Login { provider: Kind }, /// Remove stored credentials for a provider. Logout { provider: Kind }, + /// Token report for a session file (usage, cache hit rate, costliest tool results). + Stats { session: std::path::PathBuf }, /// Connect to configured MCP servers and print tools + index/eager token cost. Mcp, /// Serve lens diagnostics + LSP navigation as an MCP server over stdio. @@ -278,6 +280,10 @@ async fn main() -> Result<()> { return Ok(()); } Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?), + Some(Cmd::Stats { session }) => { + print!("{}", hx_core::stats::report(&Session::open(session)?)); + return Ok(()); + } Some(Cmd::Mcp) => { let cwd = std::env::current_dir()?; let hub = hx_mcp::Hub::start( diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 65f58c1..7805865 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -174,8 +174,12 @@ impl Agent { } fn push(&mut self, m: Message) -> Result<(), Error> { + self.push_with(m, None) + } + + fn push_with(&mut self, m: Message, usage: Option) -> Result<(), Error> { let by = (m.role == Role::Assistant).then(|| self.model.clone()); - self.session.append_by(m, by)?; + self.session.append_full(m, by, usage)?; Ok(()) } @@ -235,7 +239,7 @@ impl Agent { } let (msg, stop, usage) = done.ok_or(Error::Truncated)?; self.usage.add(&usage); - self.push(msg.clone())?; + self.push_with(msg.clone(), Some(usage))?; self.emit(Event::Message(msg.clone())).await; let calls: Vec<(String, String, serde_json::Value)> = msg diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 834026c..16ab9b5 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod context; pub mod ext; pub mod hook; pub mod session; +pub mod stats; pub mod tool; use std::collections::HashMap; diff --git a/crates/hx-core/src/session.rs b/crates/hx-core/src/session.rs index f3e7bf1..de18f59 100644 --- a/crates/hx-core/src/session.rs +++ b/crates/hx-core/src/session.rs @@ -14,6 +14,9 @@ pub struct Entry { /// Model that produced an assistant message (absent in older files). #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, + /// API usage of the request that produced this assistant message (absent in older files). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub usage: Option, } pub struct Session { @@ -60,12 +63,23 @@ impl Session { /// Append, recording which model produced it. pub fn append_by(&mut self, message: Message, model: Option) -> std::io::Result { + self.append_full(message, model, None) + } + + /// Append an assistant message with the model and request usage that produced it. + pub fn append_full( + &mut self, + message: Message, + model: Option, + usage: Option, + ) -> std::io::Result { let id = self.entries.last().map_or(0, |e| e.id + 1); let e = Entry { id, parent: self.head, message, model, + usage, }; let mut f = std::fs::OpenOptions::new() .create(true) @@ -99,6 +113,14 @@ impl Session { ok } + /// Per-request usage rows (entry id, tool results bytes in the request's input, usage), in file order. + pub fn usages(&self) -> Vec<(u64, &hx_ai::Usage)> { + self.entries + .iter() + .filter_map(|e| e.usage.as_ref().map(|u| (e.id, u))) + .collect() + } + /// Messages on the path root..=head. pub fn messages(&self) -> Vec { let mut out = vec![]; diff --git a/crates/hx-core/src/stats.rs b/crates/hx-core/src/stats.rs new file mode 100644 index 0000000..25bb220 --- /dev/null +++ b/crates/hx-core/src/stats.rs @@ -0,0 +1,153 @@ +//! 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; + +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 + ); + + // 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); + } + } + } + let asst_after: Vec = { + let mut c = 0; + let mut v: Vec = msgs + .iter() + .rev() + .map(|m| { + let r = c; + c += (m.role == Role::Assistant) as usize; + r + }) + .collect(); + v.reverse(); + v + }; + // name -> (calls, bytes, carried bytes) + let mut by: HashMap = 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; + e.2 += len * asst_after[i]; + big.push((len * asst_after[i], len, format!("msg {i} {name}"))); + } + } + let mut rows: Vec<_> = by.into_iter().collect(); + rows.sort_by_key(|(_, v)| std::cmp::Reverse(v.2)); + let _ = writeln!(o, "\ncarried cost on current branch (tokens ~ bytes/4):"); + let _ = writeln!( + o, + "{:<18}{:>6}{:>12}{:>14}", + "tool", "calls", "tok once", "tok resent" + ); + for (k, (c, b, carried)) in rows { + let _ = writeln!(o, "{k:<18}{c:>6}{:>12}{:>14}", b / 4, carried / 4); + } + big.sort_by_key(|b| std::cmp::Reverse(b.0)); + let _ = writeln!(o, "\ntop 5 single items by resent tokens:"); + 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}"); + } +}