aprender-core 0.30.0

Next-generation machine learning library in pure Rust
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
use super::*;

#[test]
fn test_jidoka_violation_display() {
    let nan = JidokaViolation::NaN { count: 5 };
    assert!(format!("{nan}").contains("5"));

    let inf = JidokaViolation::Inf { count: 3 };
    assert!(format!("{inf}").contains("3"));

    let zero_var = JidokaViolation::ZeroVariance { mean: 2.5 };
    assert!(format!("{zero_var}").contains("2.5"));

    let shape = JidokaViolation::ShapeMismatch {
        expected: vec![512, 768],
        actual: vec![768, 512],
    };
    assert!(format!("{shape}").contains("512"));

    let checksum = JidokaViolation::ChecksumFailed {
        expected: 0xABCD,
        actual: 0x1234,
    };
    assert!(format!("{checksum}").contains("0xabcd"));
}

#[test]
fn test_conversion_decision_display() {
    let decision = ConversionDecision::QuantQ4_K_Block32;
    let s = format!("{decision}");
    assert!(s.contains("QuantQ4_K_Block32"));
}

#[test]
fn test_andon_level_display() {
    assert_eq!(format!("{}", AndonLevel::Green), "GREEN");
    assert_eq!(format!("{}", AndonLevel::Yellow), "YELLOW");
    assert_eq!(format!("{}", AndonLevel::Red), "RED");
}

#[test]
fn test_conversion_category_display() {
    assert!(format!("{}", ConversionCategory::GgufToApr).contains("GGUF"));
    assert!(format!("{}", ConversionCategory::SafeTensorsToGguf).contains("SafeTensors"));
}

#[test]
fn test_anomaly_detector_insufficient_data() {
    // Less than 13 samples = None
    let data: Vec<TensorFeatures> = (0..10)
        .map(|i| TensorFeatures::from_data(&[i as f32]))
        .collect();

    let detector = AnomalyDetector::fit(&data, 0.1, 10.0);
    assert!(detector.is_none());
}

#[test]
fn test_anomaly_detector_with_data() {
    // Generate 20 similar feature vectors
    let data: Vec<TensorFeatures> = (0..20)
        .map(|i| {
            let base = vec![1.0 + (i as f32 * 0.01); 100];
            TensorFeatures::from_data(&base)
        })
        .collect();

    let detector = AnomalyDetector::fit(&data, 0.1, 100.0);
    assert!(detector.is_some());

    let detector = detector.unwrap();
    assert_eq!(detector.n_samples(), 20);
    assert!((detector.shrinkage() - 0.1).abs() < 0.01);
    assert!((detector.threshold() - 100.0).abs() < 0.01);

    // Normal point should not be anomaly
    let normal = TensorFeatures::from_data(&[1.05; 100]);
    assert!(!detector.is_anomaly(&normal));

    // Extreme point should be anomaly
    let extreme = TensorFeatures::from_data(&[1000.0; 100]);
    assert!(detector.anomaly_score(&extreme) > 1.0);
}

#[test]
fn test_fix_action_variants() {
    // Test all FixAction variants can be created
    let _swap = FixAction::SwapDimensions;
    let _requant = FixAction::Requantize { block_size: 32 };
    let _checksum = FixAction::RecomputeChecksum;
    let _pad = FixAction::PadAlignment { alignment: 64 };
    let _skip = FixAction::SkipTensor;
    let _fallback = FixAction::FallbackF32;
    let _custom = FixAction::Custom {
        description: "test".into(),
    };
}

#[test]
fn test_pattern_source_variants() {
    assert_ne!(PatternSource::Bootstrap, PatternSource::Corpus);
    assert_ne!(PatternSource::Llm, PatternSource::Manual);
}

#[test]
fn test_severity_ordering() {
    assert!(Severity::Info < Severity::Warning);
    assert!(Severity::Warning < Severity::Error);
    assert!(Severity::Error < Severity::Critical);
}

#[test]
fn test_priority_ordering() {
    assert!(Priority::Low < Priority::Medium);
    assert!(Priority::Medium < Priority::High);
    assert!(Priority::High < Priority::Critical);
}

#[test]
fn test_matrix_inversion_singular() {
    // Singular matrix (all zeros)
    let singular = vec![vec![0.0, 0.0], vec![0.0, 0.0]];
    assert!(invert_matrix(&singular).is_none());

    // Empty matrix
    let empty: Vec<Vec<f32>> = vec![];
    assert!(invert_matrix(&empty).is_none());

    // Non-square (not valid input)
    let nonsquare = vec![vec![1.0, 2.0]];
    assert!(invert_matrix(&nonsquare).is_none());
}

// =========================================================================
// Coverage: WilsonScore with low confidence (<0.90)
// =========================================================================

#[test]
fn test_wilson_score_low_confidence() {
    let score = WilsonScore::calculate(8, 10, 0.80); // Below 0.90 threshold
    assert!(score.proportion > 0.0);
    // With low confidence, the default z=1.96 should be used
    assert!(score.lower < score.proportion);
    assert!(score.upper > score.proportion);
}

#[test]
fn test_wilson_score_exact_boundaries() {
    // Test each z-score branch
    let score_99 = WilsonScore::calculate(5, 10, 0.99);
    assert!(score_99.confidence >= 0.99);

    let score_95 = WilsonScore::calculate(5, 10, 0.95);
    assert!((score_95.confidence - 0.95).abs() < 0.01);

    let score_90 = WilsonScore::calculate(5, 10, 0.90);
    assert!((score_90.confidence - 0.90).abs() < 0.01);
}

#[test]
fn test_wilson_score_zero_total() {
    let score = WilsonScore::calculate(0, 0, 0.95);
    assert_eq!(score.n, 0);
    assert!(score.proportion.abs() < 1e-6);
    assert!(score.lower.abs() < 1e-6);
    assert!(score.upper.abs() < 1e-6);
}

// =========================================================================
// Coverage: AndonLevel Display (all variants)
// =========================================================================

#[test]
fn test_andon_level_display_all_variants() {
    assert_eq!(format!("{}", AndonLevel::Green), "GREEN");
    assert_eq!(format!("{}", AndonLevel::Yellow), "YELLOW");
    assert_eq!(format!("{}", AndonLevel::Red), "RED");
}

// =========================================================================
// Coverage: WilsonScore andon_level
// =========================================================================

#[test]
fn test_wilson_score_andon_level_green() {
    let score = WilsonScore::calculate(9, 10, 0.95);
    assert_eq!(score.andon_level(0.8), AndonLevel::Green);
}

#[test]
fn test_wilson_score_andon_level_yellow() {
    let score = WilsonScore::calculate(6, 10, 0.95);
    assert_eq!(score.andon_level(0.8), AndonLevel::Yellow);
}

#[test]
fn test_wilson_score_andon_level_red() {
    let score = WilsonScore::calculate(1, 10, 0.95);
    assert_eq!(score.andon_level(0.8), AndonLevel::Red);
}

// =========================================================================
// Coverage: HanseiReport empty() and andon_level()
// =========================================================================

#[test]
fn test_hansei_report_empty() {
    let report = HanseiReport::empty();
    assert_eq!(report.total_attempts, 0);
    assert_eq!(report.successes, 0);
    assert!(report.success_rate.abs() < 1e-6);
    assert!(report.pareto_categories.is_empty());
    assert!(report.issues.is_empty());
}

#[test]
fn test_hansei_report_andon_level() {
    let results = vec![
        (ConversionCategory::GgufToApr, true),
        (ConversionCategory::GgufToApr, true),
        (ConversionCategory::GgufToApr, false),
    ];
    let report = HanseiReport::from_results(&results);
    // success_rate ~= 0.67
    let level = report.andon_level(0.9);
    assert_eq!(level, AndonLevel::Yellow);
}

#[test]
fn test_hansei_report_from_empty_results() {
    let results: Vec<(ConversionCategory, bool)> = vec![];
    let report = HanseiReport::from_results(&results);
    assert_eq!(report.total_attempts, 0);
}

// =========================================================================
// Coverage: ConversionCategory Display all variants
// =========================================================================

#[test]
fn test_conversion_category_display_all() {
    assert_eq!(
        format!("{}", ConversionCategory::GgufToApr),
        "GGUF\u{2192}APR"
    );
    assert_eq!(
        format!("{}", ConversionCategory::AprToGguf),
        "APR\u{2192}GGUF"
    );
    assert_eq!(
        format!("{}", ConversionCategory::SafeTensorsToApr),
        "SafeTensors\u{2192}APR"
    );
    assert_eq!(
        format!("{}", ConversionCategory::AprToSafeTensors),
        "APR\u{2192}SafeTensors"
    );
    assert_eq!(
        format!("{}", ConversionCategory::GgufToSafeTensors),
        "GGUF\u{2192}SafeTensors"
    );
    assert_eq!(
        format!("{}", ConversionCategory::SafeTensorsToGguf),
        "SafeTensors\u{2192}GGUF"
    );
}

// =========================================================================
// Coverage: ErrorPattern match_confidence
// =========================================================================

#[test]
fn test_error_pattern_match_confidence_zero() {
    let pattern = ErrorPattern::new(
        "test",
        vec!["alignment".into(), "padding".into()],
        FixAction::PadAlignment { alignment: 64 },
    );
    let conf = pattern.match_confidence("completely unrelated error message");
    assert!(conf.abs() < 1e-6, "No keyword matches should give 0.0");
}

#[test]
fn test_error_pattern_match_confidence_partial() {
    let pattern = ErrorPattern::new(
        "test",
        vec!["alignment".into(), "padding".into()],
        FixAction::PadAlignment { alignment: 64 },
    );
    let conf = pattern.match_confidence("alignment issue in tensor");
    assert!(
        (conf - 0.5).abs() < 1e-6,
        "One of two keywords should give 0.5"
    );
}

#[test]
fn test_error_pattern_match_confidence_full() {
    let pattern = ErrorPattern::new(
        "test",
        vec!["alignment".into(), "padding".into()],
        FixAction::PadAlignment { alignment: 64 },
    );
    let conf = pattern.match_confidence("alignment and padding issue");
    assert!((conf - 1.0).abs() < 1e-6, "All keywords should give 1.0");
}

// =========================================================================
// Coverage: ErrorPattern should_retire
// =========================================================================

#[test]
fn test_error_pattern_should_retire_not_enough_applications() {
    let pattern = ErrorPattern::new("test", vec!["error".into()], FixAction::SkipTensor);
    // < 5 applications, should not retire
    assert!(!pattern.should_retire());
}

#[test]
fn test_error_pattern_should_retire_low_success() {
    let mut pattern = ErrorPattern::new("test", vec!["error".into()], FixAction::SkipTensor);
    // 5 applications, 1 success = 20% < 30%
    for _ in 0..4 {
        pattern.record_application(false);
    }
    pattern.record_application(true);
    assert!(
        pattern.should_retire(),
        "Low success rate after 5 apps should retire"
    );
}

#[test]
fn test_error_pattern_should_not_retire_high_success() {
    let mut pattern = ErrorPattern::new("test", vec!["error".into()], FixAction::SkipTensor);
    // 5 applications, 4 successes = 80% > 30%
    for _ in 0..4 {
        pattern.record_application(true);
    }
    pattern.record_application(false);
    assert!(
        !pattern.should_retire(),
        "High success rate should not retire"
    );
}

// =========================================================================
// Coverage: TensorCanary detect_regression - RangeDrift
// =========================================================================

#[test]
fn test_tensor_canary_range_drift() {
    let baseline = TensorCanary {
        name: "test_tensor".into(),
        shape: vec![4, 4],
        dtype: "F32".into(),
        mean: 0.5,
        std: 0.1,
        min: 0.0,
        max: 1.0,
        checksum: 12345,
    };

    let current = TensorCanary {
        name: "test_tensor".into(),
        shape: vec![4, 4],
        dtype: "F32".into(),
        mean: 0.5, // same
        std: 0.1,  // same
        min: -0.5, // drifted below min - range_tolerance
        max: 1.0,  // same
        checksum: 12345,
    };

    let regression = baseline.detect_regression(&current);
    assert!(regression.is_some());
    match regression.unwrap() {
        Regression::RangeDrift { .. } => {} // Expected
        other => panic!("Expected RangeDrift, got {:?}", other),
    }
}

#[test]
fn test_tensor_canary_range_drift_max() {
    let baseline = TensorCanary {
        name: "t".into(),
        shape: vec![2],
        dtype: "F32".into(),
        mean: 0.0,
        std: 0.1,
        min: -1.0,
        max: 1.0,
        checksum: 100,
    };

    let current = TensorCanary {
        name: "t".into(),
        shape: vec![2],
        dtype: "F32".into(),
        mean: 0.0,
        std: 0.1,
        min: -1.0,
        max: 2.0, // drifted above max + range_tolerance
        checksum: 100,
    };

    let regression = baseline.detect_regression(&current);
    assert!(regression.is_some());
    match regression.unwrap() {
        Regression::RangeDrift { .. } => {}
        other => panic!("Expected RangeDrift, got {:?}", other),
    }
}

#[test]
fn test_tensor_canary_no_regression() {
    let baseline = TensorCanary {
        name: "t".into(),
        shape: vec![2, 2],
        dtype: "F32".into(),
        mean: 0.5,
        std: 0.1,
        min: 0.0,
        max: 1.0,
        checksum: 42,
    };

    let current = baseline.clone();
    assert!(baseline.detect_regression(&current).is_none());
}