asry 0.1.0

Sans-I/O cut/batch/whisper/align state machine for speech-to-text indexing pipelines
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
//! `Aligner` — per-language wav2vec2 forced-alignment engine.

use core::{num::NonZeroU32, time::Duration};
use std::path::Path;

use mediatime::TimeRange;
use ort::session::{RunOptions, Session};
use smol_str::format_smolstr;

use crate::{
  core::AlignmentResult,
  runner::{
    RunnerError,
    aligner::{
      core::{
        AlignerCore, AlignerCoreLoadError, capture_vocab_size, detect_blank_token_id,
        detect_unk_token_id, detect_vocab_uppercase_only, load_tokenizer_with_compat,
        validate_word_delimiter_present,
      },
      emissions_api::{SpanError, SpeechCoverage, SpeechSpans},
      normalizer::DynTextNormalizer,
    },
  },
  time::SAMPLE_RATE_HZ,
  types::{AlignmentError, AlignmentFailure, Lang, WorkFailure, WorkerHangTimeout},
};

/// Re-express a feature-neutral core load failure as the `Aligner`'s
/// public load error, carrying the diagnostic through verbatim.
///
/// The core cannot name [`RunnerError::AlignerLoad`] — that variant is
/// itself `#[cfg(feature = "alignment")]` — so it returns its own
/// message-carrying error and this is the one place the `alignment`
/// front end lifts it back. `Aligner::from_paths`'s public error type
/// and message text are therefore unchanged by the de-gating.
fn lift_core_load_error(err: AlignerCoreLoadError) -> RunnerError {
  RunnerError::AlignerLoad {
    message: err.message().clone(),
  }
}

/// Convert the caller's chunk-local `TimeRange` sub-segments into the
/// timebase-free [`SpeechSpans`] the core works in.
///
/// The timebase check MOVED here; it did not change. `build_speech_mask`
/// used to reject a non-1/16000 timebase itself; now
/// `SpeechSpans::from_time_ranges` is strict about it and this function
/// re-expresses the rejection as the *identical*
/// `WorkFailure::Alignment(AlignmentError::ModelInference(..))` with the
/// *identical* message, so `Aligner::align`'s observable behaviour on a
/// wrong-timebase caller is unchanged.
fn spans_from_sub_segments(
  sub_segments: &[TimeRange],
  language: &Lang,
) -> Result<SpeechSpans, WorkFailure> {
  SpeechSpans::from_time_ranges(sub_segments).map_err(|e| match e {
    SpanError::Timebase { num, den, .. } => {
      WorkFailure::Alignment(AlignmentError::ModelInference(AlignmentFailure::new(
        format_smolstr!(
          "Aligner::align expects sub_segments in chunk-local 1/{} timebase, \
 got {}/{}; caller passed sub_segments in the wrong timebase \
 (samples will not match audio if we proceed).",
          SAMPLE_RATE_HZ,
          num,
          den,
        ),
        language.clone(),
      )))
    }
    other => WorkFailure::Alignment(AlignmentError::ModelInference(AlignmentFailure::new(
      format_smolstr!("invalid sub_segment: {other}"),
      language.clone(),
    ))),
  })
}

/// Default frame stride in 16 kHz samples: 320 = 20 ms, the
/// wav2vec2-base/large convention.
const DEFAULT_HOP_SAMPLES: NonZeroU32 = match NonZeroU32::new(320) {
  Some(v) => v,
  None => unreachable!(),
};

/// `u32` → `NonZeroU32` with the panic `Aligner`'s public `hop_samples`
/// setters have always had.
///
/// The core stores a `NonZeroU32` so a zero hop is unspellable there,
/// but `set_hop_samples` / `with_hop_samples` keep their public `u32`
/// signatures — an existing caller passing `0` still panics, with the
/// same message, at the same moment.
const fn nonzero_hop(value: u32) -> NonZeroU32 {
  assert!(value > 0, "hop_samples must be > 0");
  match NonZeroU32::new(value) {
    Some(v) => v,
    None => unreachable!(),
  }
}

/// Per-language forced-alignment engine. Loads a wav2vec2 ONNX
/// model, its HuggingFace tokenizer, and the language's text
/// normaliser. Each instance is heavyweight (ONNX session +
/// tokenizer state); the [`crate::AlignmentSet`] registry keeps one
/// per registered language, gated behind `Mutex<Aligner>` so the
/// single alignment worker can drive any language without copying.
///
/// The ONNX front end of the sandwich: everything that is *not* the
/// encoder lives in [`AlignerCore`], which `EmissionsAligner` contains
/// too. Both front ends therefore run one implementation of the
/// preprocessing, the validators, and the composition, and neither can
/// drift from the other.
///
/// Fields are private; access is via getters per the findit-studio
/// convention.
///
/// **Concurrency.** `Aligner` is `Send` (every field is `Send`) but
/// not `Sync` (`ort::Session::run` requires `&mut self`). The
/// registry stores `Mutex<Aligner>` which collapses to a no-op lock
/// in the v1 single-worker case.
pub struct Aligner {
  session: Session,
  core: AlignerCore,
}

impl Aligner {
  /// Construct from on-disk paths.
  ///
  /// `model_path` points to a wav2vec2 ONNX export with input
  /// shape `(1, T)` (raw f32 samples) and output shape `(1, T',
  /// V)` (logits). `tokenizer_path` points to the matching
  /// HuggingFace `tokenizer.json`.
  ///
  /// The blank-token id is read from the tokenizer's `<pad>` /
  /// `[PAD]` entry (the standard wav2vec2 convention). If the
  /// model uses a non-standard blank token, override via a
  /// future `with_blank_token_id` method (not in v1 scope).
  ///
  /// `sample_rate` defaults to 16 000 (wav2vec2's universal
  /// pre-processing target). `hop_samples` defaults to 320 (=
  /// 20 ms @ 16 kHz, the wav2vec2-base/large convention).
  /// Custom-strided models may pass overrides via a future
  /// builder.
  ///
  /// Returns [`RunnerError::AlignerLoad`] on any I/O or parse
  /// failure.
  pub fn from_paths(
    language: Lang,
    model_path: &Path,
    tokenizer_path: &Path,
    normalizer: DynTextNormalizer,
  ) -> Result<Self, RunnerError> {
    let session = Session::builder()
      .map_err(|e| RunnerError::AlignerLoad {
        message: format_smolstr!("Session::builder failed: {e}"),
      })?
      .commit_from_file(model_path)
      .map_err(|e| RunnerError::AlignerLoad {
        message: format_smolstr!("commit_from_file({}) failed: {e}", model_path.display()),
      })?;
    let tokenizer = load_tokenizer_with_compat(tokenizer_path).map_err(lift_core_load_error)?;

    let blank_token_id =
      detect_blank_token_id(&tokenizer).ok_or_else(|| RunnerError::AlignerLoad {
        message: format_smolstr!(
          "tokenizer has no <pad> / [PAD] entry; cannot determine CTC blank token"
        ),
      })?;
    let unk_token_id = detect_unk_token_id(&tokenizer);
    // wav2vec2-base-960h's vocab is uppercase-only; en/de/fr CTC
    // checkpoints typically follow the same convention.
    let vocab_uppercase_only = detect_vocab_uppercase_only(&tokenizer);

    // When the normaliser declares `use_word_delimiter == true`
    // (the English-shape default), the tokenizer MUST expose a
    // `|` token. See [`validate_word_delimiter_present`] for the
    // rationale.
    validate_word_delimiter_present(&tokenizer, normalizer.use_word_delimiter())
      .map_err(lift_core_load_error)?;

    // Snapshot the tokenizer's vocab size (including added
    // tokens) so per-align validation can reject ORT outputs
    // whose `V` dim doesn't match — otherwise the per-token id
    // checks in `ctc_viterbi` would pass whenever the chunk's
    // tokens happen to fit, then read posteriors from
    // mis-aligned columns.
    //
    // `None` is unreachable here: `detect_blank_token_id` above
    // already required a `<pad>` / `[PAD]` / `<blank>` entry, so the
    // vocab has at least one item. Typed rather than asserted so a
    // future reordering fails with a diagnostic instead of a panic.
    let tokenizer_vocab_size =
      capture_vocab_size(&tokenizer).ok_or_else(|| RunnerError::AlignerLoad {
        message: format_smolstr!(
          "tokenizer reports a zero-size vocab; a CTC vocabulary must contain at least \
 the blank token"
        ),
      })?;

    Ok(Self {
      session,
      core: AlignerCore::from_parts(
        tokenizer,
        language,
        normalizer,
        DEFAULT_HOP_SAMPLES,
        blank_token_id,
        unk_token_id,
        vocab_uppercase_only,
        tokenizer_vocab_size,
        SpeechCoverage::DEFAULT,
        crate::runner::aligner::algorithm::compose::DEFAULT_MAX_INTRA_SILENT_RUN,
      ),
    })
  }

  /// Detected language for this aligner.
  pub const fn language(&self) -> &Lang {
    self.core.language()
  }

  /// Detect out-of-vocab characters in `text` against this
  /// aligner's wav2vec2 vocab + per-language normalizer,
  /// without making any policy decision. Returns events in
  /// the order [`tokenize_with_word_map`](crate::runner::aligner::algorithm::tokenize::tokenize_with_word_map)
  /// will encounter them — caller-supplied `&[ResolvedOov]`
  /// to `align_chunk_with_abort` (or via
  /// [`AlignWorkItem::oov_decisions`](crate::AlignWorkItem))
  /// must be in the same order.
  ///
  /// Sans-I/O OOV resolution: the library produces events as
  /// data, the caller decides via pure functions in
  /// [`crate::core::oov`] (or a custom policy), then passes
  /// the decisions back as data. No callbacks, no traits the
  /// library holds.
  ///
  /// Returns an empty vec for in-vocab text. Returns an error
  /// only on tokenizer-engine failures or normalizer rejection
  /// (`NormalizationError::EmptyText` for punctuation-only
  /// input is converted to an empty event vec — there's
  /// nothing to align, so nothing to decide).
  pub fn detect_oov(
    &self,
    text: &str,
  ) -> Result<Vec<crate::core::OovEvent>, crate::types::WorkFailure> {
    self.core.detect_oov(text)
  }

  /// Audio sample rate the model expects. Hardcoded to 16 kHz
  /// for wav2vec2; non-16 kHz models are not supported in v1
  /// (the silence mask, frame timebase, and stride checks all
  /// assume `SAMPLE_RATE_HZ`). Flagged that
  /// the previous `set_sample_rate` / `with_sample_rate`
  /// overrides mutated `self.sample_rate` but were never read
  /// downstream — a caller setting a non-16 kHz value got
  /// plausible-but-wrong masks and word timestamps instead of
  /// a configuration error. The setters were removed; the
  /// getter survives as informational ("what does this aligner
  /// expect").
  pub const fn sample_rate(&self) -> u32 {
    SAMPLE_RATE_HZ
  }

  /// Frame stride in 16 kHz samples (320 = 20 ms by default).
  pub const fn hop_samples(&self) -> u32 {
    self.core.hop_samples().get()
  }

  /// CTC blank-token id detected at construction time.
  pub const fn blank_token_id(&self) -> u32 {
    self.core.blank_token_id()
  }

  /// Set [`Self::hop_samples`].
  ///
  /// # Panics
  ///
  /// Panics if `value == 0`. A zero hop would collapse the
  /// frame→sample conversion in `compose_words` (every word
  /// would land at the chunk's first sample), corrupting word
  /// timings silently. Fail fast.
  ///
  /// The core stores a `NonZeroU32`, but this signature and this
  /// panic are unchanged: an existing caller passing `0` still gets
  /// the same message, at the same moment.
  pub const fn set_hop_samples(&mut self, value: u32) {
    self.core.set_hop_samples(nonzero_hop(value));
  }

  /// Builder-style override for [`Self::hop_samples`].
  ///
  /// # Panics
  ///
  /// Panics if `value == 0`. See [`Self::set_hop_samples`].
  pub const fn with_hop_samples(mut self, value: u32) -> Self {
    self.core.set_hop_samples(nonzero_hop(value));
    self
  }

  /// Minimum `speech_emissions / total_emissions` ratio
  /// required for a word to survive the alignment composer's
  /// post-pass. Default: `0.5` (`DEFAULT_MIN_SPEECH_COVERAGE`).
  pub const fn min_speech_coverage(&self) -> f32 {
    self.core.min_speech_coverage().get()
  }

  /// Set [`Self::min_speech_coverage`].
  ///
  /// `value` is coerced to a valid threshold rather than rejected:
  ///
  /// - finite values in `[0.0, 1.0]` are stored as-is
  /// - values above `1.0` (incl. `+∞`) clamp to `1.0`
  /// - values below `0.0` (incl. `-∞`) clamp to `0.0`
  /// - `NaN` resets to
  /// [`DEFAULT_MIN_SPEECH_COVERAGE`](crate::runner::aligner::algorithm::compose::DEFAULT_MIN_SPEECH_COVERAGE)
  /// (`0.5`)
  ///
  /// Flagged the prior permissive behaviour
  /// ("values are stored verbatim — out-of-range values
  /// effectively disable the coverage check") as a footgun: a
  /// config typo of `1.5` instead of `0.5` would silently drop
  /// every word, since the post-pass discards any word with
  /// `coverage < min_speech_coverage` and no word can exceed
  /// `1.0`. Clamping makes those configurations land on the
  /// nearest valid threshold instead.
  pub const fn set_min_speech_coverage(&mut self, value: f32) {
    self
      .core
      .set_min_speech_coverage(SpeechCoverage::clamped(value));
  }

  /// Builder-style override for [`Self::min_speech_coverage`].
  ///
  /// Coerces `value` into a valid threshold; see
  /// [`Self::set_min_speech_coverage`] for the rules.
  pub const fn with_min_speech_coverage(mut self, value: f32) -> Self {
    self
      .core
      .set_min_speech_coverage(SpeechCoverage::clamped(value));
    self
  }

  /// Maximum allowed contiguous silent run inside a word's
  /// bounding span. Default: 80 ms
  /// (`DEFAULT_MAX_INTRA_SILENT_RUN`).
  pub const fn max_intra_silent_run(&self) -> Duration {
    self.core.max_intra_silent_run()
  }

  /// Set [`Self::max_intra_silent_run`].
  pub const fn set_max_intra_silent_run(&mut self, value: Duration) {
    self.core.set_max_intra_silent_run(value);
  }

  /// Builder-style override for [`Self::max_intra_silent_run`].
  pub const fn with_max_intra_silent_run(mut self, value: Duration) -> Self {
    self.core.set_max_intra_silent_run(value);
    self
  }

  /// Convenience public alignment entrypoint. Constructs a
  /// fresh, never-flipped abort flag and a fresh
  /// [`RunOptions`] internally, then delegates to the
  /// cancellable [`Self::align_chunk_with_abort`].
  ///
  /// **No cancellation is possible through this method** — the
  /// abort flag and `RunOptions` are owned internally and a
  /// stuck ORT inference will block the caller's thread until
  /// it returns naturally. For runtimes that need timeout /
  /// cancellation (web servers, daemons, batch pipelines under
  /// SIGINT), call [`Self::align_chunk_with_abort`] with
  /// caller-owned handles.
  ///
  /// Inputs match [`Self::align`] minus the
  /// `abort_flag` / `run_options` infrastructure. See that
  /// method's doc-comment for argument semantics.
  ///
  /// Returns
  /// [`WorkFailure::Alignment`](crate::types::WorkFailure::Alignment)
  /// with variant
  /// [`AlignmentError::ModelInference`](crate::types::AlignmentError::ModelInference)
  /// if [`RunOptions::new`] fails (rare; ORT initialisation
  /// hiccup).
  pub fn align_chunk<F>(
    &mut self,
    samples: &[f32],
    sub_segments: &[TimeRange],
    text: &str,
    chunk_first_sample_in_stream: u64,
    samples_to_output_range: F,
  ) -> Result<AlignmentResult, WorkFailure>
  where
    F: Fn(u64, u64) -> TimeRange,
  {
    let abort_flag = core::sync::atomic::AtomicBool::new(false);
    let run_options = RunOptions::new().map_err(|e| {
      WorkFailure::Alignment(AlignmentError::ModelInference(AlignmentFailure::new(
        format_smolstr!("RunOptions::new failed: {e:?}"),
        self.core.language().clone(),
      )))
    })?;
    // Default OOV policy for the no-abort entrypoint:
    // detect events first, apply the historical default
    // (`alphanumeric → wildcard, pronounced → fail-closed`).
    // Power users that want `wildcard_all_decisions` or a
    // custom policy should use `align_chunk_with_abort` and
    // supply explicit decisions.
    let oov_events = self.detect_oov(text)?;
    let oov_decisions = crate::core::default_oov_decisions(&oov_events);
    // Self-generated decisions, so they carry this aligner's language by
    // construction; naming it as the key is a tautology here, and that is
    // exactly the point — there is no call path into the core that does
    // not state one.
    let expected = self.core.language().clone();
    self.align(
      samples,
      sub_segments,
      text,
      chunk_first_sample_in_stream,
      samples_to_output_range,
      &abort_flag,
      &run_options,
      &oov_decisions,
      &expected,
    )
  }

  /// Cancellable alignment entrypoint: caller owns the
  /// `abort_flag` and `RunOptions`. Use this when your
  /// runtime needs to stop in-flight inference — flip
  /// `abort_flag` from any thread and the aligner returns at
  /// the next pipeline boundary (silence mask, normalise,
  /// encode, trellis, compose). For ORT mid-call cancellation,
  /// call `run_options.terminate()` from another thread; ORT
  /// then unwinds `Session::run_with_options`.
  ///
  /// introduced this so the
  /// public Sans-I/O alignment path has a documented
  /// cancellation surface. [`Self::align_chunk`]
  /// owned both handles internally, leaving callers no way to
  /// recover from a stuck inference.
  ///
  /// `RunOptions` lives in [`crate::ort::session::RunOptions`].
  /// Construct one per align call (or share a pool — `terminate`
  /// is process-wide for the underlying ORT graph).
  #[allow(
    clippy::too_many_arguments,
    reason = "7 args carry independent semantic inputs (audio, \
 sub_segments, text, chunk anchor, timebase bridge, \
 abort flag, run options); each comes from a different \
 upstream pass"
  )]
  pub fn align_chunk_with_abort<F>(
    &mut self,
    samples: &[f32],
    sub_segments: &[TimeRange],
    text: &str,
    chunk_first_sample_in_stream: u64,
    samples_to_output_range: F,
    abort_flag: &core::sync::atomic::AtomicBool,
    run_options: &RunOptions,
    // Caller-resolved per-OOV-event decisions. See
    // `Self::align`'s `oov_decisions` parameter and
    // `crate::core::oov` for the full Sans-I/O resolution
    // flow.
    oov_decisions: &[crate::core::ResolvedOov],
  ) -> Result<AlignmentResult, WorkFailure>
  where
    F: Fn(u64, u64) -> TimeRange,
  {
    // No `Any` fallback at this layer — `align_chunk_with_abort` is
    // bound to a specific `Aligner`, so `self.language` IS the key the
    // caller's OOV policy was resolved against. The check itself lives
    // in `AlignerCore::prepare` now (so the emissions front end gets it
    // too); this call site's only job is to name the right key.
    let expected = self.core.language().clone();
    self.align(
      samples,
      sub_segments,
      text,
      chunk_first_sample_in_stream,
      samples_to_output_range,
      abort_flag,
      run_options,
      oov_decisions,
      &expected,
    )
  }

  /// Crate-private alignment entrypoint.
  ///
  /// Inputs:
  /// - `samples`: the chunk's 16 kHz f32 mono audio.
  /// - `sub_segments`: VAD sub-segments **in chunk-local 1/16000
  /// timebase**, so `start_pts()` / `end_pts()` are chunk-local
  /// 16 kHz sample indices in `[0, samples.len()]`. The silence
  /// mask in step 0 (and `build_speech_frames` in step 7) reads
  /// the PTS values directly as sample offsets — they are NOT
  /// in any output / wall-clock timebase. Out-of-range PTS get
  /// clamped to `[0, samples.len()]`. The internal worker dispatch
  /// path (`managed_transcriber.rs`) converts output-timebase
  /// sub-segments to this form before calling. External callers
  /// that drive `align_chunk` (parity / benchmarking tooling)
  /// must respect the same contract; a non-1/16000 timebase
  /// trips a `debug_assert`.
  /// - `text`: Whisper's transcribed text.
  /// - `chunk_first_sample_in_stream`: the chunk's first 16 kHz
  /// sample index in stream coordinates (used to convert
  /// wav2vec2 frame indices back to stream sample indices).
  /// - `samples_to_output_range`: callback bridging stream sample
  /// indices to output-timebase `TimeRange`s. The core's
  /// `SampleBuffer::samples_to_output_range` is `pub(crate)`;
  /// the worker constructs a closure over it.
  #[allow(
    clippy::too_many_arguments,
    reason = "8 args, each carrying an independent semantic input \
 (audio buffer, sub-segments, transcript, chunk anchor, \
 timebase bridge closure, abort flag, run options); \
 clustering them into a struct adds indirection without \
 clarity gain since callers already pass them positionally"
  )]
  pub(crate) fn align<F>(
    &mut self,
    samples: &[f32],
    sub_segments: &[TimeRange],
    text: &str,
    chunk_first_sample_in_stream: u64,
    samples_to_output_range: F,
    abort_flag: &core::sync::atomic::AtomicBool,
    run_options: &RunOptions,
    // Caller-resolved per-OOV-event decisions, in the order
    // `detect_oov_events` would have produced them. Threaded through
    // to `tokenize_with_word_map`.
    oov_decisions: &[crate::core::ResolvedOov],
    // The language `oov_decisions` were resolved against — the caller's
    // POLICY key, which is not always `self.language()`. The dispatcher
    // may land a chunk on the multilingual `AlignerKey::Any` aligner,
    // whose own `Lang` is a registry detail; the decisions still carry
    // the REQUESTED language (`job.language`, or `run.language()` per
    // run). Validating against the fallback aligner's `Lang` instead
    // would reject every correct `AnyFallback` payload.
    expected_decision_language: &Lang,
  ) -> Result<AlignmentResult, WorkFailure>
  where
    F: Fn(u64, u64) -> TimeRange,
  {
    use crate::runner::aligner::algorithm::encode::encode_log_softmax;

    // Steps 0-2. Same body, same order, same short-circuits — it just
    // lives in the core now, where `EmissionsAligner` reaches it too.
    // The timebase check moved into the type: `SpeechSpans` carries no
    // timebase, so nothing downstream can silently ignore one. The
    // rejection is byte-identical to what `build_speech_mask` produced.
    let speech = spans_from_sub_segments(sub_segments, self.core.language())?;
    let prepared = self.core.prepare(
      samples,
      &speech,
      text,
      oov_decisions,
      expected_decision_language,
      abort_flag,
    )?;

    // Empty normalised text, or zero alignable tokens. Skip the
    // encoder entirely and surface the cached ASR transcript with
    // `words: []` rather than an `Event::Error` — alignment is
    // optional, not a data-loss path.
    if prepared.is_trivial() {
      return Ok(AlignmentResult::new(Vec::new()));
    }

    // Steps 3-4: the ONE hole in the sandwich. `encoder_input()` is
    // the silence-zeroed, 400-padded buffer the core built; ORT goes
    // here, CoreML goes here for `EmissionsAligner`.
    //
    // `RunOptions` stays a caller-threaded per-call parameter: ORT
    // termination is sticky, so a shared handle would let one
    // watchdog timeout poison every later chunk. See
    // `classify_encode_abort` for why terminate-induced encode errors
    // must surface as `WorkerHangTimeout`, not `ModelInferenceFailed`.
    let log_probs = encode_log_softmax(
      &mut self.session,
      prepared.encoder_input(),
      run_options,
      self.core.language(),
    )
    .map_err(|e| classify_encode_abort(abort_flag, e))?;

    // Steps 5-9: validators, pinned DP, composition. Consumes
    // `prepared`, so the geometry `finish` uses is the geometry
    // `prepare` derived — not a number this function could get wrong.
    self.core.finish(
      prepared,
      &log_probs,
      chunk_first_sample_in_stream,
      samples_to_output_range,
      abort_flag,
    )
  }
}

// `validate_direct_decision_languages` MOVED into `AlignerCore` as
// `validate_decision_languages`, and `AlignerCore::prepare` now runs it
// unconditionally against a caller-named key.
//
// It was ONE of the shared guards still living only in the ORT front end,
// which meant `EmissionsAligner` — the other front end of the same core —
// silently did not have it. It was NOT the last: the seam's `prepare` also
// handed `AlignerCore` a permanently-false abort flag, leaving every
// prepare-stage cancellation poll dead on that path. Both are the same
// defect class the sealed sandwich exists to close — a guard in the shared
// core fed a neutered input by one front end — and both now run through the
// core on the caller's real inputs: the decision key here, and the abort
// flag `EmissionsAligner::prepare` now threads through instead of a `never`.
// This front end's remaining job is to name its key
// (`self.core.language()`, since a bound aligner has no requested-language
// concept); the dispatcher names its own.

/// Classify an `encode_log_softmax` failure based on whether the
/// alignment watchdog already flipped `abort_flag` (Codex
/// ).
///
/// The watchdog cancels in-flight ORT inference by calling
/// `RunOptions::terminate()`. ORT then returns
/// `Session::run_with_options` with an `Err`. If the caller
/// just `?`-propagates that, the failure surfaces as
/// `::ModelInferenceFailed` (looks like a
/// broken backend or bad model) instead of
/// `WorkFailure::WorkerHangTimeout` (the contract the watchdog
/// publishes — alerts and retry policy hang off this kind).
/// Promote terminate-induced errors to `WorkerHangTimeout`
/// when `abort_flag` is set; otherwise pass through unchanged
/// (so genuine model errors keep their `ModelInferenceFailed`
/// classification).
fn classify_encode_abort(
  abort_flag: &core::sync::atomic::AtomicBool,
  err: WorkFailure,
) -> WorkFailure {
  use core::sync::atomic::Ordering;
  if abort_flag.load(Ordering::Relaxed) {
    WorkFailure::WorkerHang(WorkerHangTimeout::new(
      crate::types::WorkerKind::Alignment,
      core::time::Duration::ZERO,
    ))
  } else {
    err
  }
}

// `DEFAULT_ALIGN_TIMEOUT` was the per-job timeout the legacy
// `WhisperPool` / `ManagedTranscriber` watchdog used; both
// removed in the Sans-I/O pivot. Cancellation lives entirely on
// the caller's side now (`abort_flag` + `RunOptions::terminate`).
// Constant deleted rather than kept as a dead public-crate item.

#[cfg(test)]
mod tests {
  use super::*;
  use crate::runner::aligner::test_fixtures::fixture_or_panic;

  /// when the
  /// alignment watchdog flips `abort_flag` and ORT returns an
  /// error from terminate(), the encode-failure classifier
  /// must promote it to `WorkerHangTimeout`, not pass it
  /// through as `ModelInferenceFailed`. Live ORT termination
  /// is too heavy for a unit test, but the classifier itself
  /// is a pure function.
  #[test]
  fn classify_encode_abort_promotes_to_timeout_when_aborted() {
    use core::sync::atomic::AtomicBool;
    let aborted = AtomicBool::new(true);
    let original = WorkFailure::Alignment(AlignmentError::ModelInference(AlignmentFailure::new(
      "ort terminate".into(),
      Lang::En,
    )));
    let classified = classify_encode_abort(&aborted, original);
    match classified {
      WorkFailure::WorkerHang(ref t) if t.kind() == crate::types::WorkerKind::Alignment => {}
      other => {
        panic!("aborted-encode error must surface as WorkerHangTimeout(Alignment); got {other:?}",)
      }
    }
  }

  // The three `validate_direct_decision_languages` tests MOVED to
  // `core.rs`, next to `validate_decision_languages` — the function that
  // owns the rejection now, for BOTH front ends. Their assertions are
  // byte-identical; only the name being called changed.

  /// And the dual: a genuine model failure (no abort) must
  /// pass through unchanged, so callers don't get spurious
  /// timeout alerts for real backend bugs.
  #[test]
  fn classify_encode_abort_passes_through_when_not_aborted() {
    use core::sync::atomic::AtomicBool;
    let not_aborted = AtomicBool::new(false);
    let original = WorkFailure::Alignment(AlignmentError::ModelInference(AlignmentFailure::new(
      "ort genuine error".into(),
      Lang::En,
    )));
    let classified = classify_encode_abort(&not_aborted, original);
    match classified {
      WorkFailure::Alignment(AlignmentError::ModelInference(_)) => {}
      other => panic!("non-aborted encode error must pass through unchanged; got {other:?}"),
    }
  }

  fn analysis_tb() -> mediatime::Timebase {
    mediatime::Timebase::new(1, core::num::NonZeroU32::new(SAMPLE_RATE_HZ).unwrap())
  }

  /// The timebase check MOVED (into the span type) but did NOT change.
  /// `build_speech_mask` used to reject a non-1/16000 sub-segment
  /// itself; `SpeechSpans::from_time_ranges` is strict about it now and
  /// `spans_from_sub_segments` re-expresses the rejection as the
  /// identical `WorkFailure` variant with the identical message. Same
  /// assertions the mask's test made.
  #[test]
  fn build_speech_mask_errors_on_non_analysis_timebase() {
    // Promoted from the previous `debug_assert!`-only check: a
    // non-1/16000 timebase fails the chunk in BOTH debug and release.
    // Release builds silently misinterpreted (e.g.) a
    // millisecond-timebase PTS as a 16 kHz sample index, masking the
    // wrong samples and producing plausible-but-wrong word alignments.
    let ms_tb = mediatime::Timebase::new(1, core::num::NonZeroU32::new(1000).unwrap());
    let segs = [TimeRange::new(0, 100, ms_tb)];
    let err = spans_from_sub_segments(&segs, &Lang::En).expect_err("must error");
    match err {
      WorkFailure::Alignment(AlignmentError::ModelInference(payload)) => {
        let message = payload.message();
        assert!(
          message.contains("chunk-local 1/16000 timebase"),
          "error message must cite the contract; got: {message}"
        );
        assert!(
          message.contains("1/1000"),
          "error message must cite the offending timebase; got: {message}"
        );
      }
      other => panic!("expected ModelInference, got {other:?}"),
    }
  }

  #[test]
  fn build_speech_mask_errors_on_output_timebase() {
    // Codex's example was milliseconds (1/1000); a 1/48000
    // (output-rate) PTS is the more realistic foot-gun: a production
    // caller passing the output-timebase ranges they were going to
    // emit, instead of converting back to chunk-local 1/16000. Same
    // fail-loud behaviour required.
    let out_tb = mediatime::Timebase::new(1, core::num::NonZeroU32::new(48_000).unwrap());
    let segs = [TimeRange::new(0, 1000, out_tb)];
    let err = spans_from_sub_segments(&segs, &Lang::En).expect_err("must error");
    assert!(matches!(err, WorkFailure::Alignment(_)));
  }

  /// The analysis timebase passes through and yields the same spans the
  /// mask always masked.
  #[test]
  fn spans_from_sub_segments_accepts_the_analysis_timebase() {
    let segs = [TimeRange::new(2, 5, analysis_tb())];
    let spans = spans_from_sub_segments(&segs, &Lang::En).expect("1/16000 is the contract");
    assert_eq!(spans.as_slice().len(), 1);
    assert_eq!(spans.as_slice()[0].start(), 2);
    assert_eq!(spans.as_slice()[0].end(), 5);
  }

  /// The de-gating must not move `Aligner::from_paths`'s observable
  /// error. The core returns its own message-carrying load error;
  /// `lift_core_load_error` puts it back into
  /// `RunnerError::AlignerLoad` with the diagnostic byte-identical.
  /// This pins the lift, so the message a caller reads for (e.g.) a
  /// missing `|` delimiter is the same string it was before the guards
  /// moved out of this file.
  #[test]
  fn lift_core_load_error_preserves_variant_and_message() {
    let core_err = AlignerCoreLoadError::new(
      "tokenizer is missing the `|` word-delimiter token, but the language's normaliser \
 declared `use_word_delimiter = true`."
        .into(),
    );
    let expected = core_err.message().clone();
    let RunnerError::AlignerLoad { message } = lift_core_load_error(core_err) else {
      panic!("core load failures must surface as RunnerError::AlignerLoad");
    };
    assert_eq!(
      message, expected,
      "the diagnostic must cross the front-end boundary verbatim"
    );
  }

  #[test]
  fn aligner_is_send_not_sync() {
    // Aligner is Send (each field — Session, Tokenizer, Lang,
    // DynTextNormalizer, primitives — is Send). It must not
    // be Sync because Session::run requires &mut self.
    fn assert_send<T: Send>() {}
    // We can't easily assert !Sync at the type level without
    // negative trait bounds; the Mutex<Aligner> in
    // AlignmentSet is the runtime check.
    assert_send::<Aligner>();
  }

  /// Regression: punctuation-only ASR text normalises to empty,
  /// but alignment must NOT turn the successful ASR transcript
  /// into `Event::Error`. The fix short-circuits `EmptyText` to
  /// `Ok(empty AlignmentResult)` inside `Aligner::align`; this
  /// test exercises that path without ONNX inference (the
  /// short-circuit returns before `encode_log_softmax` runs).
  ///
  /// Needs the English wav2vec2 fixture to construct the `Aligner`.
  /// Runs when `build.rs` fetched it (`asry_w2v_en`); reported as
  /// *ignored* when it didn't. Never a silent pass — see
  /// [`crate::runner::aligner::test_fixtures`].
  #[test]
  #[cfg_attr(
    not(asry_w2v_en),
    ignore = "needs the English wav2vec2 fixture: ASRY_FETCH_W2V=en cargo test --features alignment"
  )]
  fn empty_normalised_text_returns_empty_alignment_result() {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::{normalizers::EnglishNormalizer, test_fixtures::english_aligner};

    let mut aligner = english_aligner(Box::new(EnglishNormalizer::new()));

    // 16 kHz silence buffer — never read because `EmptyText`
    // short-circuits before encode runs.
    let samples = vec![0.0_f32; 16_000];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");

    // Punctuation-only input → EnglishNormalizer returns
    // `EmptyText`; align must surface as Ok(empty), not Err.
    let result = aligner
      .align(
        &samples,
        &sub_segments,
        /* text: */ "!!!...",
        /* chunk_first_sample_in_stream: */ 0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &Lang::En,
      )
      .expect("EmptyText must short-circuit to Ok, not propagate as AlignmentFailed");
    assert!(
      result.words().is_empty(),
      "empty normalisation must yield zero words; got {:?}",
      result.words()
    );
  }

  /// A chunk too short to admit any CTC path is an **`Err`** at this
  /// layer — `NoAlignmentPath`, naming the degenerate trellis.
  ///
  /// # The contract has two layers, and this is the lower one
  ///
  /// There is no sub-400-sample short-circuit in `Aligner::align`, and
  /// there never has been. `AlignerCore::prepare` zero-pads a short
  /// slice up to wav2vec2's 400-sample receptive field and encodes it
  /// (`core.rs`), deliberately, for WhisperX parity — WhisperX's
  /// `align()` pads to 400 the same way (`alignment.py:243-247`), and
  /// the ort-free `EmissionsAligner` front end pads identically. 400
  /// samples yield exactly `T = 1` frame; `"hello world"` tokenises to
  /// 11 chars; CTC cannot thread 11 tokens through 1 frame, so
  /// `ctc_viterbi` reports `NoAlignmentPath`. That answer is correct,
  /// and it is the *general* guard (`t < num_tokens`), not a
  /// special case for short audio.
  ///
  /// `Ok(empty)` — "aligned successfully, zero words" — is the answer
  /// one layer **up**. `NoAlignmentPath` is classified *recoverable*
  /// by `alignment_pool`, which names "a too-short chunk" as its
  /// canonical cause, converts it to an empty `AlignmentResult`, keeps
  /// the ASR transcript, and logs the drop. See
  /// `alignment_pool::tests::too_short_chunk_recovers_to_empty_result`,
  /// which pins that half against this exact input.
  ///
  /// Collapsing the two would be a regression, not a simplification:
  /// an `Ok(empty)` manufactured *inside* the aligner is
  /// indistinguishable from a genuine zero-word alignment, so the pool
  /// could no longer tell "alignment was dropped" from "alignment
  /// found nothing" — the very distinction it goes out of its way to
  /// log for operators.
  ///
  /// # What this test used to say
  ///
  /// It asserted `Ok(empty)` *here*, at the aligner layer, on the
  /// theory that a guard rejected sub-400 chunks before encode. No
  /// such guard was ever written. The assertion was wrong from the
  /// initial commit and it never once executed — it sat behind the
  /// vacuous fixture gate, reporting `ok` in 0.00s. Its first genuine
  /// run failed. The code was right; the test was not.
  #[test]
  #[cfg_attr(
    not(asry_w2v_en),
    ignore = "needs the English wav2vec2 fixture: ASRY_FETCH_W2V=en cargo test --features alignment"
  )]
  fn sub_400_sample_chunk_surfaces_no_alignment_path() {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::{normalizers::EnglishNormalizer, test_fixtures::english_aligner};

    let mut aligner = english_aligner(Box::new(EnglishNormalizer::new()));

    // 200 samples at 16 kHz = 12.5 ms. Padded up to 400 by
    // `prepare`, which the encoder turns into exactly one frame.
    let samples = vec![0.0_f32; 200];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");

    // Normalises and tokenises fine — 11 chars, `hello|world`. It is
    // the trellis that has nowhere to put them.
    let err = aligner
      .align(
        &samples,
        &sub_segments,
        /* text: */ "hello world",
        /* chunk_first_sample_in_stream: */ 0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &Lang::En,
      )
      .expect_err(
        "a 1-frame trellis cannot admit an 11-token CTC path; the aligner must say so, not \
         manufacture an Ok(empty) that the pool could not distinguish from a real zero-word \
         alignment",
      );

    let WorkFailure::Alignment(AlignmentError::NoAlignmentPath(failure)) = err else {
      panic!(
        "a too-short chunk must surface as the RECOVERABLE `NoAlignmentPath` — that is what \
         `alignment_pool` keys the ASR-text-preserving recovery off. Any other variant is \
         classified fatal and would destroy the transcript. Got: {err:?}"
      );
    };

    // Pin the geometry, not just the variant: `T=1` is the pad-to-400
    // behaviour (400 samples, one frame), and `11 chars` is the
    // tokenisation of `"hello world"` (10 letters + the `|`
    // delimiter). Assert them so a regression in *either* — a silently
    // dropped pad, a changed delimiter policy — fails here rather than
    // quietly producing the right error variant for the wrong reason.
    let message = failure.message();
    assert!(
      message.contains("audio too short"),
      "the failure must name its cause; got: {message}"
    );
    assert!(
      message.contains("T=1 frames"),
      "400 padded samples must yield exactly one frame; got: {message}"
    );
    assert!(
      message.contains("11 chars"),
      "`hello world` must tokenise to 11 chars (10 letters + `|`); got: {message}"
    );
    assert_eq!(
      *failure.language(),
      Lang::En,
      "the failure must carry the chunk's language for the pool's telemetry"
    );
  }

  /// Smoke test: load the Japanese wav2vec2 fixture (downloaded
  /// via `tests/parity_whisperx/python/fetch_align_model.py ja`
  /// — see `multi-lang-alignment` branch). Runs when `build.rs`
  /// fetched that fixture (`ASRY_FETCH_W2V=ja` ⇒ `asry_w2v_ja`);
  /// reported as *ignored* when it didn't, so a default `cargo test`
  /// run stays network/disk-free without ever claiming this passed.
  ///
  /// Verifies the multi-lang path end-to-end on the loader side:
  /// `Aligner::from_paths` accepts the jonatasgrosman tokenizer
  /// shape, the JapaneseNormalizer is wired up via
  /// `default_normalizer_for(Lang::Ja)`, and the empty-input
  /// short-circuit returns Ok(empty AlignmentResult) just like
  /// the English aligner.
  #[test]
  #[cfg_attr(
    not(asry_w2v_ja),
    ignore = "needs the Japanese wav2vec2 fixture: ASRY_FETCH_W2V=ja cargo test --features alignment"
  )]
  fn japanese_aligner_loads_and_short_circuits_on_empty_text() {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::default_normalizer_for;

    let model_path = fixture_or_panic(option_env!("ASRY_W2V_JA_MODEL"), "ASRY_W2V_JA_MODEL", "ja");
    let tokenizer_path = fixture_or_panic(
      option_env!("ASRY_W2V_JA_TOKENIZER"),
      "ASRY_W2V_JA_TOKENIZER",
      "ja",
    );

    let normalizer = default_normalizer_for(&Lang::Ja).expect("Ja normalizer must exist");
    let mut aligner = Aligner::from_paths(
      Lang::Ja,
      Path::new(model_path),
      Path::new(tokenizer_path),
      normalizer,
    )
    .expect("Aligner::from_paths(Ja)");

    let samples = vec![0.0_f32; 16_000];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");
    let result = aligner
      .align(
        &samples,
        &sub_segments,
        /* text: */ "!!!...",
        /* chunk_first_sample_in_stream: */ 0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &Lang::Ja,
      )
      .expect("Ja aligner empty-text must short-circuit Ok");
    assert!(result.words().is_empty());
  }

  /// Smoke test: load the Chinese wav2vec2 fixture. Mirrors the
  /// Japanese smoke test above — runs iff its fixture was fetched,
  /// *ignored* otherwise, and hard-fails if forced to run without one.
  #[test]
  #[cfg_attr(
    not(asry_w2v_zh),
    ignore = "needs the Chinese wav2vec2 fixture: ASRY_FETCH_W2V=zh cargo test --features alignment"
  )]
  fn chinese_aligner_loads_and_short_circuits_on_empty_text() {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::default_normalizer_for;

    let model_path = fixture_or_panic(option_env!("ASRY_W2V_ZH_MODEL"), "ASRY_W2V_ZH_MODEL", "zh");
    let tokenizer_path = fixture_or_panic(
      option_env!("ASRY_W2V_ZH_TOKENIZER"),
      "ASRY_W2V_ZH_TOKENIZER",
      "zh",
    );

    let normalizer = default_normalizer_for(&Lang::Zh).expect("Zh normalizer must exist");
    let mut aligner = Aligner::from_paths(
      Lang::Zh,
      Path::new(model_path),
      Path::new(tokenizer_path),
      normalizer,
    )
    .expect("Aligner::from_paths(Zh)");

    let samples = vec![0.0_f32; 16_000];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");
    let result = aligner
      .align(
        &samples,
        &sub_segments,
        "!!!...",
        0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &Lang::Zh,
      )
      .expect("Zh aligner empty-text must short-circuit Ok");
    assert!(result.words().is_empty());
  }

  /// Smoke test: load the Korean wav2vec2 fixture. Mirrors the
  /// Japanese / Chinese smoke tests above — runs iff its fixture was
  /// fetched, so a default `cargo test` run stays network/disk-free
  /// and reports this as *ignored* rather than as a pass.
  ///
  /// Verifies the multi-lang path end-to-end on the loader side:
  /// `Aligner::from_paths` accepts the kresnik tokenizer
  /// shape, the KoreanNormalizer is wired up via
  /// `default_normalizer_for(Lang::Ko)`, and the empty-input
  /// short-circuit returns Ok(empty AlignmentResult).
  #[test]
  #[cfg_attr(
    not(asry_w2v_ko),
    ignore = "needs the Korean wav2vec2 fixture: ASRY_FETCH_W2V=ko cargo test --features alignment"
  )]
  fn korean_aligner_loads_and_short_circuits_on_empty_text() {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::default_normalizer_for;

    let model_path = fixture_or_panic(option_env!("ASRY_W2V_KO_MODEL"), "ASRY_W2V_KO_MODEL", "ko");
    let tokenizer_path = fixture_or_panic(
      option_env!("ASRY_W2V_KO_TOKENIZER"),
      "ASRY_W2V_KO_TOKENIZER",
      "ko",
    );

    let normalizer = default_normalizer_for(&Lang::Ko).expect("Ko normalizer must exist");
    let mut aligner = Aligner::from_paths(
      Lang::Ko,
      Path::new(model_path),
      Path::new(tokenizer_path),
      normalizer,
    )
    .expect("Aligner::from_paths(Ko)");

    let samples = vec![0.0_f32; 16_000];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");
    let result = aligner
      .align(
        &samples,
        &sub_segments,
        "!!!...",
        0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &Lang::Ko,
      )
      .expect("Ko aligner empty-text must short-circuit Ok");
    assert!(result.words().is_empty());
  }

  /// Helper for the Latin-language smoke tests below. Loads the
  /// per-language wav2vec2 fixture, wires in the per-language
  /// `LatinNormalizer` via `default_normalizer_for`, and exercises the
  /// empty-text short-circuit path that doesn't require ONNX inference.
  ///
  /// This used to return `Option<()>` and bail via `?` on an absent
  /// fixture, and every caller discarded the result with `let _ = ..`.
  /// So all five Latin tests reported `ok` while doing nothing at all.
  /// It now panics through [`fixture_or_panic`] instead: each caller is
  /// `#[ignore]`d unless its own fixture was fetched, so the *unrun*
  /// case is reported as ignored, and the *run-without-fixture* case is
  /// reported as a failure. Neither is reported as a pass.
  fn smoke_latin_aligner(
    lang: Lang,
    fetch_code: &str,
    model_env: Option<&'static str>,
    model_var: &str,
    tokenizer_env: Option<&'static str>,
    tokenizer_var: &str,
  ) {
    use core::sync::atomic::AtomicBool;

    use mediatime::{TimeRange, Timebase};

    use crate::runner::aligner::default_normalizer_for;

    let model_path = fixture_or_panic(model_env, model_var, fetch_code);
    let tokenizer_path = fixture_or_panic(tokenizer_env, tokenizer_var, fetch_code);

    let normalizer = default_normalizer_for(&lang).expect("Latin lang must resolve a normalizer");
    let mut aligner = Aligner::from_paths(
      lang.clone(),
      Path::new(model_path),
      Path::new(tokenizer_path),
      normalizer,
    )
    .expect("Aligner::from_paths(Latin)");

    let samples = vec![0.0_f32; 16_000];
    let sub_segments: Vec<TimeRange> = Vec::new();
    let abort = AtomicBool::new(false);
    let run_options = ort::session::RunOptions::new().expect("RunOptions::new");
    let result = aligner
      .align(
        &samples,
        &sub_segments,
        /* text: */ "!!!...",
        /* chunk_first_sample_in_stream: */ 0,
        |start, end| {
          TimeRange::new(
            start as i64,
            end as i64,
            Timebase::new(1, core::num::NonZeroU32::new(16_000).unwrap()),
          )
        },
        &abort,
        &run_options,
        &[],
        &lang,
      )
      .expect("Latin aligner empty-text must short-circuit Ok");
    assert!(
      result.words().is_empty(),
      "{lang:?} aligner empty-text must yield zero words"
    );
  }

  /// Spanish smoke test.
  #[test]
  #[cfg_attr(
    not(asry_w2v_es),
    ignore = "needs the Spanish wav2vec2 fixture: ASRY_FETCH_W2V=es cargo test --features alignment"
  )]
  fn spanish_aligner_loads_and_short_circuits_on_empty_text() {
    smoke_latin_aligner(
      Lang::Es,
      "es",
      option_env!("ASRY_W2V_ES_MODEL"),
      "ASRY_W2V_ES_MODEL",
      option_env!("ASRY_W2V_ES_TOKENIZER"),
      "ASRY_W2V_ES_TOKENIZER",
    );
  }

  /// French smoke test.
  #[test]
  #[cfg_attr(
    not(asry_w2v_fr),
    ignore = "needs the French wav2vec2 fixture: ASRY_FETCH_W2V=fr cargo test --features alignment"
  )]
  fn french_aligner_loads_and_short_circuits_on_empty_text() {
    smoke_latin_aligner(
      Lang::Fr,
      "fr",
      option_env!("ASRY_W2V_FR_MODEL"),
      "ASRY_W2V_FR_MODEL",
      option_env!("ASRY_W2V_FR_TOKENIZER"),
      "ASRY_W2V_FR_TOKENIZER",
    );
  }

  /// German smoke test.
  #[test]
  #[cfg_attr(
    not(asry_w2v_de),
    ignore = "needs the German wav2vec2 fixture: ASRY_FETCH_W2V=de cargo test --features alignment"
  )]
  fn german_aligner_loads_and_short_circuits_on_empty_text() {
    smoke_latin_aligner(
      Lang::De,
      "de",
      option_env!("ASRY_W2V_DE_MODEL"),
      "ASRY_W2V_DE_MODEL",
      option_env!("ASRY_W2V_DE_TOKENIZER"),
      "ASRY_W2V_DE_TOKENIZER",
    );
  }

  /// Italian smoke test.
  #[test]
  #[cfg_attr(
    not(asry_w2v_it),
    ignore = "needs the Italian wav2vec2 fixture: ASRY_FETCH_W2V=it cargo test --features alignment"
  )]
  fn italian_aligner_loads_and_short_circuits_on_empty_text() {
    smoke_latin_aligner(
      Lang::It,
      "it",
      option_env!("ASRY_W2V_IT_MODEL"),
      "ASRY_W2V_IT_MODEL",
      option_env!("ASRY_W2V_IT_TOKENIZER"),
      "ASRY_W2V_IT_TOKENIZER",
    );
  }

  /// Portuguese smoke test.
  #[test]
  #[cfg_attr(
    not(asry_w2v_pt),
    ignore = "needs the Portuguese wav2vec2 fixture: ASRY_FETCH_W2V=pt cargo test --features alignment"
  )]
  fn portuguese_aligner_loads_and_short_circuits_on_empty_text() {
    smoke_latin_aligner(
      Lang::Pt,
      "pt",
      option_env!("ASRY_W2V_PT_MODEL"),
      "ASRY_W2V_PT_MODEL",
      option_env!("ASRY_W2V_PT_TOKENIZER"),
      "ASRY_W2V_PT_TOKENIZER",
    );
  }
}