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    /// Rows in the whole session. `messages` alone cannot answer "was anything dropped": a short
145    /// session's middle is the whole transcript (`#606`).
146    pub total_messages: usize,
147    /// Whether the middle is narrower than the session — i.e. whether a compaction would happen at
148    /// all. False means the document is what one *would* say, not what happened.
149    pub drops: bool,
150    /// Characters of transcript the handoff replaces (content plus tool-call arguments).
151    pub middle_chars: usize,
152    pub handoff_chars: usize,
153    pub budget_chars: usize,
154    pub compile_micros: u128,
155    pub passes: usize,
156    /// False when two compiles of the same input differ — a defect, not a measurement.
157    pub identical: bool,
158    pub faithfulness: Faithfulness,
159    /// Only `compare` fills this: `verify` answers a question about the document, not about how
160    /// much of the transcript survived into it.
161    pub retention: Option<Retention>,
162}
163
164impl Measurement {
165    /// Share of the middle's characters the document occupies. Above 1.0 the handoff is taller
166    /// than what it replaces, which is worth seeing before a budget hides it.
167    pub fn share(&self) -> f64 {
168        if self.middle_chars == 0 {
169            0.0
170        } else {
171            self.handoff_chars as f64 / self.middle_chars as f64
172        }
173    }
174
175    pub fn millis(&self) -> f64 {
176        self.compile_micros as f64 / 1000.0
177    }
178}
179
180// ---------------------------------------------------------------------------------------
181// Measuring
182// ---------------------------------------------------------------------------------------
183
184/// Compile `dropped` `passes` times and report what came out. Faithfulness is checked against
185/// `rows` — the whole session — because a ref must resolve against the archive, not against the
186/// slice the compiler happened to see.
187pub fn measure(
188    rows: &[Message],
189    dropped: &[Message],
190    session: &str,
191    budget: usize,
192    passes: usize,
193    with_retention: bool,
194) -> Measurement {
195    let limits = Limits::default();
196
197    let started = Instant::now();
198    let first = super::compile(dropped, &Options::new(session, budget));
199    let compile_micros = started.elapsed().as_micros();
200
201    let mut identical = true;
202    for _ in 1..passes.max(1) {
203        // A fresh `Options` per pass: nothing carried over from the previous compile can be
204        // what made this one agree.
205        if super::compile(dropped, &Options::new(session, budget)) != first {
206            identical = false;
207        }
208    }
209
210    Measurement {
211        session: session.to_string(),
212        messages: dropped.len(),
213        // `#606`: the middle a short session is given is the whole transcript, so the two numbers
214        // are equal exactly when nothing was over the rail.
215        total_messages: rows.len(),
216        drops: dropped.len() < rows.len(),
217        middle_chars: raw_chars(dropped),
218        handoff_chars: first.chars().count(),
219        budget_chars: budget,
220        compile_micros,
221        passes: passes.max(1),
222        identical,
223        faithfulness: faithfulness(&first, rows),
224        retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
225    }
226}
227
228/// The `verify` question: same bytes twice, and refs that resolve.
229pub fn verify(
230    rows: &[Message],
231    dropped: &[Message],
232    session: &str,
233    budget: usize,
234    passes: usize,
235) -> Measurement {
236    measure(rows, dropped, session, budget, passes, false)
237}
238
239/// The `compare` question: what it cost and what it kept.
240pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
241    measure(rows, dropped, session, budget, 1, true)
242}
243
244/// Retention of the four ledgers against the transcript's own facts.
245pub fn retention(handoff: &str, facts: &Facts) -> Retention {
246    Retention {
247        files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
248        commands: Tally::of(facts.commands.iter().cloned(), handoff),
249        errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
250        // A blocked entry renders as `- {ref} {tool} `{target}` — status: excerpt`, so its head
251        // is the identity and its tail is what the budget may have elided.
252        blocked: Tally::of(
253            facts.blocked.iter().map(|entry| head_of(entry).to_string()),
254            handoff,
255        ),
256    }
257}
258
259fn head_of(entry: &str) -> &str {
260    entry.split(" — ").next().unwrap_or(entry).trim()
261}
262
263/// Characters of transcript a handoff replaces: every message's content plus the arguments of
264/// every call, which is what a drop would otherwise cost.
265fn raw_chars(messages: &[Message]) -> usize {
266    messages
267        .iter()
268        .map(|m| {
269            m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
270                + m.tool_calls
271                    .iter()
272                    .map(|tc| {
273                        tc.function.name.chars().count() + tc.function.arguments.chars().count()
274                    })
275                    .sum::<usize>()
276        })
277        .sum()
278}
279
280// ---------------------------------------------------------------------------------------
281// Faithfulness: the Session Log, re-read row by row
282// ---------------------------------------------------------------------------------------
283
284/// What one line's check produced.
285struct Checked {
286    fragments: usize,
287    violations: Vec<Violation>,
288}
289
290impl Checked {
291    fn ok(fragments: usize) -> Self {
292        Checked {
293            fragments,
294            violations: Vec::new(),
295        }
296    }
297
298    fn bad(fragments: usize, violation: Violation) -> Self {
299        Checked {
300            fragments,
301            violations: vec![violation],
302        }
303    }
304}
305
306/// Check every Session Log line against the row its `[#N]` cites.
307pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
308    let limits = Limits::default();
309    let index: HashMap<u64, &Message> = rows
310        .iter()
311        .filter_map(|m| m.seq.map(|seq| (seq, m)))
312        .collect();
313    // A result line names the tool that produced it, and that name lives on the *call* row —
314    // this row only names it by id. Resolve the pairing once, up front.
315    let calls: HashMap<&str, String> = rows
316        .iter()
317        .flat_map(|m| m.tool_calls.iter())
318        .filter(|tc| !tc.id.is_empty())
319        .map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
320        .collect();
321
322    let mut report = Faithfulness::default();
323    let (_, sections) = split_sections(handoff);
324    let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
325        return report;
326    };
327
328    for line in log.lines() {
329        let Some((reference, rest)) = parse_ref(line) else {
330            continue; // the marker paragraph and the "… N older log line(s) omitted" notes
331        };
332        report.lines += 1;
333        let Ref::Row(seq) = reference else {
334            // A `[tN]` line names a position in a transcript nobody stored. There is no row to
335            // read it back from, and saying so is better than quietly not checking it.
336            report.unreferenced += 1;
337            continue;
338        };
339        let Some(row) = index.get(&seq) else {
340            report.unreferenced += 1;
341            continue;
342        };
343
344        let checked = if let Some(body) = rest.strip_prefix("→ ") {
345            check_call(&seq, line, body, row, &limits)
346        } else if let Some(body) = rest.strip_prefix("← ") {
347            check_result(&seq, line, body, row, &calls)
348        } else if let Some((role, body)) = rest.split_once(": ") {
349            check_role(&seq, line, role, body, row)
350        } else {
351            Checked::bad(
352                0,
353                Violation {
354                    at: seq,
355                    line: line.to_string(),
356                    fragment: rest.to_string(),
357                    why: "the line has no shape the renderer produces".to_string(),
358                },
359            )
360        };
361
362        report.fragments += checked.fragments;
363        report.violations.extend(checked.violations);
364    }
365    report
366}
367
368/// `[#12] user: …` → (12, "user: …"); `[t4] user: …` → a position, which names no row.
369fn parse_ref(line: &str) -> Option<(Ref, &str)> {
370    if let Some(rest) = line.strip_prefix("[#") {
371        let (digits, after) = rest.split_once(']')?;
372        return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
373    }
374    let rest = line.strip_prefix("[t")?;
375    let (digits, after) = rest.split_once(']')?;
376    digits.parse::<usize>().ok()?;
377    Some((Ref::Position, after.trim_start()))
378}
379
380/// The two kinds of citation a log line can carry.
381enum Ref {
382    Row(u64),
383    Position,
384}
385
386fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
387    let expected = match role {
388        "user" => Role::User,
389        "assistant" => Role::Assistant,
390        other => {
391            return Checked::bad(
392                0,
393                Violation {
394                    at: *seq,
395                    line: line.to_string(),
396                    fragment: other.to_string(),
397                    why: "the line names a role the compiler never writes".to_string(),
398                },
399            )
400        }
401    };
402    let fragments = fragments_of(body);
403    let mut violations = Vec::new();
404    if row.role != expected {
405        violations.push(Violation {
406            at: *seq,
407            line: line.to_string(),
408            fragment: role.to_string(),
409            why: format!("row {seq} is a {:?} row, not {role}", row.role),
410        });
411    }
412    let hay = haystack(row, expected);
413    for fragment in &fragments {
414        if !hay.iter().any(|text| text.contains(fragment)) {
415            violations.push(Violation {
416                at: *seq,
417                line: line.to_string(),
418                fragment: fragment.clone(),
419                why: format!("row {seq} does not contain it"),
420            });
421        }
422    }
423    Checked {
424        fragments: fragments.len(),
425        violations,
426    }
427}
428
429fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
430    // `tool: \`target\``, or a bare `tool` when the call carried nothing quotable.
431    let (name, target) = match body.split_once(": `") {
432        Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
433        None => (body.trim(), ""),
434    };
435    let matched = row.tool_calls.iter().any(|tc| {
436        let (call_name, call_target) = call_summary(tc, limits);
437        call_name == name && (target.is_empty() || call_target == target)
438    });
439    if matched {
440        return Checked::ok(1);
441    }
442    Checked::bad(
443        1,
444        Violation {
445            at: *seq,
446            line: line.to_string(),
447            fragment: name.to_string(),
448            why: if row.tool_calls.is_empty() {
449                format!("row {seq} is not a call row")
450            } else {
451                format!("no call on row {seq} names `{name}` with that target")
452            },
453        },
454    )
455}
456
457fn check_result(
458    seq: &u64,
459    line: &str,
460    body: &str,
461    row: &Message,
462    calls: &HashMap<&str, String>,
463) -> Checked {
464    let (name, rest) = match body.split_once(' ') {
465        Some((name, rest)) => (name, rest),
466        None => (body, ""),
467    };
468    let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
469    let fragments = fragments_of(excerpt);
470    let mut violations = Vec::new();
471
472    if let Some(id) = row.tool_call_id.as_deref() {
473        if let Some(paired) = calls.get(id) {
474            if paired != name {
475                violations.push(Violation {
476                    at: *seq,
477                    line: line.to_string(),
478                    fragment: name.to_string(),
479                    why: format!("row {seq} answers a call to `{paired}`"),
480                });
481            }
482        }
483    }
484    let hay = haystack(row, Role::Tool);
485    for fragment in &fragments {
486        if !hay.iter().any(|text| text.contains(fragment)) {
487            violations.push(Violation {
488                at: *seq,
489                line: line.to_string(),
490                fragment: fragment.clone(),
491                why: format!("row {seq} does not contain it"),
492            });
493        }
494    }
495    Checked {
496        fragments: fragments.len(),
497        violations,
498    }
499}
500
501// ---------------------------------------------------------------------------------------
502// Reading a row the way the renderer read it
503// ---------------------------------------------------------------------------------------
504
505/// Every place a fragment could legitimately be found in this row.
506///
507/// Content goes through `clean`, the function the renderer used, so quotation and whitespace
508/// differences cannot be mistaken for invention. Tool results are often JSON and the excerpt
509/// the renderer quotes is a *decoded* string from inside it — so the JSON's own string values
510/// are searched too, which is what stops an escaped newline from looking like a fabricated
511/// sentence.
512fn haystack(row: &Message, role: Role) -> Vec<String> {
513    let raw = row.text_with_pictures();
514    let raw = if role == Role::Assistant {
515        strip_think(&raw)
516    } else {
517        raw.to_string()
518    };
519    let mut out = vec![normalise(&raw)];
520    if let Ok(serde_json::Value::Object(map)) =
521        serde_json::from_str::<serde_json::Value>(raw.trim())
522    {
523        for value in map.values() {
524            let mut strings = Vec::new();
525            collect_strings(value, &mut strings);
526            for text in strings {
527                out.push(normalise(&text));
528            }
529        }
530    }
531    out
532}
533
534fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
535    match value {
536        serde_json::Value::String(text) => out.push(text.clone()),
537        serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
538        serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
539        _ => {}
540    }
541}
542
543fn normalise(text: &str) -> String {
544    clean(text, WHOLE)
545}
546
547/// Distinct alphanumeric fragments of a line, in order of first appearance.
548fn fragments_of(text: &str) -> Vec<String> {
549    let mut seen: Vec<String> = Vec::new();
550    for fragment in text.split(|c: char| !c.is_alphanumeric()) {
551        if fragment.chars().count() < MIN_FRAGMENT {
552            continue;
553        }
554        if !seen.iter().any(|s| s == fragment) {
555            seen.push(fragment.to_string());
556        }
557    }
558    seen
559}
560
561#[cfg(test)]
562mod tests;