use std::collections::HashMap;
use std::time::Instant;
use crate::message::{Message, Role};
use super::{
call_summary, clean, facts, split_sections, strip_think, Facts, Limits, Options, LOG_HEADING,
};
const MIN_FRAGMENT: usize = 3;
const WHOLE: usize = 1 << 40;
const KEEP_MISSING: usize = 8;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Tally {
pub total: usize,
pub present: usize,
pub missing: Vec<String>,
}
impl Tally {
fn of<I: IntoIterator<Item = String>>(items: I, handoff: &str) -> Self {
let mut tally = Tally::default();
for item in items {
tally.total += 1;
if handoff.contains(&item) {
tally.present += 1;
} else if tally.missing.len() < KEEP_MISSING {
tally.missing.push(item);
}
}
tally
}
pub fn all_present(&self) -> bool {
self.present == self.total
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Retention {
pub files: Tally,
pub commands: Tally,
pub errors: Tally,
pub blocked: Tally,
}
impl Retention {
pub fn totals(&self) -> (usize, usize) {
let all = [&self.files, &self.commands, &self.errors, &self.blocked];
(
all.iter().map(|t| t.present).sum(),
all.iter().map(|t| t.total).sum(),
)
}
pub fn ledgers(&self) -> [(&'static str, &Tally); 4] {
[
("files", &self.files),
("commands", &self.commands),
("errors", &self.errors),
("blocked", &self.blocked),
]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub at: u64,
pub line: String,
pub fragment: String,
pub why: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Faithfulness {
pub lines: usize,
pub fragments: usize,
pub unreferenced: usize,
pub violations: Vec<Violation>,
}
impl Faithfulness {
pub fn ok(&self) -> bool {
self.violations.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct Measurement {
pub session: String,
pub messages: usize,
pub middle_chars: usize,
pub handoff_chars: usize,
pub budget_chars: usize,
pub compile_micros: u128,
pub passes: usize,
pub identical: bool,
pub faithfulness: Faithfulness,
pub retention: Option<Retention>,
}
impl Measurement {
pub fn share(&self) -> f64 {
if self.middle_chars == 0 {
0.0
} else {
self.handoff_chars as f64 / self.middle_chars as f64
}
}
pub fn millis(&self) -> f64 {
self.compile_micros as f64 / 1000.0
}
}
pub fn measure(
rows: &[Message],
dropped: &[Message],
session: &str,
budget: usize,
passes: usize,
with_retention: bool,
) -> Measurement {
let limits = Limits::default();
let started = Instant::now();
let first = super::compile(dropped, &Options::new(session, budget));
let compile_micros = started.elapsed().as_micros();
let mut identical = true;
for _ in 1..passes.max(1) {
if super::compile(dropped, &Options::new(session, budget)) != first {
identical = false;
}
}
Measurement {
session: session.to_string(),
messages: dropped.len(),
middle_chars: raw_chars(dropped),
handoff_chars: first.chars().count(),
budget_chars: budget,
compile_micros,
passes: passes.max(1),
identical,
faithfulness: faithfulness(&first, rows),
retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
}
}
pub fn verify(
rows: &[Message],
dropped: &[Message],
session: &str,
budget: usize,
passes: usize,
) -> Measurement {
measure(rows, dropped, session, budget, passes, false)
}
pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
measure(rows, dropped, session, budget, 1, true)
}
pub fn retention(handoff: &str, facts: &Facts) -> Retention {
Retention {
files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
commands: Tally::of(facts.commands.iter().cloned(), handoff),
errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
blocked: Tally::of(
facts.blocked.iter().map(|entry| head_of(entry).to_string()),
handoff,
),
}
}
fn head_of(entry: &str) -> &str {
entry.split(" — ").next().unwrap_or(entry).trim()
}
fn raw_chars(messages: &[Message]) -> usize {
messages
.iter()
.map(|m| {
m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
+ m.tool_calls
.iter()
.map(|tc| {
tc.function.name.chars().count() + tc.function.arguments.chars().count()
})
.sum::<usize>()
})
.sum()
}
struct Checked {
fragments: usize,
violations: Vec<Violation>,
}
impl Checked {
fn ok(fragments: usize) -> Self {
Checked {
fragments,
violations: Vec::new(),
}
}
fn bad(fragments: usize, violation: Violation) -> Self {
Checked {
fragments,
violations: vec![violation],
}
}
}
pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
let limits = Limits::default();
let index: HashMap<u64, &Message> = rows
.iter()
.filter_map(|m| m.seq.map(|seq| (seq, m)))
.collect();
let calls: HashMap<&str, String> = rows
.iter()
.flat_map(|m| m.tool_calls.iter())
.filter(|tc| !tc.id.is_empty())
.map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
.collect();
let mut report = Faithfulness::default();
let (_, sections) = split_sections(handoff);
let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
return report;
};
for line in log.lines() {
let Some((reference, rest)) = parse_ref(line) else {
continue; };
report.lines += 1;
let Ref::Row(seq) = reference else {
report.unreferenced += 1;
continue;
};
let Some(row) = index.get(&seq) else {
report.unreferenced += 1;
continue;
};
let checked = if let Some(body) = rest.strip_prefix("→ ") {
check_call(&seq, line, body, row, &limits)
} else if let Some(body) = rest.strip_prefix("← ") {
check_result(&seq, line, body, row, &calls)
} else if let Some((role, body)) = rest.split_once(": ") {
check_role(&seq, line, role, body, row)
} else {
Checked::bad(
0,
Violation {
at: seq,
line: line.to_string(),
fragment: rest.to_string(),
why: "the line has no shape the renderer produces".to_string(),
},
)
};
report.fragments += checked.fragments;
report.violations.extend(checked.violations);
}
report
}
fn parse_ref(line: &str) -> Option<(Ref, &str)> {
if let Some(rest) = line.strip_prefix("[#") {
let (digits, after) = rest.split_once(']')?;
return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
}
let rest = line.strip_prefix("[t")?;
let (digits, after) = rest.split_once(']')?;
digits.parse::<usize>().ok()?;
Some((Ref::Position, after.trim_start()))
}
enum Ref {
Row(u64),
Position,
}
fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
let expected = match role {
"user" => Role::User,
"assistant" => Role::Assistant,
other => {
return Checked::bad(
0,
Violation {
at: *seq,
line: line.to_string(),
fragment: other.to_string(),
why: "the line names a role the compiler never writes".to_string(),
},
)
}
};
let fragments = fragments_of(body);
let mut violations = Vec::new();
if row.role != expected {
violations.push(Violation {
at: *seq,
line: line.to_string(),
fragment: role.to_string(),
why: format!("row {seq} is a {:?} row, not {role}", row.role),
});
}
let hay = haystack(row, expected);
for fragment in &fragments {
if !hay.iter().any(|text| text.contains(fragment)) {
violations.push(Violation {
at: *seq,
line: line.to_string(),
fragment: fragment.clone(),
why: format!("row {seq} does not contain it"),
});
}
}
Checked {
fragments: fragments.len(),
violations,
}
}
fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
let (name, target) = match body.split_once(": `") {
Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
None => (body.trim(), ""),
};
let matched = row.tool_calls.iter().any(|tc| {
let (call_name, call_target) = call_summary(tc, limits);
call_name == name && (target.is_empty() || call_target == target)
});
if matched {
return Checked::ok(1);
}
Checked::bad(
1,
Violation {
at: *seq,
line: line.to_string(),
fragment: name.to_string(),
why: if row.tool_calls.is_empty() {
format!("row {seq} is not a call row")
} else {
format!("no call on row {seq} names `{name}` with that target")
},
},
)
}
fn check_result(
seq: &u64,
line: &str,
body: &str,
row: &Message,
calls: &HashMap<&str, String>,
) -> Checked {
let (name, rest) = match body.split_once(' ') {
Some((name, rest)) => (name, rest),
None => (body, ""),
};
let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
let fragments = fragments_of(excerpt);
let mut violations = Vec::new();
if let Some(id) = row.tool_call_id.as_deref() {
if let Some(paired) = calls.get(id) {
if paired != name {
violations.push(Violation {
at: *seq,
line: line.to_string(),
fragment: name.to_string(),
why: format!("row {seq} answers a call to `{paired}`"),
});
}
}
}
let hay = haystack(row, Role::Tool);
for fragment in &fragments {
if !hay.iter().any(|text| text.contains(fragment)) {
violations.push(Violation {
at: *seq,
line: line.to_string(),
fragment: fragment.clone(),
why: format!("row {seq} does not contain it"),
});
}
}
Checked {
fragments: fragments.len(),
violations,
}
}
fn haystack(row: &Message, role: Role) -> Vec<String> {
let raw = row.text_with_pictures();
let raw = if role == Role::Assistant {
strip_think(&raw)
} else {
raw.to_string()
};
let mut out = vec![normalise(&raw)];
if let Ok(serde_json::Value::Object(map)) =
serde_json::from_str::<serde_json::Value>(raw.trim())
{
for value in map.values() {
let mut strings = Vec::new();
collect_strings(value, &mut strings);
for text in strings {
out.push(normalise(&text));
}
}
}
out
}
fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
match value {
serde_json::Value::String(text) => out.push(text.clone()),
serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
_ => {}
}
}
fn normalise(text: &str) -> String {
clean(text, WHOLE)
}
fn fragments_of(text: &str) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
for fragment in text.split(|c: char| !c.is_alphanumeric()) {
if fragment.chars().count() < MIN_FRAGMENT {
continue;
}
if !seen.iter().any(|s| s == fragment) {
seen.push(fragment.to_string());
}
}
seen
}
#[cfg(test)]
mod tests;