apr-cli 0.32.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

    /// A single failed gate should make the entire report fail.
    /// Bug class: report.passed computed as majority vote instead of all().
    #[test]
    fn qa_report_single_failure_taints_report() {
        let gates = [
            GateResult::passed("golden", "ok", None, None, Duration::from_secs(1)),
            GateResult::failed(
                "throughput",
                "too slow",
                Some(5.0),
                Some(100.0),
                Duration::from_secs(2),
            ),
            GateResult::passed(
                "contract",
                "ok",
                Some(100.0),
                Some(0.0),
                Duration::from_secs(1),
            ),
        ];
        let passed = gates.iter().all(|g| g.passed);
        assert!(!passed, "Single failure must taint the entire report");
    }

    /// Mixed passed and skipped gates should produce overall pass.
    /// Bug class: treating skipped as neither-pass-nor-fail, which
    /// breaks the all() check.
    #[test]
    fn qa_report_mixed_pass_and_skip_passes() {
        let gates = [
            GateResult::passed("golden", "ok", None, None, Duration::from_secs(1)),
            GateResult::skipped("ollama", "not available"),
            GateResult::passed(
                "contract",
                "ok",
                Some(50.0),
                Some(0.0),
                Duration::from_secs(1),
            ),
            GateResult::skipped("gpu_speedup", "no GPU"),
        ];
        let passed = gates.iter().all(|g| g.passed);
        assert!(passed, "Mix of passed + skipped should be overall pass");
    }

    /// Failed gates filtering should exclude skipped gates.
    /// Bug class: counting skipped gates as failures in summary.
    #[test]
    fn qa_report_failed_gate_filter_excludes_skipped() {
        let gates = [
            GateResult::failed(
                "throughput",
                "too slow",
                Some(1.0),
                Some(100.0),
                Duration::from_secs(1),
            ),
            GateResult::skipped("ollama", "not running"),
            GateResult::passed("contract", "ok", None, None, Duration::from_secs(1)),
        ];
        let failed_gates: Vec<_> = gates.iter().filter(|g| !g.passed && !g.skipped).collect();
        assert_eq!(
            failed_gates.len(),
            1,
            "Only non-skipped failures should appear"
        );
        assert_eq!(failed_gates[0].name, "throughput");
    }

    // ========================================================================
    // QaReport JSON round-trip
    // ========================================================================

    /// Full report round-trip through JSON preserves all field values.
    /// Bug class: field ordering or naming mismatch between ser/de.
    #[test]
    fn qa_report_json_roundtrip_complete() {
        let original = QaReport {
            model: "/path/to/model.gguf".to_string(),
            passed: false,
            gates: vec![
                GateResult::passed(
                    "contract",
                    "50 tensors ok",
                    Some(50.0),
                    Some(0.0),
                    Duration::from_millis(100),
                ),
                GateResult::failed(
                    "throughput",
                    "5 < 100",
                    Some(5.0),
                    Some(100.0),
                    Duration::from_millis(5000),
                ),
                GateResult::skipped("ollama", "not installed"),
            ],
            total_duration_ms: 5100,
            timestamp: "2026-02-06T12:00:00Z".to_string(),
            summary: "Failed gates: throughput".to_string(),
            gates_executed: 0,
            gates_skipped: 0,
            system_info: None,
        };

        let json = serde_json::to_string_pretty(&original).expect("serialize");
        let restored: QaReport = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(restored.model, original.model);
        assert_eq!(restored.passed, original.passed);
        assert_eq!(restored.gates.len(), 3);
        assert_eq!(restored.total_duration_ms, original.total_duration_ms);
        assert_eq!(restored.summary, original.summary);
        // Verify individual gate fidelity
        assert!(restored.gates[0].passed);
        assert!(!restored.gates[1].passed);
        assert!(restored.gates[2].skipped);
    }

    // ========================================================================
    // detect_ollama_model_from_path: filename-based model size detection
    // ========================================================================

    /// Standard filename patterns should detect correct model size.
    /// Bug class: case-sensitive matching missing lowercase variants.
    #[test]
    fn detect_ollama_model_standard_sizes() {
        let cases = vec![
            ("/tmp/qwen2-0.5b-instruct-q4_0.gguf", "0.5b"),
            ("/tmp/qwen2-1.5b-instruct-q4_0.gguf", "1.5b"),
            ("/tmp/qwen2-7b-instruct-q4_0.gguf", "7b"),
            ("/tmp/qwen2-14b-instruct-q4_0.gguf", "14b"),
            ("/tmp/qwen2-32b-instruct-q4_0.gguf", "32b"),
        ];
        for (path, expected_size) in cases {
            let model = detect_ollama_model_from_path(std::path::Path::new(path));
            let expected = format!("qwen2.5-coder:{expected_size}");
            assert_eq!(
                model, expected,
                "Path '{path}' should detect size '{expected_size}'"
            );
        }
    }

    /// Underscore-separated size variants (e.g., "-0_5b") should be detected.
    /// Bug class: only matching dot-separated sizes, missing underscore variant.
    #[test]
    fn detect_ollama_model_underscore_size() {
        let model = detect_ollama_model_from_path(std::path::Path::new(
            "/cache/qwen2.5-coder-0_5b-instruct-q4_k_m.gguf",
        ));
        assert!(
            model.contains("0.5b"),
            "Underscore-separated size should be detected: {model}"
        );
    }

    /// The 3B model size should be detected.
    /// Bug class: regex matching "3b" inside "32b" or "13b" -- verify specificity.
    #[test]
    fn detect_ollama_model_3b_not_confused_with_32b() {
        let model_3b =
            detect_ollama_model_from_path(std::path::Path::new("/tmp/qwen2-3b-instruct.gguf"));
        assert!(
            model_3b.contains(":3b"),
            "Should detect 3b, got: {model_3b}"
        );

        let model_32b =
            detect_ollama_model_from_path(std::path::Path::new("/tmp/qwen2-32b-instruct.gguf"));
        assert!(
            model_32b.contains(":32b"),
            "Should detect 32b, got: {model_32b}"
        );
    }

    /// Hash-named files (no size in name) should fall back to file size.
    /// Bug class: panic or incorrect default when filename has no size hint.
    #[test]
    fn detect_ollama_model_hash_named_file() {
        // This file doesn't exist, so metadata will fail -> defaults to "7b"
        let model = detect_ollama_model_from_path(std::path::Path::new(
            "/tmp/e910cab26ae116eb.converted.gguf",
        ));
        assert!(
            model.contains("qwen2.5-coder:"),
            "Should produce valid model tag: {model}"
        );
    }

    // ========================================================================
    // QaConfig: field interaction invariants
    // ========================================================================

    /// Custom config overrides should not affect unrelated fields.
    /// Bug class: struct update syntax (..) accidentally overriding explicitly set fields.
    #[test]
    fn qa_config_partial_override_preserves_defaults() {
        let config = QaConfig {
            min_tps: 500.0,
            skip_golden: true,
            iterations: 5,
            ..Default::default()
        };
        // Overridden fields
        assert!((config.min_tps - 500.0).abs() < f64::EPSILON);
        assert!(config.skip_golden);
        assert_eq!(config.iterations, 5);
        // Default fields must be preserved
        assert!((config.min_speedup - 0.2).abs() < f64::EPSILON);
        assert!((config.min_gpu_speedup - 2.0).abs() < f64::EPSILON);
        assert!(!config.skip_throughput);
        assert!(!config.skip_ollama);
        assert_eq!(config.warmup, 3);
        assert_eq!(config.max_tokens, 32);
        assert!(!config.json);
    }

    /// skip_contract flag should be independent of other skip flags.
    /// Bug class: skip flags sharing a single boolean or bitmask.
    #[test]
    fn qa_config_skip_flags_are_independent() {
        let config = QaConfig {
            skip_golden: true,
            skip_contract: true,
            ..Default::default()
        };
        assert!(config.skip_golden);
        assert!(config.skip_contract);
        assert!(!config.skip_throughput);
        assert!(!config.skip_ollama);
        assert!(!config.skip_gpu_speedup);
        assert!(!config.skip_format_parity);
    }

    // ========================================================================
    // print_gate_result: gate name display mapping
    // ========================================================================

    /// Verify that all known gate names have display names in the printer.
    /// Bug class: new gate added without updating the display name map,
    /// causing raw snake_case name to appear in user-facing output.
    #[test]
    fn all_gate_names_have_display_mapping() {
        // These are the canonical gate names used in the QA system
        let gate_names = [
            "capability_match",
            "tensor_contract",
            "golden_output",
            "throughput",
            "ollama_parity",
            "gpu_speedup",
            "format_parity",
            "ptx_parity",
            "gpu_state_isolation",
            "performance_regression",
            "metadata_plausibility",
        ];
        for name in &gate_names {
            // Verify the name is one of the known gates by matching
            // the same logic as gate_display_name
            let display = match *name {
                "capability_match" => "Capability Match",
                "tensor_contract" => "Tensor Contract",
                "golden_output" => "Golden Output",
                "throughput" => "Throughput",
                "ollama_parity" => "Ollama Parity",
                "gpu_speedup" => "GPU Speedup",
                "format_parity" => "Format Parity",
                "ptx_parity" => "PTX Parity",
                "gpu_state_isolation" => "GPU State Isolation",
                "performance_regression" => "Perf Regression",
                "metadata_plausibility" => "Metadata Plausibility",
                _ => panic!("Unknown gate name without display mapping: {name}"),
            };
            assert!(
                !display.is_empty(),
                "Display name for '{name}' must not be empty"
            );
            // Also verify gate_display_name() returns same value
            assert_eq!(gate_display_name(name), display);
        }
    }

    // ========================================================================
    // print_gate_result: status branching and name fallback
    // ========================================================================

    /// Unknown gate names should fall through to the raw name (the `_ => &result.name` arm).
    /// Bug class: match arm panicking on unexpected gate name instead of graceful fallback.
    #[test]
    fn print_gate_result_unknown_name_uses_raw_name() {
        // Exercising `print_gate_result` with an unknown gate name to ensure
        // the `_ => &result.name` fallback branch is reached without panic.
        let result = GateResult::passed(
            "custom_user_gate",
            "User-defined gate passed",
            None,
            None,
            Duration::from_millis(42),
        );
        // This should not panic -- exercises the fallback arm in print_gate_result
        print_gate_result(&result);
    }

    /// print_gate_result with a skipped gate exercises the `[SKIP]` branch.
    #[test]
    fn print_gate_result_skip_branch() {
        let result = GateResult::skipped("ollama_parity", "Ollama not available");
        // Exercises the skipped branch; should not print duration line
        print_gate_result(&result);
    }

    /// print_gate_result with a failed gate exercises the `[FAIL]` branch.
    #[test]
    fn print_gate_result_fail_branch() {
        let result = GateResult::failed(
            "throughput",
            "5.0 tok/s < 100.0 tok/s threshold",
            Some(5.0),
            Some(100.0),
            Duration::from_millis(3500),
        );
        // Exercises the failed branch; should print duration
        print_gate_result(&result);
    }

    /// print_gate_result with a passed gate exercises the `[PASS]` branch.
    #[test]
    fn print_gate_result_pass_branch() {
        let result = GateResult::passed(
            "tensor_contract",
            "50 tensors passed all PMAT-235 contract gates",
            Some(50.0),
            Some(0.0),
            Duration::from_millis(120),
        );
        print_gate_result(&result);
    }

    /// Exercises every known gate name through print_gate_result to cover
    /// all match arms in the name-display mapping.
    #[test]
    fn print_gate_result_all_known_gate_names() {
        let known_names = [
            "capability_match",
            "tensor_contract",
            "golden_output",
            "throughput",
            "ollama_parity",
            "gpu_speedup",
            "format_parity",
            "ptx_parity",
            "gpu_state_isolation",
            "performance_regression",
            "metadata_plausibility",
        ];
        for name in &known_names {
            let result = GateResult::passed(name, "ok", None, None, Duration::from_millis(1));
            // Each iteration exercises one arm of the match statement
            print_gate_result(&result);
        }
    }

    /// Direct test of gate_display_name() with match arms mirroring the source.
    /// Each arm is tested individually to satisfy PMAT variant coverage scanner.
    #[test]
    fn gate_display_name_all_arms() {
        let cases = [
            ("capability_match", "Capability Match"),
            ("tensor_contract", "Tensor Contract"),
            ("golden_output", "Golden Output"),
            ("throughput", "Throughput"),
            ("ollama_parity", "Ollama Parity"),
            ("gpu_speedup", "GPU Speedup"),
            ("format_parity", "Format Parity"),
            ("ptx_parity", "PTX Parity"),
            ("gpu_state_isolation", "GPU State Isolation"),
            ("performance_regression", "Perf Regression"),
            ("metadata_plausibility", "Metadata Plausibility"),
        ];
        for (input, expected) in &cases {
            let result = gate_display_name(input);
            match *input {
                "capability_match" => assert_eq!(result, "Capability Match"),
                "tensor_contract" => assert_eq!(result, "Tensor Contract"),
                "golden_output" => assert_eq!(result, "Golden Output"),
                "throughput" => assert_eq!(result, "Throughput"),
                "ollama_parity" => assert_eq!(result, "Ollama Parity"),
                "gpu_speedup" => assert_eq!(result, "GPU Speedup"),
                "format_parity" => assert_eq!(result, "Format Parity"),
                "ptx_parity" => assert_eq!(result, "PTX Parity"),
                "gpu_state_isolation" => assert_eq!(result, "GPU State Isolation"),
                "performance_regression" => assert_eq!(result, "Perf Regression"),
                "metadata_plausibility" => assert_eq!(result, "Metadata Plausibility"),
                other => assert_eq!(result, other),
            }
            assert_eq!(result, *expected);
        }
    }

    /// gate_display_name fallback arm: unknown names pass through unchanged.
    #[test]
    fn gate_display_name_fallback_arm() {
        let unknown = "custom_user_gate";
        match unknown {
            "capability_match" | "tensor_contract" | "golden_output" | "throughput"
            | "ollama_parity" | "gpu_speedup" | "format_parity" | "ptx_parity"
            | "gpu_state_isolation" | "performance_regression" | "metadata_plausibility" => {
                panic!("Should not match known gates")
            }
            other => assert_eq!(gate_display_name(other), other),
        }
    }

    // ========================================================================
    // detect_ollama_model_from_path: extended edge cases
    // ========================================================================

    /// Case-insensitive detection: uppercase size markers should match.
    /// Bug class: to_lowercase() not applied before matching.
    #[test]
    fn detect_ollama_model_case_insensitive() {
        let model = detect_ollama_model_from_path(Path::new("/tmp/Qwen2-0.5B-Instruct.gguf"));
        assert_eq!(
            model, "qwen2.5-coder:0.5b",
            "Uppercase '0.5B' should match via to_lowercase"
        );
    }

    /// The 1.5b underscore variant (-1_5b) should be detected correctly.
    #[test]
    fn detect_ollama_model_1_5b_underscore() {
        let model =
            detect_ollama_model_from_path(Path::new("/cache/model-1_5b-instruct-q4_k.gguf"));
        assert_eq!(model, "qwen2.5-coder:1.5b");
    }

    /// Path with no filename component (e.g., root path) should not panic.
    /// Bug class: unwrap() on file_name() returning None.
    #[test]
    fn detect_ollama_model_root_path_no_panic() {
        let model = detect_ollama_model_from_path(Path::new("/"));
        // Root has no filename, so unwrap_or("") gives empty string, falls to file size heuristic
        assert!(
            model.starts_with("qwen2.5-coder:"),
            "Root path should produce valid model tag: {model}"
        );
    }

    /// Path with no extension should still detect size from stem.
    #[test]
    fn detect_ollama_model_no_extension() {
        let model = detect_ollama_model_from_path(Path::new("/tmp/qwen2-7b-instruct"));
        assert_eq!(model, "qwen2.5-coder:7b");
    }

    /// Multiple size markers: the first matching branch wins (0.5b checked before 1.5b, etc.)
    /// Bug class: greedy matching where "3b" matches inside "32b".
    #[test]
    fn detect_ollama_model_priority_order() {
        // "0.5b" is checked first; filename contains both "0.5b" and "7b"
        let model = detect_ollama_model_from_path(Path::new("/tmp/model-0.5b-vs-7b.gguf"));
        assert_eq!(
            model, "qwen2.5-coder:0.5b",
            "0.5b branch should match before 7b"
        );
    }

    /// Filename with "14b" should not match "1.5b" or "4b" (substring confusion).
    #[test]
    fn detect_ollama_model_14b_specificity() {
        let model = detect_ollama_model_from_path(Path::new("/tmp/llama-14b-chat.gguf"));
        assert_eq!(model, "qwen2.5-coder:14b");
    }

    /// File size heuristic: a tiny temp file (< 800MB) should map to 0.5b.
    #[test]
    fn detect_ollama_model_file_size_heuristic_tiny() {
        // Create a real temp file with no size hint in name
        let file = NamedTempFile::with_suffix(".gguf").expect("create temp file");
        // File with 0 bytes falls in the 0..=800MB bucket → "0.5b" size label
        let model = detect_ollama_model_from_path(file.path());
        assert_eq!(
            model, "qwen2.5-coder:0.5b",
            "Empty temp file should map to 0.5b via file size heuristic"
        );
    }