zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//! The sandbox runtime (ZC-0018, zc#510): one [`Runtime`] trait every
//! workload this node runs for someone else goes through, and the budget
//! that sizes it.
//!
//! Named `sandbox`, not `runtime`, on purpose: `broker::deploy::runtime` is
//! the reconciler's own `ContainerRuntime` (pull, login, container IP,
//! published ports), a deploy-specific superset that builds its `docker run`
//! argv through this module's Docker backend ([`docker::run_argv`]) so the
//! limits cannot be left out there either.
//!
//! Backends:
//!
//! | kind | status |
//! |---|---|
//! | [`RuntimeKind::Docker`] | [`docker::DockerRuntime`], every container gets explicit `--cpus` / `--memory` (and `--gpus` when the budget allows a GPU) |
//! | [`RuntimeKind::Lima`] | macOS: [`lima::LimaRuntime`], one zc-owned Apple-Virtualization VM `zakuro` sized to the budget, containerd + nerdctl inside, only the work directory mounted |
//! | [`RuntimeKind::Colima`] | macOS: [`colima::ColimaRuntime`], the same contract on a zc-owned Colima profile `zakuro` (docker inside) |
//! | [`RuntimeKind::Lxc`] | Linux: [`lxc::LxcRuntime`], one unprivileged Incus container `zakuro-sandbox` sized to the budget (`limits.cpu`, `limits.memory`, root disk; GPU device only on opt-in) with containerd + nerdctl nested inside, each workload again under its own `--cpus` / `--memory` |
//! | [`RuntimeKind::Host`] | no isolation; the lab and an owner's own jobs only |
//!
//! [`Limits`] has no "unlimited" value: cpu and memory are plain numbers, not
//! `Option`s, so a start that forgets them does not compile.

pub mod colima;
pub mod docker;
pub mod engine;
pub mod ephemeral;
pub mod job;
pub mod lima;
pub mod lock;
pub mod lxc;

pub use lock::{admission_lock, AdmissionGuard};

use std::fmt;

/// Smallest `--memory` Docker accepts (6 MiB); a split below it is floored.
pub const MIN_MEMORY_BYTES: u64 = 6 * 1024 * 1024;
/// Smallest `--cpus` Docker accepts (0.01 CPU).
pub const MIN_CPU_MILLIS: u32 = 10;

const GIB: f64 = 1024.0 * 1024.0 * 1024.0;

/// GPU passthrough for one workload.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Gpus {
    /// No `--gpus` flag: the workload sees no GPU.
    #[default]
    None,
    /// `--gpus all`.
    All,
    /// `--gpus <n>`.
    Count(u32),
    /// `--gpus <value>` as given (`device=0`, `"device=0,1"`, ...), from
    /// `ZAKURO_DEPLOY_GPUS`.
    Spec(String),
}

impl Gpus {
    /// The `--gpus` value, `None` when no GPU is passed through.
    pub fn flag_value(&self) -> Option<String> {
        match self {
            Gpus::None | Gpus::Count(0) => None,
            Gpus::All => Some("all".into()),
            Gpus::Count(n) => Some(n.to_string()),
            Gpus::Spec(s) => Some(s.clone()),
        }
    }
}

/// The resource ceiling one workload runs under. Always concrete: there is
/// no unlimited value to fall back to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Limits {
    /// CPU in thousandths of a core (`--cpus 1.5` = 1500). Integer so the
    /// flag is exact and the type is `Eq`.
    pub cpu_millis: u32,
    /// Memory in bytes (`--memory`).
    pub memory_bytes: u64,
    pub gpus: Gpus,
}

impl Limits {
    /// `cpus` cores and `memory_gib` GiB, no GPU. Floors at what Docker
    /// accepts.
    pub fn new(cpus: f64, memory_gib: f64, gpus: Gpus) -> Self {
        Self {
            cpu_millis: ((cpus * 1000.0).round().max(0.0) as u32).max(MIN_CPU_MILLIS),
            memory_bytes: ((memory_gib * GIB).round().max(0.0) as u64).max(MIN_MEMORY_BYTES),
            gpus,
        }
    }

    pub fn cpus(&self) -> f64 {
        self.cpu_millis as f64 / 1000.0
    }

    /// `--cpus` value: `2`, `0.5`, `1.25` (no trailing zeros).
    pub fn cpus_flag(&self) -> String {
        cpu_millis_flag(self.cpu_millis)
    }

    /// `--memory` value in MiB (Docker wants an integer with a suffix).
    pub fn memory_flag(&self) -> String {
        format!("{}m", (self.memory_bytes / (1024 * 1024)).max(6))
    }

    /// One of `n` equal shares of this limit (share workers split the
    /// budget between their slots, so their sum never exceeds it). The GPU
    /// setting is not divided: a GPU is passed through or it is not.
    pub fn split(&self, n: u32) -> Limits {
        let n = n.max(1);
        Limits {
            cpu_millis: (self.cpu_millis / n).max(MIN_CPU_MILLIS),
            memory_bytes: (self.memory_bytes / n as u64).max(MIN_MEMORY_BYTES),
            gpus: self.gpus.clone(),
        }
    }

    /// A workload's own request, clamped to this (the node budget). A
    /// missing (zero) cpu or memory request takes the whole budget. GPUs are
    /// only ever granted from what the budget has: a budget with no GPU
    /// grants none whatever the request says; `all` grants the requested
    /// count; a count grants at most that many; a device pin
    /// (`ZAKURO_DEPLOY_GPUS=device=0`) is kept as is, never replaced by a
    /// count. No GPU request (or zero) takes the budget's setting.
    pub fn clamp_request(&self, req: &Request) -> Limits {
        let cpu_millis = if req.cpus > 0.0 {
            ((req.cpus * 1000.0).round() as u32)
                .clamp(MIN_CPU_MILLIS, self.cpu_millis.max(MIN_CPU_MILLIS))
        } else {
            self.cpu_millis
        };
        let memory_bytes = if req.memory_gib > 0.0 {
            ((req.memory_gib * GIB).round() as u64)
                .clamp(MIN_MEMORY_BYTES, self.memory_bytes.max(MIN_MEMORY_BYTES))
        } else {
            self.memory_bytes
        };
        let gpus = match (req.gpus.filter(|n| *n > 0), &self.gpus) {
            (_, Gpus::None) => Gpus::None,
            (None, budget) => budget.clone(),
            (Some(n), Gpus::All) => Gpus::Count(n),
            (Some(n), Gpus::Count(m)) => Gpus::Count(n.min(*m)),
            (Some(_), pinned @ Gpus::Spec(_)) => pinned.clone(),
        };
        Limits {
            cpu_millis,
            memory_bytes,
            gpus,
        }
    }
}

impl fmt::Display for Limits {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} cpu, {:.1} GiB memory, gpu {}",
            self.cpus_flag(),
            self.memory_bytes as f64 / GIB,
            self.gpus.flag_value().unwrap_or_else(|| "off".into())
        )
    }
}

/// The label every container started through [`docker::run_argv`] carries:
/// its own cpu and memory limits (`<cpu_millis>m,<memory_bytes>`). The
/// node-wide sum is read back from the workloads actually running (zc#565),
/// so a stopped, crashed or removed workload releases its share by no longer
/// being listed, and a restarted broker or agent rebuilds the sum from the
/// daemon instead of from a ledger it could have lost or leaked.
pub const BUDGET_LABEL: &str = "zakuro.budget";

impl Limits {
    /// The [`BUDGET_LABEL`] value for these limits.
    pub fn budget_label(&self) -> String {
        format!("{}m,{}", self.cpu_millis, self.memory_bytes)
    }
}

/// One running workload's share of the node budget, as listed by the
/// backend from [`BUDGET_LABEL`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Allocation {
    /// The workload's name (the container name for Docker).
    pub name: String,
    pub cpu_millis: u32,
    pub memory_bytes: u64,
}

impl Allocation {
    /// Parse a [`BUDGET_LABEL`] value; `None` when it is not one.
    pub fn from_label(name: &str, label: &str) -> Option<Self> {
        let (cpu, mem) = label.trim().split_once(',')?;
        Some(Self {
            name: name.to_string(),
            cpu_millis: cpu.trim().strip_suffix('m')?.parse().ok()?,
            memory_bytes: mem.trim().parse().ok()?,
        })
    }
}

/// What is left of `budget` once `running` is subtracted: `(cpu_millis,
/// memory_bytes)`, never below zero.
pub fn remaining(budget: &Limits, running: &[Allocation]) -> (u32, u64) {
    let cpu: u64 = running.iter().map(|a| a.cpu_millis as u64).sum();
    let mem: u64 = running.iter().map(|a| a.memory_bytes).sum();
    (
        (budget.cpu_millis as u64).saturating_sub(cpu) as u32,
        budget.memory_bytes.saturating_sub(mem),
    )
}

/// Admission against the node budget (ZC-0018 §2): `Ok` when starting a
/// workload under `want` keeps the sum of every running workload's limits
/// (`running`) within `budget`, else the reason, which the caller reports as
/// `budget`. Only cpu and memory are summed: a GPU is passed through or not
/// (the budget's own GPU setting already bounds what any workload gets).
pub fn admit(budget: &Limits, running: &[Allocation], want: &Limits) -> Result<(), String> {
    let (cpu_left, mem_left) = remaining(budget, running);
    let mib = |b: u64| b / (1024 * 1024);
    let mut short = Vec::new();
    if want.cpu_millis > cpu_left {
        short.push(format!(
            "cpu: asks {} of the {} left",
            want.cpus_flag(),
            cpu_millis_flag(cpu_left)
        ));
    }
    if want.memory_bytes > mem_left {
        short.push(format!(
            "memory: asks {} MiB of the {} MiB left",
            mib(want.memory_bytes),
            mib(mem_left)
        ));
    }
    if short.is_empty() {
        return Ok(());
    }
    Err(format!(
        "node budget exhausted ({}; {} running workload(s) hold {} of {} cpu and {} of {} MiB)",
        short.join(", "),
        running.len(),
        cpu_millis_flag(budget.cpu_millis - cpu_left),
        budget.cpus_flag(),
        mib(budget.memory_bytes - mem_left),
        mib(budget.memory_bytes),
    ))
}

/// A Space lease's limits: its request clamped to `budget`
/// ([`Limits::clamp_request`]), except that a cpu or memory it leaves unset
/// takes what `running` leaves of the budget rather than all of it, so an
/// unsized lease still fits beside what already runs. [`admit`] then refuses
/// it when a requested amount does not fit, or nothing is left.
pub fn lease_limits(budget: &Limits, running: &[Allocation], req: &Request) -> Limits {
    let (cpu_left, mem_left) = remaining(budget, running);
    let mut l = budget.clamp_request(req);
    if req.cpus <= 0.0 {
        l.cpu_millis = cpu_left.max(MIN_CPU_MILLIS);
    }
    if req.memory_gib <= 0.0 {
        l.memory_bytes = mem_left.max(MIN_MEMORY_BYTES);
    }
    l
}

/// The default share of the node budget one deployment is sized to when it
/// carries no resource request of its own (the hub sends none yet): a
/// quarter, so four deployments fit side by side.
pub const DEFAULT_DEPLOY_SLICE_PERCENT: f64 = 25.0;

/// One deployment's limits: `ZAKURO_DEPLOY_BUDGET_SLICE` (a percentage of
/// the node budget, default [`DEFAULT_DEPLOY_SLICE_PERCENT`]) of `budget`.
/// The GPU setting is not divided. An invalid value is an error.
pub fn deployment_limits(
    budget: &Limits,
    get: &dyn Fn(&str) -> Option<String>,
) -> Result<Limits, String> {
    let pct = match get("ZAKURO_DEPLOY_BUDGET_SLICE")
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
    {
        None => DEFAULT_DEPLOY_SLICE_PERCENT,
        Some(v) => match parse_percent(&v) {
            Some(Ok(Amount::Percent(p))) => p,
            _ => {
                return Err(format!(
                    "ZAKURO_DEPLOY_BUDGET_SLICE={v:?} is not a percentage in (0, 100]"
                ))
            }
        },
    };
    Ok(Limits {
        cpu_millis: ((budget.cpu_millis as f64 * pct / 100.0) as u32).max(MIN_CPU_MILLIS),
        memory_bytes: ((budget.memory_bytes as f64 * pct / 100.0) as u64).max(MIN_MEMORY_BYTES),
        gpus: budget.gpus.clone(),
    })
}

/// `millis` thousandths of a core as `2`, `0.5`, `1.25` (no trailing zeros).
fn cpu_millis_flag(millis: u32) -> String {
    let whole = millis / 1000;
    let frac = millis % 1000;
    if frac == 0 {
        whole.to_string()
    } else {
        let f = format!("{frac:03}");
        format!("{whole}.{}", f.trim_end_matches('0'))
    }
}

/// What a workload asked for (a deployment's or a Space lease's
/// requirements). Zero means "not specified".
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Request {
    pub cpus: f64,
    pub memory_gib: f64,
    pub gpus: Option<u32>,
}

/// An amount of a host resource: absolute, or a percentage of the host.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Amount {
    /// Cores for cpu, bytes for memory.
    Absolute(f64),
    Percent(f64),
}

impl Amount {
    fn of(&self, host_total: f64) -> f64 {
        match *self {
            Amount::Absolute(v) => v.min(host_total),
            Amount::Percent(p) => host_total * p / 100.0,
        }
    }

    fn describe(&self, unit: &str) -> String {
        match *self {
            Amount::Percent(p) => format!("{p}%"),
            Amount::Absolute(v) if unit == "bytes" => format!("{:.1} GiB", v / GIB),
            Amount::Absolute(v) => format!("{v} {unit}"),
        }
    }
}

/// What this node lends (ZC-0017 `[budget]`, semantics in ZC-0018).
/// `policy.toml` (zc#514) is the setting; these variables are deprecated and
/// still win over it when set:
///
/// - `ZAKURO_BUDGET_CPU`: cores (`2`, `1.5`) or a percentage (`50%`); default `50%`;
/// - `ZAKURO_BUDGET_MEMORY`: a size (`8g`, `512m`, bytes) or a percentage; default `50%`;
/// - `ZAKURO_BUDGET_GPU`: `1`/`true`/`yes` to pass GPUs through; default off,
///   except that a node with `ZAKURO_DEPLOY_GPUS` set (the staging GPU fleet)
///   keeps passing exactly that value;
/// - `ZAKURO_BUDGET_DISK`: a size (`20g`, at least 1 GiB); default 20 GiB.
///   The root disk of the LXC sandbox (a percentage is refused: the pool
///   size is not known).
#[derive(Debug, Clone, PartialEq)]
pub struct Budget {
    pub cpu: Amount,
    pub memory: Amount,
    pub gpu: Gpus,
    pub disk_bytes: u64,
}

impl Default for Budget {
    fn default() -> Self {
        Self {
            cpu: Amount::Percent(50.0),
            memory: Amount::Percent(50.0),
            gpu: Gpus::None,
            disk_bytes: lxc::DEFAULT_DISK_BYTES,
        }
    }
}

fn parse_percent(v: &str) -> Option<Result<Amount, String>> {
    let p = v.strip_suffix('%')?;
    Some(match p.trim().parse::<f64>() {
        Ok(p) if p > 0.0 && p <= 100.0 => Ok(Amount::Percent(p)),
        _ => Err(format!("{v:?} is not a percentage in (0, 100]")),
    })
}

/// `2`, `1.5` or `50%`.
pub fn parse_cpu(v: &str) -> Result<Amount, String> {
    let v = v.trim();
    if let Some(p) = parse_percent(v) {
        return p;
    }
    match v.parse::<f64>() {
        Ok(c) if c > 0.0 && c.is_finite() => Ok(Amount::Absolute(c)),
        _ => Err(format!("{v:?} is not a cpu count or a percentage")),
    }
}

/// `8g`, `8GiB`, `512m`, `1073741824` or `50%`.
pub fn parse_memory(v: &str) -> Result<Amount, String> {
    let v = v.trim();
    if let Some(p) = parse_percent(v) {
        return p;
    }
    let low = v.to_ascii_lowercase();
    let digits_end = low
        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
        .unwrap_or(low.len());
    let (num, unit) = low.split_at(digits_end);
    let mult: f64 = match unit.trim() {
        "" | "b" => 1.0,
        "k" | "kb" | "kib" => 1024.0,
        "m" | "mb" | "mib" => 1024.0 * 1024.0,
        "g" | "gb" | "gib" => GIB,
        "t" | "tb" | "tib" => GIB * 1024.0,
        _ => return Err(format!("{v:?} is not a memory size or a percentage")),
    };
    match num.parse::<f64>() {
        Ok(n) if n > 0.0 && n.is_finite() => Ok(Amount::Absolute(n * mult)),
        _ => Err(format!("{v:?} is not a memory size or a percentage")),
    }
}

impl Budget {
    /// The budget from `get` (an environment lookup). An invalid value is an
    /// error, never a silent default: the owner asked for something specific.
    pub fn from_env(get: &dyn Fn(&str) -> Option<String>) -> Result<Self, String> {
        Self::from_env_over(Budget::default(), get)
    }

    /// [`from_env`](Self::from_env) over `base` instead of the built-in
    /// defaults: `policy.toml`'s `[budget]` is the base, and the (deprecated)
    /// variables still win when set.
    pub fn from_env_over(
        base: Budget,
        get: &dyn Fn(&str) -> Option<String>,
    ) -> Result<Self, String> {
        let val = |k: &str| {
            get(k)
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        };
        let mut b = base;
        if let Some(v) = val("ZAKURO_BUDGET_CPU") {
            b.cpu = parse_cpu(&v).map_err(|e| format!("ZAKURO_BUDGET_CPU={e}"))?;
        }
        if let Some(v) = val("ZAKURO_BUDGET_MEMORY") {
            b.memory = parse_memory(&v).map_err(|e| format!("ZAKURO_BUDGET_MEMORY={e}"))?;
        }
        if let Some(v) = val("ZAKURO_BUDGET_DISK") {
            b.disk_bytes = match parse_memory(&v) {
                Ok(Amount::Absolute(n)) if n >= GIB => n as u64,
                Ok(Amount::Absolute(_)) => {
                    return Err(format!(
                        "ZAKURO_BUDGET_DISK={v:?} is below the 1 GiB minimum for the sandbox disk"
                    ))
                }
                Ok(Amount::Percent(_)) => {
                    return Err(format!(
                        "ZAKURO_BUDGET_DISK={v:?}: give a size such as 20g, not a percentage"
                    ))
                }
                Err(e) => return Err(format!("ZAKURO_BUDGET_DISK={e}")),
            };
        }
        let deploy_gpus = val("ZAKURO_DEPLOY_GPUS");
        b.gpu = match val("ZAKURO_BUDGET_GPU").map(|v| v.to_ascii_lowercase()) {
            Some(v) if matches!(v.as_str(), "1" | "true" | "yes" | "on") => {
                deploy_gpus.map(Gpus::Spec).unwrap_or(Gpus::All)
            }
            Some(v) if matches!(v.as_str(), "0" | "false" | "no" | "off") => Gpus::None,
            Some(v) => return Err(format!("ZAKURO_BUDGET_GPU={v:?} is not a boolean")),
            None => deploy_gpus.map(Gpus::Spec).unwrap_or(b.gpu),
        };
        Ok(b)
    }

    /// The whole budget as one [`Limits`] on a host of `host`'s size. `Err`
    /// when a percentage cannot be resolved (memory size unknown on this
    /// OS): the caller refuses the start rather than running unlimited.
    pub fn total(&self, host: &HostResources) -> Result<Limits, String> {
        let cpus = self.cpu.of(host.logical_cpus.max(1) as f64);
        let memory_bytes = match (self.memory, host.memory_bytes) {
            (Amount::Absolute(b), Some(total)) => b.min(total as f64),
            (Amount::Absolute(b), None) => b,
            (Amount::Percent(_), Some(total)) => self.memory.of(total as f64),
            (Amount::Percent(p), None) => {
                return Err(format!(
                    "cannot size the memory budget ({p}% of an unknown total): \
                     set ZAKURO_BUDGET_MEMORY to an absolute size such as 4g"
                ))
            }
        };
        Ok(Limits::new(cpus, memory_bytes / GIB, self.gpu.clone()))
    }

    /// One line for `zc doctor`.
    pub fn describe(&self, host: &HostResources) -> String {
        let host_mem = host
            .memory_bytes
            .map(|b| format!("{:.1} GiB", b as f64 / GIB))
            .unwrap_or_else(|| "unknown".into());
        format!(
            "cpu {} of {} logical, memory {} of {host_mem}, gpu {}, disk {:.1} GiB",
            self.cpu.describe("cores"),
            host.logical_cpus,
            self.memory.describe("bytes"),
            self.gpu.flag_value().unwrap_or_else(|| "off".into()),
            self.disk_bytes as f64 / GIB,
        )
    }
}

/// The size of this host, which percentages in the [`Budget`] refer to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostResources {
    pub logical_cpus: usize,
    /// `None` where it cannot be read (not Linux or macOS).
    pub memory_bytes: Option<u64>,
}

impl HostResources {
    pub fn detect() -> Self {
        Self {
            logical_cpus: std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1),
            memory_bytes: crate::setup::total_memory(),
        }
    }
}

/// The node budget from the process environment, as one [`Limits`].
pub fn node_limits() -> Result<Limits, String> {
    node_limits_from(&|k| std::env::var(k).ok())
}

/// The effective node budget: `[budget]` of `policy.toml`, then the
/// deprecated `ZAKURO_BUDGET_*` variables over it.
pub fn node_budget_from(get: &dyn Fn(&str) -> Option<String>) -> Result<Budget, String> {
    crate::policy::node_budget(crate::credentials::dir().as_deref(), get)
}

/// [`node_limits`] with the environment injected.
pub fn node_limits_from(get: &dyn Fn(&str) -> Option<String>) -> Result<Limits, String> {
    node_budget_from(get)?.total(&HostResources::detect())
}

/// The runtime backends (ZC-0018 table).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeKind {
    Lima,
    Colima,
    Lxc,
    Docker,
    Host,
}

impl RuntimeKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            RuntimeKind::Lima => "lima",
            RuntimeKind::Colima => "colima",
            RuntimeKind::Lxc => "lxc",
            RuntimeKind::Docker => "docker",
            RuntimeKind::Host => "host",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "lima" => Some(Self::Lima),
            "colima" => Some(Self::Colima),
            "lxc" | "incus" | "lxd" => Some(Self::Lxc),
            "docker" => Some(Self::Docker),
            "host" => Some(Self::Host),
            _ => None,
        }
    }
}

/// Whether a backend can be used here, and why not.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Probe {
    pub kind: RuntimeKind,
    pub available: bool,
    pub detail: String,
}

/// What a container-like workload starts from. Backend-neutral: Docker maps
/// it onto `docker run`; Lima/LXC (zc#511/#512) onto nerdctl inside their
/// boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartSpec {
    pub name: String,
    pub image: String,
    /// Network to join; `None` is the backend's default.
    pub network: Option<String>,
    /// Create `network` first (idempotently) when true.
    pub create_network: bool,
    pub labels: Vec<(String, String)>,
    /// `(host_path, container_path)`.
    pub mounts: Vec<(String, String)>,
    /// Raw publish specs (`127.0.0.1:3960:3960`, `127.0.0.1::8888`).
    pub publish: Vec<String>,
    pub env: Vec<(String, String)>,
    /// Overrides the image's command when non-empty.
    pub cmd: Vec<String>,
    /// Required: there is no unlimited start.
    pub limits: Limits,
    /// Removed when it exits (`--rm`).
    pub remove_on_exit: bool,
    /// Untrusted workload: pid cap and no-new-privileges.
    pub hardened: bool,
}

/// Run state of one workload, as the backend reports it.
pub(crate) use crate::up::ContainerState as State;

/// One sandbox backend (ZC-0018). Every method is by workload name, the
/// backend's stable identity for it. `pause`/`resume` arrive with the Lima
/// and LXC backends, where the boundary itself can be suspended.
pub trait Runtime: Send + Sync {
    fn kind(&self) -> RuntimeKind;
    /// Can this backend be used on this host now, and if not, why.
    fn probe(&self) -> Probe;
    /// Check `image` before any start: present locally and, when
    /// `expected_digest` is given (the hub-supplied one), matching it.
    fn verify_image(&self, image: &str, expected_digest: Option<&str>) -> Result<(), String>;
    /// Start a workload under `spec.limits`; returns the backend's id.
    fn start(&self, spec: &StartSpec) -> Result<String, String>;
    /// Run `argv` inside a running workload (`detach`: don't wait).
    fn exec(&self, name: &str, argv: &[String], detach: bool) -> Result<String, String>;
    /// Stop and remove the workload. Idempotent.
    fn stop(&self, name: &str) -> Result<(), String>;
    /// The limits the backend actually applied, read back from it.
    fn limits(&self, name: &str) -> Result<Limits, String>;
    /// Run state of the workload.
    fn health(&self, name: &str) -> Result<State, String>;
    /// Every running workload's share of the node budget (zc#565), read
    /// from the backend so the sum never outlives what actually runs. A
    /// boundary backend (Lima, LXC) is sized to the budget as a whole, so
    /// there is nothing to sum outside it: the default lists nothing.
    fn allocations(&self) -> Result<Vec<Allocation>, String> {
        Ok(Vec::new())
    }
}

/// The preference order: `ZAKURO_RUNTIME_PREFER` (comma list) when set,
/// else `lima, docker` on macOS and `lxc, docker` elsewhere (ZC-0018). `host`
/// is always the last resort and is never part of the preference.
pub fn preference(get: &dyn Fn(&str) -> Option<String>, macos: bool) -> Vec<RuntimeKind> {
    if let Some(v) = get("ZAKURO_RUNTIME_PREFER").filter(|v| !v.trim().is_empty()) {
        let list: Vec<RuntimeKind> = v
            .split(',')
            .filter_map(RuntimeKind::parse)
            .filter(|k| *k != RuntimeKind::Host)
            .collect();
        if !list.is_empty() {
            return list;
        }
    }
    if macos {
        vec![RuntimeKind::Lima, RuntimeKind::Colima, RuntimeKind::Docker]
    } else {
        vec![RuntimeKind::Lxc, RuntimeKind::Docker]
    }
}

/// Which backend to use: the first in `prefer` whose probe passes, with the
/// probe of every backend tried (the reasons for the fallback). `None` means
/// only the host process is left.
pub fn select(prefer: &[RuntimeKind], probe: &dyn Fn(RuntimeKind) -> Probe) -> Selection {
    let mut tried = Vec::new();
    for &k in prefer {
        let p = probe(k);
        let ok = p.available;
        tried.push(p);
        if ok {
            return Selection {
                chosen: Some(k),
                tried,
            };
        }
    }
    Selection {
        chosen: None,
        tried,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selection {
    pub chosen: Option<RuntimeKind>,
    pub tried: Vec<Probe>,
}

/// The probe for a backend that is not built yet (Lima) or not applicable
/// on this OS (LXC off Linux).
pub fn unimplemented_probe(kind: RuntimeKind, macos: bool) -> Probe {
    let detail = match kind {
        RuntimeKind::Lima | RuntimeKind::Colima if !macos => "macOS only".to_string(),
        RuntimeKind::Lima | RuntimeKind::Colima => "not probed".to_string(),
        RuntimeKind::Lxc => "Linux only".to_string(),
        RuntimeKind::Docker => "not probed".to_string(),
        RuntimeKind::Host => "no isolation".to_string(),
    };
    Probe {
        kind,
        available: false,
        detail,
    }
}

/// The `zc doctor` sandbox section: the selected backend, why each
/// preferred one before it was skipped, and the budget it will enforce.
pub fn doctor_report(
    sel: &Selection,
    budget: Result<&Budget, &String>,
    host: &HostResources,
) -> String {
    let chosen = sel
        .chosen
        .map(|k| k.as_str())
        .unwrap_or("host (no isolation)");
    let mut out = format!("sandbox runtime: {chosen}");
    for p in &sel.tried {
        let mark = if p.available { "OK" } else { "skipped" };
        out.push_str(&format!(
            "\n  {:<7} {mark}: {}",
            format!("{}:", p.kind.as_str()),
            p.detail
        ));
    }
    if sel.chosen.is_none() {
        out.push_str(
            "\n  fallback: workers run as host processes, with no cpu/memory cap; \
             install Incus or start Docker (or set ZAKURO_RUNTIME_PREFER) to enforce the budget",
        );
    }
    match budget {
        Ok(b) => {
            out.push_str(&format!("\n  budget:  {}", b.describe(host)));
            match b.total(host) {
                Ok(l) => out.push_str(&format!(
                    "\n  limits:  {l} per node (split across share workers)"
                )),
                Err(e) => out.push_str(&format!("\n  limits:  UNRESOLVED: {e}")),
            }
        }
        Err(e) => out.push_str(&format!("\n  budget:  INVALID: {e}")),
    }
    out
}

/// The `zc doctor` line for what the running workloads hold of `budget`
/// and what is left for the next start (zc#565).
pub fn allocation_line(budget: &Limits, running: &[Allocation]) -> String {
    let (cpu_left, mem_left) = remaining(budget, running);
    format!(
        "  allocated: {} of {} cpu, {:.1} of {:.1} GiB memory across {} workload(s); left {} cpu, {:.1} GiB",
        cpu_millis_flag(budget.cpu_millis - cpu_left),
        budget.cpus_flag(),
        (budget.memory_bytes - mem_left) as f64 / GIB,
        budget.memory_bytes as f64 / GIB,
        running.len(),
        cpu_millis_flag(cpu_left),
        mem_left as f64 / GIB,
    )
}

/// Probe this host for `zc doctor`: Docker through the deploy reconciler's
/// own `docker version` probe (same reasons, same next step), Incus through
/// [`lxc::LxcRuntime`]'s probe on Linux, Lima as not implemented yet.
pub fn probe_host() -> Selection {
    let macos = cfg!(target_os = "macos");
    let prefer = preference(&|k| std::env::var(k).ok(), macos);
    select(&prefer, &|k| match k {
        RuntimeKind::Docker => {
            let p = crate::broker::deploy::runtime_probe();
            let detail = match p.next_step() {
                Some(step) => format!("{} ({step})", p.detail),
                None => p.detail.clone(),
            };
            Probe {
                kind: k,
                available: p.available,
                detail,
            }
        }
        RuntimeKind::Lxc if cfg!(target_os = "linux") => lxc::LxcRuntime::shell().probe(),
        RuntimeKind::Lima if macos => lima::LimaRuntime::shell().probe(),
        RuntimeKind::Colima if macos => colima::ColimaRuntime::shell().probe(),
        other => unimplemented_probe(other, macos),
    })
}

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

    fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |k| {
            pairs
                .iter()
                .find(|(ek, _)| *ek == k)
                .map(|(_, v)| v.to_string())
        }
    }

    const HOST: HostResources = HostResources {
        logical_cpus: 8,
        memory_bytes: Some(16 * 1024 * 1024 * 1024),
    };

    #[test]
    fn the_default_budget_is_half_the_host_and_no_gpu() {
        let b = Budget::from_env(&env(&[])).unwrap();
        assert_eq!(b, Budget::default());
        let l = b.total(&HOST).unwrap();
        assert_eq!(l.cpus_flag(), "4");
        assert_eq!(l.memory_flag(), "8192m");
        assert_eq!(l.gpus, Gpus::None);
    }

    #[test]
    fn absolute_and_percent_budgets_parse() {
        let b = Budget::from_env(&env(&[
            ("ZAKURO_BUDGET_CPU", "1.5"),
            ("ZAKURO_BUDGET_MEMORY", "512m"),
            ("ZAKURO_BUDGET_GPU", "yes"),
        ]))
        .unwrap();
        let l = b.total(&HOST).unwrap();
        assert_eq!(l.cpus_flag(), "1.5");
        assert_eq!(l.memory_flag(), "512m");
        assert_eq!(l.gpus, Gpus::All);
        assert_eq!(b.disk_bytes, lxc::DEFAULT_DISK_BYTES);
        let d = Budget::from_env(&env(&[("ZAKURO_BUDGET_DISK", "40g")])).unwrap();
        assert_eq!(d.disk_bytes, 40 << 30);
        assert!(
            d.describe(&HOST).ends_with("disk 40.0 GiB"),
            "{}",
            d.describe(&HOST)
        );
        let p = Budget::from_env(&env(&[
            ("ZAKURO_BUDGET_CPU", "25%"),
            ("ZAKURO_BUDGET_MEMORY", "25%"),
        ]))
        .unwrap()
        .total(&HOST)
        .unwrap();
        assert_eq!(
            (p.cpus_flag(), p.memory_flag()),
            ("2".into(), "4096m".into())
        );
    }

    #[test]
    fn a_budget_never_exceeds_the_host() {
        let l = Budget::from_env(&env(&[
            ("ZAKURO_BUDGET_CPU", "64"),
            ("ZAKURO_BUDGET_MEMORY", "1t"),
        ]))
        .unwrap()
        .total(&HOST)
        .unwrap();
        assert_eq!(
            (l.cpus_flag(), l.memory_flag()),
            ("8".into(), "16384m".into())
        );
    }

    #[test]
    fn an_invalid_budget_is_an_error_not_a_default() {
        for (k, v) in [
            ("ZAKURO_BUDGET_CPU", "lots"),
            ("ZAKURO_BUDGET_CPU", "150%"),
            ("ZAKURO_BUDGET_MEMORY", "8 parsecs"),
            ("ZAKURO_BUDGET_MEMORY", "-1g"),
            ("ZAKURO_BUDGET_GPU", "maybe"),
            ("ZAKURO_BUDGET_DISK", "50%"),
            ("ZAKURO_BUDGET_DISK", "big"),
            ("ZAKURO_BUDGET_DISK", "100m"),
        ] {
            let e = Budget::from_env(&move |q: &str| (q == k).then(|| v.to_string()));
            assert!(e.unwrap_err().starts_with(k), "{k}={v}");
        }
    }

    #[test]
    fn deploy_gpus_keeps_the_gpu_fleet_passing_its_value() {
        let b = Budget::from_env(&env(&[("ZAKURO_DEPLOY_GPUS", "device=0")])).unwrap();
        assert_eq!(b.gpu, Gpus::Spec("device=0".into()));
        let off = Budget::from_env(&env(&[
            ("ZAKURO_DEPLOY_GPUS", "all"),
            ("ZAKURO_BUDGET_GPU", "0"),
        ]))
        .unwrap();
        assert_eq!(off.gpu, Gpus::None);
    }

    #[test]
    fn an_unknown_host_memory_refuses_a_percentage_but_not_a_size() {
        let host = HostResources {
            logical_cpus: 4,
            memory_bytes: None,
        };
        assert!(Budget::default().total(&host).is_err());
        let b = Budget::from_env(&env(&[("ZAKURO_BUDGET_MEMORY", "2g")])).unwrap();
        assert_eq!(b.total(&host).unwrap().memory_flag(), "2048m");
    }

    #[test]
    fn splitting_the_budget_never_sums_past_it() {
        let total = Limits::new(3.0, 6.0, Gpus::All);
        let one = total.split(4);
        assert_eq!(one.cpus_flag(), "0.75");
        assert_eq!(one.memory_flag(), "1536m");
        assert_eq!(one.gpus, Gpus::All);
        assert!(one.cpu_millis * 4 <= total.cpu_millis);
        // Never below what docker accepts.
        let tiny = Limits::new(0.01, 0.0, Gpus::None).split(100);
        assert_eq!(tiny.cpu_millis, MIN_CPU_MILLIS);
        assert_eq!(tiny.memory_bytes, MIN_MEMORY_BYTES);
        assert_eq!(total.split(0), total);
    }

    #[test]
    fn a_request_is_clamped_to_the_budget_and_a_missing_one_takes_it_all() {
        let budget = Limits::new(2.0, 4.0, Gpus::None);
        let big = budget.clamp_request(&Request {
            cpus: 16.0,
            memory_gib: 64.0,
            gpus: None,
        });
        assert_eq!(big, budget);
        let small = budget.clamp_request(&Request {
            cpus: 0.5,
            memory_gib: 1.0,
            gpus: None,
        });
        assert_eq!(
            (small.cpus_flag(), small.memory_flag(), small.gpus),
            ("0.5".into(), "1024m".into(), Gpus::None)
        );
        assert_eq!(budget.clamp_request(&Request::default()), budget);
    }

    #[test]
    fn a_gpu_request_is_granted_only_from_the_budget() {
        let with = |gpus: Gpus| Limits::new(2.0, 4.0, gpus);
        let ask = |n: u32| Request {
            gpus: Some(n),
            ..Request::default()
        };
        // No GPU in the budget (the default): none, whatever is asked.
        assert_eq!(with(Gpus::None).clamp_request(&ask(8)).gpus, Gpus::None);
        // `all`: the requested count.
        assert_eq!(with(Gpus::All).clamp_request(&ask(2)).gpus, Gpus::Count(2));
        // A count: at most that many.
        assert_eq!(
            with(Gpus::Count(1)).clamp_request(&ask(8)).gpus,
            Gpus::Count(1)
        );
        assert_eq!(
            with(Gpus::Count(4)).clamp_request(&ask(2)).gpus,
            Gpus::Count(2)
        );
        // A device pin is never replaced by a count.
        let pin = Gpus::Spec("device=0".into());
        assert_eq!(with(pin.clone()).clamp_request(&ask(2)).gpus, pin);
        // No request (or zero): the budget's own setting.
        for b in [Gpus::None, Gpus::All, Gpus::Count(3), pin.clone()] {
            assert_eq!(with(b.clone()).clamp_request(&ask(0)).gpus, b);
            assert_eq!(with(b.clone()).clamp_request(&Request::default()).gpus, b);
        }
    }

    #[test]
    fn the_preference_follows_the_os_and_the_override() {
        let none = env(&[]);
        assert_eq!(
            preference(&none, true),
            vec![RuntimeKind::Lima, RuntimeKind::Colima, RuntimeKind::Docker]
        );
        let colima = env(&[("ZAKURO_RUNTIME_PREFER", "colima, docker")]);
        assert_eq!(
            preference(&colima, true),
            vec![RuntimeKind::Colima, RuntimeKind::Docker]
        );
        assert_eq!(RuntimeKind::Colima.as_str(), "colima");
        assert_eq!(
            preference(&none, false),
            vec![RuntimeKind::Lxc, RuntimeKind::Docker]
        );
        let docker_only = env(&[("ZAKURO_RUNTIME_PREFER", "docker, host")]);
        assert_eq!(preference(&docker_only, false), vec![RuntimeKind::Docker]);
        let junk = env(&[("ZAKURO_RUNTIME_PREFER", "podman")]);
        assert_eq!(
            preference(&junk, false),
            vec![RuntimeKind::Lxc, RuntimeKind::Docker]
        );
    }

    #[test]
    fn selection_falls_back_and_keeps_every_reason() {
        let probe = |k: RuntimeKind| match k {
            RuntimeKind::Docker => Probe {
                kind: k,
                available: true,
                detail: "docker daemon responding".into(),
            },
            k => Probe {
                kind: k,
                available: false,
                detail: "incus is not installed".into(),
            },
        };
        let sel = select(&[RuntimeKind::Lxc, RuntimeKind::Docker], &probe);
        assert_eq!(sel.chosen, Some(RuntimeKind::Docker));
        assert_eq!(sel.tried.len(), 2);
        let report = doctor_report(&sel, Ok(&Budget::default()), &HOST);
        assert!(report.starts_with("sandbox runtime: docker"), "{report}");
        assert!(
            report.contains("lxc:    skipped: incus is not installed"),
            "{report}"
        );
        assert!(
            report.contains("docker: OK: docker daemon responding"),
            "{report}"
        );
        assert!(
            report.contains("limits:  4 cpu, 8.0 GiB memory, gpu off"),
            "{report}"
        );

        let down = |k: RuntimeKind| Probe {
            kind: k,
            available: false,
            detail: "docker daemon is not responding".into(),
        };
        let sel = select(&[RuntimeKind::Docker], &down);
        assert_eq!(sel.chosen, None);
        let report = doctor_report(&sel, Err(&"ZAKURO_BUDGET_CPU=bad".to_string()), &HOST);
        assert!(
            report.contains("fallback: workers run as host processes"),
            "{report}"
        );
        assert!(
            report.contains("budget:  INVALID: ZAKURO_BUDGET_CPU=bad"),
            "{report}"
        );
    }

    fn alloc(name: &str, cpus: f64, gib: f64) -> Allocation {
        let l = Limits::new(cpus, gib, Gpus::None);
        Allocation::from_label(name, &l.budget_label()).unwrap()
    }

    #[test]
    fn the_budget_label_round_trips() {
        let l = Limits::new(1.5, 2.0, Gpus::All);
        assert_eq!(l.budget_label(), "1500m,2147483648");
        assert_eq!(
            Allocation::from_label("w", &l.budget_label()),
            Some(Allocation {
                name: "w".into(),
                cpu_millis: 1500,
                memory_bytes: 2 << 30,
            })
        );
        for junk in ["", "1500,2", "m,2", "1500m", "1500m,lots"] {
            assert_eq!(Allocation::from_label("w", junk), None, "{junk:?}");
        }
    }

    #[test]
    fn admission_refuses_a_start_past_the_sum_of_what_runs() {
        let budget = Limits::new(4.0, 8.0, Gpus::None);
        let running = [alloc("a", 2.0, 2.0), alloc("b", 1.0, 4.0)];
        assert_eq!(remaining(&budget, &running), (1000, 2 << 30));
        // Exactly what is left fits.
        assert!(admit(&budget, &running, &Limits::new(1.0, 2.0, Gpus::None)).is_ok());
        let e = admit(&budget, &running, &Limits::new(1.5, 1.0, Gpus::None)).unwrap_err();
        assert!(e.contains("cpu: asks 1.5 of the 1 left"), "{e}");
        assert!(e.contains("2 running workload(s) hold 3 of 4 cpu"), "{e}");
        let e = admit(&budget, &running, &Limits::new(0.5, 3.0, Gpus::None)).unwrap_err();
        assert!(
            e.contains("memory: asks 3072 MiB of the 2048 MiB left"),
            "{e}"
        );
        assert!(!e.contains("cpu: asks"), "{e}");
        // Nothing running: the whole budget is free; past it never is.
        assert!(admit(&budget, &[], &budget).is_ok());
        let full = [alloc("a", 4.0, 8.0), alloc("b", 1.0, 1.0)];
        assert_eq!(remaining(&budget, &full), (0, 0));
        assert!(admit(&budget, &full, &Limits::new(0.01, 0.0, Gpus::None)).is_err());
    }

    #[test]
    fn a_deployment_takes_a_slice_of_the_budget() {
        let budget = Limits::new(2.0, 4.0, Gpus::All);
        let d = deployment_limits(&budget, &env(&[])).unwrap();
        assert_eq!(
            (d.cpus_flag(), d.memory_flag(), d.gpus),
            ("0.5".into(), "1024m".into(), Gpus::All)
        );
        let half =
            deployment_limits(&budget, &env(&[("ZAKURO_DEPLOY_BUDGET_SLICE", "50%")])).unwrap();
        assert_eq!(half.cpus_flag(), "1");
        for bad in ["0.5", "0%", "150%", "lots"] {
            let e = deployment_limits(&budget, &move |k: &str| {
                (k == "ZAKURO_DEPLOY_BUDGET_SLICE").then(|| bad.to_string())
            })
            .unwrap_err();
            assert!(e.starts_with("ZAKURO_DEPLOY_BUDGET_SLICE="), "{bad}: {e}");
        }
    }

    #[test]
    fn an_unsized_lease_takes_what_is_left_and_a_sized_one_its_request() {
        let budget = Limits::new(4.0, 8.0, Gpus::None);
        let running = [alloc("w", 3.0, 6.0)];
        let unsized_lease = lease_limits(&budget, &running, &Request::default());
        assert_eq!(
            (unsized_lease.cpus_flag(), unsized_lease.memory_flag()),
            ("1".into(), "2048m".into())
        );
        assert!(admit(&budget, &running, &unsized_lease).is_ok());
        let sized = lease_limits(
            &budget,
            &running,
            &Request {
                cpus: 2.0,
                memory_gib: 1.0,
                gpus: None,
            },
        );
        assert_eq!(sized.cpus_flag(), "2");
        assert!(
            admit(&budget, &running, &sized).is_err(),
            "2 cpu asked, 1 left"
        );
        // Nothing left: floored at what docker accepts, so admission refuses
        // it instead of a `--cpus 0` (unlimited) start.
        let full = [alloc("w", 4.0, 8.0)];
        let none = lease_limits(&budget, &full, &Request::default());
        assert_eq!(none.cpu_millis, MIN_CPU_MILLIS);
        assert!(admit(&budget, &full, &none).is_err());
    }

    #[test]
    fn the_doctor_line_shows_allocated_and_left() {
        let budget = Limits::new(4.0, 8.0, Gpus::None);
        let line = allocation_line(&budget, &[alloc("a", 1.5, 2.0)]);
        assert_eq!(
            line,
            "  allocated: 1.5 of 4 cpu, 2.0 of 8.0 GiB memory across 1 workload(s); left 2.5 cpu, 6.0 GiB"
        );
    }

    #[test]
    fn cpu_flags_have_no_trailing_zeros() {
        for (c, want) in [(1.0, "1"), (0.5, "0.5"), (1.25, "1.25"), (0.125, "0.125")] {
            assert_eq!(Limits::new(c, 1.0, Gpus::None).cpus_flag(), want);
        }
    }
}