stats: log auto routing per prompt, hx stats routing report

This commit is contained in:
hermes committed 2026-11-10 22:08:55 +00:00
1 parent 478c007271
commit c6c4add124
5 files changed
+87 -1

No files matched your search

+1 -1
View File
@@ -92,7 +92,7 @@ One-turn override, with or without auto: start the prompt with `@opus fix this`,
Within a tier the highest-versioned model is used (`claude-opus-5-5` over `claude-opus-4-1-20250805`, `gpt-5.6-sol` over `gpt-5.5-sol`), whatever order the API lists them in; no model id is hard-coded except the offline fallback list and your `[auto]` pins. Within a tier the highest-versioned model is used (`claude-opus-5-5` over `claude-opus-4-1-20250805`, `gpt-5.6-sol` over `gpt-5.5-sol`), whatever order the API lists them in; no model id is hard-coded except the offline fallback list and your `[auto]` pins.
Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` lists requests per model and the cache re-written after each switch. Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` shows the auto choices (prompts and mean score per tier, how often a tier was held, how often the next prompt went up again; raw lines in `<session>.route`) and lists requests per model and the cache re-written after each switch.
```toml ```toml
[auto] # all optional [auto] # all optional
+1
View File
@@ -579,6 +579,7 @@ async fn main() -> Result<()> {
hx_core::stats::model_report(&Session::open(&session)?) hx_core::stats::model_report(&Session::open(&session)?)
); );
print!("{}", hx_core::stats::task_report(&Session::open(&session)?)); print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!("{}", hx_core::stats::route_report(&session));
print!("{}", hx_core::stats::sub_report(&session)); print!("{}", hx_core::stats::sub_report(&session));
return Ok(()); return Ok(());
} }
+23
View File
@@ -399,6 +399,29 @@ impl Router {
} }
} }
/// One line per routed prompt in `<session>.route` (JSON), read back by `hx stats`: the data to
/// tune the keyword lists and thresholds from. Best effort.
pub fn log(session: &std::path::Path, sig: &Signals, p: &Pick, effort: Effort, forced: bool) {
use std::io::Write;
let line = serde_json::json!({
"ts": hx_ai::auth::now_ms() / 1000,
"model": p.model,
"tier": p.tier.name(),
"wanted": sig.tier.name(),
"score": sig.score,
"effort": effort.name(),
"ctx": sig.ctx,
"hits": sig.hits,
"forced": forced,
});
// ponytail: a failed log write must not fail the prompt
let _ = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(session.with_extension("route"))
.and_then(|mut f| writeln!(f, "{line}"));
}
/// What `@word` at the start of a prompt asks for. /// What `@word` at the start of a prompt asks for.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Target { pub enum Target {
+53
View File
@@ -47,6 +47,59 @@ pub fn task_report(s: &Session) -> String {
} }
/// One line per subagent log in `<session>.sub/` (empty when there are none). /// One line per subagent log in `<session>.sub/` (empty when there are none).
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
pub fn route_report(session_path: &std::path::Path) -> String {
let Ok(t) = std::fs::read_to_string(session_path.with_extension("route")) else {
return String::new();
};
let rows: Vec<serde_json::Value> = t
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect();
if rows.is_empty() {
return String::new();
}
let rank = |s: &str| {
["fast", "balanced", "deep", "max"]
.iter()
.position(|x| *x == s)
};
let s = |r: &serde_json::Value, k: &str| r[k].as_str().unwrap_or("?").to_string();
let (mut per, mut held, mut forced, mut up) = (HashMap::<String, (u32, i64)>::new(), 0, 0, 0);
for (i, r) in rows.iter().enumerate() {
if r["forced"].as_bool() == Some(true) {
forced += 1;
continue;
}
let e = per.entry(s(r, "tier")).or_default();
e.0 += 1;
e.1 += r["score"].as_i64().unwrap_or(0);
held += (s(r, "tier") != s(r, "wanted")) as u32;
if let Some(n) = rows.get(i + 1)
&& n["forced"].as_bool() != Some(true)
&& rank(&s(n, "tier")) > rank(&s(r, "tier"))
{
up += 1;
}
}
let mut o = String::from("auto routing:\n");
for t in ["fast", "balanced", "deep", "max"] {
if let Some((n, sum)) = per.get(t) {
let _ = writeln!(
o,
" {t}: {n} prompts, mean score {:.1}",
*sum as f64 / *n as f64
);
}
}
let _ = writeln!(
o,
" held back by hysteresis: {held}, next prompt went up a tier: {up}, forced with @: {forced}"
);
o
}
pub fn sub_report(session_path: &std::path::Path) -> String { pub fn sub_report(session_path: &std::path::Path) -> String {
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub")) let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
.into_iter() .into_iter()
+9
View File
@@ -250,6 +250,13 @@ impl Switcher {
self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)? self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)?
}; };
agent.set_effort(effort); agent.set_effort(effort);
route::log(
agent.session().path(),
&sig,
&pick,
effort,
forced.is_some(),
);
Ok(Some(Routed { Ok(Some(Routed {
pick: route::Pick { effort, ..pick }, pick: route::Pick { effort, ..pick },
sw, sw,
@@ -528,6 +535,8 @@ mod tests {
("claude-haiku-x", "claude-haiku-x") ("claude-haiku-x", "claude-haiku-x")
); );
assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild"); assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild");
let rep = crate::stats::route_report(a.session().path());
assert!(rep.contains("fast: 1 prompts"), "{rep}");
sw.set_model(&mut a, "claude-sonnet-x").unwrap(); sw.set_model(&mut a, "claude-sonnet-x").unwrap();
assert!(!sw.is_auto()); assert!(!sw.is_auto());
assert!( assert!(