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

    /// Simulate how run() builds QaConfig with Some parameters (overrides).
    #[test]
    fn run_config_building_some_overrides_defaults() {
        let min_tps: Option<f64> = Some(50.0);
        let min_speedup: Option<f64> = Some(1.5);
        let min_gpu_speedup: Option<f64> = Some(3.0);
        let config = QaConfig {
            min_tps: min_tps.unwrap_or(100.0),
            min_speedup: min_speedup.unwrap_or(0.2),
            min_gpu_speedup: min_gpu_speedup.unwrap_or(2.0),
            ..Default::default()
        };
        assert!((config.min_tps - 50.0).abs() < f64::EPSILON);
        assert!((config.min_speedup - 1.5).abs() < f64::EPSILON);
        assert!((config.min_gpu_speedup - 3.0).abs() < f64::EPSILON);
    }

    // ========================================================================
    // NEW: print_gate_result duration formatting (line 1490-1491)
    // ========================================================================

    /// Verify print_gate_result handles zero duration without division errors.
    #[test]
    fn print_gate_result_zero_duration_formatting() {
        let result = GateResult::passed(
            "tensor_contract",
            "0 tensors",
            Some(0.0),
            Some(0.0),
            Duration::from_millis(0),
        );
        // Should print "Duration: 0.00s" without panic
        print_gate_result(&result);
    }

    /// Verify print_gate_result handles large duration values.
    #[test]
    fn print_gate_result_large_duration_formatting() {
        let result = GateResult::passed(
            "throughput",
            "ok",
            Some(100.0),
            Some(50.0),
            Duration::from_secs(3600),
        );
        // duration_ms = 3600000, format as 3600000.0/1000.0 = 3600.00s
        assert_eq!(result.duration_ms, 3_600_000);
        print_gate_result(&result);
    }

    /// Verify print_gate_result formats duration_ms correctly for sub-second durations.
    #[test]
    fn print_gate_result_subsecond_duration_formatting() {
        let result = GateResult::passed(
            "golden_output",
            "2 cases passed",
            Some(2.0),
            Some(2.0),
            Duration::from_millis(250),
        );
        assert_eq!(result.duration_ms, 250);
        // 250ms / 1000.0 = 0.25s -> should print "Duration: 0.25s"
        print_gate_result(&result);
    }

    // ========================================================================
    // NEW: QaReport with all 6 canonical gates
    // ========================================================================

    /// Verify a report with all 6 canonical gates can be serialized/deserialized.
    #[test]
    fn qa_report_all_six_canonical_gates_roundtrip() {
        let report = QaReport {
            model: "/models/qwen2-0.5b-q4_k.gguf".to_string(),
            passed: false,
            gates: vec![
                GateResult::passed(
                    "tensor_contract",
                    "50 tensors ok",
                    Some(50.0),
                    Some(0.0),
                    Duration::from_millis(100),
                ),
                GateResult::passed(
                    "golden_output",
                    "2 test cases passed",
                    Some(2.0),
                    Some(2.0),
                    Duration::from_millis(5000),
                ),
                GateResult::failed(
                    "throughput",
                    "5 tok/s < 100 tok/s",
                    Some(5.0),
                    Some(100.0),
                    Duration::from_millis(10000),
                ),
                GateResult::skipped("ollama_parity", "Ollama not available"),
                GateResult::skipped("gpu_speedup", "CUDA not available"),
                GateResult::skipped("format_parity", "No --safetensors-path provided"),
            ],
            total_duration_ms: 15100,
            timestamp: "2026-02-07T12: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(&report).expect("serialize");
        let restored: QaReport = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(restored.gates.len(), 6);
        assert!(!restored.passed);
        // Verify each gate type
        assert!(restored.gates[0].passed && !restored.gates[0].skipped);
        assert!(restored.gates[1].passed && !restored.gates[1].skipped);
        assert!(!restored.gates[2].passed && !restored.gates[2].skipped);
        assert!(restored.gates[3].skipped);
        assert!(restored.gates[4].skipped);
        assert!(restored.gates[5].skipped);
    }

    // ========================================================================
    // NEW: GateResult message content validation
    // ========================================================================

    /// Passed gate message should be stored verbatim.
    #[test]
    fn gate_result_passed_message_stored_verbatim() {
        let msg = "150.0 tok/s >= 100.0 tok/s threshold";
        let result = GateResult::passed(
            "throughput",
            msg,
            Some(150.0),
            Some(100.0),
            Duration::from_secs(1),
        );
        assert_eq!(result.message, msg);
    }

    /// Failed gate message should be stored verbatim.
    #[test]
    fn gate_result_failed_message_stored_verbatim() {
        let msg = "5.0 tok/s < 100.0 tok/s threshold";
        let result = GateResult::failed(
            "throughput",
            msg,
            Some(5.0),
            Some(100.0),
            Duration::from_secs(1),
        );
        assert_eq!(result.message, msg);
    }

    /// Skipped gate message format: "Skipped: {reason}".
    #[test]
    fn gate_result_skipped_message_exact_format() {
        let result = GateResult::skipped("gpu_speedup", "CUDA not available");
        assert_eq!(result.message, "Skipped: CUDA not available");
    }

    /// Empty reason for skipped gate should produce "Skipped: ".
    #[test]
    fn gate_result_skipped_empty_reason() {
        let result = GateResult::skipped("test", "");
        assert_eq!(result.message, "Skipped: ");
        assert!(result.skipped);
    }

    /// Empty name for gate result should be stored as empty string.
    #[test]
    fn gate_result_empty_name() {
        let result = GateResult::passed("", "ok", None, None, Duration::from_secs(0));
        assert_eq!(result.name, "");
        assert!(result.passed);
    }

    // ========================================================================
    // NEW: GateResult negative and zero values
    // ========================================================================

    /// Negative value in a gate result (e.g., from subtraction error).
    #[test]
    fn gate_result_negative_value() {
        let result = GateResult::failed(
            "gpu_speedup",
            "-0.5x slower",
            Some(-0.5),
            Some(2.0),
            Duration::from_secs(1),
        );
        assert_eq!(result.value, Some(-0.5));
        assert!(!result.passed);
    }

    /// Zero value should be representable.
    #[test]
    fn gate_result_zero_value() {
        let result = GateResult::failed(
            "throughput",
            "0 tok/s",
            Some(0.0),
            Some(100.0),
            Duration::from_secs(1),
        );
        assert_eq!(result.value, Some(0.0));
        assert_eq!(result.threshold, Some(100.0));
    }

    /// Very small positive value (epsilon-level).
    #[test]
    fn gate_result_epsilon_value() {
        let result = GateResult::passed(
            "throughput",
            "barely passing",
            Some(f64::MIN_POSITIVE),
            Some(0.0),
            Duration::from_secs(1),
        );
        assert_eq!(result.value, Some(f64::MIN_POSITIVE));
        assert!(result.passed);
    }

    // ========================================================================
    // NEW: QaReport timestamp and model path edge cases
    // ========================================================================

    /// Report with Unicode characters in model path.
    #[test]
    fn qa_report_unicode_model_path() {
        let report = QaReport {
            model: "/modelos/modelo_espa\u{00f1}ol.gguf".to_string(),
            passed: true,
            gates: vec![],
            total_duration_ms: 0,
            timestamp: "2026-02-07T00:00:00Z".to_string(),
            summary: "ok".to_string(),
            gates_executed: 0,
            gates_skipped: 0,
            system_info: None,
        };
        let json = serde_json::to_string(&report).expect("serialize unicode path");
        let restored: QaReport = serde_json::from_str(&json).expect("deserialize unicode path");
        assert!(restored.model.contains("espa\u{00f1}ol"));
    }

    /// Report with very long model path.
    #[test]
    fn qa_report_long_model_path() {
        let long_path = format!("/very/{}/model.gguf", "deep/".repeat(100));
        let report = QaReport {
            model: long_path.clone(),
            passed: true,
            gates: vec![],
            total_duration_ms: 0,
            timestamp: "2026-02-07T00:00:00Z".to_string(),
            summary: "ok".to_string(),
            gates_executed: 0,
            gates_skipped: 0,
            system_info: None,
        };
        let json = serde_json::to_string(&report).expect("serialize long path");
        let restored: QaReport = serde_json::from_str(&json).expect("deserialize long path");
        assert_eq!(restored.model, long_path);
    }

    /// Report with empty model path.
    #[test]
    fn qa_report_empty_model_path() {
        let report = QaReport {
            model: String::new(),
            passed: true,
            gates: vec![],
            total_duration_ms: 0,
            timestamp: "2026-02-07T00:00:00Z".to_string(),
            summary: "ok".to_string(),
            gates_executed: 0,
            gates_skipped: 0,
            system_info: None,
        };
        let json = serde_json::to_string(&report).expect("serialize empty model");
        let restored: QaReport = serde_json::from_str(&json).expect("deserialize empty model");
        assert!(restored.model.is_empty());
    }

    // ========================================================================
    // NEW: QaReport aggregate pass/fail with mixed states
    // ========================================================================

    /// All gates failed: report.passed should be false and all gates listed.
    #[test]
    fn qa_report_all_gates_failed() {
        let gates = vec![
            GateResult::failed(
                "tensor_contract",
                "violations",
                Some(5.0),
                Some(0.0),
                Duration::from_secs(1),
            ),
            GateResult::failed(
                "golden_output",
                "wrong output",
                None,
                None,
                Duration::from_secs(2),
            ),
            GateResult::failed(
                "throughput",
                "too slow",
                Some(1.0),
                Some(100.0),
                Duration::from_secs(3),
            ),
        ];
        let passed = gates.iter().all(|g| g.passed);
        assert!(!passed);
        let failed_names: Vec<&str> = gates
            .iter()
            .filter(|g| !g.passed && !g.skipped)
            .map(|g| g.name.as_str())
            .collect();
        assert_eq!(failed_names.len(), 3);
        let summary = format!("Failed gates: {}", failed_names.join(", "));
        assert_eq!(
            summary,
            "Failed gates: tensor_contract, golden_output, throughput"
        );
    }

    /// Single passed gate among skipped: overall pass.
    #[test]
    fn qa_report_single_pass_rest_skipped() {
        let gates = vec![
            GateResult::passed(
                "tensor_contract",
                "ok",
                Some(10.0),
                Some(0.0),
                Duration::from_secs(1),
            ),
            GateResult::skipped("golden_output", "no engine"),
            GateResult::skipped("throughput", "no engine"),
            GateResult::skipped("ollama_parity", "not available"),
            GateResult::skipped("gpu_speedup", "no GPU"),
            GateResult::skipped("format_parity", "no path"),
        ];
        let passed = gates.iter().all(|g| g.passed);
        assert!(passed);
    }

    // ========================================================================
    // NEW: print_gate_result exercises for each known gate display name
    // ========================================================================

    /// Exercise print_gate_result with "format_parity" gate -- one of the display names.
    #[test]
    fn print_gate_result_format_parity_display_name() {
        let result = GateResult::passed(
            "format_parity",
            "GGUF argmax=42 == SafeTensors argmax=42",
            Some(42.0),
            Some(42.0),
            Duration::from_millis(8000),
        );
        print_gate_result(&result);
    }

    /// Exercise print_gate_result with "gpu_speedup" gate in failed state.
    #[test]
    fn print_gate_result_gpu_speedup_failed() {
        let result = GateResult::failed(
            "gpu_speedup",
            "GPU 1.2x faster than CPU < 2.0x threshold",
            Some(1.2),
            Some(2.0),
            Duration::from_millis(15000),
        );
        print_gate_result(&result);
    }

    // ========================================================================
    // NEW: QaConfig with zero and extreme iteration/token values
    // ========================================================================

    /// Zero iterations and warmup should be representable.
    #[test]
    fn qa_config_zero_iterations_and_warmup() {
        let config = QaConfig {
            iterations: 0,
            warmup: 0,
            max_tokens: 0,
            ..Default::default()
        };
        assert_eq!(config.iterations, 0);
        assert_eq!(config.warmup, 0);
        assert_eq!(config.max_tokens, 0);
    }

    /// Large max_tokens value.
    #[test]
    fn qa_config_large_max_tokens() {
        let config = QaConfig {
            max_tokens: 1_000_000,
            ..Default::default()
        };
        assert_eq!(config.max_tokens, 1_000_000);
    }

    // ========================================================================
    // NEW: GateResult serialization with special f64 values
    // ========================================================================

    /// Serialize gate with very large value.
    #[test]
    fn gate_result_serialize_large_value() {
        let result = GateResult::passed(
            "throughput",
            "very fast",
            Some(999_999.99),
            Some(100.0),
            Duration::from_secs(1),
        );
        let json = serde_json::to_string(&result).expect("serialize large value");
        assert!(json.contains("999999.99"));
    }

    /// Serialize gate with very small (near-zero) positive value.
    #[test]
    fn gate_result_serialize_tiny_value() {
        let result = GateResult::failed(
            "throughput",
            "basically zero",
            Some(0.000_001),
            Some(100.0),
            Duration::from_secs(1),
        );
        let json = serde_json::to_string(&result).expect("serialize tiny value");
        // serde_json will serialize this as something like 1e-6 or 0.000001
        let restored: GateResult = serde_json::from_str(&json).expect("deserialize tiny value");
        assert!((restored.value.expect("has value") - 0.000_001).abs() < 1e-10);
    }