zc2 0.0.48

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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
//! The LXC/Incus backend of [`super::Runtime`] (M3.3, zc#512), Linux's
//! first choice: one unprivileged Incus container, `zakuro-sandbox`, sized
//! to the whole node budget, with containerd + nerdctl nested inside it for
//! the OCI workloads.
//!
//! Two layers of limits, both always present:
//!
//! - the sandbox itself carries `limits.cpu` (cores it may see),
//!   `limits.cpu.allowance` (a hard `quota/period` for fractional budgets),
//!   `limits.memory` (hard, no swap on top) and a root disk size, all from
//!   [`super::Budget::total`], so the sum of everything inside it can never
//!   pass what the owner lent;
//! - each workload inside gets its own `--cpus` / `--memory` from
//!   [`StartSpec::limits`], through the same [`docker::run_argv`] the Docker
//!   backend uses (nerdctl takes the Docker flags), so a start that forgets
//!   them cannot exist here either.
//!
//! GPUs: the sandbox gets an Incus `gpu` device (and `nvidia.runtime`) only
//! when the budget allows a GPU; without that opt-in no GPU device exists in
//! the boundary and a workload asking for one is refused before it starts.
//!
//! Every Incus call goes through one [`IncusCli`] (argv in, stdout out), so a
//! fake drives every path in tests on a machine with no Incus. When Incus is
//! missing or unusable the probe says why, and [`super::select`] falls back
//! to Docker (with its own per-container limits).

use std::process::Command;
use std::sync::Arc;

use super::{
    docker, Budget, Gpus, HostResources, Limits, Probe, Runtime, RuntimeKind, StartSpec, State,
};

/// The one Incus instance every workload runs in.
pub const SANDBOX: &str = "zakuro-sandbox";
/// The sandbox's base image (`ZAKURO_SANDBOX_IMAGE` overrides): the same on
/// Ubuntu 24.04 and Debian 12 hosts, so the nested runtime is identical.
pub const DEFAULT_IMAGE: &str = "images:ubuntu/24.04";
/// nerdctl is not packaged in Ubuntu 24.04 or Debian 12; this release is
/// fetched inside the sandbox and checked against the pinned digests.
pub const NERDCTL_VERSION: &str = "2.0.3";
const NERDCTL_SHA256: [(&str, &str); 2] = [
    (
        "amd64",
        "95ff850688a73eace7453f19e74bf4cc8a1f3e458eeb97ef7a6b74de9825df16",
    ),
    (
        "arm64",
        "f2c3f12c99e112cd82ba19ca9b875045c44b2f5a19cecc295ed8d61d415e8851",
    ),
];
/// buildkit (`nerdctl build` needs its daemon: Atelier layer builds, zc#593),
/// pinned and checksummed the same way. Not packaged in Ubuntu 24.04.
pub const BUILDKIT_VERSION: &str = "0.17.3";
const BUILDKIT_SHA256: [(&str, &str); 2] = [
    (
        "amd64",
        "1ab54cc01fd2e174483070451921badc53cc463a4f2e2e980be7db99ca95c0d0",
    ),
    (
        "arm64",
        "1afabc9c0829f7fa5173f439b7212194703b48f8e79a405596ada1af6e6f8220",
    ),
];
/// The root disk size when `ZAKURO_BUDGET_DISK` is not set.
pub const DEFAULT_DISK_BYTES: u64 = 20 * 1024 * 1024 * 1024;

const GPU_DEVICE: &str = "zakuro-gpu";
const PORT_DEVICE: &str = "zakuro-port-";
const MOUNT_DEVICE: &str = "zakuro-mnt-";
const MIB: u64 = 1024 * 1024;

/// What the Incus CLI error starts with when the binary is not there.
pub const NOT_INSTALLED: &str = "incus is not installed";

/// The base image under LXD (`lxc`), whose `images:` remote is not the one
/// Incus ships: `ubuntu:` is the stock Canonical remote on both LXD and snap.
pub const DEFAULT_IMAGE_LXD: &str = "ubuntu:24.04";

/// Whether an executable `bin` is on `PATH`.
fn on_path(bin: &str) -> bool {
    std::env::var_os("PATH")
        .is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
}

/// The CLI this node manages instances with: `incus` when it is installed,
/// else `lxc` (LXD, which the LAN hosts run), else `incus` (so the probe says
/// "not installed"). Decided once per process. Every argv in this module is
/// written `incus …`; [`IncusShell`] runs it as this binary. The two CLIs take
/// the same verbs used here (launch, init, exec, config, image, publish).
pub fn cli_binary() -> &'static str {
    static CLI: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
    CLI.get_or_init(|| {
        if on_path("incus") {
            "incus"
        } else if on_path("lxc") {
            "lxc"
        } else {
            "incus"
        }
    })
}

/// The base image for `cli` (see [`cli_binary`]).
pub fn default_image(cli: &str) -> &'static str {
    if cli == "lxc" {
        DEFAULT_IMAGE_LXD
    } else {
        DEFAULT_IMAGE
    }
}

/// The slice of the Incus CLI a backend needs: run one `incus …` argv, hand
/// back its trimmed stdout, or its trimmed stderr as an error.
pub trait IncusCli: Send + Sync {
    fn run(&self, argv: &[String]) -> Result<String, String>;
}

/// The real one: shells out.
pub struct IncusShell;

impl IncusCli for IncusShell {
    fn run(&self, argv: &[String]) -> Result<String, String> {
        let (prog, rest) = argv.split_first().ok_or("empty incus command")?;
        let prog = if prog == "incus" { cli_binary() } else { prog };
        let out = Command::new(prog).args(rest).output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                format!("{NOT_INSTALLED} ({e})")
            } else {
                format!("incus failed to run: {e}")
            }
        })?;
        if out.status.success() {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

/// How big the sandbox is: the whole node budget, plus its root disk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxSize {
    pub limits: Limits,
    pub disk_bytes: u64,
}

impl SandboxSize {
    /// The node budget on this host. `Err` (an invalid budget, an
    /// unresolvable percentage) makes every start refuse rather than run
    /// unlimited.
    pub fn from_budget(b: &Budget, host: &HostResources) -> Result<Self, String> {
        Ok(Self {
            limits: b.total(host)?,
            disk_bytes: b.disk_bytes,
        })
    }
}

fn s(v: &[&str]) -> Vec<String> {
    v.iter().map(|a| a.to_string()).collect()
}

/// The instance keys that carry the budget (and its security posture),
/// applied at launch and re-applied to an existing sandbox before each
/// start, so a changed budget takes effect without recreating it.
pub fn sandbox_config(l: &Limits) -> Vec<(String, String)> {
    let cores = l.cpu_millis.div_ceil(1000).max(1);
    // 100 ms period: 1.5 cpu = 150ms/100ms (cgroup cpu.max 150000 100000).
    let allowance = (l.cpu_millis / 10).max(1);
    let gpu = l.gpus.flag_value().is_some();
    vec![
        ("limits.cpu".into(), cores.to_string()),
        (
            "limits.cpu.allowance".into(),
            format!("{allowance}ms/100ms"),
        ),
        ("limits.memory".into(), mib(l.memory_bytes)),
        ("limits.memory.enforce".into(), "hard".into()),
        ("limits.memory.swap".into(), "false".into()),
        ("security.privileged".into(), "false".into()),
        ("security.nesting".into(), "true".into()),
        ("nvidia.runtime".into(), gpu.to_string()),
    ]
}

fn mib(bytes: u64) -> String {
    format!("{}MiB", (bytes / MIB).max(6))
}

/// `incus launch IMAGE NAME -c k=v … -d root,size=…`.
pub fn launch_argv(instance: &str, image: &str, size: &SandboxSize) -> Vec<String> {
    let mut a = s(&["incus", "launch", image, instance]);
    for (k, v) in sandbox_config(&size.limits) {
        a.push("-c".into());
        a.push(format!("{k}={v}"));
    }
    a.push("-d".into());
    a.push(format!("root,size={}", mib(size.disk_bytes)));
    a
}

/// The Incus `gpu` devices for a budget's GPU setting: none without the
/// opt-in. Each device's name encodes its config, so reconciling is a diff
/// by name.
pub fn gpu_devices(g: &Gpus) -> Result<Vec<(String, Vec<String>)>, String> {
    let dev = |id: Option<&str>| {
        let mut kv = s(&["gputype=physical"]);
        if let Some(id) = id {
            kv.push(format!("id={id}"));
        }
        (format!("{GPU_DEVICE}-{}", id.unwrap_or("all")), kv)
    };
    Ok(match g {
        Gpus::None | Gpus::Count(0) => vec![],
        Gpus::All => vec![dev(None)],
        Gpus::Count(n) => (0..*n).map(|i| dev(Some(&i.to_string()))).collect(),
        Gpus::Spec(spec) => {
            let v = spec.trim().trim_matches('"').trim();
            if v == "all" {
                vec![dev(None)]
            } else if let Ok(n) = v.parse::<u32>() {
                return gpu_devices(&Gpus::Count(n));
            } else if let Some(ids) = v.strip_prefix("device=") {
                let ids: Vec<&str> = ids
                    .split(',')
                    .map(str::trim)
                    .filter(|i| !i.is_empty())
                    .collect();
                if ids.is_empty() || ids.iter().any(|i| i.parse::<u32>().is_err()) {
                    return Err(format!(
                        "GPU spec {spec:?}: the lxc backend passes GPUs by index (device=0,1)"
                    ));
                }
                ids.into_iter().map(|i| dev(Some(i))).collect()
            } else {
                return Err(format!(
                    "GPU spec {spec:?} is not understood by the lxc backend"
                ));
            }
        }
    })
}

/// The `sh` script that installs containerd, the CNI plugins and a pinned
/// nerdctl inside the sandbox. Idempotent; waits for the sandbox's network.
pub fn provision_script() -> String {
    let sums: String = NERDCTL_SHA256
        .iter()
        .map(|(arch, sum)| format!("{arch}) sum={sum} ;; "))
        .collect();
    let bk_sums: String = BUILDKIT_SHA256
        .iter()
        .map(|(arch, sum)| format!("{arch}) bsum={sum} ;; "))
        .collect();
    format!(
        "set -e; export DEBIAN_FRONTEND=noninteractive; \
         for i in $(seq 60); do getent hosts github.com >/dev/null 2>&1 && break; sleep 1; done; \
         apt-get update -q >/dev/null; \
         apt-get install -y -q containerd containernetworking-plugins iptables curl ca-certificates >/dev/null; \
         arch=$(dpkg --print-architecture); \
         case $arch in {sums}*) echo \"no pinned nerdctl for $arch\" >&2; exit 1 ;; esac; \
         curl -fsSL https://github.com/containerd/nerdctl/releases/download/v{v}/nerdctl-{v}-linux-$arch.tar.gz -o /tmp/nerdctl.tgz; \
         echo \"$sum  /tmp/nerdctl.tgz\" | sha256sum -c - >/dev/null; \
         tar -C /usr/local/bin -xzf /tmp/nerdctl.tgz nerdctl; rm -f /tmp/nerdctl.tgz; \
         case $arch in {bk_sums}*) echo \"no pinned buildkit for $arch\" >&2; exit 1 ;; esac; \
         curl -fsSL https://github.com/moby/buildkit/releases/download/v{bv}/buildkit-v{bv}.linux-$arch.tar.gz -o /tmp/buildkit.tgz; \
         echo \"$bsum  /tmp/buildkit.tgz\" | sha256sum -c - >/dev/null; \
         tar -C /usr/local -xzf /tmp/buildkit.tgz; rm -f /tmp/buildkit.tgz; \
         printf '[Unit]\\nDescription=buildkit\\nAfter=containerd.service\\n[Service]\\nExecStart=/usr/local/bin/buildkitd\\nRestart=always\\n[Install]\\nWantedBy=multi-user.target\\n' > /etc/systemd/system/buildkit.service; \
         systemctl daemon-reload; \
         systemctl enable --now containerd >/dev/null 2>&1; systemctl enable --now buildkit >/dev/null 2>&1 || true; nerdctl version >/dev/null",
        v = NERDCTL_VERSION,
        bv = BUILDKIT_VERSION
    )
}

/// One `-p` spec, split.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publish {
    pub ip: String,
    /// `None` for an ephemeral one (`127.0.0.1::8888`, `8888`).
    pub host: Option<u16>,
    /// The container side as given (`80`, `53/udp`).
    pub container: String,
    /// `tcp` or `udp`: the Incus proxy device carries it to the host.
    pub proto: String,
}

/// Parse one `-p` spec. Only `tcp` (the default) and `udp` are accepted: the
/// Incus proxy device that carries the host side speaks those two.
pub fn parse_publish(p: &str) -> Result<Publish, String> {
    let parts: Vec<&str> = p.split(':').collect();
    let port = |v: &str| {
        v.parse::<u16>()
            .map_err(|_| format!("bad publish spec {p:?}"))
    };
    let (ip, host, cont) = match parts.as_slice() {
        [c] => ("0.0.0.0", "", *c),
        [h, c] => ("0.0.0.0", *h, *c),
        [ip, h, c] => (*ip, *h, *c),
        _ => return Err(format!("bad publish spec {p:?}")),
    };
    let host = if host.is_empty() {
        None
    } else {
        Some(port(host)?)
    };
    let (cport, proto) = cont.split_once('/').unwrap_or((cont, "tcp"));
    port(cport)?;
    let proto = proto.to_ascii_lowercase();
    if proto != "tcp" && proto != "udp" {
        return Err(format!(
            "publish {p:?}: the lxc backend publishes tcp or udp, not {proto}"
        ));
    }
    Ok(Publish {
        ip: ip.to_string(),
        host,
        container: cont.to_string(),
        proto,
    })
}

/// The first 16 hex digits (64 bits) of sha256: a short, stable
/// device-name suffix for a path or a workload name (Incus device names are
/// short and restricted). Long enough that two names do not collide in
/// practice; [`LxcRuntime::mount`] still checks a reused device's source.
fn tag(v: &str) -> String {
    crate::dataset::sha256_hex(v.as_bytes())[..16].to_string()
}

/// Parse `cat cpu.max memory.max; <gpu count>` from inside a workload: the
/// limits its cgroup actually has. No cpu or memory cap is an error.
pub fn parse_cgroup_limits(out: &str) -> Result<Limits, String> {
    let bad = || format!("unexpected cgroup limits output: {out:?}");
    let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
    let cpu = lines.next().ok_or_else(bad)?;
    let mem = lines.next().ok_or_else(bad)?;
    let gpus: u32 = lines.next().unwrap_or("0").parse().map_err(|_| bad())?;
    let mut c = cpu.split_whitespace();
    let quota = c.next().ok_or_else(bad)?;
    let period: u64 = c.next().ok_or_else(bad)?.parse().map_err(|_| bad())?;
    if quota == "max" {
        return Err("workload runs without a cpu limit".into());
    }
    if mem == "max" {
        return Err("workload runs without a memory limit".into());
    }
    let quota: u64 = quota.parse().map_err(|_| bad())?;
    let mem: u64 = mem.parse().map_err(|_| bad())?;
    if period == 0 {
        return Err(bad());
    }
    Ok(Limits {
        cpu_millis: (quota * 1000 / period) as u32,
        memory_bytes: mem,
        gpus: if gpus > 0 {
            Gpus::Count(gpus)
        } else {
            Gpus::None
        },
    })
}

/// Incus as a [`Runtime`].
#[derive(Clone)]
pub struct LxcRuntime {
    cli: Arc<dyn IncusCli>,
    instance: String,
    image: String,
    size: Result<SandboxSize, String>,
}

impl LxcRuntime {
    pub fn new(
        cli: Arc<dyn IncusCli>,
        instance: &str,
        image: &str,
        size: Result<SandboxSize, String>,
    ) -> Self {
        Self {
            cli,
            instance: instance.to_string(),
            image: image.to_string(),
            size,
        }
    }

    /// The real CLI, sized from the node budget in `get` (the environment).
    pub fn from_env(cli: Arc<dyn IncusCli>, get: &dyn Fn(&str) -> Option<String>) -> Self {
        let image = get("ZAKURO_SANDBOX_IMAGE")
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| default_image(cli_binary()).to_string());
        let size = Budget::from_env(get)
            .and_then(|b| SandboxSize::from_budget(&b, &HostResources::detect()));
        Self::new(cli, SANDBOX, &image, size)
    }

    pub fn shell() -> Self {
        Self::from_env(Arc::new(IncusShell), &|k| std::env::var(k).ok())
    }

    /// The base image the sandbox (and the golden image) is built from.
    pub fn image(&self) -> &str {
        &self.image
    }

    /// The node-wide sizing, or why there is none.
    pub fn size(&self) -> &Result<SandboxSize, String> {
        &self.size
    }

    /// The sandbox instance's name.
    pub fn instance(&self) -> &str {
        &self.instance
    }

    fn incus(&self, rest: &[&str]) -> Result<String, String> {
        let mut argv = vec!["incus".to_string()];
        argv.extend(rest.iter().map(|a| a.to_string()));
        self.cli.run(&argv)
    }

    /// A Docker-shaped argv (`docker …`, as [`crate::up`] and
    /// [`docker::run_argv`] build them) run through nerdctl inside the
    /// sandbox.
    pub fn in_sandbox(&self, docker_argv: &[String]) -> Vec<String> {
        let mut a = s(&["incus", "exec", &self.instance, "--", "nerdctl"]);
        let rest = match docker_argv.first().map(String::as_str) {
            Some("docker") => &docker_argv[1..],
            _ => docker_argv,
        };
        a.extend(rest.iter().cloned());
        a
    }

    fn nerdctl(&self, docker_argv: &[String]) -> Result<String, String> {
        self.cli.run(&self.in_sandbox(docker_argv))
    }

    /// The sandbox's state (`RUNNING`, `STOPPED`, …), `None` when it does
    /// not exist. `incus list NAME` matches by prefix, hence the exact
    /// compare.
    pub fn state(&self) -> Result<Option<String>, String> {
        let out = self.incus(&["list", &self.instance, "-f", "csv", "-c", "ns"])?;
        Ok(out.lines().find_map(|l| {
            let (n, st) = l.split_once(',')?;
            (n.trim() == self.instance).then(|| st.trim().to_string())
        }))
    }

    fn privileged(&self) -> Result<bool, String> {
        Ok(self
            .incus(&["config", "get", &self.instance, "security.privileged"])?
            .trim()
            .eq_ignore_ascii_case("true"))
    }

    fn devices(&self) -> Result<Vec<String>, String> {
        Ok(self
            .incus(&["config", "device", "list", &self.instance])?
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect())
    }

    /// The sandbox's own limits, read back from Incus.
    pub fn sandbox_limits(&self) -> Result<Limits, String> {
        let get = |k: &str| self.incus(&["config", "get", &self.instance, k]);
        let allowance = get("limits.cpu.allowance")?;
        let cpu_millis = allowance
            .strip_suffix("ms/100ms")
            .and_then(|v| v.parse::<u32>().ok())
            .map(|ms| ms * 10)
            .ok_or_else(|| {
                format!(
                    "{} has no hard cpu allowance ({allowance:?})",
                    self.instance
                )
            })?;
        let mem = get("limits.memory")?;
        let memory_bytes = mem
            .strip_suffix("MiB")
            .and_then(|v| v.parse::<u64>().ok())
            .map(|m| m * MIB)
            .ok_or_else(|| format!("{} has no memory limit ({mem:?})", self.instance))?;
        let gpus = self
            .devices()?
            .iter()
            .filter(|d| d.starts_with(GPU_DEVICE))
            .count() as u32;
        Ok(Limits {
            cpu_millis,
            memory_bytes,
            gpus: if gpus > 0 {
                Gpus::Count(gpus)
            } else {
                Gpus::None
            },
        })
    }

    /// Create the sandbox, or bring an existing one to the current budget,
    /// and make sure containerd + nerdctl are inside. Refuses a privileged
    /// sandbox (someone changed it by hand): its limits would not hold.
    pub fn ensure(&self) -> Result<(), String> {
        let size = self.size.clone()?;
        let inst = self.instance.as_str();
        let wanted_gpus = gpu_devices(&size.limits.gpus)?;
        match self.state()? {
            None => {
                self.cli
                    .run(&launch_argv(inst, &self.image, &size))
                    .map_err(|e| format!("incus launch {inst} failed: {e}"))?;
            }
            Some(state) => {
                if self.privileged()? {
                    return Err(privileged_refusal(inst));
                }
                let nv_before = self.incus(&["config", "get", inst, "nvidia.runtime"])?;
                let mut set = s(&["incus", "config", "set", inst]);
                let cfg = sandbox_config(&size.limits);
                let nv_after = cfg
                    .iter()
                    .find(|(k, _)| k == "nvidia.runtime")
                    .map(|(_, v)| v.clone())
                    .unwrap_or_default();
                set.extend(cfg.into_iter().map(|(k, v)| format!("{k}={v}")));
                self.cli.run(&set)?;
                let disk = format!("size={}", mib(size.disk_bytes));
                if self
                    .incus(&["config", "device", "set", inst, "root", &disk])
                    .is_err()
                {
                    // The root disk still comes from the profile.
                    self.incus(&["config", "device", "override", inst, "root", &disk])?;
                }
                let nv_changed =
                    nv_before.trim().eq_ignore_ascii_case("true") != (nv_after == "true");
                if !state.eq_ignore_ascii_case("RUNNING") {
                    self.incus(&["start", inst])?;
                } else if nv_changed {
                    // nvidia.runtime only applies at container start.
                    self.incus(&["restart", inst])?;
                }
            }
        }
        // GPU devices: exactly the budget's, none without the opt-in.
        let have: Vec<String> = self
            .devices()?
            .into_iter()
            .filter(|d| d.starts_with(GPU_DEVICE))
            .collect();
        for d in &have {
            if !wanted_gpus.iter().any(|(n, _)| n == d) {
                self.incus(&["config", "device", "remove", inst, d])?;
            }
        }
        for (name, kv) in &wanted_gpus {
            if !have.contains(name) {
                let mut a = s(&["incus", "config", "device", "add", inst, name, "gpu"]);
                a.extend(kv.iter().cloned());
                self.cli.run(&a)?;
            }
        }
        let ready = self.incus(&[
            "exec",
            inst,
            "--",
            "sh",
            "-c",
            "command -v nerdctl >/dev/null && command -v buildkitd >/dev/null && systemctl is-active --quiet containerd",
        ]);
        if ready.is_err() {
            self.incus(&["exec", inst, "--", "sh", "-c", &provision_script()])
                .map_err(|e| format!("provisioning containerd in {inst} failed: {e}"))?;
        }
        Ok(())
    }

    /// Share `host` into the sandbox (idmapped, so an unprivileged sandbox
    /// sees the owner's files with their owners) and return its path there.
    fn mount(&self, host: &str, have: &[String]) -> Result<String, String> {
        let t = tag(host);
        let dev = format!("{MOUNT_DEVICE}{t}");
        let inner = format!("/zakuro/mnt/{t}");
        if have.contains(&dev) {
            // Reuse only a device that shares exactly this directory: a
            // stale or colliding one must never map another host path in.
            let source =
                self.incus(&["config", "device", "get", &self.instance, &dev, "source"])?;
            if source.trim() != host {
                return Err(format!(
                    "{} device {dev} shares {:?}, not {host:?}; refusing to reuse it \
                     (remove it with `incus config device remove {} {dev}`)",
                    self.instance,
                    source.trim(),
                    self.instance
                ));
            }
        } else {
            self.cli.run(&s(&[
                "incus",
                "config",
                "device",
                "add",
                &self.instance,
                &dev,
                "disk",
                &format!("source={host}"),
                &format!("path={inner}"),
                "shift=true",
            ]))?;
        }
        Ok(inner)
    }

    fn remove_port_devices(&self, name: &str) -> Result<(), String> {
        let suffix = format!("-{}", tag(name));
        for d in self.devices()? {
            if d.starts_with(PORT_DEVICE) && d.ends_with(&suffix) {
                self.incus(&["config", "device", "remove", &self.instance, &d])?;
            }
        }
        Ok(())
    }
}

fn privileged_refusal(inst: &str) -> String {
    format!(
        "{inst} is a privileged container, so the budget would not hold; \
         delete it (`incus delete -f {inst}`) and zc recreates it unprivileged"
    )
}

/// `Server version: X` from `incus version`, `None` when unreachable.
fn server_version(out: &str) -> Option<String> {
    out.lines()
        .find_map(|l| l.trim().strip_prefix("Server version:"))
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty() && v != "unreachable")
}

impl Runtime for LxcRuntime {
    fn kind(&self) -> RuntimeKind {
        RuntimeKind::Lxc
    }

    fn probe(&self) -> Probe {
        let no = |detail: String| Probe {
            kind: RuntimeKind::Lxc,
            available: false,
            detail,
        };
        let version = match self.incus(&["version"]) {
            Ok(v) => v,
            Err(e) if e.starts_with(NOT_INSTALLED) => {
                return no(format!(
                    "{NOT_INSTALLED} (apt install incus; the zakuro .deb recommends it, \
                     Zabbly repo: https://github.com/zabbly/incus)"
                ))
            }
            Err(e) => {
                return no(e
                    .lines()
                    .next()
                    .unwrap_or("incus version failed")
                    .to_string())
            }
        };
        let Some(server) = server_version(&version) else {
            return no(
                "incus daemon unreachable (start incus, and add this user to the incus-admin group)"
                    .into(),
            );
        };
        let sandbox = match self.state() {
            Err(e) => return no(e.lines().next().unwrap_or("incus list failed").to_string()),
            Ok(None) => "not created yet (created at the first start)".to_string(),
            Ok(Some(st)) => match self.privileged() {
                Ok(true) => return no(privileged_refusal(&self.instance)),
                Ok(false) => match self.sandbox_limits() {
                    Ok(l) => format!("{} ({l})", st.to_lowercase()),
                    Err(e) => format!("{} ({e})", st.to_lowercase()),
                },
                Err(e) => return no(e),
            },
        };
        Probe {
            kind: RuntimeKind::Lxc,
            available: true,
            detail: format!(
                "incus {server}, unprivileged sandbox {} {sandbox}",
                self.instance
            ),
        }
    }

    fn verify_image(&self, image: &str, expected_digest: Option<&str>) -> Result<(), String> {
        let out = self
            .nerdctl(&s(&[
                "docker",
                "image",
                "inspect",
                "--format",
                "{{.Id}}|{{json .RepoDigests}}",
                image,
            ]))
            .map_err(|e| format!("image {image} is not in {}: {e}", self.instance))?;
        let Some(want) = expected_digest else {
            return Ok(());
        };
        docker::check_digest(image, &out, want)
    }

    fn start(&self, spec: &StartSpec) -> Result<String, String> {
        let size = self.size.clone()?;
        if spec.limits.gpus.flag_value().is_some() && size.limits.gpus.flag_value().is_none() {
            return Err(format!(
                "{} asks for a GPU but this node's budget passes none through \
                 (set ZAKURO_BUDGET_GPU=1 to opt in)",
                spec.name
            ));
        }
        // Validate the publishes before touching anything.
        let publish = spec
            .publish
            .iter()
            .map(|p| parse_publish(p))
            .collect::<Result<Vec<_>, _>>()?;
        if let Some(p) = publish.iter().position(|p| p.host.is_none()) {
            return Err(format!(
                "publish {:?}: the lxc backend needs a fixed host port",
                spec.publish[p]
            ));
        }
        self.ensure()?;
        let have = self.devices()?;
        let mut inner = spec.clone();
        inner.mounts = spec
            .mounts
            .iter()
            .map(|(h, c)| Ok((self.mount(h, &have)?, c.clone())))
            .collect::<Result<_, String>>()?;
        // nerdctl publishes on the sandbox; an Incus proxy device carries
        // the host side (same address and port the spec asked for).
        inner.publish = publish
            .iter()
            .map(|p| format!("{}:{}", p.host.unwrap_or_default(), p.container))
            .collect();
        if spec.create_network {
            if let Some(net) = &spec.network {
                // Idempotent, as in the Docker backend.
                let _ = self.nerdctl(&s(&["docker", "network", "create", net]));
            }
        }
        self.remove_port_devices(&spec.name)?;
        // nerdctl refuses `run -d --rm`: run without `--rm`, and free the name
        // of a container an earlier start left behind (`stop` removes it).
        inner.remove_on_exit = false;
        let _ = self.nerdctl(&s(&["docker", "rm", "-f", &spec.name]));
        let mut run = vec!["docker".to_string()];
        run.extend(docker::run_argv(&inner));
        let id = self.nerdctl(&run)?;
        let t = tag(&spec.name);
        for p in &publish {
            let (ip, proto) = (&p.ip, &p.proto);
            let h = p.host.unwrap_or_default();
            let r = self.cli.run(&s(&[
                "incus",
                "config",
                "device",
                "add",
                &self.instance,
                &format!("{PORT_DEVICE}{proto}{h}-{t}"),
                "proxy",
                &format!("listen={proto}:{ip}:{h}"),
                &format!("connect={proto}:127.0.0.1:{h}"),
            ]));
            if let Err(e) = r {
                let _ = self.stop(&spec.name);
                return Err(format!(
                    "publishing {proto} {ip}:{h} for {} failed: {e}",
                    spec.name
                ));
            }
        }
        Ok(id)
    }

    fn exec(&self, name: &str, argv: &[String], detach: bool) -> Result<String, String> {
        let mut full = s(&["docker", "exec"]);
        if detach {
            full.push("-d".into());
        }
        full.push(name.to_string());
        full.extend(argv.iter().cloned());
        self.nerdctl(&full)
    }

    fn stop(&self, name: &str) -> Result<(), String> {
        let Some(state) = self.state()? else {
            return Ok(());
        };
        self.remove_port_devices(name)?;
        if !state.eq_ignore_ascii_case("RUNNING") {
            // Nothing runs in a stopped sandbox, and `incus exec` would fail.
            return Ok(());
        }
        match self.nerdctl(&crate::up::docker_rm_argv(name)) {
            Ok(_) => Ok(()),
            Err(e) if e.contains("no such container") || e.contains("no such object") => Ok(()),
            Err(e) => Err(e),
        }
    }

    fn limits(&self, name: &str) -> Result<Limits, String> {
        // nerdctl's inspect has no HostConfig: read the workload's cgroup.
        parse_cgroup_limits(&self.nerdctl(&s(&[
            "docker",
            "exec",
            name,
            "sh",
            "-c",
            "cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.max; \
             ls -d /dev/nvidia[0-9]* 2>/dev/null | wc -l",
        ]))?)
    }

    fn health(&self, name: &str) -> Result<State, String> {
        let out = self.nerdctl(&crate::up::docker_state_argv(name))?;
        crate::up::parse_container_state(&out)
            .ok_or_else(|| format!("unexpected nerdctl inspect output: {out:?}"))
    }
}

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

    /// Records every argv; answers by the first `needle` the joined argv
    /// contains, else `Ok("")`.
    #[derive(Default)]
    struct Rec {
        calls: Mutex<Vec<String>>,
        answer: Mutex<Vec<(&'static str, Result<String, String>)>>,
    }

    impl Rec {
        fn on(&self, needle: &'static str, a: Result<&str, &str>) {
            self.answer
                .lock()
                .unwrap()
                .push((needle, a.map(String::from).map_err(String::from)));
        }
        fn calls(&self) -> Vec<String> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl IncusCli for Rec {
        fn run(&self, argv: &[String]) -> Result<String, String> {
            let j = argv.join(" ");
            self.calls.lock().unwrap().push(j.clone());
            for (needle, a) in self.answer.lock().unwrap().iter() {
                if j.contains(needle) {
                    return a.clone();
                }
            }
            Ok(String::new())
        }
    }

    fn size(gpus: Gpus) -> SandboxSize {
        SandboxSize {
            limits: Limits::new(1.5, 2.0, gpus),
            disk_bytes: 10 * 1024 * MIB,
        }
    }

    fn rt(rec: &Arc<Rec>, gpus: Gpus) -> LxcRuntime {
        LxcRuntime::new(rec.clone(), SANDBOX, DEFAULT_IMAGE, Ok(size(gpus)))
    }

    fn spec() -> StartSpec {
        StartSpec {
            name: "zc-share-w0".into(),
            image: "img".into(),
            network: Some("net".into()),
            create_network: true,
            labels: vec![("zakuro.share".into(), "1".into())],
            mounts: vec![],
            publish: vec!["127.0.0.1:3960:3960".into()],
            env: vec![],
            cmd: vec![],
            limits: Limits::new(0.5, 1.0, Gpus::None),
            remove_on_exit: true,
            hardened: false,
        }
    }

    #[test]
    fn a_new_sandbox_is_launched_unprivileged_and_sized_to_the_budget() {
        let d = Arc::new(Rec::default());
        rt(&d, Gpus::None).ensure().unwrap();
        let calls = d.calls();
        assert_eq!(calls[0], "incus list zakuro-sandbox -f csv -c ns");
        assert_eq!(
            calls[1],
            "incus launch images:ubuntu/24.04 zakuro-sandbox \
             -c limits.cpu=2 -c limits.cpu.allowance=150ms/100ms -c limits.memory=2048MiB \
             -c limits.memory.enforce=hard -c limits.memory.swap=false \
             -c security.privileged=false -c security.nesting=true -c nvidia.runtime=false \
             -d root,size=10240MiB"
        );
        assert!(
            !calls.iter().any(|c| c.contains(" gpu")),
            "no GPU device without the opt-in: {calls:#?}"
        );
        // Not provisioned yet (the readiness check answers Ok("") = ready in
        // this fake), so make it fail and check the script runs.
        let d = Arc::new(Rec::default());
        d.on("command -v nerdctl", Err("not found"));
        rt(&d, Gpus::None).ensure().unwrap();
        let last = d.calls().pop().unwrap();
        assert!(
            last.starts_with("incus exec zakuro-sandbox -- sh -c set -e;"),
            "{last}"
        );
        assert!(
            last.contains("containerd containernetworking-plugins"),
            "{last}"
        );
        assert!(
            last.contains(&format!("nerdctl-{NERDCTL_VERSION}-linux-$arch")),
            "{last}"
        );
        assert!(last.contains("sha256sum -c"), "{last}");
    }

    #[test]
    fn an_existing_sandbox_is_brought_to_the_current_budget() {
        let d = Arc::new(Rec::default());
        d.on(
            "incus list zakuro-sandbox",
            Ok("zakuro-sandbox-old,RUNNING\nzakuro-sandbox,STOPPED"),
        );
        d.on("config get zakuro-sandbox security.privileged", Ok(""));
        d.on("config get zakuro-sandbox nvidia.runtime", Ok("false"));
        d.on(
            "device set zakuro-sandbox root",
            Err("Device from profile(s) cannot be modified"),
        );
        rt(&d, Gpus::None).ensure().unwrap();
        let calls = d.calls();
        assert!(
            calls.contains(
                &"incus config set zakuro-sandbox limits.cpu=2 limits.cpu.allowance=150ms/100ms \
              limits.memory=2048MiB limits.memory.enforce=hard limits.memory.swap=false \
              security.privileged=false security.nesting=true nvidia.runtime=false"
                    .to_string()
            ),
            "{calls:#?}"
        );
        assert!(calls.contains(
            &"incus config device override zakuro-sandbox root size=10240MiB".to_string()
        ));
        assert!(calls.contains(&"incus start zakuro-sandbox".to_string()));
        assert!(!calls.iter().any(|c| c.starts_with("incus launch")));
    }

    #[test]
    fn a_privileged_sandbox_is_refused() {
        let d = Arc::new(Rec::default());
        d.on("incus list zakuro-sandbox", Ok("zakuro-sandbox,RUNNING"));
        d.on("security.privileged", Ok("true"));
        d.on(
            "version",
            Ok("Client version: 6.0.0\nServer version: 6.0.0"),
        );
        let r = rt(&d, Gpus::None);
        assert!(r.ensure().unwrap_err().contains("privileged"));
        let p = r.probe();
        assert!(!p.available);
        assert!(p.detail.contains("privileged"), "{}", p.detail);
        assert!(r.start(&spec()).is_err());
        assert!(!d.calls().iter().any(|c| c.contains("nerdctl run")));
    }

    #[test]
    fn the_gpu_is_passed_through_only_after_opt_in() {
        // Opted in: one gpu device, and nvidia.runtime on.
        let d = Arc::new(Rec::default());
        rt(&d, Gpus::All).ensure().unwrap();
        let calls = d.calls();
        assert!(calls[1].contains("-c nvidia.runtime=true"), "{}", calls[1]);
        assert!(
            calls.contains(
                &"incus config device add zakuro-sandbox zakuro-gpu-all gpu gputype=physical"
                    .to_string()
            ),
            "{calls:#?}"
        );
        // Opt-in withdrawn: the device left behind is removed, nvidia off,
        // and the sandbox restarts for nvidia.runtime to drop.
        let d = Arc::new(Rec::default());
        d.on("incus list zakuro-sandbox", Ok("zakuro-sandbox,RUNNING"));
        d.on("security.privileged", Ok("false"));
        d.on("nvidia.runtime", Ok("true"));
        d.on(
            "device list",
            Ok("root\nzakuro-gpu-all\nzakuro-port-3960-1"),
        );
        rt(&d, Gpus::None).ensure().unwrap();
        let calls = d.calls();
        assert!(
            calls.contains(&"incus config device remove zakuro-sandbox zakuro-gpu-all".to_string()),
            "{calls:#?}"
        );
        assert!(calls.contains(&"incus restart zakuro-sandbox".to_string()));
        assert!(
            !calls.iter().any(|c| c.contains("device add")),
            "{calls:#?}"
        );
        // A workload asking for a GPU without the opt-in never starts.
        let d = Arc::new(Rec::default());
        let gpu_job = StartSpec {
            limits: Limits::new(1.0, 1.0, Gpus::Count(1)),
            ..spec()
        };
        let e = rt(&d, Gpus::None).start(&gpu_job).unwrap_err();
        assert!(e.contains("ZAKURO_BUDGET_GPU=1"), "{e}");
        assert!(d.calls().is_empty(), "{:#?}", d.calls());
        // With it, the job's --gpus reaches nerdctl.
        let d = Arc::new(Rec::default());
        rt(&d, Gpus::All).start(&gpu_job).unwrap();
        assert!(d
            .calls()
            .iter()
            .any(|c| c.contains("nerdctl run") && c.contains("--gpus 1")));
    }

    #[test]
    fn gpu_specs_map_to_devices_by_index() {
        let names = |g: Gpus| -> Vec<String> {
            gpu_devices(&g)
                .unwrap()
                .into_iter()
                .map(|(n, _)| n)
                .collect()
        };
        assert!(names(Gpus::None).is_empty());
        assert!(names(Gpus::Count(0)).is_empty());
        assert_eq!(names(Gpus::Count(2)), ["zakuro-gpu-0", "zakuro-gpu-1"]);
        assert_eq!(
            names(Gpus::Spec("\"device=1,3\"".into())),
            ["zakuro-gpu-1", "zakuro-gpu-3"]
        );
        assert_eq!(names(Gpus::Spec("all".into())), ["zakuro-gpu-all"]);
        assert_eq!(
            gpu_devices(&Gpus::Spec("device=0".into())).unwrap()[0].1,
            ["gputype=physical", "id=0"]
        );
        assert!(gpu_devices(&Gpus::Spec("device=GPU-abc".into())).is_err());
    }

    #[test]
    fn a_workload_runs_through_nerdctl_with_its_own_limits_and_a_host_proxy() {
        let d = Arc::new(Rec::default());
        d.on("nerdctl run", Ok("cid"));
        let job = StartSpec {
            mounts: vec![("/home/me/data".into(), "/data".into())],
            ..spec()
        };
        assert_eq!(rt(&d, Gpus::None).start(&job).unwrap(), "cid");
        let calls = d.calls();
        let t = tag("/home/me/data");
        assert!(
            calls.contains(&format!(
                "incus config device add zakuro-sandbox zakuro-mnt-{t} disk \
             source=/home/me/data path=/zakuro/mnt/{t} shift=true"
            )),
            "{calls:#?}"
        );
        assert!(
            calls.contains(&"incus exec zakuro-sandbox -- nerdctl network create net".to_string())
        );
        // nerdctl refuses `-d --rm`: the name is freed first instead.
        assert!(
            calls.contains(&"incus exec zakuro-sandbox -- nerdctl rm -f zc-share-w0".to_string())
        );
        let run = calls.iter().find(|c| c.contains("nerdctl run")).unwrap();
        assert_eq!(
            run,
            &format!(
                "incus exec zakuro-sandbox -- nerdctl run -d --name zc-share-w0 \
                 --network net --label zakuro.share=1 --label zakuro.budget=500m,1073741824 \
                 -v /zakuro/mnt/{t}:/data \
                 --cpus 0.5 --memory 1024m --memory-swap 1024m -p 3960:3960 img"
            )
        );
        let w = tag("zc-share-w0");
        assert_eq!(
            calls.last().unwrap(),
            &format!(
                "incus config device add zakuro-sandbox zakuro-port-tcp3960-{w} proxy \
                 listen=tcp:127.0.0.1:3960 connect=tcp:127.0.0.1:3960"
            )
        );
    }

    #[test]
    fn a_udp_publish_is_carried_as_udp_to_the_host() {
        let d = Arc::new(Rec::default());
        let job = StartSpec {
            publish: vec!["127.0.0.1:5353:53/udp".into()],
            ..spec()
        };
        rt(&d, Gpus::None).start(&job).unwrap();
        let calls = d.calls();
        let run = calls.iter().find(|c| c.contains("nerdctl run")).unwrap();
        assert!(run.contains(" -p 5353:53/udp "), "{run}");
        assert_eq!(
            calls.last().unwrap(),
            &format!(
                "incus config device add zakuro-sandbox zakuro-port-udp5353-{} proxy \
                 listen=udp:127.0.0.1:5353 connect=udp:127.0.0.1:5353",
                tag("zc-share-w0")
            )
        );
        // Anything else is refused before any Incus call.
        let d = Arc::new(Rec::default());
        let sctp = StartSpec {
            publish: vec!["9000:9000/sctp".into()],
            ..spec()
        };
        let e = rt(&d, Gpus::None).start(&sctp).unwrap_err();
        assert!(e.contains("tcp or udp, not sctp"), "{e}");
        assert!(d.calls().is_empty(), "{:#?}", d.calls());
    }

    #[test]
    fn a_mount_device_is_reused_only_for_the_same_host_directory() {
        let t = tag("/home/me/data");
        let job = StartSpec {
            mounts: vec![("/home/me/data".into(), "/data".into())],
            ..spec()
        };
        let devs = format!("root\nzakuro-mnt-{t}");
        // Same source: reused, no second device.
        let d = Arc::new(Rec::default());
        d.on("device list", Ok(&devs));
        d.on("source", Ok("/home/me/data"));
        rt(&d, Gpus::None).start(&job).unwrap();
        assert!(
            !d.calls()
                .iter()
                .any(|c| c.contains("add zakuro-sandbox zakuro-mnt-")),
            "{:#?}",
            d.calls()
        );
        // Another directory behind that name: refused, nothing runs.
        let d = Arc::new(Rec::default());
        d.on("device list", Ok(&devs));
        d.on("source", Ok("/home/someone-else"));
        let e = rt(&d, Gpus::None).start(&job).unwrap_err();
        assert!(e.contains("refusing to reuse"), "{e}");
        assert!(e.contains("/home/someone-else"), "{e}");
        assert!(
            !d.calls().iter().any(|c| c.contains("nerdctl run")),
            "{:#?}",
            d.calls()
        );
        assert!(d.calls().contains(&format!(
            "incus config device get zakuro-sandbox zakuro-mnt-{t} source"
        )));
        assert_eq!(t.len(), 16);
    }

    #[test]
    fn an_ephemeral_publish_or_a_bad_budget_is_refused_up_front() {
        let d = Arc::new(Rec::default());
        let job = StartSpec {
            publish: vec!["127.0.0.1::8888".into()],
            ..spec()
        };
        assert!(rt(&d, Gpus::None)
            .start(&job)
            .unwrap_err()
            .contains("fixed host port"));
        let bad = LxcRuntime::new(
            d.clone(),
            SANDBOX,
            DEFAULT_IMAGE,
            Err("ZAKURO_BUDGET_CPU=bad".into()),
        );
        assert_eq!(bad.start(&spec()).unwrap_err(), "ZAKURO_BUDGET_CPU=bad");
        assert!(d.calls().is_empty(), "{:#?}", d.calls());
        assert_eq!(
            parse_publish("127.0.0.1:3960:3960").unwrap(),
            Publish {
                ip: "127.0.0.1".into(),
                host: Some(3960),
                container: "3960".into(),
                proto: "tcp".into(),
            }
        );
        let p = parse_publish("8080:80/tcp").unwrap();
        assert_eq!((p.host, p.proto.as_str()), (Some(8080), "tcp"));
        assert_eq!(parse_publish("53:53/UDP").unwrap().proto, "udp");
        assert!(parse_publish("53:x/udp").is_err());
        assert!(parse_publish("a:b:c:d").is_err());
    }

    #[test]
    fn exec_stop_health_and_limits_go_through_nerdctl() {
        let d = Arc::new(Rec::default());
        d.on("incus list zakuro-sandbox", Ok("zakuro-sandbox,RUNNING"));
        let devs = format!(
            "root\nzakuro-port-tcp3960-{}\nzakuro-port-tcp4000-0000000000000000",
            tag("n1")
        );
        d.on("device list", Ok(&devs));
        d.on("inspect -f {{.State", Ok("true|2026-11-07T00:00:00Z|0"));
        d.on("cpu.max", Ok("50000 100000\n67108864\n0"));
        let r = rt(&d, Gpus::None);
        r.exec("n1", &s(&["sh", "-c", "true"]), true).unwrap();
        r.stop("n1").unwrap();
        assert!(r.health("n1").unwrap().running);
        assert_eq!(
            r.limits("n1").unwrap(),
            Limits::new(0.5, 64.0 / 1024.0, Gpus::None)
        );
        let calls = d.calls();
        assert_eq!(
            calls[0],
            "incus exec zakuro-sandbox -- nerdctl exec -d n1 sh -c true"
        );
        assert!(calls.contains(&format!(
            "incus config device remove zakuro-sandbox zakuro-port-tcp3960-{}",
            tag("n1")
        )));
        assert!(
            !calls.iter().any(|c| c.contains("zakuro-port-tcp4000")),
            "other workload's port kept"
        );
        assert!(calls.contains(&"incus exec zakuro-sandbox -- nerdctl rm -f n1".to_string()));
        // Idempotent: a gone workload or a missing sandbox is fine.
        let gone = Arc::new(Rec::default());
        gone.on("incus list", Ok("zakuro-sandbox,RUNNING"));
        gone.on(
            "rm -f",
            Err("time=... level=error msg=\"1 errors:\\nno such container: n1\""),
        );
        assert!(rt(&gone, Gpus::None).stop("n1").is_ok());
        let none = Arc::new(Rec::default());
        assert!(rt(&none, Gpus::None).stop("n1").is_ok());
        assert_eq!(none.calls().len(), 1);
        // A stopped sandbox: its proxies go, no `incus exec` (it would fail
        // with "Instance is not running"), and that is not an error.
        let stopped = Arc::new(Rec::default());
        stopped.on("incus list", Ok("zakuro-sandbox,STOPPED"));
        stopped.on("device list", Ok(&devs));
        stopped.on("incus exec", Err("Error: Instance is not running"));
        assert!(rt(&stopped, Gpus::None).stop("n1").is_ok());
        let calls = stopped.calls();
        assert!(calls.contains(&format!(
            "incus config device remove zakuro-sandbox zakuro-port-tcp3960-{}",
            tag("n1")
        )));
        assert!(
            !calls.iter().any(|c| c.starts_with("incus exec")),
            "{calls:#?}"
        );
    }

    #[test]
    fn cgroup_limits_parse_and_an_uncapped_workload_is_an_error() {
        assert_eq!(
            parse_cgroup_limits("150000 100000\n2147483648\n2").unwrap(),
            Limits::new(1.5, 2.0, Gpus::Count(2))
        );
        assert!(parse_cgroup_limits("max 100000\n1024\n0")
            .unwrap_err()
            .contains("cpu"));
        assert!(parse_cgroup_limits("1000 100000\nmax\n0")
            .unwrap_err()
            .contains("memory"));
        assert!(parse_cgroup_limits("garbage").is_err());
    }

    #[test]
    fn the_sandbox_limits_are_read_back_from_incus() {
        let d = Arc::new(Rec::default());
        d.on("limits.cpu.allowance", Ok("150ms/100ms"));
        d.on("limits.memory", Ok("2048MiB"));
        d.on("device list", Ok("root\nzakuro-gpu-all"));
        assert_eq!(
            rt(&d, Gpus::None).sandbox_limits().unwrap(),
            Limits::new(1.5, 2.0, Gpus::Count(1))
        );
        let soft = Arc::new(Rec::default());
        soft.on("limits.cpu.allowance", Ok("50%"));
        assert!(rt(&soft, Gpus::None)
            .sandbox_limits()
            .unwrap_err()
            .contains("hard cpu"));
    }

    #[test]
    fn the_probe_says_why_and_docker_takes_over_without_incus() {
        let missing = Arc::new(Rec::default());
        missing.on(
            "version",
            Err("incus is not installed (No such file or directory (os error 2))"),
        );
        let p = rt(&missing, Gpus::None).probe();
        assert!(!p.available);
        assert!(
            p.detail.contains("zakuro .deb recommends it"),
            "{}",
            p.detail
        );

        let down = Arc::new(Rec::default());
        down.on(
            "version",
            Ok("Client version: 6.0.0\nServer version: unreachable"),
        );
        let p = rt(&down, Gpus::None).probe();
        assert!(!p.available);
        assert!(p.detail.contains("incus-admin"), "{}", p.detail);

        let up = Arc::new(Rec::default());
        up.on(
            "version",
            Ok("Client version: 6.0.0\nServer version: 6.0.0"),
        );
        let p = rt(&up, Gpus::None).probe();
        assert!(p.available, "{}", p.detail);
        assert_eq!(
            p.detail,
            "incus 6.0.0, unprivileged sandbox zakuro-sandbox not created yet (created at the first start)"
        );

        // `zc doctor` on a host without Incus: Docker is chosen, and why.
        let lxc = rt(&missing, Gpus::None);
        let sel = super::super::select(&[RuntimeKind::Lxc, RuntimeKind::Docker], &|k| match k {
            RuntimeKind::Lxc => lxc.probe(),
            k => Probe {
                kind: k,
                available: true,
                detail: "docker daemon responding".into(),
            },
        });
        assert_eq!(sel.chosen, Some(RuntimeKind::Docker));
        assert!(!sel.tried[0].available);
        let host = HostResources {
            logical_cpus: 8,
            memory_bytes: Some(16 << 30),
        };
        let report = super::super::doctor_report(&sel, Ok(&Budget::default()), &host);
        assert!(
            report.contains("lxc:    skipped: incus is not installed"),
            "{report}"
        );
    }

    /// zc#512 "the sandbox enforces the budget", against a real Incus: an
    /// unprivileged sandbox sized 1 cpu / 512 MiB, containerd nested in it,
    /// and a workload under 0.5 cpu / 64 MiB that burns two cores and
    /// allocates past its memory. Its cgroup must cap cpu at half a core and
    /// OOM-kill the allocation; the sandbox must carry its own caps, have no
    /// GPU device, and refuse a GPU job. Creates and deletes its own
    /// instance (`zc-live-sandbox-<pid>`). Needs Incus and network; run with
    /// `ZC_LIVE_INCUS=1 cargo nextest run -E 'test(live_incus)' --run-ignored all`.
    #[test]
    #[ignore = "needs an Incus daemon; set ZC_LIVE_INCUS=1"]
    fn live_incus_sandbox_enforces_the_budget() {
        if std::env::var("ZC_LIVE_INCUS").ok().as_deref() != Some("1") {
            eprintln!("ZC_LIVE_INCUS != 1: skipped");
            return;
        }
        let inst = format!("zc-live-sandbox-{}", std::process::id());
        let sandbox = SandboxSize {
            limits: Limits::new(1.0, 0.5, Gpus::None),
            disk_bytes: 4 << 30,
        };
        let rt = LxcRuntime::new(
            Arc::new(IncusShell),
            &inst,
            DEFAULT_IMAGE,
            Ok(sandbox.clone()),
        );
        assert!(rt.probe().available, "{}", rt.probe().detail);
        struct Cleanup(String);
        impl Drop for Cleanup {
            fn drop(&mut self) {
                let _ = IncusShell.run(&s(&["incus", "delete", "-f", &self.0]));
            }
        }
        let _cleanup = Cleanup(inst.clone());
        let t0 = std::time::Instant::now();
        rt.ensure().expect("ensure sandbox");
        eprintln!("sandbox ready in {:?}", t0.elapsed());
        assert_eq!(rt.sandbox_limits().unwrap(), sandbox.limits);
        let inside =
            |cmd: &str| IncusShell.run(&s(&["incus", "exec", &inst, "--", "sh", "-c", cmd]));
        assert_eq!(
            inside("cat /sys/fs/cgroup/cpu.max").unwrap(),
            "100000 100000"
        );
        assert_eq!(
            inside("cat /sys/fs/cgroup/memory.max").unwrap(),
            (512 * MIB).to_string()
        );
        assert_eq!(
            inside("cat /proc/self/uid_map")
                .unwrap()
                .split_whitespace()
                .next(),
            Some("0")
        );
        assert_ne!(
            inside("cat /proc/self/uid_map")
                .unwrap()
                .split_whitespace()
                .nth(1),
            Some("0"),
            "sandbox root must not be host root"
        );

        let budget = Limits::new(0.5, 64.0 / 1024.0, Gpus::None);
        let name = "zc-live-stress".to_string();
        let spec = StartSpec {
            name: name.clone(),
            image: "docker.io/library/alpine:3.20".into(),
            network: None,
            create_network: false,
            labels: vec![("zakuro.test".into(), "stress".into())],
            mounts: vec![],
            publish: vec![],
            env: vec![],
            cmd: vec![
                "sh".into(),
                "-c".into(),
                "a=$(awk '/usage_usec/{print $2}' /sys/fs/cgroup/cpu.stat); \
                 (timeout 3 sh -c 'while :; do :; done' &); \
                 (timeout 3 sh -c 'while :; do :; done' &); sleep 3.2; \
                 b=$(awk '/usage_usec/{print $2}' /sys/fs/cgroup/cpu.stat); \
                 echo cpu_usec=$((b-a)) > /tmp/cpu; sleep 600"
                    .into(),
            ],
            limits: budget.clone(),
            remove_on_exit: false,
            hardened: true,
        };
        rt.start(&spec).expect("start");
        assert_eq!(
            rt.limits(&name).unwrap(),
            budget,
            "nerdctl applied the budget"
        );
        assert!(rt.health(&name).unwrap().running);
        std::thread::sleep(std::time::Duration::from_secs(5));
        let cpu = rt
            .exec(&name, &s(&["cat", "/tmp/cpu"]), false)
            .expect("cpu sample");
        let usec: u64 = cpu.trim().trim_start_matches("cpu_usec=").parse().unwrap();
        eprintln!("workload cpu over 3.2 s: {usec} usec");
        assert!(usec < 2_400_000, "cpu not capped: {usec} usec in 3.2 s");
        let mem = rt.exec(
            &name,
            &s(&[
                "sh",
                "-c",
                "dd if=/dev/zero of=/dev/null bs=256M count=1 2>/dev/null && echo survived",
            ]),
            false,
        );
        assert!(
            !mem.as_deref().unwrap_or("").contains("survived"),
            "memory not capped: {mem:?}"
        );
        // No opt-in: no GPU device in the sandbox, and a GPU job is refused.
        assert!(!rt
            .devices()
            .unwrap()
            .iter()
            .any(|d| d.starts_with(GPU_DEVICE)));
        let gpu = StartSpec {
            name: "zc-live-gpu".into(),
            limits: Limits::new(0.5, 0.0625, Gpus::Count(1)),
            ..spec.clone()
        };
        assert!(rt.start(&gpu).unwrap_err().contains("ZAKURO_BUDGET_GPU"));
        rt.stop(&name).unwrap();
        rt.stop(&name).unwrap();
    }
}