warble_eval_runner/cache.rs
1//! Trace cache — content-addressed per-case results + 0-LLM re-scoring.
2//!
3//! Every replayed golden case emits a **trace**: the agent's captured `{columns, rows}` result plus
4//! the run's cost/latency/turns and the inputs that determined it — `(case, agent_sha, model,
5//! context_sha, sample)`. The trace is written under a content-addressed key so a later run can
6//! reuse it:
7//!
8//! - **Re-score without re-run** (the killer): a golden's `expected`/`tolerance`/`match` can change
9//! while the agent, model, MDL, and sample index do not. The key deliberately excludes the
10//! expectation, so such a change still *hits* — and [`rescore`] re-compares the cached result
11//! against the **current** expectation with **zero LLM calls**. The v1→v2 golden-calibration
12//! rerun goes from ~90 min to sub-second.
13//! - **Content-addressed skip**: identical `(case, agent_sha, model, context_sha, sample)` → reuse
14//! the cached result on a plain re-run too (no re-sampling). `--no-cache` is the escape hatch that
15//! forces every case to re-run and refreshes the cache.
16//!
17//! The key material reuses the same `git hash-object` content addressing as `eval verify-context`
18//! (the MDL SHA): `agent_sha` = SHA of the dispatched agent dir, `context_sha` = MDL SHA of the
19//! bound project, and the cache filename is the SHA of the canonical key string. No new deps, no
20//! network, single machine — the OSS boundary is preserved.
21//!
22//! No silent caps: the caller surfaces hit/miss counts in the report and per-case `[cache]` markers,
23//! and a re-scored run is never mistaken for a fresh one.
24
25use std::path::{Path, PathBuf};
26
27use serde::{Deserialize, Serialize};
28use warble_eval_compare::CompareResult;
29
30use crate::context::hash_str;
31use crate::{score_value, Backend, GoldenCase};
32
33/// Sentinel `model` component for the ablation / frontmatter path, where there is no whole-run
34/// `--model` override (the per-step tier binding is baked into the agent, so `agent_sha` already
35/// distinguishes the points). Keeps the key total for every run.
36pub(crate) const FRONTMATTER_MODEL: &str = "frontmatter";
37
38/// One captured case result. The `result` is stored as the raw `{columns, rows}` JSON value (the
39/// same object `capture` embeds) so no `Serialize` is needed on the compare crate's `Table`; it is
40/// deserialized back into a `Table` at re-score time.
41///
42/// `sql_executed` and `tool_calls` are schema slots the P4 trace shape reserves, but the single-shot
43/// `claude -p --output-format json` envelope does not expose either (only `num_turns`), so they are
44/// captured as `None` today. `turns` (from `num_turns`) is the delivered per-case diagnostic; full
45/// SQL / tool-call granularity would need `--output-format stream-json` (a later change).
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct Trace {
48 pub case_id: String,
49 pub agent_sha: String,
50 pub model: String,
51 /// The golden's symbolic `context_version` pin (informational), e.g. `driftwood@a1b2c3d`.
52 pub context_version: Option<String>,
53 /// The computed MDL SHA of the bound project — the `context_sha` key component.
54 pub context_sha: String,
55 /// The question the result answers. Part of the key: if a case's question changes under the
56 /// same id, the cached result is for a different prompt and must be re-run (a miss).
57 pub question: String,
58 /// The SQL the agent executed. Not exposed by the `--output-format json` result envelope; `None`.
59 pub sql_executed: Option<String>,
60 /// The captured `{columns, rows}` result object.
61 pub result: serde_json::Value,
62 /// `None` when the backend that produced this trace couldn't report cost — absent is not zero.
63 #[serde(default)]
64 pub cost: Option<f64>,
65 pub latency_ms: u64,
66 /// Conversation turns (`num_turns`) — the round-trip count ("4–8 round-trips" per case, typically).
67 /// `None` when the backend couldn't report a turn count.
68 #[serde(default)]
69 pub turns: Option<u64>,
70 /// Tool-call count. Not exposed by the JSON result envelope; `None` (see struct docs).
71 pub tool_calls: Option<u64>,
72 /// Which back-end/runtime produced this trace — part of the cache key (see [`CaseKey::backend`])
73 /// so a trace from one back-end is never replayed as another's result. `#[serde(default)]` so a
74 /// pre-existing on-disk trace (no field at all) deserializes to [`Backend::default`] — the
75 /// back-end that behavior always meant before this dimension existed.
76 #[serde(default)]
77 pub backend: Backend,
78}
79
80/// The inputs that determine a case's result. Everything here is in the cache key; the golden's
81/// expectation (expected/tolerance/match) deliberately is **not**, which is what makes re-scoring a
82/// changed expectation a cache hit.
83pub struct CaseKey<'a> {
84 pub case_id: &'a str,
85 pub question: &'a str,
86 pub agent_sha: &'a str,
87 /// The whole-run `--model` binding, or `FRONTMATTER_MODEL` on the ablation path.
88 pub model: &'a str,
89 pub context_sha: &'a str,
90 /// Which repeated-sample run this is (0-indexed). Distinct samples of the same case are
91 /// distinct cache entries — the pass-rate methodology depends on each sample actually invoking
92 /// the agent (or replaying its OWN prior trace), not silently collapsing onto sample 0.
93 pub sample: u32,
94 /// Which back-end/runtime this run is measuring. Part of the key so runs on different
95 /// back-ends can never hit each other's cache.
96 pub backend: Backend,
97}
98
99impl CaseKey<'_> {
100 /// The canonical, order-fixed key string that gets hashed. Encoded as a fixed-order JSON array
101 /// so a field value can never spoof the delimiter structure — a `question` may legitimately
102 /// contain newlines or `=`, which a plain `k=v\n` join could use to collide with a different
103 /// logical key (relevant once goldens are machine-generated, not just hand-authored). `sample`
104 /// is stringified and placed among the first five so they stay stable for anyone comparing
105 /// keys across a `samples`-unaware era.
106 ///
107 /// `backend` is appended as a **sixth** element only when it isn't [`Backend::default`] — so
108 /// the default-backend path still produces the exact legacy 6-element array (byte-identical,
109 /// same hash), keeping pre-existing cache entries for the default back-end valid, while any
110 /// non-default backend gets a 7-element array guaranteed not to collide with a default-backend
111 /// key for the same case.
112 fn canonical(&self) -> String {
113 let sample = self.sample.to_string();
114 let mut parts: Vec<&str> = vec![
115 self.case_id,
116 self.question,
117 self.agent_sha,
118 self.model,
119 self.context_sha,
120 &sample,
121 ];
122 if self.backend != Backend::default() {
123 parts.push(self.backend.as_str());
124 }
125 serde_json::to_string(&parts).expect("array of strings serializes")
126 }
127
128 /// Content-addressed hash of the key → the cache entry's filename stem.
129 pub fn hash(&self) -> Result<String, String> {
130 hash_str(&self.canonical())
131 }
132}
133
134/// A content-addressed store of [`Trace`]s under one directory (`<dir>/<key-hash>.json`).
135///
136/// When `enabled` is false (the `--no-cache` escape hatch) [`load`](Self::load) always misses and
137/// [`store`](Self::store) is a no-op, so a run behaves exactly as it did before P4.
138pub struct TraceStore {
139 dir: PathBuf,
140 enabled: bool,
141}
142
143impl TraceStore {
144 /// A store rooted at `dir`. `enabled = false` disables both read and write (`--no-cache`).
145 pub fn new(dir: PathBuf, enabled: bool) -> Self {
146 TraceStore { dir, enabled }
147 }
148
149 /// An always-missing store (used when the cache key material can't be computed, so the run
150 /// still proceeds — every case just re-runs and nothing is cached).
151 pub fn disabled() -> Self {
152 TraceStore {
153 dir: PathBuf::new(),
154 enabled: false,
155 }
156 }
157
158 pub fn is_enabled(&self) -> bool {
159 self.enabled
160 }
161
162 pub fn dir(&self) -> &Path {
163 &self.dir
164 }
165
166 fn entry_path(&self, key_hash: &str) -> PathBuf {
167 self.dir.join(format!("{key_hash}.json"))
168 }
169
170 /// Load a cached trace for `key`, or `None` on a disabled store, a missing entry, or an
171 /// unreadable/corrupt one (a corrupt entry is treated as a miss — the case just re-runs).
172 pub fn load(&self, key: &CaseKey) -> Option<Trace> {
173 if !self.enabled {
174 return None;
175 }
176 let hash = key.hash().ok()?;
177 let raw = std::fs::read_to_string(self.entry_path(&hash)).ok()?;
178 serde_json::from_str(&raw).ok()
179 }
180
181 /// Write `trace` under `key`. A no-op on a disabled store. Creates the cache dir on first write.
182 pub fn store(&self, key: &CaseKey, trace: &Trace) -> Result<(), String> {
183 if !self.enabled {
184 return Ok(());
185 }
186 let hash = key.hash()?;
187 std::fs::create_dir_all(&self.dir)
188 .map_err(|e| format!("create cache dir {}: {e}", self.dir.display()))?;
189 let json = serde_json::to_string_pretty(trace).map_err(|e| e.to_string())?;
190 std::fs::write(self.entry_path(&hash), json)
191 .map_err(|e| format!("write trace {}: {e}", self.entry_path(&hash).display()))
192 }
193}
194
195/// Re-score a cached `trace` against a golden case's **current** expectation — the 0-LLM path.
196/// Dispatches on the case's [`crate::ResultKind`] via [`score_value`] just like a fresh run does, so
197/// a Table case's cached `{columns,rows}` and a Verdict case's cached envelope both re-project the
198/// same way. Returns `None` if the cached result doesn't have the shape the case's kind expects (a
199/// corrupt entry, or a case whose `result_kind` changed since the trace was captured; the caller then
200/// re-runs the case). This is what makes "only the golden's expected changed" cost zero LLM calls:
201/// the result is reused, only the comparison is redone.
202pub fn rescore(trace: &Trace, case: &GoldenCase) -> Option<CompareResult> {
203 score_value(&trace.result, case)
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 use warble_eval_compare::{MatchMode, Tolerance};
210
211 fn trace_with(result: serde_json::Value) -> Trace {
212 Trace {
213 case_id: "q1".into(),
214 agent_sha: "AAAA".into(),
215 model: "opus".into(),
216 context_version: Some("driftwood@c0ffee".into()),
217 context_sha: "CCCC".into(),
218 question: "how many orders?".into(),
219 sql_executed: None,
220 result,
221 cost: Some(0.12),
222 latency_ms: 20_000,
223 turns: Some(5),
224 tool_calls: None,
225 backend: Backend::default(),
226 }
227 }
228
229 fn case_expecting(rows: serde_json::Value) -> GoldenCase {
230 // Build a GoldenCase via YAML so we don't depend on field visibility.
231 let yaml = format!(
232 "id: q1\nquestion: \"how many orders?\"\nmatch: scalar\nexpected: {{ columns: [n], rows: {rows} }}\n"
233 );
234 serde_yaml::from_str(&yaml).expect("golden case parses")
235 }
236
237 #[test]
238 fn key_hash_is_stable_and_expectation_independent() {
239 let k1 = CaseKey {
240 case_id: "q1",
241 question: "how many orders?",
242 agent_sha: "AAAA",
243 model: "opus",
244 context_sha: "CCCC",
245 sample: 0,
246 backend: Backend::default(),
247 };
248 // Same inputs → same hash (content-addressed, deterministic).
249 assert_eq!(k1.hash().unwrap(), k1.hash().unwrap());
250 assert_eq!(k1.hash().unwrap().len(), 40, "git blob sha is 40 hex");
251 }
252
253 #[test]
254 fn changing_a_key_component_changes_the_hash() {
255 let base = CaseKey {
256 case_id: "q1",
257 question: "how many orders?",
258 agent_sha: "AAAA",
259 model: "opus",
260 context_sha: "CCCC",
261 sample: 0,
262 backend: Backend::default(),
263 };
264 let base_hash = base.hash().unwrap();
265 // Each of the six key components moves the hash (→ a miss → a re-run). Covers decision 5's
266 // testing mandate: a non-default backend must never hit a default-backend key's cache entry.
267 for changed in [
268 CaseKey {
269 question: "how many customers?",
270 ..key_copy(&base)
271 },
272 CaseKey {
273 agent_sha: "BBBB",
274 ..key_copy(&base)
275 },
276 CaseKey {
277 model: "haiku",
278 ..key_copy(&base)
279 },
280 CaseKey {
281 context_sha: "DDDD",
282 ..key_copy(&base)
283 },
284 CaseKey {
285 sample: 1,
286 ..key_copy(&base)
287 },
288 CaseKey {
289 backend: Backend::ClaudeAgentSdk,
290 ..key_copy(&base)
291 },
292 ] {
293 assert_ne!(base_hash, changed.hash().unwrap());
294 }
295 }
296
297 // Helper to copy a CaseKey's fields (CaseKey holds &str, so this is cheap).
298 fn key_copy<'a>(k: &CaseKey<'a>) -> CaseKey<'a> {
299 CaseKey {
300 case_id: k.case_id,
301 question: k.question,
302 agent_sha: k.agent_sha,
303 model: k.model,
304 context_sha: k.context_sha,
305 sample: k.sample,
306 backend: k.backend,
307 }
308 }
309
310 #[test]
311 fn store_round_trips_and_no_cache_never_hits() {
312 let dir = tempfile::tempdir().unwrap();
313 let key = CaseKey {
314 case_id: "q1",
315 question: "how many orders?",
316 agent_sha: "AAAA",
317 model: "opus",
318 context_sha: "CCCC",
319 sample: 0,
320 backend: Backend::default(),
321 };
322 let trace = trace_with(serde_json::json!({"columns":["n"],"rows":[[42]]}));
323
324 let enabled = TraceStore::new(dir.path().to_path_buf(), true);
325 enabled.store(&key, &trace).unwrap();
326 let loaded = enabled.load(&key).expect("hit");
327 assert_eq!(loaded.result, trace.result);
328 assert_eq!(loaded.turns, Some(5));
329
330 // A disabled store (the --no-cache path) never hits, even with the entry on disk.
331 let disabled = TraceStore::new(dir.path().to_path_buf(), false);
332 assert!(disabled.load(&key).is_none());
333 // …and writing is a silent no-op.
334 disabled.store(&key, &trace).unwrap();
335 }
336
337 #[test]
338 fn rescore_reuses_result_against_the_current_expectation() {
339 let trace = trace_with(serde_json::json!({"columns":["n"],"rows":[[42]]}));
340
341 // Golden still expects 42 → pass, using only the cached result (no LLM).
342 let pass = rescore(&trace, &case_expecting(serde_json::json!([[42]]))).unwrap();
343 assert!(pass.pass, "cached 42 matches expected 42");
344
345 // The golden's expected changes to 99 → the SAME cached result now fails the re-score.
346 // This is the "only the expectation changed" path: 0 LLM, correct new verdict.
347 let fail = rescore(&trace, &case_expecting(serde_json::json!([[99]]))).unwrap();
348 assert!(!fail.pass, "cached 42 no longer matches expected 99");
349
350 let _ = Tolerance::default();
351 let _ = MatchMode::Scalar;
352 }
353
354 #[test]
355 fn canonical_key_is_a_six_element_array_for_the_default_backend() {
356 // The default backend's canonical key stays byte-identical to the pre-Backend-dimension
357 // shape — this is what keeps legacy cache entries valid for the default target (decision 5).
358 let key = CaseKey {
359 case_id: "q1",
360 question: "how many orders?",
361 agent_sha: "AAAA",
362 model: "opus",
363 context_sha: "CCCC",
364 sample: 2,
365 backend: Backend::default(),
366 };
367 let parsed: Vec<String> = serde_json::from_str(&key.canonical()).unwrap();
368 assert_eq!(
369 parsed,
370 vec!["q1", "how many orders?", "AAAA", "opus", "CCCC", "2"]
371 );
372 }
373
374 #[test]
375 fn canonical_key_is_a_seven_element_array_for_a_non_default_backend() {
376 // A non-default backend gets an extra element — guaranteed not to collide with any
377 // default-backend (legacy) key for the same case, so no cross-backend cache hit is even
378 // representable at the key-encoding level.
379 let key = CaseKey {
380 case_id: "q1",
381 question: "how many orders?",
382 agent_sha: "AAAA",
383 model: "opus",
384 context_sha: "CCCC",
385 sample: 2,
386 backend: Backend::ClaudeAgentSdk,
387 };
388 let parsed: Vec<String> = serde_json::from_str(&key.canonical()).unwrap();
389 assert_eq!(
390 parsed,
391 vec![
392 "q1",
393 "how many orders?",
394 "AAAA",
395 "opus",
396 "CCCC",
397 "2",
398 "claude-agent-sdk"
399 ]
400 );
401 }
402}