apr-cli 0.64.0

CLI tool for APR model inspection, debugging, and operations
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

    // ========================================================================
    // TensorStats::from_slice: additional edge cases
    // ========================================================================

    #[test]
    fn test_tensor_stats_all_zeros() {
        let data = vec![0.0; 100];
        let stats = TensorStats::from_slice(&data);
        assert_eq!(stats.count, 100);
        assert!((stats.mean - 0.0).abs() < 1e-8);
        assert_eq!(stats.min, 0.0);
        assert_eq!(stats.max, 0.0);
        assert_eq!(stats.max_abs, 0.0);
    }

    #[test]
    fn test_tensor_stats_all_same_value() {
        let data = vec![7.0; 50];
        let stats = TensorStats::from_slice(&data);
        assert!((stats.mean - 7.0).abs() < 1e-5);
        assert_eq!(stats.min, 7.0);
        assert_eq!(stats.max, 7.0);
    }

    #[test]
    fn test_tensor_stats_mixed_nan_and_inf() {
        let data = vec![1.0, f32::NAN, f32::INFINITY, 3.0, f32::NEG_INFINITY];
        let stats = TensorStats::from_slice(&data);
        assert_eq!(stats.nan_count, 1);
        assert_eq!(stats.inf_count, 2);
        assert_eq!(stats.count, 5);
        // Mean of [1.0, 3.0] = 2.0
        assert!((stats.mean - 2.0).abs() < 1e-5);
    }

    #[test]
    fn test_tensor_stats_large_values() {
        let data = vec![1e10, -1e10];
        let stats = TensorStats::from_slice(&data);
        assert!((stats.mean - 0.0).abs() < 1.0); // Close to zero
        assert!(stats.max_abs > 1e9);
    }

    #[test]
    fn test_tensor_stats_very_small_values() {
        let data = vec![1e-10, 2e-10, 3e-10];
        let stats = TensorStats::from_slice(&data);
        assert!(stats.mean > 0.0);
        assert!(stats.mean < 1.0);
    }

    // ========================================================================
    // TensorStats::detect_anomalies: additional branches
    // ========================================================================

    #[test]
    fn test_anomaly_detection_large_max_abs() {
        let stats = TensorStats {
            count: 100,
            mean: 0.0,
            std: 1.0,
            l2_norm: 150.0,
            min: -150.0,
            max: 150.0,
            max_abs: 150.0,
            nan_count: 0,
            inf_count: 0,
        };
        let anomalies = stats.detect_anomalies("test");
        assert!(anomalies.iter().any(|a| a.contains("large values")));
    }

    #[test]
    fn test_anomaly_detection_multiple_anomalies() {
        let stats = TensorStats {
            count: 100,
            mean: 15.0, // Large mean
            std: 0.0,   // Zero std
            l2_norm: 200.0,
            min: -200.0,
            max: 200.0,
            max_abs: 200.0, // Large values
            nan_count: 5,   // NaN
            inf_count: 3,   // Inf
        };
        let anomalies = stats.detect_anomalies("layer_7");
        // Should detect NaN, Inf, zero variance, large values, large mean
        assert!(anomalies.len() >= 4);
    }

    #[test]
    fn test_anomaly_detection_single_element_no_zero_std() {
        // count = 1, std < 1e-8 but count is not > 1, so no zero-variance anomaly
        let stats = TensorStats {
            count: 1,
            mean: 5.0,
            std: 0.0,
            l2_norm: 5.0,
            min: 5.0,
            max: 5.0,
            max_abs: 5.0,
            nan_count: 0,
            inf_count: 0,
        };
        let anomalies = stats.detect_anomalies("test");
        // Should NOT flag zero-variance for single element
        assert!(!anomalies.iter().any(|a| a.contains("variance")));
    }

    #[test]
    fn test_anomaly_detection_negative_large_mean() {
        let stats = TensorStats {
            count: 100,
            mean: -15.0, // Large negative mean
            std: 1.0,
            l2_norm: 100.0,
            min: -20.0,
            max: 0.0,
            max_abs: 20.0,
            nan_count: 0,
            inf_count: 0,
        };
        let anomalies = stats.detect_anomalies("test");
        assert!(anomalies.iter().any(|a| a.contains("large mean")));
    }

    // ========================================================================
    // validate_path tests
    // ========================================================================

    #[test]
    fn test_validate_path_nonexistent() {
        let result = validate_path(Path::new("/nonexistent/file.apr"));
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_path_directory() {
        let dir = tempdir().expect("create temp dir");
        let result = validate_path(dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_path_valid_file() {
        let file = NamedTempFile::new().expect("create temp file");
        let result = validate_path(file.path());
        assert!(result.is_ok());
    }

    // ========================================================================
    // trace_layers: with valid and invalid metadata
    // ========================================================================

    #[test]
    fn test_trace_layers_empty_metadata() {
        let layers = trace_layers(&[], false);
        // Invalid metadata, should return default layer
        assert_eq!(layers.len(), 1);
        assert!(layers[0].name.contains("not available"));
    }

    #[test]
    fn test_trace_layers_invalid_metadata() {
        let layers = trace_layers(b"not valid msgpack", false);
        // Should fall back to default layer
        assert_eq!(layers.len(), 1);
        assert!(layers[0].name.contains("not available"));
    }

    #[test]
    fn test_trace_layers_valid_metadata_no_hyperparameters() {
        // Valid msgpack but no hyperparameters key
        let map: BTreeMap<String, serde_json::Value> = BTreeMap::new();
        let bytes = rmp_serde::to_vec(&map).expect("serialize msgpack");
        let layers = trace_layers(&bytes, false);
        // No hyperparameters → default layer
        assert_eq!(layers.len(), 1);
        assert!(layers[0].name.contains("not available"));
    }

    #[test]
    fn test_trace_layers_valid_metadata_with_hyperparameters() {
        let mut hp = serde_json::Map::new();
        hp.insert("n_layer".to_string(), serde_json::json!(2));
        hp.insert("n_embd".to_string(), serde_json::json!(128));

        let mut map: BTreeMap<String, serde_json::Value> = BTreeMap::new();
        map.insert("hyperparameters".to_string(), serde_json::Value::Object(hp));
        let bytes = rmp_serde::to_vec(&map).expect("serialize msgpack");
        let layers = trace_layers(&bytes, false);
        // embedding + 2 transformer blocks + final_layer_norm = 4
        assert_eq!(layers.len(), 4);
        assert_eq!(layers[0].name, "embedding");
        assert_eq!(layers[1].name, "transformer_block_0");
        assert_eq!(layers[2].name, "transformer_block_1");
        assert_eq!(layers[3].name, "final_layer_norm");
    }

    #[test]
    fn test_trace_layers_with_filter() {
        let mut hp = serde_json::Map::new();
        hp.insert("n_layer".to_string(), serde_json::json!(5));
        hp.insert("n_embd".to_string(), serde_json::json!(256));

        let mut map: BTreeMap<String, serde_json::Value> = BTreeMap::new();
        map.insert("hyperparameters".to_string(), serde_json::Value::Object(hp));
        let bytes = rmp_serde::to_vec(&map).expect("serialize msgpack");
        let (layers, notes) = apply_layer_filter(trace_layers(&bytes, false), Some("block_2"));
        // Only block_2 should match the filter
        assert!(layers.iter().any(|l| l.name == "transformer_block_2"));
        assert!(notes.is_empty());
    }

    // ========================================================================
    // print_stats: smoke test (no crash)
    // ========================================================================

    #[test]
    fn test_print_stats_no_panic() {
        let stats = compute_vector_stats(&[1.0, 2.0, 3.0]);
        print_stats("  ", &stats);
    }

    #[test]
    fn test_print_stats_with_nan_no_panic() {
        let stats = VectorStats {
            l2_norm: 5.0,
            min: 0.0,
            max: 10.0,
            mean: 5.0,
            nan_count: 3,
            inf_count: 2,
        };
        print_stats("  ", &stats);
    }

    #[test]
    fn test_print_stats_no_anomalies_no_extra_output() {
        let stats = VectorStats {
            l2_norm: 5.0,
            min: 0.0,
            max: 10.0,
            mean: 5.0,
            nan_count: 0,
            inf_count: 0,
        };
        // Should not panic, and should skip NaN/Inf line
        print_stats("", &stats);
    }

    // ========================================================================
    // LayerTrace: construction with stats
    // ========================================================================

    #[test]
    fn test_layer_trace_with_all_stats() {
        let stats = TensorStats::from_slice(&[1.0, 2.0, 3.0]);
        let trace = LayerTrace {
            name: "full_layer".to_string(),
            index: Some(5),
            hidden_dim: None,
            input_stats: Some(stats.clone()),
            output_stats: Some(stats.clone()),
            weight_stats: Some(stats),
            anomalies: vec!["test anomaly".to_string()],
        };
        assert!(trace.input_stats.is_some());
        assert!(trace.output_stats.is_some());
        assert!(trace.weight_stats.is_some());
        assert_eq!(trace.anomalies.len(), 1);
    }

    #[test]
    fn test_layer_trace_serialize_with_stats() {
        let stats = TensorStats::from_slice(&[1.0, 2.0, 3.0]);
        let trace = LayerTrace {
            name: "layer_with_stats".to_string(),
            index: Some(0),
            hidden_dim: None,
            input_stats: Some(stats.clone()),
            output_stats: None,
            weight_stats: None,
            anomalies: vec!["anomaly1".to_string()],
        };
        let json = serde_json::to_string(&trace).expect("serialize");
        assert!(json.contains("layer_with_stats"));
        assert!(json.contains("anomaly1"));
        assert!(json.contains("input_stats"));
    }

    // ========================================================================
    // TraceSummary and TraceResult serialization
    // ========================================================================

    #[test]
    fn test_trace_summary_serialize() {
        let summary = TraceSummary {
            total_layers: 12,
            total_parameters: 1_000_000,
            anomaly_count: 2,
            anomalies: vec![
                "NaN in layer 3".to_string(),
                "Large mean in layer 7".to_string(),
            ],
        };
        let json = serde_json::to_string(&summary).expect("serialize");
        assert!(json.contains("\"total_layers\":12"));
        assert!(json.contains("\"total_parameters\":1000000"));
        assert!(json.contains("\"anomaly_count\":2"));
    }

    // ========================================================================
    // handle_special_modes: interactive precedence over payload
    // ========================================================================

    #[test]
    fn test_handle_special_modes_interactive_takes_precedence() {
        let path = Path::new("/tmp/model.apr");
        // Both interactive and payload set - interactive should win (checked first)
        let result = handle_special_modes(path, None, true, false, true);
        assert!(result.is_some());
        assert!(result.expect("should be Some").is_ok());
    }

    // ========================================================================
    // GGUF layer filter tests
    // ========================================================================

    #[test]
    fn test_run_valid_gguf_with_layer_filter() {
        let file = build_test_gguf();
        let result = run(
            file.path(),
            Some("block_0"),
            None,
            false,
            false,
            false,
            false,
            false,
        );
        assert!(
            result.is_ok(),
            "trace on valid GGUF with filter failed: {result:?}"
        );
    }

    #[test]
    fn test_run_valid_gguf_verbose() {
        let file = build_test_gguf();
        let result = run(
            file.path(),
            None,
            None,
            false,
            true, // verbose
            false,
            false,
            false,
        );
        assert!(
            result.is_ok(),
            "trace on valid GGUF verbose failed: {result:?}"
        );
    }

    #[test]
    fn test_run_valid_safetensors_with_filter() {
        let file = build_test_safetensors();
        let result = run(
            file.path(),
            Some("block_0"),
            None,
            false,
            false,
            false,
            false,
            false,
        );
        assert!(
            result.is_ok(),
            "trace on valid SafeTensors with filter failed: {result:?}"
        );
    }

    #[test]
    fn test_run_valid_safetensors_verbose() {
        let file = build_test_safetensors();
        let result = run(
            file.path(),
            None,
            None,
            false,
            true, // verbose
            false,
            false,
            false,
        );
        assert!(
            result.is_ok(),
            "trace on valid SafeTensors verbose failed: {result:?}"
        );
    }

    // ========================================================================
    // GGUF with layer filter returning no matches
    // ========================================================================

    /// #2407: this test asserted `!layers.is_empty()` for a filter that
    /// matches nothing — it required the fabricated
    /// "(layer trace metadata not available)" entry, and so held the defect in
    /// place. What a caller needs is the opposite: no layers, no anomaly, and
    /// a note saying the filter matched nothing.
    #[test]
    fn test_trace_gguf_filter_no_match_reports_zero_layers_not_a_fake_one() {
        let file = build_test_gguf();
        let unfiltered =
            detect_and_trace(file.path(), None, false).expect("detect_and_trace unfiltered");
        assert!(
            !unfiltered.layers.is_empty(),
            "control: this file does have layers"
        );

        let traced = detect_and_trace(file.path(), Some("nonexistent"), false)
            .expect("detect_and_trace filtered");
        assert!(
            traced.layers.is_empty(),
            "a filter matching nothing must not fabricate a layer, got: {:?}",
            traced.layers.iter().map(|l| &l.name).collect::<Vec<_>>()
        );

        let summary = compute_trace_summary(&traced.layers, traced.total_params);
        assert_eq!(
            summary.anomaly_count, 0,
            "a filter miss is not an anomaly in the model; got: {:?}",
            summary.anomalies
        );

        assert_eq!(
            traced.notes,
            vec![format!(
                "layer filter \"nonexistent\" matched 0 of {} layers",
                unfiltered.layers.len()
            )],
            "the result must say why it is empty"
        );
    }

    // ========================================================================
    // #2407 — a metadata-only trace must say that it is one
    // ========================================================================

    /// `apr trace --json` never executes the model, so every `*_stats` field
    /// is null and `anomaly_count` is 0 no matter how broken the weights are.
    /// Emitted as a bare success that was indistinguishable from "traced
    /// fine, nothing anomalous". The payload now labels itself.
    #[test]
    fn test_trace_json_payload_declares_that_no_activations_were_computed() {
        let file = build_test_gguf();
        let traced = detect_and_trace(file.path(), None, false).expect("detect_and_trace");
        let summary = compute_trace_summary(&traced.layers, traced.total_params);
        let result = build_trace_result(
            file.path(),
            &traced.format_name,
            &traced.layers,
            &summary,
            &traced.notes,
        );
        let json = serde_json::to_value(&result).expect("serialize trace result");

        assert_eq!(
            json["stats_source"], "metadata-only",
            "a caller must be able to branch on where the stats came from"
        );
        assert!(
            json["notes"]
                .as_array()
                .expect("notes is an array")
                .iter()
                .any(|n| n
                    .as_str()
                    .is_some_and(|s| s.contains("no activations were computed"))),
            "the payload must state that nothing was executed; got: {}",
            json["notes"]
        );
        assert_eq!(
            summary.anomaly_count, 0,
            "control: no anomalies are reported because none were looked for"
        );

        // And no layer may carry a statistics block, because none was measured.
        for layer in &traced.layers {
            assert!(
                layer.output_stats.is_none() && layer.input_stats.is_none(),
                "layer {} reports statistics that were never computed",
                layer.name
            );
        }
    }

    // ========================================================================
    // #2407 — --reference must fail rather than print a stub at exit 0
    // ========================================================================

    /// v0.63.0 printed `{"comparison": "reference comparison not yet
    /// implemented"}` on stdout, put its only real signal on stderr (which
    /// the MCP wrapper discards on success), and exited 0.
    #[test]
    fn test_trace_reference_is_an_error_not_a_stub_success() {
        let model = build_test_gguf();
        let reference = build_test_gguf();

        let result = run(
            model.path(),
            None,
            Some(reference.path()),
            true, // --json
            false,
            false,
            false,
            false,
        );

        let err = result.expect_err("an unimplemented comparison must not succeed");
        assert!(
            matches!(err, CliError::NotImplemented(_)),
            "expected NotImplemented, got: {err:?}"
        );
        assert!(
            err.to_string().contains("not implemented"),
            "the message must say what is missing; got: {err}"
        );
        assert_ne!(
            err.exit_code(),
            std::process::ExitCode::SUCCESS,
            "a stub must not exit 0"
        );
    }

    // ========================================================================
    // is_likely_garbage: mixed cases
    // ========================================================================

    #[test]
    fn test_is_likely_garbage_short_two_repeated() {
        // Only 2 words, repeated check needs len > 2
        assert!(!is_likely_garbage("foo foo"));
    }

    #[test]
    fn test_is_likely_garbage_three_different_unknown() {
        // 3 different words, none common, no numbers → garbage
        assert!(is_likely_garbage("xyzzy plugh plover"));
    }

    #[test]
    fn test_is_likely_garbage_has_digit_in_text() {
        // Has number, so the no-normal-words check is skipped
        assert!(!is_likely_garbage("xyzzy plugh 42"));
    }