apr-cli 0.4.16

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

    /// Test execute_command: Export with non-existent file returns error
    #[test]
    fn test_execute_export_file_not_found() {
        let cli = make_cli(Commands::Export {
            file: Some(PathBuf::from("/tmp/nonexistent_model_export_test.apr")),
            format: "safetensors".to_string(),
            output: Some(PathBuf::from("/tmp/out.safetensors")),
            quantize: None,
            list_formats: false,
            batch: None,
            json: false,
            plan: false,
        });
        let result = execute_command(&cli);
        assert!(result.is_err(), "Export should fail with non-existent file");
    }

    /// Test execute_command: Convert with non-existent file returns error
    #[test]
    fn test_execute_convert_file_not_found() {
        let cli = make_cli(Commands::Convert {
            file: PathBuf::from("/tmp/nonexistent_model_convert_test.apr"),
            quantize: None,
            compress: None,
            output: PathBuf::from("/tmp/out.apr"),
            force: false,
        });
        let result = execute_command(&cli);
        assert!(
            result.is_err(),
            "Convert should fail with non-existent file"
        );
    }

    /// Test execute_command: Hex with non-existent file returns error
    #[test]
    fn test_execute_hex_file_not_found() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Hex {
            file: PathBuf::from("/tmp/nonexistent_model_hex_test.apr"),
            tensor: None,
            limit: 64,
            stats: false,
            list: false,
            json: false,
            header: false,
            blocks: false,
            distribution: false,
            contract: false,
            entropy: false,
            raw: false,
            offset: String::new(),
            width: 16,
            slice: None,
        }));
        let result = execute_command(&cli);
        assert!(result.is_err(), "Hex should fail with non-existent file");
    }

    /// Test execute_command: Tree with non-existent file returns error
    #[test]
    fn test_execute_tree_file_not_found() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Tree {
            file: PathBuf::from("/tmp/nonexistent_model_tree_test.apr"),
            filter: None,
            format: "ascii".to_string(),
            sizes: false,
            depth: None,
        }));
        let result = execute_command(&cli);
        assert!(result.is_err(), "Tree should fail with non-existent file");
    }

    /// Test execute_command: Flow with non-existent file returns error
    #[test]
    fn test_execute_flow_file_not_found() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Flow {
            file: PathBuf::from("/tmp/nonexistent_model_flow_test.apr"),
            layer: None,
            component: "full".to_string(),
            verbose: false,
            json: false,
        }));
        let result = execute_command(&cli);
        assert!(result.is_err(), "Flow should fail with non-existent file");
    }

    /// Test execute_command: Probar with non-existent file returns error
    #[test]
    fn test_execute_probar_file_not_found() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Probar {
            file: PathBuf::from("/tmp/nonexistent_model_probar_test.apr"),
            output: PathBuf::from("/tmp/probar-out"),
            format: "both".to_string(),
            golden: None,
            layer: None,
            assert: false,
            tolerance: 0.98,
        }));
        let result = execute_command(&cli);
        assert!(result.is_err(), "Probar should fail with non-existent file");
    }

    /// Test execute_command: Check with non-existent file returns error
    #[test]
    fn test_execute_check_file_not_found() {
        let cli = make_cli(Commands::Check {
            file: PathBuf::from("/tmp/nonexistent_model_check_test.apr"),
            no_gpu: true,
            json: false,
        });
        let result = execute_command(&cli);
        assert!(result.is_err(), "Check should fail with non-existent file");
    }

    /// Test execute_command: List succeeds (no file needed)
    #[test]
    fn test_execute_list_succeeds() {
        let cli = make_cli(Commands::List);
        // List should succeed even if cache is empty
        let result = execute_command(&cli);
        assert!(result.is_ok(), "List should succeed without arguments");
    }

    /// Test execute_command: Explain without args returns validation error
    #[test]
    fn test_execute_explain_no_args() {
        let cli = make_cli(Commands::Explain {
            code_or_file: None,
            file: None,
            tensor: None,
            kernel: false,
            json: false,
            verbose: false,
            proof_status: false,
        });
        // Explain with no args returns error (shows usage guidance)
        let result = execute_command(&cli);
        assert!(result.is_err(), "Explain with no args should return error");
    }

    /// Test execute_command: Explain with code succeeds
    #[test]
    fn test_execute_explain_with_code() {
        let cli = make_cli(Commands::Explain {
            code_or_file: Some("E001".to_string()),
            file: None,
            tensor: None,
            kernel: false,
            json: false,
            verbose: false,
            proof_status: false,
        });
        let result = execute_command(&cli);
        // Should succeed even for unknown error codes (it prints "unknown error code")
        assert!(result.is_ok(), "Explain with error code should succeed");
    }

    /// Test execute_command: Tune --plan without file succeeds
    #[test]
    fn test_execute_tune_plan_no_file() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Tune {
            file: None,
            method: "auto".to_string(),
            rank: None,
            vram: 16.0,
            plan: true,
            model: Some("7B".to_string()),
            freeze_base: false,
            train_data: None,
            json: false,
            task: None,
            budget: 10,
            strategy: "tpe".to_string(),
            scheduler: "asha".to_string(),
            scout: false,
            data: None,
            num_classes: 5,
            model_size: None,
            from_scout: None,
            max_epochs: 20,
            time_limit: None,
        }));
        let result = execute_command(&cli);
        // Tune with --plan and --model should succeed without a file
        assert!(
            result.is_ok(),
            "Tune --plan --model 7B should succeed without file"
        );
    }

    /// Test execute_command: Qa with non-existent file and all skips still succeeds
    /// because QA gates are individually skipped. With no gates enabled, it just
    /// prints summary and returns Ok.
    #[test]
    fn test_execute_qa_all_skips_succeeds() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Qa {
            file: PathBuf::from("/tmp/nonexistent_model_qa_test.gguf"),
            assert_tps: None,
            assert_speedup: None,
            assert_gpu_speedup: None,
            skip_golden: true,
            skip_throughput: true,
            skip_ollama: true,
            skip_gpu_speedup: true,
            skip_contract: true,
            skip_format_parity: true,
            skip_ptx_parity: true,
            safetensors_path: None,
            iterations: 1,
            warmup: 0,
            max_tokens: 1,
            json: false,
            verbose: false,
            min_executed: None,
            previous_report: None,
            regression_threshold: None,
            skip_gpu_state: false,
            skip_metadata: true,
            skip_capability: true,
            assert_classifier_head: false,
        }));
        let result = execute_command(&cli);
        assert!(
            result.is_ok(),
            "Qa with all gates skipped should succeed even with non-existent file"
        );
    }

    /// Test execute_command: Qa with non-existent file and gates enabled returns error
    #[test]
    fn test_execute_qa_with_gates_file_not_found() {
        let cli = make_cli(Commands::Extended(ExtendedCommands::Qa {
            file: PathBuf::from("/tmp/nonexistent_model_qa_gates_test.gguf"),
            assert_tps: None,
            assert_speedup: None,
            assert_gpu_speedup: None,
            skip_golden: false, // Gate enabled
            skip_throughput: true,
            skip_ollama: true,
            skip_gpu_speedup: true,
            skip_contract: true,
            skip_format_parity: true,
            skip_ptx_parity: true,
            safetensors_path: None,
            iterations: 1,
            warmup: 0,
            max_tokens: 1,
            json: false,
            verbose: false,
            min_executed: None,
            previous_report: None,
            regression_threshold: None,
            skip_gpu_state: false,
            skip_metadata: true,
            skip_capability: true,
            assert_classifier_head: false,
        }));
        let result = execute_command(&cli);
        assert!(
            result.is_err(),
            "Qa with golden gate enabled should fail with non-existent file"
        );
    }

    /// Test execute_command: Import with invalid source returns error
    #[test]
    fn test_execute_import_invalid_source() {
        let cli = make_cli(Commands::Import {
            source: "/tmp/nonexistent_model_import_test.gguf".to_string(),
            output: None,
            arch: "auto".to_string(),
            quantize: None,
            strict: false,
            preserve_q4k: false,
            tokenizer: None,
            enforce_provenance: false,
            allow_no_config: false,
        });
        let result = execute_command(&cli);
        assert!(
            result.is_err(),
            "Import should fail with non-existent source file"
        );
    }

    // =========================================================================
    // --chat flag logic: effective_prompt with ChatML wrapping
    // =========================================================================

    /// Test that --chat flag wraps prompt in ChatML format (verified via parse)
    #[test]
    fn test_chat_flag_chatml_wrapping_logic() {
        // We cannot call execute_command with --chat on a non-existent model
        // without error, but we can verify the ChatML wrapping logic directly.
        let prompt = "What is the meaning of life?";
        let chat = true;

        let effective_prompt = if chat {
            Some(format!(
                "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n",
                prompt
            ))
        } else {
            Some(prompt.to_string())
        };

        assert!(effective_prompt
            .as_ref()
            .expect("prompt should exist")
            .starts_with("<|im_start|>user\n"));
        assert!(effective_prompt
            .as_ref()
            .expect("prompt should exist")
            .ends_with("<|im_start|>assistant\n"));
        assert!(effective_prompt
            .as_ref()
            .expect("prompt should exist")
            .contains("What is the meaning of life?"));
    }

    /// Test that without --chat, prompt is passed through unchanged
    #[test]
    fn test_no_chat_flag_passthrough() {
        let prompt = Some("Hello world".to_string());
        let chat = false;

        let effective_prompt = if chat {
            prompt
                .as_ref()
                .map(|p| format!("<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", p))
        } else {
            prompt.clone()
        };

        assert_eq!(effective_prompt, Some("Hello world".to_string()));
    }

    /// Test that --chat with no prompt produces None
    #[test]
    fn test_chat_flag_no_prompt() {
        let prompt: Option<String> = None;
        let chat = true;

        let effective_prompt = if chat {
            prompt
                .as_ref()
                .map(|p| format!("<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n", p))
        } else {
            prompt.clone()
        };

        assert!(effective_prompt.is_none());
    }

    // =========================================================================
    // --trace-payload shorthand logic
    // =========================================================================

    /// Test trace-payload shorthand enables trace and sets level to payload
    #[test]
    fn test_trace_payload_shorthand_logic() {
        let trace = false;
        let trace_payload = true;
        let trace_level = "basic".to_string();

        let effective_trace = trace || trace_payload;
        let effective_trace_level = if trace_payload {
            "payload"
        } else {
            trace_level.as_str()
        };

        assert!(effective_trace);
        assert_eq!(effective_trace_level, "payload");
    }

    /// Test that without --trace-payload, trace settings are preserved
    #[test]
    fn test_no_trace_payload_preserves_settings() {
        let trace = true;
        let trace_payload = false;
        let trace_level = "layer".to_string();

        let effective_trace = trace || trace_payload;
        let effective_trace_level = if trace_payload {
            "payload"
        } else {
            trace_level.as_str()
        };

        assert!(effective_trace);
        assert_eq!(effective_trace_level, "layer");
    }

    /// Test that neither trace nor trace_payload results in no trace
    #[test]
    fn test_no_trace_no_trace_payload() {
        let trace = false;
        let trace_payload = false;
        let trace_level = "basic".to_string();

        let effective_trace = trace || trace_payload;
        let effective_trace_level = if trace_payload {
            "payload"
        } else {
            trace_level.as_str()
        };

        assert!(!effective_trace);
        assert_eq!(effective_trace_level, "basic");
    }

    // =========================================================================
    // Verbose flag inheritance (local vs global)
    // =========================================================================

    /// Test that local verbose flag overrides global false
    #[test]
    fn test_verbose_local_true_global_false() {
        let local_verbose = true;
        let global_verbose = false;
        let effective_verbose = local_verbose || global_verbose;
        assert!(effective_verbose);
    }

    /// Test that global verbose flag takes effect when local is false
    #[test]
    fn test_verbose_local_false_global_true() {
        let local_verbose = false;
        let global_verbose = true;
        let effective_verbose = local_verbose || global_verbose;
        assert!(effective_verbose);
    }

    /// Test that both verbose false means not verbose
    #[test]
    fn test_verbose_both_false() {
        let local_verbose = false;
        let global_verbose = false;
        let effective_verbose = local_verbose || global_verbose;
        assert!(!effective_verbose);
    }

    /// Test that both verbose true means verbose
    #[test]
    fn test_verbose_both_true() {
        let local_verbose = true;
        let global_verbose = true;
        let effective_verbose = local_verbose || global_verbose;
        assert!(effective_verbose);
    }

    /// Test verbose inheritance end-to-end via global flag and Run command.
    /// Note: clap with `global = true` and matching short flag `-v` means
    /// the global verbose flag propagates to both the Cli struct and the
    /// Run subcommand's local verbose field.
    #[test]
    fn test_verbose_inheritance_run_global() {
        let args = vec!["apr", "--verbose", "run", "model.gguf", "--prompt", "test"];
        let cli = parse_cli(args).expect("Failed to parse");
        assert!(cli.verbose);
        match *cli.command {
            Commands::Run { verbose, .. } => {
                // With global = true, clap propagates to both levels
                // effective_verbose = local || global = always true
                let effective = verbose || cli.verbose;
                assert!(effective);
            }
            _ => panic!("Expected Run command"),
        }
    }