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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
//! **The word-timing parity gate** (design spec §7 Gate 1, as reframed by
//! issue #12): alignkit's CoreML wav2vec2 encoder against asry's ONNX-Runtime
//! wav2vec2 encoder, compared where a user actually consumes the result —
//! **per-word start/end times and scores** on real speech.
//!
//! # Why the word level, and not the emission tensor
//!
//! The original Gate 1 compared raw emission tensors under a `max-abs ≤ 5e-2 /
//! argmax ≥ 99.9%` bound invented before anything was measured. That bound is
//! physically unreachable for two independently-converted copies of wav2vec2
//! (ours `torchaudio → CoreML`, fp16, 29-class; asry's `HuggingFace → ONNX`,
//! fp32, 32-class) and the one alarming number it produced turned out to be a
//! **harness bug**, not a model disagreement
//! (`.superpowers/sdd/alignkit-gate1-diagnostic.md`). Comparing at the word
//! level deliberately abstracts away the vocab width and the fp16/fp32 tail,
//! neither of which a caller can observe, and measures the thing that ships.
//!
//! asry is the right oracle at that level: it is the SAME forced-alignment
//! algorithm — literally the same `AlignerCore`, reached through the same
//! `prepare` / `finish` — and it is WhisperX-parity-proven. The two code paths
//! differ in exactly one place:
//!
//! ```text
//! asry prepare(samples) → encoder_input → [ ONNX fp32, 32-class ] → finish
//! alignkit prepare(samples) → encoder_input → [ CoreML fp16, 29-class ] → finish
//! ```
//!
//! so a word-timing disagreement can only come from the encoder swap. That is
//! what this gate isolates.
//!
//! # The oracle is not ground truth, and this gate does not pretend it is
//!
//! Measured on `jfk.wav`: the median boundary disagreement is 0.0 ms — the
//! median boundary is frame-identical — and 37 of 44 boundaries agree to within
//! one 20 ms frame. One boundary is not decided by the emissions at all: the
//! second `ask`, which follows a pause the model carries no evidence across. The
//! audio decides it:
//!
//! - A 20 ms RMS envelope of `jfk.wav` puts **silence** across 7460–8180 ms
//! (RMS 0.009–0.037, against 0.2+ for speech).
//! - The acoustic model's own emissions are `logP(blank) == 0.0000` — exactly,
//! fp16-saturated — for all 41 frames from 7560 to 8360 ms. The tensor
//! carries *no information whatsoever* about where a token begins in that
//! run, so a trellis that scores only the run is choosing between numerically
//! identical paths and the tie can fall anywhere. This is not encoder noise;
//! it is an absence of evidence.
//! - The first frame with real evidence is 419 (**8380 ms**), where the model
//! fires `A` with a +6.64 margin over blank. A greedy CTC decode of the whole
//! clip confirms it: `…|FOR|YOU|AND|WHAT|YOU|CAN|…` with `A@8380ms`.
//!
//! The oracle's answer for that onset has moved with asry's lattice while the
//! audio has not: 7,507.3 ms under asry 0.2 (873 ms before the evidence, inside
//! the silence), 7,453.5 ms under asry 0.3.0 (927 ms before it), and 8,395.2 ms
//! under asry 0.3.1, which starts a word after a pause at the first frame the
//! model emits its first character. alignkit's fp16 emissions place it at
//! 8,375.2 ms, 4.8 ms before the acoustic onset; the oracle's answer is 15.2 ms
//! after it. The gate holds the onset to the AUDIO, within one frame
//! ([`ANCHOR_TOLERANCE_MS`] of [`ACOUSTIC_ONSET_OF_ASK_MS`]), and neither to the
//! oracle nor to a distance recorded by number: a recorded distance would have
//! accepted asry 0.3.0's boundary, 927 ms from the evidence, for as long as it
//! stayed there. Beside it stand **robust statistics** (median, p90) and an
//! explicit, pinned **ledger of the gross divergences**
//! ([`JFK_EXPECTED_DIVERGENCES`], empty on this clip). Never a max-delta bound:
//! whichever tie-break boundary is worst decides one.
//!
//! # Two clips, because one of them is padded and the other is not
//!
//! | test | clip | samples | padding CoreML sees | what it isolates |
//! |---|---|---|---|---|
//! | [`word_timings_agree_with_asry_ort_on_jfk`] | `jfk.wav` | 176,000 | **784,000 zeros (81.7%)** | encoder swap **+** fixed-window padding, summed |
//! | [`word_timings_agree_with_asry_ort_on_ted_60`] | `ted_60.wav` | **960,000** | **none** | the encoder swap, **alone** |
//!
//! alignkit's CoreML graph takes a fixed `[1, 960_000]` input, so a short chunk
//! is zero-padded to 60 s before the encoder sees it; asry's ONNX graph is
//! variable-length and sees the buffer as-is. On `jfk.wav` that asymmetry is
//! **most of the input**, and it is not cosmetic — wav2vec2-base group-norms
//! over the whole sequence axis and attends globally with no padding mask, so
//! 49 s of zeros perturb every real frame. Every jfk number is therefore a
//! *sum* of two effects and cannot separate them;
//! [`fixed_window_padding_does_not_explain_the_divergence`] exists solely to
//! bound the second.
//!
//! `ted_60.wav` is **exactly** `ENCODER_WINDOW_SAMPLES`, so `emissions_raw`
//! borrows the buffer and appends nothing: both encoders see the identical
//! 960,000 real samples and the encoder swap is the only difference left. It
//! needs no control, and it is the stronger measurement. It also says something
//! jfk cannot:
//!
//! | | jfk (padded) | **ted_60 (unpadded)** |
//! |---|---|---|
//! | median \|Δ\| | 0.0 ms | **0.0 ms** |
//! | p90 \|Δ\| | 20.1 ms | **0.0 ms** |
//! | boundaries within one frame | 37/44 (84.1%) | **367/370 (99.2%)** |
//!
//! **The median boundary is frame-identical on BOTH clips (0.0 ms): the padding
//! does not move the median.** What the zeros still cost is the *tail* — jfk's
//! p90 is 20.1 ms where ted_60's is 0.0 ms. (An earlier revision of this gate
//! measured jfk's median at 12.8 ms and read it as the padding; it was not. It
//! was alignkit over-counting jfk's emission frames by one — 550 where the
//! wav2vec2 conv stack yields 549 — which, under asry 0.2's effective
//! `n_samples / (T - 1)` frame-to-sample ratio (its compose.rs:71), put
//! 176,000/549 = 320.582878 samples/frame against the oracle's
//! 176,000/548 = 321.167883 and skewed every boundary, exactly the truncation
//! off-by-one [`MAX_MEDIAN_BOUNDARY_DELTA_MS`] exists to catch. ted_60 was
//! already correct
//! at 2,999 frames, so it never showed the skew; correcting the truncation drops
//! jfk's median to ted_60's 0.0, with the zeros' real cost left in the p90 tail.)
//!
//! ted_60 also runs what jfk leaves cold: the full 2,999-frame emission tensor
//! instead of 549, a trellis over 185 words instead of 22, and real
//! disfluencies — the speaker says `would` twice and stammers `then`, and the
//! ASR transcript names each once — which is exactly where a forced aligner has
//! to guess. Under asry 0.3.1 both aligners end `would` on the second
//! realisation, within a frame of the audio
//! ([`ACOUSTIC_OFFSET_OF_SECOND_WOULD_MS`]), and part across the stammered
//! `then` ([`TED_60_EXPECTED_DIVERGENCES`]).
//!
//! # What "same input" means here
//!
//! Both aligners receive the **same decoded `Vec<f32>`, by reference**, the
//! same transcript, the same `EnglishNormalizer`, the same OOV policy
//! (`default_oov_policy`), the same whole-chunk speech span, the same
//! 320-sample stride, and the same coverage / silent-run defaults. Buffer
//! identity holds by construction; [`common::JFK_SAMPLES_SHA256`] and
//! [`common::TED_60_SAMPLES_SHA256`] additionally pin the fixtures, because the
//! first attempt at this comparison reported an "86.6% divergence" that was
//! really one side being handed a padded buffer and the other an unpadded one.
//! A parity number measured on two different inputs measures the harness.
//!
//! # This test does not skip
//!
//! `#[ignore]` is the opt-in gate and the only gate; `required-features =
//! ["align-oracle"]` (see `Cargo.toml`) keeps ort out of the default test
//! build. A missing model, tokenizer or fixture is a hard `.expect()` failure,
//! never an early `return`. A model-gated test that silently returns and still
//! prints `ok` is a fake gate — that exact bug shipped in asry's CI and in
//! this crate's own `tests/align_chunk.rs`, where an empty models directory
//! reported `test result: ok. 1 passed` having aligned nothing.
//!
//! # Running it
//!
//! ```text
//! cargo test -p coremlit --features align-oracle -- --ignored
//! ```
//!
//! Needs `Models/alignkit/` (or `ALIGNKIT_TEST_MODELS`), asry's ONNX oracle in
//! its `models/` directory (or `ALIGNKIT_ASRY_MODELS`), and — because `ort`
//! runs in `load-dynamic` mode — `libonnxruntime.dylib` on the loader path.
use AtomicBool;
use ;
use Aligner as OrtAligner;
use ;
/// 16 kHz: 16 samples per millisecond. Word PTS are 16 kHz sample indices
/// (both aligners are anchored at stream sample 0 in [`ANALYSIS_TIMEBASE`]),
/// so this is the only conversion the comparison needs.
const SAMPLES_PER_MS: f64 = 16.0;
/// One encoder frame in milliseconds, at the model's **nominal** stride:
/// `HOP_SAMPLES` (320) @ 16 kHz. **The quantum of this entire measurement.** A
/// CTC trellis backtrack yields a frame index per token, so the smallest
/// disagreement either aligner can express is one frame.
///
/// 20 ms is the *nominal* hop; the *effective* frame asry 0.3 places boundaries
/// on is `n_samples / T`, `T` frames over the chunk's `n` real samples —
/// 176,000/549 = 320.582878 samples ≈ 20.04 ms on jfk, 960,000/2999 =
/// 320.106702 samples ≈ 20.01 ms on ted_60 — so one frame is ≈ 20 ms, within
/// ~0.1 ms of the nominal. The bounds below are set in the nominal 20 ms and
/// carry that ~0.1 ms slack knowingly.
const FRAME_MS: f64 = 20.0;
/// Largest tolerated **median** boundary disagreement: **one frame**.
///
/// The bound on *systematic* shift: a defect that moves every word — an
/// off-by-one in the emissions truncation (which shifts the grid asry maps
/// frames on, as the module header's note shows), a mis-anchored clock — moves
/// the median, however small each individual shift is. A worst-case bound
/// cannot see any of that. (The seam hop is NOT such a defect: asry maps frames
/// by their count over the chunk's real samples, `n_samples / T`, not by the
/// hop.)
///
/// Measured: **0.0 ms** — the median boundary is frame-identical. (An earlier
/// revision measured 12.8 ms; that WAS the "off-by-one in the emissions
/// truncation" this bound names — alignkit over-counted jfk's frames by one, 550
/// where the wav2vec2 conv stack yields 549 — and correcting the truncation drove
/// it to 0.0.)
///
/// It is **not** the bound that catches the ANE corruption, and this is recorded
/// rather than assumed because it was measured: the median barely moves under
/// corruption (a pre-truncation-fix run measured a 12.8 → 16.7 ms correct/corrupt
/// split), staying inside this bound. What refuses the ANE corruption is the
/// encoder's sentinel band (see [`JFK_EXPECTED_DIVERGENCES`]). Do not "simplify"
/// the gate down to this bound.
const MAX_MEDIAN_BOUNDARY_DELTA_MS: f64 = FRAME_MS;
/// Largest tolerated **90th-percentile** boundary disagreement: **5 frames**.
///
/// Bounds the bulk of the distribution without being hostage to the
/// information-free outlier ([`JFK_EXPECTED_DIVERGENCES`]). Measured: **20.1 ms**.
///
/// The headroom above that is not slack, it is a *measured floor*: alignkit
/// cannot beat its own fixed-window padding, and
/// [`fixed_window_padding_does_not_explain_the_divergence`] measures the
/// padding's cost — asry-ort against **itself**, ONNX both times, nothing but
/// the zeros changing — at a p90 in this same band. A bound tighter than the
/// padding's own contribution would be demanding that alignkit outperform its
/// model's input shape.
const MAX_P90_BOUNDARY_DELTA_MS: f64 = 5.0 * FRAME_MS;
/// A boundary disagreement above this is "gross": no longer explicable as
/// encoder precision or as fixed-window padding, and therefore something that
/// must be *named* in [`JFK_EXPECTED_DIVERGENCES`] rather than absorbed by a
/// tolerance.
///
/// **150 ms = 7.5 frames.** It sits above the worst *acoustically anchored*
/// disagreement measured anywhere on this fixture (60.1 ms under asry 0.3.1, on
/// the first `ask`'s end; 80.2 ms under 0.3.0 and 91.1 ms under 0.2, both on
/// `country`) with 1.6× of room or more, and far below the 881.6 ms by which
/// the ANE's corrupted emissions displaced `ask` in the pre-truncation-fix
/// measurement. It is a
/// classifier, not a tolerance — nothing passes merely by coming in under it.
const GROSS_DELTA_MS: f64 = 150.0;
/// **The ledger.** Every boundary that diverges from the oracle by more than
/// [`GROSS_DELTA_MS`], named — an `assert_eq!` on the set, so it is pinned in
/// **both** directions.
///
/// `(word index, boundary)`. **Empty under asry 0.3.** Under 0.2 it held the
/// second `ask`'s ONSET (word 14 of 22), which alignkit's fp16 emissions placed
/// on the acoustic evidence and the oracle 873 ms before it. asry 0.3.0 broke
/// that tie, across 41 frames of fp16-saturated blank, the oracle's way for both
/// encoders (7,453.5 ms); asry 0.3.1 starts a word after a pause at the first
/// frame the model emits its first character, and both encoders put the onset
/// within a frame of the evidence. The audio referee holds it there
/// ([`ACOUSTIC_ONSET_OF_ASK_MS`]). See the module doc for the acoustic proof.
///
/// # Why a ledger and not a max-delta bound
///
/// Because under asry 0.2 a max-delta bound here was not merely weak, it was
/// **inverted** — measured, not argued. Mutating
/// [`coremlit::audio::align::encode::DEFAULT_ENCODER_COMPUTE`]
/// to `ComputeUnits::All` (the ANE placement, whose fp16 `log(softmax)` tail
/// saturates 16.7% of emission cells to a `-45440` sentinel) gave — a
/// pre-truncation-fix measurement, whose exact ms shifted with the fix (the
/// correct-path median is now 0.0 ms, max 923.4 ms), though the inversion and the
/// vanishing ledger entry it demonstrates did not:
///
/// | | correct (`CpuOnly`) | **corrupted (`All`)** |
/// |---|---|---|
/// | max \|Δ\| vs oracle | 908.0 ms | **87.1 ms** |
/// | median \|Δ\| | 12.8 ms | 16.7 ms |
/// | boundaries within 1 frame | 38/44 | 32/44 |
/// | gross divergences | `[(14, Start)]` | **`[]`** |
///
/// The corruption makes alignkit agree **better** with the oracle on every
/// worst-case statistic, because it destroys the fp16-saturated blank plateau
/// that was anchoring the `ask` onset to the real acoustic evidence, and lets
/// the trellis drift early into the silence — to 7533.7 ms, right next to the
/// oracle's own wrong 7507.3 ms. A `max |Δ| <= 100 ms` gate would have **passed
/// the corrupted build and failed the correct one.**
///
/// So the ledger pins the divergence set by identity: a **new** divergence fails
/// (a fresh defect), and so does the disappearance of a pinned one. Under asry
/// 0.3 the shipping placement agrees with the oracle at `ask` too, so the
/// ledger alone no longer tells the ANE path from the shipping one there; the
/// audio referee still measures that boundary ([`ACOUSTIC_ONSET_OF_ASK_MS`]), and the
/// corruption is refused where it arises, by the encoder's sentinel band
/// (`encode::tests::emissions_reject_an_ane_corrupted_matrix`).
const JFK_EXPECTED_DIVERGENCES: & = &;
/// The true acoustic onset of the second `ask`, in ms: **8380**, frame 419.
///
/// Where the oracle cannot be trusted, the gate falls back to something that
/// can — the audio. This is the first frame at which the acoustic model's
/// posterior leaves its fp16-saturated blank plateau (`logP(blank) == 0.0000`
/// for all 41 frames from 7560 ms to 8360 ms) and fires a letter, `A`, with a
/// +6.64 log-prob margin over blank. It is corroborated independently by the
/// signal itself: a 20 ms RMS envelope shows silence (RMS ≤ 0.037) through
/// 8180 ms and speech (RMS 0.2+) after it.
///
/// The referee has not moved: this is the onset the gate has always measured
/// alignkit against. What moved is the oracle — under asry 0.2 alignkit sat
/// +50.7 ms from this onset and the oracle 873 ms before it; under asry 0.3.0
/// both sat 927 ms before it; under asry 0.3.1 alignkit sits 4.8 ms before it
/// and the oracle 15.2 ms after.
const ACOUSTIC_ONSET_OF_ASK_MS: f64 = 8380.0;
/// How far an audio-refereed anchor ([`ACOUSTIC_ONSET_OF_ASK_MS`],
/// [`ACOUSTIC_OFFSET_OF_SECOND_WOULD_MS`]) may sit from the acoustic evidence:
/// **one frame**, the quantum of the measurement.
///
/// An anchor is judged by its distance from the audio and by nothing else: not
/// by the oracle's answer, which has moved with asry's lattice, and not by a
/// distance recorded by number, which would have accepted asry 0.3.0's `ask` for
/// as long as it stayed 927 ms from its onset.
const ANCHOR_TOLERANCE_MS: f64 = FRAME_MS;
/// Largest tolerated **median** per-word score disagreement: `0.10`.
///
/// Scores are the mean per-frame posterior along the word's path, so unlike a
/// frame index they are a *continuous* function of the emission values and
/// cannot be expected to agree closely across an fp16/fp32, 29-vs-32-class
/// encoder swap: the measured per-word spread runs from 0.0008 to 0.2468, with
/// a median of **0.0262** (0.0902 under asry 0.3.0, 0.0838 under asry 0.2; asry
/// 0.3.1 counts a word's held frames at its token's probability, not the
/// blank's). The maximum is deliberately NOT bounded: a word whose span a
/// tie-break decides restates the timing there, not independent evidence.
///
/// This bounds a **systematic confidence regression** and nothing else. It does
/// NOT catch the ANE corruption — measured under asry 0.2, not assumed: on the
/// corrupted path the median score delta *falls*, to 0.0465, for the same reason its timing
/// statistics improve (it converges on the oracle's wrong answer). Keeping a
/// bound honest about what it cannot see is the point of writing this down.
const MAX_MEDIAN_SCORE_DELTA: f32 = 0.10;
/// Largest tolerated boundary movement when the ORACLE's OWN input is
/// zero-padded to alignkit's fixed window: **5 frames** at p90.
/// [`fixed_window_padding_does_not_explain_the_divergence`] measures it.
const MAX_PADDING_P90_DELTA_MS: f64 = 5.0 * FRAME_MS;
// =========================================================================
// ted_60 — the UNPADDED clip. Its own bounds, because they are properties of
// its audio, not of the harness.
//
// Why the numbers below are so much tighter than jfk's: with the padding gone
// (`ted_60.wav` is exactly ENCODER_WINDOW_SAMPLES, so `emissions_raw` borrows
// the buffer and appends no zeros), the ONLY difference left between the two
// pipelines is the encoder itself — CoreML fp16 29-class against ONNX fp32
// 32-class. jfk cannot separate those two effects; it can only measure their
// sum. ted_60 measures the encoder swap ALONE, and the answer is that the two
// encoders put **90%+ of all word boundaries on exactly the same frame**:
//
// | | jfk (padded 81.7%) | ted_60 (unpadded) |
// |--------------------|--------------------|-------------------|
// | median |Δ| | 0.0 ms | **0.0 ms** |
// | p90 |Δ| | 20.1 ms | **0.0 ms** |
// | within one frame | 37/44 (84.1%) | **367/370 (99.2%)** |
//
// That is the affirmative result of this fixture. The MEDIAN is frame-identical
// on both clips (0.0 ms) — the padding does not move it; what the padding costs
// jfk is the TAIL (p90 20.1 ms vs ted_60's 0.0). An earlier revision read jfk's
// then-12.8 ms median as the zero-padding, but it was alignkit over-counting
// jfk's frames by one (550 vs 549); correcting the emissions truncation dropped
// jfk's median to ted_60's 0.0.
// =========================================================================
/// ted_60's largest tolerated **median** boundary disagreement: **one frame**.
/// Measured: **0.0 ms** — the median boundary is frame-IDENTICAL.
///
/// Bounds systematic shift (an off-by-one in the emissions truncation, a
/// mis-anchored clock), exactly as its jfk counterpart does.
///
/// It does **not** catch the ANE corruption, and that is measured, not
/// assumed: under asry 0.2 the corrupted path's median was *also* 0.0 ms. The
/// encoder's sentinel band refuses it (see [`JFK_EXPECTED_DIVERGENCES`]).
const MAX_TED_60_MEDIAN_BOUNDARY_DELTA_MS: f64 = FRAME_MS;
/// ted_60's largest tolerated **90th-percentile** boundary disagreement: **one
/// frame**. Measured: **0.0 ms**.
///
/// Five times tighter than jfk's `MAX_P90_BOUNDARY_DELTA_MS` (5 frames), and
/// the gap is the whole point of this clip. jfk's p90 headroom is a *measured
/// floor* imposed by its zero-padding — the control test shows the padding
/// alone costs p90 25.3 ms under asry 0.3.1 (an earlier revision measured 80.9
/// ms), and alignkit cannot beat its own model's input shape. Remove the
/// padding and that floor disappears: on ted_60 at least 90% of the 370
/// boundaries land on the **same frame**, so one frame of headroom over a
/// measured 0.0 ms is the honest bound.
///
/// Also does **not** catch the ANE (corrupted p90 is likewise 0.0 ms).
const MAX_TED_60_P90_BOUNDARY_DELTA_MS: f64 = FRAME_MS;
/// **ted_60's ledger.** The gross (> [`GROSS_DELTA_MS`]) divergences, an
/// `assert_eq!` on the set, so it is pinned in **both** directions: the end of
/// word 92, `then` (after `but`), and the start of word 93, `actually`.
///
/// # The stammered `then`
///
/// The speaker stammers between `then` and `actually` — "but then… actually the
/// paper would come along" — and the ASR transcript names `then` once (see
/// [`common::TED_60_TRANSCRIPT`], which names this kind of spot in advance as a
/// place the trellis can diverge). The audio, in ms, by a 20 ms RMS envelope of
/// the clip and by alignkit's own emissions:
///
/// - `then` is loud over 30,080–30,240 (RMS up to 0.27); the greedy decode reads
/// `THEN` at 30,070–30,170 and a word delimiter at 30,270.1.
/// - Speech continues over 30,300–30,680 (RMS up to 0.16, dipping to 0.025 at
/// 30,440 and 0.051 at 30,600). The emissions carry two further `T`-`H`-`E`-`N`
/// runs there, each letter the best non-blank candidate of its frame
/// (30,290–30,390: `T` −0.89, `H` −1.02, `E` −1.50, `N` −2.29; 30,450–30,530:
/// `T` −1.00, `H` −1.50, `E` −1.14, `N` −0.73), of which the greedy decode keeps
/// only the `N`.
/// - A silent run follows, 30,720–30,780 (RMS ≤ 0.019).
/// - `actually` begins at 30,800 (RMS 0.088, then 0.156) and peaks at 30,900
/// (0.27).
///
/// The aligners must put one `then` and an `actually` around that. alignkit ends
/// `then` after its first realisation (30,270.1, the delimiter) and enters
/// `actually` at 30,690.2, where its emissions give `A` −0.79, tied with blank,
/// inside the stammer. The oracle ends `then` at 30,750.3, inside the silent run,
/// and enters `actually` at 30,890.2, the first frame after the silent run on
/// which alignkit's emissions give `A` any weight (−1.07, behind `U` at −0.53).
/// The boundaries part by −480.2 and −200.1 ms. Neither start is within a frame
/// of the audio's 30,800 (alignkit −109.8, the oracle +90.2), so unlike `ask` and
/// `would` the audio does not referee this one: the transcript has no word for
/// what the speaker said there, and the lattice breaks the tie.
///
/// # The one-letter words under asry 0.3.0
///
/// The ledger held both ends of word 83, `I` (after `plan.`), and of word 122,
/// `a` (after `thesis,`): each a word one frame long after a pause, which
/// alignkit's fp16 head put right after the previous word and the oracle's fp32
/// head about 560 ms later (`I`: 26,988.9 against 27,529.1 ms; `a`: 43,034.3
/// against 43,594.5 ms). asry 0.3.1 starts a word after a pause at its first
/// spoken frame, and the two aligners now agree on both to the millisecond.
///
/// # The `would` the ledger held under asry 0.2
///
/// The speaker says `would` **twice** — "the paper would… would come along" —
/// a disfluency the ASR transcript elides (see [`common::TED_60_TRANSCRIPT`],
/// which names this spot in advance as a place the trellis can diverge). One
/// transcript word, two acoustic realisations, and a 100 ms fp16-saturated
/// blank plateau between them: the trellis has to pick. Under asry 0.2 the two
/// aligners picked differently; asry 0.3.0 had both pick the first realisation;
/// asry 0.3.1 has both pick the second, which the audio referee holds them to
/// ([`ACOUSTIC_OFFSET_OF_SECOND_WOULD_MS`]):
///
/// | | `would`.end |
/// |---|---|
/// | alignkit (`CpuOnly`, shipping), asry 0.2 | 31,981.3 ms |
/// | asry-ort (the oracle), asry 0.2 | 31,741.2 ms |
/// | alignkit (`ComputeUnits::All`, ANE-corrupt), asry 0.2 | 31,741.2 ms — the oracle's value, exactly |
/// | alignkit and the oracle, asry 0.3.0 | 31,710.6 ms, both |
/// | alignkit and the oracle, asry 0.3.1 | **31,950.7 ms**, both |
///
/// Three independent readings of the audio say the second realisation is real
/// speech, and the word ends there:
///
/// 1. A **greedy CTC decode** of alignkit's own emissions reads `WOULD` at
/// 31,560–31,680 ms and a **second** `WOULD` at 31,820–**31,940** ms.
/// 2. A **verbatim forced alignment** — the same clip with `would would` in
/// the transcript — places those two words at 31,601.1–31,741.2 and
/// 31,861.2–**31,981.3** ms, with scores 0.758 and 0.664. The second
/// realisation is real, confident speech.
/// 3. The **RMS envelope** has no silent run anywhere in 28,400–33,720 ms, so
/// 31,820–31,940 ms carries speech energy, not silence.
///
/// An answer at the FIRST `would`'s offset therefore assigns a 120 ms,
/// confidently-decoded `WOULD` to **blank** — contradicted by the posterior.
/// asry 0.3.0 gave that answer for both aligners; under asry 0.2 alignkit's
/// answer, and under 0.3.1 both aligners', span the word's full acoustic
/// support.
///
/// # Why a ledger and not a max-delta bound — measured on THIS clip
///
/// Because under asry 0.2 a max-delta bound here was not merely weak, it was
/// **inverted**, and more starkly than on jfk. Mutating
/// [`coremlit::audio::align::encode::DEFAULT_ENCODER_COMPUTE`] to
/// `ComputeUnits::All`:
///
/// | | correct (`CpuOnly`) | **corrupted (`All`)** |
/// |---|---|---|
/// | max \|Δ\| vs oracle | 240.1 ms | **20.1 ms** |
/// | median \|Δ\| | 0.0 ms | 0.0 ms |
/// | p90 \|Δ\| | 0.0 ms | 0.0 ms |
/// | boundaries within 1 frame | 367/372 | **369/372** |
/// | median \|Δscore\| | 0.0134 | **0.0076** |
/// | gross divergences | `[(96, End)]` | **`[]`** |
///
/// **Every agreement statistic IMPROVES under corruption.** max, within-one-frame
/// and score-delta all move the *wrong* way; median and p90 cannot see it at
/// all. The corruption destroys the blank plateau that was anchoring `would`
/// to its second realisation and lets the trellis collapse onto the oracle's
/// answer — to the exact millisecond.
///
/// So the ledger pins the divergence set by identity: a **new** divergence
/// fails (a fresh defect), and so does the disappearance of a pinned one. The
/// ANE corruption is refused by the encoder's sentinel band
/// (`encode::tests::emissions_reject_an_ane_corrupted_matrix`); under asry 0.3
/// the shipping placement agrees with the oracle at `would` too, so the ledger
/// alone no longer tells the two apart there, and the audio referee still
/// measures that boundary ([`ACOUSTIC_OFFSET_OF_SECOND_WOULD_MS`]).
const TED_60_EXPECTED_DIVERGENCES: & =
&;
/// The acoustic offset of the **second** spoken `would`, in ms: **31,940**,
/// frame 1597 — the last frame at which a greedy argmax over alignkit's
/// emissions still reads a letter of `WOULD` before the blank that precedes
/// `come`.
///
/// Deliberately taken from the **greedy argmax**, not from any forced
/// alignment, so the constant is not derived from either trellis. Corroborated
/// independently by the RMS envelope (speech energy, no silent run) and by the
/// verbatim two-`would` alignment (which ends its second `would` at 31,981.3
/// ms, 41 ms later — two frames, the usual CTC offset lag).
///
/// The referee has not moved: this is the offset the gate has always measured
/// alignkit against. What moved is the oracle — under asry 0.2 alignkit sat
/// +41.3 ms from this offset; under asry 0.3.0 both aligners ended `would` at the
/// first realisation, 31,710.6 ms, 229 ms before it; under asry 0.3.1 both end
/// it at 31,950.7 ms, 10.7 ms after it.
const ACOUSTIC_OFFSET_OF_SECOND_WOULD_MS: f64 = 31_940.0;
/// ted_60's largest tolerated **median** per-word score disagreement: `0.05`.
/// Measured: **0.0108** (0.0122 under asry 0.3.0, 0.0134 under asry 0.2) — about
/// 2.4 times tighter than jfk's 0.0262, again because no zero-padding is
/// perturbing the emissions.
///
/// Bounds a **systematic confidence regression**. It does **NOT** catch the
/// ANE — measured under asry 0.2: the corrupted median score delta *falls* to 0.0076, for the
/// same reason its timing statistics improve. Recorded so nobody mistakes it
/// for a safety net.
const MAX_TED_60_MEDIAN_SCORE_DELTA: f32 = 0.05;
/// Which end of a word a delta belongs to. Named, because
/// [`JFK_EXPECTED_DIVERGENCES`] pins divergences by identity and "word 14" alone
/// would not say whether it is the onset (which is what the oracle gets wrong)
/// or the offset (which it does not).
/// Word PTS as `(start_ms, end_ms)`. Both aligners are built with a clock
/// anchored at stream sample 0 in [`ANALYSIS_TIMEBASE`], so a PTS **is** a
/// 16 kHz sample index.
/// One clip's measured alignkit-vs-oracle comparison.
///
/// Built by [`compare`], which owns every mechanic the two clips share — the
/// tokenization-identity and word-sequence preconditions, the per-word delta
/// table, the robust statistics, and the gross-divergence classification. The
/// per-clip *bounds* deliberately do NOT live here: they are properties of the
/// audio, not of the harness, and each one is justified against its own clip's
/// measurements at its own call site.
///
/// # There is deliberately no `max` field
///
/// [`compare`] computes and PRINTS the maximum boundary delta, because it is
/// the first thing a human wants when a bound trips — but it does not hand one
/// back, because **a max-delta bound is the single trap this gate exists to
/// avoid**. Under asry 0.2 the maximum moved the *wrong way* on both clips
/// under the ANE corruption (jfk 908.0 → 87.1 ms; ted_60 240.1 → 20.1 ms), so
/// any assertion built on it would have passed the corrupt build and failed the
/// correct one, and whichever tie-break boundary is worst decides it. The gross
/// boundaries are named in a ledger ([`JFK_EXPECTED_DIVERGENCES`],
/// [`TED_60_EXPECTED_DIVERGENCES`]) instead. Not offering the number is the
/// cheapest way to stop someone reaching for it.
/// Runs both aligners on one clip, asserts the two preconditions that make a
/// per-word delta meaningful at all, and reduces the result to [`Comparison`].
///
/// The preconditions are asserted *here*, once, for both clips: identical OOV
/// event streams (the two heads carry different vocabularies — 29-class chordai
/// vs 32-class HuggingFace — so an equal transcript is not by itself proof that
/// equal TOKENS reach the two trellises) and identical word sequences (different
/// words means there is no per-word delta to take).
/// Nearest-rank percentile over an already-sorted slice. `p` in `[0, 1]`.
/// Loads alignkit's aligner on the shipping defaults.
///
/// `Aligner::from_paths` → `AlignerOptions::new()` → `DEFAULT_ENCODER_COMPUTE`.
/// **Never a hardcoded compute placement**: a gate pinned to a compute unit
/// proves only that compute unit, and this crate's default *is* the thing under
/// test — the previous default (`ComputeUnits::All`) silently corrupted every
/// emission tensor while every model-gated test, each pinned to `CpuOnly`,
/// stayed green.
/// Fails loudly, and fast, if `ort` will not be able to load ONNX Runtime —
/// before the parity gate spends ~400 MB of model loads finding out, and never
/// by hanging.
///
/// # Why a subprocess, and why REAL `ort` init inside it
///
/// `ort` runs in `load-dynamic` mode: it resolves `libonnxruntime.dylib` at
/// *runtime*, not link time, and whatever first touches its API runs the load.
/// How a failed load surfaces depends on the `ort` version, which is asry's
/// (`asry` re-exports it under `alignment` and pins it exactly):
///
/// - `ort` 2.0.0-rc.12 (asry 0.1) **deadlocked**. It built its load-failure error
/// through `ort::api()`, the `OnceLock` that was running the load, so
/// constructing the error re-entered that `Once` from the same thread and
/// parked forever — every load failure hung.
/// - `ort` 2.0.0-rc.13 (asry 0.2 and 0.3, today's) **panics**: `load_dynamic::init`
/// returns a typed `LoadError` without touching the API, and `setup_api`
/// answers it with `expect("Failed to load ONNX Runtime dylib")`
/// (`ort-2.0.0-rc.13/src/lib.rs:234`). Measured: a text file at
/// `ORT_DYLIB_PATH` fails in well under a second
/// ([`preflight_fails_fast_on_a_decoy_ort_dylib`]); a real dylib loads in
/// ~160 ms.
///
/// Probing in a child covers both: a failure that exits (rc.13's panic) comes
/// back as the child's status and `ort`'s own message, and a load that never
/// returns — rc.12's deadlock, or a `dlopen` that blocks — is killed at
/// [`PREFLIGHT_TIMEOUT`] ([`preflight_kills_an_ort_init_that_hangs`]).
///
/// # The preflight IS `ort`'s loader, by construction
///
/// Earlier revisions hand-modelled `ort`'s loader in the child — `dlopen`, then
/// `OrtGetApiBase`, then `GetApi`, then the executable-adjacent path precedence,
/// then the `GetVersionString` ordering — and each review found the mirror one
/// layer shallower than the real thing. This models nothing: the child re-execs
/// this test binary and calls **`asry::ort::api()`**, the real entry point every
/// `ort` API funnels through (`ort-2.0.0-rc.13/src/lib.rs:201`). That single call
/// runs the *authoritative* sequence — `ORT_DYLIB_PATH` selection (`lib.rs:224`),
/// executable-adjacent precedence for a relative path (`lib.rs:134`), the real
/// `dlopen` (`lib.rs:136`), `OrtGetApiBase`, `GetVersionString` plus the
/// minor-version compatibility check (`lib.rs:146`), and finally
/// `GetApi(ORT_API_VERSION)` (`lib.rs:246`). Selection precedence, version
/// negotiation and API resolution are therefore whatever `ort` itself does, with
/// nothing left to drift out of sync.
///
/// The child **inherits** this process's `ORT_DYLIB_PATH` (it does not re-select
/// it), so it probes the exact library the in-process `ort` will load. On success
/// (`exit 0`) the real session build in [`load_asry_ort`] cannot then hit a load
/// failure; on a failure or a hang, this actionable panic says what to install.
/// The wall-clock the real preflight allows `ort`'s init before declaring it
/// hung and killing the child: **30 s**. A good `asry::ort::api()` is
/// sub-second (~160 ms measured), so this only bounds a genuine hang.
const PREFLIGHT_TIMEOUT: Duration = from_secs;
/// Env var that switches [`ort_preflight_init_child`] out of its no-op mode into
/// calling REAL `ort` init. Set only on the child's environment by
/// [`probe_ort_init`]; absent in an ordinary run, where the child test is a
/// passing no-op.
const ORT_PREFLIGHT_CHILD_ENV: &str = "ALIGNKIT_ORT_PREFLIGHT_INIT";
/// Run REAL `ort` initialization in a killable child and report whether it
/// succeeds. `Ok(())` iff the child called `asry::ort::api()` and it returned —
/// the dylib loaded, its version was accepted, and `GetApi` yielded an `OrtApi`.
/// `Err` if the child exited non-zero (surfacing its stderr verbatim — how
/// `ort` rc.13 reports an unusable runtime) or did not return within `timeout`,
/// i.e. the load hung and this poll loop killed it.
///
/// `ort_dylib_path`: `None` inherits this process's `ORT_DYLIB_PATH`, which is
/// what the real preflight wants (probe what the in-process `ort` will load);
/// `Some(p)` overrides it on the CHILD only, which is what the containment tests
/// want (point the child at a decoy). The override is applied to the child's
/// environment, never this process's — `std::env::set_var` is racy and its safety
/// cannot be guaranteed here.
///
/// The timeout is a poll loop over [`std::process::Child::try_wait`] — no extra
/// dependency — that kills the child if it overruns. The real preflight passes
/// [`PREFLIGHT_TIMEOUT`]; the containment tests pass a short bound, because the
/// property under test is that a hang is KILLED, not the specific 30 s value.
/// The child half of [`probe_ort_init`], re-exec'd by it with
/// [`ORT_PREFLIGHT_CHILD_ENV`] set: it calls **`asry::ort::api()`** — the real
/// `ort` load + version + `GetApi` sequence (`ort-2.0.0-rc.13/src/lib.rs:201`) —
/// and exits 0 if it returns. An unusable runtime panics `ort` here (see
/// [`assert_onnxruntime_is_resolvable`]), which exits non-zero through libtest
/// with `ort`'s message on stderr; a load that never returns is killed by the
/// parent. Absent the env var — i.e. in any ordinary `--ignored` run — it is a
/// passing no-op.
/// Short, but far above a good init's ~160 ms: a probe still running at this
/// bound genuinely hung rather than being slow.
const CONTAINMENT_TIMEOUT: Duration = from_secs;
/// A decoy `libonnxruntime.dylib` in a fresh temporary directory, spelled
/// exactly like the thing it stands in for, made by `make` at the path.
/// **The fail-fast proof.** A path that exists but is not a loadable ONNX
/// Runtime — a text file named `libonnxruntime.dylib` — makes REAL `ort` init
/// panic (`ort` rc.13: `Failed to load ONNX Runtime dylib`), and the preflight
/// must report exactly that, carrying `ort`'s own message, well inside the
/// timeout rather than at it.
///
/// It is the negative half of the gate — its positive half is
/// [`preflight_accepts_a_real_onnxruntime`] and the parity tests' own preflight
/// succeeding — and it is the standing proof that **existence is not
/// loadability**: the decoy is a real `is_file()`, so it would pass any existence
/// check, yet `ort` cannot load it. Hermetic (a text file in a temp dir; no ONNX
/// Runtime, no models) and NOT `#[ignore]`, so it runs wherever `align-oracle`
/// builds.
/// **The containment proof.** A load that never returns — `ort` rc.12's
/// deadlock, or a `dlopen` that blocks — must be KILLED at the bound, never
/// waited on. A FIFO named `libonnxruntime.dylib` is that load, and needs no
/// `ort` bug to be one: `dlopen` opens the path and blocks until a writer
/// appears, which never happens (measured: blocked until killed). So
/// [`probe_ort_init`]'s poll loop must kill the child and return the timeout
/// error, promptly. Hermetic and NOT `#[ignore]`, like the fail-fast proof.
/// **The preflight's good path, in isolation.** With a real ONNX Runtime on the
/// loader path, [`assert_onnxruntime_is_resolvable`] must PASS quickly — the
/// child's `asry::ort::api()` returns and exits 0. Kept separate from the parity
/// tests (which also exercise it, but only after loading ~400 MB of models and a
/// 60 s clip) so that a broken preflight fails HERE, fast and unambiguously.
/// `#[ignore]` and needs `ORT_DYLIB_PATH` at a real `libonnxruntime.dylib`,
/// exactly like the parity gate it guards.
/// Loads the oracle. Separate from [`align_with_asry_ort`] so the ONNX session
/// (a ~378 MB model) is built once and reused across a test's runs.
/// Runs alignkit's CoreML pipeline. `speech` is passed explicitly rather than
/// as `&[]` so this side and the oracle are spelled the same way — see
/// [`align_with_asry_ort`]'s doc for why an empty slice is a trap.
/// Runs asry's ONNX-Runtime pipeline — the oracle — on its own defaults.
///
/// `Aligner::from_paths` gives hop 320, `SpeechCoverage::DEFAULT` (0.5) and
/// `DEFAULT_MAX_INTRA_SILENT_RUN` (80 ms): the same three knobs alignkit's
/// `AlignerOptions::new()` sets to the same three values, so the two pipelines
/// differ in the encoder and nothing else.
///
/// `align_chunk` (rather than `align_chunk_with_abort`) is deliberate: it
/// applies `default_oov_policy` to its own `detect_oov` output internally —
/// exactly the policy [`align_with_alignkit`] applies — so the OOV path cannot
/// drift between the two sides through a hand-written argument.
///
/// The closure is asry's pre-`OutputClock` bridge; anchoring the chunk at
/// stream sample 0 and emitting [`ANALYSIS_TIMEBASE`] PTS reproduces
/// `OutputClock::new(0, ANALYSIS_TIMEBASE, 0)` exactly (that clock's `range`
/// rescales `ANALYSIS_TIMEBASE → ANALYSIS_TIMEBASE`, the identity, and adds a
/// zero `base_pts`).
/// "No VAD" — one span covering the whole chunk, in the 1/16000 analysis
/// timebase.
///
/// # Why this is spelled out and never `&[]`
///
/// The two front ends disagree about what an empty `sub_segments` slice means,
/// and they disagree in the most dangerous possible direction:
///
/// | call | empty `sub_segments` means |
/// |---|---|
/// | `coremlit::audio::align::Aligner::align_chunk` | `SpeechSpans::all_speech()` — every sample is speech |
/// | `asry::Aligner::align_chunk` | `SpeechSpans::from_time_ranges(&[])` → **no speech at all** |
///
/// asry's own `SpeechSpans` doc calls this out ("mean 'no VAD' and get 'all
/// silence', which dropped every word"), and its `EmissionsAligner` seam exists
/// partly to force the distinction into the type — but the ORT front end still
/// takes the raw slice. Handing `&[]` to the oracle would silence-mask the
/// entire buffer to zeros and then compare alignkit's real alignment against an
/// oracle that had been fed 11 seconds of digital silence: the same class of
/// defect as the padded-vs-unpadded harness bug this gate's fingerprint exists
/// to prevent, and just as quiet — it produces numbers, only meaningless ones.
///
/// One span over `[0, samples.len())` is the faithful translation on both
/// sides: `all_speech()` is `[0, SampleSpan::MAX_SAMPLE)`, which the mask and
/// the frame classifier both clamp to the chunk's real length, so the two are
/// the same mask and the same 1.0 coverage on every word. Spelling it
/// identically for both aligners removes the asymmetry entirely.
/// Decodes the fixture and asserts it is the audio these numbers were measured
/// on.
/// Decodes `ted_60.wav` and asserts **both** things the unpadded half depends
/// on: that it is the audio these numbers were measured on, and that it still
/// fills the encoder window *exactly*.
///
/// The length assertion is not a tautology of the digest — it is the one that
/// says what this fixture is FOR. At exactly [`coremlit::audio::align::encode::ENCODER_WINDOW_SAMPLES`]
/// samples, `Encoder::emissions_raw` borrows the caller's buffer and appends no
/// zeros at all; one sample fewer and it silently takes the zero-fill branch,
/// which would quietly convert this test back into a second copy of the padded
/// jfk case and retire the only coverage the unpadded path has. Spelled out, so
/// that a re-encoded fixture fails HERE, loudly, instead of passing while
/// measuring nothing new.
/// **The gate.** Per-word start/end/score agreement between alignkit (CoreML)
/// and asry (ONNX Runtime) on real speech.
///
/// The fixture is `jfk.wav` — **real speech, and it has to be**. Synthetic input
/// is not merely weaker here, it is actively misleading: measured on the
/// known-corrupt ANE path, 60 s of digital silence bottoms out at `-8.55` and a
/// sine at `-9.07`, both *above* fp16's `log` floor (≈ `-16.6`), so neither
/// underflows and **both pass on a corrupted model**. Only real speech drives a
/// per-class posterior to `e^-30.8 ≈ 4e-14`, under the floor, where the failure
/// this crate ships a `CpuOnly` default to avoid actually lives.
/// **The gate's unpadded half** — the configuration
/// [`word_timings_agree_with_asry_ort_on_jfk`] structurally cannot reach.
///
/// `jfk.wav` is 176,000 samples against a 960,000-sample encoder window, so
/// **81.7% of what CoreML sees is zeros alignkit appended**. Every number that
/// test produces is a sum of two effects — the encoder swap and the padding —
/// and it cannot separate them;
/// `fixed_window_padding_does_not_explain_the_divergence` exists only to bound
/// the second one. `ted_60.wav` is **exactly** 960,000 samples
/// ([`ted_60_samples`] asserts it), so `Encoder::emissions_raw` borrows the
/// caller's buffer and appends **no zeros at all**: both encoders see the
/// identical 960,000 real samples, and the encoder swap is the *only*
/// difference left. This is the stronger comparison, and it needs no control.
///
/// It also runs the parts of the pipeline jfk leaves cold: the full
/// 2,999-frame emission tensor rather than 549 (the conv-geometry
/// `truncated_frame_count` yields the full 2,999 naturally, dropping nothing), a
/// trellis over 186 words rather than 22,
/// and — because the transcript is real ASR output over spontaneous speech — a
/// disfluency the transcript elides, which is exactly where a forced aligner
/// is forced to guess.
/// **The control.** Answers the one question
/// [`word_timings_agree_with_asry_ort_on_jfk`]'s numbers cannot answer on their own:
/// **are jfk's divergences from the oracle caused by alignkit's fixed 60 s
/// window, or by its CoreML conversion?** (Under asry 0.2 the question was a
/// 923 ms `ask` divergence; under 0.3 the two agree at `ask`, and the p90 tail
/// is what is left.)
///
/// alignkit zero-pads an 11 s chunk to 960,000 samples because its CoreML graph
/// takes no other shape; asry's ONNX graph is variable-length and does not. That
/// asymmetry is real, and at the *emission* level it is not small —
/// wav2vec2-base group-norms over the whole sequence axis and attends globally
/// with no padding mask, so on a 3 s slice padding alone moved 13.4% of frame
/// argmaxes and produced a max-abs log-prob difference of 27.17
/// (`.superpowers/sdd/alignkit-gate1-diagnostic.md`). It is the obvious suspect.
///
/// So: run the oracle against **itself** — ONNX both times, same fp32 weights,
/// same transcript, same span, the zeros the only difference. It exonerates the
/// window for `ask`: padded, the oracle still puts its onset at ~8.4 s, within
/// two frames of where it puts it unpadded (8,362.8 ms against 8,395.2 ms, under
/// asry 0.3.1). **The padding does not move that word**, and it bounds what the
/// padding costs the rest.
///
/// # Why onsets only
///
/// Not cherry-picking — a structural difference in what the two sides even
/// compute. alignkit **truncates its emissions** to the real audio's frame count
/// (`floor((176_000 − 400) / 320) + 1 = 549` of 2999) before `finish` ever sees
/// them, so its
/// trellis cannot path a token into the pad. asry's ORT front end fuses encode
/// and finish and offers no seam to truncate at, so its padded trellis runs over
/// all 2999 frames and the FINAL token is free to run out into the zeros — which
/// it does, to ~60 s. (Marking the pad as non-speech instead does not rescue it:
/// the coverage post-pass then simply drops the last word, 22 → 21.) That
/// artifact is a property of *not truncating*, which alignkit does not do; it
/// would answer a different question, and a loud one, drowning out this one.
/// Word ONSETS are unaffected by it and are exactly the quantity the gate's
/// outlier is about.
///
/// The end-blowout is worth stating plainly, because it is the affirmative case
/// for a design decision B3 made and B4 kept: **the emissions truncation is not
/// an optimisation, it is what makes the fixed-window bridge correct at all.**