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

// ---------------------------------------------------------------------
// repeat_pad_f32: hermetic repeat-padding math (brief Step 1) — exact
// hand-computed expected rows for short inputs, plus an empirical
// cross-check against a literal transliteration of FluidAudio's Swift
// doubling-copy loop.
// ---------------------------------------------------------------------

#[test]
fn repeat_pad_f32_empty_source_returns_zeros() {
  assert_eq!(repeat_pad_f32(&[], 5), vec![0.0; 5]);
}

#[test]
fn repeat_pad_f32_empty_source_and_zero_target_returns_empty() {
  assert_eq!(repeat_pad_f32(&[], 0), Vec::<f32>::new());
}

#[test]
fn repeat_pad_f32_exact_length_is_identity() {
  assert_eq!(
    repeat_pad_f32(&[1.0, 2.0, 3.0, 4.0], 4),
    vec![1.0, 2.0, 3.0, 4.0]
  );
}

/// Hand-computed: source `[1,2,3]` repeat-tiled to 10 elements. Traced by
/// hand against FluidAudio's doubling-copy loop (module doc's
/// `repeat_pad_f32` proof): fill=[1,2,3], double to
/// [1,2,3,1,2,3,?,?,?,?] (copy 3), then copy min(6,4)=4 from the start to
/// reach [1,2,3,1,2,3,1,2,3,1].
#[test]
fn repeat_pad_f32_short_source_tiles_periodically() {
  assert_eq!(
    repeat_pad_f32(&[1.0, 2.0, 3.0], 10),
    vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0]
  );
}

#[test]
fn repeat_pad_f32_single_element_source_fills_uniformly() {
  assert_eq!(repeat_pad_f32(&[7.0], 4), vec![7.0, 7.0, 7.0, 7.0]);
}

#[test]
fn repeat_pad_f32_longer_source_truncates() {
  assert_eq!(
    repeat_pad_f32(&[1.0, 2.0, 3.0, 4.0, 5.0], 3),
    vec![1.0, 2.0, 3.0]
  );
}

#[test]
fn repeat_pad_f32_zero_target_returns_empty() {
  assert_eq!(repeat_pad_f32(&[1.0, 2.0], 0), Vec::<f32>::new());
}

/// Literal Rust transliteration of FluidAudio's Swift doubling-copy loop
/// (`fillWaveformBuffer`/`fillMaskBufferOptimized`,
/// `EmbeddingExtractor.swift#L117-199` at the pinned SHA — module doc) —
/// used ONLY to empirically cross-check that `repeat_pad_f32`'s closed-form
/// periodic-tile output is bit-identical to the doubling-copy algorithm's
/// output, per this task's brief instruction to verify the loop-pad
/// behavior empirically, not just by proof:
///
/// ```swift
/// while sampleCount < requiredCount {
///     let copyCount = min(sampleCount, requiredCount - sampleCount)
///     vDSP_mmov(ptr, ptr.advanced(by: sampleCount), vDSP_Length(copyCount), ...)
///     sampleCount += copyCount
/// }
/// ```
fn doubling_copy_simulation(source: &[f32], target_len: usize) -> Vec<f32> {
  let mut buf = vec![0.0f32; target_len];
  let mut sample_count = source.len().min(target_len);
  buf[..sample_count].copy_from_slice(&source[..sample_count]);
  if sample_count == 0 {
    return buf;
  }
  while sample_count < target_len {
    let copy_count = sample_count.min(target_len - sample_count);
    let (filled, rest) = buf.split_at_mut(sample_count);
    rest[..copy_count].copy_from_slice(&filled[..copy_count]);
    sample_count += copy_count;
  }
  buf
}

#[test]
fn doubling_copy_simulation_matches_repeat_pad_f32_non_power_of_two_lengths() {
  // Several non-power-of-2 (source, target_len) pairs — the case the
  // module doc's equivalence proof is least obviously true for at a
  // glance (the proof only needs "multiple of source.len()", not "power
  // of two", but empirical cross-checking beats trusting the proof alone).
  let cases: &[(&[f32], usize)] = &[
    (&[1.0, 2.0, 3.0], 10),
    (&[1.0, 2.0, 3.0, 4.0, 5.0], 13),
    (&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], 20),
    (&[9.0], 7),
    (&[1.0, 2.0], 2),
    (&[1.0, 2.0, 3.0, 4.0, 5.0], 3),
    (&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 1),
  ];
  for &(source, target_len) in cases {
    assert_eq!(
      repeat_pad_f32(source, target_len),
      doubling_copy_simulation(source, target_len),
      "mismatch for source={source:?}, target_len={target_len}"
    );
  }
}

#[test]
fn doubling_copy_simulation_matches_repeat_pad_f32_on_empty_source() {
  assert_eq!(repeat_pad_f32(&[], 6), doubling_copy_simulation(&[], 6));
}

// ---------------------------------------------------------------------
// mask_row_f32: hermetic mask f32 conversion (brief Step 1).
// ---------------------------------------------------------------------

#[test]
fn mask_row_f32_converts_true_and_false() {
  assert_eq!(
    mask_row_f32(&[true, false, true, true, false]),
    vec![1.0, 0.0, 1.0, 1.0, 0.0]
  );
}

#[test]
fn mask_row_f32_empty_mask_is_empty() {
  assert_eq!(mask_row_f32(&[]), Vec::<f32>::new());
}

#[test]
fn mask_row_f32_all_false() {
  assert_eq!(mask_row_f32(&[false, false]), vec![0.0, 0.0]);
}

#[test]
fn mask_row_f32_all_true() {
  assert_eq!(mask_row_f32(&[true, true, true]), vec![1.0, 1.0, 1.0]);
}

/// Composition of `mask_row_f32` + `repeat_pad_f32` — the exact pipeline
/// `build_masks` runs per slot: a short boolean mask, converted then
/// repeat-padded. Hand-computed: `[true,false]` -> `[1.0,0.0]`, tiled to 5
/// (period 2) -> `[1.0,0.0,1.0,0.0,1.0]`.
#[test]
fn mask_row_padding_short_mask_tiles_after_conversion() {
  let converted = mask_row_f32(&[true, false]);
  assert_eq!(repeat_pad_f32(&converted, 5), vec![1.0, 0.0, 1.0, 0.0, 1.0]);
}

// ---------------------------------------------------------------------
// build_waveform / build_masks: hermetic batched-buffer assembly.
// ---------------------------------------------------------------------

#[test]
fn build_waveform_repeats_the_same_row_in_every_slot() {
  let out = build_waveform(&[1.0, 2.0]);
  assert_eq!(
    out.len(),
    EMBED_SLOTS * crate::audio::speaker::segment::SEG_CHUNK_SAMPLES
  );
  for slot in out
    .as_chunks::<{ crate::audio::speaker::segment::SEG_CHUNK_SAMPLES }>()
    .0
  {
    assert_eq!(slot[0], 1.0);
    assert_eq!(slot[1], 2.0);
    assert_eq!(slot[2], 1.0); // period-2 tiling continues into slot's tail
  }
}

#[test]
fn build_masks_pads_each_slot_independently() {
  let mask_a = [true, false, true];
  let mask_b: [bool; 0] = [];
  let mask_c = [true];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask_a, &mask_b, &mask_c];
  let out = build_masks(&masks, 4);
  assert_eq!(out.len(), EMBED_SLOTS * 4);
  assert_eq!(&out[0..4], &[1.0, 0.0, 1.0, 1.0]); // period-3 tiling
  assert_eq!(&out[4..8], &[0.0, 0.0, 0.0, 0.0]); // empty -> zero-fill
  assert_eq!(&out[8..12], &[1.0, 1.0, 1.0, 1.0]); // period-1 tiling
}

// ---------------------------------------------------------------------
// check_mask_active: hermetic dia-parity mask-validity check.
// ---------------------------------------------------------------------

#[test]
fn check_mask_active_accepts_one_active_frame() {
  assert_eq!(check_mask_active(&[false, true, false]), Ok(()));
}

#[test]
fn check_mask_active_accepts_all_active() {
  assert_eq!(check_mask_active(&[true, true]), Ok(()));
}

#[test]
fn check_mask_active_rejects_all_false() {
  assert_eq!(
    check_mask_active(&[false, false, false]),
    Err(InferError::EmptyMask)
  );
}

#[test]
fn check_mask_active_rejects_empty_mask() {
  assert_eq!(check_mask_active(&[]), Err(InferError::EmptyMask));
}

// ---------------------------------------------------------------------
// check_finite_input / check_finite_output: hermetic NonFinite scans.
// ---------------------------------------------------------------------

#[test]
fn check_finite_input_accepts_all_finite() {
  assert_eq!(check_finite_input(&[0.0, 1.0, -1.0]), Ok(()));
}

#[test]
fn check_finite_input_rejects_nan_at_reported_index() {
  assert_eq!(
    check_finite_input(&[0.0, f32::NAN, 2.0]),
    Err(InferError::NonFiniteInput(1))
  );
}

#[test]
fn check_finite_input_rejects_positive_infinity() {
  assert_eq!(
    check_finite_input(&[f32::INFINITY]),
    Err(InferError::NonFiniteInput(0))
  );
}

#[test]
fn check_finite_input_rejects_negative_infinity() {
  assert_eq!(
    check_finite_input(&[0.0, 0.0, f32::NEG_INFINITY]),
    Err(InferError::NonFiniteInput(2))
  );
}

#[test]
fn check_finite_output_accepts_all_finite() {
  assert_eq!(check_finite_output(&[0.0, 1.0, -1.0]), Ok(()));
}

#[test]
fn check_finite_output_rejects_nan_at_reported_index() {
  assert_eq!(
    check_finite_output(&[0.0, f32::NAN, 2.0]),
    Err(InferError::NonFiniteOutput(1))
  );
}

#[test]
fn check_finite_output_reports_first_offending_index() {
  assert_eq!(
    check_finite_output(&[f32::NAN, f32::INFINITY]),
    Err(InferError::NonFiniteOutput(0))
  );
}

// ---------------------------------------------------------------------
// check_output_shape: hermetic output-shape validation (T2 commit
// fcbce74's precedent — review-queue item 3).
// ---------------------------------------------------------------------

#[test]
fn check_output_shape_accepts_correct_shape() {
  assert_eq!(check_output_shape(&[EMBED_SLOTS, EMBEDDING_DIM]), Ok(()));
}

/// The exact corruption this guard exists to catch: axes swapped
/// (`[EMBEDDING_DIM, EMBED_SLOTS]` instead of `[EMBED_SLOTS,
/// EMBEDDING_DIM]`) carries the identical element count as the correct
/// shape, so a total-element-count check alone (as `MultiArray::copy_into`
/// performs) would not detect it.
#[test]
fn check_output_shape_rejects_swapped_axes() {
  assert_eq!(
    check_output_shape(&[EMBEDDING_DIM, EMBED_SLOTS]),
    Err(InferError::OutputShape(OutputShape::new(
      vec![EMBEDDING_DIM, EMBED_SLOTS],
      vec![EMBED_SLOTS, EMBEDDING_DIM]
    )))
  );
}

#[test]
fn check_output_shape_rejects_wrong_rank() {
  assert_eq!(
    check_output_shape(&[EMBED_SLOTS * EMBEDDING_DIM]),
    Err(InferError::OutputShape(OutputShape::new(
      vec![EMBED_SLOTS * EMBEDDING_DIM],
      vec![EMBED_SLOTS, EMBEDDING_DIM]
    )))
  );
}

#[test]
fn check_output_shape_rejects_wrong_slot_count() {
  assert_eq!(
    check_output_shape(&[2, EMBEDDING_DIM]),
    Err(InferError::OutputShape(OutputShape::new(
      vec![2, EMBEDDING_DIM],
      vec![EMBED_SLOTS, EMBEDDING_DIM]
    )))
  );
}

#[test]
fn check_output_shape_rejects_wrong_embedding_dim() {
  assert_eq!(
    check_output_shape(&[EMBED_SLOTS, EMBEDDING_DIM - 1]),
    Err(InferError::OutputShape(OutputShape::new(
      vec![EMBED_SLOTS, EMBEDDING_DIM - 1],
      vec![EMBED_SLOTS, EMBEDDING_DIM]
    )))
  );
}

// ---------------------------------------------------------------------
// EmbedModelOptions
// ---------------------------------------------------------------------

#[test]
fn options_new_defaults_to_all_compute() {
  assert_eq!(EmbedModelOptions::new().compute(), ComputeUnits::All);
}

#[test]
fn options_default_matches_new() {
  assert_eq!(EmbedModelOptions::default(), EmbedModelOptions::new());
}

#[test]
fn options_with_compute_overrides() {
  let options = EmbedModelOptions::new().with_compute(ComputeUnits::CpuOnly);
  assert_eq!(options.compute(), ComputeUnits::CpuOnly);
}

#[test]
fn options_set_compute_in_place() {
  let mut options = EmbedModelOptions::new();
  options.set_compute(ComputeUnits::CpuAndNeuralEngine);
  assert_eq!(options.compute(), ComputeUnits::CpuAndNeuralEngine);
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_missing_compute_defaults_to_all() {
  let options: EmbedModelOptions = serde_json::from_str("{}").unwrap();
  assert_eq!(options.compute(), ComputeUnits::All);
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_round_trips_explicit_compute() {
  let options: EmbedModelOptions = serde_json::from_str(r#"{"compute":"cpu_only"}"#).unwrap();
  assert_eq!(options.compute(), ComputeUnits::CpuOnly);
  let json = serde_json::to_string(&options).unwrap();
  assert!(json.contains("cpu_only"), "round-tripped json: {json}");
}

// ---------------------------------------------------------------------
// EmbedModel: model-gated (brief Step 2) — requires local
// wespeaker_v2.mlmodelc AND wespeaker.mlmodelc (SPEAKERKIT_TEST_MODELS or
// Models/speakerkit/, same convention as tests/model_io.rs's `common`
// module and crate::audio::speaker::segment::tests). Duplicated here in miniature because
// unit tests under `src/` cannot import the separate `tests/`
// integration-test crate.
//
// The full suite below runs against BOTH artifacts, per this task's
// brief. Determinism is checked WITHIN one artifact only per call — int8
// (`wespeaker_v2`) and fp32 (`wespeaker`) legitimately diverge
// numerically, so no test compares results ACROSS artifacts.
// ---------------------------------------------------------------------

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

fn embed_v2_path() -> std::path::PathBuf {
  models_dir().join("wespeaker_v2.mlmodelc")
}

fn embed_fp32_path() -> std::path::PathBuf {
  models_dir().join("wespeaker.mlmodelc")
}

/// Loads a real embedding model from `path` with `ComputeUnits::CpuOnly` —
/// matching `tests/model_io.rs`'s and
/// `crate::audio::speaker::segment::tests::load_seg_model`'s convention: deterministic, no
/// ANE compile-latency variance across runs. `DEFAULT_EMBED_COMPUTE`
/// (`ComputeUnits::All`) stays the production default. Parameterized over
/// `path` so the SAME loader drives both `wespeaker_v2.mlmodelc` (int8,
/// T1's targeted artifact) and `wespeaker.mlmodelc` (fp32, contract-equal
/// per T1) — this task's brief requires the full model-gated suite run
/// against both.
fn load_embed_model(path: std::path::PathBuf) -> EmbedModel {
  EmbedModel::from_file_with(
    path,
    EmbedModelOptions::new().with_compute(ComputeUnits::CpuOnly),
  )
  .expect("load embedding model")
}

/// Non-silent, deterministic synthetic signal for tests that need a real
/// (non-degenerate) embedding — a two-tone sine mix, not noise, so it is
/// exactly reproducible across runs and platforms.
fn synthetic_samples(len: usize) -> Vec<f32> {
  (0..len)
    .map(|i| {
      let t = i as f32 / 16_000.0; // 16 kHz, dia's SAMPLE_RATE_HZ (diarization/src/embed/options.rs:34)
      0.2 * (2.0 * core::f32::consts::PI * 220.0 * t).sin()
        + 0.1 * (2.0 * core::f32::consts::PI * 440.0 * t).sin()
    })
    .collect()
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn from_file_loads_and_reports_mask_frame_count_v2() {
  let model = load_embed_model(embed_v2_path());
  // Ground truth pinned by
  // `tests/model_io.rs::wespeaker_v2_io_matches_spec`: 589 frames.
  assert_eq!(model.num_mask_frames(), 589);
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn from_file_loads_and_reports_mask_frame_count_fp32() {
  let model = load_embed_model(embed_fp32_path());
  // Ground truth pinned by
  // `tests/model_io.rs::wespeaker_fp32_io_matches_spec`.
  assert_eq!(model.num_mask_frames(), 589);
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn from_file_rejects_wrong_contract_model() {
  // pyannote_segmentation.mlmodelc has no `waveform`/`mask` inputs at all
  // (its input is `audio`) — a real, locally-available model with a
  // definitely-mismatched contract, mirroring
  // `crate::audio::speaker::segment::tests::from_file_rejects_wrong_contract_model`'s
  // reciprocal use of `wespeaker_v2.mlmodelc`.
  let path = models_dir().join("pyannote_segmentation.mlmodelc");
  let err = EmbedModel::from_file(path).expect_err("wrong contract must be rejected");
  assert!(matches!(
    err,
    ModelError::ContractMismatch(m) if m.feature() == "waveform"
  ));
}

fn embed_chunk_produces_correctly_shaped_finite_embeddings(path: std::path::PathBuf) {
  let model = load_embed_model(path);
  let samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  let mask = vec![true; model.num_mask_frames()];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask, &mask, &mask];
  let out = model
    .embed_chunk(&samples, &masks)
    .expect("embed_chunk on real audio");
  for row in out.iter() {
    assert_eq!(row.len(), EMBEDDING_DIM);
    assert!(
      row.iter().all(|v| v.is_finite()),
      "all embedding values finite"
    );
  }
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_produces_correctly_shaped_finite_embeddings_v2() {
  embed_chunk_produces_correctly_shaped_finite_embeddings(embed_v2_path());
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_produces_correctly_shaped_finite_embeddings_fp32() {
  embed_chunk_produces_correctly_shaped_finite_embeddings(embed_fp32_path());
}

fn embed_chunk_is_deterministic_across_repeated_calls(path: std::path::PathBuf) {
  let model = load_embed_model(path);
  let samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  let mask = vec![true; model.num_mask_frames()];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask, &mask, &mask];
  let first = model
    .embed_chunk(&samples, &masks)
    .expect("first embed_chunk");
  let second = model
    .embed_chunk(&samples, &masks)
    .expect("second embed_chunk");
  assert_eq!(
    first, second,
    "repeated embed_chunk must be bit-identical WITHIN one artifact"
  );
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_is_deterministic_across_repeated_calls_v2() {
  embed_chunk_is_deterministic_across_repeated_calls(embed_v2_path());
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_is_deterministic_across_repeated_calls_fp32() {
  embed_chunk_is_deterministic_across_repeated_calls(embed_fp32_path());
}

fn embed_chunk_with_frame_mask_is_raw_not_unit_norm(path: std::path::PathBuf) {
  let model = load_embed_model(path);
  let samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  let mask = vec![true; model.num_mask_frames()];
  let embedding = model
    .embed_chunk_with_frame_mask(&samples, &mask)
    .expect("embed_chunk_with_frame_mask on real audio");
  let norm: f32 = embedding.iter().map(|v| v * v).sum::<f32>().sqrt();
  assert!(
    (norm - 1.0).abs() > 1e-3,
    "raw WeSpeaker output must not be unit-normalized (dia normalizes downstream, not here); got norm {norm}"
  );
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_with_frame_mask_is_raw_not_unit_norm_v2() {
  embed_chunk_with_frame_mask_is_raw_not_unit_norm(embed_v2_path());
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_with_frame_mask_is_raw_not_unit_norm_fp32() {
  embed_chunk_with_frame_mask_is_raw_not_unit_norm(embed_fp32_path());
}

/// [`EmbedModel::embed_chunk_with_frame_mask`] must equal
/// [`EmbedModel::embed_chunk`]'s slot 0 when called with the same samples
/// and the same mask in slot 0 (empty masks in slots 1-2) — pins the
/// veneer relationship the module doc describes, against the real model,
/// not just by code inspection.
fn embed_chunk_with_frame_mask_matches_batched_slot_zero(path: std::path::PathBuf) {
  let model = load_embed_model(path);
  let samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  // Partial (not all-active) mask — exercises a non-trivial pooling
  // weight, not just the degenerate all-ones case.
  let mut mask = vec![false; model.num_mask_frames()];
  for m in mask.iter_mut().step_by(3) {
    *m = true;
  }
  let veneer = model
    .embed_chunk_with_frame_mask(&samples, &mask)
    .expect("embed_chunk_with_frame_mask");
  let empty: &[bool] = &[];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask, empty, empty];
  let batched = model.embed_chunk(&samples, &masks).expect("embed_chunk");
  assert_eq!(
    veneer, batched[0],
    "embed_chunk_with_frame_mask must equal embed_chunk's slot 0 for the same mask"
  );
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_with_frame_mask_matches_batched_slot_zero_v2() {
  embed_chunk_with_frame_mask_matches_batched_slot_zero(embed_v2_path());
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_with_frame_mask_matches_batched_slot_zero_fp32() {
  embed_chunk_with_frame_mask_matches_batched_slot_zero(embed_fp32_path());
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_with_frame_mask_rejects_all_false_mask() {
  let model = load_embed_model(embed_v2_path());
  let samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  let mask = vec![false; model.num_mask_frames()];
  let err = model
    .embed_chunk_with_frame_mask(&samples, &mask)
    .expect_err("all-false mask must be rejected");
  assert_eq!(err, InferError::EmptyMask);
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_rejects_non_finite_samples() {
  let model = load_embed_model(embed_v2_path());
  let mut samples = synthetic_samples(crate::audio::speaker::segment::SEG_CHUNK_SAMPLES);
  samples[1234] = f32::NAN;
  let mask = vec![true; model.num_mask_frames()];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask, &mask, &mask];
  let err = model
    .embed_chunk(&samples, &masks)
    .expect_err("NaN samples must be rejected");
  assert_eq!(err, InferError::NonFiniteInput(1234));
}

#[test]
#[ignore = "requires local speakerkit models (SPEAKERKIT_TEST_MODELS)"]
fn embed_chunk_handles_short_padded_input() {
  // A chunk shorter than SEG_CHUNK_SAMPLES exercises the repeat-pad path
  // against the real model end to end (not just the hermetic
  // `repeat_pad_f32` unit tests).
  let model = load_embed_model(embed_v2_path());
  let samples = synthetic_samples(40_000); // 2.5s, well under the 10s chunk
  let mask = vec![true; model.num_mask_frames()];
  let masks: [&[bool]; EMBED_SLOTS] = [&mask, &mask, &mask];
  let out = model
    .embed_chunk(&samples, &masks)
    .expect("embed_chunk on a short, repeat-padded chunk");
  for row in out.iter() {
    assert!(row.iter().all(|v| v.is_finite()));
  }
}

// ── The door's own contract ────────────────────────────────────────────────
//
// `model::contract`'s tests drive every CLAUSE of `check_load_contract`. What
// these drive is this door's `LoadContract` itself — its feature names, its
// element types, its geometry and its state clause — against descriptions built
// with the same fixture machinery, so a mis-stated contract is caught here and
// a mis-implemented checker is caught there.

use crate::{AxisRange, FeatureInfo, ModelDescription, ShapeConstraint, model::RawShapeConstraint};

/// A fixed-shape multi-array feature, exactly as a plain coremltools export
/// reports one: raw type 2, its declared shape as the sole enumerated shape,
/// and `(d, 1)` on every axis.
fn fixed(name: &str, shape: &[usize], dtype: DataType) -> FeatureInfo {
  FeatureInfo::from_parts(
    name.to_string(),
    shape.to_vec(),
    Some(dtype),
    false,
    Some(RawShapeConstraint::new(
      2,
      vec![shape.to_vec()],
      shape.iter().map(|d| AxisRange::new(*d, 1)).collect(),
    )),
  )
}

/// A `RangeDims` multi-array feature: raw type 3, no enumerated shapes, and the
/// per-axis bounds it was converted with. `shape` is the DEFAULT, which is the
/// whole point of the falsifier below.
fn ranged(name: &str, shape: &[usize], dtype: DataType, ranges: &[AxisRange]) -> FeatureInfo {
  FeatureInfo::from_parts(
    name.to_string(),
    shape.to_vec(),
    Some(dtype),
    false,
    Some(RawShapeConstraint::new(3, Vec::new(), ranges.to_vec())),
  )
}

/// The staged wespeaker bundles' description, as `Model::load` reads it back off
/// all three (`wespeaker`, `wespeaker_v2`, `wespeaker_int8` are contract-equal):
/// `waveform [3, 160_000]` and `mask [3, 589]` f32 `Fixed` in;
/// `embedding [3, 256]` f32 `Fixed` out, beside the undocumented scalar
/// `constant` output — rank 0, and therefore `Unspecified`, which is exactly
/// why the contract must not name it.
fn wespeaker_description() -> ModelDescription {
  ModelDescription::from_parts(
    vec![
      fixed(
        names::MASK,
        &[EMBED_SLOTS, MEASURED_MASK_FRAMES],
        DataType::F32,
      ),
      fixed(
        names::WAVEFORM,
        &[
          EMBED_SLOTS,
          crate::audio::speaker::segment::SEG_CHUNK_SAMPLES,
        ],
        DataType::F32,
      ),
    ],
    vec![
      FeatureInfo::from_parts(
        "constant".to_string(),
        Vec::new(),
        Some(DataType::F32),
        false,
        Some(RawShapeConstraint::new(1, Vec::new(), Vec::new())),
      ),
      fixed(
        names::EMBEDDING,
        &[EMBED_SLOTS, EMBEDDING_DIM],
        DataType::F32,
      ),
    ],
    Vec::new(),
  )
}

/// The frame count every staged wespeaker bundle declares. Spelled here rather
/// than imported so the contract test does not pin a constant against itself —
/// the door reads this number off the artifact and hardcodes it nowhere.
const MEASURED_MASK_FRAMES: usize = 589;

/// This door's contract, run against `description` and mapped into this
/// module's errors — exactly what `EmbedModel::from_file_with` does after
/// `Model::load`.
fn check(description: &ModelDescription) -> Result<(), ModelError> {
  crate::model::contract::check_load_contract(description, &embed_contract())
    .map_err(crate::audio::speaker::error::contract_violation)
}

/// The staged artifact satisfies the contract, `constant` and all — and the
/// frame count the door then reads back is the artifact's own.
#[test]
fn the_contract_accepts_the_staged_wespeaker_description() {
  let description = wespeaker_description();
  assert_eq!(check(&description), Ok(()));
  assert_eq!(
    description.input(names::MASK).expect("mask").shape()[1],
    MEASURED_MASK_FRAMES
  );
  // The `constant` output is DECLARED and not named, which is the case the
  // contract has to accept: it carries no geometry at all
  // (`ShapeConstraint::Unspecified`, empty shape), so naming it would refuse
  // every wespeaker bundle this repository stages.
  assert_eq!(
    description
      .output("constant")
      .expect("constant")
      .shape_constraint(),
    Some(ShapeConstraint::Unspecified)
  );
}

/// **FALSIFIER (red first) — issue #137's defect (ii), with teeth.**
///
/// The check this contract replaced read `mask.shape()[1]` and required only
/// `>= 1`. `FeatureInfo::shape` reports the DEFAULT shape of a flexible
/// feature, so a `mask` declared over 1..=4096 frames and converted at 589
/// satisfied every clause it made — same rank, same leading dimension, same
/// dtype, same number — and the door then bound `F = 589` and built every
/// `embed_chunk` mask row at a length the graph does not require. It does not
/// fail; it computes against the wrong geometry.
///
/// `Dim::AnyFixed` requires the whole feature to be `ShapeConstraint::Fixed`,
/// which is the only thing that separates this description from the accepted
/// one above.
#[test]
fn the_contract_refuses_a_flexible_mask_whose_default_is_the_artifacts_589() {
  let description = ModelDescription::from_parts(
    vec![
      ranged(
        names::MASK,
        &[EMBED_SLOTS, MEASURED_MASK_FRAMES],
        DataType::F32,
        &[
          AxisRange::new(EMBED_SLOTS, 1),
          AxisRange::inclusive(1, 4096),
        ],
      ),
      fixed(
        names::WAVEFORM,
        &[
          EMBED_SLOTS,
          crate::audio::speaker::segment::SEG_CHUNK_SAMPLES,
        ],
        DataType::F32,
      ),
    ],
    vec![fixed(
      names::EMBEDDING,
      &[EMBED_SLOTS, EMBEDDING_DIM],
      DataType::F32,
    )],
    Vec::new(),
  );
  // The number the old check read is right there, and is not what decides it.
  assert_eq!(
    description.input(names::MASK).expect("mask").shape()[1],
    MEASURED_MASK_FRAMES
  );
  let err = check(&description).unwrap_err();
  assert!(
    matches!(&err, ModelError::ContractMismatch(m)
      if m.feature() == names::MASK && m.actual() == "range" && m.expected() == "fixed"),
    "{err}"
  );
}

/// The floor, on the door that motivated it: a zero-frame `mask` is pinned, so
/// it satisfies "exactly one size" — and every mask row built from it would be
/// empty.
#[test]
fn the_contract_refuses_a_zero_frame_mask() {
  let description = ModelDescription::from_parts(
    vec![
      fixed(names::MASK, &[EMBED_SLOTS, 0], DataType::F32),
      fixed(
        names::WAVEFORM,
        &[
          EMBED_SLOTS,
          crate::audio::speaker::segment::SEG_CHUNK_SAMPLES,
        ],
        DataType::F32,
      ),
    ],
    vec![fixed(
      names::EMBEDDING,
      &[EMBED_SLOTS, EMBEDDING_DIM],
      DataType::F32,
    )],
    Vec::new(),
  );
  let err = check(&description).unwrap_err();
  assert!(
    matches!(&err, ModelError::ContractMismatch(m) if m.feature() == names::MASK),
    "{err}"
  );
}

/// **Defect (i).** A graph carrying this door's two inputs PLUS another
/// required one clears every per-feature clause and then fails every
/// prediction, because the door sends the features its contract names and
/// nothing else. Nothing the shape checks this replaced looked at could see it.
#[test]
fn the_contract_refuses_an_extra_required_input() {
  let mut inputs = wespeaker_description().inputs().to_vec();
  inputs.push(fixed("speaker_ids", &[EMBED_SLOTS], DataType::I32));
  let description = ModelDescription::from_parts(
    inputs,
    wespeaker_description().outputs().to_vec(),
    Vec::new(),
  );
  let err = check(&description).unwrap_err();
  assert!(
    matches!(&err, ModelError::UnsatisfiableInput(name) if name == "speaker_ids"),
    "{err}"
  );
}

/// **State is not an input.** It lives in its own dictionary, so a stateful
/// graph declaring exactly `waveform`, `mask` and `embedding` clears every
/// other clause — and then meets a door predicting through the stateless API,
/// which CoreML does not let a stateful model be called with.
#[test]
fn the_contract_refuses_a_graph_that_declares_state() {
  let base = wespeaker_description();
  let description = ModelDescription::from_parts(
    base.inputs().to_vec(),
    base.outputs().to_vec(),
    vec![fixed("kv_cache", &[1, 8], DataType::F32)],
  );
  let err = check(&description).unwrap_err();
  assert!(
    matches!(&err, ModelError::UnsatisfiableState(name) if name == "kv_cache"),
    "{err}"
  );
}

/// **The wiring, pinned on a REAL model, in every `cargo test`.**
///
/// Every other contract gate here drives `check_load_contract` over a fixture.
/// This one runs `EmbedModel::from_file` against
/// `Models/vadkit/silero-vad-unified-256ms-v6.2.1.mlmodelc`, which is
/// COMMITTED — 1.1 MiB, staged by no download — so unlike every other gate in
/// this module that loads a model it carries no `#[ignore]`.
///
/// Delete the `Checked::new` call from `from_file_with` and this is the gate
/// that reds: the fixture tests call the checker directly and would all still
/// pass. (The deletion does not compile either, because the field is a
/// `Checked` — this is the belt beside that brace, and it also covers a
/// `Checked::new` left in place against the WRONG contract.)
#[test]
fn the_embed_contract_refuses_the_vendored_silero_bundle() {
  let bundle = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    .join("../Models/vadkit/silero-vad-unified-256ms-v6.2.1.mlmodelc");
  assert!(
    bundle.is_dir(),
    "the vendored silero bundle is committed, so this gate is NOT model-gated; looked for {}",
    bundle.display()
  );
  let err = EmbedModel::from_file(&bundle).expect_err("silero is not this door's model");
  assert!(
    matches!(&err, ModelError::ContractMismatch(m)
      if m.feature() == names::WAVEFORM && m.actual() == "missing"),
    "{err}"
  );
}

/// `base` with one axis of one named feature made one larger, rebuilt through
/// the same fixture constructor so the perturbed feature is still a plain
/// fixed-shape export.
fn with_axis_bumped(base: &ModelDescription, feature: &str, axis: usize) -> ModelDescription {
  let bump = |declared: &FeatureInfo| -> FeatureInfo {
    if declared.name() != feature {
      return declared.clone();
    }
    let mut shape = declared.shape().to_vec();
    shape[axis] += 1;
    fixed(
      declared.name(),
      &shape,
      declared.data_type().expect("a multi-array feature"),
    )
  };
  ModelDescription::from_parts(
    base.inputs().iter().map(bump).collect(),
    base.outputs().iter().map(bump).collect(),
    base.states().to_vec(),
  )
}

/// **Every axis clause is load-bearing, and the free ones are named.**
///
/// One test per dimension is a list that silently stops covering an axis the
/// contract later gains, and it is exactly what let a loosened
/// `Dim::Exactly(EMBEDDING_DIM)` survive a mutation run. This perturbs EVERY
/// axis of every named feature in turn and asserts the contract refuses it —
/// EXCEPT for the axes below, which the door deliberately reads back off the
/// checked model rather than requiring.
///
/// So it reds in both directions: loosen a pinned axis and its perturbation is
/// wrongly accepted; pin a read-back axis and its perturbation is wrongly
/// refused.
#[test]
fn every_axis_is_pinned_except_the_frame_count_the_door_reads_back() {
  /// The one axis this door READS: `mask`'s frame count, which is the
  /// artifact's and is `Dim::AnyFixed` rather than a number.
  const FREE: &[(&str, usize)] = &[(names::MASK, 1)];

  let base = wespeaker_description();
  let named = [names::MASK, names::WAVEFORM, names::EMBEDDING];
  let mut perturbations = 0_usize;
  for declared in base.inputs().iter().chain(base.outputs()) {
    if !named.contains(&declared.name()) {
      continue;
    }
    for axis in 0..declared.shape().len() {
      let perturbed = with_axis_bumped(&base, declared.name(), axis);
      let free = FREE.contains(&(declared.name(), axis));
      assert_eq!(
        check(&perturbed).is_ok(),
        free,
        "`{}` axis {axis}: the contract {} it",
        declared.name(),
        if free { "must accept" } else { "must refuse" }
      );
      perturbations += 1;
    }
  }
  // Non-vacuous: two rank-2 inputs and one rank-2 output.
  assert_eq!(perturbations, 6);
}

/// **Every named feature's element type is pinned**, which no check this door
/// replaced stated for more than the two it happened to look at. Each is
/// re-declared at a type the door does not write, and every one must be
/// refused.
#[test]
fn every_named_features_element_type_is_pinned() {
  let base = wespeaker_description();
  let named = [names::MASK, names::WAVEFORM, names::EMBEDDING];
  let mut checked = 0_usize;
  for declared in base.inputs().iter().chain(base.outputs()) {
    if !named.contains(&declared.name()) {
      continue;
    }
    let swap = |other: &FeatureInfo| -> FeatureInfo {
      if other.name() == declared.name() {
        fixed(other.name(), other.shape(), DataType::F16)
      } else {
        other.clone()
      }
    };
    let perturbed = ModelDescription::from_parts(
      base.inputs().iter().map(swap).collect(),
      base.outputs().iter().map(swap).collect(),
      base.states().to_vec(),
    );
    assert!(
      matches!(check(&perturbed), Err(ModelError::ContractMismatch(m))
        if m.feature() == declared.name()
          && m.expected() == "float32"
          && m.actual() == "float16"),
      "`{}` re-declared float16 must be refused",
      declared.name()
    );
    checked += 1;
  }
  assert_eq!(checked, 3);
}