coremlit 0.1.1

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
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
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Structured error types for `alignkit` (design spec §8). Foreign errors
//! from `coremlit` and `asry` are wrapped as typed `#[from]` variants — no
//! `Box<dyn Error>`, no string blobs.
//!
//! Five enums, matching the spec's construction-vs-per-call split, with the
//! vocabulary a model ships beside it and the statements of its contract read
//! before either:
//!
//! - [`VocabularyError`]: reading a model's own `{token: id}` table into a
//!   [`crate::audio::align::vocab::Vocabulary`].
//! - [`GeometryError`]: stating a front end's
//!   [`crate::audio::align::acoustic::AcousticGeometry`] that asry's seam
//!   cannot time.
//! - [`TokenizationError`]: a model's
//!   [`crate::audio::align::acoustic::Tokenization`] that asry's seam cannot
//!   honour, or that its table or its normalizer contradicts.
//! - [`AlignerError`]: construction-time — loading and contract-validating
//!   the CoreML model ([`AlignerError::Load`],
//!   [`AlignerError::ContractMismatch`]), checking the model's
//!   [`crate::audio::align::acoustic::AcousticContract`] against what it
//!   declares and against its vocabulary ([`AlignerError::FrameCountMismatch`],
//!   [`AlignerError::BlankOutOfVocabulary`]), building asry's alignment seam
//!   from the vocabulary + normalizer ([`AlignerError::Seam`]) and reading back
//!   the columns it reserves ([`AlignerError::ReservedSetMismatch`]), and
//!   pairing the two ([`AlignerError::VocabularyMismatch`]).
//! - [`AlignError`]: per-call — returned by both
//!   `Encoder::emissions` and
//!   [`crate::audio::align::aligner::Aligner::align_chunk`], which sit at the same "one
//!   chunk's worth of work" layer.
//!
//! # A refusal and an unalignable chunk are named, never an empty result
//!
//! Two of the seam's [`asry::emissions::EmissionsError`] variants are
//! per-chunk outcomes rather than a broken setup: `SemanticOutOfVocab` (the
//! caller's OOV decisions resolved a position `FailClosed`) and
//! `NoAlignmentPath` (the CTC lattice admits no path for this chunk's audio and
//! tokens). [`crate::audio::align::aligner::Aligner::align_chunk`] names each:
//! [`AlignError::Refused`] carries every position the caller's policy refused,
//! and [`AlignError::NoAlignmentPath`] carries asry's diagnostic. Neither is an
//! unaligned `UnitAlignment`, so a caller can tell them apart from each other
//! and from a SUCCESS with no words, which names its own cause: text that
//! normalizes to nothing or yields no tokens (`Unaligned(NoAlignableText)`,
//! answered before the encoder), or an alignment whose every word fell outside
//! the chunk's speech (`Unaligned(NoSurvivingWords)`). Either way the ASR text
//! is the caller's to keep; only per-word timings are missing. Every other
//! `EmissionsError` reaches [`AlignError::Alignment`] and is a genuine failure.

/// A loaded model's input or output feature does not match the
/// shape/dtype contract this crate was built against (see
/// `tests/model_io.rs` for the pinned ground truth).
///
/// Payload of [`AlignerError::ContractMismatch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractMismatch {
  /// Name of the input/output feature that mismatched.
  feature: &'static str,
  /// The contract this crate expects, rendered for display.
  expected: String,
  /// What the loaded model actually declares, rendered for display.
  actual: String,
}

impl ContractMismatch {
  /// Construct from the mismatched feature, the expected contract, and what
  /// the loaded model actually declares.
  #[inline(always)]
  pub const fn new(feature: &'static str, expected: String, actual: String) -> Self {
    Self {
      feature,
      expected,
      actual,
    }
  }

  /// Name of the input/output feature that mismatched.
  #[inline(always)]
  pub const fn feature(&self) -> &'static str {
    self.feature
  }

  /// The contract this crate expects, rendered for display.
  #[inline(always)]
  pub fn expected(&self) -> &str {
    &self.expected
  }

  /// What the loaded model actually declares, rendered for display.
  #[inline(always)]
  pub fn actual(&self) -> &str {
    &self.actual
  }
}

/// Failure locating, loading, or validating the CoreML wav2vec2 forced-
/// aligner model (design spec §8's `AlignerError`, model-loading subset).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum AlignerError {
  /// The CoreML runtime failed to load the compiled model.
  #[error("failed to load model: {0}")]
  Load(#[from] crate::LoadError),
  /// A loaded model's input or output feature does not match the
  /// shape/dtype contract this crate was built against (see
  /// `tests/model_io.rs` for the pinned ground truth).
  #[error(
    "model contract mismatch on `{}`: expected {}, got {}",
    .0.feature(),
    .0.expected(),
    .0.actual()
  )]
  ContractMismatch(ContractMismatch),
  /// The loaded graph declares a REQUIRED input this door never supplies, so
  /// every prediction through it would fail.
  ///
  /// Carries the offending feature name. An OPTIONAL extra input is not this:
  /// CoreML runs a prediction that omits one, so only a required input the
  /// door cannot fill makes the contract unsatisfiable.
  #[error(
    "model declares a required input `{0}` that this door never supplies; \
     it sends `waveform` and nothing else, so every prediction would fail"
  )]
  UnsatisfiableInput(String),
  /// The loaded graph declares CoreML STATE buffers, and this door predicts
  /// through the stateless API.
  ///
  /// Carries the offending state feature name. A stateful model must receive an
  /// `MLState` on every prediction; a door that never makes one either fails
  /// the prediction outright or silently discards the persistence the graph was
  /// built around. Neither is something to discover at predict time.
  #[error(
    "model declares the state buffer `{0}`, and this door predicts through the \
     stateless API; a stateful graph needs an `MLState` on every prediction"
  )]
  UnsatisfiableState(String),
  /// Building asry's alignment seam
  /// ([`asry::emissions::EmissionsAligner`]) failed: the tokenizer JSON did
  /// not parse, the language has no default text normalizer, or the
  /// normalizer needs a `|` word-delimiter the vocabulary lacks. Surfaced by
  /// [`crate::audio::align::aligner::Aligner::from_paths`].
  #[error("alignment seam construction failed: {0}")]
  Seam(#[from] asry::emissions::EmissionsError),
  /// The contract's geometry does not make the model's declared frame count
  /// out of the model's declared window: the geometry is not this model's
  /// front end.
  ///
  /// A model declares its window and its frame count, not the receptive field
  /// and stride that relate them, and one frame count fits several geometries.
  /// What the load CAN check is that the stated geometry agrees with the
  /// declared pair, and a geometry that disagrees would truncate every chunk to
  /// the wrong number of frames, so it is refused here, by name, before the
  /// first one.
  #[error(
    "the contract's front end ({}-sample receptive field, {}-sample stride) makes {} frames \
     of the model's {}-sample window, but the model declares {}: the geometry is not this \
     model's",
    .0.geometry().receptive_field(),
    .0.geometry().stride(),
    .0.derived(),
    .0.window(),
    .0.declared()
  )]
  FrameCountMismatch(FrameCountMismatch),
  /// The contract's blank is no id of the vocabulary: the table's ids run
  /// `0..n`, and the blank the contract names is `n` or beyond.
  ///
  /// The blank is the contract's statement, never the table's: a flat
  /// `{token: id}` table does not say which class is the blank. What the load
  /// can check is that the stated id is one of the table's columns.
  #[error(
    "the contract names id {} the CTC blank, but the vocabulary's {} entries hold ids 0..{}; \
     the blank must be one of the table's own ids",
    .0.blank(),
    .0.entries(),
    .0.entries()
  )]
  BlankOutOfVocabulary(BlankOutOfVocabulary),
  /// The contract's tokenization is one this table or this normalizer
  /// contradicts: see [`TokenizationError`].
  ///
  /// asry's seam takes the word delimiter and the letter case as the contract
  /// states them and does not second-guess a statement, so a statement the
  /// table or the normalizer contradicts is refused here rather than aligned
  /// against the wrong columns.
  #[error("the contract's tokenization cannot be honoured: {0}")]
  Tokenization(TokenizationError),
  /// The seam built from the table under the contract reserves other columns
  /// than the contract declares non-lexical: see [`ReservedSetMismatch`].
  ///
  /// asry reserves the columns of the blank and the word delimiter it is
  /// stated, of the unknown token the tokenizer document declares, and of every
  /// special added token the document still holds once the `tokenizers` crate
  /// has parsed it. It spells no transcript character onto a reserved column
  /// and scores no wildcard there. The document declares exactly the contract's
  /// non-lexical tokens special, and a parse can drop one (an added token with
  /// empty content, [`TokenizationError::EmptySpecial`]), so the aligner reads
  /// the reserved set back after building the seam and refuses a seam whose set
  /// is not the contract's: a declared column left unreserved could be scored
  /// for a wildcard, and a lexical column reserved could never be spelled.
  #[error(
    "the seam reserves the columns {:?} where the contract declares {:?} non-lexical: a declared \
     column the seam does not reserve can be scored for a wildcard, and a reserved column the \
     contract calls lexical is never spelled",
    .0.reserved(),
    .0.declared()
  )]
  ReservedSetMismatch(ReservedSetMismatch),
  /// The contract says the head emits log-probabilities, and the head is too
  /// wide for their normalization to be checked: see
  /// [`UnprovableNormalization`].
  #[error(
    "a {}-class head's log-probabilities cannot be checked for normalization: fp16 rounding over \
     that many classes can move a genuine frame's logsumexp by up to {:.3}, too near an \
     unnormalized frame's; the check separates the two only up to {} classes. State the head's \
     output as logits: asry then normalizes it, and normalizing a log-softmax output again \
     changes nothing",
    .0.vocab_size(),
    crate::audio::align::encode::log_prob_sum_tolerance(.0.vocab_size_nonzero()),
    .0.widest()
  )]
  UnprovableNormalization(UnprovableNormalization),
  /// The vocabulary does not have one entry per class of the model's CTC
  /// head: it names one number of classes, the model's `emissions` scores
  /// another per frame.
  ///
  /// Refused at load because the pair is wrong for every chunk: asry would read
  /// each token's posterior from a column that does not belong to it. A model
  /// is paired with the vocabulary that ships beside it
  /// ([`crate::audio::align::vocab::Vocabulary::from_file`]); the bundled table
  /// [`crate::audio::align::aligner::Aligner::from_paths`] binds is the 29-class
  /// English one.
  #[error(
    "the vocabulary names {} classes but the model's CTC head scores {} per frame; \
     pair the model with the vocabulary that ships beside it",
    .0.vocabulary(),
    .0.model()
  )]
  VocabularyMismatch(VocabularyMismatch),
}

/// A vocabulary and a model's CTC head disagree on the number of classes.
///
/// Payload of [`AlignerError::VocabularyMismatch`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VocabularyMismatch {
  /// Entries in the vocabulary the seam was built from.
  vocabulary: usize,
  /// Classes the model's `emissions` scores per frame.
  model: usize,
}

impl VocabularyMismatch {
  /// Construct from the vocabulary's entry count and the model's CTC head
  /// width.
  #[inline(always)]
  pub const fn new(vocabulary: usize, model: usize) -> Self {
    Self { vocabulary, model }
  }

  /// Entries in the vocabulary the seam was built from.
  #[inline(always)]
  pub const fn vocabulary(&self) -> usize {
    self.vocabulary
  }

  /// Classes the model's `emissions` scores per frame.
  #[inline(always)]
  pub const fn model(&self) -> usize {
    self.model
  }
}

/// The columns asry's seam reserves differ from the contract's non-lexical
/// columns.
///
/// Payload of [`AlignerError::ReservedSetMismatch`]. Both are vocabulary ids,
/// in ascending order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReservedSetMismatch {
  /// The ids the contract declares non-lexical: the entry at its blank id, its
  /// word delimiter and every special it names that the table spells.
  declared: Vec<usize>,
  /// The ids the seam reserves, read back after it was built.
  reserved: Vec<usize>,
}

impl ReservedSetMismatch {
  /// Construct from the ids the contract declares non-lexical and the ids the
  /// seam reserves, each in ascending order.
  #[must_use]
  pub const fn new(declared: Vec<usize>, reserved: Vec<usize>) -> Self {
    Self { declared, reserved }
  }

  /// The ids the contract declares non-lexical, in ascending order.
  #[inline]
  pub fn declared(&self) -> &[usize] {
    &self.declared
  }

  /// The ids the seam reserves, in ascending order.
  #[inline]
  pub fn reserved(&self) -> &[usize] {
    &self.reserved
  }
}

/// A contract's geometry and a model's declaration disagree on the frames of
/// one window.
///
/// Payload of [`AlignerError::FrameCountMismatch`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameCountMismatch {
  /// The geometry the contract states.
  geometry: crate::audio::align::acoustic::AcousticGeometry,
  /// The samples of the model's declared input window.
  window: usize,
  /// The frames the model declares for one window.
  declared: usize,
}

impl FrameCountMismatch {
  /// Construct from the contract's geometry, the model's declared window and
  /// the frames the model declares for it.
  #[inline(always)]
  pub const fn new(
    geometry: crate::audio::align::acoustic::AcousticGeometry,
    window: usize,
    declared: usize,
  ) -> Self {
    Self {
      geometry,
      window,
      declared,
    }
  }

  /// The geometry the contract states.
  #[inline(always)]
  pub const fn geometry(&self) -> crate::audio::align::acoustic::AcousticGeometry {
    self.geometry
  }

  /// The samples of the model's declared input window.
  #[inline(always)]
  pub const fn window(&self) -> usize {
    self.window
  }

  /// The frames the model declares for one window.
  #[inline(always)]
  pub const fn declared(&self) -> usize {
    self.declared
  }

  /// The frames the contract's geometry makes of that window.
  #[inline(always)]
  pub const fn derived(&self) -> usize {
    self.geometry.frames(self.window)
  }
}

/// A log-probability head too wide for its normalization to be checked.
///
/// Payload of [`AlignerError::UnprovableNormalization`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnprovableNormalization {
  /// The head's width.
  vocab_size: core::num::NonZeroUsize,
  /// The widest head whose normalization the check separates from an
  /// unnormalized frame's
  /// ([`MAX_LOG_PROB_WIDTH`](crate::audio::align::encode::MAX_LOG_PROB_WIDTH)).
  widest: usize,
}

impl UnprovableNormalization {
  /// Construct from the head's width and the widest checkable one.
  #[inline(always)]
  pub const fn new(vocab_size: core::num::NonZeroUsize, widest: usize) -> Self {
    Self { vocab_size, widest }
  }

  /// The head's width.
  #[inline(always)]
  pub const fn vocab_size(&self) -> usize {
    self.vocab_size.get()
  }

  /// The head's width, as the non-zero count it is.
  #[inline(always)]
  pub const fn vocab_size_nonzero(&self) -> core::num::NonZeroUsize {
    self.vocab_size
  }

  /// The widest head whose normalization the check separates from an
  /// unnormalized frame's.
  #[inline(always)]
  pub const fn widest(&self) -> usize {
    self.widest
  }
}

/// A contract's blank that is no id of the vocabulary it is paired with.
///
/// Payload of [`AlignerError::BlankOutOfVocabulary`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlankOutOfVocabulary {
  /// The id the contract names the blank.
  blank: u32,
  /// Entries in the vocabulary, whose ids run `0..entries`.
  entries: usize,
}

impl BlankOutOfVocabulary {
  /// Construct from the contract's blank and the vocabulary's entry count.
  #[inline(always)]
  pub const fn new(blank: u32, entries: usize) -> Self {
    Self { blank, entries }
  }

  /// The id the contract names the blank.
  #[inline(always)]
  pub const fn blank(&self) -> u32 {
    self.blank
  }

  /// Entries in the vocabulary, whose ids run `0..entries`.
  #[inline(always)]
  pub const fn entries(&self) -> usize {
    self.entries
  }
}

/// A front end's geometry that asry's seam cannot time, refused by
/// [`crate::audio::align::acoustic::AcousticGeometry::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum GeometryError {
  /// The front end takes audio at this rate, and asry's seam analyses 16 kHz
  /// audio only: its speech spans, its output clock and every stride it checks
  /// count 16 kHz samples. Carries the rate refused.
  #[error(
    "the front end takes {0} Hz audio, and asry's seam analyses 16000 Hz audio only: its spans, \
     its clock and its strides count 16 kHz samples"
  )]
  SampleRate(u32),
}

/// A model's tokenization that its table or its normalizer contradicts, or
/// that a contract cannot state. Refused at load
/// ([`AlignerError::Tokenization`]), except
/// [`Self::UnsupportedDelimiter`], which
/// [`WordDelimiter::from_token`](crate::audio::align::acoustic::WordDelimiter::from_token)
/// refuses when the contract is stated.
///
/// asry's seam takes the contract's word delimiter and letter case as stated.
/// A contract states the model's own tokenization, and this is every way that
/// statement and the table or the normalizer can disagree.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TokenizationError {
  /// The model delimits words with this token, and a contract states the `|`
  /// delimiter, the space, or none.
  #[error(
    "the model delimits words with {0:?}, and a contract states the `|` delimiter, the space, or \
     none"
  )]
  UnsupportedDelimiter(String),
  /// The table spells this whitespace token as a LEXICAL class: the contract
  /// states it neither as its space delimiter nor as its blank or a special.
  /// asry splits a text into words at whitespace and never looks whitespace
  /// up, so its column would never be read as a class — and beside a `|` the
  /// contract states, a space does not say which of the two delimits the
  /// model's words.
  #[error(
    "the table spells the whitespace token {0:?}, which the contract does not state as its word \
     delimiter: asry splits words at whitespace and never looks one up, so its column would \
     never be read, and beside a stated `|` it does not say which of the two delimits the words"
  )]
  WhitespaceToken(String),
  /// The contract delimits words with `|` or a space, and the table does not
  /// spell that token.
  #[error("the table does not spell the word delimiter the contract states")]
  DelimiterMissing,
  /// The contract states a word delimiter, and the normalizer delimits no
  /// words: the model's delimiter frames between words would be read as the
  /// letters beside them.
  #[error(
    "the contract states a word delimiter, but the normalizer delimits no words: the model's \
     delimiter frames between words would be read as the letters beside them"
  )]
  DelimiterUnused,
  /// The normalizer delimits words, and the contract says the model has no
  /// word delimiter: there is no token to put between them.
  #[error(
    "the normalizer delimits words, and the contract says the model has no word delimiter to \
     put between them"
  )]
  DelimiterRequired,
  /// The contract spells letters in upper case, and the table also spells
  /// this lowercase letter as a LEXICAL class (not the blank, the delimiter or
  /// a declared special): asry looks every ASCII letter up in upper case, so
  /// it would never read its column.
  #[error(
    "the contract spells letters in upper case, but the table also spells {0:?}: asry looks \
     every ASCII letter up in upper case and would never read its column"
  )]
  UpperWithLowercase(char),
  /// The contract looks letters up as written, and the table's LEXICAL
  /// letters (not the blank, the delimiter or a declared special) are
  /// uppercase ASCII letters with no lowercase one among them: an upper-case
  /// table, which [`LetterCase::Upper`] states.
  ///
  /// [`LetterCase::Upper`]: crate::audio::align::acoustic::LetterCase::Upper
  #[error(
    "the contract looks letters up as written, but the table's letters are uppercase only: an \
     upper-case table, which `LetterCase::Upper` states"
  )]
  ProjectedAsWritten,
  /// The table spells this LEXICAL token — one that is not the blank, the
  /// delimiter, or a declared special
  /// ([`Tokenization::specials`](crate::audio::align::acoustic::Tokenization::specials))
  /// — as other than one Unicode scalar value.
  ///
  /// [`Granularity::Character`](crate::audio::align::acoustic::Granularity::Character)
  /// is the only granularity asry's seam can execute: it always resolves a
  /// text's tokens with a per-character `token_to_id` lookup, never a real
  /// subword tokenizer. A table can truthfully hold a class like `AB` beside
  /// `A` and `B` — nothing about the table is malformed — and still be
  /// unalignable through this seam: asry would look `A` and `B` up
  /// separately and never read the `AB` column a subword model actually
  /// scored, which is a silent misalignment, not a load failure. So a
  /// lexical token of any length but one is refused by name here, before
  /// that can happen.
  #[error(
    "the table spells the lexical token {0:?} as other than one Unicode scalar value: asry \
     looks a text up one character at a time and would never read this token's column; declare \
     it a special if it is not a letter, or use a tokenizer-driven seam for a model that truly \
     tokenizes in wider units"
  )]
  NotCharacterLevel(String),
  /// The contract declares a special the table spells as the empty string, at
  /// this id, and neither the blank nor the delimiter the seam is stated
  /// reserves its column.
  ///
  /// asry reserves a declared special's column because the tokenizer document
  /// declares it a special added token, and the `tokenizers` crate drops an
  /// added token whose content is empty when it parses the document
  /// (`AddedVocabulary::add_tokens`): the declaration never reaches asry, and a
  /// wildcard could be scored in that column. The blank's id is reserved
  /// whatever it spells, so an empty entry at the contract's blank id passes;
  /// under
  /// [`WordDelimiter::Absent`](crate::audio::align::acoustic::WordDelimiter::Absent)
  /// the seam is stated the empty token as its delimiter, and its lookup
  /// reserves the table's empty entry, so that passes too.
  #[error(
    "the contract declares the table's empty token, id {0}, a special, and nothing else reserves \
     its column: the `tokenizers` crate drops an empty added token when it parses the tokenizer \
     document, so asry would not reserve the column and a wildcard could be scored there"
  )]
  EmptySpecial(usize),
}

/// Failure reading a model's own CTC vocabulary into a
/// [`crate::audio::align::vocab::Vocabulary`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum VocabularyError {
  /// The vocabulary file could not be read.
  #[error(transparent)]
  Read(VocabularyRead),
  /// The bytes are not a JSON object mapping each token to a non-negative
  /// integer id. Carries the parser's diagnostic.
  #[error("a vocabulary is a JSON object mapping each token to its id: {0}")]
  Parse(String),
  /// The JSON object names this token twice. JSON leaves a repeated key's
  /// meaning to the reader — one keeps the first id, another the last — so a
  /// table that repeats a token does not say which column it is scored in, and
  /// is refused rather than resolved either way. Carries the repeated token.
  #[error(
    "the vocabulary names the token {0:?} twice; a repeated key leaves its column to whichever \
     JSON reader reads it"
  )]
  DuplicateToken(String),
  /// An id in `0..n` names no token, where `n` is the number of entries: the
  /// table skips an id, or gives two tokens the same one. Each of a CTC head's
  /// columns is one class, so a table that does not name every id exactly once
  /// would leave a column unnamed or read one column for two tokens.
  #[error(
    "no token has id {}: a vocabulary of {} entries names every id in 0..{} exactly once, \
     one per class of its model's CTC head",
    .0.id(),
    .0.entries(),
    .0.entries()
  )]
  MissingId(MissingId),
  /// The object names no token. A CTC head has at least one class, its blank.
  #[error("the vocabulary names no token; a CTC head has at least one class, its blank")]
  Empty,
}

/// The vocabulary file at [`Self::path`] could not be read.
///
/// Payload of [`VocabularyError::Read`], which is `#[error(transparent)]`: this
/// struct owns the message and the `#[source]`, so the error chain has one
/// link, to the [`std::io::Error`].
#[derive(Debug, thiserror::Error)]
#[error("failed to read the vocabulary `{path}`: {source}")]
pub struct VocabularyRead {
  /// The file that could not be read.
  path: std::path::PathBuf,
  /// The underlying I/O failure.
  #[source]
  source: std::io::Error,
}

impl VocabularyRead {
  /// Construct from the file that could not be read and the underlying I/O
  /// failure.
  #[inline(always)]
  pub const fn new(path: std::path::PathBuf, source: std::io::Error) -> Self {
    Self { path, source }
  }

  /// The file that could not be read.
  #[inline(always)]
  pub fn path(&self) -> &std::path::Path {
    &self.path
  }
}

/// An id of `0..entries` that no token of a vocabulary holds.
///
/// Payload of [`VocabularyError::MissingId`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MissingId {
  /// The lowest id in `0..entries` no token holds.
  id: usize,
  /// The number of entries in the table.
  entries: usize,
}

impl MissingId {
  /// Construct from the lowest unnamed id and the table's entry count.
  #[inline(always)]
  pub const fn new(id: usize, entries: usize) -> Self {
    Self { id, entries }
  }

  /// The lowest id in `0..entries` no token holds.
  #[inline(always)]
  pub const fn id(&self) -> usize {
    self.id
  }

  /// The number of entries in the table.
  #[inline(always)]
  pub const fn entries(&self) -> usize {
    self.entries
  }
}

/// `samples` exceeded the aligner's input window
/// ([`Aligner::window_samples`](crate::audio::align::Aligner::window_samples)).
///
/// Payload of [`AlignError::InputTooLong`].
#[derive(Debug, Clone)]
pub struct InputTooLong {
  /// Samples the caller supplied.
  got: usize,
  /// The aligner's input window, read from its model at load
  /// ([`Aligner::window_samples`](crate::audio::align::Aligner::window_samples)).
  max: usize,
}

impl InputTooLong {
  /// Construct from the sample count the caller supplied and the encoder's
  /// input window.
  #[inline(always)]
  pub const fn new(got: usize, max: usize) -> Self {
    Self { got, max }
  }

  /// Samples the caller supplied.
  #[inline(always)]
  pub const fn got(&self) -> usize {
    self.got
  }

  /// The aligner's input window, read from its model at load
  /// ([`Aligner::window_samples`](crate::audio::align::Aligner::window_samples)).
  #[inline(always)]
  pub const fn max(&self) -> usize {
    self.max
  }
}

/// The encoder returned an emission matrix that is **not log-probabilities**:
/// at least one cell sits in the model's
/// [`SentinelBand`](crate::audio::align::acoustic::SentinelBand), the band
/// its contract says it emits in place of a log-probability. For the staged
/// `base960h` that is fp16's saturation band, where a saturated fp16 `log(0)`
/// lands (`-45440` on the Apple Neural Engine).
///
/// This is the loud form of what used to be a silent one. The values are
/// finite and negative, so they pass asry's own `finite ∧ <= 0` scan of a
/// log-probability output untouched and would align to *plausible, wrong*
/// timings (in the pre-truncation-fix measurement `ask` landed 881.6 ms early
/// on `jfk.wav`), which is why the band is checked separately. See
/// [`crate::audio::align::encode::DEFAULT_ENCODER_COMPUTE`] for the mechanism.
/// Only a contract that carries a band raises this: a band is one artifact's
/// measurement, and [`AcousticContract::new`](crate::audio::align::acoustic::AcousticContract::new)
/// carries none.
///
/// The corruption is a defect of the **model artifact**, not of the caller's
/// audio: no input makes a *correctly-converted* artifact produce it. But on a
/// *corrupted* artifact its DETECTION is input-dependent — this error fires
/// only when the input drives a class posterior under the fp16 floor and so
/// exposes the `log(0)` sentinel. Real speech can (measured `min ≈ -45440` on
/// `jfk.wav`); 960,000 samples of digital silence (`min ≈ -8.55`) and a
/// low-amplitude sine (`≈ -9.07`) stay ABOVE the band and pass clean even on
/// the corrupt placement — the recorded evidence in
/// `tests::emissions_reject_an_ane_corrupted_matrix`'s doc, and why real speech
/// is load-bearing there. The fix is the placement named in this error, or a
/// re-converted model; nothing in this crate can recover the underflowed cells.
///
/// Payload of [`AlignError::CorruptEmissions`].
#[derive(Debug, Clone)]
pub struct CorruptEmissions {
  /// The compute placement the encoder was loaded on — the knob the caller
  /// can actually turn, hence the one the message names.
  compute: crate::ComputeUnits,
  /// The band the cells were found in: the model's contract's.
  band: crate::audio::align::acoustic::SentinelBand,
  /// The most negative cell in the matrix (`≈ -45440` on an ANE placement;
  /// `-30.81` on the `CpuOnly` default, measured on `jfk.wav`).
  min: f32,
  /// How many cells fell in the band (2,667 on `jfk.wav`'s ANE run).
  cells: usize,
  /// Cells scanned: `frames × V`, `V` the model's head width (15,921 on
  /// `jfk.wav`).
  total: usize,
}

impl CorruptEmissions {
  /// Construct from the compute placement, the band the cells were found in,
  /// the most negative cell, the number of cells in the band, and the number
  /// of cells scanned.
  #[inline(always)]
  pub const fn new(
    compute: crate::ComputeUnits,
    band: crate::audio::align::acoustic::SentinelBand,
    min: f32,
    cells: usize,
    total: usize,
  ) -> Self {
    Self {
      compute,
      band,
      min,
      cells,
      total,
    }
  }

  /// The compute placement the encoder was loaded on — the knob the caller
  /// can actually turn, hence the one the message names.
  #[inline(always)]
  pub const fn compute(&self) -> crate::ComputeUnits {
    self.compute
  }

  /// The band the cells were found in: the model's contract's.
  #[inline(always)]
  pub const fn band(&self) -> crate::audio::align::acoustic::SentinelBand {
    self.band
  }

  /// The most negative cell in the matrix (`≈ -45440` on an ANE placement;
  /// `-30.81` on the `CpuOnly` default, measured on `jfk.wav`).
  #[inline(always)]
  pub const fn min(&self) -> f32 {
    self.min
  }

  /// How many cells fell in the band (2,667 on `jfk.wav`'s ANE run).
  #[inline(always)]
  pub const fn cells(&self) -> usize {
    self.cells
  }

  /// Cells scanned: `frames × V`, `V` the model's head width (15,921 on
  /// `jfk.wav`).
  #[inline(always)]
  pub const fn total(&self) -> usize {
    self.total
  }
}

/// The encoder returned an emission matrix that is **not normalized
/// log-probabilities**: frame `row`'s `logsumexp` over the vocab axis is
/// `logsumexp`, exceeding in magnitude the allowance
/// [`crate::audio::align::encode::log_prob_sum_tolerance`] gives a head of its
/// width. A genuine CTC log-probability frame sums to 1 in probability space,
/// so its `logsumexp` is `0` (`ln Σ exp(log p_j) = ln Σ p_j = ln 1`); a
/// whole-unit deviation means the tensor carries raw logits — or another
/// un-normalized distribution — not the log-softmaxed output this crate's
/// encoder contract requires.
///
/// Unlike [`AlignError::CorruptEmissions`] — a placement-dependent fp16 underflow of
/// THIS reviewed artifact — this is a **model-artifact contract** failure that
/// no placement causes and no placement cures: a revision shipping a raw-logit
/// CTC head (the *standard* wav2vec2 export, and what asry's own ONNX model
/// emits) is rejected here rather than silently re-normalized by asry's
/// log-softmax of a logit output and aligned on forever. It is the check that makes
/// `Encoder::emissions`'s "these really are log-probs" a
/// verified contract for any same-contract artifact loaded through the public
/// API, not merely for the one reviewed here. The finite ∧ `<= 0` scan asry
/// runs on a log-probability output cannot catch it: raw logits shifted wholly
/// into `[-20, -10]`, or an all-zeros frame, are finite and `<= 0` on every
/// cell yet no distribution at all. See
/// [`crate::audio::align::encode::log_prob_sum_tolerance`] for the allowance and the
/// [`crate::audio::align::encode`] module doc's "The normalization guard".
///
/// Payload of [`AlignError::UnnormalizedEmissions`].
#[derive(Debug, Clone)]
pub struct UnnormalizedEmissions {
  /// The compute placement the encoder was loaded on. Carried for parity with
  /// [`AlignError::CorruptEmissions`]; unlike that error the placement is not the
  /// cause here (the model artifact is), but it remains useful context.
  compute: crate::ComputeUnits,
  /// Index of the worst frame — the one with the largest `|logsumexp|`.
  row: usize,
  /// That frame's `logsumexp` over the vocab axis (`≈ 0` for real log-probs;
  /// `ln 29 ≈ 3.367` for an all-zeros frame; `>= 6.6` for a `[-20, -10]`
  /// shifted raw-logit frame). Accumulated in `f64`.
  logsumexp: f64,
  /// The bound it exceeded: [`crate::audio::align::encode::log_prob_sum_tolerance`] of the
  /// head's width.
  tolerance: f64,
}

impl UnnormalizedEmissions {
  /// Construct from the compute placement, the worst frame's index, that
  /// frame's `logsumexp`, and the tolerance it exceeded.
  #[inline(always)]
  pub const fn new(
    compute: crate::ComputeUnits,
    row: usize,
    logsumexp: f64,
    tolerance: f64,
  ) -> Self {
    Self {
      compute,
      row,
      logsumexp,
      tolerance,
    }
  }

  /// The compute placement the encoder was loaded on. Carried for parity with
  /// [`AlignError::CorruptEmissions`]; unlike that error the placement is not the
  /// cause here (the model artifact is), but it remains useful context.
  #[inline(always)]
  pub const fn compute(&self) -> crate::ComputeUnits {
    self.compute
  }

  /// Index of the worst frame — the one with the largest `|logsumexp|`.
  #[inline(always)]
  pub const fn row(&self) -> usize {
    self.row
  }

  /// That frame's `logsumexp` over the vocab axis (`≈ 0` for real log-probs;
  /// `ln 29 ≈ 3.367` for an all-zeros frame; `>= 6.6` for a `[-20, -10]`
  /// shifted raw-logit frame). Accumulated in `f64`.
  #[inline(always)]
  pub const fn logsumexp(&self) -> f64 {
    self.logsumexp
  }

  /// The bound it exceeded: [`crate::audio::align::encode::log_prob_sum_tolerance`] of the
  /// head's width.
  #[inline(always)]
  pub const fn tolerance(&self) -> f64 {
    self.tolerance
  }
}

/// A caller's OOV decisions were made for another request than the one being
/// aligned.
///
/// Returned by [`crate::audio::align::registry::AlignmentSet::align_chunk`] when
/// its [`SetResolution`](crate::audio::align::registry::SetResolution) was
/// decided for `found` rather than the `requested` language the chunk is being
/// aligned for. asry binds decisions to the text and the aligner that detected
/// them, not to a request: an
/// [`AlignerKey::Any`](crate::audio::align::registry::AlignerKey::Any) aligner
/// serves every language, so one language's wildcard / fail-closed policy would
/// otherwise apply silently under another. Decide the detection of the SAME
/// language you pass to `align_chunk` — the one
/// [`AlignmentSet::detect_oov`](crate::audio::align::registry::AlignmentSet::detect_oov)
/// was asked for.
///
/// Payload of [`AlignError::DecisionLanguage`].
#[derive(Debug, Clone)]
pub struct DecisionLanguage {
  /// The language the chunk is being aligned for (the `align_chunk` argument).
  requested: asry::Lang,
  /// The language the decisions were made for.
  found: asry::Lang,
}

impl DecisionLanguage {
  /// Construct from the language the chunk is being aligned for and the
  /// language the decisions were made for.
  #[inline(always)]
  pub const fn new(requested: asry::Lang, found: asry::Lang) -> Self {
    Self { requested, found }
  }

  /// The language the chunk is being aligned for (the `align_chunk` argument).
  #[inline(always)]
  pub const fn requested(&self) -> &asry::Lang {
    &self.requested
  }

  /// The language the decisions were made for.
  #[inline(always)]
  pub const fn found(&self) -> &asry::Lang {
    &self.found
  }
}

/// A resolution another alignment set made, handed to this one.
///
/// Payload of [`AlignError::ForeignResolution`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ForeignResolution {
  /// The set whose detection the resolution was decided from.
  made_by: crate::audio::align::registry::SetId,
  /// The set asked to apply it.
  asked: crate::audio::align::registry::SetId,
}

impl ForeignResolution {
  /// Construct from the set that made the resolution and the set asked to
  /// apply it.
  #[inline(always)]
  pub const fn new(
    made_by: crate::audio::align::registry::SetId,
    asked: crate::audio::align::registry::SetId,
  ) -> Self {
    Self { made_by, asked }
  }

  /// The set whose detection the resolution was decided from.
  #[inline(always)]
  pub const fn made_by(&self) -> crate::audio::align::registry::SetId {
    self.made_by
  }

  /// The set asked to apply it.
  #[inline(always)]
  pub const fn asked(&self) -> crate::audio::align::registry::SetId {
    self.asked
  }
}

/// A resolution whose shape is not its request's route.
///
/// Payload of [`AlignError::MisroutedResolution`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MisroutedResolution {
  /// The route the request takes.
  route: crate::audio::align::registry::AlignmentBinding,
  /// Whether the resolution holds an aligner's decisions.
  decided: bool,
}

impl MisroutedResolution {
  /// Construct from the route the request takes and whether the resolution
  /// holds an aligner's decisions.
  #[inline(always)]
  pub const fn new(route: crate::audio::align::registry::AlignmentBinding, decided: bool) -> Self {
    Self { route, decided }
  }

  /// The route the request takes.
  #[inline(always)]
  pub const fn route(&self) -> &crate::audio::align::registry::AlignmentBinding {
    &self.route
  }

  /// Whether the resolution holds an aligner's decisions: `true` where the
  /// route is a miss, `false` where an aligner reads the text.
  #[inline(always)]
  pub const fn decided(&self) -> bool {
    self.decided
  }

  /// What the resolution holds, in words.
  const fn shape(&self) -> &'static str {
    if self.decided {
      "holds an aligner's decisions"
    } else {
      "was decided where no aligner read the text"
    }
  }
}

/// The shape a prediction's `emissions` tensor had, against the one the load
/// contract declared.
///
/// Payload of [`AlignError::OutputShape`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputShape {
  /// Shape the runtime tensor actually had.
  got: Vec<usize>,
  /// Shape the load contract declares: `[1, frames, V]`.
  expected: Vec<usize>,
}

impl OutputShape {
  /// Construct from the shape the runtime tensor had and the shape the load
  /// contract declares.
  #[inline(always)]
  pub const fn new(got: Vec<usize>, expected: Vec<usize>) -> Self {
    Self { got, expected }
  }

  /// Shape the runtime tensor actually had.
  #[inline(always)]
  pub fn got(&self) -> &[usize] {
    &self.got
  }

  /// Shape the load contract declares: `[1, frames, V]`.
  #[inline(always)]
  pub fn expected(&self) -> &[usize] {
    &self.expected
  }
}

/// Every position a caller's OOV decisions refused in one chunk.
///
/// Payload of [`AlignError::Refused`]. The positions are those the caller's
/// decisions resolved `FailClosed`, in the order `detect_oov` reported them,
/// each a [`RefusedOov`] under the language the decisions were made for: the
/// request's on every road. A `Symbol` or `InternalPunct` position names its
/// character ([`RefusedOov::char`]); a `BoundaryPunct` one carries none,
/// because the normalizer stripped that mark before tokenization.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
  /// The refused positions, under the requested language.
  events: Vec<RefusedOov>,
}

impl Refusal {
  /// Construct from the refused positions.
  #[inline(always)]
  pub const fn new(events: Vec<RefusedOov>) -> Self {
    Self { events }
  }

  /// The refused positions, under the requested language.
  #[inline(always)]
  pub fn events(&self) -> &[RefusedOov] {
    &self.events
  }

  /// This refusal for a request in `language`: every position under it.
  pub(crate) fn under(self, language: &asry::Lang) -> Self {
    Self {
      events: self
        .events
        .into_iter()
        .map(|event| event.under(language))
        .collect(),
    }
  }
}

/// One position a caller's OOV decision refused, as a [`Refusal`] names it:
/// owned, and under the requested language.
///
/// It mirrors asry's [`OovEvent`](asry::emissions::OovEvent) reader for reader,
/// with one difference: [`Self::language`] is the language the decision was
/// made for, the request's, never the language asry stamped the event with,
/// which for an `AlignerKey::Any` fallback of an
/// [`AlignmentSet`](crate::audio::align::registry::AlignmentSet) is the
/// fallback's own. It holds no asry event, so no reader, log or `Debug` of a
/// refusal shows that stamp.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefusedOov {
  /// What kind of wildcard-generating position this is.
  kind: asry::emissions::OovKind,
  /// The offending character, as asry's event names it.
  char: Option<char>,
  /// Zero-based char index in the chunk's normalized text.
  char_index: usize,
  /// Zero-based word index (separator-counted).
  word_index: usize,
  /// The language the decision was made for.
  language: asry::Lang,
}

impl RefusedOov {
  /// `event`, refused under the language its detection was read in: the
  /// aligner's own, which is the request's on a direct road. The registry's
  /// roads restate it under the requested language ([`Refusal`]'s `under`).
  pub(crate) fn detected(event: &asry::emissions::OovEvent) -> Self {
    Self {
      kind: event.kind().clone(),
      char: event.char(),
      char_index: event.char_index(),
      word_index: event.word_index(),
      language: event.language().clone(),
    }
  }

  /// This position under `language`.
  fn under(self, language: &asry::Lang) -> Self {
    Self {
      language: language.clone(),
      ..self
    }
  }

  /// What kind of wildcard-generating position this is.
  #[inline(always)]
  pub const fn kind(&self) -> &asry::emissions::OovKind {
    &self.kind
  }

  /// The offending character when the kind is `Symbol` or `InternalPunct`;
  /// `None` for `BoundaryPunct`, whose mark the normalizer removed, and for
  /// `NotInspected`.
  #[inline(always)]
  pub const fn char(&self) -> Option<char> {
    self.char
  }

  /// Zero-based char index in the chunk's normalized text.
  #[inline(always)]
  pub const fn char_index(&self) -> usize {
    self.char_index
  }

  /// Zero-based word index (separator-counted).
  #[inline(always)]
  pub const fn word_index(&self) -> usize {
    self.word_index
  }

  /// The language the decision was made for: the request's.
  #[inline(always)]
  pub const fn language(&self) -> &asry::Lang {
    &self.language
  }
}

/// Each refused position, comma-separated: a character quoted with the
/// zero-based index of its word, or a boundary mark (whose character the
/// normalizer removed) with the index of its word.
impl core::fmt::Display for Refusal {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    if self.events.is_empty() {
      return f.write_str("no position");
    }
    for (at, event) in self.events.iter().enumerate() {
      if at > 0 {
        f.write_str(", ")?;
      }
      match event.char() {
        Some(symbol) => write!(f, "{symbol:?} (word {})", event.word_index())?,
        None => write!(f, "a boundary mark (word {})", event.word_index())?,
      }
    }
    Ok(())
  }
}

/// Failure computing per-chunk CTC emissions or a full word-level
/// alignment (design spec §8's `AlignError`).
///
/// Wraps [`asry::emissions::EmissionsError`] — asry's own per-chunk
/// alignment failures from the emissions seam
/// ([`crate::audio::align::aligner::Aligner::align_chunk`] feeds
/// `Encoder::emissions`'s output through
/// `prepare`/`encode_with`/`finish`) — alongside the CoreML-sourced variants
/// `Encoder::emissions` itself can raise and the
/// [`asry::emissions::SpanError`] the VAD bridge can produce. The
/// CoreML-sourced shape (`Prediction` + `Tensor`) mirrors `dia-coreml`'s
/// analogous `InferError` (`crates/dia-coreml/src/error/mod.rs`) rather than
/// design spec §8's literal "one CoreML-sourced variant" —
/// `crate::Model::predict_with` and
/// `crate::MultiArray::from_slice`/`copy_into` fail with two distinct
/// foreign error types ([`crate::PredictionError`] and
/// [`crate::TensorError`] respectively), and collapsing both into one
/// variant would mean re-stringifying one of them instead of preserving it
/// as a typed `#[from]` source, the exact thing this module's opening
/// paragraph rules out.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum AlignError {
  /// A per-chunk alignment failure from asry's emissions seam — stride /
  /// vocab / blank-id validation, a non-finite or positive log-probability
  /// from the encoder, tokenization, or abort. A refusal and an unalignable
  /// chunk never reach here: they are [`Self::Refused`] and
  /// [`Self::NoAlignmentPath`]; see the module doc.
  #[error(transparent)]
  Alignment(#[from] asry::emissions::EmissionsError),
  /// The caller's OOV policy refused the chunk: at least one decision it passed
  /// resolved a position `FailClosed`, so no word timings were produced.
  ///
  /// Carries every refused position ([`Refusal::events`]), read off the
  /// decisions the caller passed. A refusal is the caller's own policy at
  /// work, not a failure of the aligner: the text is the caller's to keep and
  /// only its word timings are missing. It is never an empty result, so it
  /// cannot be mistaken for [`Self::NoAlignmentPath`] or for a chunk with
  /// nothing to align.
  #[error("the OOV policy refused this chunk at {0}; no word timings were produced")]
  Refused(Refusal),
  /// The CTC lattice admits no alignment path for this chunk: its audio is too
  /// short for its tokens (one frame cannot carry three), a trellis boundary
  /// cell is non-finite, or the lattice overran its cell budget.
  ///
  /// Carries asry's diagnostic. Like [`Self::Refused`] it is an outcome of this
  /// chunk's data, not a broken setup: the text is the caller's to keep and only
  /// its word timings are missing. It is never an empty result, so it cannot be
  /// mistaken for a refusal or for a chunk with nothing to align.
  #[error("no alignment path for this chunk: {0}")]
  NoAlignmentPath(asry::emissions::EmissionsFailure),
  /// The VAD sub-segments were not in the chunk-local 1/16000 analysis
  /// timebase (or exceeded the representable sample range) when
  /// [`crate::audio::align::aligner::Aligner::align_chunk`] bridged them into
  /// [`asry::emissions::SpeechSpans`].
  #[error(transparent)]
  Span(#[from] asry::emissions::SpanError),
  /// The CoreML runtime failed to run the encoder.
  #[error("prediction failed: {0}")]
  Prediction(#[from] crate::PredictionError),
  /// A tensor failed to construct or view.
  #[error("tensor failed: {0}")]
  Tensor(#[from] crate::TensorError),
  /// `samples` exceeded the aligner's input window
  /// ([`Aligner::window_samples`](crate::audio::align::Aligner::window_samples)).
  #[error("input exceeds encoder window: {} samples > {} samples", .0.got(), .0.max())]
  InputTooLong(InputTooLong),
  /// The encoder returned an emission matrix that is **not log-probabilities**:
  /// at least one cell sits in the model's
  /// [`SentinelBand`](crate::audio::align::acoustic::SentinelBand), the band
  /// its contract says it emits in place of a log-probability. For the staged
  /// `base960h` that is fp16's saturation band, where a saturated fp16 `log(0)`
  /// lands (`-45440` on the Apple Neural Engine).
  ///
  /// This is the loud form of what used to be a silent one. The values are
  /// finite and negative, so they pass asry's own `finite ∧ <= 0` scan of a
  /// log-probability output untouched and would align to *plausible, wrong*
  /// timings (in the pre-truncation-fix measurement `ask` landed 881.6 ms early
  /// on `jfk.wav`), which is why the band is checked separately. See
  /// [`crate::audio::align::encode::DEFAULT_ENCODER_COMPUTE`] for the mechanism.
  /// Only a contract that carries a band raises this: a band is one artifact's
  /// measurement, and [`AcousticContract::new`](crate::audio::align::acoustic::AcousticContract::new)
  /// carries none.
  ///
  /// The corruption is a defect of the **model artifact**, not of the caller's
  /// audio: no input makes a *correctly-converted* artifact produce it. But on a
  /// *corrupted* artifact its DETECTION is input-dependent — this error fires
  /// only when the input drives a class posterior under the fp16 floor and so
  /// exposes the `log(0)` sentinel. Real speech can (measured `min ≈ -45440` on
  /// `jfk.wav`); 960,000 samples of digital silence (`min ≈ -8.55`) and a
  /// low-amplitude sine (`≈ -9.07`) stay ABOVE the band and pass clean even on
  /// the corrupt placement — the recorded evidence in
  /// `tests::emissions_reject_an_ane_corrupted_matrix`'s doc, and why real speech
  /// is load-bearing there. The fix is the placement named in this error, or a
  /// re-converted model; nothing in this crate can recover the underflowed cells.
  #[error(
    "encoder emissions are not log-probabilities: {} of {} cells are at or below {} \
     (min = {}), in the band ({:?}) the model's contract says it emits in place of a \
     log-probability — for the staged base960h, a saturated fp16 `log(0)`. The encoder was \
     scheduled on {:?}: an fp16 `softmax` then `log` tail underflows to it on the Apple Neural \
     Engine (the staged base960h's does, and its word timings shift by hundreds of \
     milliseconds). Load the encoder on \
     `coremlit::audio::align::encode::DEFAULT_ENCODER_COMPUTE` (the default) — or re-convert \
     the model with a fused `log_softmax` tail.",
    .0.cells(),
    .0.total(),
    .0.band().ceiling(),
    .0.min(),
    .0.band(),
    .0.compute(),
  )]
  CorruptEmissions(CorruptEmissions),
  /// A prediction's `emissions` tensor did not have the shape the load
  /// contract declared, `[1, frames, V]`.
  ///
  /// The load contract fixes what the graph DECLARES; this is the tensor a
  /// prediction actually returned, read before a single cell is copied. The
  /// copy itself checks only the element count, so a tensor with the same
  /// count and other axes — `[1, V, frames]`, say — would be copied without
  /// complaint and read as frames of `V` classes that are nothing of the kind:
  /// each token scored from a column that does not belong to it. See
  /// [`OutputShape`] for the two shapes.
  #[error(
    "the encoder's emissions came back with shape {:?}, not the declared {:?}; a tensor of \
     any other shape cannot be read as frames of vocabulary classes",
    .0.got(),
    .0.expected()
  )]
  OutputShape(OutputShape),
  /// The encoder returned an emission matrix that is **not normalized
  /// log-probabilities**: frame `row`'s `logsumexp` over the vocab axis is
  /// `logsumexp`, exceeding in magnitude the allowance
  /// [`crate::audio::align::encode::log_prob_sum_tolerance`] gives a head of its
  /// width. A genuine CTC log-probability frame sums to 1 in probability space,
  /// so its `logsumexp` is `0` (`ln Σ exp(log p_j) = ln Σ p_j = ln 1`); a
  /// whole-unit deviation means the tensor carries raw logits — or another
  /// un-normalized distribution — not the log-softmaxed output this crate's
  /// encoder contract requires.
  ///
  /// Unlike [`Self::CorruptEmissions`] — a placement-dependent fp16 underflow of
  /// THIS reviewed artifact — this is a **model-artifact contract** failure that
  /// no placement causes and no placement cures: a revision shipping a raw-logit
  /// CTC head (the *standard* wav2vec2 export, and what asry's own ONNX model
  /// emits) is rejected here rather than silently re-normalized by asry's
  /// log-softmax of a logit output and aligned on forever. It is the check that makes
  /// `Encoder::emissions`'s "these really are log-probs" a
  /// verified contract for any same-contract artifact loaded through the public
  /// API, not merely for the one reviewed here. The finite ∧ `<= 0` scan asry
  /// runs on a log-probability output cannot catch it: raw logits shifted wholly
  /// into `[-20, -10]`, or an all-zeros frame, are finite and `<= 0` on every
  /// cell yet no distribution at all. See
  /// [`crate::audio::align::encode::log_prob_sum_tolerance`] for the allowance and the
  /// [`crate::audio::align::encode`] module doc's "The normalization guard".
  #[error(
    "encoder emissions are not normalized log-probabilities: frame {} has logsumexp \
     {} over the vocab axis (tolerance ±{}), but a CTC log-probability frame \
     sums to 1 in probability space so its logsumexp is 0. This emission tensor carries raw \
     logits or another un-normalized distribution, not the log-softmaxed output alignkit's \
     encoder contract requires — most likely the model artifact was swapped for a raw-logit CTC \
     head (the standard wav2vec2 export). The encoder was scheduled on {:?}.",
    .0.row(),
    .0.logsumexp(),
    .0.tolerance(),
    .0.compute()
  )]
  UnnormalizedEmissions(UnnormalizedEmissions),
  /// The caller's OOV decisions were made for another request than the one
  /// being aligned.
  ///
  /// Returned by [`crate::audio::align::registry::AlignmentSet::align_chunk`]
  /// when its resolution was decided for `found` rather than the `requested`
  /// language the chunk is being aligned for, before any dispatch. An
  /// [`AlignerKey::Any`](crate::audio::align::registry::AlignerKey::Any) aligner
  /// serves every language, so one language's wildcard / fail-closed policy
  /// would otherwise apply silently under another. Decide the detection of the
  /// SAME language you pass to `align_chunk` — the one
  /// [`AlignmentSet::detect_oov`](crate::audio::align::registry::AlignmentSet::detect_oov)
  /// was asked for. See [`DecisionLanguage`].
  #[error(
    "the OOV decisions were made for language {:?} but the chunk is being aligned for \
     {:?}; decide the detection of the language you request (the one \
     `AlignmentSet::detect_oov` was asked for)",
    .0.found(),
    .0.requested()
  )]
  DecisionLanguage(DecisionLanguage),
  /// Returned by [`crate::audio::align::registry::AlignmentSet::align_chunk`]
  /// when another set made its resolution: a resolution answers the set whose
  /// detection it was decided from, on every route, and this is checked before
  /// the route is read. Without it a set with no aligner for the language would
  /// answer another set's decisions with its miss policy — a `FailClosed`
  /// decision skipped, or the mistake reported as an unsupported language. See
  /// [`ForeignResolution`].
  #[error(
    "this resolution was made by {}, and {} was asked to apply it: OOV decisions answer the \
     alignment set whose detection they were decided from; detect and decide the text with the \
     set that aligns it",
    .0.made_by(),
    .0.asked()
  )]
  ForeignResolution(ForeignResolution),
  /// Returned by [`crate::audio::align::registry::AlignmentSet::align_chunk`]
  /// when a resolution's shape is not its route's: an aligner's decisions on a
  /// registry miss, where no aligner reads the text, or none where an aligner
  /// does. A set cannot change once built, so its own resolution for the
  /// language it was asked always matches; a mismatch is refused by name rather
  /// than skipped or aligned without decisions. See [`MisroutedResolution`].
  #[error(
    "this resolution {}, and this request takes the route {:?}: a resolution applies only on \
     the route its detection took",
    .0.shape(),
    .0.route()
  )]
  MisroutedResolution(MisroutedResolution),
  /// No aligner is registered for the requested language, no
  /// [`AlignerKey::Any`](crate::audio::align::registry::AlignerKey::Any) fallback exists, and
  /// the registry's miss policy is
  /// [`AlignmentFallback::Error`](crate::audio::align::registry::AlignmentFallback).
  ///
  /// Returned by [`crate::audio::align::registry::AlignmentSet::align_chunk`]. Under the
  /// default `SkipChunk` policy a miss instead yields `Unaligned(Skipped)`
  /// (the ASR text survives, only per-word timings are dropped); this variant is
  /// the opt-in loud form, for a pipeline that wants a missing language to stop
  /// it rather than pass silently.
  ///
  /// Carries the requested language with no registered aligner and no `Any`
  /// fallback.
  #[error(
    "no aligner registered for language {0:?}, no `Any` fallback, and the registry miss \
     policy is `Error`"
  )]
  LanguageUnsupported(asry::Lang),
}

#[cfg(test)]
mod tests;