Skip to main content

lean_ctx_ext/core/scorecard/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Reproducible scorecard (#211): one command → compression savings + retrieval
3//! recall/MRR + latency over a fixed, deterministic scenario matrix.
4//!
5//! The quality metrics (savings, recall, MRR) are reproducible run-to-run and
6//! machine-to-machine because the corpus is generated deterministically and the
7//! retrieval path is pure BM25. Latency is measured wall-clock and therefore
8//! reported but not part of the determinism contract (see `determinism_digest`).
9
10pub mod dual_arm;
11mod scenarios;
12
13use std::collections::BTreeMap;
14use std::time::Instant;
15
16use serde::Serialize;
17
18use crate::core::{benchmark, bm25_index::BM25Index};
19
20/// Per-scenario result.
21#[derive(Debug, Clone, Serialize, PartialEq)]
22pub struct ScenarioScore {
23    pub name: String,
24    pub files: usize,
25    pub raw_tokens: usize,
26    pub best_mode: String,
27    pub best_savings_pct: f64,
28    pub savings_by_mode: BTreeMap<String, f64>,
29    pub queries: usize,
30    pub recall_at_5: f64,
31    pub recall_at_10: f64,
32    pub mrr: f64,
33    /// Wall-clock; informational only (not part of the determinism contract).
34    pub search_latency_us_p50: u64,
35}
36
37/// Cross-scenario averages.
38#[derive(Debug, Clone, Serialize, PartialEq)]
39pub struct Aggregate {
40    pub avg_savings_pct: f64,
41    pub avg_recall_at_5: f64,
42    pub avg_recall_at_10: f64,
43    pub avg_mrr: f64,
44}
45
46/// The full scorecard.
47#[derive(Debug, Clone, Serialize)]
48pub struct Scorecard {
49    pub schema_version: u32,
50    pub tokenizer: String,
51    /// Stable fingerprint of the reproducible (latency-free) metrics. Serialized
52    /// so the JSON artifact is self-verifying: two runs on the same code (any
53    /// machine) yield the same digest.
54    pub determinism_digest: String,
55    pub scenarios: Vec<ScenarioScore>,
56    pub aggregate: Aggregate,
57}
58
59impl Scorecard {
60    /// Compute the stable fingerprint from scenario scores. Latency is excluded
61    /// by construction, so two runs on the same code must produce the same value.
62    fn compute_digest(scenarios: &[ScenarioScore]) -> String {
63        let mut parts: Vec<String> = Vec::new();
64        for s in scenarios {
65            let modes: Vec<String> = s
66                .savings_by_mode
67                .iter()
68                .map(|(m, v)| format!("{m}={v:.2}"))
69                .collect();
70            parts.push(format!(
71                "{}|raw={}|best={}:{:.2}|r5={:.4}|r10={:.4}|mrr={:.4}|{}",
72                s.name,
73                s.raw_tokens,
74                s.best_mode,
75                s.best_savings_pct,
76                s.recall_at_5,
77                s.recall_at_10,
78                s.mrr,
79                modes.join(",")
80            ));
81        }
82        parts.join(";")
83    }
84
85    pub fn to_json(&self) -> String {
86        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
87    }
88
89    /// Human-readable scorecard table.
90    pub fn to_human(&self) -> String {
91        let mut out = String::new();
92        out.push_str("lean-ctx scorecard\n");
93        out.push_str(&format!("tokenizer: {}\n", self.tokenizer));
94        out.push_str(&format!("digest:    {}\n\n", self.determinism_digest));
95        out.push_str(
96            "scenario   files  raw_tokens  best_mode      savings%  R@5    R@10   MRR    p50(us)\n",
97        );
98        out.push_str(
99            "--------------------------------------------------------------------------------\n",
100        );
101        for s in &self.scenarios {
102            out.push_str(&format!(
103                "{:<10} {:>5}  {:>10}  {:<13}  {:>7.2}  {:>4.2}  {:>4.2}  {:>4.2}  {:>7}\n",
104                s.name,
105                s.files,
106                s.raw_tokens,
107                s.best_mode,
108                s.best_savings_pct,
109                s.recall_at_5,
110                s.recall_at_10,
111                s.mrr,
112                s.search_latency_us_p50,
113            ));
114        }
115        out.push_str(
116            "--------------------------------------------------------------------------------\n",
117        );
118        out.push_str(&format!(
119            "aggregate                            {:<13}  {:>7.2}  {:>4.2}  {:>4.2}  {:>4.2}\n",
120            "",
121            self.aggregate.avg_savings_pct,
122            self.aggregate.avg_recall_at_5,
123            self.aggregate.avg_recall_at_10,
124            self.aggregate.avg_mrr,
125        ));
126        out
127    }
128}
129
130/// Run the full scenario matrix and assemble the scorecard.
131pub fn run_scorecard() -> std::io::Result<Scorecard> {
132    let mut scenarios = Vec::with_capacity(scenarios::SCENARIOS.len());
133    for sc in scenarios::SCENARIOS {
134        scenarios.push(run_one(sc)?);
135    }
136    let aggregate = aggregate(&scenarios);
137    let determinism_digest = Scorecard::compute_digest(&scenarios);
138    Ok(Scorecard {
139        schema_version: 1,
140        tokenizer: crate::core::tokens::counting_family_label(),
141        determinism_digest,
142        scenarios,
143        aggregate,
144    })
145}
146
147fn run_one(sc: &scenarios::Scenario) -> std::io::Result<ScenarioScore> {
148    let dir = tempfile::TempDir::new()?;
149    let root = dir.path();
150    let queries = scenarios::materialize(sc, root)?;
151
152    // --- Compression savings (existing, tested benchmark path) ---
153    let bench = benchmark::run_project_benchmark(&root.to_string_lossy());
154    let mut savings_by_mode = BTreeMap::new();
155    for m in &bench.mode_summaries {
156        savings_by_mode.insert(m.mode.clone(), round2(m.avg_savings_pct));
157    }
158    let (best_mode, best_savings_pct) = savings_by_mode
159        .iter()
160        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
161        .map_or_else(|| ("none".to_string(), 0.0), |(m, v)| (m.clone(), *v));
162
163    // --- Retrieval quality (pure BM25 → deterministic, feature-independent) ---
164    let index = BM25Index::build_from_directory(root);
165    let mut sum_r5 = 0.0;
166    let mut sum_r10 = 0.0;
167    let mut sum_mrr = 0.0;
168    let mut latencies: Vec<u64> = Vec::with_capacity(queries.len());
169    for q in &queries {
170        let start = Instant::now();
171        let results = index.search(&q.query, 10);
172        latencies.push(start.elapsed().as_micros() as u64);
173        let files = dedup_files(&results);
174        sum_r5 += recall_at_k(&files, &q.expected_file, 5);
175        sum_r10 += recall_at_k(&files, &q.expected_file, 10);
176        sum_mrr += reciprocal_rank(&files, &q.expected_file);
177    }
178    let n = queries.len().max(1) as f64;
179
180    Ok(ScenarioScore {
181        name: sc.name.to_string(),
182        files: sc.files,
183        raw_tokens: bench.total_raw_tokens,
184        best_mode,
185        best_savings_pct,
186        savings_by_mode,
187        queries: queries.len(),
188        recall_at_5: round2(sum_r5 / n),
189        recall_at_10: round2(sum_r10 / n),
190        mrr: round2(sum_mrr / n),
191        search_latency_us_p50: percentile_p50(&mut latencies),
192    })
193}
194
195fn aggregate(scenarios: &[ScenarioScore]) -> Aggregate {
196    if scenarios.is_empty() {
197        return Aggregate {
198            avg_savings_pct: 0.0,
199            avg_recall_at_5: 0.0,
200            avg_recall_at_10: 0.0,
201            avg_mrr: 0.0,
202        };
203    }
204    let n = scenarios.len() as f64;
205    Aggregate {
206        avg_savings_pct: round2(scenarios.iter().map(|s| s.best_savings_pct).sum::<f64>() / n),
207        avg_recall_at_5: round2(scenarios.iter().map(|s| s.recall_at_5).sum::<f64>() / n),
208        avg_recall_at_10: round2(scenarios.iter().map(|s| s.recall_at_10).sum::<f64>() / n),
209        avg_mrr: round2(scenarios.iter().map(|s| s.mrr).sum::<f64>() / n),
210    }
211}
212
213/// Unique file paths in rank order (the first chunk of each file defines rank).
214fn dedup_files(results: &[crate::core::bm25_index::SearchResult]) -> Vec<String> {
215    let mut seen = std::collections::HashSet::new();
216    let mut files = Vec::new();
217    for r in results {
218        if seen.insert(r.file_path.clone()) {
219            files.push(r.file_path.clone());
220        }
221    }
222    files
223}
224
225/// Platform-independent path suffix match.
226fn path_matches(retrieved: &str, expected: &str) -> bool {
227    let r = retrieved.replace('\\', "/");
228    let e = expected.replace('\\', "/");
229    r.ends_with(&e) || e.ends_with(&r)
230}
231
232fn recall_at_k(files: &[String], expected: &str, k: usize) -> f64 {
233    if files.iter().take(k).any(|f| path_matches(f, expected)) {
234        1.0
235    } else {
236        0.0
237    }
238}
239
240fn reciprocal_rank(files: &[String], expected: &str) -> f64 {
241    for (i, f) in files.iter().enumerate() {
242        if path_matches(f, expected) {
243            return 1.0 / (i as f64 + 1.0);
244        }
245    }
246    0.0
247}
248
249fn percentile_p50(latencies: &mut [u64]) -> u64 {
250    if latencies.is_empty() {
251        return 0;
252    }
253    latencies.sort_unstable();
254    latencies[latencies.len() / 2]
255}
256
257fn round2(v: f64) -> f64 {
258    (v * 100.0).round() / 100.0
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn path_matching_is_suffix_based() {
267        assert!(path_matches(
268            "/tmp/x/src/auth/file_001.rs",
269            "src/auth/file_001.rs"
270        ));
271        assert!(!path_matches(
272            "src/auth/file_002.rs",
273            "src/auth/file_001.rs"
274        ));
275    }
276
277    #[test]
278    fn recall_and_rr_basics() {
279        let files = vec![
280            "src/db/file_000.rs".to_string(),
281            "src/auth/file_001.rs".to_string(),
282        ];
283        assert_eq!(recall_at_k(&files, "src/auth/file_001.rs", 5), 1.0);
284        assert_eq!(recall_at_k(&files, "src/auth/file_001.rs", 1), 0.0);
285        assert_eq!(reciprocal_rank(&files, "src/auth/file_001.rs"), 0.5);
286        assert_eq!(reciprocal_rank(&files, "src/missing.rs"), 0.0);
287    }
288
289    #[test]
290    fn round2_rounds() {
291        assert_eq!(round2(12.3456), 12.35);
292        assert_eq!(round2(0.0), 0.0);
293    }
294}