coremlit 0.1.1

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
use super::*;

// ---------------------------------------------------------------------
// SlidingWindow: accessors, builders, dia visibility-decision conversion
// ---------------------------------------------------------------------

#[test]
fn sliding_window_accessors() {
  let sw = SlidingWindow::new(1.0, 2.0, 0.5);
  assert_eq!(sw.start(), 1.0);
  assert_eq!(sw.duration(), 2.0);
  assert_eq!(sw.step(), 0.5);
}

#[test]
fn sliding_window_builders_replace_fields() {
  let sw = SlidingWindow::new(0.0, 0.0, 0.0)
    .with_start(1.0)
    .with_duration(2.0)
    .with_step(3.0);
  assert_eq!(sw, SlidingWindow::new(1.0, 2.0, 3.0));
}

#[test]
fn sliding_window_is_copy() {
  let sw = SlidingWindow::new(1.0, 2.0, 3.0);
  let copy = sw;
  // Both usable after the "move" — proves Copy, not just Clone.
  assert_eq!(sw, copy);
}

#[test]
fn sliding_window_round_trips_into_dia_and_back() {
  let ours = SlidingWindow::new(0.25, 4.0, 1.5);
  let theirs: diaric::reconstruct::SlidingWindow = ours.into();
  assert_eq!(theirs.start(), 0.25);
  assert_eq!(theirs.duration(), 4.0);
  assert_eq!(theirs.step(), 1.5);
  let back: SlidingWindow = theirs.into();
  assert_eq!(back, ours);
}

// ---------------------------------------------------------------------
// WindowOptions: defaults, builders, validation, serde
// ---------------------------------------------------------------------

#[test]
fn options_new_matches_dia_defaults() {
  let o = WindowOptions::new();
  assert_eq!(o.step_samples(), 16_000);
  assert_eq!(o.onset(), 0.5);
}

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

#[test]
fn options_with_step_samples_overrides() {
  let o = WindowOptions::new().with_step_samples(40_000);
  assert_eq!(o.step_samples(), 40_000);
}

#[test]
fn options_set_step_samples_in_place() {
  let mut o = WindowOptions::new();
  o.set_step_samples(80_000);
  assert_eq!(o.step_samples(), 80_000);
}

#[test]
fn options_with_onset_overrides() {
  let o = WindowOptions::new().with_onset(0.7);
  assert_eq!(o.onset(), 0.7);
}

#[test]
fn options_set_onset_in_place() {
  let mut o = WindowOptions::new();
  o.set_onset(0.3);
  assert_eq!(o.onset(), 0.3);
}

#[test]
#[should_panic(expected = "step_samples must be > 0")]
fn options_with_step_samples_zero_panics() {
  let _ = WindowOptions::new().with_step_samples(0);
}

#[test]
#[should_panic(expected = "step_samples must be > 0")]
fn options_set_step_samples_zero_panics() {
  let mut o = WindowOptions::new();
  o.set_step_samples(0);
}

#[test]
#[should_panic(expected = "step_samples must be <= SEG_CHUNK_SAMPLES")]
fn options_with_step_samples_above_chunk_panics() {
  let _ = WindowOptions::new().with_step_samples(SEG_CHUNK_SAMPLES as u32 + 1);
}

#[test]
fn options_with_step_samples_equal_to_chunk_ok() {
  let o = WindowOptions::new().with_step_samples(SEG_CHUNK_SAMPLES as u32);
  assert_eq!(o.step_samples(), SEG_CHUNK_SAMPLES as u32);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_zero_panics() {
  let _ = WindowOptions::new().with_onset(0.0);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_negative_panics() {
  let _ = WindowOptions::new().with_onset(-0.1);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_above_one_panics() {
  let _ = WindowOptions::new().with_onset(1.01);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_nan_panics() {
  let _ = WindowOptions::new().with_onset(f32::NAN);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_infinity_panics() {
  let _ = WindowOptions::new().with_onset(f32::INFINITY);
}

#[test]
#[should_panic(expected = "onset must be finite in (0.0, 1.0]")]
fn options_with_onset_neg_infinity_panics() {
  let _ = WindowOptions::new().with_onset(f32::NEG_INFINITY);
}

#[test]
fn options_with_onset_one_ok() {
  let o = WindowOptions::new().with_onset(1.0);
  assert_eq!(o.onset(), 1.0);
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_missing_fields_default() {
  let o: WindowOptions = serde_json::from_str("{}").unwrap();
  assert_eq!(o, WindowOptions::new());
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_round_trips_explicit_values() {
  let o: WindowOptions = serde_json::from_str(r#"{"step_samples":40000,"onset":0.7}"#).unwrap();
  assert_eq!(o.step_samples(), 40_000);
  assert_eq!(o.onset(), 0.7);
  let json = serde_json::to_string(&o).unwrap();
  assert!(json.contains("40000"), "round-tripped json: {json}");
  assert!(json.contains("0.7"), "round-tripped json: {json}");
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_partial_fields_default_the_rest() {
  let o: WindowOptions = serde_json::from_str(r#"{"onset":0.3}"#).unwrap();
  assert_eq!(o.step_samples(), 16_000);
  assert_eq!(o.onset(), 0.3);
}

// L1: `Deserialize` must route through the SAME invariants the checked setters
// enforce (`serde(try_from = WindowOptionsRepr)`), not bypass them. The derived
// field-Deserialize let `{"step_samples":200000}` construct geometry that
// silently drops the samples in `[SEG_CHUNK_SAMPLES, step)` of every chunk.

#[cfg(feature = "serde")]
#[test]
fn options_serde_rejects_step_samples_exceeding_window() {
  // The brief's exact witness: 200000 > SEG_CHUNK_SAMPLES (160000). On 320000
  // samples this produced windows [0,160000)+[200000,360000), omitting
  // [160000,200000). Must now fail to deserialize.
  let r: Result<WindowOptions, _> = serde_json::from_str(r#"{"step_samples":200000,"onset":0.5}"#);
  assert!(
    r.is_err(),
    "step_samples 200000 > SEG_CHUNK_SAMPLES must fail to deserialize, got {r:?}"
  );
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_rejects_zero_step_samples() {
  let r: Result<WindowOptions, _> = serde_json::from_str(r#"{"step_samples":0}"#);
  assert!(
    r.is_err(),
    "step_samples 0 must fail to deserialize, got {r:?}"
  );
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_rejects_out_of_range_onset() {
  for bad in [r#"{"onset":0.0}"#, r#"{"onset":1.5}"#, r#"{"onset":-0.1}"#] {
    let r: Result<WindowOptions, _> = serde_json::from_str(bad);
    assert!(r.is_err(), "{bad} must fail to deserialize, got {r:?}");
  }
}

#[cfg(feature = "serde")]
#[test]
fn options_serde_accepts_valid_boundary_values() {
  // The deserialize path must be no stricter than the builders: `step ==
  // SEG_CHUNK_SAMPLES` and `onset == 1.0` are both valid at the setter
  // (`options_with_step_samples_equal_to_chunk_ok`, `options_with_onset_one_ok`).
  let o: WindowOptions = serde_json::from_str(r#"{"step_samples":160000,"onset":1.0}"#).unwrap();
  assert_eq!(o.step_samples(), 160_000);
  assert_eq!(o.onset(), 1.0);
}

/// [`WindowOptions`]'s `Display`, pinned byte-exactly: this composes into
/// [`crate::audio::speaker::extract::Options`]'s own persisted-fingerprint
/// spelling (nested in parentheses there), so a silent respelling here would
/// silently invalidate every fingerprint built on it.
#[test]
fn window_options_display_pins_the_spelling() {
  assert_eq!(
    WindowOptions::new().to_string(),
    "step_samples=16000,onset=0.5"
  );
  assert_eq!(
    WindowOptions::new()
      .with_step_samples(8_000)
      .with_onset(0.75)
      .to_string(),
    "step_samples=8000,onset=0.75"
  );
}

// ---------------------------------------------------------------------
// chunk_starts: hand-computed geometry edge cases (brief Step 1)
// ---------------------------------------------------------------------

#[test]
fn chunk_starts_zero_samples_yields_single_zero_padded_chunk() {
  // See the module doc's "total_samples == 0" note: the formula's own
  // literal answer is one fully-zero-padded chunk. dia's own pipeline
  // never reaches this arithmetic for empty audio (it rejects earlier,
  // `owned.rs:369-371`) — this is this crate's own, documented, total
  // answer for the input domain a Result-free function must cover.
  let starts = chunk_starts(0, &WindowOptions::new());
  assert_eq!(starts, vec![0]);
}

#[test]
fn chunk_starts_shorter_than_one_chunk_yields_single_start() {
  let starts = chunk_starts(50_000, &WindowOptions::new());
  assert_eq!(starts, vec![0]);
}

#[test]
fn chunk_starts_exactly_one_chunk_yields_single_start() {
  let starts = chunk_starts(SEG_CHUNK_SAMPLES, &WindowOptions::new());
  assert_eq!(starts, vec![0]);
}

#[test]
fn chunk_starts_chunk_plus_one_sample_yields_two_chunks() {
  let starts = chunk_starts(SEG_CHUNK_SAMPLES + 1, &WindowOptions::new());
  assert_eq!(starts, vec![0, 16_000]);
}

#[test]
fn chunk_starts_chunk_plus_step_yields_two_chunks_exact_fit() {
  let starts = chunk_starts(SEG_CHUNK_SAMPLES + 16_000, &WindowOptions::new());
  assert_eq!(starts, vec![0, 16_000]);
}

#[test]
fn chunk_starts_chunk_plus_step_plus_one_yields_three_chunks() {
  let starts = chunk_starts(SEG_CHUNK_SAMPLES + 16_000 + 1, &WindowOptions::new());
  assert_eq!(starts, vec![0, 16_000, 32_000]);
}

#[test]
fn chunk_starts_multi_chunk_regular_grid() {
  let starts = chunk_starts(SEG_CHUNK_SAMPLES + 3 * 16_000, &WindowOptions::new());
  assert_eq!(starts, vec![0, 16_000, 32_000, 48_000]);
}

#[test]
fn chunk_starts_custom_step() {
  let options = WindowOptions::new().with_step_samples(40_000);
  let starts = chunk_starts(200_000, &options);
  assert_eq!(starts, vec![0, 40_000]);
}

#[test]
fn chunk_starts_step_equal_to_chunk_no_overlap() {
  let options = WindowOptions::new().with_step_samples(SEG_CHUNK_SAMPLES as u32);
  let starts = chunk_starts(2 * SEG_CHUNK_SAMPLES, &options);
  assert_eq!(starts, vec![0, SEG_CHUNK_SAMPLES]);
}

#[test]
#[should_panic(expected = "step_samples must be > 0")]
fn chunk_starts_panics_on_zero_step_via_bypassed_options() {
  // WindowOptions's own builder rejects step_samples == 0 (see the
  // options panic tests above); construct the field directly here
  // (this test module is a child of `window`, so private fields are
  // visible) to simulate a serde-deserialized WindowOptions that
  // bypassed builder validation — the exact scenario chunk_starts' own
  // defense-in-depth assert exists for.
  let options = WindowOptions {
    step_samples: 0,
    onset: DEFAULT_ONSET,
  };
  let _ = chunk_starts(1_000_000, &options);
}

// ---------------------------------------------------------------------
// chunk_sliding_window / frame_sliding_window
// ---------------------------------------------------------------------

#[test]
fn chunk_sliding_window_matches_dia_defaults() {
  let sw = chunk_sliding_window(&WindowOptions::new());
  assert_eq!(sw.start(), 0.0);
  assert_eq!(sw.duration(), 10.0);
  assert_eq!(sw.step(), 1.0); // 16_000 / 16_000
}

#[test]
fn chunk_sliding_window_reflects_custom_step() {
  let options = WindowOptions::new().with_step_samples(40_000);
  let sw = chunk_sliding_window(&options);
  assert_eq!(sw.step(), 2.5); // 40_000 / 16_000
}

#[test]
fn frame_sliding_window_matches_dia_constants() {
  let sw = frame_sliding_window();
  assert_eq!(sw.start(), 0.0);
  assert_eq!(sw.duration(), 0.0619375);
  assert_eq!(sw.step(), 0.016875);
}

// ---------------------------------------------------------------------
// count_from_segmentations: hand-computed 3-chunk overlap (brief Step 1)
// plus the diaric code-oracle cross-check (brief Step 1, "THE ORACLE IS
// CODE")
// ---------------------------------------------------------------------

/// Synthetic 3-chunk overlap scenario shared between the hand-computed
/// hermetic test and the `diaric` code-oracle test: `num_chunks=3`,
/// `num_frames_per_chunk=4`, `num_speakers=2`, `chunks_sw = (0.0, 4.0,
/// 2.0)`, `frames_sw = (0.0, 1.0, 1.0)`, `onset=0.5`.
///
/// Hand derivation (also independently re-derived by diaric's own
/// `try_count_pyannote` in the `diaric` oracle test below):
///
/// `chunk_count[c][f]` (active-speaker count per (chunk, frame), `v >=
/// 0.5`):
/// - c=0: `[1, 2, 1, 0]` (f=2 has `s0 == 0.5`, exactly at onset —
///   exercises the inclusive `>=`)
/// - c=1: `[2, 1, 1, 2]`
/// - c=2: `[1, 2, 1, 0]`
///
/// `start_frame(c) = round_ties_even(c * 2.0 / 1.0)`: `0, 2, 4` (exact,
/// no rounding needed). `num_output_frames = round_ties_even((4.0 + 2 *
/// 2.0) / 1.0) + 1 = 9`.
///
/// Per-output-frame `(aggregated, overlapping_count)`:
/// `t=0: (1,1)`, `t=1: (2,1)`, `t=2: (1+2=3,2)`, `t=3: (0+1=1,2)`,
/// `t=4: (1+1=2,2)`, `t=5: (2+2=4,2)`, `t=6: (1,1)`, `t=7: (0,1)`,
/// `t=8: (0,0)` (no chunk covers frame 8 — c=2's frames only reach
/// `start_frame(2) + 3 = 7`).
///
/// `count[t] = round_ties_even(aggregated[t] / overlapping_count[t])`,
/// `0` where uncovered: `[1, 2, 2, 0, 1, 2, 1, 0, 0]`. `t=2` (`3/2 =
/// 1.5`) and `t=3` (`1/2 = 0.5`) both exercise round_ties_even's
/// banker's-rounding tie rule (1.5 -> 2, the nearest EVEN integer; 0.5
/// -> 0, likewise nearest even) — not "round half up", which would give
/// `[1, 2, 2, 1, 1, 2, 1, 0, 0]` instead.
fn three_chunk_overlap_segmentations() -> Vec<f64> {
  #[rustfmt::skip]
  let segs = vec![
    1.0, 0.0,  1.0, 1.0,  0.5, 0.0,  0.0, 0.0, // c=0: f0..f3
    1.0, 1.0,  0.4, 0.6,  1.0, 0.0,  1.0, 1.0, // c=1: f0..f3
    0.0, 1.0,  1.0, 1.0,  1.0, 0.0,  0.0, 0.0, // c=2: f0..f3
  ];
  segs
}

#[test]
fn count_from_segmentations_single_chunk_no_overlap() {
  // 1 chunk, 3 frames, 2 speakers — isolates the basic accumulate/divide
  // path (no overlap) before the multi-chunk scenario below.
  #[rustfmt::skip]
  let segmentations = vec![
    1.0, 0.0, // f0: 1 active
    1.0, 1.0, // f1: 2 active
    0.0, 0.0, // f2: 0 active
  ];
  let chunks_sw = SlidingWindow::new(0.0, 3.0, 1.0);
  let frames_sw = SlidingWindow::new(0.0, 1.0, 1.0);
  let got = count_from_segmentations(&segmentations, 1, 3, 2, 0.5, chunks_sw, frames_sw);
  // num_output_frames = round(3.0 / 1.0) + 1 = 4; output frame 3 is
  // never covered by the single chunk's 3 frames (0..=2).
  assert_eq!(got, vec![1, 2, 0, 0]);
}

#[test]
fn count_from_segmentations_hand_computed_3_chunk_overlap() {
  let segmentations = three_chunk_overlap_segmentations();
  let chunks_sw = SlidingWindow::new(0.0, 4.0, 2.0);
  let frames_sw = SlidingWindow::new(0.0, 1.0, 1.0);

  let got = count_from_segmentations(&segmentations, 3, 4, 2, 0.5, chunks_sw, frames_sw);

  assert_eq!(got, vec![1, 2, 2, 0, 1, 2, 1, 0, 0]);
}

#[test]
fn try_aggregate_output_frame_count_reproduces_the_hand_computed_overlap() {
  // Direct cover for the extracted `try_aggregate_output_frame_count` seam (the
  // steps-2..4 overlap-add + round_ties_even that `try_count_from_segmentations`
  // and `Extraction::diarize_online` now share). Feeding it the step-1 chunk_count
  // the 3-chunk-overlap fixture documents (c=0:[1,2,1,0], c=1:[2,1,1,2],
  // c=2:[1,2,1,0]) must reproduce that fixture's end-to-end output vector — proving
  // the refactor's step-1 / steps-2..4 split is value-identical, not just that the
  // whole `count_from_segmentations` wrapper still passes.
  #[rustfmt::skip]
  let chunk_count = [
    1.0, 2.0, 1.0, 0.0, // c=0
    2.0, 1.0, 1.0, 2.0, // c=1
    1.0, 2.0, 1.0, 0.0, // c=2
  ];
  let got = try_aggregate_output_frame_count(
    &chunk_count,
    3,
    4,
    SlidingWindow::new(0.0, 4.0, 2.0),
    SlidingWindow::new(0.0, 1.0, 1.0),
  )
  .expect("valid geometry: num_output_frames fits usize");
  assert_eq!(got, vec![1, 2, 2, 0, 1, 2, 1, 0, 0]);
}

#[test]
fn count_from_segmentations_matches_dia_oracle_3_chunk_overlap() {
  // THE ORACLE IS CODE: dia's own `try_count_pyannote` is public
  // (`diarization::aggregate::try_count_pyannote`) and is called here
  // directly on the SAME synthetic segmentations this crate's hermetic
  // test hand-derives an expected vector for — an independent,
  // compiled-code cross-check of that hand math, not just a repeat of
  // it.
  let segmentations = three_chunk_overlap_segmentations();

  let ours = count_from_segmentations(
    &segmentations,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 4.0, 2.0),
    SlidingWindow::new(0.0, 1.0, 1.0),
  );

  let golden = diaric::aggregate::try_count_pyannote(
    &segmentations,
    3,
    4,
    2,
    0.5_f64,
    diaric::reconstruct::SlidingWindow::new(0.0, 4.0, 2.0),
    diaric::reconstruct::SlidingWindow::new(0.0, 1.0, 1.0),
    &diaric::spill::SpillOptions::default(),
  )
  .expect("dia try_count_pyannote on synthetic 3-chunk overlap");

  assert_eq!(ours.as_slice(), golden.count_slice());
  // Cross-check against the hand-derived vector too, so a divergence
  // between the hand math and dia's own oracle would fail HERE, not
  // just in the separate hermetic test.
  assert_eq!(ours, vec![1, 2, 2, 0, 1, 2, 1, 0, 0]);
}

// ---------------------------------------------------------------------
// count_from_segmentations: dia oracle cross-check at this crate's
// DEFAULT production geometry (~10x nominal simultaneous overlap —
// CHUNK_DURATION_S / step_s = 10.0 / 1.0 = 10 — vs. the 2x-overlap
// fixture above)
// ---------------------------------------------------------------------

// Consumed only by the diaric code-oracle cross-check test below (unlike
// `three_chunk_overlap_segmentations` above, there is no separate
// hermetic hand-derived test at this data volume — see that test's own
// doc for why). `diaric` is a runtime dependency, so `diaric::aggregate` is
// always available and this fixture + its oracle test compile
// unconditionally.
const DEFAULT_10X_NUM_CHUNKS: usize = 15;
/// dia's real `FRAMES_PER_WINDOW` (`diarization/src/segment/options.rs:
/// 21`) — the actual pyannote segmentation model's per-chunk frame
/// count (also this crate's own introspected model contract, the
/// `crate::audio::speaker::segment` module doc's `[1, 589, 7]`). A smaller synthetic
/// frame count would NOT exercise genuine 10x overlap: consecutive
/// chunks' `start_frame(c) = round_ties_even(c * chunk_step /
/// frame_step)` values are ~59.26 frames apart (`1.0 / 0.016875`), so a
/// chunk's own frame span must be close to this real value for ~10
/// consecutive chunks' windows to overlap a common output frame at all.
const DEFAULT_10X_NUM_FRAMES_PER_CHUNK: usize = 589;
const DEFAULT_10X_NUM_SPEAKERS: usize = 2;

/// Synthetic segmentations at this crate's DEFAULT production geometry
/// (`chunk_sliding_window(&WindowOptions::new())` = `(0.0, 10.0, 1.0)`,
/// `frame_sliding_window()` = `(0.0, 0.0619375, 0.016875)`).
///
/// Base values follow `((c * 37 + f * 17 + s * 11) % 10) as f64 / 10.0`
/// — deterministic, spans `{0.0, 0.1, ..., 0.9}`, crossing `onset =
/// 0.5` in both directions broadly across the whole tensor (including
/// exact `0.5` hits from the formula itself, at cells where `(c * 37 +
/// f * 17 + s * 11) % 10 == 5`).
///
/// Ten cells are then deliberately overridden to force output frame `t
/// = 711` onto an EXACT `round_ties_even` rounding TIE at full 10x
/// overlap — a structurally different tie than the 2x-overlap fixture
/// above (that one ties at divisor 2; a divisor-10 tie is only possible
/// where the covering-chunk count is EVEN, and only exists at all in
/// the interior of a long-enough recording). Exact arithmetic
/// (`start_frame(c) = round_ties_even(c * 1.0 / 0.016875)` for `c` in
/// `0..15`): output frame `t = 711` is covered by EXACTLY chunks `[3, 4,
/// 5, 6, 7, 8, 9, 10, 11, 12]` (10 consecutive chunks — a covering
/// range is always contiguous, since `start_frame` is monotonic in
/// `c`), at local frame offsets `t - start_frame(c)`:
///
/// | c        | 3   | 4   | 5   | 6   | 7   | 8   | 9   | 10  | 11 | 12 |
/// |----------|-----|-----|-----|-----|-----|-----|-----|-----|----|----|
/// | local_f  | 533 | 474 | 415 | 355 | 296 | 237 | 178 | 118 | 59 | 0  |
///
/// Chunks `3..=7` get speaker 0 forced ACTIVE (`1.0`) at their local
/// frame (speaker 1 forced `0.0`) — `chunk_count = 1` each. Chunks
/// `8..=12` get BOTH speakers forced `0.0` — `chunk_count = 0` each.
/// `aggregated[711] = 5 * 1 + 5 * 0 = 5`, `overlapping_count[711] =
/// 10`, ratio `0.5` exactly — `round_ties_even` rounds to the nearest
/// EVEN integer, `0`.
fn default_geometry_10x_overlap_segmentations() -> Vec<f64> {
  let mut segs =
    vec![
      0.0_f64;
      DEFAULT_10X_NUM_CHUNKS * DEFAULT_10X_NUM_FRAMES_PER_CHUNK * DEFAULT_10X_NUM_SPEAKERS
    ];
  for c in 0..DEFAULT_10X_NUM_CHUNKS {
    for f in 0..DEFAULT_10X_NUM_FRAMES_PER_CHUNK {
      for s in 0..DEFAULT_10X_NUM_SPEAKERS {
        let idx = (c * DEFAULT_10X_NUM_FRAMES_PER_CHUNK + f) * DEFAULT_10X_NUM_SPEAKERS + s;
        segs[idx] = ((c * 37 + f * 17 + s * 11) % 10) as f64 / 10.0;
      }
    }
  }

  let overrides: [(usize, usize, bool); 10] = [
    (3, 533, true),
    (4, 474, true),
    (5, 415, true),
    (6, 355, true),
    (7, 296, true),
    (8, 237, false),
    (9, 178, false),
    (10, 118, false),
    (11, 59, false),
    (12, 0, false),
  ];
  for (c, f, active) in overrides {
    let base = (c * DEFAULT_10X_NUM_FRAMES_PER_CHUNK + f) * DEFAULT_10X_NUM_SPEAKERS;
    segs[base] = if active { 1.0 } else { 0.0 }; // speaker 0
    segs[base + 1] = 0.0; // speaker 1: always inactive at these cells
  }

  segs
}

#[test]
fn count_from_segmentations_matches_dia_oracle_default_geometry_10x_overlap() {
  let segmentations = default_geometry_10x_overlap_segmentations();
  let chunks_sw = chunk_sliding_window(&WindowOptions::new());
  let frames_sw = frame_sliding_window();

  let ours = count_from_segmentations(
    &segmentations,
    DEFAULT_10X_NUM_CHUNKS,
    DEFAULT_10X_NUM_FRAMES_PER_CHUNK,
    DEFAULT_10X_NUM_SPEAKERS,
    0.5,
    chunks_sw,
    frames_sw,
  );

  let golden = diaric::aggregate::try_count_pyannote(
    &segmentations,
    DEFAULT_10X_NUM_CHUNKS,
    DEFAULT_10X_NUM_FRAMES_PER_CHUNK,
    DEFAULT_10X_NUM_SPEAKERS,
    0.5_f64,
    chunks_sw.into(),
    frames_sw.into(),
    &diaric::spill::SpillOptions::default(),
  )
  .expect("dia try_count_pyannote on default-geometry 10x-overlap synthetic fixture");

  assert_eq!(ours.as_slice(), golden.count_slice());
  // Pin the deliberately engineered round_ties_even tie directly too —
  // makes the construction's intent independently checkable, not just
  // implied by the oracle match.
  assert_eq!(ours[711], 0);
}

// ---------------------------------------------------------------------
// count_from_segmentations: precondition panics ("Who validates dims")
// ---------------------------------------------------------------------

#[test]
#[should_panic(expected = "num_chunks must be at least 1")]
fn count_from_segmentations_panics_on_zero_num_chunks() {
  let _ = count_from_segmentations(
    &[],
    0,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "num_frames_per_chunk must be at least 1")]
fn count_from_segmentations_panics_on_zero_num_frames_per_chunk() {
  let _ = count_from_segmentations(
    &[],
    3,
    0,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "num_speakers must be at least 1")]
fn count_from_segmentations_panics_on_zero_num_speakers() {
  let _ = count_from_segmentations(
    &[],
    3,
    4,
    0,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "chunks_sw.duration() must be a positive finite scalar")]
fn count_from_segmentations_panics_on_zero_chunk_duration() {
  let segs = vec![0.0; 3 * 4 * 2];
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 0.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "chunks_sw.step() must be a positive finite scalar")]
fn count_from_segmentations_panics_on_negative_chunk_step() {
  let segs = vec![0.0; 3 * 4 * 2];
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, -1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "frames_sw.duration() must be a positive finite scalar")]
fn count_from_segmentations_panics_on_non_finite_frame_duration() {
  let segs = vec![0.0; 3 * 4 * 2];
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    SlidingWindow::new(0.0, f64::NAN, 0.016875),
  );
}

#[test]
#[should_panic(expected = "frames_sw.step() must be a positive finite scalar")]
fn count_from_segmentations_panics_on_non_finite_frame_step() {
  let segs = vec![0.0; 3 * 4 * 2];
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    SlidingWindow::new(0.0, 0.0619375, f64::INFINITY),
  );
}

#[test]
#[should_panic(expected = "onset must be finite")]
fn count_from_segmentations_panics_on_non_finite_onset() {
  let segs = vec![0.0; 3 * 4 * 2];
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    f32::NAN,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(
  expected = "segmentations.len() must equal num_chunks * num_frames_per_chunk * num_speakers"
)]
fn count_from_segmentations_panics_on_length_mismatch() {
  let segs = vec![0.0; 23]; // one short of 3*4*2 = 24
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

#[test]
#[should_panic(expected = "segmentations must not contain NaN/infinite values")]
fn count_from_segmentations_panics_on_non_finite_segmentation_value() {
  let mut segs = vec![0.0; 24];
  segs[5] = f64::NAN;
  let _ = count_from_segmentations(
    &segs,
    3,
    4,
    2,
    0.5,
    SlidingWindow::new(0.0, 10.0, 1.0),
    frame_sliding_window(),
  );
}

// ---------------------------------------------------------------------
// try_num_output_frames / count_from_segmentations: output-frame-count
// overflow guard (review finding: adversarial-but-finite SlidingWindow
// values — both individually positive and finite, so no OTHER
// precondition assert above rejects them — previously drove
// `num_output_frames`'s division/round/cast/+1 sequence to a debug
// "attempt to add with overflow" panic, or a silent release wrap to 0,
// instead of a typed/diagnosable failure. See `try_num_output_frames`'s
// own doc for dia's cited guard this ports.)
// ---------------------------------------------------------------------

#[test]
fn try_num_output_frames_accepts_valid_geometry() {
  // Same last_chunk_end/frame_step as the hand-computed 3-chunk-overlap
  // fixture above: chunk_duration=4.0, chunk_step=2.0, num_chunks=3 ->
  // last_chunk_end = 4.0 + 2 * 2.0 = 8.0; frame_step=1.0 -> 8.0 + 1 = 9,
  // matching that fixture's documented num_output_frames = 9.
  assert_eq!(try_num_output_frames(8.0, 1.0), Ok(9));
}

#[test]
fn try_num_output_frames_rejects_infinite_division() {
  // Reviewer's exact adversarial construction: duration=1e300,
  // frame_step=1e-300 -> the division overflows f64 directly to +inf
  // (1e300 / 1e-300 = 1e600, outside f64's finite range). round_ties_even
  // of +inf is still +inf, caught by the `!frames_f.is_finite()` arm.
  assert_eq!(
    try_num_output_frames(1e300, 1e-300),
    Err(WindowError::OutputFrameCountOverflow)
  );
}

#[test]
fn try_num_output_frames_rejects_finite_but_saturating_division() {
  // A DIFFERENT adversarial route than the +inf case above: the
  // division stays FINITE (1e20 is far below f64::MAX ~1.8e308) but
  // exceeds usize::MAX (~1.8447e19 on 64-bit), so `as usize` would
  // saturate. Exercises the `frames_f >= usize::MAX as f64` arm
  // specifically, not the `!frames_f.is_finite()` arm above — dia's own
  // guard distinguishes the two, so this crate's port must too.
  assert_eq!(
    try_num_output_frames(1e20, 1.0),
    Err(WindowError::OutputFrameCountOverflow)
  );
}

#[test]
#[should_panic(expected = "num_output_frames must fit in usize")]
fn count_from_segmentations_panics_on_output_frame_count_overflow() {
  // End-to-end: the same +inf adversarial geometry, reached through the
  // public function. Both `chunks_sw` and `frames_sw` are constructible
  // via the public, unchecked `SlidingWindow::new`; no OTHER guard in
  // this function rejects them (duration/step are each individually
  // positive and finite — only their COMBINATION overflows
  // `num_output_frames`).
  let segs = vec![0.0; 1]; // num_chunks=1, num_frames_per_chunk=1, num_speakers=1
  let chunks_sw = SlidingWindow::new(0.0, 1e300, 1.0);
  let frames_sw = SlidingWindow::new(0.0, 0.0619375, 1e-300);
  let _ = count_from_segmentations(&segs, 1, 1, 1, 0.5, chunks_sw, frames_sw);
}

// ---------------------------------------------------------------------
// The two chunk→output-frame mappings (round 2, finding B)
// ---------------------------------------------------------------------

/// Reads back the grid length `diaric::reconstruct` ACTUALLY requires for this
/// geometry, by under-sizing the output grid and letting its
/// `OutputFrameCountTooSmall` guard report the minimum
/// (`diarization/src/reconstruct/algo.rs:478-492`). That minimum IS
/// `last_start_frame + num_frames_per_chunk`.
///
/// The oracle behind BOTH [`reconstruct_chunk_start_frame`] — a hand-written
/// mirror, because `diaric::reconstruct::SlidingWindow::closest_frame` is
/// private to that crate — and [`uncovered_last_chunk`], whose whole job is to
/// predict this number before `diaric` is called. One oracle for the two, so a
/// mirror that drifted could not satisfy one test by breaking the other.
fn diaric_required_output_frames(
  num_chunks: usize,
  num_frames_per_chunk: usize,
  chunks_sw: SlidingWindow,
  frames_sw: SlidingWindow,
) -> usize {
  const SPEAKERS: usize = 3;
  let segmentations = vec![0.0f64; num_chunks * num_frames_per_chunk * SPEAKERS];
  let hard: Vec<diaric::pipeline::ChunkAssignment> = vec![[0, -2, -2]; num_chunks];
  // One output frame: below any non-negative placement's requirement, so the
  // guard fires and names the minimum. `count.len()` must match — reconstruct
  // checks that first.
  let count = vec![0u8; 1];
  let input = diaric::reconstruct::ReconstructInput::new(
    &segmentations,
    num_chunks,
    num_frames_per_chunk,
    SPEAKERS,
    &hard,
    &count,
    1,
    chunks_sw.into(),
    frames_sw.into(),
  );
  match diaric::reconstruct::reconstruct(&input) {
    Err(diaric::reconstruct::Error::Shape(
      diaric::reconstruct::ShapeError::OutputFrameCountTooSmall { required, .. },
    )) => required,
    other => panic!("expected OutputFrameCountTooSmall to report the placement, got {other:?}"),
  }
}

/// The output frame `diaric::reconstruct` places the last chunk's first frame
/// at, peeled off [`diaric_required_output_frames`].
fn diaric_last_chunk_start_frame(
  num_chunks: usize,
  num_frames_per_chunk: usize,
  chunks_sw: SlidingWindow,
  frames_sw: SlidingWindow,
) -> i64 {
  (diaric_required_output_frames(num_chunks, num_frames_per_chunk, chunks_sw, frames_sw)
    - num_frames_per_chunk) as i64
}

#[test]
fn reconstruct_chunk_start_frame_mirrors_diarics_own_placement() {
  // The mirror is only worth having if it cannot drift from the thing it
  // mirrors. Each geometry below is checked against `diaric` itself, including
  // the one whose two mappings DISAGREE — which is the case a mirror derived
  // from the aggregation expression would get wrong.
  let community1_frames = frame_sliding_window();
  let cases: [(usize, usize, SlidingWindow, SlidingWindow); 5] = [
    // Community-1 production timing: 1 s chunk step on the 0.016875 s frame grid.
    (
      4,
      589,
      chunk_sliding_window(&WindowOptions::new()),
      community1_frames,
    ),
    // Unit grid, zero origins.
    (
      3,
      2,
      SlidingWindow::new(0.0, 1.0, 1.0),
      SlidingWindow::new(0.0, 1.0, 1.0),
    ),
    // Equal, CANCELLING non-zero origins — placement is unshifted.
    (
      3,
      2,
      SlidingWindow::new(1.0, 1.0, 1.0),
      SlidingWindow::new(1.0, 1.0, 1.0),
    ),
    // An uncancelled origin — placement IS shifted, and negatively.
    (
      2,
      2,
      SlidingWindow::new(-1.0, 1.0, 1.0),
      SlidingWindow::new(0.0, 1.0, 1.0),
    ),
    // The round-2 finding-B geometry: both origins 0.0, and the two mappings
    // still disagree about chunk 1.
    (
      2,
      1,
      SlidingWindow::new(0.0, 0.04218750000000001, 0.04218750000000001),
      SlidingWindow::new(0.0, 0.0619375, 0.016875),
    ),
  ];
  for (num_chunks, num_frames_per_chunk, chunks_sw, frames_sw) in cases {
    let mirrored = reconstruct_chunk_start_frame(num_chunks - 1, chunks_sw, frames_sw);
    let actual =
      diaric_last_chunk_start_frame(num_chunks, num_frames_per_chunk, chunks_sw, frames_sw);
    assert_eq!(
      mirrored, actual,
      "mirror drifted from diaric for chunks_sw={chunks_sw:?} frames_sw={frames_sw:?}"
    );
  }
}

#[test]
fn the_two_chunk_mappings_agree_on_the_production_grid_and_split_on_the_finding_b_grid() {
  // `aggregate_chunk_start_frame` is what the count aggregation uses;
  // `reconstruct_chunk_start_frame` is what `diaric::reconstruct` uses. On the
  // community-1 grid the two agree for every chunk in a 12-hour clip, which is
  // why nothing downstream had ever noticed they are different expressions.
  let chunks_sw = chunk_sliding_window(&WindowOptions::new());
  let frames_sw = frame_sliding_window();
  for c in 0..43_200 {
    assert_eq!(
      aggregate_chunk_start_frame(c, chunks_sw.step(), frames_sw.step()),
      reconstruct_chunk_start_frame(c, chunks_sw, frames_sw),
      "production grid, chunk {c}"
    );
  }

  // And the finding-B geometry splits them by a whole frame with BOTH origins
  // at 0.0 — the reconstruction route adds `frames_sw.duration / 2` and takes
  // it back off, and `(x + h) - h != x` in binary floating point.
  let d = 0.04218750000000001_f64;
  let chunks_sw = SlidingWindow::new(0.0, d, d);
  let frames_sw = SlidingWindow::new(0.0, 0.0619375, 0.016875);
  assert_eq!(
    aggregate_chunk_start_frame(1, chunks_sw.step(), frames_sw.step()),
    3
  );
  assert_eq!(reconstruct_chunk_start_frame(1, chunks_sw, frames_sw), 2);

  // Equal, non-zero origins cancel exactly: a zero-origin test would have
  // rejected this grid, and there is nothing wrong with it.
  let sw = SlidingWindow::new(1.0, 1.0, 1.0);
  for c in 0..8 {
    assert_eq!(
      aggregate_chunk_start_frame(c, sw.step(), sw.step()),
      reconstruct_chunk_start_frame(c, sw, sw),
      "cancelling origins, chunk {c}"
    );
  }
}

// ---------------------------------------------------------------------
// The last chunk's coverage (round 12)
// ---------------------------------------------------------------------

/// The whole justification for check 14: the number `uncovered_last_chunk`
/// predicts is `diaric`'s OWN `required`, MEASURED out of that crate rather
/// than restated here.
///
/// Round 12's finding turns on one claim — that
/// [`reconstruct_chunk_start_frame`] is already the quantity the coverage bound
/// needs, so the check is a CALL and not a fourth frame-index derivation. This
/// is that claim, falsifiable: for each geometry the predicted `required` must
/// equal what `diaric::reconstruct` reports when handed a grid too short. The
/// finding-B grid is in the list on purpose — its two mappings disagree by a
/// whole frame, so a coverage bound built on the AGGREGATION expression instead
/// would predict the wrong number there and only there.
#[test]
fn uncovered_last_chunks_requirement_is_diarics_own_required_measured_not_copied() {
  let community1_frames = frame_sliding_window();
  let cases: [(usize, usize, SlidingWindow, SlidingWindow); 6] = [
    // Community-1 production timing, the shipped 589-frame grid.
    (
      4,
      589,
      chunk_sliding_window(&WindowOptions::new()),
      community1_frames,
    ),
    // The round-12 repro: 594 frames over three default chunks.
    (
      3,
      594,
      chunk_sliding_window(&WindowOptions::new()),
      community1_frames,
    ),
    // The producer repro: a 595-frame segmenter on a one-chunk clip.
    (
      1,
      595,
      chunk_sliding_window(&WindowOptions::new()),
      community1_frames,
    ),
    // Unit grid, zero origins.
    (
      3,
      2,
      SlidingWindow::new(0.0, 1.0, 1.0),
      SlidingWindow::new(0.0, 1.0, 1.0),
    ),
    // Equal, CANCELLING non-zero origins.
    (
      3,
      2,
      SlidingWindow::new(1.0, 1.0, 1.0),
      SlidingWindow::new(1.0, 1.0, 1.0),
    ),
    // The round-2 finding-B geometry: the two mappings disagree about chunk 1,
    // so only the RECONSTRUCTION mapping predicts `diaric`'s requirement.
    (
      2,
      1,
      SlidingWindow::new(0.0, 0.04218750000000001, 0.04218750000000001),
      SlidingWindow::new(0.0, 0.0619375, 0.016875),
    ),
  ];
  for (num_chunks, num_frames_per_chunk, chunks_sw, frames_sw) in cases {
    let actual =
      diaric_required_output_frames(num_chunks, num_frames_per_chunk, chunks_sw, frames_sw);
    // A grid one frame short of `actual` MUST be refused, and the payload must
    // name that very number.
    let u = uncovered_last_chunk(
      num_chunks,
      num_frames_per_chunk,
      actual - 1,
      chunks_sw,
      frames_sw,
    )
    .expect("a grid one frame short of diaric's requirement must be refused");
    assert_eq!(
      u.required(),
      actual,
      "predicted requirement drifted from diaric for {chunks_sw:?} / {frames_sw:?}"
    );
    assert_eq!(u.got(), actual - 1);
    assert_eq!(
      u.start_frame(),
      reconstruct_chunk_start_frame(num_chunks - 1, chunks_sw, frames_sw)
    );
    // And a grid of exactly `actual` must be accepted — the bound is `<`, not
    // `<=`, so the boundary itself is the case a sign error moves.
    assert_eq!(
      uncovered_last_chunk(
        num_chunks,
        num_frames_per_chunk,
        actual,
        chunks_sw,
        frames_sw
      ),
      None,
      "diaric's own requirement must be admitted"
    );
  }
}

/// The check is `<`, and a NEGATIVE placement is not checked at all — `diaric`
/// guards `last_start_frame >= 0` before deriving its requirement
/// (`diarization/src/reconstruct/algo.rs:478`), so refusing there would refuse
/// a geometry that crate accepts.
#[test]
fn uncovered_last_chunk_is_silent_below_frame_zero() {
  // An uncancelled negative chunk origin places chunk 0 at frame -1.
  let chunks_sw = SlidingWindow::new(-1.0, 1.0, 1.0);
  let frames_sw = SlidingWindow::new(0.0, 1.0, 1.0);
  assert_eq!(reconstruct_chunk_start_frame(0, chunks_sw, frames_sw), -1);
  assert_eq!(
    uncovered_last_chunk(1, 9_999, 1, chunks_sw, frames_sw),
    None,
    "a negative placement must not be refused here"
  );
}

// ---------------------------------------------------------------------
// The forward frame→time mapping (round 8, finding 2)
// ---------------------------------------------------------------------

/// Reads back the `(start, duration)` `diaric` ACTUALLY emits for a span, by
/// handing its public `discrete_to_spans` a one-cluster grid whose active run
/// is `t_start..t_end`.
///
/// This is the oracle for [`frame_center`], which has to be a hand-written
/// mirror: `try_discrete_to_spans` computes those times inline and takes a
/// whole grid, so there is no way to ask `diaric` for one frame's center.
///
/// `start` and `duration` are the two values that conversion actually computes
/// — `RttmSpan::new(k, s, e - s)` (`rttm.rs:255`) — so they pin both centers
/// exactly: `start` IS `frame_center(t_start)` and `duration` IS
/// `frame_center(t_end) - frame_center(t_start)`. `RttmSpan::end()` is NOT used
/// here, deliberately: it re-derives `start + duration`, and that round trip is
/// not the identity in binary floating point (on the `(-1.25, 0.1, 0.3)` grid
/// below it lands 5 ULP below the center it came from) — the same
/// re-association hazard `reconstruct_chunk_start_frame` exists for.
fn diaric_span_start_and_duration(
  t_start: usize,
  t_end: usize,
  num_frames: usize,
  frames_sw: SlidingWindow,
) -> (f64, f64) {
  assert!(t_end < num_frames, "the run must CLOSE inside the grid");
  let mut grid = vec![0.0f32; num_frames];
  grid[t_start..t_end].fill(1.0);
  let spans = diaric::reconstruct::discrete_to_spans(&grid, num_frames, 1, frames_sw.into(), 0.0);
  assert_eq!(spans.len(), 1, "one contiguous run is one span");
  (spans[0].start(), spans[0].duration())
}

#[test]
fn frame_center_mirrors_diarics_own_span_conversion() {
  // The mirror is only worth having if it cannot drift. `diaric` computes
  // `center_offset = duration / 2.0` ONCE and then `start + t * step +
  // center_offset`; the algebraically equal `start + (t * step + duration / 2)`
  // is a different `f64`, and these grids are chosen so that difference shows.
  let cases: [(usize, usize, usize, SlidingWindow); 5] = [
    // Community-1 production timing.
    (0, 1, 8, frame_sliding_window()),
    (13, 37, 64, frame_sliding_window()),
    // Unit grid, zero origin.
    (0, 1, 4, SlidingWindow::new(0.0, 1.0, 1.0)),
    // A non-zero origin, and a duration whose half is not exact in binary.
    (2, 5, 8, SlidingWindow::new(-1.25, 0.1, 0.3)),
    // A large origin against a small step: the regime finding 2 lives in, but
    // one ULP clear of the collapse (step 1e-6 > ULP(1e9)/2 = 5.96e-8).
    (1, 3, 6, SlidingWindow::new(1e9, 1e-6, 1e-6)),
  ];
  for (t_start, t_end, num_frames, frames_sw) in cases {
    let (start, duration) = diaric_span_start_and_duration(t_start, t_end, num_frames, frames_sw);
    let (lo, hi) = (
      frame_center(t_start, frames_sw),
      frame_center(t_end, frames_sw),
    );
    assert_eq!(
      (lo, hi - lo),
      (start, duration),
      "mirror drifted from diaric's span conversion for frames_sw={frames_sw:?}"
    );
  }
}

#[test]
fn first_collapsed_frame_center_finds_the_first_repeated_center() {
  // The community-1 grid is a usable timeline over the whole admitted range.
  assert_eq!(
    first_collapsed_frame_center(
      crate::audio::speaker::extract::MAX_OUTPUT_FRAMES,
      frame_sliding_window()
    ),
    None,
    "the only frame grid this crate's models produce must never collapse"
  );

  // Round 8, finding 2's window: at `start = 1e9` the f64 ULP is 1.19e-7, so a
  // step of 1e-8 adds nothing and frame 1 lands on frame 0's center.
  let collapsing = SlidingWindow::new(1e9, 1e-8, 1e-8);
  assert_eq!(
    f64::from_bits(1e9f64.to_bits() + 1) - 1e9,
    1.1920928955078125e-7
  );
  assert_eq!(1e9f64 + 1e-8, 1e9);
  let c = first_collapsed_frame_center(4, collapsing).expect("this grid collapses");
  assert_eq!((c.frame(), c.center(), c.previous()), (1, 1e9, 1e9));

  // A single frame cannot collapse — there is nothing to be equal to.
  assert_eq!(first_collapsed_frame_center(1, collapsing), None);
  assert_eq!(first_collapsed_frame_center(0, collapsing), None);

  // Not just the first pair: `step` exactly half an ULP with an EVEN mantissa
  // ties-to-even back onto the same value at t=1, separates at t=2, and ties
  // again at t=3 — so a check that only compared frames 0 and 1 would miss the
  // second collapse, and one that only tested the endpoints would miss both.
  let half_ulp = SlidingWindow::new(0.0, 0.0, f64::EPSILON / 2.0).with_start(1.0);
  let centers: Vec<f64> = (0..4).map(|t| frame_center(t, half_ulp)).collect();
  assert_eq!(centers[0], centers[1], "ties-to-even keeps frame 1 at 1.0");
  assert!(centers[2] > centers[1], "frame 2 does separate");
  assert_eq!(
    first_collapsed_frame_center(4, half_ulp).map(|c| c.frame()),
    Some(1)
  );
  assert_eq!(
    first_collapsed_frame_center(4, half_ulp.with_start(1.0 + f64::EPSILON)).map(|c| c.frame()),
    Some(2),
    "shifting the origin by one ULP moves WHICH pair collapses — the reason \
     this is an adjacent-pair scan and not an endpoint test"
  );

  // A non-finite center is caught where it occurs, frame 0 included.
  let overflowing = SlidingWindow::new(f64::MAX, f64::MAX, 1.0);
  let c = first_collapsed_frame_center(2, overflowing).expect("start + duration/2 overflows");
  assert_eq!((c.frame(), c.previous()), (0, f64::NEG_INFINITY));
  assert!(!c.center().is_finite());
}