veridict 0.19.7

Statistical regression gate for A/B and hypothesis testing: compare candidate vs baseline results with win-rate, Elo, SPRT, and bootstrap confidence intervals.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Multiple-comparison correction for a `compare --metric` run's family of *simultaneous
//! per-metric claims* (`--claim-correction bonferroni|holm`, with `--correction` kept as a
//! deprecated alias for one release - see `main.rs`'s CLI arg doc).
//!
//! **The problem, and what this module does and doesn't protect.** `compare --metric elo
//! --metric winrate --metric sign-test` already lets a user run several metrics against the same
//! candidate in one call. Each metric's own pass/fail decision is made independently at the
//! stated `--confidence` - run enough metrics (or, in a broader campaign, enough candidates) and
//! the chance that *some individual metric's own* claim clears its bar by luck alone climbs. That
//! matters for whatever, if anything, reads one metric's own `verdict`/`promotion` as a claim on
//! its own. It is *not* the same target as `verdict::aggregate`'s combined result
//! (`Report`/`MultiReport`'s `verdict`/`promotion`): requiring *every* metric to pass is already
//! an intersection-union rule over level-`alpha/2` tests, itself level `alpha/2` unconditionally
//! (Berger 1982) - already at least as conservative as a single uncorrected metric, no correction
//! needed. So this module never touches `verdict`/`promotion` (the deployment-gate fields); it
//! only ever populates `Report.family_adjusted_verdict`/`family_adjusted_promotion` and, for a
//! multi-metric run (`apply_correction_to_multi`), `MultiReport.simultaneous_claims_promotion` -
//! see `docs/metrics.md`'s `--claim-correction` section for the full split.
//!
//! **The family-error target.** `compare`'s pass rule already reads a *two-sided*
//! `(1-confidence)` CI's *lower* bound as a one-sided pass signal - a two-sided interval splits
//! its error budget evenly between both tails, so a single, uncorrected metric today already has
//! a one-sided false-pass rate of `alpha/2` (e.g. 0.025 at the default 95% confidence), not the
//! nominal `alpha`. The natural, and only defensible, correction target is therefore "running `m`
//! metrics together is no more dangerous than running one" - i.e. keep the *family's* one-sided
//! false-pass rate at that same `alpha/2`, not the nominal `alpha` itself (which would let a
//! "corrected" multi-metric family tolerate a *higher* false-pass rate than a single uncorrected
//! metric already has today - backwards for this project). This falls straight out of standard
//! textbook Bonferroni simultaneous confidence intervals (Dunn 1961; Miller, *Simultaneous
//! Statistical Inference*, 1966): recompute each test's ordinary, symmetric, two-sided CI at
//! confidence `1 - alpha/m` (the same `alpha = 1-confidence` the tool already uses, split across
//! the family - no extra factor of anything) and re-run the *existing, unchanged* `verdict::decide`
//! against it. Because a valid CI always has `ci_low <= ci_high`, and this only ever *widens* an
//! already-`Pass` report's interval (`ci_low >= pass_above > fail_below` at the narrower, original
//! confidence), the widened `ci_high` can never newly satisfy `ci_high <= fail_below` - correction
//! can only ever move an unadjusted `Pass` to `Inconclusive`, never manufacture a `Fail`. That
//! asymmetry isn't a special case implemented below; it's a direct consequence of widening plus
//! `decide`'s existing logic, and it's exactly what this project's bias calls for.
//!
//! **`achieved_alpha`: the p-value-equivalent both corrections share.** Rather than literally
//! recomputing a full CI and re-running `decide` for every candidate confidence level, this module
//! binary-searches for the smallest `gamma` (same units as `1 - confidence`) at which a report's
//! own CI, built from the same observed data at confidence `1 - gamma`, would still have its lower
//! bound clear `pass_above`. This is the standard CI-test duality (a `1-gamma` CI is exactly the
//! set of null values not rejected by a `gamma`-level test) - rigorous for Clopper-Pearson (exact
//! binomial tail test), Wilson (score test), and Jeffreys (a monotone Beta-posterior family), all
//! three provably monotone in `gamma`, so bisection is safe. Bonferroni then compares
//! `achieved_alpha <= alpha/m` directly; Holm compares each rank's achieved alpha to
//! `alpha/(m-k+1)` in ascending order, stopping at the first failure. Both read straight off the
//! CI functions `compare` already uses (`stats::wilson`/`stats::exact`/`stats::jeffreys`) - no
//! separate math for Bonferroni vs. Holm, one search drives both.
//!
//! **`mean-diff`/`quantile-diff`/`relative-diff` and `--cluster-by-id` are rejected outright, not
//! silently miscorrected or partially counted.** None of the three bootstrap-CI metrics
//! (`metrics::lacks_closed_form_ci`) nor a cluster bootstrap CI (`--cluster-by-id`) has a
//! closed-form CI-at-a-hypothetical-confidence
//! function to search against (same reason `verdict::estimate_additional_trials`/`power` special-
//! case the bootstrap metrics). Silently leaving such a report uncorrected while still counting
//! it toward `family_size` - this module's behavior before `family_adjusted_verdict` existed -
//! meant a "corrected" family's own guarantee was never actually complete. Worse for
//! `--cluster-by-id`: reconstructing a plain i.i.d. CI from `successes`/`paired_count` alone (the
//! only inputs `achieved_alpha` has) comes out *narrower* than the true cluster-robust CI whenever
//! there's positive intra-cluster correlation (the usual case; that correlation is the whole
//! reason `--cluster-by-id` widens the CI to begin with) - correction could then under-downgrade a
//! pass it should have caught, leniency in exactly the direction this project's own bias forbids.
//! Both are now a hard `Err` instead: a family that can't get a real, method-consistent guarantee
//! for every member doesn't get a `family_adjusted_verdict`/`simultaneous_claims_promotion` result
//! at all. Bootstrap-aware and cluster-aware correction are both separate, deferred pieces of work
//! (see `docs/research-map.md`).

use crate::error::VeridictError;
use crate::metrics;
use crate::report::{MultiReport, Report};
use crate::stats::elo;
use crate::stats::{exact, jeffreys, wilson};
use crate::{CiMethod, MetricConfig, MetricKind, Promotion, Verdict};

/// Which multiple-comparison correction (if any) `compare --claim-correction` applies to a
/// multi-metric family. `None` is the default - `apply_correction` returns immediately without
/// touching any report, so an unrequested run's JSON stays byte-identical to before this existed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Correction {
    None,
    Bonferroni,
    Holm,
}

impl Correction {
    fn label(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Bonferroni => "bonferroni",
            Self::Holm => "holm",
        }
    }
}

/// Bisection stops here rather than searching all the way to `gamma = 0` - past this point the
/// implied CI is already wider than any real analysis would use, and 60 halvings of the starting
/// bracket already converge far past `f64` precision.
const ACHIEVED_ALPHA_FLOOR: f64 = 1e-12;
const BISECTION_ITERATIONS: u32 = 60;

/// Smallest `gamma` (same units as `1 - confidence`) at which this report's own CI, recomputed at
/// confidence `1 - gamma` from the same observed data, would still have its lower bound (in the
/// metric's native "effect" units - a proportion offset from zero for winrate/sign-test, Elo
/// points for elo) clear `pass_above`. `None` for `mean-diff`/`quantile-diff`/`relative-diff`
/// (`metrics::lacks_closed_form_ci` - no closed-form CI-at-a-hypothetical-confidence function
/// exists for any of the three's bootstrap CI - see module doc) - callers must leave such a
/// report's verdict unadjusted. Only ever called for a report whose
/// verdict is already `Pass` at `confidence`, so `gamma_orig = 1 - confidence` is a known-passing
/// search bracket, not re-verified here.
fn achieved_alpha(
    metric: MetricKind,
    ci_method: CiMethod,
    successes: u64,
    paired_count: u64,
    effect: f64,
    pass_above: f64,
    confidence: f64,
) -> Option<f64> {
    if metrics::lacks_closed_form_ci(metric) {
        return None;
    }

    // Recovers the same proportion `estimate_additional_trials` recovers from `effect` for
    // exactly the same reason: elo's `effect` has already been through `elo_from_score`'s
    // logistic transform, so this is that transform's inverse.
    let p_hat = if metric == MetricKind::Elo {
        1.0 / (1.0 + 10f64.powf(-effect / 400.0))
    } else {
        effect + 0.5
    };

    let ci_lower_effect_at = |gamma: f64| -> Option<f64> {
        let candidate_confidence = 1.0 - gamma;
        if metric == MetricKind::Elo {
            let (lo, _) =
                wilson::wilson_ci_from_proportion(p_hat, paired_count as f64, candidate_confidence)
                    .ok()?;
            Some(elo::elo_from_score(lo))
        } else {
            let (lo, _) = match ci_method {
                CiMethod::Wilson => {
                    wilson::wilson_ci(successes, paired_count, candidate_confidence).ok()?
                }
                CiMethod::Jeffreys => {
                    jeffreys::jeffreys_ci(successes, paired_count, candidate_confidence).ok()?
                }
                CiMethod::Exact => {
                    exact::clopper_pearson_ci(successes, paired_count, candidate_confidence).ok()?
                }
            };
            Some(lo - 0.5)
        }
    };

    let gamma_orig = 1.0 - confidence;
    let mut lo = ACHIEVED_ALPHA_FLOOR;
    let mut hi = gamma_orig;
    for _ in 0..BISECTION_ITERATIONS {
        let mid = lo + (hi - lo) / 2.0;
        match ci_lower_effect_at(mid) {
            Some(lower) if lower >= pass_above => hi = mid,
            _ => lo = mid,
        }
    }
    Some(hi)
}

/// Holm's step-down rejection: sort correctable reports (those with a `Some` achieved alpha) by
/// achieved alpha ascending, compare each rank `k` (1-based) to `alpha/(family_size-k+1)`, and
/// **stop rejecting at the first failure** - a report past an early failure is held back
/// regardless of its own achieved alpha, because Holm's family-wise error guarantee (Holm 1979)
/// depends on the sequential stop, not independent per-test comparisons. Returns, indexed the same
/// as `achieved`: whether each report was rejected (`Some(true)`/`Some(false)`, `None` if
/// uncorrectable) and the per-rank threshold it was actually compared against.
fn holm_reject(
    achieved: &[Option<f64>],
    alpha: f64,
    family_size: usize,
) -> (Vec<Option<bool>>, Vec<Option<f64>>) {
    let mut order: Vec<usize> = (0..achieved.len())
        .filter(|&i| achieved[i].is_some())
        .collect();
    order.sort_by(|&a, &b| achieved[a].unwrap().total_cmp(&achieved[b].unwrap()));

    let mut rejected = vec![None; achieved.len()];
    let mut thresholds = vec![None; achieved.len()];
    let mut still_rejecting = true;
    for (rank, &idx) in order.iter().enumerate() {
        let k = rank + 1;
        let threshold = alpha / (family_size - k + 1) as f64;
        thresholds[idx] = Some(threshold);
        still_rejecting = still_rejecting && achieved[idx].unwrap() <= threshold;
        rejected[idx] = Some(still_rejecting);
    }
    (rejected, thresholds)
}

/// Populates each report's `family_adjusted_verdict`/`family_adjusted_promotion` (and
/// `correction_method`/`family_size`/`achieved_alpha`/`adjusted_alpha_threshold`) from
/// `correction`; never touches `report.verdict`/`report.promotion` (see the module doc for why).
/// `reports`/`configs` must be the same length and index-aligned (one `MetricConfig` per
/// `Report`, needed to recover each report's `ci_method` - not itself stored on `Report`). Only
/// ever adjusts a report whose own `verdict` is `Pass` (correction exists to catch a lucky pass
/// among many attempts, not to second-guess a fail or inconclusive) - call this *after* any
/// `FailureCaps` have been applied (`verdict::apply_failure_caps`/`apply_failure_caps_to_multi`),
/// so a report already forced to `Inconclusive` for a technical failure never counts as a
/// legitimate statistical claim. `family_size = reports.len()` always - a single-metric run
/// degenerates both Bonferroni and Holm to a no-op (`alpha/1 = alpha`, exactly the report's own
/// existing pass condition), so callers don't need to special-case it away.
///
/// Returns `Err(VeridictError::CorrectionConflictsWithClusterById)` if any report was built with
/// `--cluster-by-id` (detected via `report.cluster_count.is_some()`), or
/// `Err(VeridictError::CorrectionRequiresClosedFormCi)` if any report's metric lacks a
/// closed-form CI (`mean-diff`/`quantile-diff`/`relative-diff` -
/// `metrics::lacks_closed_form_ci`) - both only when `correction != Correction::None` (see the
/// module doc's "rejected outright" section for why).
pub fn apply_correction(
    reports: &mut [Report],
    configs: &[MetricConfig],
    correction: Correction,
    confidence: f64,
) -> Result<(), VeridictError> {
    if correction == Correction::None {
        return Ok(());
    }
    if reports.iter().any(|r| r.cluster_count.is_some()) {
        return Err(VeridictError::CorrectionConflictsWithClusterById);
    }
    if let Some(report) = reports
        .iter()
        .find(|r| metrics::lacks_closed_form_ci(r.metric))
    {
        return Err(VeridictError::CorrectionRequiresClosedFormCi {
            metric: metrics::metric_label(report.metric),
        });
    }
    let family_size = reports.len();
    let alpha = 1.0 - confidence;

    let achieved: Vec<Option<f64>> = reports
        .iter()
        .zip(configs)
        .map(|(report, config)| {
            if report.verdict != Verdict::Pass {
                return None;
            }
            achieved_alpha(
                report.metric,
                config.ci_method(),
                report.candidate_count,
                report.paired_count,
                report.effect,
                report.pass_above,
                confidence,
            )
        })
        .collect();

    let (rejected, thresholds): (Vec<Option<bool>>, Vec<Option<f64>>) = match correction {
        Correction::None => unreachable!("returned above"),
        Correction::Bonferroni => {
            let uniform = alpha / family_size as f64;
            (
                achieved.iter().map(|a| a.map(|v| v <= uniform)).collect(),
                achieved.iter().map(|a| a.map(|_| uniform)).collect(),
            )
        }
        Correction::Holm => holm_reject(&achieved, alpha, family_size),
    };

    for (i, report) in reports.iter_mut().enumerate() {
        // `None` (an already-Fail/Inconclusive report) just mirrors `verdict` - correction never
        // invents a Fail and never second-guesses a report that wasn't a Pass to begin with.
        let family_adjusted_verdict = match rejected[i] {
            Some(true) => Verdict::Pass,
            Some(false) => Verdict::Inconclusive,
            None => report.verdict,
        };
        report.family_adjusted_verdict = Some(family_adjusted_verdict);
        report.family_adjusted_promotion =
            Some(Promotion::decide(report.validity, family_adjusted_verdict));
        report.correction_method = Some(correction.label());
        report.family_size = Some(family_size);
        report.achieved_alpha = achieved[i];
        report.adjusted_alpha_threshold = thresholds[i];
        // Deprecated compatibility alias - always equals `verdict` now (see the field's own doc).
        report.unadjusted_verdict = Some(report.verdict);
    }
    Ok(())
}

/// `apply_correction` for a multi-metric run, plus `MultiReport.simultaneous_claims_promotion`:
/// `Some(Promoted)` only if every report's `family_adjusted_promotion` is `Promoted` too - every
/// metric's own improvement claim individually survives being read as part of the family.
/// `None`/omitted when `correction == Correction::None`, same as every other correction field.
/// Call *after* `verdict::apply_failure_caps_to_multi` (see `apply_correction`'s doc) -
/// `multi.verdict`/`multi.promotion` (the deployment gate, already finalized by that point) are
/// untouched either way.
pub fn apply_correction_to_multi(
    multi: &mut MultiReport,
    configs: &[MetricConfig],
    correction: Correction,
    confidence: f64,
) -> Result<(), VeridictError> {
    apply_correction(&mut multi.reports, configs, correction, confidence)?;
    if correction != Correction::None {
        let promoted = multi
            .reports
            .iter()
            .all(|r| r.family_adjusted_promotion == Some(Promotion::Promoted));
        multi.simultaneous_claims_promotion = Some(if promoted {
            Promotion::Promoted
        } else {
            Promotion::NotPromoted
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::{DataQuality, REPORT_SCHEMA_VERSION};
    use crate::stats::wilson;
    use crate::{Promotion, Validity};

    #[allow(clippy::too_many_arguments)]
    fn report_with(
        metric: MetricKind,
        verdict: Verdict,
        candidate_count: u64,
        paired_count: u64,
        effect: f64,
        ci_low: f64,
        ci_high: f64,
        pass_above: f64,
        fail_below: f64,
    ) -> Report {
        Report {
            schema_version: REPORT_SCHEMA_VERSION,
            verdict,
            validity: Validity::Valid,
            promotion: Promotion::decide(Validity::Valid, verdict),
            metric,
            baseline_count: paired_count - candidate_count,
            candidate_count,
            paired_count,
            effect,
            confidence: 0.95,
            ci_low,
            ci_high,
            pass_above,
            fail_below,
            timeouts: 0,
            crashes: 0,
            invalid: 0,
            failure_breakdown: crate::metrics::FailureBreakdown::default(),
            reason: "test fixture".to_string(),
            estimated_additional_trials: None,
            inconclusive_kind: None,
            warnings: Vec::new(),
            data_quality: DataQuality::default(),
            quantile: None,
            cluster_count: None,
            max_cluster_size: None,
            effective_sample_size: None,
            design_effect: None,
            scale_diagnostics: None,
            tied_count: None,
            pair_score_counts: None,
            correction_method: None,
            family_size: None,
            achieved_alpha: None,
            adjusted_alpha_threshold: None,
            unadjusted_verdict: None,
            family_adjusted_verdict: None,
            family_adjusted_promotion: None,
        }
    }

    fn winrate_pass(candidate_wins: u64, n: u64, pass_above: f64) -> Report {
        let (lo, hi) = wilson::wilson_ci(candidate_wins, n, 0.95).unwrap();
        let p_hat = candidate_wins as f64 / n as f64;
        report_with(
            MetricKind::WinRate,
            Verdict::Pass,
            candidate_wins,
            n,
            p_hat - 0.5,
            lo - 0.5,
            hi - 0.5,
            pass_above,
            -pass_above,
        )
    }

    fn winrate_config() -> MetricConfig {
        MetricConfig::WinRate {
            ci_method: CiMethod::Wilson,
            failure_policy: crate::FailurePolicy::ReportOnly,
        }
    }

    #[test]
    fn stronger_effect_has_smaller_achieved_alpha() {
        let weak = achieved_alpha(
            MetricKind::WinRate,
            CiMethod::Wilson,
            58,
            100,
            0.08,
            0.02,
            0.95,
        )
        .unwrap();
        let strong = achieved_alpha(
            MetricKind::WinRate,
            CiMethod::Wilson,
            80,
            100,
            0.30,
            0.02,
            0.95,
        )
        .unwrap();
        assert!(
            strong < weak,
            "a larger, cleaner effect should need a smaller achieved alpha to still pass: \
             strong={strong}, weak={weak}"
        );
    }

    #[test]
    fn achieved_alpha_self_consistency_across_all_ci_methods() {
        // CI-test duality check (mirrors verdict.rs's
        // winrate_wilson_search_matches_a_direct_wilson_recompute): achieved_alpha's own crossing
        // point must reproduce ci_low == pass_above when the CI is recomputed at confidence
        // (1 - achieved_alpha) via the SAME function - proves the search actually lands on the
        // right value, not just "smaller for stronger effects" (the test above). Every other test
        // in this module uses the default Wilson method - this is the only coverage for the
        // Exact/Jeffreys branches of `achieved_alpha`'s internal closure.
        // 64/100 verified (via a real `compare` run) to be a genuine pass at 95% confidence under
        // all three CI methods - Exact is always at least as wide as Wilson, so a smaller margin
        // passes under Wilson/Jeffreys but not Exact, which would violate achieved_alpha's own
        // "already passing at confidence" precondition.
        let successes = 64u64;
        let n = 100u64;
        let effect = successes as f64 / n as f64 - 0.5;
        let pass_above = 0.02;

        for ci_method in [CiMethod::Wilson, CiMethod::Exact, CiMethod::Jeffreys] {
            let gamma = achieved_alpha(
                MetricKind::WinRate,
                ci_method,
                successes,
                n,
                effect,
                pass_above,
                0.95,
            )
            .unwrap();
            let confidence = 1.0 - gamma;
            let (lo, _hi) = match ci_method {
                CiMethod::Wilson => wilson::wilson_ci(successes, n, confidence).unwrap(),
                CiMethod::Exact => exact::clopper_pearson_ci(successes, n, confidence).unwrap(),
                CiMethod::Jeffreys => jeffreys::jeffreys_ci(successes, n, confidence).unwrap(),
            };
            let ci_low_effect = lo - 0.5;
            assert!(
                (ci_low_effect - pass_above).abs() < 1e-6,
                "{ci_method:?}: recomputed ci_low {ci_low_effect} should land on pass_above \
                 {pass_above}, gamma={gamma}"
            );
        }
    }

    #[test]
    fn mean_diff_has_no_achieved_alpha() {
        assert_eq!(
            achieved_alpha(
                MetricKind::MeanDiff,
                CiMethod::Wilson,
                0,
                100,
                0.05,
                0.02,
                0.95
            ),
            None
        );
    }

    #[test]
    fn none_leaves_reports_completely_untouched() {
        let mut reports = vec![winrate_pass(80, 100, 0.02)];
        let configs = vec![winrate_config()];
        apply_correction(&mut reports, &configs, Correction::None, 0.95).unwrap();
        assert_eq!(reports[0].verdict, Verdict::Pass);
        assert_eq!(reports[0].correction_method, None);
        assert_eq!(reports[0].family_size, None);
        assert_eq!(reports[0].achieved_alpha, None);
        assert_eq!(reports[0].unadjusted_verdict, None);
        assert_eq!(reports[0].family_adjusted_verdict, None);
        assert_eq!(reports[0].family_adjusted_promotion, None);
    }

    #[test]
    fn single_metric_family_degenerates_to_a_no_op() {
        // family_size=1: alpha/1 == alpha, exactly the report's own existing pass condition.
        // verdict/promotion (the deployment gate) are never touched at all - only the
        // family_adjusted_* counterpart is populated, and even that degenerates to Pass here.
        let mut reports = vec![winrate_pass(80, 100, 0.02)];
        let configs = vec![winrate_config()];
        apply_correction(&mut reports, &configs, Correction::Bonferroni, 0.95).unwrap();
        assert_eq!(reports[0].verdict, Verdict::Pass);
        assert_eq!(reports[0].family_adjusted_verdict, Some(Verdict::Pass));
        assert_eq!(
            reports[0].family_adjusted_promotion,
            Some(Promotion::Promoted)
        );
        apply_correction(&mut reports, &configs, Correction::Holm, 0.95).unwrap();
        assert_eq!(reports[0].verdict, Verdict::Pass);
        assert_eq!(reports[0].family_adjusted_verdict, Some(Verdict::Pass));
    }

    #[test]
    fn bonferroni_downgrades_a_marginal_claim_without_touching_verdict() {
        // 62/100 is a genuine, bare pass at 95% confidence (ci_low ~= 0.0221, just past
        // pass_above=0.02 - verified against a real `compare` run before writing this test) that
        // survives alone but not split three ways.
        let mut reports = vec![winrate_pass(62, 100, 0.02)];
        let configs = vec![winrate_config()];
        apply_correction(&mut reports, &configs, Correction::None, 0.95).unwrap();
        assert_eq!(reports[0].verdict, Verdict::Pass);

        let single = winrate_pass(62, 100, 0.02);
        let mut family = vec![
            clone_report(&single),
            clone_report(&single),
            clone_report(&single),
        ];
        let configs = vec![winrate_config(), winrate_config(), winrate_config()];
        apply_correction(&mut family, &configs, Correction::Bonferroni, 0.95).unwrap();
        // The deployment-gate verdict/promotion are untouched by correction...
        assert_eq!(family[0].verdict, Verdict::Pass);
        assert_eq!(family[0].promotion, Promotion::Promoted);
        // ...unadjusted_verdict is a deprecated compatibility alias that always mirrors verdict...
        assert_eq!(family[0].unadjusted_verdict, Some(Verdict::Pass));
        // ...but the family-adjusted claim is downgraded.
        assert_eq!(
            family[0].family_adjusted_verdict,
            Some(Verdict::Inconclusive)
        );
        assert_eq!(
            family[0].family_adjusted_promotion,
            Some(Promotion::NotPromoted)
        );
        assert_eq!(family[0].family_size, Some(3));
    }

    fn clone_report(r: &Report) -> Report {
        Report {
            schema_version: r.schema_version,
            verdict: r.verdict,
            validity: r.validity,
            promotion: r.promotion,
            metric: r.metric,
            baseline_count: r.baseline_count,
            candidate_count: r.candidate_count,
            paired_count: r.paired_count,
            effect: r.effect,
            confidence: r.confidence,
            ci_low: r.ci_low,
            ci_high: r.ci_high,
            pass_above: r.pass_above,
            fail_below: r.fail_below,
            timeouts: r.timeouts,
            crashes: r.crashes,
            invalid: r.invalid,
            failure_breakdown: r.failure_breakdown,
            reason: r.reason.clone(),
            estimated_additional_trials: r.estimated_additional_trials,
            inconclusive_kind: r.inconclusive_kind,
            warnings: r.warnings.clone(),
            data_quality: r.data_quality,
            quantile: r.quantile,
            cluster_count: r.cluster_count,
            max_cluster_size: r.max_cluster_size,
            effective_sample_size: r.effective_sample_size,
            design_effect: r.design_effect,
            scale_diagnostics: r.scale_diagnostics,
            tied_count: r.tied_count,
            pair_score_counts: r.pair_score_counts,
            correction_method: r.correction_method,
            family_size: r.family_size,
            achieved_alpha: r.achieved_alpha,
            adjusted_alpha_threshold: r.adjusted_alpha_threshold,
            unadjusted_verdict: r.unadjusted_verdict,
            family_adjusted_verdict: r.family_adjusted_verdict,
            family_adjusted_promotion: r.family_adjusted_promotion,
        }
    }

    #[test]
    fn holm_sequential_stop_holds_back_a_report_that_would_pass_its_own_threshold() {
        // Three reports ranked by achieved alpha ascending: rank 1 fails its own (tightest)
        // threshold alpha/3; ranks 2 and 3 must then be held back too, even if rank 3's own
        // achieved alpha would individually clear its (loosest) threshold alpha/1 in isolation.
        let alpha = 0.05;
        let achieved = vec![
            Some(alpha / 3.0 + 0.001), // rank 1: fails alpha/3 by a hair
            Some(alpha / 2.0 - 0.001), // rank 2: would pass alpha/2 alone
            Some(alpha - 0.001),       // rank 3: would pass alpha/1 alone
        ];
        let (rejected, _) = holm_reject(&achieved, alpha, 3);
        assert_eq!(rejected, vec![Some(false), Some(false), Some(false)]);
    }

    #[test]
    fn holm_rejects_every_report_when_the_whole_ordered_prefix_holds() {
        let alpha = 0.05;
        let achieved = vec![
            Some(alpha / 3.0 - 1e-6),
            Some(alpha / 2.0 - 1e-6),
            Some(alpha - 1e-6),
        ];
        let (rejected, _) = holm_reject(&achieved, alpha, 3);
        assert_eq!(rejected, vec![Some(true), Some(true), Some(true)]);
    }

    #[test]
    fn correction_rejects_a_mean_diff_report() {
        let mean_diff = report_with(
            MetricKind::MeanDiff,
            Verdict::Pass,
            0,
            100,
            0.05,
            0.01,
            0.09,
            0.0,
            0.0,
        );
        let winrate = winrate_pass(62, 100, 0.02);
        let mut reports = vec![mean_diff, winrate];
        let configs = vec![
            MetricConfig::MeanDiff {
                bootstrap_method: crate::BootstrapMethod::Percentile,
            },
            winrate_config(),
        ];
        let err =
            apply_correction(&mut reports, &configs, Correction::Bonferroni, 0.95).unwrap_err();
        assert!(matches!(
            err,
            crate::VeridictError::CorrectionRequiresClosedFormCi {
                metric: "metric mean-diff"
            }
        ));
        assert_eq!(reports[0].correction_method, None);
    }

    #[test]
    fn correction_rejects_a_quantile_diff_report() {
        let quantile_diff = report_with(
            MetricKind::QuantileDiff,
            Verdict::Pass,
            0,
            100,
            0.05,
            0.01,
            0.09,
            0.0,
            0.0,
        );
        let mut reports = vec![quantile_diff];
        let configs = vec![MetricConfig::QuantileDiff {
            quantile: 0.95,
            bootstrap_method: crate::BootstrapMethod::Percentile,
        }];
        let err =
            apply_correction(&mut reports, &configs, Correction::Bonferroni, 0.95).unwrap_err();
        assert!(matches!(
            err,
            crate::VeridictError::CorrectionRequiresClosedFormCi {
                metric: "metric quantile-diff"
            }
        ));
    }

    #[test]
    fn correction_rejects_a_cluster_by_id_report() {
        let mut report = winrate_pass(80, 100, 0.02);
        report.cluster_count = Some(20);
        let mut reports = vec![report];
        let configs = vec![winrate_config()];
        let err =
            apply_correction(&mut reports, &configs, Correction::Bonferroni, 0.95).unwrap_err();
        assert!(matches!(
            err,
            crate::VeridictError::CorrectionConflictsWithClusterById
        ));
        // Untouched - the error is returned before any report is mutated.
        assert_eq!(reports[0].verdict, Verdict::Pass);
        assert_eq!(reports[0].correction_method, None);
    }

    fn multi_report_with(reports: Vec<Report>) -> MultiReport {
        let verdict = crate::verdict::aggregate(reports.iter().map(|r| r.verdict));
        MultiReport {
            schema_version: REPORT_SCHEMA_VERSION,
            verdict,
            validity: Validity::Valid,
            promotion: Promotion::decide(Validity::Valid, verdict),
            simultaneous_claims_promotion: None,
            reports,
        }
    }

    #[test]
    fn simultaneous_claims_promotion_is_promoted_only_when_every_claim_survives() {
        // Both metrics are strong, clean passes - neither should be downgraded even split two
        // ways, so every family_adjusted claim survives and the family is jointly promoted.
        let mut multi = multi_report_with(vec![
            winrate_pass(90, 100, 0.02),
            winrate_pass(90, 100, 0.02),
        ]);
        let configs = vec![winrate_config(), winrate_config()];
        apply_correction_to_multi(&mut multi, &configs, Correction::Bonferroni, 0.95).unwrap();
        assert_eq!(
            multi.simultaneous_claims_promotion,
            Some(Promotion::Promoted)
        );
        // The deployment-gate verdict/promotion are untouched.
        assert_eq!(multi.verdict, Verdict::Pass);
        assert_eq!(multi.promotion, Promotion::Promoted);
    }

    #[test]
    fn simultaneous_claims_promotion_is_not_promoted_if_any_claim_is_downgraded() {
        // Same marginal-pass-times-three family as bonferroni_downgrades_a_marginal_claim... -
        // the deployment gate stays pass, but the joint claim doesn't survive.
        let single = winrate_pass(62, 100, 0.02);
        let mut multi = multi_report_with(vec![
            clone_report(&single),
            clone_report(&single),
            clone_report(&single),
        ]);
        let configs = vec![winrate_config(), winrate_config(), winrate_config()];
        apply_correction_to_multi(&mut multi, &configs, Correction::Bonferroni, 0.95).unwrap();
        assert_eq!(
            multi.simultaneous_claims_promotion,
            Some(Promotion::NotPromoted)
        );
        assert_eq!(multi.verdict, Verdict::Pass);
        assert_eq!(multi.promotion, Promotion::Promoted);
    }

    #[test]
    fn simultaneous_claims_promotion_stays_none_when_correction_is_none() {
        let mut multi = multi_report_with(vec![winrate_pass(90, 100, 0.02)]);
        let configs = vec![winrate_config()];
        apply_correction_to_multi(&mut multi, &configs, Correction::None, 0.95).unwrap();
        assert_eq!(multi.simultaneous_claims_promotion, None);
    }
}