Skip to main content

eclipse_core/compact/
verify.rs

1//! The compaction harness (22d): measure the handoff instead of trusting it.
2//!
3//! Three questions live here, and none of them needs a model:
4//!
5//! * **Is it stable?** A compiler that is deterministic by accident still produces two
6//!   different documents on two runs, two builds or two machines. The answer is a byte
7//!   comparison of two fresh compiles, which is a thing a test can hold and a person can read.
8//! * **What did it cost, and what did it keep?** There is no A/B partner any more: the
9//!   model-written summary was deleted (decisions #12), so the baseline is the transcript
10//!   itself. Cost is wall clock and size; retention is mechanical — every path, command,
11//!   error name and blocked call the middle holds, found or not found in the rendered handoff.
12//! * **Is every `[#N]` line actually readable at row N?** This is the one that matters most.
13//!   The handoff *tells the model* that `session_search(around_message_id=N)` recovers what was
14//!   omitted, so a line whose ref lands on a row that does not say that is the document lying
15//!   about its own evidence. Every alphanumeric fragment of every log line is re-read from the
16//!   row it cites; a fragment that is not there is a violation, not a rounding error.
17//!
18//! What is deliberately *not* here: the judgement pass. It is the one part that calls a model,
19//! so it cannot be byte-compared, and the compiler half is what must hold at any transcript
20//! size. `compile` is called with no `previous` handoff and no judgement, which is exactly the
21//! deterministic body the loop ships when the pass is off or its answer is rejected.
22
23use std::collections::HashMap;
24use std::time::Instant;
25
26use crate::message::{Message, Role};
27
28use super::{
29    call_summary, clean, facts, split_sections, strip_think, Facts, Limits, Options, LOG_HEADING,
30};
31
32/// The shortest fragment worth calling a claim. Two characters is "ok", "1", "in" — noise a
33/// normalisation can move around; three is something a reader could check.
34const MIN_FRAGMENT: usize = 3;
35
36/// A ceiling for `clean`, whose only other job here is normalisation: big enough that it never
37/// elides, small enough that `limit * 2 + 64` cannot overflow.
38const WHOLE: usize = 1 << 40;
39
40/// How many misses a tally names before it stops. A report that listed every miss at a
41/// thousand-message transcript would be a second transcript.
42const KEEP_MISSING: usize = 8;
43
44// ---------------------------------------------------------------------------------------
45// Reports
46// ---------------------------------------------------------------------------------------
47
48/// How many of a set of facts survived into the handoff.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct Tally {
51    pub total: usize,
52    pub present: usize,
53    pub missing: Vec<String>,
54}
55
56impl Tally {
57    fn of<I: IntoIterator<Item = String>>(items: I, handoff: &str) -> Self {
58        let mut tally = Tally::default();
59        for item in items {
60            tally.total += 1;
61            if handoff.contains(&item) {
62                tally.present += 1;
63            } else if tally.missing.len() < KEEP_MISSING {
64                tally.missing.push(item);
65            }
66        }
67        tally
68    }
69
70    pub fn all_present(&self) -> bool {
71        self.present == self.total
72    }
73}
74
75/// Retention per ledger. Separate tallies rather than one number, because the four failures
76/// mean different things: a missing path is a place the model can no longer look, a missing
77/// error name is a diagnosis it will repeat, a missing command is work it will redo.
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct Retention {
80    pub files: Tally,
81    pub commands: Tally,
82    pub errors: Tally,
83    pub blocked: Tally,
84}
85
86impl Retention {
87    /// (present, total) across every ledger.
88    pub fn totals(&self) -> (usize, usize) {
89        let all = [&self.files, &self.commands, &self.errors, &self.blocked];
90        (
91            all.iter().map(|t| t.present).sum(),
92            all.iter().map(|t| t.total).sum(),
93        )
94    }
95
96    pub fn ledgers(&self) -> [(&'static str, &Tally); 4] {
97        [
98            ("files", &self.files),
99            ("commands", &self.commands),
100            ("errors", &self.errors),
101            ("blocked", &self.blocked),
102        ]
103    }
104}
105
106/// One log line that does not survive being re-read from the row it cites.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Violation {
109    /// The row the line pointed at.
110    pub at: u64,
111    /// The whole log line, as it appears in the handoff.
112    pub line: String,
113    /// The fragment that could not be found, or the structural complaint when there is no
114    /// fragment to name.
115    pub fragment: String,
116    pub why: String,
117}
118
119/// The Session Log, checked line by line against the transcript.
120#[derive(Debug, Clone, Default, PartialEq, Eq)]
121pub struct Faithfulness {
122    pub lines: usize,
123    /// Distinct fragments actually looked for, across all lines. Reported so "no violations"
124    /// cannot be the answer of a check that never ran.
125    pub fragments: usize,
126    /// Log lines whose ref names no stored row. Only reachable from an in-memory transcript
127    /// (`[tN]` refs), which nothing can be read back from — counted, not called a defect.
128    pub unreferenced: usize,
129    pub violations: Vec<Violation>,
130}
131
132impl Faithfulness {
133    pub fn ok(&self) -> bool {
134        self.violations.is_empty()
135    }
136}
137
138/// Everything one run of the harness measured.
139#[derive(Debug, Clone)]
140pub struct Measurement {
141    pub session: String,
142    /// Rows in the middle window — the ones the handoff stands in for.
143    pub messages: usize,
144    /// Characters of transcript the handoff replaces (content plus tool-call arguments).
145    pub middle_chars: usize,
146    pub handoff_chars: usize,
147    pub budget_chars: usize,
148    pub compile_micros: u128,
149    pub passes: usize,
150    /// False when two compiles of the same input differ — a defect, not a measurement.
151    pub identical: bool,
152    pub faithfulness: Faithfulness,
153    /// Only `compare` fills this: `verify` answers a question about the document, not about how
154    /// much of the transcript survived into it.
155    pub retention: Option<Retention>,
156}
157
158impl Measurement {
159    /// Share of the middle's characters the document occupies. Above 1.0 the handoff is taller
160    /// than what it replaces, which is worth seeing before a budget hides it.
161    pub fn share(&self) -> f64 {
162        if self.middle_chars == 0 {
163            0.0
164        } else {
165            self.handoff_chars as f64 / self.middle_chars as f64
166        }
167    }
168
169    pub fn millis(&self) -> f64 {
170        self.compile_micros as f64 / 1000.0
171    }
172}
173
174// ---------------------------------------------------------------------------------------
175// Measuring
176// ---------------------------------------------------------------------------------------
177
178/// Compile `dropped` `passes` times and report what came out. Faithfulness is checked against
179/// `rows` — the whole session — because a ref must resolve against the archive, not against the
180/// slice the compiler happened to see.
181pub fn measure(
182    rows: &[Message],
183    dropped: &[Message],
184    session: &str,
185    budget: usize,
186    passes: usize,
187    with_retention: bool,
188) -> Measurement {
189    let limits = Limits::default();
190
191    let started = Instant::now();
192    let first = super::compile(dropped, &Options::new(session, budget));
193    let compile_micros = started.elapsed().as_micros();
194
195    let mut identical = true;
196    for _ in 1..passes.max(1) {
197        // A fresh `Options` per pass: nothing carried over from the previous compile can be
198        // what made this one agree.
199        if super::compile(dropped, &Options::new(session, budget)) != first {
200            identical = false;
201        }
202    }
203
204    Measurement {
205        session: session.to_string(),
206        messages: dropped.len(),
207        middle_chars: raw_chars(dropped),
208        handoff_chars: first.chars().count(),
209        budget_chars: budget,
210        compile_micros,
211        passes: passes.max(1),
212        identical,
213        faithfulness: faithfulness(&first, rows),
214        retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
215    }
216}
217
218/// The `verify` question: same bytes twice, and refs that resolve.
219pub fn verify(
220    rows: &[Message],
221    dropped: &[Message],
222    session: &str,
223    budget: usize,
224    passes: usize,
225) -> Measurement {
226    measure(rows, dropped, session, budget, passes, false)
227}
228
229/// The `compare` question: what it cost and what it kept.
230pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
231    measure(rows, dropped, session, budget, 1, true)
232}
233
234/// Retention of the four ledgers against the transcript's own facts.
235pub fn retention(handoff: &str, facts: &Facts) -> Retention {
236    Retention {
237        files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
238        commands: Tally::of(facts.commands.iter().cloned(), handoff),
239        errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
240        // A blocked entry renders as `- {ref} {tool} `{target}` — status: excerpt`, so its head
241        // is the identity and its tail is what the budget may have elided.
242        blocked: Tally::of(
243            facts.blocked.iter().map(|entry| head_of(entry).to_string()),
244            handoff,
245        ),
246    }
247}
248
249fn head_of(entry: &str) -> &str {
250    entry.split(" — ").next().unwrap_or(entry).trim()
251}
252
253/// Characters of transcript a handoff replaces: every message's content plus the arguments of
254/// every call, which is what a drop would otherwise cost.
255fn raw_chars(messages: &[Message]) -> usize {
256    messages
257        .iter()
258        .map(|m| {
259            m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
260                + m.tool_calls
261                    .iter()
262                    .map(|tc| {
263                        tc.function.name.chars().count() + tc.function.arguments.chars().count()
264                    })
265                    .sum::<usize>()
266        })
267        .sum()
268}
269
270// ---------------------------------------------------------------------------------------
271// Faithfulness: the Session Log, re-read row by row
272// ---------------------------------------------------------------------------------------
273
274/// What one line's check produced.
275struct Checked {
276    fragments: usize,
277    violations: Vec<Violation>,
278}
279
280impl Checked {
281    fn ok(fragments: usize) -> Self {
282        Checked {
283            fragments,
284            violations: Vec::new(),
285        }
286    }
287
288    fn bad(fragments: usize, violation: Violation) -> Self {
289        Checked {
290            fragments,
291            violations: vec![violation],
292        }
293    }
294}
295
296/// Check every Session Log line against the row its `[#N]` cites.
297pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
298    let limits = Limits::default();
299    let index: HashMap<u64, &Message> = rows
300        .iter()
301        .filter_map(|m| m.seq.map(|seq| (seq, m)))
302        .collect();
303    // A result line names the tool that produced it, and that name lives on the *call* row —
304    // this row only names it by id. Resolve the pairing once, up front.
305    let calls: HashMap<&str, String> = rows
306        .iter()
307        .flat_map(|m| m.tool_calls.iter())
308        .filter(|tc| !tc.id.is_empty())
309        .map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
310        .collect();
311
312    let mut report = Faithfulness::default();
313    let (_, sections) = split_sections(handoff);
314    let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
315        return report;
316    };
317
318    for line in log.lines() {
319        let Some((reference, rest)) = parse_ref(line) else {
320            continue; // the marker paragraph and the "… N older log line(s) omitted" notes
321        };
322        report.lines += 1;
323        let Ref::Row(seq) = reference else {
324            // A `[tN]` line names a position in a transcript nobody stored. There is no row to
325            // read it back from, and saying so is better than quietly not checking it.
326            report.unreferenced += 1;
327            continue;
328        };
329        let Some(row) = index.get(&seq) else {
330            report.unreferenced += 1;
331            continue;
332        };
333
334        let checked = if let Some(body) = rest.strip_prefix("→ ") {
335            check_call(&seq, line, body, row, &limits)
336        } else if let Some(body) = rest.strip_prefix("← ") {
337            check_result(&seq, line, body, row, &calls)
338        } else if let Some((role, body)) = rest.split_once(": ") {
339            check_role(&seq, line, role, body, row)
340        } else {
341            Checked::bad(
342                0,
343                Violation {
344                    at: seq,
345                    line: line.to_string(),
346                    fragment: rest.to_string(),
347                    why: "the line has no shape the renderer produces".to_string(),
348                },
349            )
350        };
351
352        report.fragments += checked.fragments;
353        report.violations.extend(checked.violations);
354    }
355    report
356}
357
358/// `[#12] user: …` → (12, "user: …"); `[t4] user: …` → a position, which names no row.
359fn parse_ref(line: &str) -> Option<(Ref, &str)> {
360    if let Some(rest) = line.strip_prefix("[#") {
361        let (digits, after) = rest.split_once(']')?;
362        return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
363    }
364    let rest = line.strip_prefix("[t")?;
365    let (digits, after) = rest.split_once(']')?;
366    digits.parse::<usize>().ok()?;
367    Some((Ref::Position, after.trim_start()))
368}
369
370/// The two kinds of citation a log line can carry.
371enum Ref {
372    Row(u64),
373    Position,
374}
375
376fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
377    let expected = match role {
378        "user" => Role::User,
379        "assistant" => Role::Assistant,
380        other => {
381            return Checked::bad(
382                0,
383                Violation {
384                    at: *seq,
385                    line: line.to_string(),
386                    fragment: other.to_string(),
387                    why: "the line names a role the compiler never writes".to_string(),
388                },
389            )
390        }
391    };
392    let fragments = fragments_of(body);
393    let mut violations = Vec::new();
394    if row.role != expected {
395        violations.push(Violation {
396            at: *seq,
397            line: line.to_string(),
398            fragment: role.to_string(),
399            why: format!("row {seq} is a {:?} row, not {role}", row.role),
400        });
401    }
402    let hay = haystack(row, expected);
403    for fragment in &fragments {
404        if !hay.iter().any(|text| text.contains(fragment)) {
405            violations.push(Violation {
406                at: *seq,
407                line: line.to_string(),
408                fragment: fragment.clone(),
409                why: format!("row {seq} does not contain it"),
410            });
411        }
412    }
413    Checked {
414        fragments: fragments.len(),
415        violations,
416    }
417}
418
419fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
420    // `tool: \`target\``, or a bare `tool` when the call carried nothing quotable.
421    let (name, target) = match body.split_once(": `") {
422        Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
423        None => (body.trim(), ""),
424    };
425    let matched = row.tool_calls.iter().any(|tc| {
426        let (call_name, call_target) = call_summary(tc, limits);
427        call_name == name && (target.is_empty() || call_target == target)
428    });
429    if matched {
430        return Checked::ok(1);
431    }
432    Checked::bad(
433        1,
434        Violation {
435            at: *seq,
436            line: line.to_string(),
437            fragment: name.to_string(),
438            why: if row.tool_calls.is_empty() {
439                format!("row {seq} is not a call row")
440            } else {
441                format!("no call on row {seq} names `{name}` with that target")
442            },
443        },
444    )
445}
446
447fn check_result(
448    seq: &u64,
449    line: &str,
450    body: &str,
451    row: &Message,
452    calls: &HashMap<&str, String>,
453) -> Checked {
454    let (name, rest) = match body.split_once(' ') {
455        Some((name, rest)) => (name, rest),
456        None => (body, ""),
457    };
458    let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
459    let fragments = fragments_of(excerpt);
460    let mut violations = Vec::new();
461
462    if let Some(id) = row.tool_call_id.as_deref() {
463        if let Some(paired) = calls.get(id) {
464            if paired != name {
465                violations.push(Violation {
466                    at: *seq,
467                    line: line.to_string(),
468                    fragment: name.to_string(),
469                    why: format!("row {seq} answers a call to `{paired}`"),
470                });
471            }
472        }
473    }
474    let hay = haystack(row, Role::Tool);
475    for fragment in &fragments {
476        if !hay.iter().any(|text| text.contains(fragment)) {
477            violations.push(Violation {
478                at: *seq,
479                line: line.to_string(),
480                fragment: fragment.clone(),
481                why: format!("row {seq} does not contain it"),
482            });
483        }
484    }
485    Checked {
486        fragments: fragments.len(),
487        violations,
488    }
489}
490
491// ---------------------------------------------------------------------------------------
492// Reading a row the way the renderer read it
493// ---------------------------------------------------------------------------------------
494
495/// Every place a fragment could legitimately be found in this row.
496///
497/// Content goes through `clean`, the function the renderer used, so quotation and whitespace
498/// differences cannot be mistaken for invention. Tool results are often JSON and the excerpt
499/// the renderer quotes is a *decoded* string from inside it — so the JSON's own string values
500/// are searched too, which is what stops an escaped newline from looking like a fabricated
501/// sentence.
502fn haystack(row: &Message, role: Role) -> Vec<String> {
503    let raw = row.text_with_pictures();
504    let raw = if role == Role::Assistant {
505        strip_think(&raw)
506    } else {
507        raw.to_string()
508    };
509    let mut out = vec![normalise(&raw)];
510    if let Ok(serde_json::Value::Object(map)) =
511        serde_json::from_str::<serde_json::Value>(raw.trim())
512    {
513        for value in map.values() {
514            let mut strings = Vec::new();
515            collect_strings(value, &mut strings);
516            for text in strings {
517                out.push(normalise(&text));
518            }
519        }
520    }
521    out
522}
523
524fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
525    match value {
526        serde_json::Value::String(text) => out.push(text.clone()),
527        serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
528        serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
529        _ => {}
530    }
531}
532
533fn normalise(text: &str) -> String {
534    clean(text, WHOLE)
535}
536
537/// Distinct alphanumeric fragments of a line, in order of first appearance.
538fn fragments_of(text: &str) -> Vec<String> {
539    let mut seen: Vec<String> = Vec::new();
540    for fragment in text.split(|c: char| !c.is_alphanumeric()) {
541        if fragment.chars().count() < MIN_FRAGMENT {
542            continue;
543        }
544        if !seen.iter().any(|s| s == fragment) {
545            seen.push(fragment.to_string());
546        }
547    }
548    seen
549}
550
551#[cfg(test)]
552mod tests;