frink-cli 0.74.0

llama.cpp-style CLI for the Frink inference engine
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
use super::GpuLayers;
use std::str::FromStr;

use super::{banner_line, kv_elem_for, InferArgs, OffloadDevice};
use clap::Parser;

/// `InferArgs` is a `clap::Args` group, not a `Parser`, so the test
/// gives it the top-level command it is normally flattened into.
#[derive(Parser, Debug)]
struct Cli {
    #[command(flatten)]
    infer: InferArgs,
}

fn args(argv: &[&str]) -> InferArgs {
    let mut full = vec!["frink"];
    full.extend_from_slice(argv);
    Cli::parse_from(full).infer
}

/// GitHub issue #170, at the flag rather than at the predicate: the
/// DEFAULT `frink run -m … --temp 0 --ngl 99` must not let Metal
/// fold `lm_head + argmax` onto the device.
///
/// `--repeat-penalty` defaults to **1.1** here, deliberately unlike
/// llama.cpp's 1.0 (`docs/FEATURES.md` records the difference), and
/// a device argmax over raw logits never applies it. The fold gate
/// read a predicate that tested XTC, typical-p and DRY and not the
/// penalties, so a plain greedy Metal run returned a token the host
/// sampler would not have chosen -- and agreed instead, byte for
/// byte, with the same run at `--repeat-penalty 1.0`.
///
/// This test is here and not only in `frink-models` because the
/// DEFAULT is the thing that made it live: the predicate and the
/// flag are two structures that have to agree, and `frink-models`
/// cannot see this crate's `default_value_t`.
///
/// Sabotage: set `default_value_t = 1.0` on `--repeat-penalty`; the
/// first assertion goes red.
#[test]
fn the_default_flags_forbid_the_metal_greedy_argmax_fold() {
    let step = super::TokenStep::new(frink_models::sampling::Sampler::new(1), None);
    let sampling = |argv: &[&str]| {
        args(argv)
            .sampling(None, 4096)
            .expect("no --dry-multiplier, so no vocabulary is needed")
    };

    let defaults = sampling(&["-m", "m.gguf", "--temp", "0"]);
    assert_eq!(defaults.repetition_penalty, 1.1, "llama.cpp's is 1.0");
    assert!(
        step.needs_vocab_logits(&defaults),
        "the default repetition penalty is applied on the host, so the \
         device must hand back a vocabulary and not one token id"
    );

    // Both of llama.cpp's off switches restore the fold, which is
    // what makes the assertion above about the penalty and not about
    // `--top-k 40` or `--min-p 0.05`, which default on too.
    for off in [
        ["-m", "m.gguf", "--temp", "0", "--repeat-penalty", "1.0"],
        ["-m", "m.gguf", "--temp", "0", "--repeat-last-n", "0"],
    ] {
        let s = sampling(&off);
        assert!(
            !step.needs_vocab_logits(&s),
            "{off:?} switches the penalties off, so the fold is exact again"
        );
    }
}

/// The banner may not promise a KV dtype the run will not use.
///
/// `frink -m m.gguf -dev cpu -ngl all` once printed `ctk=f16` while
/// the host `KvCache` was `Vec<f32>` and the budget priced it at f32.
/// The host store honours `--ctk f16` / `f32` now
/// (`frink_models::host_kv_types`), and the banner, the budget and the
/// caches all read that one function, so this pins the answers the
/// host can give: the flag honoured at f16, f32 and q8_0 (#535), and a
/// wire with no host store (`q4_0`) falling back to f16 by name.
#[test]
fn the_banner_reports_the_kv_dtype_the_run_will_actually_keep() {
    let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "f16"]);
    assert_eq!(kv_elem_for(&a).as_str(), "f16", "llama.cpp's default width");
    assert_eq!(
        frink_models::KvElem::from(super::host_kv_types_for(&a).unwrap().k),
        kv_elem_for(&a),
        "the caches and the budget read one function"
    );
    let line = banner_line(&a, OffloadDevice::Cpu);
    assert!(
        line.contains("ctk=f16") && !line.contains("--ctk f16"),
        "{line}"
    );

    let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "f32"]);
    assert_eq!(kv_elem_for(&a).as_str(), "f32");
    assert!(banner_line(&a, OffloadDevice::Cpu).contains("ctk=f32"));

    let a = args(&[
        "-m", "m.gguf", "--device", "cpu", "--ctk", "q8_0", "--ctv", "q8_0",
    ]);
    assert_eq!(kv_elem_for(&a).as_str(), "q8_0");
    assert_eq!(
        super::host_kv_types_for(&a).unwrap(),
        frink_core::kv_store::KvDtype::Q8_0.into()
    );
    let line = banner_line(&a, OffloadDevice::Cpu);
    assert!(
        line.contains("ctk=q8_0") && line.contains("ctv=q8_0") && !line.contains("--ctk q8_0"),
        "{line}"
    );

    let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "q4_0"]);
    assert_eq!(kv_elem_for(&a).as_str(), "f16");
    let line = banner_line(&a, OffloadDevice::Cpu);
    assert!(line.contains("ctk=f16"), "{line}");
    assert!(
        line.contains("--ctk q4_0 has no cpu host store; using f16"),
        "a flag the host cannot honour must say so: {line}"
    );
}

/// `-ctk` sets K and `-ctv` sets V, each f16 by default, as llama.cpp's
/// do (`common/arg.cpp`, #788). `-ctk` used to set both, so
/// `-ctk q8_0` alone, which upstream runs as q8_0 K over f16 V, ran
/// q8_0 V here too. The CPU store keeps the pair as asked, the banner
/// names both halves, and the budget prices the wider one.
#[test]
fn ctk_sets_k_only_and_ctv_sets_v_as_llama_cpps_do() {
    use frink_core::kv_store::{KvDtype, KvTypes};
    let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "q8_0"]);
    assert_eq!((a.ctk.as_str(), a.ctv.as_str()), ("q8_0", "f16"));
    assert_eq!(
        super::host_kv_types_for(&a).unwrap(),
        KvTypes {
            k: KvDtype::Q8_0,
            v: KvDtype::F16
        },
        "-ctk q8_0 alone is q8_0 K over llama.cpp's default f16 V"
    );
    let line = banner_line(&a, OffloadDevice::Cpu);
    assert!(line.contains("ctk=q8_0 ctv=f16"), "{line}");
    assert_eq!(kv_elem_for(&a).as_str(), "f16", "priced at the wider half");

    let a = args(&["-m", "m.gguf", "--device", "cpu", "--cache-type-v", "q8_0"]);
    assert_eq!(
        super::host_kv_types_for(&a).unwrap(),
        KvTypes {
            k: KvDtype::F16,
            v: KvDtype::Q8_0
        }
    );
    assert!(banner_line(&a, OffloadDevice::Cpu).contains("ctk=f16 ctv=q8_0"));

    // `FRINK_CTV` is `-ctv`'s variable, as `FRINK_CTK` is `-ctk`'s.
    use clap::CommandFactory;
    let cmd = Cli::command();
    let env_of = |id: &str| {
        cmd.get_arguments()
            .find(|a| a.get_id() == id)
            .and_then(|a| a.get_env())
            .map(|e| e.to_string_lossy().into_owned())
    };
    assert_eq!(env_of("ctk").as_deref(), Some("FRINK_CTK"));
    assert_eq!(env_of("ctv").as_deref(), Some("FRINK_CTV"));
}

/// Metal's device store keeps one wire for K and V, so a pair that
/// differs there is refused by name before anything loads, rather than
/// run at a type nobody asked for (ADR 0002).
#[test]
fn a_metal_run_refuses_k_and_v_of_different_types() {
    let a = args(&[
        "-m", "m.gguf", "--device", "metal", "--ngl", "all", "--ctk", "q8_0",
    ]);
    if super::budget_backend_for(&a) != frink_models::BudgetBackend::Metal {
        // A build without Metal does not select it.
        return;
    }
    let err = super::host_kv_types_for(&a).unwrap_err().to_string();
    assert!(
        err.contains("-ctk q8_0 -ctv f16") && err.contains("one type"),
        "{err}"
    );
    let a = args(&[
        "-m", "m.gguf", "--device", "metal", "--ngl", "all", "--ctk", "q8_0", "--ctv", "q8_0",
    ]);
    assert!(super::host_kv_types_for(&a).is_ok());
}

/// GitHub issue #297: `FRINK_CTK` is documented as "same as
/// `--ctk`" and could not be.
///
/// The resolution writes `args.ctk` into the variable
/// unconditionally, so before clap read it as the default an
/// environment that said `q4` was overwritten with the flag's
/// `f16` before `frink_metal::attn::metal_kv_dtype` ever looked.
/// Nothing checked it, which is why a documented spelling shipped
/// dead.
///
/// Serialised, because it mutates process-wide state and the other
/// tests in this file parse the same argument.
#[test]
fn the_environment_supplies_the_kv_dtype_when_the_flag_does_not() {
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let restore = std::env::var("FRINK_CTK").ok();

    // SAFETY: single-threaded test body, holding ENV_LOCK.
    unsafe { std::env::set_var("FRINK_CTK", "q4_0") };
    let a = args(&["-m", "m.gguf"]);
    assert_eq!(a.ctk, "q4_0", "the environment was ignored");

    // An explicit flag still wins over it.
    let a = args(&["-m", "m.gguf", "--ctk", "q8_0"]);
    assert_eq!(a.ctk, "q8_0", "the flag lost to the environment");

    // SAFETY: same.
    unsafe {
        match restore {
            Some(v) => std::env::set_var("FRINK_CTK", v),
            None => std::env::remove_var("FRINK_CTK"),
        }
    }
}

/// `-dev cpu` is not `-dev none`, and `-ngl all` under either does
/// nothing. Both were printed as if honoured.
#[test]
fn the_banner_does_not_promise_gpu_layers_on_a_cpu_device() {
    let a = args(&["-m", "m.gguf", "--device", "cpu", "--ngl", "all"]);
    let line = banner_line(&a, OffloadDevice::Cpu);
    assert!(line.contains("device=cpu"), "{line}");
    assert!(line.contains("ignored, no GPU offload"), "{line}");
}

/// And a run that really does select the dtype keeps a clean line.
#[test]
fn a_metal_run_reports_the_requested_dtype_with_no_caveat() {
    let a = args(&[
        "-m", "m.gguf", "--device", "metal", "--ngl", "all", "--ctk", "f16",
    ]);
    let line = banner_line(&a, OffloadDevice::Metal);
    assert!(line.contains("ctk=f16"), "{line}");
    assert!(!line.contains("ignored"), "{line}");
}

/// `-ngl N` must not silently mean "all layers".
///
/// llama.cpp's `-ngl N` puts exactly N layers in VRAM and runs the
/// rest on the CPU, which is how people fit a model that otherwise
/// does not fit. frink parsed the count and read only
/// `offload_enabled()`, a bool, so `--ngl 10` on a 32-layer model
/// offloaded all 32 -- same flag, same value, no error, and the
/// failure arrives as an OOM on the machine the flag existed to
/// accommodate.
///
/// Partial offload is not implemented, so it refuses. The two exact
/// cases still work.
#[test]
fn a_partial_gpu_layer_count_is_refused_rather_than_rounded_up() {
    let err = GpuLayers::Count(10)
        .check_supported(32)
        .expect_err("10 of 32 is partial");
    let msg = err.to_string();
    assert!(msg.contains("PARTIAL"), "{msg}");
    assert!(
        msg.contains("--ngl 0"),
        "the message must say what works: {msg}"
    );
    assert!(msg.contains("--ngl 32"), "{msg}");

    // The exact cases are not partial and must stay accepted.
    GpuLayers::Count(0)
        .check_supported(32)
        .expect("0 = CPU only");
    GpuLayers::Count(32).check_supported(32).expect("32 = all");
    GpuLayers::Count(99)
        .check_supported(32)
        .expect("clamps to all");
    GpuLayers::All.check_supported(32).expect("all");
    GpuLayers::Auto.check_supported(32).expect("auto");
}

/// `--escape` defaults TRUE, as llama.cpp does.
///
/// frink defaulted false, so `-p "a\\nb"` reached the model as a
/// literal backslash-n on frink and as a newline on llama.cpp: the
/// same command, a different prompt, and no error on either side.
#[test]
fn escapes_are_processed_by_default_like_llama_cpp() {
    use clap::Parser;
    #[derive(Parser)]
    struct Probe {
        #[command(flatten)]
        args: super::InferArgs,
    }
    let parsed = Probe::try_parse_from(["frink", "-m", "x.gguf"]).expect("defaults parse");
    assert!(parsed.args.escape, "llama.cpp common/common.h:563 is true");
    assert!(!parsed.args.no_escape);

    let off = Probe::try_parse_from(["frink", "-m", "x.gguf", "--no-escape"])
        .expect("--no-escape parses");
    assert!(off.args.no_escape, "llama.cpp spells the negation this way");
}

/// `--samplers` is llama.cpp's, and the DEFAULT is the chain frink
/// already ran: a command line that does not mention the flag must
/// sample exactly what it did before the flag existed.
///
/// The distribution-level proof of that is
/// `frink_models::sampling::tests::the_default_order_is_the_chain_frink_already_ran`;
/// this is the CLI half -- that the flag's default resolves to the
/// same chain, so the two cannot drift apart.
#[test]
fn samplers_defaults_to_the_chain_frink_already_ran() {
    let default = args(&["-m", "x.gguf"])
        .sampling(None, 4096)
        .expect("no dry, so no vocabulary is needed")
        .sampler_order;
    assert_eq!(default, frink_models::SamplerOrder::default());
    assert_eq!(
        default.to_string(),
        "penalties;dry;top_n_sigma;top_k;typ_p;top_p;min_p;xtc;temperature"
    );
}

/// A caller-supplied order reaches the sampler, in the order typed.
#[test]
fn a_caller_supplied_order_reaches_the_sampler() {
    let order = args(&["-m", "x.gguf", "--samplers", "penalties;temperature;top_k"])
        .sampling(None, 4096)
        .expect("no dry")
        .sampler_order;
    assert_eq!(order.to_string(), "penalties;temperature;top_k");
    // llama.cpp's own aliases, so an upstream command line works.
    assert_eq!(
        args(&["-m", "x.gguf", "--samplers", "top-k;min-p;temp"])
            .sampling(None, 4096)
            .expect("no dry")
            .sampler_order
            .to_string(),
        "top_k;min_p;temperature"
    );
}

/// A sampler frink does not implement is refused BY NAME at the
/// command line, rather than dropped out of the chain.
///
/// Upstream's own default string names three samplers this engine
/// lacks, so pasting it must fail loudly. A caller who asked for
/// `xtc` and was given a chain without it was silently handed a
/// different sampler.
#[test]
fn a_sampler_frink_lacks_is_refused_by_name_on_the_command_line() {
    let err = Cli::try_parse_from([
        "frink",
        "-m",
        "x.gguf",
        "--samplers",
        "penalties;mirostat;temperature",
    ])
    .expect_err("mirostat is not a chain member here")
    .to_string();
    assert!(err.contains("mirostat"), "{err}");
    assert!(err.contains("not implemented"), "{err}");

    // And llama.cpp's OWN default string now parses, which is the
    // point of this change: pasting an upstream command line works.
    Cli::try_parse_from([
        "frink",
        "-m",
        "x.gguf",
        "--samplers",
        "penalties;dry;top_n_sigma;top_k;typ_p;top_p;min_p;xtc;temperature",
    ])
    .expect("llama.cpp's default chain is frink's default chain");

    let unknown = Cli::try_parse_from(["frink", "-m", "x.gguf", "--samplers", "top_kk"])
        .expect_err("no such sampler")
        .to_string();
    assert!(unknown.contains("top_kk"), "{unknown}");
    assert!(unknown.contains("unknown sampler"), "{unknown}");
}

#[test]
fn parses_llama_gpu_layer_values() {
    assert_eq!(GpuLayers::from_str("0"), Ok(GpuLayers::Count(0)));
    assert_eq!(GpuLayers::from_str("42"), Ok(GpuLayers::Count(42)));
    assert_eq!(GpuLayers::from_str("auto"), Ok(GpuLayers::Auto));
    assert_eq!(GpuLayers::from_str("all"), Ok(GpuLayers::All));
    assert!(GpuLayers::from_str("-1").is_err());
    assert!(GpuLayers::from_str("some").is_err());
}

/// A file under the system temp directory, unique to this test process
/// and `tag`, holding `text`.
/// [`args`] with `-m x.gguf` in front, which every parse needs.
fn with_model(argv: &[&str]) -> InferArgs {
    let mut full = vec!["-m", "x.gguf"];
    full.extend_from_slice(argv);
    args(&full)
}

fn temp_file(tag: &str, text: &str) -> std::path::PathBuf {
    let path = std::env::temp_dir().join(format!("frink-run-{}-{tag}", std::process::id()));
    std::fs::write(&path, text).unwrap();
    path
}

/// `-jf FILE` is `-j "$(cat FILE)"`: the same grammar, from the same
/// converter, and exclusive with the other three grammar flags.
///
/// Sabotage: drop the `json_schema_file` branch from `grammar_source`;
/// the first assertion goes red (no grammar at all).
#[test]
fn json_schema_file_is_the_json_schema_flag_read_from_a_file() {
    let schema = r#"{"type": "object", "properties": {"n": {"type": "integer"}}}"#;
    let path = temp_file("schema.json", schema);
    let p = path.to_str().unwrap();
    let from_file = with_model(&["--json-schema-file", p]);
    let inline = with_model(&["--json-schema", schema]);
    let got = from_file.grammar_source().unwrap();
    assert!(got.is_some(), "-jf produced no grammar");
    assert_eq!(got, inline.grammar_source().unwrap());
    let both = with_model(&["--json-schema-file", p, "--grammar", "root ::= \"a\""]);
    let err = both.grammar_source().unwrap_err().to_string();
    assert!(err.contains("mutually exclusive"), "{err}");
    std::fs::remove_file(path).ok();
}

/// `-sysf` drops exactly one trailing newline, as llama.cpp's
/// `read_file` + `pop_back` does, and is exclusive with `--system`.
///
/// Sabotage: replace the `pop` with nothing; the first assertion goes
/// red with a trailing newline.
#[test]
fn system_prompt_file_drops_one_trailing_newline_like_llama_cpp() {
    for (text, want) in [
        ("be terse\n", "be terse"),
        ("two\n\n", "two\n"),
        ("none", "none"),
    ] {
        let path = temp_file("sys.txt", text);
        let mut a = with_model(&["--system-prompt-file", path.to_str().unwrap()]);
        a.read_system_prompt_file().unwrap();
        assert_eq!(a.system.as_deref(), Some(want), "{text:?}");
        std::fs::remove_file(path).ok();
    }
    let clash = Cli::try_parse_from([
        "frink",
        "-m",
        "x.gguf",
        "--system",
        "a",
        "--system-prompt-file",
        "b",
    ]);
    assert!(
        clash.is_err(),
        "--system and --system-prompt-file both accepted"
    );
    let mut missing = with_model(&["--system-prompt-file", "/nonexistent/frink-sysf"]);
    let err = missing.read_system_prompt_file().unwrap_err().to_string();
    assert!(err.contains("--system-prompt-file"), "{err}");
}

/// `--no-jinja` asks for a template mode frink does not have, so it is
/// refused; `--jinja` is what already happens, so it is accepted.
/// `-fa off` is refused, and `-fa` with no value is `auto`.
///
/// Sabotage: delete the `no_jinja` bail; the first assertion goes red.
#[test]
fn jinja_and_flash_attn_refuse_what_frink_cannot_do() {
    let err = with_model(&["--no-jinja"])
        .apply_llama_flags()
        .unwrap_err()
        .to_string();
    assert!(err.contains("--no-jinja"), "{err}");
    with_model(&["--jinja"]).apply_llama_flags().unwrap();
    for off in ["off", "0", "disabled", "false"] {
        let err = with_model(&["--flash-attn", off])
            .apply_llama_flags()
            .unwrap_err()
            .to_string();
        assert!(err.contains("backend property"), "{off}: {err}");
    }
    let err = with_model(&["--flash-attn", "maybe"])
        .apply_llama_flags()
        .unwrap_err()
        .to_string();
    assert!(err.contains("expected on, off or auto"), "{err}");
    assert_eq!(
        with_model(&["--flash-attn"]).flash_attn.as_deref(),
        Some("auto")
    );
    with_model(&["--flash-attn", "on"])
        .apply_llama_flags()
        .unwrap();
}

/// The paired switches: the default is on, and the later spelling wins,
/// as llama.cpp's `{"--warmup"}, {"--no-warmup"}` pair is last-wins.
///
/// Sabotage: make `warmup_enabled` return `true`; the `--no-warmup`
/// assertion goes red.
#[test]
fn warmup_and_show_timings_default_on_and_the_last_spelling_wins() {
    assert!(with_model(&[]).warmup_enabled());
    assert!(!with_model(&["--no-warmup"]).warmup_enabled());
    assert!(with_model(&["--no-warmup", "--warmup"]).warmup_enabled());
    assert!(!with_model(&["--warmup", "--no-warmup"]).warmup_enabled());
    assert!(with_model(&[]).show_timings_enabled());
    assert!(!with_model(&["--no-show-timings"]).show_timings_enabled());
    assert!(with_model(&["--no-show-timings", "--show-timings"]).show_timings_enabled());
}

/// `-co` takes llama.cpp's truthy, falsey and auto spellings, a bare
/// `-co` is on, and anything else is refused as upstream throws.
///
/// Sabotage: map `Switch::Off` to `Some(true)`; the `off` row goes red.
#[test]
fn color_takes_llama_cpps_values() {
    for (argv, want) in [
        (&["--color", "on"][..], Some(true)),
        (&["--color", "1"], Some(true)),
        (&["--color", "off"], Some(false)),
        (&["--color", "false"], Some(false)),
        (&["--color", "auto"], None),
        (&["--color"], Some(true)),
        (&[], None),
    ] {
        assert_eq!(with_model(argv).colour_choice().unwrap(), want, "{argv:?}");
    }
    let err = with_model(&["--color", "rainbow"])
        .colour_choice()
        .unwrap_err()
        .to_string();
    assert!(err.contains("expected on, off or auto"), "{err}");
}

/// The same rule as `--system`: the template is what `--no-cnv` skips.
#[test]
fn chat_template_flags_are_refused_with_no_cnv() {
    for flag in [
        &["--chat-template", "chatml"][..],
        &["--chat-template-kwargs", r#"{"a": 1}"#][..],
        &["--reasoning", "off"][..],
        &["--reasoning-effort", "high"][..],
        &["--reasoning-preserve"][..],
        &["--no-reasoning-preserve"][..],
    ] {
        let mut argv = vec!["-m", "x.gguf", "--no-cnv"];
        argv.extend_from_slice(flag);
        let error = args(&argv).resolve_template_flags().unwrap_err();
        assert!(error.to_string().contains("--no-cnv"), "{error}");

        let without: Vec<&str> = argv.into_iter().filter(|a| *a != "--no-cnv").collect();
        assert!(args(&without).resolve_template_flags().is_ok(), "{flag:?}");
    }
}

/// `auto` and `default` change nothing, so they stay legal with `--no-cnv`.
#[test]
fn template_flags_that_change_nothing_are_not_refused_with_no_cnv() {
    let mut parsed = args(&["-m", "x.gguf", "--no-cnv", "--reasoning", "auto"]);
    parsed.resolve_template_flags().unwrap();
}

#[test]
fn the_later_of_chat_template_and_its_file_wins() {
    let parsed = args(&[
        "-m",
        "x",
        "--chat-template",
        "a",
        "--chat-template-file",
        "b",
    ]);
    assert_eq!(parsed.chat_template, None);
    assert!(parsed.chat_template_file.is_some());
}

/// llama.cpp's default reaches the render, and the flag replaces it.
#[test]
fn reasoning_preserve_defaults_on_and_the_flag_turns_it_off() {
    let mut parsed = args(&["-m", "x.gguf"]);
    parsed.resolve_template_flags().unwrap();
    assert_eq!(
        parsed.template_flags.kwargs["preserve_reasoning"],
        serde_json::json!(true)
    );
    let mut parsed = args(&["-m", "x.gguf", "--no-reasoning-preserve"]);
    parsed.resolve_template_flags().unwrap();
    assert_eq!(
        parsed.template_flags.kwargs["preserve_reasoning"],
        serde_json::json!(false)
    );
}

#[test]
fn a_bad_reasoning_value_is_refused() {
    let mut parsed = args(&["-m", "x", "--reasoning", "maybe"]);
    assert!(parsed.resolve_template_flags().is_err());
}

/// llama.cpp's documented negative values parse, through the same
/// argv rewrite and command the binary uses. `--seed -1`,
/// `--top-nsigma -1` and `--dry-penalty-last-n -1` were refused as an
/// unknown flag `-1`.
#[test]
fn llama_cpps_negative_values_parse() {
    let argv = [
        "frink",
        "-m",
        "x.gguf",
        "--seed",
        "-1",
        "--top-nsigma",
        "-1",
        "--dry-penalty-last-n",
        "-1",
        "--dynatemp-range",
        "-0.5",
        "-l",
        "-5-1",
    ]
    .map(String::from)
    .to_vec();
    let argv = crate::argv::rewrite_llama_style_argv(argv).expect("rewrite");
    let crate::Commands::Run(a) = crate::argv::parse(argv).expect("parses").command else {
        panic!("not run");
    };
    assert_eq!(a.seed, -1);
    assert_eq!(a.top_n_sigma, -1.0);
    assert_eq!(a.dry_penalty_last_n, -1);
    assert_eq!(a.dynatemp_range, -0.5);
    assert_eq!(a.logit_bias[0].token, -5);
}

/// `--dynatemp-range` and `--dynatemp-exp` reach the sampler, with
/// llama.cpp's defaults (`common/common.h:244-245`) when not given.
#[test]
fn dynatemp_flags_reach_the_sampler() {
    let s = args(&["-m", "x.gguf"])
        .sampling(None, 4096)
        .expect("no dry");
    assert_eq!((s.dynatemp_range, s.dynatemp_exponent), (0.0, 1.0));
    let s = args(&[
        "-m",
        "x.gguf",
        "--dynatemp-range",
        "0.5",
        "--dynatemp-exp",
        "2",
    ])
    .sampling(None, 4096)
    .expect("no dry");
    assert_eq!((s.dynatemp_range, s.dynatemp_exponent), (0.5, 2.0));
}

/// The sampler flags frink cannot honour are refused by name before
/// anything loads, and their neutral values pass.
#[test]
fn mirostat_and_greedy_dynatemp_are_refused_by_name() {
    let check = |argv: &[&str]| args(argv).check_sampler_flags();
    for v in ["1", "2"] {
        let err = check(&["-m", "x.gguf", "--mirostat", v])
            .expect_err("mirostat is not implemented")
            .to_string();
        assert!(
            err.contains("--mirostat") && err.contains("not implemented"),
            "{err}"
        );
    }
    let err = check(&["-m", "x.gguf", "--mirostat", "3"])
        .expect_err("no such version")
        .to_string();
    assert!(err.contains("expected 0"), "{err}");
    // Inert at --mirostat 0, as upstream reads them only under Mirostat.
    check(&[
        "-m",
        "x.gguf",
        "--mirostat",
        "0",
        "--mirostat-lr",
        "0.2",
        "--mirostat-ent",
        "3",
    ])
    .expect("--mirostat 0 is the default chain");

    let err = check(&["-m", "x.gguf", "--temp", "0", "--dynatemp-range", "0.5"])
        .expect_err("greedy here, sampled upstream")
        .to_string();
    assert!(err.contains("--dynatemp-range"), "{err}");
    check(&["-m", "x.gguf", "--temp", "0.7", "--dynatemp-range", "0.5"]).expect("sampled");
    // A range of zero or below is upstream's off switch, so greedy is fine.
    check(&["-m", "x.gguf", "--temp", "0", "--dynatemp-range", "-1"]).expect("off");
}

/// `-l` / `--logit-bias` is repeatable, takes a leading `-` id, and is
/// added to the logits BEFORE the penalties, where upstream's chain
/// puts it (`common/sampling.cpp:338-349`).
///
/// The case is built so the order decides the greedy token: token 1
/// has logit -1, is in the history, and gets `+2`. Bias first, then a
/// repeat penalty of 2: `(-1 + 2) / 2 = 0.5`, above token 0's 0.3.
/// Penalty first: `-1 * 2 + 2 = 0`, below it.
#[test]
fn logit_bias_runs_before_the_penalties() {
    let a = args(&[
        "-m",
        "x.gguf",
        "--temp",
        "0",
        "--repeat-penalty",
        "2",
        "-l",
        "1+2",
        "--logit-bias",
        "-5-1",
    ]);
    assert_eq!(a.logit_bias.len(), 2);
    let sampling = a.sampling(None, 4096).expect("no dry");
    let mut step = super::TokenStep::new(frink_models::sampling::Sampler::new(1), None)
        .with_logit_bias(a.logit_bias.clone());
    // With every penalty off, the bias alone must keep a device
    // `lm_head + argmax` fold from skipping it.
    let neutral = args(&["-m", "x.gguf", "--temp", "0", "--repeat-penalty", "1"])
        .sampling(None, 4096)
        .expect("no dry");
    assert!(
        step.needs_vocab_logits(&neutral),
        "a device argmax never sees the bias"
    );
    let history = [1usize];
    let next = step
        .next(
            &[0.3, -1.0],
            &sampling,
            frink_models::PenaltyWindow::new(&history, &[]),
        )
        .expect("no grammar");
    assert_eq!(next, Some(1));
}