Skip to main content

lean_ctx/core/eval_ab/
model.rs

1//! Pinned, reproducible model adapter (#234).
2//!
3//! The harness talks to a model through one small [`ModelRunner`] trait. Two real
4//! implementations ship:
5//!
6//! * [`OpenAiRunner`] — a synchronous OpenAI-compatible chat client (OpenAI, Azure OpenAI,
7//!   vLLM, llama.cpp, Ollama's `/v1` …). Decoding is pinned (`temperature = 0`, fixed `seed`)
8//!   so a compliant provider is as deterministic as it can be.
9//! * [`RecordedRunner`] — strict replay of responses previously captured from a real provider.
10//!   Missing keys are a hard error (never a silent fallback), which is what makes CI runs and
11//!   the determinism digest byte-stable across machines.
12//!
13//! [`RecordingRunner`] wraps any real runner and captures every response so an operator can
14//! produce a replay file once with `eval ab --record`. Secrets (API keys) never enter a
15//! fingerprint, recording, or report.
16
17use std::cell::RefCell;
18use std::collections::BTreeMap;
19use std::path::Path;
20
21use anyhow::{Context, Result, anyhow, bail};
22use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
23use serde::{Deserialize, Serialize};
24
25use super::sha256_hex;
26
27/// Provider label for the OpenAI-compatible chat runner.
28pub const PROVIDER_OPENAI: &str = "openai-compatible";
29/// Provider label for the strict replay runner.
30pub const PROVIDER_RECORDED: &str = "recorded";
31
32/// Model identity and decoding parameters pinned for reproducibility. The lean-ctx
33/// version is recorded on the report (`AbReport::lean_ctx_version`), outside every
34/// digest, so a version bump never invalidates a committed recording.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct ModelParams {
37    /// Provider model identifier, e.g. `gpt-4o-mini` or `qwen2.5-coder:7b`.
38    pub model: String,
39    /// Provider-reported model revision or tag when available.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub version: Option<String>,
42    pub temperature: f64,
43    pub top_p: f64,
44    pub max_tokens: u32,
45    /// Best-effort decoding seed (forwarded to providers that honour it).
46    pub seed: u64,
47}
48
49impl Default for ModelParams {
50    fn default() -> Self {
51        Self {
52            model: String::new(),
53            version: None,
54            temperature: 0.0,
55            top_p: 1.0,
56            max_tokens: 1024,
57            seed: 7,
58        }
59    }
60}
61
62/// Identifies exactly which model + params produced a set of answers. Embedded in the report
63/// and the determinism digest so a third party knows precisely what was run.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65pub struct ModelFingerprint {
66    /// `openai-compatible` or `recorded`.
67    pub provider: String,
68    /// Base URL or recording path — never contains credentials.
69    pub endpoint: String,
70    pub params: ModelParams,
71}
72
73impl ModelFingerprint {
74    /// Stable hex digest of the fingerprint (canonical JSON over sorted keys via serde).
75    pub fn digest(&self) -> String {
76        let canonical = serde_json::to_vec(self).unwrap_or_default();
77        sha256_hex(&canonical)
78    }
79}
80
81/// A single chat request (one system + one user turn). Deliberately minimal so the recording
82/// key is stable across runs.
83#[derive(Debug, Clone, PartialEq)]
84pub struct ModelRequest {
85    pub system: String,
86    pub user: String,
87}
88
89impl ModelRequest {
90    /// Content-addressed replay key: hex SHA-256 over `system` and `user`.
91    pub fn key(&self) -> String {
92        let mut joined = Vec::with_capacity(self.system.len() + self.user.len() + 1);
93        joined.extend_from_slice(self.system.as_bytes());
94        joined.push(0);
95        joined.extend_from_slice(self.user.as_bytes());
96        sha256_hex(&joined)
97    }
98}
99
100/// The model's answer plus a content digest for auditing.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102pub struct ModelResponse {
103    pub text: String,
104    /// What a real exchange with a provider looked like from here. `None` for every
105    /// answer that did not come from one (synthetic runners, recordings made before
106    /// this field existed) — and then not serialized, so those recordings keep their
107    /// bytes. Never part of [`ModelResponse::digest`].
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub exchange: Option<ProviderExchange>,
110}
111
112/// Whether the metadata of an answer was seen in this run or read from a recording.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum ObservationOrigin {
116    /// The runner made the request itself, in this run.
117    Observed,
118    /// A recording was replayed: what an earlier run saw, not a fresh measurement,
119    /// whatever provider the inherited fingerprint names.
120    Replayed,
121}
122
123/// One request/response exchange as this process saw it.
124///
125/// The two digests are over the request body exactly as it was sent and the
126/// response body exactly as it was read (no header, so no credential). They
127/// bind a local observation of bytes: they are not an authorization by the
128/// provider, not a signature, and not a receipt of this engine's tools.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct ProviderExchange {
132    pub origin: ObservationOrigin,
133    pub request_body_sha256: String,
134    pub response_body_sha256: String,
135    /// `None`: the provider reported no usage (absent or `null`).
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub usage: Option<ProviderUsage>,
138}
139
140/// Token counts as the provider REPORTED them in its answer — reported, not
141/// signed, and never estimated here: a count the provider did not send stays
142/// `None`, and a reported `0` is `Some(0)`.
143#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
144#[serde(deny_unknown_fields)]
145pub struct ProviderUsage {
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub input_tokens: Option<u64>,
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub output_tokens: Option<u64>,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub total_tokens: Option<u64>,
152    /// Input tokens the provider says it read from its cache.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub cached_input_tokens: Option<u64>,
155    /// Known counters that WERE sent but are no count (a boolean, a fraction, a
156    /// negative or too large number, a text): named here and left `None` above.
157    /// A usage with an entry here is damaged evidence, not a measurement.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub invalid: Vec<String>,
160}
161
162impl ProviderUsage {
163    /// Whether every counter that was sent is a count.
164    pub fn is_well_formed(&self) -> bool {
165        self.invalid.is_empty()
166    }
167
168    /// A usage that is not even an object: invalid as a whole.
169    fn not_an_object() -> Self {
170        Self {
171            invalid: vec!["usage".to_owned()],
172            ..Self::default()
173        }
174    }
175}
176
177// The usage of an OpenAI-compatible answer is read key by key, as it was sent.
178// A generic JSON value would keep only one of two equal keys, and then
179// `{"prompt_tokens": true, "prompt_tokens": 7}` would look like a count of 7.
180
181/// One known counter as it was sent.
182#[derive(Clone, Copy)]
183enum Counted {
184    Null,
185    Count(u64),
186    /// Sent, and no count: a boolean, a fraction, a negative or too large
187    /// number, a text, a list or an object.
188    Invalid,
189}
190
191impl<'de> Deserialize<'de> for Counted {
192    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
193        struct Sent;
194        impl<'de> Visitor<'de> for Sent {
195            type Value = Counted;
196            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197                f.write_str("a token count as the provider sent it")
198            }
199            fn visit_unit<E>(self) -> Result<Counted, E> {
200                Ok(Counted::Null)
201            }
202            fn visit_u64<E>(self, count: u64) -> Result<Counted, E> {
203                Ok(Counted::Count(count))
204            }
205            fn visit_i64<E>(self, count: i64) -> Result<Counted, E> {
206                Ok(u64::try_from(count).map_or(Counted::Invalid, Counted::Count))
207            }
208            fn visit_f64<E>(self, _: f64) -> Result<Counted, E> {
209                Ok(Counted::Invalid)
210            }
211            fn visit_bool<E>(self, _: bool) -> Result<Counted, E> {
212                Ok(Counted::Invalid)
213            }
214            fn visit_str<E>(self, _: &str) -> Result<Counted, E> {
215                Ok(Counted::Invalid)
216            }
217            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Counted, A::Error> {
218                while seq.next_element::<IgnoredAny>()?.is_some() {}
219                Ok(Counted::Invalid)
220            }
221            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Counted, A::Error> {
222                while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
223                Ok(Counted::Invalid)
224            }
225        }
226        deserializer.deserialize_any(Sent)
227    }
228}
229
230/// Everything that was sent under ONE known counter name.
231#[derive(Default)]
232struct Slot {
233    times: u8,
234    count: Option<u64>,
235    invalid: bool,
236}
237
238impl Slot {
239    fn see(&mut self, counted: Counted) {
240        self.times = self.times.saturating_add(1);
241        match counted {
242            Counted::Null => {}
243            Counted::Count(count) => self.count = Some(count),
244            Counted::Invalid => self.invalid = true,
245        }
246    }
247
248    /// A count only if the name was sent ONCE and as a count. Sent twice —
249    /// whatever the two values, in whatever order, equal or not — it is named
250    /// as invalid and is no count: neither the first nor the last one wins.
251    fn settle(self, name: &'static str, invalid: &mut Vec<String>) -> Option<u64> {
252        if self.invalid || self.times > 1 {
253            invalid.push(name.to_owned());
254            None
255        } else {
256            self.count
257        }
258    }
259}
260
261/// `prompt_tokens_details` as it was sent.
262#[derive(Default)]
263struct ReportedDetails {
264    cached: Slot,
265    not_an_object: bool,
266}
267
268impl<'de> Deserialize<'de> for ReportedDetails {
269    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
270        struct Sent;
271        impl Sent {
272            fn other<E>() -> Result<ReportedDetails, E> {
273                Ok(ReportedDetails {
274                    not_an_object: true,
275                    ..ReportedDetails::default()
276                })
277            }
278        }
279        impl<'de> Visitor<'de> for Sent {
280            type Value = ReportedDetails;
281            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282                f.write_str("the prompt token details as the provider sent them")
283            }
284            fn visit_unit<E>(self) -> Result<ReportedDetails, E> {
285                Ok(ReportedDetails::default())
286            }
287            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<ReportedDetails, A::Error> {
288                let mut details = ReportedDetails::default();
289                while let Some(key) = map.next_key::<String>()? {
290                    if key == "cached_tokens" {
291                        details.cached.see(map.next_value()?);
292                    } else {
293                        map.next_value::<IgnoredAny>()?;
294                    }
295                }
296                Ok(details)
297            }
298            fn visit_u64<E>(self, _: u64) -> Result<ReportedDetails, E> {
299                Self::other()
300            }
301            fn visit_i64<E>(self, _: i64) -> Result<ReportedDetails, E> {
302                Self::other()
303            }
304            fn visit_f64<E>(self, _: f64) -> Result<ReportedDetails, E> {
305                Self::other()
306            }
307            fn visit_bool<E>(self, _: bool) -> Result<ReportedDetails, E> {
308                Self::other()
309            }
310            fn visit_str<E>(self, _: &str) -> Result<ReportedDetails, E> {
311                Self::other()
312            }
313            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<ReportedDetails, A::Error> {
314                while seq.next_element::<IgnoredAny>()?.is_some() {}
315                Self::other()
316            }
317        }
318        deserializer.deserialize_any(Sent)
319    }
320}
321
322/// The `usage` of an answer, typed: `None` for absent, `null`, or an object with
323/// none of the known counters. Names a provider adds are ignored.
324#[derive(Default)]
325struct ReportedUsage(Option<ProviderUsage>);
326
327impl<'de> Deserialize<'de> for ReportedUsage {
328    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
329        struct Sent;
330        impl Sent {
331            fn other<E>() -> Result<ReportedUsage, E> {
332                Ok(ReportedUsage(Some(ProviderUsage::not_an_object())))
333            }
334        }
335        impl<'de> Visitor<'de> for Sent {
336            type Value = ReportedUsage;
337            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338                f.write_str("the usage as the provider sent it")
339            }
340            fn visit_unit<E>(self) -> Result<ReportedUsage, E> {
341                Ok(ReportedUsage(None))
342            }
343            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<ReportedUsage, A::Error> {
344                let (mut input, mut output, mut total) =
345                    (Slot::default(), Slot::default(), Slot::default());
346                let mut details = ReportedDetails::default();
347                let mut details_times = 0_u8;
348                while let Some(key) = map.next_key::<String>()? {
349                    match key.as_str() {
350                        "prompt_tokens" => input.see(map.next_value()?),
351                        "completion_tokens" => output.see(map.next_value()?),
352                        "total_tokens" => total.see(map.next_value()?),
353                        "prompt_tokens_details" => {
354                            details_times = details_times.saturating_add(1);
355                            details = map.next_value()?;
356                        }
357                        _ => {
358                            map.next_value::<IgnoredAny>()?;
359                        }
360                    }
361                }
362                // Each name is settled once, so `invalid` holds every known name at
363                // most once.
364                let mut invalid = Vec::new();
365                let input_tokens = input.settle("prompt_tokens", &mut invalid);
366                let output_tokens = output.settle("completion_tokens", &mut invalid);
367                let total_tokens = total.settle("total_tokens", &mut invalid);
368                let cached_input_tokens = if details_times > 1 || details.not_an_object {
369                    invalid.push("prompt_tokens_details".to_owned());
370                    None
371                } else {
372                    details.cached.settle("cached_tokens", &mut invalid)
373                };
374                let usage = ProviderUsage {
375                    input_tokens,
376                    output_tokens,
377                    total_tokens,
378                    cached_input_tokens,
379                    invalid,
380                };
381                Ok(ReportedUsage(
382                    (usage != ProviderUsage::default()).then_some(usage),
383                ))
384            }
385            fn visit_u64<E>(self, _: u64) -> Result<ReportedUsage, E> {
386                Self::other()
387            }
388            fn visit_i64<E>(self, _: i64) -> Result<ReportedUsage, E> {
389                Self::other()
390            }
391            fn visit_f64<E>(self, _: f64) -> Result<ReportedUsage, E> {
392                Self::other()
393            }
394            fn visit_bool<E>(self, _: bool) -> Result<ReportedUsage, E> {
395                Self::other()
396            }
397            fn visit_str<E>(self, _: &str) -> Result<ReportedUsage, E> {
398                Self::other()
399            }
400            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<ReportedUsage, A::Error> {
401                while seq.next_element::<IgnoredAny>()?.is_some() {}
402                Self::other()
403            }
404        }
405        deserializer.deserialize_any(Sent)
406    }
407}
408
409impl ModelResponse {
410    pub fn new(text: impl Into<String>) -> Self {
411        Self {
412            text: text.into(),
413            exchange: None,
414        }
415    }
416
417    /// Hex SHA-256 of the answer text (goes into the determinism digest).
418    pub fn digest(&self) -> String {
419        sha256_hex(self.text.as_bytes())
420    }
421}
422
423/// Anything that can turn a request into a response under a fixed fingerprint.
424pub trait ModelRunner {
425    /// The pinned identity of this runner (model, params, provider).
426    fn fingerprint(&self) -> &ModelFingerprint;
427    /// Executes one request. Implementations must be deterministic given the same fingerprint.
428    fn run(&self, req: &ModelRequest) -> Result<ModelResponse>;
429}
430
431// ---------------------------------------------------------------------------
432// OpenAI-compatible runner (real HTTP)
433// ---------------------------------------------------------------------------
434
435const ENDPOINT_ADMISSION_ERROR: &str = "model endpoint is not admitted";
436
437// Parse only for admission: accepted destinations keep their exact existing
438// trailing-slash-trimmed bytes. This key list is not a generic secret scanner.
439fn admitted_endpoint(base_url: &str) -> Option<String> {
440    let endpoint = base_url.trim_end_matches('/');
441    let parsed = reqwest::Url::parse(endpoint).ok()?;
442    if !matches!(parsed.scheme(), "http" | "https")
443        || parsed.host_str().is_none()
444        || !parsed.username().is_empty()
445        || parsed.password().is_some()
446        || parsed.fragment().is_some()
447        || parsed.query_pairs().any(|(key, _)| {
448            [
449                "api_key",
450                "api-key",
451                "apikey",
452                "access_token",
453                "token",
454                "authorization",
455                "password",
456                "client_secret",
457                "signature",
458                "sig",
459            ]
460            .iter()
461            .any(|blocked| key.eq_ignore_ascii_case(blocked))
462        })
463    {
464        return None;
465    }
466    Some(endpoint.to_owned())
467}
468
469/// Synchronous OpenAI-compatible chat client. Credentials are held only in memory.
470pub struct OpenAiRunner {
471    fingerprint: ModelFingerprint,
472    api_key: String,
473    endpoint_admitted: bool,
474}
475
476impl OpenAiRunner {
477    /// Builds a runner against `base_url` (e.g. `https://api.openai.com/v1`).
478    pub fn new(
479        base_url: impl Into<String>,
480        api_key: impl Into<String>,
481        params: ModelParams,
482    ) -> Self {
483        let endpoint = admitted_endpoint(&base_url.into());
484        let endpoint_admitted = endpoint.is_some();
485        Self {
486            fingerprint: ModelFingerprint {
487                provider: PROVIDER_OPENAI.to_string(),
488                endpoint: endpoint.unwrap_or_default(),
489                params,
490            },
491            api_key: api_key.into(),
492            endpoint_admitted,
493        }
494    }
495
496    /// Builds a runner from the standard environment:
497    /// `LEAN_CTX_EVAL_MODEL_URL`, `LEAN_CTX_EVAL_MODEL_KEY`, `LEAN_CTX_EVAL_MODEL`.
498    pub fn from_env() -> Result<Self> {
499        let base = std::env::var("LEAN_CTX_EVAL_MODEL_URL")
500            .context("LEAN_CTX_EVAL_MODEL_URL not set (OpenAI-compatible base URL)")?;
501        if admitted_endpoint(&base).is_none() {
502            bail!(ENDPOINT_ADMISSION_ERROR);
503        }
504        let key = std::env::var("LEAN_CTX_EVAL_MODEL_KEY").unwrap_or_default();
505        let model = std::env::var("LEAN_CTX_EVAL_MODEL")
506            .context("LEAN_CTX_EVAL_MODEL not set (provider model id)")?;
507        let seed = std::env::var("LEAN_CTX_EVAL_SEED")
508            .ok()
509            .and_then(|s| s.parse().ok())
510            .unwrap_or(ModelParams::default().seed);
511        let version = std::env::var("LEAN_CTX_EVAL_MODEL_VERSION")
512            .ok()
513            .map(|value| value.trim().to_string())
514            .filter(|value| !value.is_empty())
515            .or_else(|| model.rsplit_once(':').map(|(_, tag)| tag.to_string()));
516        let params = ModelParams {
517            model,
518            version,
519            seed,
520            ..ModelParams::default()
521        };
522        Ok(Self::new(base, key, params))
523    }
524}
525
526#[derive(Serialize)]
527struct ChatPayload<'a> {
528    model: &'a str,
529    temperature: f64,
530    top_p: f64,
531    max_tokens: u32,
532    seed: u64,
533    messages: Vec<ChatMessage<'a>>,
534}
535
536#[derive(Serialize)]
537struct ChatMessage<'a> {
538    role: &'a str,
539    content: &'a str,
540}
541
542#[derive(Deserialize)]
543struct ChatResponse {
544    choices: Vec<ChatChoice>,
545    /// Read key by key ([`ReportedUsage`]): a counter of the wrong kind, or one
546    /// sent twice, is named as invalid instead of failing the whole answer.
547    #[serde(default)]
548    usage: ReportedUsage,
549}
550
551#[derive(Deserialize)]
552struct ChatChoice {
553    message: ChatChoiceMessage,
554}
555
556#[derive(Deserialize)]
557struct ChatChoiceMessage {
558    content: String,
559}
560
561impl ModelRunner for OpenAiRunner {
562    fn fingerprint(&self) -> &ModelFingerprint {
563        &self.fingerprint
564    }
565
566    fn run(&self, req: &ModelRequest) -> Result<ModelResponse> {
567        if !self.endpoint_admitted {
568            bail!(ENDPOINT_ADMISSION_ERROR);
569        }
570        let p = &self.fingerprint.params;
571        let payload = ChatPayload {
572            model: &p.model,
573            temperature: p.temperature,
574            top_p: p.top_p,
575            max_tokens: p.max_tokens,
576            seed: p.seed,
577            messages: vec![
578                ChatMessage {
579                    role: "system",
580                    content: &req.system,
581                },
582                ChatMessage {
583                    role: "user",
584                    content: &req.user,
585                },
586            ],
587        };
588        let url = format!("{}/chat/completions", self.fingerprint.endpoint);
589        let body = serde_json::to_vec(&payload).context("serialize chat payload")?;
590        let mut request = ureq::post(&url).header("Content-Type", "application/json");
591        if !self.api_key.is_empty() {
592            request = request.header("Authorization", &format!("Bearer {}", self.api_key));
593        }
594        let resp = request
595            .send(&body[..])
596            .map_err(|_| anyhow!("model request failed"))?;
597        let status = resp.status().as_u16();
598        let text = resp
599            .into_body()
600            .read_to_string()
601            .map_err(|e| anyhow!("reading model response failed: {e}"))?;
602        if status != 200 {
603            bail!("model endpoint returned HTTP {status}: {text}");
604        }
605        let parsed: ChatResponse = serde_json::from_str(&text)
606            .with_context(|| format!("parsing model response: {text}"))?;
607        let answer = parsed
608            .choices
609            .into_iter()
610            .next()
611            .map(|c| c.message.content)
612            .ok_or_else(|| anyhow!("model response contained no choices"))?;
613        Ok(ModelResponse {
614            text: answer,
615            // Of this very exchange: the bytes that were sent and read, and what
616            // the provider said it counted. Nothing is requested again for it.
617            exchange: Some(ProviderExchange {
618                origin: ObservationOrigin::Observed,
619                request_body_sha256: sha256_hex(&body),
620                response_body_sha256: sha256_hex(text.as_bytes()),
621                usage: parsed.usage.0,
622            }),
623        })
624    }
625}
626
627// ---------------------------------------------------------------------------
628// Recording + strict replay
629// ---------------------------------------------------------------------------
630
631/// A captured set of real responses, keyed by [`ModelRequest::key`]. Serialized as JSON with a
632/// `BTreeMap` so the on-disk form is byte-stable.
633#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
634pub struct Recording {
635    /// `lean-ctx.eval-recording`.
636    pub kind: String,
637    /// The fingerprint that produced these responses (used to label the replay runner).
638    pub fingerprint: ModelFingerprint,
639    /// `request key -> response`.
640    pub entries: BTreeMap<String, ModelResponse>,
641}
642
643const RECORDING_KIND: &str = "lean-ctx.eval-recording";
644
645impl Recording {
646    pub fn new(fingerprint: ModelFingerprint) -> Self {
647        Self {
648            kind: RECORDING_KIND.to_string(),
649            fingerprint,
650            entries: BTreeMap::new(),
651        }
652    }
653
654    /// Loads + validates a recording file.
655    pub fn load(path: &Path) -> Result<Self> {
656        let raw = std::fs::read_to_string(path)
657            .with_context(|| format!("reading recording {}", path.display()))?;
658        let rec: Recording = serde_json::from_str(&raw)
659            .with_context(|| format!("parsing recording {}", path.display()))?;
660        if rec.kind != RECORDING_KIND {
661            bail!("not a {RECORDING_KIND} file (kind = {:?})", rec.kind);
662        }
663        Ok(rec)
664    }
665
666    /// Writes the recording as pretty JSON (creating parent dirs).
667    pub fn save(&self, path: &Path) -> Result<()> {
668        if let Some(parent) = path.parent() {
669            std::fs::create_dir_all(parent).ok();
670        }
671        let json = serde_json::to_string_pretty(self).context("serialize recording")?;
672        std::fs::write(path, json)
673            .with_context(|| format!("writing recording {}", path.display()))?;
674        Ok(())
675    }
676}
677
678/// Strict replay runner: every request must hit a recorded entry, or it errors. This guarantees
679/// the run is fully deterministic and machine-independent.
680pub struct RecordedRunner {
681    recording: Recording,
682}
683
684impl RecordedRunner {
685    pub fn new(recording: Recording) -> Self {
686        Self { recording }
687    }
688
689    /// Loads a replay runner from a recording file.
690    pub fn from_file(path: &Path) -> Result<Self> {
691        Ok(Self::new(Recording::load(path)?))
692    }
693}
694
695impl ModelRunner for RecordedRunner {
696    fn fingerprint(&self) -> &ModelFingerprint {
697        &self.recording.fingerprint
698    }
699
700    fn run(&self, req: &ModelRequest) -> Result<ModelResponse> {
701        let mut response = self
702            .recording
703            .entries
704            .get(&req.key())
705            .cloned()
706            .ok_or_else(|| anyhow!("no recorded response for request key {}", req.key()))?;
707        // The answer and the inherited fingerprint are replayed unchanged. What an
708        // earlier run saw of its exchange is handed on as exactly that: history.
709        if let Some(exchange) = &mut response.exchange {
710            exchange.origin = ObservationOrigin::Replayed;
711        }
712        Ok(response)
713    }
714}
715
716/// Wraps a real runner and captures every response so it can be replayed later. Pass-through:
717/// the wrapped runner's answers are returned unchanged.
718pub struct RecordingRunner<R: ModelRunner> {
719    inner: R,
720    recording: RefCell<Recording>,
721}
722
723impl<R: ModelRunner> RecordingRunner<R> {
724    pub fn new(inner: R) -> Self {
725        let recording = Recording::new(inner.fingerprint().clone());
726        Self {
727            inner,
728            recording: RefCell::new(recording),
729        }
730    }
731
732    /// Consumes the wrapper and returns everything captured so far.
733    pub fn into_recording(self) -> Recording {
734        self.recording.into_inner()
735    }
736}
737
738impl<R: ModelRunner> ModelRunner for RecordingRunner<R> {
739    fn fingerprint(&self) -> &ModelFingerprint {
740        self.inner.fingerprint()
741    }
742
743    fn run(&self, req: &ModelRequest) -> Result<ModelResponse> {
744        let resp = self.inner.run(req)?;
745        self.recording
746            .borrow_mut()
747            .entries
748            .insert(req.key(), resp.clone());
749        Ok(resp)
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    #[test]
758    fn admitted_endpoints_preserve_fingerprint_bytes_and_benign_queries() {
759        for endpoint in [
760            "https://api.example.invalid/v1///",
761            "http://localhost:11434/v1/",
762            "https://EXAMPLE.invalid:443/v1?region=west&mode=fast",
763            "https://example.invalid/v1?%72egion=west",
764        ] {
765            let params = ModelParams::default();
766            let old_fingerprint = ModelFingerprint {
767                provider: PROVIDER_OPENAI.to_owned(),
768                endpoint: endpoint.trim_end_matches('/').to_owned(),
769                params: params.clone(),
770            };
771            let runner = OpenAiRunner::new(endpoint, "", params);
772            assert!(runner.endpoint_admitted);
773            assert_eq!(runner.fingerprint(), &old_fingerprint);
774            assert_eq!(runner.fingerprint().digest(), old_fingerprint.digest());
775        }
776    }
777
778    #[test]
779    fn credential_endpoint_keys_are_refused_after_percent_and_case_decoding() {
780        for key in [
781            "api_key",
782            "api-key",
783            "apikey",
784            "access_token",
785            "token",
786            "authorization",
787            "password",
788            "client_secret",
789            "signature",
790            "sig",
791            "%41PI%5FKEY",
792            "%61pi-key",
793            "AP%49KEY",
794            "access%5Ftoken",
795            "ToKeN",
796            "AUTHORIZATION",
797            "pass%77ord",
798            "client%5Fsecret",
799            "sign%61ture",
800            "%73ig",
801        ] {
802            let endpoint = format!("https://example.invalid/v1?{key}=TEST_ENDPOINT_MARKER");
803            assert!(admitted_endpoint(&endpoint).is_none());
804        }
805    }
806
807    #[test]
808    fn refused_endpoints_fail_before_request_and_record_no_rejected_url() {
809        let request = ModelRequest {
810            system: "test".into(),
811            user: "test".into(),
812        };
813        for endpoint in [
814            "https://TEST_ENDPOINT_MARKER@example.invalid/v1",
815            "https://:TEST_ENDPOINT_MARKER@example.invalid/v1",
816            "https://example.invalid/v1#TEST_ENDPOINT_MARKER",
817            "https://example.invalid/v1#",
818            "https://example.invalid/v1?token=TEST_ENDPOINT_MARKER",
819            "file:///TEST_ENDPOINT_MARKER",
820            "TEST_ENDPOINT_MARKER",
821        ] {
822            let runner = OpenAiRunner::new(endpoint, "", ModelParams::default());
823            assert!(!runner.endpoint_admitted);
824            assert!(runner.fingerprint().endpoint.is_empty());
825            let recorder = RecordingRunner::new(runner);
826            let error = recorder.run(&request).unwrap_err();
827            assert_eq!(error.to_string(), ENDPOINT_ADMISSION_ERROR);
828            assert_eq!(error.chain().count(), 1);
829            let recording = recorder.into_recording();
830            assert!(recording.fingerprint.endpoint.is_empty());
831            assert!(recording.entries.is_empty());
832            let serialized = serde_json::to_string(&recording).unwrap();
833            assert!(!serialized.contains("TEST_ENDPOINT_MARKER"));
834        }
835    }
836
837    fn fp() -> ModelFingerprint {
838        ModelFingerprint {
839            provider: PROVIDER_RECORDED.to_string(),
840            endpoint: "rec".into(),
841            params: ModelParams {
842                model: "test-model".into(),
843                ..ModelParams::default()
844            },
845        }
846    }
847
848    #[test]
849    fn request_key_is_stable_and_order_sensitive() {
850        let a = ModelRequest {
851            system: "s".into(),
852            user: "u".into(),
853        };
854        let b = ModelRequest {
855            system: "s".into(),
856            user: "u".into(),
857        };
858        assert_eq!(a.key(), b.key());
859        let swapped = ModelRequest {
860            system: "u".into(),
861            user: "s".into(),
862        };
863        assert_ne!(a.key(), swapped.key());
864    }
865
866    #[test]
867    fn fingerprint_digest_changes_with_params() {
868        let mut f1 = fp();
869        let d1 = f1.digest();
870        f1.params.seed = 99;
871        assert_ne!(d1, f1.digest());
872        f1.params.seed = ModelParams::default().seed;
873        f1.params.version = Some("revision-2".into());
874        assert_ne!(d1, f1.digest());
875    }
876
877    #[test]
878    fn legacy_recording_without_model_version_still_loads() {
879        let legacy = r#"{"kind":"lean-ctx.eval-recording","fingerprint":{"provider":"openai-compatible","endpoint":"http://localhost:11434/v1","params":{"model":"gemma4:e4b","temperature":0.0,"top_p":1.0,"max_tokens":1024,"seed":7}},"entries":{}}"#;
880        let recording: Recording = serde_json::from_str(legacy).unwrap();
881        assert_eq!(recording.fingerprint.params.version, None);
882        // Committed recordings must re-serialize byte-identically, or the
883        // `gen_testbench_recording --check` gate breaks on every release.
884        assert_eq!(serde_json::to_string(&recording).unwrap(), legacy);
885    }
886
887    #[test]
888    fn recorded_runner_replays_and_errors_on_miss() {
889        let mut rec = Recording::new(fp());
890        let req = ModelRequest {
891            system: "sys".into(),
892            user: "hi".into(),
893        };
894        rec.entries.insert(req.key(), ModelResponse::new("hello"));
895        let runner = RecordedRunner::new(rec);
896        assert_eq!(runner.run(&req).unwrap().text, "hello");
897
898        let miss = ModelRequest {
899            system: "sys".into(),
900            user: "missing".into(),
901        };
902        assert!(runner.run(&miss).is_err(), "unknown key must hard-error");
903    }
904
905    #[test]
906    fn provider_usage_is_only_what_was_reported_and_a_replay_says_so() {
907        // The raw JSON as a provider would send it, read the way an answer is read.
908        let usage = |raw: &str| serde_json::from_str::<ReportedUsage>(raw).unwrap().0;
909        // Absent, null and an object without a known counter are all "not reported".
910        for raw in [
911            "null",
912            "{}",
913            r#"{"prompt_tokens":null,"prompt_tokens_details":null}"#,
914            r#"{"vendor_extension":{"anything":[1,true]}}"#,
915        ] {
916            assert_eq!(usage(raw), None, "{raw}");
917        }
918        // A reported zero is a count; a counter that was not sent stays unknown; names
919        // a provider adds are ignored.
920        let reported = usage(
921            r#"{"prompt_tokens":12,"vendor":[1],"completion_tokens":0,"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":4}}"#,
922        )
923        .unwrap();
924        assert_eq!(
925            (
926                reported.input_tokens,
927                reported.output_tokens,
928                reported.total_tokens,
929                reported.cached_input_tokens
930            ),
931            (Some(12), Some(0), None, Some(4))
932        );
933        assert!(reported.is_well_formed());
934        // No count: named, never a number.
935        for (raw, name) in [
936            (r#"{"prompt_tokens":true}"#, "prompt_tokens"),
937            (r#"{"prompt_tokens":1.0}"#, "prompt_tokens"),
938            (r#"{"completion_tokens":-1}"#, "completion_tokens"),
939            (r#"{"total_tokens":18446744073709551616}"#, "total_tokens"),
940            (r#"{"total_tokens":"7"}"#, "total_tokens"),
941            (r#"{"prompt_tokens_details":7}"#, "prompt_tokens_details"),
942            (r#""none""#, "usage"),
943            // A known name sent twice is no count, whichever value comes first and
944            // even when both are the same count.
945            (
946                r#"{"prompt_tokens":true,"prompt_tokens":7}"#,
947                "prompt_tokens",
948            ),
949            (
950                r#"{"prompt_tokens":7,"prompt_tokens":true}"#,
951                "prompt_tokens",
952            ),
953            (r#"{"prompt_tokens":7,"prompt_tokens":7}"#, "prompt_tokens"),
954            (
955                r#"{"prompt_tokens_details":{"cached_tokens":1,"cached_tokens":1}}"#,
956                "cached_tokens",
957            ),
958            (
959                r#"{"prompt_tokens_details":{"cached_tokens":1},"prompt_tokens_details":{"cached_tokens":1}}"#,
960                "prompt_tokens_details",
961            ),
962        ] {
963            let damaged = usage(raw).unwrap();
964            assert_eq!(damaged.invalid, [name], "{raw}");
965            assert!(!damaged.is_well_formed());
966            assert_eq!(
967                (
968                    damaged.input_tokens,
969                    damaged.output_tokens,
970                    damaged.total_tokens
971                ),
972                (None, None, None),
973                "{raw}"
974            );
975            assert_eq!(damaged.cached_input_tokens, None, "{raw}");
976        }
977
978        // A recorded exchange comes back as history; an answer without one is
979        // unchanged and serializes as it always did.
980        let req = ModelRequest {
981            system: "sys".into(),
982            user: "hi".into(),
983        };
984        let mut rec = Recording::new(fp());
985        let mut seen = ModelResponse::new("hello");
986        seen.exchange = Some(ProviderExchange {
987            origin: ObservationOrigin::Observed,
988            request_body_sha256: "a".repeat(64),
989            response_body_sha256: "b".repeat(64),
990            usage: Some(reported),
991        });
992        rec.entries.insert(req.key(), seen);
993        let replayed = RecordedRunner::new(rec)
994            .run(&req)
995            .unwrap()
996            .exchange
997            .unwrap();
998        assert_eq!(replayed.origin, ObservationOrigin::Replayed);
999        assert_eq!(replayed.usage.unwrap().input_tokens, Some(12));
1000        assert_eq!(
1001            serde_json::to_string(&ModelResponse::new("hello")).unwrap(),
1002            r#"{"text":"hello"}"#
1003        );
1004    }
1005
1006    #[test]
1007    fn recording_runner_captures_then_replays() {
1008        let mut seed = Recording::new(fp());
1009        let req = ModelRequest {
1010            system: "sys".into(),
1011            user: "q".into(),
1012        };
1013        seed.entries.insert(req.key(), ModelResponse::new("answer"));
1014        let recorder = RecordingRunner::new(RecordedRunner::new(seed));
1015        let _ = recorder.run(&req).unwrap();
1016        let captured = recorder.into_recording();
1017        assert_eq!(captured.entries.get(&req.key()).unwrap().text, "answer");
1018    }
1019}