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//! Three 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//! - **eprocess**: anytime-valid risk control — [`calibrate_from_store_eprocess`].
9//!
10//! All three enumerate stored traces, pair each trace that has a deferred outcome with the score of
11//! the attempt actually served, and hand the pairs to the respective core module. None feeds
12//! back into the request hot path — that wiring is a deliberate follow-on once an operator has
13//! reviewed a report.
14//!
15//! ## Which one to run, and why there are three
16//!
17//! The first two are **fixed-sample**: they answer "given this calibration set, what threshold is
18//! safe?", and their guarantees are stated over that one set. That is the right question when an
19//! operator recalibrates deliberately, reviews the report, and adopts a threshold.
20//!
21//! It is the wrong question when calibration runs continuously. Re-running a fixed-sample method
22//! whenever more feedback lands, and adopting the winner each time, is optional stopping on a
23//! growing stream — each individual run is valid while the sequence of adoptions is not. `eprocess`
24//! exists for that regime: its bound holds at **every** round, so re-reading it as often as you like
25//! costs nothing in validity. It pays for that in conservatism, and
26//! [`firstpass_core::eprocess`] documents the trade rather than burying it.
27
28use std::path::Path;
29
30use firstpass_core::conformal::{self, ConformalResult};
31use firstpass_core::eprocess;
32use firstpass_core::ltt::{self, LttResult};
33use firstpass_core::{Attempt, DeferredVerdict, GateResult, Score, Trace, Verdict};
34
35use crate::store::{self, StoreError};
36
37/// The result of calibrating a conformal threshold against real deferred feedback.
38#[derive(Debug, Clone)]
39pub struct CalibrationReport {
40    /// Number of `(score, correct)` pairs calibration ran on — one per trace with at least one
41    /// deferred verdict recorded.
42    pub n_pairs: usize,
43    /// The conformal calibration result (threshold, feasibility, calibration risk).
44    pub conformal: ConformalResult,
45    /// Empirical served-failure rate at `conformal.threshold`, measured on the same pairs used
46    /// to calibrate (a sanity check, not a held-out estimate — the proxy doesn't yet split
47    /// feedback into separate calibration/test batches).
48    pub empirical_served_failure: f64,
49    /// How many pairs would be served at the calibrated threshold.
50    pub n_served: usize,
51}
52
53impl CalibrationReport {
54    /// Render the report as human-readable lines for `firstpass calibrate`.
55    #[must_use]
56    pub fn render(&self) -> String {
57        format!(
58            "pairs: {n_pairs} ({n_served} served at threshold)\n\
59             threshold: {threshold:.4}\n\
60             feasible: {feasible}\n\
61             target alpha: {alpha:.4} (delta {delta:.4})\n\
62             calibration risk: {calib_risk:.4}\n\
63             empirical served-failure: {empirical:.4}\n",
64            n_pairs = self.n_pairs,
65            n_served = self.n_served,
66            threshold = self.conformal.threshold,
67            feasible = self.conformal.feasible,
68            alpha = self.conformal.alpha,
69            delta = self.conformal.delta,
70            calib_risk = self.conformal.calib_risk,
71            empirical = self.empirical_served_failure,
72        )
73    }
74}
75
76/// Calibrate a conformal threshold from `(score, correct)` pairs — a thin wrapper over
77/// [`firstpass_core::conformal`] that also reports the empirical served-failure at the chosen
78/// threshold.
79#[must_use]
80pub fn calibrate_pairs(
81    pairs: &[(f64, bool)],
82    alpha: f64,
83    delta: f64,
84    min_n: usize,
85) -> CalibrationReport {
86    let result = conformal::calibrate(pairs, alpha, delta, min_n);
87    let (empirical_served_failure, n_served) =
88        conformal::served_failure_rate(pairs, result.threshold);
89    CalibrationReport {
90        n_pairs: pairs.len(),
91        conformal: result,
92        empirical_served_failure,
93        n_served,
94    }
95}
96
97/// The aggregate score for a set of gate results at a given verdict: the mean of the numeric gate
98/// scores, or — when no gate reported a numeric score at all — `1.0` if it passed and `0.0` if it
99/// didn't. A bare pass/fail with no score still needs to sit somewhere on the `[0, 1]` axis
100/// conformal thresholds against; treating a scoreless pass as maximally confident and a scoreless
101/// fail as minimally confident keeps "higher score = more servable" true either way.
102///
103/// Shared by [`attempt_score`] (calibration, offline) and the router's `serve_threshold` decision
104/// (serving, online) so the two agree on what "the score" means.
105pub(crate) fn gate_score(gates: &[GateResult], verdict: Verdict) -> f64 {
106    let numeric: Vec<f64> = gates
107        .iter()
108        .filter_map(|g| g.score.map(Score::value))
109        .collect();
110    if numeric.is_empty() {
111        f64::from(verdict == Verdict::Pass)
112    } else {
113        numeric.iter().sum::<f64>() / numeric.len() as f64
114    }
115}
116
117/// The aggregate score for a served attempt (see [`gate_score`]).
118fn attempt_score(attempt: &Attempt) -> f64 {
119    gate_score(&attempt.gates, attempt.verdict)
120}
121
122/// Build a `(score, correct)` pair for one trace, if it has deferred feedback and a served
123/// attempt. `correct` is whether the MOST RECENT deferred verdict for the trace is `Pass` (later
124/// feedback supersedes earlier — e.g. a flaky CI run retried).
125fn trace_pair(trace: &Trace, deferred: &[DeferredVerdict]) -> Option<(f64, bool)> {
126    let last = deferred.last()?;
127    let served_rung = trace.final_.served_rung?;
128    let attempt = trace.attempts.iter().find(|a| a.rung == served_rung)?;
129    Some((attempt_score(attempt), last.verdict == Verdict::Pass))
130}
131
132/// The result of LTT calibration against real deferred feedback.
133#[derive(Debug, Clone)]
134pub struct LttReport {
135    /// Number of `(score, correct)` pairs — one per trace with a deferred verdict.
136    pub n_pairs: usize,
137    /// The LTT calibration result (threshold, feasibility, empirical risk, diagnostics).
138    pub ltt: LttResult,
139}
140
141impl LttReport {
142    /// Render the report as human-readable lines for `firstpass calibrate --method ltt`.
143    /// Format mirrors [`CalibrationReport::render`] with an added verifier ROC note.
144    #[must_use]
145    pub fn render(&self) -> String {
146        let far = match self.ltt.false_accept_rate {
147            Some(r) => format!("{r:.4}"),
148            None => "N/A (no incorrect items in calibration set)".to_owned(),
149        };
150        format!(
151            "method: ltt\n\
152             pairs: {n_pairs} ({n_served} served at threshold)\n\
153             threshold: {threshold:.4}\n\
154             feasible: {feasible}\n\
155             target alpha: {alpha:.4} (delta {delta:.4})\n\
156             empirical risk: {risk:.4}\n\
157             false-accept rate: {far}  (P(score >= lambda | incorrect); verifier ROC point)\n",
158            n_pairs = self.n_pairs,
159            n_served = self.ltt.n_served,
160            threshold = self.ltt.threshold,
161            feasible = self.ltt.feasible,
162            alpha = self.ltt.alpha,
163            delta = self.ltt.delta,
164            risk = self.ltt.empirical_risk,
165        )
166    }
167}
168
169/// Calibrate an LTT threshold from `(score, correct)` pairs — thin wrapper over
170/// [`firstpass_core::ltt`].
171#[must_use]
172pub fn calibrate_pairs_ltt(
173    pairs: &[(f64, bool)],
174    alpha: f64,
175    delta: f64,
176    min_n: usize,
177) -> LttReport {
178    LttReport {
179        n_pairs: pairs.len(),
180        ltt: ltt::calibrate(pairs, alpha, delta, min_n),
181    }
182}
183
184/// Report for `--method eprocess`: anytime-valid risk control.
185///
186/// Unlike [`CalibrationReport`] and [`LttReport`], which each summarise a **single** fixed-sample
187/// decision, this replays the stored feedback as the *stream it actually was* and reports what the
188/// controller would certify at the end of it. That difference is the point: the other two answer
189/// "given this calibration set, what threshold is safe?", while this answers "having watched this
190/// stream round by round, what is certified *now*?" — the question a continuously-recalibrating
191/// deployment is really asking.
192#[derive(Debug, Clone)]
193pub struct EProcessReport {
194    /// Pairs replayed.
195    pub n_pairs: usize,
196    /// Certified threshold and its evidence, or `None` if the stream never certified anything.
197    pub certification: Option<firstpass_core::eprocess::Certification>,
198    /// Target served-failure rate.
199    pub alpha: f64,
200    /// Family-wise error budget across the grid and all rounds.
201    pub delta: f64,
202    /// Evidence required per threshold (`n / delta`, the Bonferroni crossing level).
203    pub crossing_level: f64,
204    /// Realized served-failure over the replay, as a diagnostic — not the guarantee.
205    pub realized_served_failure: f64,
206}
207
208impl EProcessReport {
209    /// Render for `firstpass calibrate --method eprocess`. Mirrors [`LttReport::render`].
210    #[must_use]
211    pub fn render(&self) -> String {
212        let cert = match &self.certification {
213            Some(c) => format!(
214                "{:.4}  (e-value {:.1} >= {:.1}, first certified at round {})",
215                c.threshold, c.e_value, self.crossing_level, c.certified_at_round
216            ),
217            // Not an error, and deliberately not a number: an uncertified controller has proven
218            // nothing, and printing a threshold anyway is exactly the unproven claim this method
219            // exists to refuse.
220            None => "NONE — no threshold has earned a guarantee on this stream yet".to_owned(),
221        };
222        format!(
223            "method: eprocess (anytime-valid)\n\
224             pairs: {n_pairs}\n\
225             certified threshold: {cert}\n\
226             target alpha: {alpha:.4} (delta {delta:.4}, family-wise across grid AND rounds)\n\
227             realized served-failure: {realized:.4}\n\
228             guarantee: holds at EVERY round, no exchangeability assumed (Ville / e-process)\n",
229            n_pairs = self.n_pairs,
230            alpha = self.alpha,
231            delta = self.delta,
232            realized = self.realized_served_failure,
233        )
234    }
235}
236
237/// Replay `pairs` through an anytime-valid controller, in order.
238///
239/// Order matters here and nowhere else in this module: the other two methods sort or sweep, because
240/// exchangeability makes order irrelevant to them. This one consumes the sequence as a stream, which
241/// is what lets it stay valid when the stream is *not* exchangeable.
242#[must_use]
243pub fn calibrate_pairs_eprocess(pairs: &[(f64, bool)], alpha: f64, delta: f64) -> EProcessReport {
244    // Grid from the observed score support, as LTT does — but QUANTISED, which LTT does not need to
245    // be and this does.
246    //
247    // The Bonferroni crossing level is `n/delta`, so evidence required per threshold grows linearly
248    // in the number of distinct scores. LTT can take one candidate per distinct score for free
249    // because its exact-binomial test does not pay per candidate; here, a judge emitting
250    // full-precision floats over 10k traces yields ~10k distinct scores and a crossing level of
251    // 200,000 — a threshold that would essentially never certify, and the failure is silent: the
252    // report just says "nothing certified" and looks like insufficient data rather than a
253    // self-inflicted power collapse.
254    //
255    // Quantising to 2dp bounds the grid at 101 points regardless of store size. Resolution finer
256    // than 0.01 on a gate score is not information anyone acts on, and the statistical power bought
257    // back is worth far more than the granularity given up.
258    //
259    // Caught in review after I documented this exact hazard in the module doc and then failed to
260    // guard it — the grid is data-derived, so it looked bounded while being bounded by the data.
261    const GRID_QUANTUM: f64 = 100.0;
262    let mut grid: Vec<f64> = pairs
263        .iter()
264        .map(|&(s, _)| (s * GRID_QUANTUM).round() / GRID_QUANTUM)
265        .collect();
266    grid.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
267    grid.dedup();
268
269    let mut ctrl = eprocess::EProcessRiskControl::new(alpha, delta, eprocess::DEFAULT_BET, &grid);
270    for &(score, correct) in pairs {
271        ctrl.observe_served(score, correct);
272    }
273    EProcessReport {
274        n_pairs: pairs.len(),
275        certification: ctrl.certified_threshold(),
276        alpha,
277        delta,
278        crossing_level: ctrl.crossing_level(),
279        realized_served_failure: ctrl.realized_served_failure(),
280    }
281}
282
283/// Anytime-valid calibration from every trace in the store that has a deferred outcome.
284///
285/// Error handling and tenant scoping match [`calibrate_from_store`] exactly.
286///
287/// # Errors
288/// Returns [`StoreError`] if a stored trace's deferred verdicts cannot be read.
289pub fn calibrate_from_store_eprocess(
290    db_path: impl AsRef<Path>,
291    tenant: &str,
292    alpha: f64,
293    delta: f64,
294) -> Result<EProcessReport, StoreError> {
295    let db_path = db_path.as_ref();
296    let traces = store::load_tenant_traces(db_path, tenant).unwrap_or_default();
297    let mut pairs = Vec::with_capacity(traces.len());
298    for trace in &traces {
299        let deferred = store::load_deferred(db_path, &trace.trace_id.to_string())?;
300        if let Some(pair) = trace_pair(trace, &deferred) {
301            pairs.push(pair);
302        }
303    }
304    Ok(calibrate_pairs_eprocess(&pairs, alpha, delta))
305}
306
307/// Calibrate an LTT threshold from every trace in the store that has a deferred outcome.
308///
309/// Error handling and tenant scoping match [`calibrate_from_store`] exactly.
310///
311/// # Errors
312/// Returns [`StoreError`] if a stored trace's deferred verdicts cannot be read.
313pub fn calibrate_from_store_ltt(
314    db_path: impl AsRef<Path>,
315    tenant: &str,
316    alpha: f64,
317    delta: f64,
318    min_n: usize,
319) -> Result<LttReport, StoreError> {
320    let traces = store::load_tenant_traces(&db_path, tenant).unwrap_or_default();
321    let mut pairs = Vec::with_capacity(traces.len());
322    for trace in &traces {
323        let deferred = store::load_deferred(&db_path, &trace.trace_id.to_string())?;
324        if let Some(pair) = trace_pair(trace, &deferred) {
325            pairs.push(pair);
326        }
327    }
328    Ok(calibrate_pairs_ltt(&pairs, alpha, delta, min_n))
329}
330
331/// Calibrate a conformal threshold from every trace in the store that has a deferred outcome
332/// recorded.
333///
334/// # Errors
335/// Returns [`StoreError`] if a stored trace's deferred verdicts cannot be read. An unreadable or
336/// not-yet-initialized store is treated as zero traces (a 0-pair, infeasible report), matching the
337/// forgiving behaviour of `firstpass trace` — calibrating before any traffic is a valid state, not
338/// an error.
339pub fn calibrate_from_store(
340    db_path: impl AsRef<Path>,
341    tenant: &str,
342    alpha: f64,
343    delta: f64,
344    min_n: usize,
345) -> Result<CalibrationReport, StoreError> {
346    // Tenant-scoped (ADR 0004 §D3): a tenant only ever calibrates against its own feedback. The
347    // per-trace `load_deferred` below is safe unscoped because every `trace` here already belongs
348    // to `tenant`.
349    let traces = store::load_tenant_traces(&db_path, tenant).unwrap_or_default();
350    let mut pairs = Vec::with_capacity(traces.len());
351    for trace in &traces {
352        let deferred = store::load_deferred(&db_path, &trace.trace_id.to_string())?;
353        if let Some(pair) = trace_pair(trace, &deferred) {
354            pairs.push(pair);
355        }
356    }
357    Ok(calibrate_pairs(&pairs, alpha, delta, min_n))
358}
359
360#[cfg(test)]
361mod tests {
362    use firstpass_core::{
363        Features, FinalOutcome, GENESIS_HASH, GateResult, Mode, PolicyRef, RequestInfo, ServedFrom,
364        TaskKind,
365    };
366
367    use super::*;
368    use crate::store;
369
370    /// A minimal trace serving rung 0 with a single deterministic gate score, mirroring
371    /// `store::sample_trace` but with a caller-chosen score.
372    fn trace_with_score(score: f64) -> Trace {
373        let verdict = if score >= 0.5 {
374            Verdict::Pass
375        } else {
376            Verdict::Fail
377        };
378        let attempt = Attempt {
379            rung: 0,
380            model: "claude-haiku-4-5".to_owned(),
381            provider: "anthropic".to_owned(),
382            in_tokens: 10,
383            cache_write_tokens: 0,
384            cache_read_tokens: 0,
385            out_tokens: 5,
386            cost_usd: 0.001,
387            latency_ms: 12,
388            gates: vec![GateResult {
389                gate_id: "gate@v1".to_owned(),
390                verdict,
391                score: Some(Score::clamped(score)),
392                cost_usd: 0.0,
393                ms: 10,
394                reason: None,
395                evidence_ref: None,
396            }],
397            verdict,
398        };
399        let mut trace = Trace {
400            trace_id: uuid::Uuid::now_v7(),
401            prev_hash: GENESIS_HASH.to_owned(),
402            tenant_id: "tenant-a".to_owned(),
403            session_id: "session-1".to_owned(),
404            ts: jiff::Timestamp::now(),
405            mode: Mode::Enforce,
406            policy: PolicyRef {
407                id: "test@v0".to_owned(),
408                explore: false,
409                propensity: None,
410                mode_profile: None,
411            },
412            request: RequestInfo {
413                api: "anthropic.messages".to_owned(),
414                prompt_hash: "deadbeef".to_owned(),
415                features: Features::new(TaskKind::Other),
416            },
417            attempts: vec![attempt],
418            deferred: Vec::new(),
419            final_: FinalOutcome {
420                served_rung: Some(0),
421                served_from: ServedFrom::Attempt,
422                total_cost_usd: 0.001,
423                gate_cost_usd: 0.0,
424                total_latency_ms: 12,
425                escalations: 0,
426                counterfactual_baseline_usd: 0.001,
427                savings_usd: 0.0,
428                cache_source: None,
429            },
430            probe: None,
431            rollout: None,
432            shadow: None,
433            route_ix: None,
434            predicted_pass: None,
435            elastic: None,
436        };
437        trace.recompute_savings();
438        trace
439    }
440
441    #[test]
442    fn calibrate_pairs_finds_a_feasible_threshold_on_clean_pairs() {
443        // Scores cleanly separate correct (>=0.7) from incorrect (<0.3). alpha=0.2 tolerates
444        // some incorrect items being served, so conformal maximizes coverage — not just
445        // separation — up to that budget; alpha=0.2 also keeps the Hoeffding slack satisfiable
446        // at this sample size (min_n=30 wants a workable n, not the hundreds needed to certify
447        // alpha=0.1 at zero observed failures).
448        let mut pairs = Vec::new();
449        for i in 0..60u32 {
450            pairs.push((0.7 + f64::from(i % 10) * 0.01, true));
451        }
452        for i in 0..60u32 {
453            pairs.push((0.2 + f64::from(i % 10) * 0.01, false));
454        }
455        let report = calibrate_pairs(&pairs, 0.2, 0.1, 30);
456        assert!(
457            report.conformal.feasible,
458            "clean separation must be feasible"
459        );
460        assert!(
461            report.conformal.threshold >= 0.2 && report.conformal.threshold <= 0.79,
462            "threshold {} must land inside the observed score range",
463            report.conformal.threshold
464        );
465        assert_eq!(report.n_pairs, 120);
466        assert!(
467            report.empirical_served_failure <= 0.2 + 1e-9,
468            "empirical served-failure {} must respect alpha — the conformal guarantee",
469            report.empirical_served_failure
470        );
471    }
472
473    #[test]
474    fn calibrate_pairs_infeasible_below_min_n() {
475        let pairs = vec![(0.9, true), (0.9, true), (0.1, false)];
476        let report = calibrate_pairs(&pairs, 0.1, 0.1, 30);
477        assert!(
478            !report.conformal.feasible,
479            "too few pairs must be infeasible"
480        );
481    }
482
483    #[tokio::test]
484    async fn calibrate_from_store_pairs_only_traces_with_deferred_feedback() {
485        let db_path = std::env::temp_dir().join(format!(
486            "firstpass-calibrate-test-{}.db",
487            uuid::Uuid::now_v7()
488        ));
489        let (tx, handle) = store::open(&db_path).unwrap();
490
491        // 40 high-score traces confirmed correct, 40 low-score traces confirmed incorrect, and
492        // 5 traces with no deferred verdict at all (must be excluded from calibration).
493        let mut correct_ids = Vec::new();
494        let mut incorrect_ids = Vec::new();
495        for i in 0..40u32 {
496            let t = trace_with_score(0.7 + f64::from(i % 10) * 0.01);
497            correct_ids.push(t.trace_id.to_string());
498            tx.try_send(t).unwrap();
499        }
500        for i in 0..40u32 {
501            let t = trace_with_score(0.2 + f64::from(i % 10) * 0.01);
502            incorrect_ids.push(t.trace_id.to_string());
503            tx.try_send(t).unwrap();
504        }
505        for i in 0..5u32 {
506            tx.try_send(trace_with_score(0.5 + f64::from(i) * 0.01))
507                .unwrap();
508        }
509        drop(tx);
510        handle.await.unwrap();
511
512        for trace_id in &correct_ids {
513            let dv = DeferredVerdict {
514                gate_id: "outcome".to_owned(),
515                verdict: Verdict::Pass,
516                score: None,
517                reported_at: jiff::Timestamp::now(),
518                reporter: "unit-test".to_owned(),
519            };
520            store::append_deferred(&db_path, trace_id, &dv).unwrap();
521        }
522        for trace_id in &incorrect_ids {
523            let dv = DeferredVerdict {
524                gate_id: "outcome".to_owned(),
525                verdict: Verdict::Fail,
526                score: None,
527                reported_at: jiff::Timestamp::now(),
528                reporter: "unit-test".to_owned(),
529            };
530            store::append_deferred(&db_path, trace_id, &dv).unwrap();
531        }
532
533        // alpha=0.2 for the same Hoeffding-slack reason as the calibrate_pairs test above.
534        let report = calibrate_from_store(&db_path, "tenant-a", 0.2, 0.1, 30).unwrap();
535        assert_eq!(
536            report.n_pairs, 80,
537            "only the 80 traces with deferred feedback pair up"
538        );
539        assert!(report.conformal.feasible);
540        assert!(
541            report.empirical_served_failure <= 0.2 + 1e-9,
542            "empirical served-failure {} must respect alpha on clean synthetic data",
543            report.empirical_served_failure
544        );
545
546        // D7 isolation: a different tenant sees none of tenant-a's pairs — calibration is empty.
547        let other = calibrate_from_store(&db_path, "tenant-b", 0.2, 0.1, 30).unwrap();
548        assert_eq!(
549            other.n_pairs, 0,
550            "tenant-b must not see tenant-a's feedback"
551        );
552
553        let _ = std::fs::remove_file(&db_path);
554    }
555
556    // ── LTT wiring tests ─────────────────────────────────────────────────────────────────────
557
558    #[test]
559    fn calibrate_pairs_ltt_feasible_on_clean_pairs() {
560        // Same synthetic data as the conformal test — clean score separation, alpha=0.2.
561        let mut pairs = Vec::new();
562        for i in 0..60u32 {
563            pairs.push((0.7 + f64::from(i % 10) * 0.01, true));
564        }
565        for i in 0..60u32 {
566            pairs.push((0.2 + f64::from(i % 10) * 0.01, false));
567        }
568        let report = calibrate_pairs_ltt(&pairs, 0.2, 0.1, 30);
569        assert!(
570            report.ltt.feasible,
571            "clean separation must be feasible with LTT"
572        );
573        assert!(
574            report.ltt.threshold >= 0.2 && report.ltt.threshold <= 0.79,
575            "threshold {} must land inside the observed score range",
576            report.ltt.threshold
577        );
578        assert_eq!(report.n_pairs, 120);
579        assert!(
580            report.ltt.empirical_risk <= 0.2 + 1e-9,
581            "empirical risk {} must respect alpha",
582            report.ltt.empirical_risk
583        );
584    }
585
586    #[test]
587    fn calibrate_pairs_ltt_infeasible_below_min_n() {
588        let pairs = vec![(0.9, true), (0.9, true), (0.1, false)];
589        let report = calibrate_pairs_ltt(&pairs, 0.1, 0.05, 30);
590        assert!(
591            !report.ltt.feasible,
592            "too few pairs must be infeasible with LTT"
593        );
594    }
595
596    /// **The grid must stay bounded no matter how many distinct scores the store holds.**
597    ///
598    /// Caught in review. The Bonferroni crossing level is `n/delta`, so evidence required per
599    /// threshold grows linearly in grid size: a judge emitting full-precision floats over 10k traces
600    /// gives ~10k candidates and a crossing level of 200,000. Nothing would ever certify, and the
601    /// report would say "no threshold certified" — indistinguishable from honest insufficient data,
602    /// which is what makes it dangerous rather than merely wasteful.
603    ///
604    /// Asserts both halves: the grid is bounded, AND a clean stream at that scale still certifies.
605    /// Bounding it while destroying certification would pass a size check and fail the user.
606    #[test]
607    fn a_high_precision_score_distribution_does_not_collapse_statistical_power() {
608        // 4000 pairs, each with a distinct full-precision score in a tight band — exactly what a
609        // continuous judge emits, and previously ~4000 grid points.
610        let pairs: Vec<(f64, bool)> = (0..4000)
611            .map(|i| {
612                let score = 0.90 + f64::from(i) * 1e-7;
613                (score, i % 20 != 0) // 5% failure rate, well under alpha
614            })
615            .collect();
616        let report = calibrate_pairs_eprocess(&pairs, 0.20, 0.05);
617
618        // 2dp quantisation over a 0.9..0.9004 band collapses to a handful of points; the hard
619        // requirement is that it cannot scale with the store.
620        assert!(
621            report.crossing_level <= 101.0 / 0.05,
622            "the grid must be bounded by quantisation, not by the data: crossing level {} implies \
623             {} grid points",
624            report.crossing_level,
625            report.crossing_level * 0.05
626        );
627        assert!(
628            report.certification.is_some(),
629            "4000 clean pairs must still certify — bounding the grid must not cost the power it \
630             was meant to protect"
631        );
632    }
633
634    /// An uncertified stream must render as NONE, never as a number.
635    ///
636    /// The failure this guards is a quiet one: printing some default threshold when nothing has been
637    /// proven reads exactly like a calibrated result to whoever runs the command. Too few pairs to
638    /// certify must look like too few pairs to certify.
639    #[test]
640    fn eprocess_reports_no_threshold_when_nothing_is_certified() {
641        let pairs: Vec<(f64, bool)> = vec![(0.9, true), (0.8, true)];
642        let report = calibrate_pairs_eprocess(&pairs, 0.10, 0.05);
643        assert!(
644            report.certification.is_none(),
645            "two pairs cannot certify anything at delta=0.05"
646        );
647        let rendered = report.render();
648        assert!(
649            rendered.contains("NONE"),
650            "an uncertified stream must say so plainly, got: {rendered}"
651        );
652        assert!(
653            rendered.contains("anytime-valid"),
654            "the report must name the guarantee it provides, got: {rendered}"
655        );
656    }
657
658    /// Enough clean evidence must certify, and the rendered threshold must be the certified one.
659    /// The pairing with the test above is the contract: silent when unproven, specific when proven.
660    #[test]
661    fn eprocess_certifies_and_renders_the_threshold_on_a_clean_stream() {
662        let mut pairs: Vec<(f64, bool)> = Vec::new();
663        for i in 0..2000 {
664            // Deterministic 5% failure rate, well under alpha — no RNG, so this is reproducible.
665            pairs.push((0.9, i % 20 != 0));
666        }
667        let report = calibrate_pairs_eprocess(&pairs, 0.20, 0.05);
668        let cert = report
669            .certification
670            .as_ref()
671            .expect("2000 clean pairs must certify");
672        assert!(
673            cert.e_value >= report.crossing_level,
674            "a certified threshold must meet the Bonferroni crossing level: {} < {}",
675            cert.e_value,
676            report.crossing_level
677        );
678        assert!(
679            report.render().contains(&format!("{:.4}", cert.threshold)),
680            "the rendered report must show the certified threshold"
681        );
682    }
683
684    #[test]
685    fn ltt_report_render_includes_method_and_far() {
686        // Smoke-test that render() produces the expected key fields without panicking.
687        let mut pairs: Vec<(f64, bool)> = Vec::new();
688        for _ in 0..200 {
689            pairs.push((0.9, true));
690        }
691        for _ in 0..5 {
692            pairs.push((0.9, false));
693        }
694        for _ in 0..15 {
695            pairs.push((0.2, false));
696        }
697        let report = calibrate_pairs_ltt(&pairs, 0.10, 0.05, 30);
698        let rendered = report.render();
699        assert!(
700            rendered.contains("method: ltt"),
701            "render must tag the method"
702        );
703        assert!(
704            rendered.contains("false-accept rate:"),
705            "render must include verifier ROC note"
706        );
707        assert!(
708            rendered.contains("feasible:"),
709            "render must include feasibility"
710        );
711    }
712}