llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! What the daemon passes to the backends it spawns: the `LLMMAN_*` env
//! vars (context length, flash attention, KV-cache type, scheduling,
//! parallelism, threads, queue and load limits, metrics) and the
//! `--ctx-size` arithmetic around them (trained-context cap, `--parallel`
//! scaling, the OOM shrink retry). Each `*_from_env` reads the process
//! environment; its `parse_*` half is what the tests exercise.

use std::path::PathBuf;

/// Context tokens requested for every backend this daemon spawns — read
/// from `LLMMAN_CONTEXT_LENGTH` (an env var, not a `llmman serve` flag).
/// Forwarded to llama-server as-is for generation models (0 meaning
/// "trained context"); embedding models are always capped to their
/// trained context. See [`initial_ctx_size`]. Not forwarded to vLLM
/// when 0.
///
/// Unset or unparseable, this falls back to [`DEFAULT_CTX_SIZE`].
pub fn context_length_from_env() -> Option<u32> {
    parse_context_length(std::env::var("LLMMAN_CONTEXT_LENGTH").ok().as_deref())
}

/// [`context_length_from_env`]'s parsing, split out so it's testable
/// without mutating the real process environment.
fn parse_context_length(value: Option<&str>) -> Option<u32> {
    value?.trim().parse().ok()
}

/// An embedding model's context, from `LLMMAN_EMBEDDING_CONTEXT_LENGTH`, in
/// place of [`context_length_from_env`]: its batch is as large as its
/// context (llmmanorg/llmman#820). `0` means the trained context.
pub(super) fn embedding_context_length_from_env() -> Option<u32> {
    parse_context_length(
        std::env::var("LLMMAN_EMBEDDING_CONTEXT_LENGTH")
            .ok()
            .as_deref(),
    )
}

/// `--ctx-size` when `LLMMAN_CONTEXT_LENGTH` is unset: 256k regardless
/// of VRAM, capped per model to its trained context (see
/// [`initial_ctx_size`]). A load that then OOMs is retried halved (see
/// [`next_ctx_size_after_oom`]) instead of guessing from memory up front.
pub const DEFAULT_CTX_SIZE: u32 = 262144;

/// Flash Attention mode requested for every `llama-server` this daemon
/// spawns — read from `LLMMAN_FLASH_ATTENTION` (an env var, not a
/// `llmman serve` flag, mirroring [`context_length_from_env`]). Forwarded
/// verbatim as `--flash-attn <mode>`; unset leaves it off llama-server's
/// own command line entirely, falling back to its own default (`auto`,
/// which already enables it whenever the backend/model support it).
pub(super) fn flash_attention_from_env() -> Option<String> {
    parse_flash_attention(std::env::var("LLMMAN_FLASH_ATTENTION").ok().as_deref())
}

/// [`flash_attention_from_env`]'s parsing, split out so it's testable
/// without mutating the real process environment. Accepts llama-server's
/// own vocabulary (`on`/`off`/`auto`) as well as the boolean spelling
/// (`1`/`0`, `true`/`false`) Ollama documents for `OLLAMA_FLASH_ATTENTION`,
/// since users porting a config from there would otherwise silently get
/// llama-server's default instead of what they asked for.
fn parse_flash_attention(value: Option<&str>) -> Option<String> {
    let v = value?.trim();
    if v.is_empty() {
        return None;
    }
    Some(match v.to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" => "on".to_string(),
        "0" | "false" | "no" => "off".to_string(),
        other => other.to_string(),
    })
}

/// KV-cache quantization type requested for every `llama-server` this
/// daemon spawns — read from `LLMMAN_KV_CACHE_TYPE` (an env var, not a
/// `llmman serve` flag, mirroring [`context_length_from_env`]). Forwarded
/// as both `--cache-type-k` and `--cache-type-v`: llama-server takes
/// those separately, but Ollama's `OLLAMA_KV_CACHE_TYPE` (the convention
/// this mirrors) documents a single value applied to both, and there's no
/// use case yet for setting K and V independently through this daemon.
///
/// One of `f16` (llama-server's own default), `q8_0`, or `q4_0` — the
/// same set Ollama documents — trades output quality for a smaller
/// KV-cache footprint at long context lengths. Not validated here;
/// llama-server rejects an unsupported value itself, surfaced via
/// `wait_for_ready`'s stderr-tail capture same as any other startup
/// failure.
pub(super) fn kv_cache_type_from_env() -> Option<String> {
    parse_kv_cache_type(std::env::var("LLMMAN_KV_CACHE_TYPE").ok().as_deref())
}

/// [`kv_cache_type_from_env`]'s parsing, split out so it's testable
/// without mutating the real process environment.
fn parse_kv_cache_type(value: Option<&str>) -> Option<String> {
    let v = value?.trim();
    (!v.is_empty()).then(|| v.to_string())
}

/// `--split-mode` value requested for every `llama-server` spawn — read
/// from `LLMMAN_SCHED_SPREAD`, llmman's equivalent of Ollama's
/// `OLLAMA_SCHED_SPREAD`. Truthy forwards `--split-mode layer` (spread
/// across every GPU — already llama-server's own default, now explicit);
/// falsey forwards `--split-mode none` (restrict to one GPU). Unset
/// leaves llama-server's own default untouched.
pub(super) fn sched_spread_from_env() -> Option<&'static str> {
    parse_sched_spread(std::env::var("LLMMAN_SCHED_SPREAD").ok().as_deref())
}

/// [`sched_spread_from_env`]'s parsing, split out so it's testable
/// without mutating the real process environment.
fn parse_sched_spread(value: Option<&str>) -> Option<&'static str> {
    let v = value?.trim();
    if v.is_empty() {
        return None;
    }
    match v.to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" | "layer" => Some("layer"),
        "0" | "false" | "no" | "off" | "none" => Some("none"),
        _ => None,
    }
}

/// `--parallel <n>` for every `llama-server` this daemon spawns (GGUF
/// models only — vllm/mlx_lm.server handle concurrency their own way,
/// with no equivalent flag), from `LLMMAN_NUM_PARALLEL`. Mirrors
/// Ollama's `OLLAMA_NUM_PARALLEL`; unset leaves llama-server's own
/// default untouched (`auto`: four slots sharing one KV cache), bar an
/// embedding model's — see [`effective_num_parallel`].
pub(super) fn num_parallel_from_env() -> Option<u32> {
    parse_num_parallel(std::env::var("LLMMAN_NUM_PARALLEL").ok().as_deref())
}

/// `0` is rejected, same as llama-server's own `--parallel` validation.
fn parse_num_parallel(value: Option<&str>) -> Option<u32> {
    let n: u32 = value?.trim().parse().ok()?;
    (n != 0).then_some(n)
}

/// `--threads <n>` for every `llama-server` this daemon spawns:
/// [`default_threads`] of `std::thread::available_parallelism`, which
/// already reflects a cgroup quota or a narrowed affinity mask.
/// `LLAMA_ARG_THREADS` set wins: `None` here, llama-server reads it
/// itself (in a container, via `LLAMA_CPP_ENV_PASSTHROUGH_VARS`).
pub(super) fn threads_from_env_or_host() -> Option<u32> {
    if std::env::var_os("LLAMA_ARG_THREADS").is_some() {
        return None;
    }
    let available = std::thread::available_parallelism().ok()?.get();
    Some(default_threads(
        u32::try_from(available).unwrap_or(u32::MAX),
    ))
}

/// Above this many available CPUs, [`default_threads`] uses half.
const HALVE_THREADS_ABOVE: u32 = 8;

/// Half the available CPUs when more than [`HALVE_THREADS_ABOVE`] are
/// available, otherwise all of them. On SMT hosts half is roughly the
/// physical core count; small boxes and quota-limited containers keep
/// every CPU they were given.
fn default_threads(available: u32) -> u32 {
    if available > HALVE_THREADS_ABOVE {
        available / 2
    } else {
        available
    }
}

/// This daemon's effective CPU limit in whole CPUs, `Some(n)` only when
/// one binds: `std::thread::available_parallelism` — min(affinity,
/// cgroup quota), floored, at least 1; std walks the cgroup ancestor
/// chain itself, v1 and v2 — below the online CPU count from
/// /sys/devices/system/cpu/online. Any read failure is `None`: fail
/// closed.
#[cfg(target_os = "linux")]
fn host_cpu_limit() -> Option<u32> {
    let allowed = std::thread::available_parallelism().ok()?.get() as u32;
    let online = online_cpu_count()?;
    (allowed < online).then_some(allowed)
}

/// The backend container's `--cpus`: this daemon's cgroup v2 quota as a
/// fraction (the tightest `cpu.max` on its own chain, so `0.5` stays
/// `0.5`), capped by its affinity mask; without a v2 quota, the
/// whole-CPU [`host_cpu_limit`] (a cgroup v1 quota is floored). `Some`
/// only when it binds. Needed even when `LLAMA_ARG_THREADS` owns the
/// thread count.
pub(super) fn container_cpu_limit() -> Option<f64> {
    #[cfg(target_os = "linux")]
    {
        let online = online_cpu_count()?;
        let limit = match cgroup_v2_cpu_quota() {
            Some(q) => q.min(f64::from(affinity_cpu_count().unwrap_or(online))),
            None => f64::from(host_cpu_limit()?),
        };
        (limit < f64::from(online)).then_some(limit)
    }
    #[cfg(not(target_os = "linux"))]
    None
}

/// CPUs in this process's affinity mask, from `Cpus_allowed_list` in
/// /proc/self/status.
#[cfg(target_os = "linux")]
fn affinity_cpu_count() -> Option<u32> {
    let status = std::fs::read_to_string("/proc/self/status").ok()?;
    let list = status
        .lines()
        .find_map(|l| l.strip_prefix("Cpus_allowed_list:"))?;
    cpu_list_count(list)
}

/// The tightest `cpu.max` quota, in CPUs, from this process's cgroup v2
/// node up to the root; `None` without one.
#[cfg(target_os = "linux")]
fn cgroup_v2_cpu_quota() -> Option<f64> {
    let cgroup = std::fs::read_to_string("/proc/self/cgroup").ok()?;
    let rel = cgroup.lines().find_map(|l| l.strip_prefix("0::"))?.trim();
    let root = std::path::Path::new("/sys/fs/cgroup");
    root.join(rel.trim_start_matches('/'))
        .ancestors()
        .take_while(|d| d.starts_with(root))
        .filter_map(|d| std::fs::read_to_string(d.join("cpu.max")).ok())
        .filter_map(|s| parse_cpu_max(&s))
        .reduce(f64::min)
}

/// `cpu.max`'s `<quota> <period>` in microseconds as CPUs; `max <period>`
/// (unlimited) or malformed content is `None`.
#[cfg(target_os = "linux")]
fn parse_cpu_max(content: &str) -> Option<f64> {
    let mut parts = content.split_whitespace();
    let quota: f64 = parts.next()?.parse().ok()?;
    let period: f64 = parts.next()?.parse().ok()?;
    (quota > 0.0 && period > 0.0).then(|| quota / period)
}

/// Online CPUs from /sys/devices/system/cpu/online, the baseline
/// `available_parallelism` is compared against to decide whether a
/// quota or affinity limit binds. `None` when the file is unreadable
/// or malformed.
#[cfg(target_os = "linux")]
fn online_cpu_count() -> Option<u32> {
    cpu_list_count(&std::fs::read_to_string("/sys/devices/system/cpu/online").ok()?)
}

/// CPU count from a kernel CPU list such as /sys/devices/system/cpu/online:
/// comma-separated single IDs or inclusive ranges (`0-15`, `0,4-7`).
/// `None` on empty or malformed content.
#[cfg(target_os = "linux")]
fn cpu_list_count(list: &str) -> Option<u32> {
    let mut count: u32 = 0;
    for part in list.trim().split(',') {
        match part.split_once('-') {
            Some((lo, hi)) => {
                let (lo, hi): (u32, u32) = (lo.trim().parse().ok()?, hi.trim().parse().ok()?);
                if lo > hi {
                    return None;
                }
                count = count.checked_add(hi.checked_sub(lo)?.checked_add(1)?)?;
            }
            None => {
                let _: u32 = part.trim().parse().ok()?;
                count = count.checked_add(1)?;
            }
        }
    }
    (count > 0).then_some(count)
}

/// The `--ctx-size` value to actually forward to llama-server: `ctx_size`
/// (the per-request context every other computation — retries, error
/// messages, `LLMMAN_CONTEXT_LENGTH` itself — is expressed in) times
/// `num_parallel`. llama-server splits one `--ctx-size` evenly across
/// every `--parallel` slot rather than giving each its own full amount,
/// so forwarding `ctx_size` unscaled would silently divide a request's
/// real context by `num_parallel`; Ollama avoids exactly this by
/// launching with `NumCtx * numParallel` (`llm/llama_server.go`).
/// Callers should only ever pass a non-`None` `num_parallel` alongside
/// a `Some` `ctx_size` — see `ensure_model`'s own `num_parallel`
/// fallback, which drops it to `None` otherwise (nothing safe to scale
/// against).
pub(super) fn backend_ctx_size(ctx_size: Option<u32>, num_parallel: Option<u32>) -> Option<u32> {
    ctx_size.map(|c| c.saturating_mul(num_parallel.unwrap_or(1)))
}

/// `num_parallel` unless `ctx_size` is `None` (a high-VRAM host
/// deferring to the model's own trained context, nothing safe to scale
/// against — see `backend_ctx_size`'s doc comment), in which case
/// `None`: forwarding `--parallel` unscaled would silently divide that
/// trained context across slots instead.
///
/// An `embedding` model with none left gets one slot, not llama-server's
/// `auto` of four, which cost 3.5x the memory (llmmanorg/llmman#686). One
/// divides nothing, so needs no `ctx_size`.
pub(super) fn effective_num_parallel(
    ctx_size: Option<u32>,
    num_parallel: Option<u32>,
    embedding: bool,
) -> Option<u32> {
    ctx_size.and(num_parallel).or(embedding.then_some(1))
}

/// Matches Ollama's own default for `OLLAMA_MAX_QUEUE`.
const DEFAULT_MAX_QUEUE: usize = 512;

/// Maximum number of requests `ensure_model` admits at once before
/// rejecting with a 503, from `LLMMAN_MAX_QUEUE` (mirrors Ollama's
/// `OLLAMA_MAX_QUEUE`). See `try_admit`.
pub(super) fn max_queue_from_env() -> usize {
    parse_max_queue(std::env::var("LLMMAN_MAX_QUEUE").ok().as_deref())
}

/// Unlike most other `parse_*` functions here, `0` is a real value (see
/// `try_admit_against`'s doc comment), not "unset".
fn parse_max_queue(value: Option<&str>) -> usize {
    match value.map(str::trim) {
        Some(v) if !v.is_empty() => v.parse().unwrap_or(DEFAULT_MAX_QUEUE),
        _ => DEFAULT_MAX_QUEUE,
    }
}

/// The certificate chain and private key `llmman serve` terminates TLS
/// with, from `LLMMAN_TLS_CERT` and `LLMMAN_TLS_KEY` (PEM paths). Both or
/// neither: one alone is a misconfiguration, refused at startup rather
/// than served over plain http.
pub(super) fn tls_from_env() -> anyhow::Result<Option<(PathBuf, PathBuf)>> {
    parse_tls(
        std::env::var_os("LLMMAN_TLS_CERT"),
        std::env::var_os("LLMMAN_TLS_KEY"),
    )
}

fn parse_tls(
    cert: Option<std::ffi::OsString>,
    key: Option<std::ffi::OsString>,
) -> anyhow::Result<Option<(PathBuf, PathBuf)>> {
    let present = |v: Option<std::ffi::OsString>| v.filter(|v| !v.is_empty()).map(PathBuf::from);
    match (present(cert), present(key)) {
        (Some(cert), Some(key)) => Ok(Some((cert, key))),
        (None, None) => Ok(None),
        (Some(_), None) => anyhow::bail!("LLMMAN_TLS_CERT is set but LLMMAN_TLS_KEY is not"),
        (None, Some(_)) => anyhow::bail!("LLMMAN_TLS_KEY is set but LLMMAN_TLS_CERT is not"),
    }
}

/// Whether to serve `GET /metrics` at all, from `LLMMAN_METRICS`. Off
/// unless the operator asked for it: a daemon without keys (see the
/// `auth` module) has no authentication, and a scrape reports version,
/// route mix, model names and model churn. None of that should start
/// answering because llmman was upgraded. With keys configured, the
/// scrape route requires one like every other.
pub(super) fn metrics_enabled_from_env() -> bool {
    parse_metrics_enabled(std::env::var("LLMMAN_METRICS").ok().as_deref())
}

/// [`metrics_enabled_from_env`]'s parsing, split out so it's testable
/// without mutating the real process environment. `1` is what the README
/// documents; the rest of the truthy set is here because every other
/// boolean env var in this file accepts it, and a `LLMMAN_METRICS=true`
/// that silently did nothing would be worse than the extra branch.
fn parse_metrics_enabled(value: Option<&str>) -> bool {
    matches!(
        value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),
        Some("1" | "true" | "yes" | "on")
    )
}

/// Maximum number of models `ensure_model` keeps loaded at once, from
/// `LLMMAN_MAX_LOADED_MODELS` (mirrors Ollama's `OLLAMA_MAX_LOADED_MODELS`,
/// but as one flat daemon-wide total, not per-GPU — llmman has no
/// per-model memory estimate to size a per-GPU figure against). `0` =
/// unbounded. See `enforce_max_loaded_models`.
pub(super) fn max_loaded_models_from_env() -> usize {
    parse_max_loaded_models(std::env::var("LLMMAN_MAX_LOADED_MODELS").ok().as_deref())
}

fn parse_max_loaded_models(value: Option<&str>) -> usize {
    value
        .map(str::trim)
        .and_then(|v| v.parse().ok())
        .unwrap_or(0)
}

/// Whether `model_ref` gets `--context-shift`. Enabled except for
/// DeepSeek-family ("deepseek2" architecture) models, mirroring Ollama's
/// own `supportsContextShift` (`server/sched.go`) — their MLA-compressed
/// KV cache can't be shifted the way llama-server expects. Ollama reads
/// the GGUF architecture; this is a coarser name-based heuristic.
pub(super) fn supports_context_shift(model_ref: &str) -> bool {
    !model_ref.to_ascii_lowercase().contains("deepseek")
}

/// A GGUF's `{arch}.context_length` (`n_ctx_train`), if present and
/// non-zero.
pub(super) fn gguf_trained_ctx(info: &crate::gguf::Info) -> Option<u32> {
    trained_ctx(info.context_length())
}

/// A header's `{arch}.context_length` as a trained context: `None` if
/// absent, zero or past `u32`.
pub(super) fn trained_ctx(context_length: Option<u64>) -> Option<u32> {
    context_length
        .and_then(|n| u32::try_from(n).ok())
        .filter(|n| *n > 0)
}

/// `Some(trained context)` if the GGUF is an embedding model (see
/// [`crate::gguf::Info::is_embedding`]), else `None`.
pub(super) fn embedding_model_ctx(info: &crate::gguf::Info) -> Option<Option<u32>> {
    info.is_embedding().then(|| gguf_trained_ctx(info))
}

/// A decision model's default prompt limit, in tokens. llama-server reads
/// its whole prompt in one ubatch, and the compute buffer grows with it
/// (about 2 GiB here, 8.7 GiB at 32768, for a 9B model), so the 256k default
/// context is no size to allocate.
pub(super) const DECISION_DEFAULT_BATCH: u32 = 8192;

/// The `-b`/`-ub` for a model whose whole input must fit one ubatch, else
/// `None`. An embedding model gets its context. A decision model too, as
/// ollama sizes it by `num_ctx`, but only an `explicit`
/// `LLMMAN_CONTEXT_LENGTH` takes it past [`DECISION_DEFAULT_BATCH`], and
/// never past the `trained` context (which is what `0` asks for).
pub(super) fn whole_prompt_batch(
    embedding: bool,
    decision: bool,
    ctx_size: Option<u32>,
    explicit: bool,
    trained: Option<u32>,
) -> Option<u32> {
    if embedding {
        return ctx_size.filter(|n| *n > 0);
    }
    if !decision {
        return None;
    }
    if !explicit {
        let wanted = ctx_size.filter(|n| *n > 0);
        return Some(wanted.map_or(DECISION_DEFAULT_BATCH, |n| n.min(DECISION_DEFAULT_BATCH)));
    }
    // An explicit 0 is the trained context, if known.
    let trained = trained.filter(|n| *n > 0);
    match (ctx_size.unwrap_or(0), trained) {
        (0, trained) => trained,
        (n, Some(trained)) => Some(n.min(trained)),
        (n, None) => Some(n),
    }
}

/// The `--ctx-size` a load starts from: `configured` capped to `trained`
/// unless it's an `explicit` user value for a non-`embedding` model.
/// llama-server allocates the KV cache at `--ctx-size` and only caps
/// per-slot use to `n_ctx_train`, so an unclamped [`DEFAULT_CTX_SIZE`]
/// would reserve 256k of KV for a 32k model. 0/`None` mean `trained`.
pub(super) fn initial_ctx_size(
    configured: Option<u32>,
    explicit: bool,
    trained: Option<u32>,
    embedding: bool,
) -> Option<u32> {
    let Some(trained) = trained else {
        return configured;
    };
    if explicit && !embedding {
        return configured;
    }
    Some(
        configured
            .filter(|n| *n > 0)
            .map_or(trained, |n| n.min(trained)),
    )
}

// ---------------------------------------------------------------------------
// Out-of-memory auto-shrink retry (ensure_model) — mirrors Ollama's
// reduceAutoNumCtxForLoadOOM: a chosen --ctx-size can still be too big
// for actual free VRAM, so retry with it halved a few times instead of
// failing the load outright.
// ---------------------------------------------------------------------------

/// Max halving retries for an OOM-looking llama-server load.
pub(super) const MAX_CTX_SHRINK_ATTEMPTS: u32 = 4;

/// Floor below which a still-failing load is a hard failure, not
/// something to keep shrinking.
const MIN_CTX_SIZE_FOR_RETRY: u32 = 16384;

/// Next `--ctx-size` to retry an OOM'd load with, or `None` if shrinking
/// further wouldn't help (at/under the floor already).
pub(super) fn next_ctx_size_after_oom(current: u32) -> Option<u32> {
    let next = (current / 2).max(MIN_CTX_SIZE_FOR_RETRY);
    // `next < current`, not `!=`: below the floor, halving+max would
    // otherwise suggest a *larger* ctx-size after an OOM.
    (next < current).then_some(next)
}

/// True if `detail` (a failed load's stderr tail, or an error message)
/// looks like a memory-allocation failure rather than some other startup
/// error. Matched against known ggml/llama.cpp allocator log phrasings —
/// deliberately specific rather than one broad substring, since
/// misclassifying an unrelated failure as OOM would burn several slow
/// retries before surfacing the real error.
pub(super) fn looks_like_oom(detail: &str) -> bool {
    let d = detail.to_ascii_lowercase();
    [
        "failed to allocate",
        "out of memory",
        "not enough memory",
        "insufficient memory",
        "cudamalloc failed",
        "std::bad_alloc",
    ]
    .iter()
    .any(|needle| d.contains(needle))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_threads_halves_only_above_eight() {
        assert_eq!(default_threads(1), 1);
        assert_eq!(default_threads(2), 2);
        assert_eq!(default_threads(8), 8);
        assert_eq!(default_threads(9), 4);
        assert_eq!(default_threads(16), 8);
        assert_eq!(default_threads(128), 64);
    }

    #[test]
    fn parse_max_queue_defaults_to_ollamas_own_512_on_anything_unparseable() {
        assert_eq!(parse_max_queue(None), 512);
        assert_eq!(parse_max_queue(Some("")), 512);
        assert_eq!(parse_max_queue(Some("garbage")), 512);
        assert_eq!(parse_max_queue(Some("10")), 10);
        // Unlike most other LLMMAN_*/parse_* pairs, an explicit "0" is a
        // real value (disables the bound), not treated as unset.
        assert_eq!(parse_max_queue(Some("0")), 0);
    }

    #[test]
    fn parse_max_loaded_models_defaults_to_unbounded_on_anything_unparseable() {
        assert_eq!(parse_max_loaded_models(None), 0);
        assert_eq!(parse_max_loaded_models(Some("")), 0);
        assert_eq!(parse_max_loaded_models(Some("garbage")), 0);
        assert_eq!(parse_max_loaded_models(Some("3")), 3);
    }

    #[test]
    fn parse_metrics_enabled_accepts_the_truthy_spellings_and_nothing_else() {
        for on in ["1", "true", "TRUE", "yes", "on", " 1 "] {
            assert!(parse_metrics_enabled(Some(on)), "{on:?} should enable");
        }
        for off in ["0", "false", "no", "off", "", "  ", "2", "enabled"] {
            assert!(!parse_metrics_enabled(Some(off)), "{off:?} should not");
        }
        assert!(
            !parse_metrics_enabled(None),
            "unset is the default, and the default is off"
        );
    }

    #[test]
    fn tls_takes_both_paths_or_neither() {
        let os = |v: &str| Some(std::ffi::OsString::from(v));
        assert_eq!(parse_tls(None, None).unwrap(), None);
        assert_eq!(parse_tls(os(""), os("")).unwrap(), None, "blank is unset");
        assert_eq!(
            parse_tls(os("/c.pem"), os("/k.pem")).unwrap(),
            Some((PathBuf::from("/c.pem"), PathBuf::from("/k.pem")))
        );
        assert!(parse_tls(os("/c.pem"), None)
            .unwrap_err()
            .to_string()
            .contains("LLMMAN_TLS_KEY"));
        assert!(parse_tls(None, os("/k.pem"))
            .unwrap_err()
            .to_string()
            .contains("LLMMAN_TLS_CERT"));
    }

    #[test]
    fn parse_context_length_accepts_a_plain_number_and_rejects_everything_else() {
        assert_eq!(parse_context_length(Some("32768")), Some(32768));
        assert_eq!(parse_context_length(Some(" 32768 \n")), Some(32768));
        assert_eq!(parse_context_length(Some("0")), Some(0));
        assert_eq!(parse_context_length(None), None);
        assert_eq!(parse_context_length(Some("")), None);
        assert_eq!(parse_context_length(Some("not-a-number")), None);
        assert_eq!(parse_context_length(Some("-1")), None);
    }

    #[test]
    fn parse_flash_attention_accepts_llama_server_and_ollama_spellings() {
        // llama-server's own vocabulary passes straight through.
        assert_eq!(parse_flash_attention(Some("on")), Some("on".into()));
        assert_eq!(parse_flash_attention(Some("off")), Some("off".into()));
        assert_eq!(parse_flash_attention(Some("auto")), Some("auto".into()));
        // Ollama's OLLAMA_FLASH_ATTENTION boolean spelling is translated.
        assert_eq!(parse_flash_attention(Some("1")), Some("on".into()));
        assert_eq!(parse_flash_attention(Some("true")), Some("on".into()));
        assert_eq!(parse_flash_attention(Some("0")), Some("off".into()));
        assert_eq!(parse_flash_attention(Some("false")), Some("off".into()));
        // Case-insensitive, whitespace-tolerant.
        assert_eq!(parse_flash_attention(Some(" ON \n")), Some("on".into()));
        // Unset/empty leaves llama-server's own default untouched.
        assert_eq!(parse_flash_attention(None), None);
        assert_eq!(parse_flash_attention(Some("")), None);
        assert_eq!(parse_flash_attention(Some("   ")), None);
    }

    #[test]
    fn parse_kv_cache_type_trims_whitespace_and_treats_empty_as_unset() {
        assert_eq!(parse_kv_cache_type(Some("q8_0")), Some("q8_0".into()));
        assert_eq!(parse_kv_cache_type(Some(" q4_0 \n")), Some("q4_0".into()));
        assert_eq!(parse_kv_cache_type(None), None);
        assert_eq!(parse_kv_cache_type(Some("")), None);
        assert_eq!(parse_kv_cache_type(Some("   ")), None);
    }

    #[test]
    fn parse_sched_spread_maps_truthy_and_falsey_spellings_to_split_mode() {
        for truthy in ["1", "true", "yes", "on", "layer", " ON \n"] {
            assert_eq!(
                parse_sched_spread(Some(truthy)),
                Some("layer"),
                "input {truthy:?}"
            );
        }
        for falsey in ["0", "false", "no", "off", "none", " OFF \n"] {
            assert_eq!(
                parse_sched_spread(Some(falsey)),
                Some("none"),
                "input {falsey:?}"
            );
        }
    }

    #[test]
    fn parse_sched_spread_leaves_llama_servers_own_default_untouched_when_unset_or_unparseable() {
        assert_eq!(parse_sched_spread(None), None);
        assert_eq!(parse_sched_spread(Some("")), None);
        assert_eq!(parse_sched_spread(Some("   ")), None);
        assert_eq!(parse_sched_spread(Some("garbage")), None);
    }

    #[test]
    fn parse_num_parallel_accepts_a_positive_integer() {
        assert_eq!(parse_num_parallel(Some("4")), Some(4));
        assert_eq!(parse_num_parallel(Some(" 1 ")), Some(1));
    }

    #[test]
    fn parse_num_parallel_rejects_zero_and_unparseable_values() {
        assert_eq!(parse_num_parallel(Some("0")), None);
        assert_eq!(parse_num_parallel(None), None);
        assert_eq!(parse_num_parallel(Some("")), None);
        assert_eq!(parse_num_parallel(Some("-1")), None);
        assert_eq!(parse_num_parallel(Some("garbage")), None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn cpu_list_count_counts_ids_and_inclusive_ranges() {
        // (kernel CPU list, expected count)
        let cases = [
            ("0-15\n", Some(16)),
            ("0", Some(1)),
            ("0,4-7\n", Some(5)),
            ("0-3,8-11\n", Some(8)),
            // Malformed or empty content fails closed: the caller then
            // passes no --threads and llama-server autodetects.
            ("", None),
            ("\n", None),
            ("3-1", None),
            ("0-x", None),
            ("a", None),
            ("0,,2", None),
            // Range length would overflow u32; no kernel emits this.
            ("0-4294967295", None),
            ("0-4294967295,4", None),
        ];
        for (list, expected) in &cases {
            assert_eq!(&cpu_list_count(list), expected, "list={list:?}");
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn parse_cpu_max_reads_quota_over_period_and_treats_max_as_unlimited() {
        assert_eq!(parse_cpu_max("200000 100000\n"), Some(2.0));
        assert_eq!(parse_cpu_max("50000 100000\n"), Some(0.5));
        assert_eq!(parse_cpu_max("150000 100000"), Some(1.5));
        for bad in ["max 100000\n", "", "100000", "0 100000", "100000 0", "x y"] {
            assert_eq!(parse_cpu_max(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn backend_ctx_size_scales_by_num_parallel_so_each_slot_keeps_the_full_context() {
        // llama-server splits one --ctx-size evenly across every
        // --parallel slot, so this must scale up to compensate —
        // matching Ollama's own NumCtx * numParallel.
        assert_eq!(backend_ctx_size(Some(4096), Some(4)), Some(16384));
        assert_eq!(backend_ctx_size(Some(4096), Some(1)), Some(4096));
        assert_eq!(backend_ctx_size(Some(4096), None), Some(4096));
        assert_eq!(backend_ctx_size(None, Some(4)), None);
        assert_eq!(backend_ctx_size(None, None), None);
    }

    #[test]
    fn backend_ctx_size_saturates_instead_of_overflowing() {
        assert_eq!(backend_ctx_size(Some(u32::MAX), Some(2)), Some(u32::MAX));
    }

    #[test]
    fn effective_num_parallel_drops_to_none_without_a_ctx_size_to_scale() {
        // Nothing to scale --parallel against, so don't forward it at
        // all rather than let llama-server silently divide the model's
        // own trained context across slots.
        assert_eq!(effective_num_parallel(None, Some(4), false), None);
        assert_eq!(effective_num_parallel(Some(4096), Some(4), false), Some(4));
        assert_eq!(effective_num_parallel(Some(4096), None, false), None);
        assert_eq!(effective_num_parallel(None, None, false), None);
    }

    /// An embedding model defaults to one slot (llmmanorg/llmman#686); an
    /// explicit `LLMMAN_NUM_PARALLEL` wins, and other models are untouched.
    #[test]
    fn an_embedding_model_defaults_to_one_slot() {
        assert_eq!(effective_num_parallel(Some(2048), None, true), Some(1));
        assert_eq!(effective_num_parallel(None, None, true), Some(1));
        assert_eq!(effective_num_parallel(Some(2048), Some(4), true), Some(4));
        // Dropped for want of a ctx_size to scale: one slot, not `auto`.
        assert_eq!(effective_num_parallel(None, Some(4), true), Some(1));
        assert_eq!(effective_num_parallel(Some(2048), None, false), None);
    }

    /// The GGUF test (ollama's own): a `{arch}.pooling_type` key marks an
    /// embedding model; both kinds report their trained context.
    #[test]
    fn embedding_model_ctx_keys_off_pooling_type_and_reports_the_trained_context() {
        let chat = crate::gguf::write_test_gguf_with(&[]);
        let embed = crate::gguf::write_test_gguf_with(&[("llama.pooling_type", 1)]);
        let chat_info = crate::gguf::read_info(&chat).unwrap();
        let embed_info = crate::gguf::read_info(&embed).unwrap();
        std::fs::remove_file(&chat).ok();
        std::fs::remove_file(&embed).ok();
        assert_eq!(embedding_model_ctx(&chat_info), None);
        assert_eq!(embedding_model_ctx(&embed_info), Some(Some(4096)));
        assert_eq!(gguf_trained_ctx(&chat_info), Some(4096));
        assert_eq!(gguf_trained_ctx(&embed_info), Some(4096));
    }

    #[test]
    fn whole_prompt_batch_sizes_the_ubatch_for_a_model_that_reads_its_input_at_once() {
        let embed = |ctx| whole_prompt_batch(true, false, ctx, false, Some(4096));
        // An embedding model takes its whole context, whatever that is.
        assert_eq!(embed(Some(32768)), Some(32768));
        assert_eq!(embed(Some(0)), None);
        assert_eq!(embed(None), None);
        // Anything else keeps llama-server's own batch.
        assert_eq!(
            whole_prompt_batch(false, false, Some(4096), true, None),
            None
        );
    }

    #[test]
    fn whole_prompt_batch_gives_a_decision_model_its_context_up_to_what_memory_allows() {
        let default = |ctx, trained| whole_prompt_batch(false, true, ctx, false, trained);
        // Not asked for: the context, but never past the default batch.
        assert_eq!(default(Some(4096), Some(262144)), Some(4096));
        assert_eq!(
            default(Some(262144), Some(262144)),
            Some(DECISION_DEFAULT_BATCH)
        );
        assert_eq!(default(None, None), Some(DECISION_DEFAULT_BATCH));
        assert_eq!(default(Some(0), Some(262144)), Some(DECISION_DEFAULT_BATCH));

        let explicit = |ctx, trained| whole_prompt_batch(false, true, ctx, true, trained);
        // Asked for: all of it, up to the trained context.
        assert_eq!(explicit(Some(65536), Some(262144)), Some(65536));
        assert_eq!(explicit(Some(1 << 20), Some(262144)), Some(262144));
        assert_eq!(explicit(Some(2048), Some(262144)), Some(2048));
        assert_eq!(explicit(Some(65536), None), Some(65536));
        // 0 is the trained context.
        assert_eq!(explicit(Some(0), Some(262144)), Some(262144));
        assert_eq!(explicit(None, Some(262144)), Some(262144));
        assert_eq!(explicit(Some(0), None), None);
    }

    #[test]
    fn initial_ctx_size_caps_the_auto_default_at_the_trained_context() {
        let auto = Some(DEFAULT_CTX_SIZE);
        // Smaller trained context wins; larger leaves the default alone.
        assert_eq!(
            initial_ctx_size(auto, false, Some(32768), false),
            Some(32768)
        );
        assert_eq!(initial_ctx_size(auto, false, Some(1 << 20), false), auto);
        // No readable header: nothing to clamp against.
        assert_eq!(initial_ctx_size(auto, false, None, false), auto);
    }

    #[test]
    fn initial_ctx_size_forwards_an_explicit_value_unless_embedding() {
        // A user's LLMMAN_CONTEXT_LENGTH is theirs to get wrong; 0 stays 0.
        assert_eq!(
            initial_ctx_size(Some(65536), true, Some(4096), false),
            Some(65536)
        );
        assert_eq!(initial_ctx_size(Some(0), true, Some(4096), false), Some(0));
        // Embedding models are capped regardless, and 0/None mean trained.
        assert_eq!(
            initial_ctx_size(Some(65536), true, Some(4096), true),
            Some(4096)
        );
        assert_eq!(
            initial_ctx_size(Some(2048), true, Some(4096), true),
            Some(2048)
        );
        assert_eq!(
            initial_ctx_size(Some(0), false, Some(4096), true),
            Some(4096)
        );
        assert_eq!(initial_ctx_size(None, false, Some(4096), true), Some(4096));
    }

    #[test]
    fn supports_context_shift_disables_only_for_deepseek_family_models() {
        assert!(!supports_context_shift("deepseek-v3:latest"));
        assert!(!supports_context_shift("deepseek-r1:70b"));
        assert!(!supports_context_shift("DeepSeek-V2.5:latest")); // case-insensitive
        assert!(supports_context_shift("qwen3.5:latest"));
        assert!(supports_context_shift("gpt-oss:20b"));
    }

    #[test]
    fn next_ctx_size_after_oom_halves_from_the_default_down_to_the_floor() {
        assert_eq!(next_ctx_size_after_oom(DEFAULT_CTX_SIZE), Some(131072));
        assert_eq!(next_ctx_size_after_oom(131072), Some(65536));
        assert_eq!(next_ctx_size_after_oom(65536), Some(32768));
        assert_eq!(next_ctx_size_after_oom(32768), Some(16384));
        // At (or below) the floor, no further shrink is offered.
        assert_eq!(next_ctx_size_after_oom(16384), None);
        assert_eq!(next_ctx_size_after_oom(8192), None);
    }

    #[test]
    fn default_ctx_size_reaches_the_floor_within_the_shrink_budget() {
        // 262144 -> 131072 -> 65536 -> 32768 -> 16384: exactly
        // MAX_CTX_SHRINK_ATTEMPTS halvings, so the floor is reachable.
        let mut ctx = DEFAULT_CTX_SIZE;
        let mut attempts = 0;
        while let Some(next) = next_ctx_size_after_oom(ctx) {
            ctx = next;
            attempts += 1;
        }
        assert_eq!(ctx, MIN_CTX_SIZE_FOR_RETRY);
        assert!(attempts <= MAX_CTX_SHRINK_ATTEMPTS);
    }

    #[test]
    fn looks_like_oom_matches_known_allocation_failure_phrasings() {
        for msg in [
            "ggml_backend_alloc_ctx_tensors_from_buft: failed to allocate CUDA0 buffer of size 123",
            "llama_kv_cache: failed to allocate buffer for kv cache",
            "CUDA error: out of memory",
            "terminate called after throwing an instance of 'std::bad_alloc'",
            "cudaMalloc failed: out of memory",
        ] {
            assert!(looks_like_oom(msg), "expected OOM match for {msg:?}");
        }
    }

    #[test]
    fn looks_like_oom_does_not_flag_unrelated_startup_failures() {
        for msg in [
            "error while loading shared libraries: libcuda.so.1: cannot open shared object file",
            "error loading model: unknown architecture 'not-a-real-arch'",
            "error: unknown argument: --not-a-real-flag",
        ] {
            assert!(!looks_like_oom(msg), "unexpected OOM match for {msg:?}");
        }
    }
}