Skip to main content

lean_ctx/core/eval_ab/
mod.rs

1//! Deterministic with/without output-quality eval (#232).
2//!
3//! Proves — reproducibly and with a signature — whether putting lean-ctx in front of a model
4//! changes the *quality of its answers*, not just the token count. The design separates the two
5//! sources of variance:
6//!
7//! * **Context** is deterministic. Both the baseline ("raw dump") and the lean-ctx
8//!   ("retrieve + compress") window are assembled byte-for-byte reproducibly and digested.
9//! * **The model** is the only stochastic part. It is pinned (`temperature = 0`, fixed `seed`)
10//!   and, for CI, replaced by [`model::RecordedRunner`] replaying captured real responses, so a
11//!   run is byte-identical everywhere.
12//!
13//! The pipeline per task is: [`conditions::assemble`] → [`model::ModelRunner`] →
14//! [`scorers::score_task`]. Results become a paired [`report::AbReport`], which a
15//! [`artifact::SignedAbReportV1`] turns into a portable, verifiable attestation.
16
17pub mod artifact;
18pub mod conditions;
19pub mod footprint;
20pub mod judge;
21pub mod model;
22pub mod report;
23pub mod routing_eval;
24pub mod scorers;
25pub mod suite;
26pub mod testbench;
27
28use anyhow::{Context, Result};
29
30use conditions::{Condition, DEFAULT_BUDGET_TOKENS, assemble};
31use model::{ModelRequest, ModelRunner};
32use report::{AbReport, PairRecord, ReportConfig};
33use scorers::score_task;
34use suite::EvalSuite;
35
36/// Shared hex SHA-256 used across the eval modules for context/answer/fingerprint digests.
37pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
38    use sha2::{Digest, Sha256};
39    let mut hasher = Sha256::new();
40    hasher.update(bytes);
41    crate::core::agent_identity::hex_encode(&hasher.finalize())
42}
43
44/// Identical framing for both conditions — only the CONTEXT block differs between A and B.
45/// `pub(crate)` so the testbench builds byte-identical requests (recordings interchange).
46pub(crate) const SYSTEM_PROMPT: &str = "You are a precise engineering assistant. Answer using only the provided CONTEXT. \
47If the context does not contain the answer, say so. Be concise and correct.";
48
49/// Configuration for one A/B run.
50#[derive(Debug, Clone, Copy)]
51pub struct AbRunConfig {
52    /// Token budget enforced identically on both conditions.
53    pub budget_tokens: usize,
54    /// Statistics + gate configuration.
55    pub report: ReportConfig,
56}
57
58impl Default for AbRunConfig {
59    fn default() -> Self {
60        Self {
61            budget_tokens: DEFAULT_BUDGET_TOKENS,
62            report: ReportConfig::default(),
63        }
64    }
65}
66
67/// Builds the user turn from a context window + the task prompt. `pub(crate)` so the
68/// testbench answers tasks with the exact same framing as [`run_ab`].
69pub(crate) fn build_request(context: &str, prompt: &str) -> ModelRequest {
70    ModelRequest {
71        system: SYSTEM_PROMPT.to_string(),
72        user: format!("CONTEXT:\n{context}\n\nTASK:\n{prompt}"),
73    }
74}
75
76/// Runs every task in `suite` under both conditions through `runner`, scoring each answer, and
77/// assembles the paired report. The model is the only non-deterministic input.
78pub fn run_ab(
79    suite: &EvalSuite,
80    suite_name: &str,
81    runner: &dyn ModelRunner,
82    cfg: &AbRunConfig,
83) -> Result<AbReport> {
84    suite.validate().context("validating eval suite")?;
85    let mut records = Vec::with_capacity(suite.tasks.len());
86    for task in &suite.tasks {
87        let workspace = task.resolve_workspace_path(&suite.dir)?;
88
89        let base_ctx = assemble(
90            Condition::Baseline,
91            &workspace,
92            task.query(),
93            cfg.budget_tokens,
94        )?;
95        let lean_ctx = assemble(
96            Condition::LeanCtx,
97            &workspace,
98            task.query(),
99            cfg.budget_tokens,
100        )?;
101
102        let base_resp = runner.run(&build_request(&base_ctx.text, &task.prompt))?;
103        let lean_resp = runner.run(&build_request(&lean_ctx.text, &task.prompt))?;
104
105        let base_score = score_task(task, &base_resp.text, &workspace)?;
106        let lean_score = score_task(task, &lean_resp.text, &workspace)?;
107
108        records.push(PairRecord {
109            task_id: task.id.clone(),
110            domain: task.domain.label().to_string(),
111            baseline_value: base_score.value,
112            lean_ctx_value: lean_score.value,
113            baseline_passed: base_score.passed,
114            lean_ctx_passed: lean_score.passed,
115            baseline_tokens: base_ctx.tokens,
116            lean_ctx_tokens: lean_ctx.tokens,
117            baseline_context_digest: base_ctx.digest,
118            lean_ctx_context_digest: lean_ctx.digest,
119            baseline_answer_digest: base_resp.digest(),
120            lean_ctx_answer_digest: lean_resp.digest(),
121        });
122    }
123
124    Ok(AbReport::build(
125        suite_name,
126        cfg.budget_tokens,
127        runner.fingerprint().clone(),
128        records,
129        cfg.report,
130    ))
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use model::{ModelFingerprint, ModelParams, ModelResponse, RecordedRunner, Recording};
137    use std::path::PathBuf;
138
139    /// Builds a corpus where naive path order exhausts the budget on irrelevant text.
140    fn workspace(dir: &std::path::Path) {
141        std::fs::write(
142            dir.join("a-noise.md"),
143            "Completely unrelated notes about weather, cats, and lunch plans.\n".repeat(1_000),
144        )
145        .unwrap();
146        std::fs::write(
147            dir.join("z-answer.md"),
148            "Consolidation persists artifacts to bm25, graph, knowledge and session stores.",
149        )
150        .unwrap();
151    }
152
153    #[test]
154    fn full_pipeline_runs_and_scores_deterministically() {
155        let root = tempfile::tempdir().unwrap();
156        let ws = root.path().join("corpus");
157        std::fs::create_dir_all(&ws).unwrap();
158        workspace(&ws);
159
160        let raw = r#"{"id":"t1","domain":"qa","prompt":"Which stores does consolidation persist to?","workspace":"corpus","answers":["bm25 graph knowledge session"]}"#;
161        let suite = EvalSuite::parse(raw, root.path().to_path_buf()).unwrap();
162        let task = &suite.tasks[0];
163
164        // Pre-compute the exact requests so we can record canned answers (replay scaffolding).
165        let cfg = AbRunConfig::default();
166        let base_ctx = assemble(Condition::Baseline, &ws, task.query(), cfg.budget_tokens).unwrap();
167        let lean_ctx = assemble(Condition::LeanCtx, &ws, task.query(), cfg.budget_tokens).unwrap();
168        let base_req = build_request(&base_ctx.text, &task.prompt);
169        let lean_req = build_request(&lean_ctx.text, &task.prompt);
170        assert_ne!(
171            base_req.key(),
172            lean_req.key(),
173            "fixture must keep baseline and lean-ctx requests distinct",
174        );
175
176        let fp = ModelFingerprint {
177            provider: model::PROVIDER_RECORDED.into(),
178            endpoint: "test".into(),
179            params: ModelParams {
180                model: "fixture".into(),
181                ..ModelParams::default()
182            },
183        };
184        let mut rec = Recording::new(fp);
185        rec.entries
186            .insert(base_req.key(), ModelResponse::new("I don't know."));
187        rec.entries.insert(
188            lean_req.key(),
189            ModelResponse::new("bm25, graph, knowledge and session"),
190        );
191        let runner = RecordedRunner::new(rec);
192
193        let report = run_ab(&suite, "fixture-suite", &runner, &cfg).unwrap();
194        assert_eq!(report.records.len(), 1);
195        assert!(
196            report.stats.lean_ctx_mean > report.stats.baseline_mean,
197            "lean-ctx answer should outscore the baseline: {:?}",
198            report.stats
199        );
200
201        // Determinism: a second identical run yields the same evidence digest.
202        let report2 = run_ab(&suite, "fixture-suite", &runner, &cfg).unwrap();
203        assert_eq!(
204            artifact::determinism_digest(&report),
205            artifact::determinism_digest(&report2)
206        );
207    }
208
209    #[test]
210    fn run_ab_propagates_recorded_miss() {
211        let root = tempfile::tempdir().unwrap();
212        let ws = root.path().join("corpus");
213        std::fs::create_dir_all(&ws).unwrap();
214        workspace(&ws);
215        let raw = r#"{"id":"t1","domain":"qa","prompt":"q","workspace":"corpus","answers":["x"]}"#;
216        let suite = EvalSuite::parse(raw, root.path().to_path_buf()).unwrap();
217
218        let fp = ModelFingerprint {
219            provider: model::PROVIDER_RECORDED.into(),
220            endpoint: "test".into(),
221            params: ModelParams::default(),
222        };
223        let runner = RecordedRunner::new(Recording::new(fp));
224        // Empty recording → first request misses → run errors (no silent fallback).
225        assert!(run_ab(&suite, "s", &runner, &AbRunConfig::default()).is_err());
226        let _ = PathBuf::new();
227    }
228}
229
230#[cfg(test)]
231mod accuracy_suite_tests {
232    //! Guards the committed accuracy suite (`rust/eval/accuracy-suite.ndjson`, #730)
233    //! in-process so a corpus/answer drift fails in `cargo test` — i.e. during
234    //! `dev-install` — not only when someone runs the live gate.
235
236    use super::*;
237    use std::path::Path;
238    use suite::Domain;
239
240    fn load_accuracy_suite() -> EvalSuite {
241        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("eval/accuracy-suite.ndjson");
242        EvalSuite::load(&path).expect("committed accuracy suite must load + validate")
243    }
244
245    /// The suite covers all three TTC-relevant shapes (needle, long-context QA, code).
246    #[test]
247    fn accuracy_suite_has_all_three_shapes() {
248        let suite = load_accuracy_suite();
249        let qa = suite
250            .tasks
251            .iter()
252            .filter(|t| t.domain == Domain::Qa)
253            .count();
254        let code = suite
255            .tasks
256            .iter()
257            .filter(|t| t.domain == Domain::Code)
258            .count();
259        assert!(qa >= 2, "need needle + long-context QA, got {qa}");
260        assert!(code >= 1, "need a code-edit task, got {code}");
261    }
262
263    /// Model-free accuracy floor (#730): for every QA task, lean-ctx's own
264    /// retrieve+compress context must still CONTAIN a gold answer at the default
265    /// budget — compression preserves the answer-bearing signal. We reuse the SQuAD
266    /// containment scorer over the assembled context itself, so this is the
267    /// deterministic lower bound of the "compressed ≥ raw" claim with no live model.
268    #[test]
269    fn lean_ctx_compression_preserves_every_qa_answer() {
270        let suite = load_accuracy_suite();
271        let budget = AbRunConfig::default().budget_tokens;
272        let qa = suite.tasks.iter().filter(|t| t.domain == Domain::Qa);
273        for task in qa {
274            let ws = task.workspace_path(&suite.dir);
275            let ctx = assemble(Condition::LeanCtx, &ws, task.query(), budget)
276                .unwrap_or_else(|e| panic!("assemble {}: {e:#}", task.id));
277            let score = score_task(task, &ctx.text, &ws)
278                .unwrap_or_else(|e| panic!("score {}: {e:#}", task.id));
279            assert!(
280                score.passed,
281                "lean-ctx compression dropped the answer for '{}' ({})",
282                task.id, score.detail
283            );
284        }
285    }
286
287    /// #942: the dedicated `json_crush` condition must clear the same accuracy
288    /// floor (the gold answer survives the lossless array crush) while packing the
289    /// answer in strictly fewer tokens than the raw baseline — proving the crush is
290    /// a real, answer-preserving saving on a redundant JSON payload, model-free.
291    #[test]
292    fn json_crush_condition_preserves_answer_and_beats_baseline() {
293        let suite = load_accuracy_suite();
294        let budget = AbRunConfig::default().budget_tokens;
295        let task = suite
296            .tasks
297            .iter()
298            .find(|t| t.id == "jsonqa-operator-clearance")
299            .expect("json-qa fixture present");
300        let ws = task.workspace_path(&suite.dir);
301
302        let crushed = assemble(Condition::JsonCrush, &ws, task.query(), budget)
303            .unwrap_or_else(|e| panic!("assemble json_crush: {e:#}"));
304        let baseline = assemble(Condition::Baseline, &ws, task.query(), budget)
305            .unwrap_or_else(|e| panic!("assemble baseline: {e:#}"));
306
307        let score = score_task(task, &crushed.text, &ws)
308            .unwrap_or_else(|e| panic!("score {}: {e:#}", task.id));
309        assert!(
310            score.passed,
311            "json_crush dropped the answer for '{}' ({})",
312            task.id, score.detail
313        );
314        assert!(
315            crushed.tokens < baseline.tokens,
316            "json_crush ({}) must beat the raw baseline ({}) on a redundant array",
317            crushed.tokens,
318            baseline.tokens
319        );
320    }
321
322    /// The code-edit task must be genuinely solvable: a correct reference solution
323    /// passes the committed unit test and the shipped failing stub does not. Proves
324    /// the harness end-to-end (sandbox copy + `test_cmd`) with zero model calls.
325    #[test]
326    fn code_task_is_solvable_and_stub_fails() {
327        let suite = load_accuracy_suite();
328        let task = suite
329            .tasks
330            .iter()
331            .find(|t| t.domain == Domain::Code)
332            .expect("code task present");
333        let ws = task.workspace_path(&suite.dir);
334
335        let reference = "factorial() { n=$1; [ \"$n\" -le 1 ] && { echo 1; return; }; \
336             r=1; i=2; while [ \"$i\" -le \"$n\" ]; do r=$((r * i)); i=$((i + 1)); done; echo \"$r\"; }";
337        let good = score_task(task, reference, &ws).unwrap();
338        assert!(good.passed, "reference solution must pass: {}", good.detail);
339
340        let stub = "factorial() { echo 0; }";
341        let bad = score_task(task, stub, &ws).unwrap();
342        assert!(!bad.passed, "wrong solution must fail the unit test");
343    }
344}