whisper-apr 0.3.3

WASM-first automatic speech recognition engine implementing OpenAI Whisper
Documentation
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
//! Tests for pre-publish verification module
#![allow(clippy::unwrap_used, clippy::large_stack_arrays)]
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;

#[test]
fn test_check_result() {
    let pass = CheckResult::pass("test", "ok");
    assert!(pass.passed);
    assert_eq!(pass.name, "test");
    assert_eq!(pass.message, "ok");

    let fail = CheckResult::fail("test", "error");
    assert!(!fail.passed);
    assert_eq!(fail.name, "test");
    assert_eq!(fail.message, "error");
}

#[test]
fn test_check_result_clone() {
    let result = CheckResult::pass("name", "msg");
    let cloned = result.clone();
    assert_eq!(result.name, cloned.name);
    assert_eq!(result.passed, cloned.passed);
}

#[test]
fn test_verification_report() {
    let mut report = VerificationReport::new();
    assert!(report.passed);

    report.add(CheckResult::pass("a", "ok"));
    report.add(CheckResult::pass("b", "ok"));
    report.add(CheckResult::fail("c", "error"));

    assert!(!report.passed);
    assert_eq!(report.total_checks, 3);
    assert_eq!(report.passed_checks, 2);
    assert!((report.pass_rate() - 66.67).abs() < 0.1);
}

#[test]
fn test_verification_report_empty() {
    let report = VerificationReport::new();
    assert!(report.passed);
    assert_eq!(report.total_checks, 0);
    assert_eq!(report.passed_checks, 0);
    assert!((report.pass_rate() - 100.0).abs() < 0.01);
}

#[test]
fn test_verification_report_all_pass() {
    let mut report = VerificationReport::new();
    report.add(CheckResult::pass("a", "ok"));
    report.add(CheckResult::pass("b", "ok"));
    report.add(CheckResult::pass("c", "ok"));

    assert!(report.passed);
    assert_eq!(report.total_checks, 3);
    assert_eq!(report.passed_checks, 3);
    assert!((report.pass_rate() - 100.0).abs() < 0.01);
}

#[test]
fn test_verification_report_all_fail() {
    let mut report = VerificationReport::new();
    report.add(CheckResult::fail("a", "err"));
    report.add(CheckResult::fail("b", "err"));

    assert!(!report.passed);
    assert_eq!(report.total_checks, 2);
    assert_eq!(report.passed_checks, 0);
    assert!((report.pass_rate() - 0.0).abs() < 0.01);
}

#[test]
fn test_verification_report_clone() {
    let mut report = VerificationReport::new();
    report.add(CheckResult::pass("a", "ok"));
    let cloned = report.clone();
    assert_eq!(report.total_checks, cloned.total_checks);
    assert_eq!(report.passed, cloned.passed);
}

#[test]
fn test_verification_report_default() {
    let report = VerificationReport::default();
    assert!(report.passed);
    assert_eq!(report.total_checks, 0);
}

#[test]
fn test_verifier_default() {
    let v1 = Verifier::new();
    let v2 = Verifier::default();
    // Both should have same default pass rate
    assert!((v1.min_pass_rate - v2.min_pass_rate).abs() < 0.01);
}

#[test]
fn test_verifier_threshold() {
    let verifier = Verifier::new().with_min_pass_rate(80.0);

    let mut report = VerificationReport::new();
    report.add(CheckResult::pass("a", "ok"));
    report.add(CheckResult::pass("b", "ok"));
    report.add(CheckResult::pass("c", "ok"));
    report.add(CheckResult::pass("d", "ok"));
    report.add(CheckResult::fail("e", "error"));

    // 4/5 = 80%
    assert!(verifier.meets_threshold(&report));
}

#[test]
fn test_verifier_threshold_below() {
    let verifier = Verifier::new().with_min_pass_rate(90.0);

    let mut report = VerificationReport::new();
    report.add(CheckResult::pass("a", "ok"));
    report.add(CheckResult::fail("b", "err"));

    // 50% < 90%
    assert!(!verifier.meets_threshold(&report));
}

#[test]
fn test_tensor_verification() {
    let verifier = Verifier::new();

    let mut tensors = BTreeMap::new();
    tensors.insert(
        "good".to_string(),
        TensorData::new(vec![1.0, 2.0, 3.0], vec![3]),
    );
    tensors.insert(
        "has_nan".to_string(),
        TensorData::new(vec![1.0, f32::NAN, 3.0], vec![3]),
    );

    let report = verifier.verify_tensors(&tensors).unwrap();

    // Should have checks for each tensor
    assert!(report.total_checks >= 4); // nan + inf checks for each

    // Should fail due to NaN
    assert!(!report.passed);
}

#[test]
fn test_tensor_verification_with_inf() {
    let verifier = Verifier::new();

    let mut tensors = BTreeMap::new();
    tensors.insert(
        "has_inf".to_string(),
        TensorData::new(vec![1.0, f32::INFINITY, 3.0], vec![3]),
    );

    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(!report.passed);
}

#[test]
fn test_tensor_verification_with_neg_inf() {
    let verifier = Verifier::new();

    let mut tensors = BTreeMap::new();
    tensors.insert(
        "has_neg_inf".to_string(),
        TensorData::new(vec![f32::NEG_INFINITY, 2.0, 3.0], vec![3]),
    );

    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(!report.passed);
}

#[test]
fn test_tensor_verification_all_good() {
    let verifier = Verifier::new();

    let mut tensors = BTreeMap::new();
    tensors.insert(
        "tensor1".to_string(),
        TensorData::new(vec![1.0, 2.0, 3.0], vec![3]),
    );
    tensors.insert(
        "tensor2".to_string(),
        TensorData::new(vec![4.0, 5.0, 6.0, 7.0], vec![2, 2]),
    );

    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(report.passed);
}

#[test]
fn test_tensor_verification_shape_mismatch() {
    let verifier = Verifier::new();

    let mut tensors = BTreeMap::new();
    // Data has 3 elements but shape says 4
    tensors.insert(
        "bad_shape".to_string(),
        TensorData::new(vec![1.0, 2.0, 3.0], vec![2, 2]),
    );

    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(!report.passed);
}

#[test]
fn test_nonexistent_file() {
    let report = verify_apr("/nonexistent/path/model.apr").unwrap();
    assert!(!report.passed);
    assert!(report.checks[0].message.contains("not found"));
}

#[test]
fn test_verify_safetensors_nonexistent() {
    let report = verify_safetensors("/nonexistent/model.safetensors").unwrap();
    assert!(!report.passed);
}

#[test]
fn test_verify_safetensors_too_small() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(&[0u8; 4]).unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    assert!(!report.passed);
}

#[test]
fn test_verify_safetensors_valid_header() {
    let mut file = NamedTempFile::new().unwrap();
    // Header length (2 bytes as u64)
    let header = b"{}";
    let header_len = (header.len() as u64).to_le_bytes();
    file.write_all(&header_len).unwrap();
    file.write_all(header).unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    // Should pass basic checks
    assert!(report
        .checks
        .iter()
        .any(|c| c.name == "A1_file_exists" && c.passed));
}

#[test]
fn test_verify_safetensors_header_too_large() {
    let mut file = NamedTempFile::new().unwrap();
    // Claim header is 200MB (too large)
    let header_len = (200_000_000u64).to_le_bytes();
    file.write_all(&header_len).unwrap();
    file.write_all(&[0u8; 100]).unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    // Should have header limit check fail
    let has_limit_fail = report
        .checks
        .iter()
        .any(|c| c.name == "C11_header_limit" && !c.passed);
    assert!(has_limit_fail);
}

#[test]
fn test_verify_apr_small_file() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(&[0u8; 10]).unwrap();
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    // File exists but is too small
    assert!(report
        .checks
        .iter()
        .any(|c| c.name == "A1_file_exists" && c.passed));
}

#[test]
fn test_verify_apr_wrong_magic() {
    let mut file = NamedTempFile::new().unwrap();
    // Write wrong magic bytes
    file.write_all(b"XXXX").unwrap();
    file.write_all(&[0u8; 60]).unwrap();
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    // Magic check should fail
    let has_magic_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("magic") && !c.passed);
    assert!(has_magic_fail);
}

#[test]
fn test_verify_apr_correct_magic() {
    let mut file = NamedTempFile::new().unwrap();
    // Write correct APR magic
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 60]).unwrap();
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    // Magic check should pass
    let has_magic_pass = report
        .checks
        .iter()
        .any(|c| c.name.contains("magic") && c.passed);
    assert!(has_magic_pass);
}

#[test]
fn test_verify_apr_potential_secret() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 56]).unwrap();
    // Add something that looks like a secret
    file.write_all(b"api_key=secret123").unwrap();
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    // Should have secret check
    let has_secret_check = report.checks.iter().any(|c| c.name.contains("secret"));
    assert!(has_secret_check);
}

#[test]
fn test_convenience_functions() {
    // Test that convenience functions work
    let apr_result = verify_apr("/nonexistent.apr");
    assert!(apr_result.is_ok());

    let st_result = verify_safetensors("/nonexistent.safetensors");
    assert!(st_result.is_ok());
}

#[test]
fn test_verify_apr_secret_patterns() {
    // Test various secret patterns

    // PASSWORD pattern
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 56]).unwrap();
    file.write_all(b"PASSWORD=hunter2").unwrap();
    file.flush().unwrap();
    let report = verify_apr(file.path()).unwrap();
    let has_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("secret") && !c.passed);
    assert!(has_fail);
}

#[test]
fn test_verify_apr_secret_sk_pattern() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 56]).unwrap();
    file.write_all(b"sk-abc123def456").unwrap();
    file.flush().unwrap();
    let report = verify_apr(file.path()).unwrap();
    let has_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("secret") && !c.passed);
    assert!(has_fail);
}

#[test]
fn test_verify_apr_secret_private_key() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 56]).unwrap();
    file.write_all(b"-----BEGIN PRIVATE KEY-----").unwrap();
    file.flush().unwrap();
    let report = verify_apr(file.path()).unwrap();
    let has_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("secret") && !c.passed);
    assert!(has_fail);
}

#[test]
fn test_verify_apr_secret_token() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 56]).unwrap();
    file.write_all(b"auth_token=xyz").unwrap();
    file.flush().unwrap();
    let report = verify_apr(file.path()).unwrap();
    let has_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("secret") && !c.passed);
    assert!(has_fail);
}

#[test]
fn test_verify_apr_no_secrets_clean_file() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 100]).unwrap();
    file.flush().unwrap();
    let report = verify_apr(file.path()).unwrap();
    let has_pass = report
        .checks
        .iter()
        .any(|c| c.name.contains("secret") && c.passed);
    assert!(has_pass);
}

#[test]
fn test_verify_safetensors_invalid_utf8() {
    let mut file = NamedTempFile::new().unwrap();
    // Valid header length
    let header_len = 10u64.to_le_bytes();
    file.write_all(&header_len).unwrap();
    // Invalid UTF-8 bytes
    file.write_all(&[0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89])
        .unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    let has_utf8_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("json") && !c.passed);
    assert!(has_utf8_fail);
}

#[test]
fn test_verify_safetensors_truncated() {
    let mut file = NamedTempFile::new().unwrap();
    // Claim header is 100 bytes but only provide 8 bytes total
    let header_len = 100u64.to_le_bytes();
    file.write_all(&header_len).unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    let has_truncated_fail = report
        .checks
        .iter()
        .any(|c| c.message.contains("truncated"));
    assert!(has_truncated_fail);
}

#[test]
fn test_verify_safetensors_invalid_json_structure() {
    let mut file = NamedTempFile::new().unwrap();
    // Valid UTF-8 but not valid JSON object structure
    let header = b"not a json object";
    let header_len = (header.len() as u64).to_le_bytes();
    file.write_all(&header_len).unwrap();
    file.write_all(header).unwrap();
    file.flush().unwrap();

    let report = verify_safetensors(file.path()).unwrap();
    let has_json_fail = report
        .checks
        .iter()
        .any(|c| c.name.contains("json") && !c.passed);
    assert!(has_json_fail);
}

#[test]
fn test_verifier_threshold_exact_boundary() {
    let verifier = Verifier::new().with_min_pass_rate(88.0);

    // Create report with exactly 88% pass rate (22 pass, 3 fail = 22/25 = 88%)
    let mut report = VerificationReport::new();
    for i in 0..22 {
        report.add(CheckResult::pass(format!("pass_{}", i), "ok"));
    }
    for i in 0..3 {
        report.add(CheckResult::fail(format!("fail_{}", i), "err"));
    }

    assert!(verifier.meets_threshold(&report));
}

#[test]
fn test_verifier_threshold_just_below() {
    let verifier = Verifier::new().with_min_pass_rate(88.0);

    // Create report with 87.5% pass rate (7 pass, 1 fail = 7/8 = 87.5%)
    let mut report = VerificationReport::new();
    for i in 0..7 {
        report.add(CheckResult::pass(format!("pass_{}", i), "ok"));
    }
    report.add(CheckResult::fail("fail", "err"));

    assert!(!verifier.meets_threshold(&report));
}

#[test]
fn test_check_result_debug() {
    let result = CheckResult::pass("test_name", "test message");
    let debug_str = format!("{:?}", result);
    assert!(debug_str.contains("CheckResult"));
    assert!(debug_str.contains("test_name"));
}

#[test]
fn test_verification_report_debug() {
    let report = VerificationReport::new();
    let debug_str = format!("{:?}", report);
    assert!(debug_str.contains("VerificationReport"));
}

#[test]
fn test_tensor_empty_collection() {
    let verifier = Verifier::new();
    let tensors = BTreeMap::new();
    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(report.passed);
    assert_eq!(report.total_checks, 0);
}

#[test]
fn test_tensor_single_element() {
    let verifier = Verifier::new();
    let mut tensors = BTreeMap::new();
    tensors.insert("single".to_string(), TensorData::new(vec![42.0], vec![1]));
    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(report.passed);
}

#[test]
fn test_tensor_large_shape() {
    let verifier = Verifier::new();
    let mut tensors = BTreeMap::new();
    tensors.insert(
        "large".to_string(),
        TensorData::new(vec![1.0; 1000], vec![10, 10, 10]),
    );
    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(report.passed);
}

#[test]
fn test_tensor_multiple_issues() {
    let verifier = Verifier::new();
    let mut tensors = BTreeMap::new();
    // One tensor with NaN
    tensors.insert(
        "has_nan".to_string(),
        TensorData::new(vec![f32::NAN], vec![1]),
    );
    // One tensor with Inf
    tensors.insert(
        "has_inf".to_string(),
        TensorData::new(vec![f32::INFINITY], vec![1]),
    );
    // One tensor with shape mismatch
    tensors.insert("bad_shape".to_string(), TensorData::new(vec![1.0], vec![2]));

    let report = verifier.verify_tensors(&tensors).unwrap();
    assert!(!report.passed);
    // Should have multiple failures
    let fail_count = report.checks.iter().filter(|c| !c.passed).count();
    assert!(fail_count >= 3);
}

#[test]
fn test_verify_apr_size_exactly_64() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 60]).unwrap(); // Total 64 bytes
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    let size_check = report.checks.iter().find(|c| c.name.contains("size"));
    assert!(size_check.is_some());
    assert!(size_check.unwrap().passed);
}

#[test]
fn test_verify_apr_size_below_64() {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 50]).unwrap(); // Total 54 bytes (< 64)
    file.flush().unwrap();

    let report = verify_apr(file.path()).unwrap();
    let size_check = report.checks.iter().find(|c| c.name.contains("size"));
    assert!(size_check.is_some());
    assert!(!size_check.unwrap().passed);
}

#[test]
fn test_verifier_with_custom_pass_rate() {
    let verifier = Verifier::new().with_min_pass_rate(50.0);
    assert!((verifier.min_pass_rate - 50.0).abs() < 0.01);
}

#[test]
fn test_verifier_meets_threshold_empty_report() {
    let verifier = Verifier::new();
    let report = VerificationReport::new();
    // Empty report has 100% pass rate
    assert!(verifier.meets_threshold(&report));
}

#[cfg(unix)]
#[test]
fn test_verify_apr_permission_denied() {
    use std::os::unix::fs::PermissionsExt;

    // Root bypasses file permission checks, so this test is meaningless as root
    if std::env::var("USER").unwrap_or_default() == "root"
        || std::fs::read_to_string("/proc/self/status")
            .map(|s| s.lines().any(|l| l.starts_with("Uid:\t0\t")))
            .unwrap_or(false)
    {
        eprintln!("skipping test_verify_apr_permission_denied: running as root");
        return;
    }

    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"APR\0").unwrap();
    file.write_all(&[0u8; 60]).unwrap();
    file.flush().unwrap();
    let path = file.path().to_path_buf();

    // Remove all permissions so File::open fails (A2_readable)
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();

    let report = verify_apr(&path).unwrap();

    // Restore permissions for cleanup
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();

    // A1 should pass (file exists), A2 should fail (can't open)
    let a1 = report.checks.iter().find(|c| c.name == "A1_file_exists");
    assert!(a1.is_some());
    assert!(a1.unwrap().passed);

    let a2 = report.checks.iter().find(|c| c.name == "A2_readable");
    assert!(a2.is_some());
    assert!(!a2.unwrap().passed);
    assert!(a2.unwrap().message.contains("Cannot read"));
}