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

/// Flatten spans to `(start, end)` pairs for terse geometry assertions.
fn offsets(plan: &WindowPlan, total: usize) -> Vec<(usize, usize)> {
  plan
    .spans(total)
    .unwrap()
    .iter()
    .map(|s| (s.start(), s.end()))
    .collect()
}

/// The naive soundevents `chunk_slices` geometry: starts at 0, H, 2H, … while
/// `start < total`, each chunk `[start, min(start + W, total))`. The reference
/// CED's multi-tail continuation must match for `total > WINDOW_SAMPLES` under
/// `TailPolicy::Pad` (spec §2: "matching soundevents' chunk_slices overlapped
/// semantics"). For `total <= WINDOW_SAMPLES` the short-clip guard deliberately
/// deviates (exactly one span regardless of hop — spec-settled), so this
/// reference is only consulted for long clips.
fn chunk_slices_reference(total: usize, window: usize, hop: usize) -> Vec<(usize, usize)> {
  let mut out = Vec::new();
  let mut start = 0usize;
  while start < total {
    out.push((start, total.min(start + window)));
    start += hop;
  }
  out
}

#[test]
fn window_samples_is_the_model_geometry() {
  assert_eq!(WINDOW_SAMPLES, 160_000); // 10 s × 16 kHz
  assert_eq!(DEFAULT_HOP_SAMPLES as usize, WINDOW_SAMPLES);
}

#[test]
fn default_plan_is_no_overlap_pad() {
  let plan = WindowPlan::default();
  assert_eq!(plan, WindowPlan::new());
  assert_eq!(plan.hop_samples(), DEFAULT_HOP_SAMPLES);
  assert_eq!(plan.tail_policy(), TailPolicy::Pad);
}

#[test]
fn empty_clip_plans_no_windows() {
  assert!(WindowPlan::new().spans(0).unwrap().is_empty());
}

#[test]
fn short_clip_is_one_window_regardless_of_hop() {
  // Clap contract 1: total <= window ⇒ exactly one span, even under a tiny hop
  // (where a literal soundevents chunk_slices would emit several sub-window
  // chunks — the recorded deviation, spec §2).
  let plan = WindowPlan::new().with_hop_samples(1_000);
  assert_eq!(offsets(&plan, 50_000), vec![(0, 50_000)]);
  assert_eq!(offsets(&plan, WINDOW_SAMPLES), vec![(0, WINDOW_SAMPLES)]);
}

#[test]
fn short_clip_survives_drop_below_min() {
  // A short clip's sole span is never dropped — there is nothing else to
  // represent it.
  let plan =
    WindowPlan::new().with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(100_000)));
  assert_eq!(offsets(&plan, 50_000), vec![(0, 50_000)]);
}

#[test]
fn short_clip_coverage_is_padding_aware() {
  let spans = WindowPlan::new().spans(40_000).unwrap();
  assert_eq!(spans.len(), 1);
  let coverage = spans[0].coverage();
  assert!(
    (coverage - 0.25).abs() < 1e-6,
    "40_000 / 160_000 = 0.25, got {coverage}"
  );
}

#[test]
fn no_overlap_tiling_with_padded_tail() {
  // 400_000 = 2 full windows + an 80_000-sample tail, kept under Pad.
  let plan = WindowPlan::new();
  assert_eq!(
    offsets(&plan, 400_000),
    vec![(0, 160_000), (160_000, 320_000), (320_000, 400_000)]
  );
}

#[test]
fn drop_below_min_drops_the_short_tail() {
  let plan =
    WindowPlan::new().with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(100_000)));
  // The 80_000-sample tail is below the 100_000 threshold.
  assert_eq!(
    offsets(&plan, 400_000),
    vec![(0, 160_000), (160_000, 320_000)]
  );
  // A tail AT the threshold is kept.
  assert_eq!(
    offsets(&plan, 420_000),
    vec![(0, 160_000), (160_000, 320_000), (320_000, 420_000)]
  );
}

#[test]
fn overlapping_hop_produces_full_windows_then_tails() {
  // hop 80_000 over 400_000: full windows at 0/80k/160k/240k, then the
  // multi-tail continuation keeps striding past windit's first-tail stop
  // (clap contract 2), emitting the 80k tail at 320k.
  let plan = WindowPlan::new().with_hop_samples(80_000);
  assert_eq!(
    offsets(&plan, 400_000),
    vec![
      (0, 160_000),
      (80_000, 240_000),
      (160_000, 320_000),
      (240_000, 400_000),
      (320_000, 400_000),
    ]
  );
}

#[test]
fn spans_match_soundevents_chunk_slices_for_long_clips() {
  // The Pad-policy geometry for total > WINDOW_SAMPLES is exactly soundevents'
  // chunk_slices (start, end) sequence — including EVERY progressively shorter
  // tail an overlapped hop generates.
  for (total, hop) in [
    (400_000usize, 80_000u32),
    (500_000, 60_000),
    (160_001, 160_000),
    (1_000_000, 160_000),
    (330_000, 100_000),
  ] {
    let plan = WindowPlan::new().with_hop_samples(hop);
    assert_eq!(
      offsets(&plan, total),
      chunk_slices_reference(total, WINDOW_SAMPLES, hop as usize),
      "total={total} hop={hop}"
    );
  }
}

#[test]
fn window_just_over_boundary_keeps_a_one_sample_tail_under_pad() {
  assert_eq!(
    offsets(&WindowPlan::new(), WINDOW_SAMPLES + 1),
    vec![(0, WINDOW_SAMPLES), (WINDOW_SAMPLES, WINDOW_SAMPLES + 1)]
  );
}

#[test]
fn span_geometry_accessors() {
  let spans = WindowPlan::new().spans(400_000).unwrap();
  let tail = spans[2];
  assert_eq!(tail.start(), 320_000);
  assert_eq!(tail.len(), 80_000);
  assert_eq!(tail.end(), 400_000);
  assert!((tail.coverage() - 0.5).abs() < 1e-6);
}

#[test]
#[should_panic(expected = "hop_samples")]
fn zero_hop_setter_panics() {
  let _ = WindowPlan::new().with_hop_samples(0);
}

#[test]
#[should_panic(expected = "hop_samples")]
fn hop_past_window_setter_panics() {
  // hop > window would leave gaps of un-classified audio (the soundevents
  // sparse-skim mode is a recorded non-goal).
  let _ = WindowPlan::new().with_hop_samples(WINDOW_SAMPLES as u32 + 1);
}

#[test]
#[should_panic(expected = "min_samples")]
fn zero_drop_min_setter_panics() {
  let _ = WindowPlan::new().with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(0)));
}

#[test]
fn hop_one_twenty_second_clip_is_rejected_typed() {
  // The codex [high] regression: a serde-supplied hop of 1 over a 20 s clip
  // would plan 320 000 windows (~643 MiB retained + 320 000 CoreML inferences).
  // The O(1) cap refuses it typed BEFORE materializing anything — this test
  // completing at all (no OOM, no 320 000 pushes) is half the point; the exact
  // `got` pins the FULL-count semantics (not windit's abort-at-`max + 1`).
  let plan = WindowPlan::new().with_hop_samples(1);
  let total = 2 * WINDOW_SAMPLES; // 320_000 = 20 s at 16 kHz
  let err = plan.spans(total).unwrap_err();
  assert!(
    matches!(
      err,
      Error::Windowing(WinditError::TooManyWindows { got: 320_000, max })
        if max == DEFAULT_MAX_WINDOWS as usize
    ),
    "expected TooManyWindows {{ got: 320_000, max: {} }}, got {err:?}",
    DEFAULT_MAX_WINDOWS
  );
}

#[test]
fn cap_boundary_exact_count_passes_and_plus_one_fails() {
  // hop 80_000 over 400_000 is the pinned 5-span geometry
  // (`overlapping_hop_produces_full_windows_then_tails`). A cap of exactly the
  // planned count admits it unchanged; one below refuses with the full count.
  let expected = vec![
    (0, 160_000),
    (80_000, 240_000),
    (160_000, 320_000),
    (240_000, 400_000),
    (320_000, 400_000),
  ];
  let at_cap = WindowPlan::new()
    .with_hop_samples(80_000)
    .with_max_windows(5);
  assert_eq!(offsets(&at_cap, 400_000), expected);

  let under_cap = WindowPlan::new()
    .with_hop_samples(80_000)
    .with_max_windows(4);
  let err = under_cap.spans(400_000).unwrap_err();
  assert!(
    matches!(
      err,
      Error::Windowing(WinditError::TooManyWindows { got: 5, max: 4 })
    ),
    "got {err:?}"
  );
}

#[test]
fn planned_windows_matches_materialized_len() {
  // The O(1) formula MUST equal the real materialized length for every
  // admissible geometry — otherwise the cap check would guard the wrong count.
  // The cap is lifted (`u32::MAX`) so only geometry, never the rail, is tested.
  let pad = |hop: u32| {
    WindowPlan::new()
      .with_hop_samples(hop)
      .with_max_windows(u32::MAX)
  };
  let drop_min = |hop: u32, min: u32| {
    WindowPlan::new()
      .with_hop_samples(hop)
      .with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(min)))
      .with_max_windows(u32::MAX)
  };
  let cases: [(WindowPlan, usize); 20] = [
    // Pad geometry (mirrors the chunk_slices grid) + boundary totals.
    (pad(80_000), 400_000),
    (pad(60_000), 500_000),
    (pad(160_000), 160_001),
    (pad(160_000), 1_000_000),
    (pad(100_000), 330_000),
    (pad(160_000), 0),
    (pad(160_000), 40_000),
    (pad(160_000), WINDOW_SAMPLES - 1),
    (pad(160_000), WINDOW_SAMPLES),
    (pad(160_000), WINDOW_SAMPLES + 1),
    (pad(1), WINDOW_SAMPLES),       // guard-1 immunity: 1 span
    (pad(1), WINDOW_SAMPLES + 100), // hop-1 multi-tail, materialized
    // DropBelowMin geometry (the pinned 400_000/420_000 @ 100_000 cases + edges).
    (drop_min(160_000, 100_000), 400_000),
    (drop_min(160_000, 100_000), 420_000),
    (drop_min(80_000, 100_000), 400_000),
    (drop_min(60_000, 40_000), 500_000),
    (drop_min(160_000, 160_000), 320_001),
    (drop_min(2, 100_000), 170_000), // small-hop multi-tail under a drop policy
    (drop_min(160_000, 100_000), 40_000),
    (drop_min(160_000, 100_000), 0),
  ];
  for (plan, total) in cases {
    assert_eq!(
      plan.planned_windows(total),
      plan.spans(total).unwrap().len(),
      "planned_windows != materialized len for hop={} tail={:?} total={total}",
      plan.hop_samples(),
      plan.tail_policy(),
    );
  }
}

#[test]
fn short_clip_never_trips_cap() {
  // Guard-1 immunity: a short clip is one span regardless of hop/cap, so even
  // the tightest cap admits it (planned == 1 <= any valid cap).
  let plan = WindowPlan::new().with_max_windows(1).with_hop_samples(1);
  let spans = plan.spans(WINDOW_SAMPLES).unwrap();
  assert_eq!(spans.len(), 1);
  assert_eq!((spans[0].start(), spans[0].end()), (0, WINDOW_SAMPLES));
}

#[test]
#[should_panic(expected = "max_windows")]
fn zero_max_windows_setter_panics() {
  let _ = WindowPlan::new().with_max_windows(0);
}

#[cfg(feature = "serde")]
mod serde_tests {
  use super::*;

  #[test]
  fn round_trips_through_json() {
    let plan = WindowPlan::new()
      .with_hop_samples(80_000)
      .with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(40_000)))
      .with_max_windows(50_000);
    let json = serde_json::to_string(&plan).unwrap();
    let back: WindowPlan = serde_json::from_str(&json).unwrap();
    assert_eq!(back, plan);
  }

  #[test]
  fn defaults_fill_for_a_partial_config() {
    let plan: WindowPlan = serde_json::from_str("{}").unwrap();
    assert_eq!(plan, WindowPlan::new());
    // The omitted cap fills the default — it is default-on for every config.
    assert_eq!(plan.max_windows(), DEFAULT_MAX_WINDOWS);
  }

  /// The [`TailPolicy`] document, pinned byte-exactly in BOTH directions, plus
  /// the whole-plan document that carries it.
  ///
  /// The form is windit 0.4's: adjacently tagged, `kind` naming the variant and
  /// `value` carrying the payload. The externally tagged `"pad"` /
  /// `{"drop_below_min":{…}}` spellings this replaced are asserted to be
  /// REFUSED, so the wire break is a fact this suite states rather than a
  /// comment somebody has to trust.
  #[test]
  fn tail_policy_wire_spellings_are_pinned() {
    // Wildcard-free: a new variant fails to compile until its spelling is
    // pinned here (the ChunkAggregation golden pattern, `aggregate/tests.rs`).
    for kind in [
      TailPolicy::Pad,
      TailPolicy::DropBelowMin(DropBelowMin::new(40_000)),
    ] {
      let expected = match kind {
        TailPolicy::Pad => "{\"kind\":\"pad\"}".to_string(),
        TailPolicy::DropBelowMin(d) => {
          let min_samples = d.min_samples();
          format!("{{\"kind\":\"drop_below_min\",\"value\":{{\"min_samples\":{min_samples}}}}}")
        }
      };
      assert_eq!(serde_json::to_string(&kind).unwrap(), expected);
      let back: TailPolicy = serde_json::from_str(&expected).unwrap();
      assert_eq!(back, kind);
    }
    assert_eq!(
      serde_json::to_string(&WindowPlan::new()).unwrap(),
      "{\"hop_samples\":160000,\"tail\":{\"kind\":\"pad\"},\"max_windows\":100000}"
    );
    // A whole non-default plan, serialized and read back from the SAME literal
    // document — the payload variant reached as a struct field, which is how a
    // config file actually carries it.
    let doc = "{\"hop_samples\":80000,\"tail\":{\"kind\":\"drop_below_min\",\
                \"value\":{\"min_samples\":40000}},\"max_windows\":50000}";
    let plan = WindowPlan::new()
      .with_hop_samples(80_000)
      .with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(40_000)))
      .with_max_windows(50_000);
    assert_eq!(serde_json::to_string(&plan).unwrap(), doc);
    assert_eq!(serde_json::from_str::<WindowPlan>(doc).unwrap(), plan);
    // The retired externally tagged form is refused, both variants.
    assert!(serde_json::from_str::<TailPolicy>("\"pad\"").is_err());
    assert!(
      serde_json::from_str::<TailPolicy>("{\"drop_below_min\":{\"min_samples\":40000}}").is_err()
    );
  }

  /// Every [`TailPolicy`] variant and the plans that carry it survive a
  /// NON-self-describing format.
  ///
  /// The falsifier for the `is_human_readable` split. postcard carries no field
  /// names, so the adjacently tagged form cannot be read back at all: serde
  /// writes the tag as a struct FIELD and reads it through
  /// `deserialize_identifier`, which postcard refuses. Measured on the derived
  /// `tail_policy_serde::Document` mirror — the exact shape the branch replaced
  /// — EVERY variant serializes and then fails to deserialize, `Pad` (bytes
  /// `[0]`) and `DropBelowMin` (`[1, …]`) alike; the unit variant additionally
  /// has its missing content read through `deserialize_any`. Drop the
  /// `is_human_readable` branch and all four cases below red — both policies
  /// and both plans, the DEFAULT `WindowPlan` included — while every JSON pin
  /// above stays green.
  #[test]
  fn every_variant_round_trips_through_a_non_self_describing_format() {
    for policy in [
      TailPolicy::Pad,
      TailPolicy::DropBelowMin(DropBelowMin::new(40_000)),
    ] {
      let bytes = postcard::to_allocvec(&policy).unwrap();
      assert_eq!(
        postcard::from_bytes::<TailPolicy>(&bytes).unwrap(),
        policy,
        "postcard round-trip lost {policy:?} (bytes {bytes:?})"
      );
    }
    for plan in [
      WindowPlan::new(),
      WindowPlan::new()
        .with_hop_samples(80_000)
        .with_tail_policy(TailPolicy::DropBelowMin(DropBelowMin::new(40_000)))
        .with_max_windows(50_000),
    ] {
      let bytes = postcard::to_allocvec(&plan).unwrap();
      assert_eq!(
        postcard::from_bytes::<WindowPlan>(&bytes).unwrap(),
        plan,
        "postcard round-trip lost {plan:?} (bytes {bytes:?})"
      );
    }
  }

  #[test]
  fn invalid_hop_fails_to_deserialize() {
    // The validated repr makes the checked setters unbypassable via serde:
    // hop 0 would loop forever, hop > window would skip audio.
    assert!(serde_json::from_str::<WindowPlan>("{\"hop_samples\":0}").is_err());
    assert!(serde_json::from_str::<WindowPlan>("{\"hop_samples\":160001}").is_err());
  }

  #[test]
  fn invalid_tail_min_fails_to_deserialize() {
    let json = "{\"tail\":{\"kind\":\"drop_below_min\",\"value\":{\"min_samples\":0}}}";
    assert!(serde_json::from_str::<WindowPlan>(json).is_err());
    let json = "{\"tail\":{\"kind\":\"drop_below_min\",\"value\":{\"min_samples\":160001}}}";
    assert!(serde_json::from_str::<WindowPlan>(json).is_err());
  }

  /// The rejection MESSAGE, pinned byte-exactly. `TailPolicy::DropBelowMin`
  /// carries a payload struct that shares its variant's name, so interpolating
  /// the PAYLOAD renders `DropBelowMin { min_samples: 0 }` — what the
  /// struct-shaped variant rendered before it was newtyped. Interpolating the
  /// whole policy instead would double the name, and nothing else asserts this.
  #[test]
  fn invalid_tail_min_rejection_message_names_the_payload_once() {
    let err = WindowPlan::try_from(WindowPlanRepr {
      hop_samples: DEFAULT_HOP_SAMPLES,
      tail: TailPolicy::DropBelowMin(DropBelowMin::new(0)),
      max_windows: DEFAULT_MAX_WINDOWS,
    })
    .unwrap_err();
    assert_eq!(
      err,
      "tail DropBelowMin.min_samples must be > 0 and <= WINDOW_SAMPLES \
       (160000), got DropBelowMin { min_samples: 0 }"
    );
  }

  #[test]
  fn zero_max_windows_fails_to_deserialize() {
    // A zero cap can never score any clip; the validated repr rejects it, just
    // as the setter panics on it.
    assert!(serde_json::from_str::<WindowPlan>("{\"max_windows\":0}").is_err());
  }

  /// A MISSPELLED key is REFUSED, not silently discarded.
  ///
  /// Every field defaults, so without `deny_unknown_fields` `{"max_window":1}`
  /// — the plural dropped — deserializes with the typo thrown away and
  /// `max_windows` filled from [`DEFAULT_MAX_WINDOWS`]: an operator capping the
  /// door at ONE window gets 100 000 instead, so a misspelled RESOURCE LIMIT
  /// silently becomes up to 100 000 CoreML predictions. A misspelled `hop` or
  /// `tail` key changes the scored geometry the same silent way. Each rejection
  /// is paired with the spelling that must still parse, so this cannot pass by
  /// the whole struct having stopped deserializing.
  #[test]
  fn a_misspelled_key_is_refused_rather_than_silently_defaulted() {
    for (doc, key) in [
      (r#"{"max_window":1}"#, "max_window"),
      (r#"{"hop":80000}"#, "hop"),
      (r#"{"tail_policy":{"kind":"pad"}}"#, "tail_policy"),
      // Beside a well-spelled key, where a permissive impl is likeliest to let
      // it through.
      (r#"{"hop_samples":80000,"max_window":1}"#, "max_window"),
    ] {
      let err = match serde_json::from_str::<WindowPlan>(doc) {
        Ok(plan) => panic!(
          "{doc} must be refused; it deserialized to {plan:?} (max_windows {})",
          plan.max_windows()
        ),
        Err(e) => e.to_string(),
      };
      assert!(
        err.contains(key),
        "the refusal must name {key}, got {err:?}"
      );
    }
    // Positive control: the correct spellings still parse and land.
    let ok: WindowPlan = serde_json::from_str(r#"{"hop_samples":80000,"max_windows":1}"#).unwrap();
    assert_eq!(ok.hop_samples(), 80_000);
    assert_eq!(ok.max_windows(), 1);
  }
}