euhadra 0.2.0

A programmable voice input framework — ASR, LLM refinement, and OS integration as composable adapters
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! `ci_baseline*.json` schemas, I/O, and regression gating.
//!
//! Two baseline files live under `docs/benchmarks/`, each consumed by a
//! separate CI job:
//!
//! - `ci_baseline.json` — produced by `eval_l1_smoke` (Phase A-1):
//!   per-language WER/CER + ASR + E2E latency from a live whisper run
//!   on a FLEURS subset.
//! - `ci_baseline_layers.json` — produced by `eval_l1_fast` (Phase A-2):
//!   per-language layer ablation (ΔWER from running the pipeline with
//!   each post-ASR layer toggled on/off) and per-layer μ-benchmark
//!   latency.
//!
//! Both files are self-describing on tolerances so policy lives next to
//! the numbers it constrains.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

use crate::eval::latency::LatencySummary;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Baseline {
    pub schema_version: u32,
    pub generated: String,
    pub asr_model: String,
    pub languages: BTreeMap<String, LanguageBaseline>,
    pub tolerances: Tolerances,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageBaseline {
    pub samples: usize,
    /// `Some` for languages where WER is the primary metric (en),
    /// `None` for languages that report CER instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wer: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cer: Option<f64>,
    pub asr_latency_ms: LatencyRecord,
    pub e2e_latency_ms: LatencyRecord,
    /// Real-Time Factor: ASR processing time divided by audio duration.
    /// `< 1.0` means the engine ran faster than real-time (required for
    /// streaming dictation). Stored separately from latency because it
    /// is hardware-normalised (RTF on a 5-second utterance is directly
    /// comparable to RTF on a 10-second utterance, while raw latency is
    /// not). `None` on legacy baselines that pre-date RTF reporting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rtf: Option<f64>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct LatencyRecord {
    pub p50: f64,
    pub p95: f64,
}

impl From<LatencySummary> for LatencyRecord {
    fn from(s: LatencySummary) -> Self {
        Self {
            p50: round2(s.p50_ms),
            p95: round2(s.p95_ms),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Tolerances {
    /// Absolute WER/CER increase that triggers a warning, e.g. 0.05 = 5%
    /// absolute regression flagged.
    pub wer_absolute_warn: f64,
    pub wer_absolute_fail: f64,
    pub wer_relative_warn: f64,
    pub wer_relative_fail: f64,
    pub latency_p50_relative_warn: f64,
    pub latency_p50_relative_fail: f64,
    pub e2e_latency_p50_relative_warn: f64,
    pub e2e_latency_p50_relative_fail: f64,
    /// RTF regression tolerances (relative). RTF correlates with latency
    /// on the same model + runner pair, but tracking it independently
    /// catches the case where a faster runner masks a model-side
    /// slowdown.
    #[serde(default = "default_rtf_warn")]
    pub rtf_relative_warn: f64,
    #[serde(default = "default_rtf_fail")]
    pub rtf_relative_fail: f64,
    /// Absolute thresholds — anchored to user-perceived dictation
    /// quality, independent of the per-runner baseline. These exist
    /// because the relative checks let an already-bad baseline slide;
    /// the absolutes pin the floor.
    ///
    /// `rtf_absolute_warn`: RTF at or above this is a streaming-quality
    /// red flag (≥ 1.0 = slower than real-time).
    /// `*_latency_absolute_warn_ms`: latency at or above this is too
    /// slow to feel responsive.
    #[serde(default = "default_rtf_absolute_warn")]
    pub rtf_absolute_warn: f64,
    #[serde(default = "default_latency_absolute_warn_ms")]
    pub asr_latency_absolute_warn_ms: f64,
    #[serde(default = "default_latency_absolute_warn_ms")]
    pub e2e_latency_absolute_warn_ms: f64,
}

fn default_rtf_warn() -> f64 {
    0.50
}
fn default_rtf_fail() -> f64 {
    1.50
}
fn default_rtf_absolute_warn() -> f64 {
    1.00
}
fn default_latency_absolute_warn_ms() -> f64 {
    1000.0
}

impl Default for Tolerances {
    fn default() -> Self {
        // Tightened post-launch (PR #9) after four successful CI runs
        // confirmed the original (very generous) tolerances always
        // landed comfortably inside the warning band. The new values
        // halve the relative ranges while keeping enough headroom for
        // expected runner-vs-sandbox variance (1.5–3× on whisper-tiny
        // ASR latency). Absolute thresholds are unchanged because
        // those are anchored to user-perceived dictation quality, not
        // the per-runner baseline.
        Self {
            wer_absolute_warn: 0.03,
            wer_absolute_fail: 0.07,
            wer_relative_warn: 0.10,
            wer_relative_fail: 0.30,
            latency_p50_relative_warn: 0.50, // was 1.00 (2×); now 1.5× → warn
            latency_p50_relative_fail: 1.50, // was 2.00 (3×); now 2.5× → fail
            e2e_latency_p50_relative_warn: 0.30,
            e2e_latency_p50_relative_fail: 1.00,
            rtf_relative_warn: default_rtf_warn(),
            rtf_relative_fail: default_rtf_fail(),
            rtf_absolute_warn: default_rtf_absolute_warn(),
            asr_latency_absolute_warn_ms: default_latency_absolute_warn_ms(),
            e2e_latency_absolute_warn_ms: default_latency_absolute_warn_ms(),
        }
    }
}

impl Baseline {
    pub fn load(path: &Path) -> std::io::Result<Self> {
        let bytes = std::fs::read(path)?;
        serde_json::from_slice(&bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        let bytes = serde_json::to_vec_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, bytes)?;
        Ok(())
    }
}

/// Outcome of comparing a single (language, metric) measurement against
/// the baseline.
#[derive(Debug, Clone, PartialEq)]
pub enum Verdict {
    Pass,
    Warn(String),
    Fail(String),
}

impl Verdict {
    pub fn is_fail(&self) -> bool {
        matches!(self, Verdict::Fail(_))
    }
}

/// Compare one language's measurement to its baseline entry. Returns one
/// `Verdict` per checked metric (wer/cer, asr latency, e2e latency); call
/// sites can summarise.
pub fn check_language(
    measured: &LanguageBaseline,
    baseline: &LanguageBaseline,
    tol: &Tolerances,
) -> Vec<(String, Verdict)> {
    let mut out = Vec::new();

    if let (Some(m), Some(b)) = (measured.wer, baseline.wer) {
        out.push(("wer".to_string(), check_error_rate(m, b, tol)));
    }
    if let (Some(m), Some(b)) = (measured.cer, baseline.cer) {
        out.push(("cer".to_string(), check_error_rate(m, b, tol)));
    }
    out.push((
        "asr_latency_p50_ms".to_string(),
        check_latency(
            measured.asr_latency_ms.p50,
            baseline.asr_latency_ms.p50,
            tol.latency_p50_relative_warn,
            tol.latency_p50_relative_fail,
        ),
    ));
    out.push((
        "e2e_latency_p50_ms".to_string(),
        check_latency(
            measured.e2e_latency_ms.p50,
            baseline.e2e_latency_ms.p50,
            tol.e2e_latency_p50_relative_warn,
            tol.e2e_latency_p50_relative_fail,
        ),
    ));
    if let (Some(m), Some(b)) = (measured.rtf, baseline.rtf) {
        out.push((
            "rtf".to_string(),
            check_latency(m, b, tol.rtf_relative_warn, tol.rtf_relative_fail),
        ));
    }

    // Absolute thresholds — independent of baseline; tied to user-
    // perceived quality so the relative checks can't paper over a
    // genuinely-too-slow run.
    if let Some(m) = measured.rtf {
        out.push((
            "rtf_absolute".to_string(),
            check_absolute_max(m, tol.rtf_absolute_warn, |x| format!("{x:.3}")),
        ));
    }
    out.push((
        "asr_latency_p50_ms_absolute".to_string(),
        check_absolute_max(
            measured.asr_latency_ms.p50,
            tol.asr_latency_absolute_warn_ms,
            |x| format!("{x:.0}ms"),
        ),
    ));
    out.push((
        "e2e_latency_p50_ms_absolute".to_string(),
        check_absolute_max(
            measured.e2e_latency_ms.p50,
            tol.e2e_latency_absolute_warn_ms,
            |x| format!("{x:.0}ms"),
        ),
    ));
    out
}

/// Warns (never fails) when `measured` is at or above `warn_at`.
/// Used for absolute thresholds that exist alongside relative
/// regression checks: the user told us "X is too slow / too high
/// regardless of where the baseline sits", so we surface it as a
/// permanent floor.
fn check_absolute_max(measured: f64, warn_at: f64, fmt: impl Fn(f64) -> String) -> Verdict {
    if measured.is_nan() || warn_at <= 0.0 {
        return Verdict::Pass;
    }
    if measured >= warn_at {
        Verdict::Warn(format!("{}{}", fmt(measured), fmt(warn_at)))
    } else {
        Verdict::Pass
    }
}

fn check_error_rate(measured: f64, baseline: f64, tol: &Tolerances) -> Verdict {
    if measured.is_nan() || baseline.is_nan() {
        return Verdict::Fail(format!(
            "NaN encountered: measured={measured}, baseline={baseline}"
        ));
    }
    let abs_delta = measured - baseline;
    let rel_delta = if baseline > 0.0 {
        abs_delta / baseline
    } else {
        0.0
    };

    if abs_delta >= tol.wer_absolute_fail || rel_delta >= tol.wer_relative_fail {
        Verdict::Fail(format!(
            "{:.4}{:.4}{:+.4}, rel {:+.1}%)",
            baseline,
            measured,
            abs_delta,
            rel_delta * 100.0
        ))
    } else if abs_delta >= tol.wer_absolute_warn || rel_delta >= tol.wer_relative_warn {
        Verdict::Warn(format!(
            "{:.4}{:.4}{:+.4}, rel {:+.1}%)",
            baseline,
            measured,
            abs_delta,
            rel_delta * 100.0
        ))
    } else {
        Verdict::Pass
    }
}

fn check_latency(measured: f64, baseline: f64, warn_rel: f64, fail_rel: f64) -> Verdict {
    if baseline <= 0.0 {
        return Verdict::Pass;
    }
    let rel = (measured - baseline) / baseline;
    if rel >= fail_rel {
        Verdict::Fail(format!(
            "{:.1}ms → {:.1}ms ({:+.1}%)",
            baseline,
            measured,
            rel * 100.0
        ))
    } else if rel >= warn_rel {
        Verdict::Warn(format!(
            "{:.1}ms → {:.1}ms ({:+.1}%)",
            baseline,
            measured,
            rel * 100.0
        ))
    } else {
        Verdict::Pass
    }
}

fn round2(x: f64) -> f64 {
    (x * 100.0).round() / 100.0
}

// ---------------------------------------------------------------------------
// Layer baseline (Phase A-2: ablation + per-layer latency)
// ---------------------------------------------------------------------------

/// Schema for `docs/benchmarks/ci_baseline_layers.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayerBaseline {
    pub schema_version: u32,
    pub generated: String,
    pub languages: BTreeMap<String, LanguageLayerBaseline>,
    pub tolerances: LayerTolerances,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageLayerBaseline {
    pub fixtures: usize,
    /// Mean error rate (WER for en, CER for ja/zh) of the full pipeline,
    /// then with each post-ASR layer disabled in turn. Layer keys are
    /// well-known identifiers: `full`, `without_filler`,
    /// `without_self_correction`, `without_punctuation`. Languages skip
    /// keys when the layer is not configured for them (e.g. zh has no
    /// filter today).
    pub ablation: BTreeMap<String, f64>,
    /// Median + p95 latency for each layer in isolation (μ-benchmark).
    pub layer_latency_us: BTreeMap<String, LatencyMicrosRecord>,
}

/// Per-layer μ-benchmark latency record. Reported in **microseconds**
/// because rule-based layers are sub-millisecond on typical CI runners
/// and millisecond rounding would erase the signal.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct LatencyMicrosRecord {
    pub p50: f64,
    pub p95: f64,
}

impl From<LatencySummary> for LatencyMicrosRecord {
    fn from(s: LatencySummary) -> Self {
        Self {
            p50: round2(s.p50_ms * 1000.0),
            p95: round2(s.p95_ms * 1000.0),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct LayerTolerances {
    /// Absolute ΔWER drift allowed before warning, e.g. 0.02 = +2 abs.
    pub ablation_absolute_warn: f64,
    pub ablation_absolute_fail: f64,
    /// Relative latency drift allowed before warning / failing.
    pub layer_latency_p50_relative_warn: f64,
    pub layer_latency_p50_relative_fail: f64,
    /// Absolute upper bound on per-layer p50 latency, in microseconds.
    /// Defaults to 1 second (1_000_000 μs) — layers are expected to be
    /// sub-millisecond in practice, so this is a sanity floor for
    /// catastrophic regressions, not a tight budget.
    #[serde(default = "default_layer_latency_absolute_warn_us")]
    pub layer_latency_absolute_warn_us: f64,
}

fn default_layer_latency_absolute_warn_us() -> f64 {
    1_000_000.0
}

impl Default for LayerTolerances {
    fn default() -> Self {
        // Ablation is fixture-deterministic, so absolute drift is the
        // operative gate (already tight at ±2%/±5%). Layer μ-benchmark
        // p50 is sub-microsecond and noisy on shared CI runners; we
        // tightened from 2×/4× to 1.5×/3.5× after PR #6/#8 confirmed
        // measurements stay in a narrow band across runs.
        Self {
            ablation_absolute_warn: 0.02,
            ablation_absolute_fail: 0.05,
            layer_latency_p50_relative_warn: 1.50,
            layer_latency_p50_relative_fail: 3.50,
            layer_latency_absolute_warn_us: default_layer_latency_absolute_warn_us(),
        }
    }
}

impl LayerBaseline {
    pub fn load(path: &Path) -> std::io::Result<Self> {
        let bytes = std::fs::read(path)?;
        serde_json::from_slice(&bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        let bytes = serde_json::to_vec_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, bytes)?;
        Ok(())
    }
}

pub fn check_language_layers(
    measured: &LanguageLayerBaseline,
    baseline: &LanguageLayerBaseline,
    tol: &LayerTolerances,
) -> Vec<(String, Verdict)> {
    let mut out = Vec::new();

    for (key, m_val) in &measured.ablation {
        let Some(b_val) = baseline.ablation.get(key) else {
            out.push((
                format!("ablation/{key}"),
                Verdict::Warn(format!("no baseline entry for {key}")),
            ));
            continue;
        };
        let abs_delta = (m_val - b_val).abs();
        let v = if abs_delta >= tol.ablation_absolute_fail {
            Verdict::Fail(format!(
                "{:.4}{:.4} (|Δ| {:.4})",
                b_val, m_val, abs_delta
            ))
        } else if abs_delta >= tol.ablation_absolute_warn {
            Verdict::Warn(format!(
                "{:.4}{:.4} (|Δ| {:.4})",
                b_val, m_val, abs_delta
            ))
        } else {
            Verdict::Pass
        };
        out.push((format!("ablation/{key}"), v));
    }

    for (layer, m_lat) in &measured.layer_latency_us {
        let Some(b_lat) = baseline.layer_latency_us.get(layer) else {
            out.push((
                format!("latency/{layer}"),
                Verdict::Warn(format!("no baseline entry for {layer}")),
            ));
            continue;
        };
        let v = check_latency(
            m_lat.p50,
            b_lat.p50,
            tol.layer_latency_p50_relative_warn,
            tol.layer_latency_p50_relative_fail,
        );
        out.push((format!("latency/{layer}_p50_us"), v));

        // Absolute upper bound — independent of baseline.
        out.push((
            format!("latency/{layer}_p50_us_absolute"),
            check_absolute_max(m_lat.p50, tol.layer_latency_absolute_warn_us, |x| {
                format!("{x:.0}μs")
            }),
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn bl(wer: Option<f64>, cer: Option<f64>) -> LanguageBaseline {
        LanguageBaseline {
            samples: 10,
            wer,
            cer,
            asr_latency_ms: LatencyRecord {
                p50: 100.0,
                p95: 200.0,
            },
            e2e_latency_ms: LatencyRecord {
                p50: 150.0,
                p95: 250.0,
            },
            rtf: Some(0.20),
        }
    }

    #[test]
    fn equal_measurement_passes_all_checks() {
        let baseline = bl(Some(0.20), None);
        let measured = baseline.clone();
        let tol = Tolerances::default();
        let results = check_language(&measured, &baseline, &tol);
        for (name, v) in &results {
            assert_eq!(v, &Verdict::Pass, "{name} expected Pass, got {v:?}");
        }
    }

    #[test]
    fn wer_absolute_regression_warns_then_fails() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        let tol = Tolerances::default();
        // Defaults: warn ≥ +0.03 abs OR ≥ +10% rel; fail ≥ +0.07 abs OR ≥ +30% rel.

        measured.wer = Some(0.24); // +0.04 abs, +20% rel → warn (rel)
        let results = check_language(&measured, &baseline, &tol);
        let wer_v = &results.iter().find(|(k, _)| k == "wer").unwrap().1;
        assert!(matches!(wer_v, Verdict::Warn(_)), "got {wer_v:?}");

        measured.wer = Some(0.28); // +0.08 abs (≥ 0.07) → fail
        let results = check_language(&measured, &baseline, &tol);
        let wer_v = &results.iter().find(|(k, _)| k == "wer").unwrap().1;
        assert!(matches!(wer_v, Verdict::Fail(_)), "got {wer_v:?}");
    }

    #[test]
    fn wer_improvement_is_pass() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        measured.wer = Some(0.10);
        let tol = Tolerances::default();
        let results = check_language(&measured, &baseline, &tol);
        let wer_v = &results.iter().find(|(k, _)| k == "wer").unwrap().1;
        assert_eq!(wer_v, &Verdict::Pass);
    }

    #[test]
    fn latency_regression_classified_correctly() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        let tol = Tolerances::default();
        // Defaults: warn at +50% (1.5×), fail at +150% (2.5×).
        measured.asr_latency_ms.p50 = 200.0; // +100% → warn
        let results = check_language(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "asr_latency_p50_ms")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        measured.asr_latency_ms.p50 = 280.0; // +180% → fail
        let results = check_language(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "asr_latency_p50_ms")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Fail(_)), "got {v:?}");
    }

    #[test]
    fn rtf_regression_classified() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        let tol = Tolerances::default();
        // Defaults: warn at +100% (2× RTF), fail at +200% (3× RTF)
        measured.rtf = Some(0.50); // 0.20 → 0.50, +150% → warn
        let results = check_language(&measured, &baseline, &tol);
        let v = &results.iter().find(|(k, _)| k == "rtf").unwrap().1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        measured.rtf = Some(0.70); // +250% → fail
        let results = check_language(&measured, &baseline, &tol);
        let v = &results.iter().find(|(k, _)| k == "rtf").unwrap().1;
        assert!(matches!(v, Verdict::Fail(_)), "got {v:?}");
    }

    #[test]
    fn rtf_absolute_threshold_warns_at_one() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        let tol = Tolerances::default();
        // RTF baseline is 0.20; bumping to 0.95 still passes both
        // relative (within +200% fail bound from 0.20 → 0.60) and
        // absolute (< 1.0)
        measured.rtf = Some(0.50); // already triggers relative warn
        let results = check_language(&measured, &baseline, &tol);
        let v = &results.iter().find(|(k, _)| k == "rtf_absolute").unwrap().1;
        assert_eq!(v, &Verdict::Pass, "0.50 < 1.0 should be absolute pass");

        // RTF crosses the absolute threshold
        measured.rtf = Some(1.20);
        let results = check_language(&measured, &baseline, &tol);
        let v = &results.iter().find(|(k, _)| k == "rtf_absolute").unwrap().1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");
    }

    #[test]
    fn latency_absolute_threshold_warns_at_one_second() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        let tol = Tolerances::default();

        measured.e2e_latency_ms.p50 = 1500.0;
        let results = check_language(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "e2e_latency_p50_ms_absolute")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        measured.e2e_latency_ms.p50 = 800.0;
        let results = check_language(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "e2e_latency_p50_ms_absolute")
            .unwrap()
            .1;
        assert_eq!(v, &Verdict::Pass);
    }

    #[test]
    fn rtf_missing_skips_check() {
        let baseline = bl(Some(0.20), None);
        let mut measured = baseline.clone();
        measured.rtf = None;
        let tol = Tolerances::default();
        let results = check_language(&measured, &baseline, &tol);
        assert!(results.iter().all(|(k, _)| k != "rtf"));
    }

    #[test]
    fn round_trip_serde() {
        let mut langs = BTreeMap::new();
        langs.insert("en".to_string(), bl(Some(0.20), None));
        langs.insert("ja".to_string(), bl(None, Some(0.30)));
        let b = Baseline {
            schema_version: 1,
            generated: "2026-04-25T00:00:00Z".to_string(),
            asr_model: "ggml-tiny.en.bin".to_string(),
            languages: langs,
            tolerances: Tolerances::default(),
        };
        let json = serde_json::to_string(&b).unwrap();
        let parsed: Baseline = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.languages.len(), 2);
        assert_eq!(parsed.schema_version, 1);
    }

    fn lbl() -> LanguageLayerBaseline {
        let mut ablation = BTreeMap::new();
        ablation.insert("full".to_string(), 0.10);
        ablation.insert("without_filler".to_string(), 0.20);
        let mut layer_latency = BTreeMap::new();
        layer_latency.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 500.0,
                p95: 1000.0,
            },
        );
        LanguageLayerBaseline {
            fixtures: 25,
            ablation,
            layer_latency_us: layer_latency,
        }
    }

    #[test]
    fn layer_ablation_drift_classification() {
        let baseline = lbl();
        let mut measured = baseline.clone();
        let tol = LayerTolerances::default();

        // Same → pass
        let results = check_language_layers(&measured, &baseline, &tol);
        for (k, v) in &results {
            assert_eq!(v, &Verdict::Pass, "{k}: expected pass, got {v:?}");
        }

        // +0.03 absolute drift on `without_filler` → warn (>=0.02, <0.05)
        measured.ablation.insert("without_filler".to_string(), 0.23);
        let results = check_language_layers(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "ablation/without_filler")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        // +0.06 absolute drift → fail (>=0.05)
        measured.ablation.insert("without_filler".to_string(), 0.26);
        let results = check_language_layers(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "ablation/without_filler")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Fail(_)), "got {v:?}");
    }

    #[test]
    fn layer_latency_drift_classification() {
        let baseline = lbl();
        let mut measured = baseline.clone();
        let tol = LayerTolerances::default();

        // Default tolerances: warn 200%, fail 400%
        measured.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 1500.0,
                p95: 1500.0,
            }, // +200% → warn boundary
        );
        let results = check_language_layers(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "latency/filler_p50_us")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        measured.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 3000.0,
                p95: 3000.0,
            }, // +500% → fail
        );
        let results = check_language_layers(&measured, &baseline, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "latency/filler_p50_us")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Fail(_)), "got {v:?}");
    }

    #[test]
    fn layer_latency_absolute_threshold_warns_at_one_second() {
        let baseline = lbl();
        let mut measured = baseline.clone();
        let tol = LayerTolerances::default();

        // Bump filler p50 to 1.5 seconds (absurd, but tests the path).
        // Set baseline match so the relative check stays Pass.
        measured.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 1_500_000.0,
                p95: 1_500_000.0,
            },
        );
        // Match in baseline so the relative check would pass
        let mut bl_match = baseline.clone();
        bl_match.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 1_500_000.0,
                p95: 1_500_000.0,
            },
        );
        let results = check_language_layers(&measured, &bl_match, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "latency/filler_p50_us_absolute")
            .unwrap()
            .1;
        assert!(matches!(v, Verdict::Warn(_)), "got {v:?}");

        // Baseline-matching sub-second filler stays Pass on absolute.
        measured.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 500.0,
                p95: 1000.0,
            },
        );
        bl_match.layer_latency_us.insert(
            "filler".to_string(),
            LatencyMicrosRecord {
                p50: 500.0,
                p95: 1000.0,
            },
        );
        let results = check_language_layers(&measured, &bl_match, &tol);
        let v = &results
            .iter()
            .find(|(k, _)| k == "latency/filler_p50_us_absolute")
            .unwrap()
            .1;
        assert_eq!(v, &Verdict::Pass);
    }

    #[test]
    fn layer_baseline_round_trip_serde() {
        let mut langs = BTreeMap::new();
        langs.insert("en".to_string(), lbl());
        let b = LayerBaseline {
            schema_version: 1,
            generated: "2026-04-25T00:00:00Z".to_string(),
            languages: langs,
            tolerances: LayerTolerances::default(),
        };
        let json = serde_json::to_string(&b).unwrap();
        let parsed: LayerBaseline = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.languages.len(), 1);
    }
}