coremlit 0.1.2

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
use super::*;

use asry::{
  emissions::{EmissionsAligner, EmissionsError, EnglishNormalizer},
  time::ANALYSIS_TIMEBASE,
};

use crate::audio::align::error::{Refusal, RefusedOov};

/// asry's default policy, over the registry's view of an event.
fn default_policy(event: &SetOovEvent<'_>) -> OovDecision {
  event.default_decision()
}

/// A policy refusing every event, over the registry's view of an event.
fn fail_closed_policy(_event: &SetOovEvent<'_>) -> OovDecision {
  OovDecision::FailClosed
}

// ---------------------------------------------------------------------
// Hermetic: registry key / fallback / miss semantics need no aligner.
// ---------------------------------------------------------------------

#[test]
fn aligner_key_distinguishes_lang_from_any() {
  assert_ne!(AlignerKey::Lang(Lang::En), AlignerKey::Any);
  assert_eq!(AlignerKey::Lang(Lang::En), AlignerKey::Lang(Lang::En));
  assert_ne!(AlignerKey::Lang(Lang::En), AlignerKey::Lang(Lang::Zh));
}

#[test]
fn aligner_key_hashes_consistently() {
  use std::collections::HashSet;
  let mut set = HashSet::new();
  set.insert(AlignerKey::Lang(Lang::En));
  set.insert(AlignerKey::Any);
  set.insert(AlignerKey::Lang(Lang::En)); // duplicate
  assert_eq!(set.len(), 2);
}

#[test]
fn fallback_default_is_skip_chunk() {
  assert_eq!(AlignmentFallback::default(), AlignmentFallback::SkipChunk);
}

// ---------------------------------------------------------------------
// The enum contract (mirrors `coremlit::audio::whisper::log::LogLevel`): as_str, a Display
// derived FROM as_str, a TOTAL FromStr, an opaque parse error, snake_case
// serde, and IsVariant. A fallback policy arrives from a config file or a CLI
// flag, so it has to survive a round trip through text — which it could not do
// in either direction before.
// ---------------------------------------------------------------------

// The roster the round-trip / spelling / serde tests below iterate is
// `AlignmentFallback::ALL`, GENERATED from the same one-row-per-variant table as
// the enum, its spellings and its parser (`define_alignment_fallback!`, F2). It
// can no longer fall behind the enum by construction — a variant that is not in
// `ALL` cannot exist — so the hand-listed roster and the compiler-checked
// exhaustive match this file used to carry (two structures that did not
// constrain each other, the finding) are gone: the macro grammar now rejects a
// variant with no spelling/parser at COMPILE time, which no test could.

#[test]
fn fallback_round_trips_through_its_own_text_form() {
  // THE contract, as one property over the exhaustive roster: for every variant,
  // `as_str` → `from_str` is the identity. Iterating ALL_FALLBACKS (kept complete
  // by `fallback_roster_is_exhaustive`) rather than a local slice means a new
  // variant added without a `from_str` arm fails here instead of silently becoming
  // unparseable.
  for &fallback in AlignmentFallback::ALL {
    let text = fallback.as_str();
    assert_eq!(
      text.parse::<AlignmentFallback>(),
      Ok(fallback),
      "`{text}` must parse back to the variant that produced it"
    );
    // Display is DERIVED from as_str (`#[display("{}", self.as_str())]`), so
    // the two can never drift apart — this pins that they are wired that way.
    assert_eq!(fallback.to_string(), text);
  }
}

#[test]
fn fallback_from_str_names_the_snake_case_spelling() {
  // The exact spellings, pinned per variant: they are the serde wire form and the
  // CLI/env form, so a rename is a breaking change and must be a deliberate one.
  // The wildcard-free `match` is the F3 tripwire — a new variant must pin its own
  // spelling here — and the loop over ALL_FALLBACKS checks every variant both
  // spells to and parses from that literal.
  for &fallback in AlignmentFallback::ALL {
    let spelling = match fallback {
      AlignmentFallback::SkipChunk => "skip_chunk",
      AlignmentFallback::Error => "error",
    };
    assert_eq!(
      fallback.as_str(),
      spelling,
      "as_str spelling for {fallback:?} drifted from its pinned wire form"
    );
    assert_eq!(
      spelling.parse::<AlignmentFallback>(),
      Ok(fallback),
      "`{spelling}` must parse back to {fallback:?}"
    );
  }
}

#[test]
fn fallback_from_str_is_total_and_rejects_everything_else() {
  // Total: every input has an answer, and an unknown one is an Err rather than
  // a panic or a silent default. A policy that quietly defaulted to SkipChunk
  // on a typo'd config value is exactly the failure this crate exists not to
  // have.
  for unknown in [
    "",
    "SkipChunk",
    "skip-chunk",
    "Error",
    "skip_chunk ",
    "fail",
  ] {
    assert!(
      unknown.parse::<AlignmentFallback>().is_err(),
      "`{unknown}` must not parse"
    );
  }
}

#[test]
fn fallback_is_variant_predicates() {
  assert!(AlignmentFallback::SkipChunk.is_skip_chunk());
  assert!(!AlignmentFallback::SkipChunk.is_error());
  assert!(AlignmentFallback::Error.is_error());
}

#[test]
fn aligner_key_is_variant_predicates() {
  assert!(AlignerKey::Lang(Lang::En).is_lang());
  assert!(!AlignerKey::Lang(Lang::En).is_any());
  assert!(AlignerKey::Any.is_any());
}

#[cfg(feature = "serde")]
#[test]
fn fallback_serde_uses_the_same_snake_case_spelling() {
  // One spelling across `as_str`, `FromStr` and serde for EVERY variant, or the
  // text form is not a round trip at all — a config file that serializes
  // `skip_chunk` and a CLI that parses `SkipChunk` is two vocabularies wearing one
  // type. The wildcard-free `match` is the F3 tripwire (a new variant must pin its
  // JSON here); the loop checks each variant serializes to that literal, matches
  // `as_str`, and deserializes back.
  for &fallback in AlignmentFallback::ALL {
    let expected_json = match fallback {
      AlignmentFallback::SkipChunk => r#""skip_chunk""#,
      AlignmentFallback::Error => r#""error""#,
    };
    let json = serde_json::to_string(&fallback).unwrap();
    assert_eq!(
      json, expected_json,
      "serde spelling for {fallback:?} drifted"
    );
    assert_eq!(json, format!("\"{}\"", fallback.as_str()));
    let back: AlignmentFallback = serde_json::from_str(&json).unwrap();
    assert_eq!(
      back, fallback,
      "{fallback:?} must deserialize back from its own JSON"
    );
  }
  // A non-snake_case spelling must NOT deserialize — the rename guard, unchanged.
  assert!(serde_json::from_str::<AlignmentFallback>(r#""SkipChunk""#).is_err());
}

#[test]
fn empty_set_misses_with_default_fallback() {
  let set = AlignmentSetBuilder::new().build();
  assert!(set.is_empty());
  assert_eq!(set.len(), 0);
  match set.lookup(&Lang::En) {
    AlignmentLookup::Miss(fallback) => assert_eq!(fallback, AlignmentFallback::SkipChunk),
    _ => panic!("expected Miss"),
  }
}

#[test]
fn empty_set_misses_with_error_fallback() {
  let set = AlignmentSetBuilder::new()
    .with_fallback(AlignmentFallback::Error)
    .build();
  assert_eq!(set.fallback(), AlignmentFallback::Error);
  match set.lookup(&Lang::Zh) {
    AlignmentLookup::Miss(fallback) => assert_eq!(fallback, AlignmentFallback::Error),
    _ => panic!("expected Miss"),
  }
}

#[test]
fn builder_set_fallback_in_place() {
  let mut builder = AlignmentSetBuilder::new();
  assert!(builder.is_empty());
  builder.set_fallback(AlignmentFallback::Error);
  assert_eq!(builder.build().fallback(), AlignmentFallback::Error);
}

/// **A miss reads no text, so it is never reported as a text found spelled
/// whole.** The detection names the requested language and holds no events at
/// all — `None`, not an empty list — and deciding it decides nothing.
#[test]
fn empty_set_detect_oov_on_miss_reads_nothing() {
  let set = AlignmentSetBuilder::new().build();
  let detection = set.detect_oov("anything", &Lang::En).unwrap();
  assert_eq!(detection.language(), &Lang::En);
  assert!(detection.events().is_none());
  let resolution = detection.decide(fail_closed_policy);
  assert_eq!(resolution.language(), &Lang::En);
  assert!(resolution.resolved().is_none());
}

// ---------------------------------------------------------------------
// F2: registry-owned alignment orchestration. The request binding and the
// miss policy are hermetic (no aligner, no model); the end-to-end proof that a
// cross-language request reaches encoding is model-gated below.
// ---------------------------------------------------------------------

/// **A resolution decided for another request is refused, on every route,
/// before the route decides anything.** On a miss the fallback would otherwise
/// answer for a language the decisions were not made for; the model-gated
/// `a_resolution_decided_for_another_request_is_refused_before_dispatch` pins the
/// aligner routes.
#[test]
fn a_resolution_decided_for_another_language_is_refused_on_a_miss_too() {
  for fallback in [AlignmentFallback::SkipChunk, AlignmentFallback::Error] {
    let set = AlignmentSetBuilder::new().with_fallback(fallback).build();
    let resolution = set
      .detect_oov("anything", &Lang::Zh)
      .expect("detect_oov")
      .decide(default_policy);
    let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
    let abort = AtomicBool::new(false);
    let err = set
      .align_chunk(&Lang::En, &[], &[], "anything", clock, &abort, resolution)
      .expect_err("decisions made for Zh do not answer an En request");
    assert!(
      matches!(
        err,
        AlignError::DecisionLanguage(ref e)
          if *e.requested() == Lang::En && *e.found() == Lang::Zh
      ),
      "{fallback}: {err:?}"
    );
  }
}

/// A registry miss's resolution: the request's language, no detection.
fn missed(set: &AlignmentSet, language: &Lang) -> SetResolution {
  set
    .detect_oov("anything", language)
    .expect("a miss detects nothing, and fails at nothing")
    .decide(default_policy)
}

#[test]
fn align_chunk_miss_skip_chunk_returns_empty_words() {
  // Empty registry, default SkipChunk policy: a miss is not an error, it drops
  // the timings and keeps going, and says so. No aligner is touched, so this is
  // hermetic.
  let set = AlignmentSetBuilder::new().build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let alignment = set
    .align_chunk(
      &Lang::Zh,
      &[],
      &[],
      "anything",
      clock,
      &abort,
      missed(&set, &Lang::Zh),
    )
    .expect("a SkipChunk miss is not an error");
  assert!(alignment.words().is_empty());
  assert!(matches!(alignment.cause(), Some(UnalignedCause::Skipped)));
}

#[test]
fn align_chunk_miss_error_returns_language_unsupported() {
  let set = AlignmentSetBuilder::new()
    .with_fallback(AlignmentFallback::Error)
    .build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let err = set
    .align_chunk(
      &Lang::Zh,
      &[],
      &[],
      "anything",
      clock,
      &abort,
      missed(&set, &Lang::Zh),
    )
    .unwrap_err();
  assert!(matches!(
    err,
    AlignError::LanguageUnsupported(ref language) if *language == Lang::Zh
  ));
}

#[test]
fn resolve_binds_the_requested_language_and_reports_the_miss() {
  // Empty registry: `resolve` binds the REQUESTED language, and `binding()`
  // reports the miss policy as data — no aligner involved, so hermetic.
  let set = AlignmentSetBuilder::new().build();
  let handle = set.resolve(&Lang::Zh);
  assert_eq!(handle.language(), &Lang::Zh);
  assert_eq!(
    handle.binding(),
    AlignmentBinding::Miss(AlignmentFallback::SkipChunk)
  );
}

#[test]
fn handle_align_chunk_is_the_guarded_set_align_chunk() {
  // The handle's `align_chunk` is `AlignmentSet::align_chunk` bound to the
  // requested language: a SkipChunk miss returns empty words, exactly as the set
  // method does, with no aligner touched (hermetic).
  let set = AlignmentSetBuilder::new().build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let handle = set.resolve(&Lang::Zh);
  let resolution = handle
    .detect_oov("anything")
    .expect("detect_oov")
    .decide(default_policy);
  let alignment = handle
    .align_chunk(&[], &[], "anything", clock, &abort, resolution)
    .expect("a SkipChunk miss is not an error");
  assert!(alignment.words().is_empty());
  assert!(matches!(alignment.cause(), Some(UnalignedCause::Skipped)));
}

// ---------------------------------------------------------------------
// Every event is judged under the requested language. asry stamps a
// detection's events with the language of the aligner that read the text, an
// `Any` fallback's own, so the registry shows its policy, its event list and
// its resolution each event under the request. Plant (the stamped language
// shown, as the raw events were handed on): the fallback laws fail.
// ---------------------------------------------------------------------

/// The bundled English seam, built without a model: how an English aligner
/// reads a text, and what asry stamps its events with.
fn english_seam() -> EmissionsAligner {
  EmissionsAligner::builder(Lang::En, crate::audio::align::vocab::tokenizer_json_bytes())
    .normalizer(Box::new(EnglishNormalizer::new()))
    .blank_token_id(crate::audio::align::vocab::BLANK_ID)
    .build()
    .expect("the bundled document builds a seam")
}

/// English wildcards and Korean fails closed: a policy keyed on the language
/// each event is shown under.
fn english_wildcard_korean_fail_closed(event: &SetOovEvent<'_>) -> OovDecision {
  match event.language() {
    Lang::Ko => OovDecision::FailClosed,
    _ => OovDecision::Wildcard,
  }
}

/// Korean wildcards and English fails closed.
fn korean_wildcard_english_fail_closed(event: &SetOovEvent<'_>) -> OovDecision {
  match event.language() {
    Lang::Ko => OovDecision::Wildcard,
    _ => OovDecision::FailClosed,
  }
}

/// The decisions `policy` makes for `text`, read by the English seam and held
/// for `requested`, with the language every event was shown under.
fn decided_under(
  requested: Lang,
  text: &str,
  policy: fn(&SetOovEvent<'_>) -> OovDecision,
) -> Vec<(Lang, OovDecision)> {
  let detection = english_seam().detect_oov(text).expect("detect_oov");
  assert!(
    detection
      .events()
      .iter()
      .all(|event| event.language() == &Lang::En),
    "asry stamps the language of the aligner that read the text"
  );
  let held = SetDetection {
    made_by: SetId::next(),
    language: requested.clone(),
    detection: Some(detection),
  };
  let shown = held.events().expect("an aligner read the text");
  assert!(shown.iter().all(|event| event.language() == &requested));
  let resolution = held.decide(policy);
  resolution
    .resolved()
    .expect("decided")
    .iter()
    .map(|resolved| (resolved.event().language().clone(), resolved.decision()))
    .collect()
}

/// **A fallback's detection is judged under the requested language.** The
/// English seam reads `Café AT&T b4d` and asry stamps its three events English;
/// held for a Korean request, the policy, the event list and the resolution see
/// each under Korean: an English-wildcard, Korean-fail-closed policy fails all
/// three closed, and a Korean-wildcard one wildcards them.
#[test]
fn a_fallback_detection_is_judged_under_the_requested_language() {
  let text = "Café AT&T b4d";
  assert_eq!(
    decided_under(Lang::Ko, text, english_wildcard_korean_fail_closed),
    vec![(Lang::Ko, OovDecision::FailClosed); 3]
  );
  assert_eq!(
    decided_under(Lang::Ko, text, korean_wildcard_english_fail_closed),
    vec![(Lang::Ko, OovDecision::Wildcard); 3]
  );
}

/// **An exact-language detection is judged as it was**: held for English, the
/// language it was read in, every event is shown under English, so the
/// English-wildcard policy wildcards all three and the Korean-wildcard one fails
/// them closed.
#[test]
fn an_exact_language_detection_is_judged_as_before() {
  let text = "Café AT&T b4d";
  assert_eq!(
    decided_under(Lang::En, text, english_wildcard_korean_fail_closed),
    vec![(Lang::En, OovDecision::Wildcard); 3]
  );
  assert_eq!(
    decided_under(Lang::En, text, korean_wildcard_english_fail_closed),
    vec![(Lang::En, OovDecision::FailClosed); 3]
  );
}

/// The view's equality and its debug form are the position and the language
/// shown: the stamped language takes no part in either.
#[test]
fn the_event_view_compares_and_prints_the_language_shown() {
  let detection = english_seam().detect_oov("b4d").expect("detect_oov");
  let held = SetDetection {
    made_by: SetId::next(),
    language: Lang::Ko,
    detection: Some(detection),
  };
  let shown = held.events().expect("read");
  let [four] = shown.as_slice() else {
    panic!("one event: {shown:?}");
  };
  assert_eq!(
    (four.char(), four.char_index(), four.word_index()),
    (Some('4'), 1, 0)
  );
  assert_eq!(four.default_decision(), OovDecision::Wildcard);
  let rendered = format!("{four:?}");
  assert!(rendered.contains("language: Ko"), "{rendered}");
  assert!(!rendered.contains("En"), "{rendered}");
  assert_eq!(*four, held.events().expect("read")[0]);
}

/// **A detection and its resolution print the requested language alone.** The
/// English seam's detection of `Café AT&T b4d`, held for a Korean request, and
/// the resolution decided from it: each debug form names Korean — the request
/// and every event under it — and never English, the stamp asry's detection and
/// resolution carry inside them.
///
/// Plant: the derived `Debug`, which prints asry's stamped values, and this law
/// fails.
#[test]
fn a_detection_and_its_resolution_print_the_requested_language_alone() {
  let held = SetDetection {
    made_by: SetId::next(),
    language: Lang::Ko,
    detection: Some(
      english_seam()
        .detect_oov("Café AT&T b4d")
        .expect("detect_oov"),
    ),
  };
  let detection = format!("{held:?}");
  assert!(detection.contains("language: Ko"), "{detection}");
  assert!(detection.contains("Symbol('&')"), "{detection}");
  assert!(!detection.contains("En"), "{detection}");

  let resolution = format!("{:?}", held.decide(english_wildcard_korean_fail_closed));
  assert!(resolution.contains("language: Ko"), "{resolution}");
  assert!(resolution.contains("FailClosed"), "{resolution}");
  assert!(!resolution.contains("En"), "{resolution}");
}

/// **The registry restates a refusal under the requested language.** An
/// aligner names its refused positions under its own language; the registry
/// returns them under the request's, as every event it shows. Read by the
/// English seam, refused for a Korean request: every position reports Korean,
/// and the error's debug form never names English. Any other error passes as it
/// is.
///
/// Plant: the refusal returned as the aligner made it, and this law fails.
#[test]
fn the_registry_restates_a_refusal_under_the_requested_language() {
  let read = english_seam()
    .detect_oov("Café AT&T b4d")
    .expect("detect_oov");
  let refusal = Refusal::new(read.events().iter().map(RefusedOov::detected).collect());
  assert!(
    refusal
      .events()
      .iter()
      .all(|event| event.language() == &Lang::En)
  );

  let restated = for_request(AlignError::Refused(refusal), &Lang::Ko);
  let shown = format!("{restated:?}");
  let AlignError::Refused(refusal) = restated else {
    panic!("a refusal stays a refusal: {shown}");
  };
  assert_eq!(refusal.events().len(), 3);
  assert!(
    refusal
      .events()
      .iter()
      .all(|event| event.language() == &Lang::Ko)
  );
  assert!(!shown.contains("En"), "{shown}");

  let other = for_request(AlignError::LanguageUnsupported(Lang::Zh), &Lang::Ko);
  assert!(matches!(other, AlignError::LanguageUnsupported(Lang::Zh)));
}

// ---------------------------------------------------------------------
// A resolution answers the set that made it. Every set has an identity
// (`SetId`), its detections and resolutions carry it from the moment they are
// made, and `align_chunk` checks it before the route is read, on every route.
// Plant (today's miss arm, the miss route ignoring the resolution): the
// foreign-miss laws fail.
// ---------------------------------------------------------------------

/// A resolution made by `set` for `language`, of `text`.
fn decided_by(set: &AlignmentSet, language: &Lang, text: &str) -> SetResolution {
  set
    .detect_oov(text, language)
    .expect("detect_oov")
    .decide(default_policy)
}

/// The miss route's answer to `resolution` in `set`, for an English request.
fn on_a_miss(set: &AlignmentSet, resolution: SetResolution) -> Result<UnitAlignment, AlignError> {
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  set.align_chunk(&Lang::En, &[], &[], "anything", clock, &abort, resolution)
}

/// **Every set is its own**: two sets built alike have two identities, and a
/// detection and the resolution decided from it carry the identity of the set
/// that made them.
#[test]
fn a_set_and_what_it_makes_share_one_identity() {
  let one = AlignmentSetBuilder::new().build();
  let two = AlignmentSetBuilder::new().build();
  assert_ne!(one.id(), two.id());
  assert_ne!(one.id().to_string(), two.id().to_string());
  assert!(one.id().to_string().starts_with("alignment set #"));
  let detection = one.detect_oov("anything", &Lang::En).expect("detect_oov");
  assert_eq!(detection.made_by(), one.id());
  assert_eq!(detection.decide(default_policy).made_by(), one.id());
}

/// **Another set's miss resolution is refused as foreign on a miss, under
/// either policy**: registry A reads nothing for English (a miss) and decides
/// that; registry B, missing English too, refuses A's resolution as
/// [`AlignError::ForeignResolution`] naming A and B, where its policy would
/// otherwise answer it — skipped under `SkipChunk`, an unsupported language
/// under `Error`.
///
/// Plant: today's miss arm, and this law fails.
#[test]
fn a_foreign_resolution_is_refused_on_a_miss_under_either_policy() {
  let a = AlignmentSetBuilder::new().build();
  let outcomes: Vec<_> = [AlignmentFallback::SkipChunk, AlignmentFallback::Error]
    .into_iter()
    .map(|policy| {
      let b = AlignmentSetBuilder::new().with_fallback(policy).build();
      let outcome = on_a_miss(&b, decided_by(&a, &Lang::En, "anything"));
      (policy, b.id(), outcome)
    })
    .collect();
  for (policy, b, outcome) in &outcomes {
    assert!(
      matches!(
        outcome,
        Err(AlignError::ForeignResolution(foreign))
          if foreign.made_by() == a.id() && foreign.asked() == *b
      ),
      "{policy}: every outcome {outcomes:?}"
    );
    let shown = outcome.as_ref().expect_err("refused").to_string();
    assert!(shown.contains(&a.id().to_string()), "{shown}");
    assert!(shown.contains(&b.to_string()), "{shown}");
  }
}

/// **A set's own miss resolution is answered as it was**: skipped under
/// `SkipChunk`, an unsupported language under `Error`.
#[test]
fn a_miss_with_no_resolution_skips_or_errors_as_before() {
  let skip = AlignmentSetBuilder::new().build();
  let skipped = on_a_miss(&skip, decided_by(&skip, &Lang::En, "anything"))
    .expect("a SkipChunk miss is not an error");
  assert!(matches!(skipped.cause(), Some(UnalignedCause::Skipped)));

  let error = AlignmentSetBuilder::new()
    .with_fallback(AlignmentFallback::Error)
    .build();
  assert!(matches!(
    on_a_miss(&error, decided_by(&error, &Lang::En, "anything")),
    Err(AlignError::LanguageUnsupported(Lang::En))
  ));
}

/// **A resolution off its route is refused by name**: a set's own resolution
/// that holds an aligner's decisions, handed to a route where no aligner reads
/// the text, is [`AlignError::MisroutedResolution`], never skipped. A set
/// cannot change once built, so only a resolution made by hand can be one;
/// this law makes it so.
#[test]
fn a_resolution_off_its_route_is_refused_by_name() {
  let set = AlignmentSetBuilder::new().build();
  let resolution = SetResolution {
    made_by: set.id(),
    language: Lang::En,
    resolution: Some(
      english_seam()
        .detect_oov("AT&T")
        .expect("detect_oov")
        .decide(asry::emissions::default_oov_policy),
    ),
  };
  let err = on_a_miss(&set, resolution).expect_err("decisions on a miss");
  assert!(
    matches!(
      err,
      AlignError::MisroutedResolution(ref misrouted)
        if misrouted.decided()
          && *misrouted.route() == AlignmentBinding::Miss(AlignmentFallback::SkipChunk)
    ),
    "{err:?}"
  );
  let shown = err.to_string();
  assert!(shown.contains("holds an aligner's decisions"), "{shown}");
  assert!(shown.contains("Miss(SkipChunk)"), "{shown}");
}

// ---------------------------------------------------------------------
// Model-gated: populated lookup / register / detect_oov need a real
// Aligner, which loads the CoreML model (ALIGNKIT_TEST_MODELS). Same
// convention as src/encode/tests.rs (a separate `tests/` integration
// crate is unreachable from these src-level unit tests).
// ---------------------------------------------------------------------

fn models_dir() -> std::path::PathBuf {
  std::env::var_os("ALIGNKIT_TEST_MODELS").map_or_else(
    || crate::tests::models_root().join("alignkit"),
    std::path::PathBuf::from,
  )
}

/// Loads the real model as an En aligner on the SHIPPING compute placement
/// (`AlignerOptions::new()` → `DEFAULT_ENCODER_COMPUTE`), never a hardcoded
/// `ComputeUnits::_` — so these tests exercise the default rather than a
/// configuration no user runs.
fn en_aligner() -> Aligner {
  Aligner::from_paths(
    Lang::En,
    &models_dir().join("base960h_aligner.mlmodelc"),
    Box::new(EnglishNormalizer::new()),
  )
  .expect("load base960h_aligner.mlmodelc as an En aligner (set ALIGNKIT_TEST_MODELS)")
}

#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn lookup_hits_registered_language() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  assert_eq!(set.len(), 1);
  // Internal lookup hits the language's own aligner (never the Any fallback).
  assert!(matches!(set.lookup(&Lang::En), AlignmentLookup::Hit(_)));
  // The public handle reports the same resolution as DATA: an exact bind.
  assert_eq!(set.resolve(&Lang::En).binding(), AlignmentBinding::Exact);
}

#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn lookup_misses_unregistered_language_without_any() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  assert!(matches!(
    set.lookup(&Lang::Zh),
    AlignmentLookup::Miss(AlignmentFallback::SkipChunk)
  ));
}

#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn strict_lookup_prefers_lang_over_any() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .register(AlignerKey::Any, en_aligner())
    .build();
  // A registered language hits its own aligner, never the Any fallback.
  assert!(matches!(set.lookup(&Lang::En), AlignmentLookup::Hit(_)));
  // An unregistered language falls through to Any.
  assert!(matches!(
    set.lookup(&Lang::Zh),
    AlignmentLookup::AnyFallback(_)
  ));
}

#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn any_fallback_can_match_the_requested_language() {
  // The AnyFallback binding does NOT require the fallback aligner's language to
  // DIFFER from the request — the state the variant doc once excluded. Register
  // ONLY an English aligner under AlignerKey::Any (no AlignerKey::Lang(En)); an
  // English request finds no exact Lang(En) key and falls through to Any, whose
  // own construction language IS En. What made it a fallback is the missing exact
  // key, not a language difference.
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  assert!(matches!(
    set.lookup(&Lang::En),
    AlignmentLookup::AnyFallback(_)
  ));
  // The public binding carries the Any aligner's own language — here EQUAL to the
  // requested language, exactly the case the doc now cites.
  assert_eq!(
    set.resolve(&Lang::En).binding(),
    AlignmentBinding::AnyFallback(Lang::En)
  );
}

#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
#[should_panic(expected = "cannot accept an aligner built for")]
fn register_panics_on_language_mismatch() {
  let _ = AlignmentSetBuilder::new().register(AlignerKey::Lang(Lang::Zh), en_aligner());
}

/// An `Any`-registered En aligner serving a Zh request: the detection names the
/// REQUESTED language (Zh), and shows every event under it, though asry stamped
/// them with the language of the aligner that read the text (En).
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn any_fallback_detection_names_the_requested_language() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let detection = set
    .detect_oov("hello AT&T", &Lang::Zh)
    .expect("detect_oov on the Any-fallback aligner");
  assert_eq!(detection.language(), &Lang::Zh);
  let events = detection.events().expect("the Any aligner read the text");
  assert!(!events.is_empty(), "the `&` is an OOV event");
  assert!(events.iter().all(|event| event.language() == &Lang::Zh));
}

/// **The F2 regression, end-to-end.** An English aligner registered as the
/// multilingual [`AlignerKey::Any`] fallback, a Chinese request, real speech,
/// and a real OOV decision (the `é` of `Américans`, which the bundled table
/// cannot spell and the default policy wildcards).
///
/// Under asry 0.2 this needed the registry to re-stamp the caller's
/// requested-language decisions into the Any aligner's own language, or its
/// `prepare` refused them. asry binds decisions to the aligner that detected
/// them now, and the registry binds them to the request, so a cross-language
/// request reaches encoding and produces words with the decisions its own
/// detection made.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn any_fallback_aligns_a_cross_language_request_with_an_oov_decision() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let samples = load_jfk_wav();
  let text = JFK_TRANSCRIPT.replace("Americans", "Américans");

  let detection = set
    .detect_oov(&text, &Lang::Zh)
    .expect("detect_oov on the Any fallback");
  assert_eq!(detection.language(), &Lang::Zh);
  assert!(
    detection
      .events()
      .is_some_and(|events| events.iter().any(|event| event.char() == Some('é'))),
    "the `é` of `Américans` is an OOV event"
  );
  let resolution = detection.decide(default_policy);

  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let alignment = set
    .align_chunk(
      &Lang::Zh,
      &samples,
      &whole_chunk_is_speech(&samples),
      &text,
      clock,
      &abort,
      resolution,
    )
    .expect("Any-fallback alignment must not fail on the decisions");
  assert!(
    !alignment.words().is_empty(),
    "the English Any aligner must align English speech to English words"
  );
}

/// `text` aligned on the jfk audio through `set` for a `requested` language,
/// its OOV events decided by `policy`.
fn aligned_with(
  set: &AlignmentSet,
  requested: &Lang,
  text: &str,
  policy: fn(&SetOovEvent<'_>) -> OovDecision,
) -> Result<UnitAlignment, AlignError> {
  let samples = load_jfk_wav();
  let resolution = set
    .detect_oov(text, requested)
    .expect("detect_oov")
    .decide(policy);
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  set.align_chunk(
    requested,
    &samples,
    &whole_chunk_is_speech(&samples),
    text,
    clock,
    &abort,
    resolution,
  )
}

/// **An English fallback judges a Korean request's OOV under Korean**, end to
/// end. An English aligner registered as the [`AlignerKey::Any`] fallback serves
/// a Korean request on real speech with one OOV event, the `é` of `Américans`.
/// Under an English-wildcard, Korean-fail-closed policy the Korean request's
/// `é` fails closed: the chunk is [`AlignError::Refused`], naming it, never
/// wildcarded into plausible timings. Under a Korean-wildcard policy the same
/// request aligns, the `é` wildcarded.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn an_english_fallback_judges_a_korean_requests_oov_under_korean() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let text = JFK_TRANSCRIPT.replace("Americans", "Américans");

  let refused = aligned_with(&set, &Lang::Ko, &text, english_wildcard_korean_fail_closed)
    .expect_err("the Korean policy fails the `é` closed");
  let AlignError::Refused(refusal) = refused else {
    panic!("the refusal must be named, got {refused:?}");
  };
  assert_eq!(
    refusal
      .events()
      .iter()
      .map(RefusedOov::char)
      .collect::<Vec<_>>(),
    [Some('é')]
  );

  let aligned = aligned_with(&set, &Lang::Ko, &text, korean_wildcard_english_fail_closed)
    .expect("the Korean policy wildcards the `é`");
  assert!(!aligned.words().is_empty(), "the chunk aligns");
}

/// **A Korean request refused through the English fallback reports every
/// refused position under Korean**, through [`Refusal::events`]: the English
/// `Any` aligner refuses under its own language, and the registry returns the
/// refusal under the request's. Neither the error's debug form nor its message
/// names English.
///
/// Plant: the refusal returned as the aligner made it (today's clone of asry's
/// stamped events), and this law fails.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn a_korean_refusal_through_the_english_fallback_is_reported_under_korean() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let text = "ask not what your country can do for you, AT&T b4d";
  let err = aligned_with(&set, &Lang::Ko, text, |_| OovDecision::FailClosed)
    .expect_err("a policy failing every event closed refuses the chunk");
  let shown = format!("{err:?}");
  let AlignError::Refused(refusal) = err else {
    panic!("the refusal must be named, got {shown}");
  };
  assert!(
    refusal.events().len() >= 2,
    "the `&` and the `4` are both refused: {shown}"
  );
  assert!(
    refusal
      .events()
      .iter()
      .all(|event| event.language() == &Lang::Ko),
    "{shown}"
  );
  assert!(!shown.contains("En"), "{shown}");
}

/// **An exact hit is judged under its own language, as before**: an English
/// request to an English aligner registered under its language. The
/// English-wildcard policy aligns the `é`, and the Korean-wildcard one refuses
/// it.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn an_exact_hit_is_judged_under_its_own_language() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  let text = JFK_TRANSCRIPT.replace("Americans", "Américans");
  let aligned = aligned_with(&set, &Lang::En, &text, english_wildcard_korean_fail_closed)
    .expect("English wildcards the `é`");
  assert!(!aligned.words().is_empty());
  assert!(matches!(
    aligned_with(&set, &Lang::En, &text, korean_wildcard_english_fail_closed),
    Err(AlignError::Refused(_))
  ));
}

/// **A fallback's resolution stays bound to the text its detection read, and
/// to its set**: the view changes what the policy sees, not the detection.
/// Decided for a Korean request, it is refused for another text by asry, which
/// binds decisions to the text and the aligner its detection read; and through
/// another registry's `Any` aligner, for the same request and text, by the
/// registry, as another set's — before asry is reached.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn a_fallback_resolution_stays_bound_to_its_text_and_its_aligner() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let other = AlignmentSetBuilder::new()
    .register(AlignerKey::Any, en_aligner())
    .build();
  let samples = load_jfk_wav();
  let speech = whole_chunk_is_speech(&samples);
  let text = JFK_TRANSCRIPT.replace("Americans", "Américans");
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let decided = || {
    set
      .detect_oov(&text, &Lang::Ko)
      .expect("detect_oov")
      .decide(korean_wildcard_english_fail_closed)
  };

  let another_text = text.replace("country", "county");
  let err = set
    .align_chunk(
      &Lang::Ko,
      &samples,
      &speech,
      &another_text,
      clock,
      &abort,
      decided(),
    )
    .expect_err("decided in another text");
  assert!(
    matches!(err, AlignError::Alignment(EmissionsError::Tokenization(_))),
    "{err:?}"
  );
  let err = other
    .align_chunk(
      &Lang::Ko,
      &samples,
      &speech,
      &text,
      clock,
      &abort,
      decided(),
    )
    .expect_err("detected by another aligner");
  assert!(
    matches!(
      err,
      AlignError::ForeignResolution(ref foreign)
        if foreign.made_by() == set.id() && foreign.asked() == other.id()
    ),
    "{err:?}"
  );
}

/// **The F2 regression: decisions answer the request they were decided for,
/// checked before any dispatch.** asry binds a resolution to the text and the
/// aligner that detected it, so what it cannot see is the request. Three calls
/// pin the ways an unbound registry would leak:
///
/// - **one `Any` aligner, two requests**: Zh and Fr both fall through to the
///   same `Any` aligner, which detected the decisions in the same text, so asry
///   would ACCEPT the Zh policy's decisions under the Fr request and align
///   silently — the leak only the registry's binding closes;
/// - **in-window** audio under the exact En hit, with decisions the `Any`
///   aligner made for Zh: asry would refuse them as another aligner's, an
///   undifferentiated [`AlignError::Alignment`] (its `Tokenization`);
/// - **oversized** audio, same decisions:
///   [`Aligner::align_chunk`](crate::audio::align::aligner::Aligner::align_chunk)'s own length
///   check would raise [`AlignError::InputTooLong`] before `prepare` even runs,
///   so the SAME wrong input would produce a DIFFERENT error depending on the
///   audio length.
///
/// With the binding all three are the identical typed
/// [`AlignError::DecisionLanguage`], because [`AlignmentSet::align_chunk`] checks
/// the resolution's language ahead of dispatching anywhere. Deleting that check
/// turns the first call into a successful alignment and the other two into the
/// route-dependent errors above — the mutation proof.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn a_resolution_decided_for_another_request_is_refused_before_dispatch() {
  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .register(AlignerKey::Any, en_aligner())
    .build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);

  let assert_decision_language =
    |requested: Lang, decided_for: Lang, samples: &[f32], case: &str| {
      let resolution = set
        .detect_oov("test", &decided_for)
        .expect("detect_oov")
        .decide(default_policy);
      let err = set
        .align_chunk(&requested, samples, &[], "test", clock, &abort, resolution)
        .expect_err("decisions made for another request must be refused");
      assert!(
        matches!(
          err,
          AlignError::DecisionLanguage(ref e)
            if *e.requested() == requested && *e.found() == decided_for
        ),
        "{case}: must be the typed DecisionLanguage, got {err:?}"
      );
    };

  let in_window = vec![0.0f32; 16_000];
  assert_decision_language(
    Lang::Fr,
    Lang::Zh,
    &in_window,
    "one Any aligner, two requests",
  );
  assert_decision_language(Lang::En, Lang::Zh, &in_window, "in-window");
  let oversized = vec![0.0f32; crate::audio::align::encode::ENCODER_WINDOW_SAMPLES + 1];
  assert_decision_language(Lang::En, Lang::Zh, &oversized, "oversized");
}

/// **A resolution another registry decided on a miss is refused where the
/// language has an aligner**, as another set's, by name: it carries no
/// decisions this set's aligner detected, and is refused before the route is
/// read rather than aligned with none.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn another_registrys_miss_resolution_is_refused_on_a_hit() {
  let empty = AlignmentSetBuilder::new().build();
  let resolution = empty
    .detect_oov("test", &Lang::En)
    .expect("a miss detects nothing")
    .decide(default_policy);
  assert!(resolution.resolved().is_none());

  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let err = set
    .align_chunk(
      &Lang::En,
      &[0.0f32; 16_000],
      &[],
      "test",
      clock,
      &abort,
      resolution,
    )
    .expect_err("no aligner here detected these decisions");
  assert!(
    matches!(
      err,
      AlignError::ForeignResolution(ref foreign)
        if foreign.made_by() == empty.id() && foreign.asked() == set.id()
    ),
    "{err:?}"
  );
}

/// The registries a foreign resolution is handed to, one per route, under
/// `policy`: an English aligner registered under its language (the hit), one
/// registered as [`AlignerKey::Any`] (the fallback), and none (the miss).
fn routes(policy: AlignmentFallback) -> [(&'static str, AlignmentSet); 3] {
  [
    (
      "hit",
      AlignmentSetBuilder::new()
        .with_fallback(policy)
        .register(AlignerKey::Lang(Lang::En), en_aligner())
        .build(),
    ),
    (
      "fallback",
      AlignmentSetBuilder::new()
        .with_fallback(policy)
        .register(AlignerKey::Any, en_aligner())
        .build(),
    ),
    (
      "miss",
      AlignmentSetBuilder::new().with_fallback(policy).build(),
    ),
  ]
}

/// **A resolution another set made is refused as foreign on every route, under
/// either miss policy.** Registry A, with an English aligner, detects and
/// decides `AT&T b4d` for English, a `FailClosed` decision among them; the
/// resolution, for the same language, is handed to registry B on the hit, the
/// fallback and the miss route, under `SkipChunk` and `Error`. Each refuses it
/// as [`AlignError::ForeignResolution`] naming A and B — on the miss route too,
/// where B's policy would otherwise answer it: skipped as `Unaligned(Skipped)`
/// under `SkipChunk`, reported as an unsupported language under `Error`.
///
/// Plant: today's miss arm (the miss route ignoring the resolution), and this
/// law fails on its two miss cases alone.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn a_foreign_resolution_is_refused_on_every_route() {
  let samples = load_jfk_wav();
  let text = "ask not what your country can do for you, AT&T b4d";
  let a = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);
  let mut outcomes = Vec::new();
  for policy in [AlignmentFallback::SkipChunk, AlignmentFallback::Error] {
    for (route, b) in routes(policy) {
      let resolution = a
        .detect_oov(text, &Lang::En)
        .expect("detect_oov")
        .decide(fail_closed_policy);
      assert!(
        resolution
          .resolved()
          .is_some_and(|resolved| !resolved.is_empty()),
        "A's aligner read the text and decided its events"
      );
      let outcome = b.align_chunk(&Lang::En, &samples, &[], text, clock, &abort, resolution);
      outcomes.push((policy, route, b.id(), outcome));
    }
  }
  let every: Vec<String> = outcomes
    .iter()
    .map(|(policy, route, _, outcome)| format!("{policy} {route}: {outcome:?}"))
    .collect();
  for (policy, route, b, outcome) in &outcomes {
    assert!(
      matches!(
        outcome,
        Err(AlignError::ForeignResolution(foreign))
          if foreign.made_by() == a.id() && foreign.asked() == *b
      ),
      "{policy} {route}: every outcome {every:#?}"
    );
  }
}

/// **A same-set resolution aligns as the aligner itself does**, word for word:
/// the registry's checks run before the route and leave the alignment to the
/// bound aligner. An English request through a registry's English aligner and
/// the same text through a directly loaded English aligner give the same words,
/// ranges and scores.
#[test]
#[ignore = "requires local alignkit models (ALIGNKIT_TEST_MODELS)"]
fn a_same_set_resolution_aligns_as_the_aligner_does() {
  let samples = load_jfk_wav();
  let speech = whole_chunk_is_speech(&samples);
  let text = JFK_TRANSCRIPT.replace("Americans", "Américans");
  let clock = OutputClock::new(0, ANALYSIS_TIMEBASE, 0).expect("clock");
  let abort = AtomicBool::new(false);

  let set = AlignmentSetBuilder::new()
    .register(AlignerKey::Lang(Lang::En), en_aligner())
    .build();
  let through_the_set = set
    .align_chunk(
      &Lang::En,
      &samples,
      &speech,
      &text,
      clock,
      &abort,
      set
        .detect_oov(&text, &Lang::En)
        .expect("detect_oov")
        .decide(default_policy),
    )
    .expect("the set aligns");

  let aligner = en_aligner();
  let direct = aligner
    .align_chunk(
      &samples,
      &speech,
      &text,
      clock,
      &abort,
      aligner
        .detect_oov(&text)
        .expect("detect_oov")
        .decide(asry::emissions::default_oov_policy),
    )
    .expect("the aligner aligns");
  assert!(!direct.words().is_empty());
  let words = |alignment: &UnitAlignment| {
    alignment
      .words()
      .iter()
      .map(|word| {
        (
          word.text().to_owned(),
          word.range().start_pts(),
          word.range().end_pts(),
          word.score().to_bits(),
        )
      })
      .collect::<Vec<_>>()
  };
  assert_eq!(words(&through_the_set), words(&direct));
}

/// The known transcript for `jfk.wav`, with the commas that make the F2 test's
/// punctuation OOV real (duplicated from `tests/common`, as the other src-level
/// unit tests duplicate their fixtures — a `tests/` module is unreachable here).
const JFK_TRANSCRIPT: &str = "And so my fellow Americans ask not what your country can do for you, \
                              ask what you can do for your country.";

/// "No VAD" — one explicit span over the whole chunk in the 1/16000 analysis
/// timebase, i.e. all speech. Passing empty `sub_segments` is also "no VAD": the
/// shipping API maps empty to
/// [`SpeechSpans::all_speech`](asry::emissions::SpeechSpans::all_speech), NOT to
/// "all silence" (see [`crate::audio::align::aligner::Aligner::align_chunk`]); this helper just
/// states the whole-chunk span explicitly.
fn whole_chunk_is_speech(samples: &[f32]) -> [TimeRange; 1] {
  [TimeRange::new(0, samples.len() as i64, ANALYSIS_TIMEBASE)]
}

/// The 11 s `jfk.wav` fixture, borrowed from the whisperkit crate by relative
/// path (as the other src-level tests do) and failing LOUDLY if it ever moves.
fn load_jfk_wav() -> Vec<f32> {
  let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
    .join("tests/whisper/fixtures/audio/jfk.wav");
  let mut reader = hound::WavReader::open(&path)
    .unwrap_or_else(|e| panic!("open the jfk.wav fixture at {path:?}: {e}"));
  assert_eq!(reader.spec().sample_rate, 16_000, "fixture must be 16 kHz");
  reader
    .samples::<i16>()
    .map(|s| f32::from(s.expect("valid sample")) / 32_768.0)
    .collect()
}