Skip to main content

firstpass_proxy/
calibrate.rs

1//! Recalibrate the serving threshold from real deferred feedback (SPEC §10.1, run against live
2//! traffic instead of a static benchmark suite) — the "learns your quality bar" loop.
3//!
4//! Two calibration methods are available:
5//! - **conformal** (default): split-conformal with Hoeffding bound — [`calibrate_from_store`].
6//! - **ltt**: Learn-then-Test / RCPS with exact-binomial fixed-sequence testing —
7//!   [`calibrate_from_store_ltt`].
8//!
9//! Both enumerate stored traces, pair each trace that has a deferred outcome with the score of
10//! the attempt actually served, and hand the pairs to the respective core module. Neither feeds
11//! back into the request hot path — that wiring is a deliberate follow-on once an operator has
12//! reviewed a report.
13
14use std::path::Path;
15
16use firstpass_core::conformal::{self, ConformalResult};
17use firstpass_core::ltt::{self, LttResult};
18use firstpass_core::{Attempt, DeferredVerdict, GateResult, Score, Trace, Verdict};
19
20use crate::store::{self, StoreError};
21
22/// The result of calibrating a conformal threshold against real deferred feedback.
23#[derive(Debug, Clone)]
24pub struct CalibrationReport {
25    /// Number of `(score, correct)` pairs calibration ran on — one per trace with at least one
26    /// deferred verdict recorded.
27    pub n_pairs: usize,
28    /// The conformal calibration result (threshold, feasibility, calibration risk).
29    pub conformal: ConformalResult,
30    /// Empirical served-failure rate at `conformal.threshold`, measured on the same pairs used
31    /// to calibrate (a sanity check, not a held-out estimate — the proxy doesn't yet split
32    /// feedback into separate calibration/test batches).
33    pub empirical_served_failure: f64,
34    /// How many pairs would be served at the calibrated threshold.
35    pub n_served: usize,
36}
37
38impl CalibrationReport {
39    /// Render the report as human-readable lines for `firstpass calibrate`.
40    #[must_use]
41    pub fn render(&self) -> String {
42        format!(
43            "pairs: {n_pairs} ({n_served} served at threshold)\n\
44             threshold: {threshold:.4}\n\
45             feasible: {feasible}\n\
46             target alpha: {alpha:.4} (delta {delta:.4})\n\
47             calibration risk: {calib_risk:.4}\n\
48             empirical served-failure: {empirical:.4}\n",
49            n_pairs = self.n_pairs,
50            n_served = self.n_served,
51            threshold = self.conformal.threshold,
52            feasible = self.conformal.feasible,
53            alpha = self.conformal.alpha,
54            delta = self.conformal.delta,
55            calib_risk = self.conformal.calib_risk,
56            empirical = self.empirical_served_failure,
57        )
58    }
59}
60
61/// Calibrate a conformal threshold from `(score, correct)` pairs — a thin wrapper over
62/// [`firstpass_core::conformal`] that also reports the empirical served-failure at the chosen
63/// threshold.
64#[must_use]
65pub fn calibrate_pairs(
66    pairs: &[(f64, bool)],
67    alpha: f64,
68    delta: f64,
69    min_n: usize,
70) -> CalibrationReport {
71    let result = conformal::calibrate(pairs, alpha, delta, min_n);
72    let (empirical_served_failure, n_served) =
73        conformal::served_failure_rate(pairs, result.threshold);
74    CalibrationReport {
75        n_pairs: pairs.len(),
76        conformal: result,
77        empirical_served_failure,
78        n_served,
79    }
80}
81
82/// The aggregate score for a set of gate results at a given verdict: the mean of the numeric gate
83/// scores, or — when no gate reported a numeric score at all — `1.0` if it passed and `0.0` if it
84/// didn't. A bare pass/fail with no score still needs to sit somewhere on the `[0, 1]` axis
85/// conformal thresholds against; treating a scoreless pass as maximally confident and a scoreless
86/// fail as minimally confident keeps "higher score = more servable" true either way.
87///
88/// Shared by [`attempt_score`] (calibration, offline) and the router's `serve_threshold` decision
89/// (serving, online) so the two agree on what "the score" means.
90pub(crate) fn gate_score(gates: &[GateResult], verdict: Verdict) -> f64 {
91    let numeric: Vec<f64> = gates
92        .iter()
93        .filter_map(|g| g.score.map(Score::value))
94        .collect();
95    if numeric.is_empty() {
96        f64::from(verdict == Verdict::Pass)
97    } else {
98        numeric.iter().sum::<f64>() / numeric.len() as f64
99    }
100}
101
102/// The aggregate score for a served attempt (see [`gate_score`]).
103fn attempt_score(attempt: &Attempt) -> f64 {
104    gate_score(&attempt.gates, attempt.verdict)
105}
106
107/// Build a `(score, correct)` pair for one trace, if it has deferred feedback and a served
108/// attempt. `correct` is whether the MOST RECENT deferred verdict for the trace is `Pass` (later
109/// feedback supersedes earlier — e.g. a flaky CI run retried).
110fn trace_pair(trace: &Trace, deferred: &[DeferredVerdict]) -> Option<(f64, bool)> {
111    let last = deferred.last()?;
112    let served_rung = trace.final_.served_rung?;
113    let attempt = trace.attempts.iter().find(|a| a.rung == served_rung)?;
114    Some((attempt_score(attempt), last.verdict == Verdict::Pass))
115}
116
117/// The result of LTT calibration against real deferred feedback.
118#[derive(Debug, Clone)]
119pub struct LttReport {
120    /// Number of `(score, correct)` pairs — one per trace with a deferred verdict.
121    pub n_pairs: usize,
122    /// The LTT calibration result (threshold, feasibility, empirical risk, diagnostics).
123    pub ltt: LttResult,
124}
125
126impl LttReport {
127    /// Render the report as human-readable lines for `firstpass calibrate --method ltt`.
128    /// Format mirrors [`CalibrationReport::render`] with an added verifier ROC note.
129    #[must_use]
130    pub fn render(&self) -> String {
131        let far = match self.ltt.false_accept_rate {
132            Some(r) => format!("{r:.4}"),
133            None => "N/A (no incorrect items in calibration set)".to_owned(),
134        };
135        format!(
136            "method: ltt\n\
137             pairs: {n_pairs} ({n_served} served at threshold)\n\
138             threshold: {threshold:.4}\n\
139             feasible: {feasible}\n\
140             target alpha: {alpha:.4} (delta {delta:.4})\n\
141             empirical risk: {risk:.4}\n\
142             false-accept rate: {far}  (P(score >= lambda | incorrect); verifier ROC point)\n",
143            n_pairs = self.n_pairs,
144            n_served = self.ltt.n_served,
145            threshold = self.ltt.threshold,
146            feasible = self.ltt.feasible,
147            alpha = self.ltt.alpha,
148            delta = self.ltt.delta,
149            risk = self.ltt.empirical_risk,
150        )
151    }
152}
153
154/// Calibrate an LTT threshold from `(score, correct)` pairs — thin wrapper over
155/// [`firstpass_core::ltt`].
156#[must_use]
157pub fn calibrate_pairs_ltt(
158    pairs: &[(f64, bool)],
159    alpha: f64,
160    delta: f64,
161    min_n: usize,
162) -> LttReport {
163    LttReport {
164        n_pairs: pairs.len(),
165        ltt: ltt::calibrate(pairs, alpha, delta, min_n),
166    }
167}
168
169/// Calibrate an LTT threshold from every trace in the store that has a deferred outcome.
170///
171/// Error handling and tenant scoping match [`calibrate_from_store`] exactly.
172///
173/// # Errors
174/// Returns [`StoreError`] if a stored trace's deferred verdicts cannot be read.
175pub fn calibrate_from_store_ltt(
176    db_path: impl AsRef<Path>,
177    tenant: &str,
178    alpha: f64,
179    delta: f64,
180    min_n: usize,
181) -> Result<LttReport, StoreError> {
182    let traces = store::load_tenant_traces(&db_path, tenant).unwrap_or_default();
183    let mut pairs = Vec::with_capacity(traces.len());
184    for trace in &traces {
185        let deferred = store::load_deferred(&db_path, &trace.trace_id.to_string())?;
186        if let Some(pair) = trace_pair(trace, &deferred) {
187            pairs.push(pair);
188        }
189    }
190    Ok(calibrate_pairs_ltt(&pairs, alpha, delta, min_n))
191}
192
193/// Calibrate a conformal threshold from every trace in the store that has a deferred outcome
194/// recorded.
195///
196/// # Errors
197/// Returns [`StoreError`] if a stored trace's deferred verdicts cannot be read. An unreadable or
198/// not-yet-initialized store is treated as zero traces (a 0-pair, infeasible report), matching the
199/// forgiving behaviour of `firstpass trace` — calibrating before any traffic is a valid state, not
200/// an error.
201pub fn calibrate_from_store(
202    db_path: impl AsRef<Path>,
203    tenant: &str,
204    alpha: f64,
205    delta: f64,
206    min_n: usize,
207) -> Result<CalibrationReport, StoreError> {
208    // Tenant-scoped (ADR 0004 §D3): a tenant only ever calibrates against its own feedback. The
209    // per-trace `load_deferred` below is safe unscoped because every `trace` here already belongs
210    // to `tenant`.
211    let traces = store::load_tenant_traces(&db_path, tenant).unwrap_or_default();
212    let mut pairs = Vec::with_capacity(traces.len());
213    for trace in &traces {
214        let deferred = store::load_deferred(&db_path, &trace.trace_id.to_string())?;
215        if let Some(pair) = trace_pair(trace, &deferred) {
216            pairs.push(pair);
217        }
218    }
219    Ok(calibrate_pairs(&pairs, alpha, delta, min_n))
220}
221
222#[cfg(test)]
223mod tests {
224    use firstpass_core::{
225        Features, FinalOutcome, GENESIS_HASH, GateResult, Mode, PolicyRef, RequestInfo, ServedFrom,
226        TaskKind,
227    };
228
229    use super::*;
230    use crate::store;
231
232    /// A minimal trace serving rung 0 with a single deterministic gate score, mirroring
233    /// `store::sample_trace` but with a caller-chosen score.
234    fn trace_with_score(score: f64) -> Trace {
235        let verdict = if score >= 0.5 {
236            Verdict::Pass
237        } else {
238            Verdict::Fail
239        };
240        let attempt = Attempt {
241            rung: 0,
242            model: "claude-haiku-4-5".to_owned(),
243            provider: "anthropic".to_owned(),
244            in_tokens: 10,
245            out_tokens: 5,
246            cost_usd: 0.001,
247            latency_ms: 12,
248            gates: vec![GateResult {
249                gate_id: "gate@v1".to_owned(),
250                verdict,
251                score: Some(Score::clamped(score)),
252                cost_usd: 0.0,
253                ms: 10,
254                reason: None,
255                evidence_ref: None,
256            }],
257            verdict,
258        };
259        let mut trace = Trace {
260            trace_id: uuid::Uuid::now_v7(),
261            prev_hash: GENESIS_HASH.to_owned(),
262            tenant_id: "tenant-a".to_owned(),
263            session_id: "session-1".to_owned(),
264            ts: jiff::Timestamp::now(),
265            mode: Mode::Enforce,
266            policy: PolicyRef {
267                id: "test@v0".to_owned(),
268                explore: false,
269                propensity: None,
270            },
271            request: RequestInfo {
272                api: "anthropic.messages".to_owned(),
273                prompt_hash: "deadbeef".to_owned(),
274                features: Features::new(TaskKind::Other),
275            },
276            attempts: vec![attempt],
277            deferred: Vec::new(),
278            final_: FinalOutcome {
279                served_rung: Some(0),
280                served_from: ServedFrom::Attempt,
281                total_cost_usd: 0.001,
282                gate_cost_usd: 0.0,
283                total_latency_ms: 12,
284                escalations: 0,
285                counterfactual_baseline_usd: 0.001,
286                savings_usd: 0.0,
287            },
288        };
289        trace.recompute_savings();
290        trace
291    }
292
293    #[test]
294    fn calibrate_pairs_finds_a_feasible_threshold_on_clean_pairs() {
295        // Scores cleanly separate correct (>=0.7) from incorrect (<0.3). alpha=0.2 tolerates
296        // some incorrect items being served, so conformal maximizes coverage — not just
297        // separation — up to that budget; alpha=0.2 also keeps the Hoeffding slack satisfiable
298        // at this sample size (min_n=30 wants a workable n, not the hundreds needed to certify
299        // alpha=0.1 at zero observed failures).
300        let mut pairs = Vec::new();
301        for i in 0..60u32 {
302            pairs.push((0.7 + f64::from(i % 10) * 0.01, true));
303        }
304        for i in 0..60u32 {
305            pairs.push((0.2 + f64::from(i % 10) * 0.01, false));
306        }
307        let report = calibrate_pairs(&pairs, 0.2, 0.1, 30);
308        assert!(
309            report.conformal.feasible,
310            "clean separation must be feasible"
311        );
312        assert!(
313            report.conformal.threshold >= 0.2 && report.conformal.threshold <= 0.79,
314            "threshold {} must land inside the observed score range",
315            report.conformal.threshold
316        );
317        assert_eq!(report.n_pairs, 120);
318        assert!(
319            report.empirical_served_failure <= 0.2 + 1e-9,
320            "empirical served-failure {} must respect alpha — the conformal guarantee",
321            report.empirical_served_failure
322        );
323    }
324
325    #[test]
326    fn calibrate_pairs_infeasible_below_min_n() {
327        let pairs = vec![(0.9, true), (0.9, true), (0.1, false)];
328        let report = calibrate_pairs(&pairs, 0.1, 0.1, 30);
329        assert!(
330            !report.conformal.feasible,
331            "too few pairs must be infeasible"
332        );
333    }
334
335    #[tokio::test]
336    async fn calibrate_from_store_pairs_only_traces_with_deferred_feedback() {
337        let db_path = std::env::temp_dir().join(format!(
338            "firstpass-calibrate-test-{}.db",
339            uuid::Uuid::now_v7()
340        ));
341        let (tx, handle) = store::open(&db_path).unwrap();
342
343        // 40 high-score traces confirmed correct, 40 low-score traces confirmed incorrect, and
344        // 5 traces with no deferred verdict at all (must be excluded from calibration).
345        let mut correct_ids = Vec::new();
346        let mut incorrect_ids = Vec::new();
347        for i in 0..40u32 {
348            let t = trace_with_score(0.7 + f64::from(i % 10) * 0.01);
349            correct_ids.push(t.trace_id.to_string());
350            tx.try_send(t).unwrap();
351        }
352        for i in 0..40u32 {
353            let t = trace_with_score(0.2 + f64::from(i % 10) * 0.01);
354            incorrect_ids.push(t.trace_id.to_string());
355            tx.try_send(t).unwrap();
356        }
357        for i in 0..5u32 {
358            tx.try_send(trace_with_score(0.5 + f64::from(i) * 0.01))
359                .unwrap();
360        }
361        drop(tx);
362        handle.await.unwrap();
363
364        for trace_id in &correct_ids {
365            let dv = DeferredVerdict {
366                gate_id: "outcome".to_owned(),
367                verdict: Verdict::Pass,
368                score: None,
369                reported_at: jiff::Timestamp::now(),
370                reporter: "unit-test".to_owned(),
371            };
372            store::append_deferred(&db_path, trace_id, &dv).unwrap();
373        }
374        for trace_id in &incorrect_ids {
375            let dv = DeferredVerdict {
376                gate_id: "outcome".to_owned(),
377                verdict: Verdict::Fail,
378                score: None,
379                reported_at: jiff::Timestamp::now(),
380                reporter: "unit-test".to_owned(),
381            };
382            store::append_deferred(&db_path, trace_id, &dv).unwrap();
383        }
384
385        // alpha=0.2 for the same Hoeffding-slack reason as the calibrate_pairs test above.
386        let report = calibrate_from_store(&db_path, "tenant-a", 0.2, 0.1, 30).unwrap();
387        assert_eq!(
388            report.n_pairs, 80,
389            "only the 80 traces with deferred feedback pair up"
390        );
391        assert!(report.conformal.feasible);
392        assert!(
393            report.empirical_served_failure <= 0.2 + 1e-9,
394            "empirical served-failure {} must respect alpha on clean synthetic data",
395            report.empirical_served_failure
396        );
397
398        // D7 isolation: a different tenant sees none of tenant-a's pairs — calibration is empty.
399        let other = calibrate_from_store(&db_path, "tenant-b", 0.2, 0.1, 30).unwrap();
400        assert_eq!(
401            other.n_pairs, 0,
402            "tenant-b must not see tenant-a's feedback"
403        );
404
405        let _ = std::fs::remove_file(&db_path);
406    }
407
408    // ── LTT wiring tests ─────────────────────────────────────────────────────────────────────
409
410    #[test]
411    fn calibrate_pairs_ltt_feasible_on_clean_pairs() {
412        // Same synthetic data as the conformal test — clean score separation, alpha=0.2.
413        let mut pairs = Vec::new();
414        for i in 0..60u32 {
415            pairs.push((0.7 + f64::from(i % 10) * 0.01, true));
416        }
417        for i in 0..60u32 {
418            pairs.push((0.2 + f64::from(i % 10) * 0.01, false));
419        }
420        let report = calibrate_pairs_ltt(&pairs, 0.2, 0.1, 30);
421        assert!(
422            report.ltt.feasible,
423            "clean separation must be feasible with LTT"
424        );
425        assert!(
426            report.ltt.threshold >= 0.2 && report.ltt.threshold <= 0.79,
427            "threshold {} must land inside the observed score range",
428            report.ltt.threshold
429        );
430        assert_eq!(report.n_pairs, 120);
431        assert!(
432            report.ltt.empirical_risk <= 0.2 + 1e-9,
433            "empirical risk {} must respect alpha",
434            report.ltt.empirical_risk
435        );
436    }
437
438    #[test]
439    fn calibrate_pairs_ltt_infeasible_below_min_n() {
440        let pairs = vec![(0.9, true), (0.9, true), (0.1, false)];
441        let report = calibrate_pairs_ltt(&pairs, 0.1, 0.05, 30);
442        assert!(
443            !report.ltt.feasible,
444            "too few pairs must be infeasible with LTT"
445        );
446    }
447
448    #[test]
449    fn ltt_report_render_includes_method_and_far() {
450        // Smoke-test that render() produces the expected key fields without panicking.
451        let mut pairs: Vec<(f64, bool)> = Vec::new();
452        for _ in 0..200 {
453            pairs.push((0.9, true));
454        }
455        for _ in 0..5 {
456            pairs.push((0.9, false));
457        }
458        for _ in 0..15 {
459            pairs.push((0.2, false));
460        }
461        let report = calibrate_pairs_ltt(&pairs, 0.10, 0.05, 30);
462        let rendered = report.render();
463        assert!(
464            rendered.contains("method: ltt"),
465            "render must tag the method"
466        );
467        assert!(
468            rendered.contains("false-accept rate:"),
469            "render must include verifier ROC note"
470        );
471        assert!(
472            rendered.contains("feasible:"),
473            "render must include feasibility"
474        );
475    }
476}