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
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
//! Tier 2 of the isolation ladder (zc#578): one EPHEMERAL Incus/LXD instance
//! per foreign job, cloned from a golden image and destroyed when the job
//! ends, with the container the job runs inside it under nerdctl.
//!
//! ```text
//! T0  host process            the owner's own work only
//! T1  shared sandbox          `zakuro-sandbox`, one long-lived unprivileged
//!                             instance, a container per workload (deployments,
//!                             share workers)                         lxc.rs
//! T2  per-job sandbox         `zk-job-<id>`, ephemeral, from the golden image
//!                             `zakuro-sandbox-base`; default for Spaces leases
//! ```
//!
//! The instance carries the job's ADMITTED limits (`limits.cpu`,
//! `limits.memory`, root disk), so what the job can take is bounded by the
//! boundary itself, and the container inside is again capped (a little under
//! the boundary, so the instance's own daemons cannot starve it). The budget
//! share is recorded on the instance (`user.zakuro.budget`), which is how
//! admission sums it back ([`Ephemeral::allocations`]) the same way it sums
//! labelled Docker containers. The owner pid and the GPUs it holds are
//! recorded too, so the reaper can tell a leaked instance from a live one and
//! two jobs never share a GPU.
//!
//! Every Incus/LXD call goes through [`IncusCli`], so a fake drives each path
//! here; `tests::real` (ignored, `ZAKURO_TEST_REAL_INCUS=1`) drives the real
//! thing.

use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use super::lxc::{self, IncusCli, SandboxSize};
use super::{docker, Allocation, Gpus, Limits, StartSpec};

/// Name prefix of every per-job instance; the reaper only ever touches these.
pub const JOB_PREFIX: &str = "zk-job-";
/// The local image every job instance is cloned from.
pub const GOLDEN_ALIAS: &str = "zakuro-sandbox-base";
/// The scratch instance the golden image is built in.
pub const BUILD_INSTANCE: &str = "zk-golden-build";
/// Image property holding the provisioning version the image was built from.
pub const PROVISION_PROP: &str = "zakuro.provision";
/// Instance config keys.
pub const CFG_BUDGET: &str = "user.zakuro.budget";
pub const CFG_OWNER: &str = "user.zakuro.owner";
pub const CFG_GPUS: &str = "user.zakuro.gpus";
pub const CFG_LEASE: &str = "user.zakuro.lease";

const MIB: u64 = 1024 * 1024;
/// What the instance's own systemd, containerd and nerdctl are allowed to
/// take out of the boundary before the job container's share starts.
const OVERHEAD_BYTES: u64 = 256 * MIB;

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

/// The provisioning version: changes when the provisioning script, the pinned
/// nerdctl or the base image does, which is what makes the golden image
/// rebuild itself.
pub fn provision_version(base_image: &str) -> String {
    let material = format!(
        "{base_image}\n{}\n{}",
        lxc::NERDCTL_VERSION,
        lxc::provision_script()
    );
    crate::dataset::sha256_hex(material.as_bytes())[..12].to_string()
}

/// `zk-job-<8 hex>` for a job's container name: deterministic, short, and a
/// valid instance name whatever the job name holds.
pub fn instance_name(job: &str) -> String {
    format!(
        "{JOB_PREFIX}{}",
        &crate::dataset::sha256_hex(job.as_bytes())[..8]
    )
}

/// The limits the container inside the instance runs under: the instance's
/// own, less [`OVERHEAD_BYTES`] of memory (three quarters on a tiny instance),
/// so an instance whose daemons grew cannot OOM-kill the job it hosts.
pub fn inner_limits(l: &Limits, gpu_attached: bool) -> Limits {
    let memory_bytes = if l.memory_bytes > 3 * OVERHEAD_BYTES {
        l.memory_bytes - OVERHEAD_BYTES
    } else {
        (l.memory_bytes / 4 * 3).max(super::MIN_MEMORY_BYTES)
    };
    Limits {
        cpu_millis: l.cpu_millis,
        memory_bytes,
        gpus: if gpu_attached { Gpus::All } else { Gpus::None },
    }
}

/// One NVIDIA GPU as `nvidia-smi` lists it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GpuInfo {
    pub index: u32,
    pub uuid: String,
    /// `0000:01:00.0`, the form Incus' `pci=` takes.
    pub pci: String,
}

/// `00000000:01:00.0` (nvidia-smi) to `0000:01:00.0` (sysfs, Incus).
pub fn normalize_pci(addr: &str) -> String {
    let a = addr.trim().to_ascii_lowercase();
    match a.split_once(':') {
        Some((domain, rest)) if domain.len() > 4 => {
            format!("{}:{rest}", &domain[domain.len() - 4..])
        }
        _ => a,
    }
}

/// `nvidia-smi --query-gpu=index,uuid,pci.bus_id --format=csv,noheader`.
pub fn parse_nvidia_smi(out: &str) -> Vec<GpuInfo> {
    out.lines()
        .filter_map(|l| {
            let mut f = l.split(',').map(str::trim);
            let index = f.next()?.parse().ok()?;
            let uuid = f.next()?.to_string();
            let pci = normalize_pci(f.next()?);
            (!uuid.is_empty() && !pci.is_empty()).then_some(GpuInfo { index, uuid, pci })
        })
        .collect()
}

/// Which GPUs a job gets: `want` resolved against what the node has (`all`)
/// and what other job instances already hold (`taken`, as PCI addresses).
/// One job per GPU: a GPU in `taken` is never handed out twice. A UUID,
/// index or PCI pin resolves to the card, so `device=GPU-<uuid>` (which
/// Incus' `id=` cannot express) works.
pub fn pick_gpus(
    want: &Gpus,
    all: &[GpuInfo],
    taken: &HashSet<String>,
) -> Result<Vec<GpuInfo>, String> {
    let free: Vec<&GpuInfo> = all.iter().filter(|g| !taken.contains(&g.pci)).collect();
    let by_id = |id: &str| -> Result<GpuInfo, String> {
        let hit = all.iter().find(|g| {
            g.uuid.eq_ignore_ascii_case(id)
                || g.pci == normalize_pci(id)
                || id.parse::<u32>().ok() == Some(g.index)
        });
        let g = hit.ok_or_else(|| format!("no GPU {id:?} on this node"))?;
        if taken.contains(&g.pci) {
            return Err(format!("GPU {id:?} is held by another job"));
        }
        Ok(g.clone())
    };
    let n_free = |n: usize| -> Result<Vec<GpuInfo>, String> {
        if free.len() < n {
            return Err(format!(
                "asks for {n} GPU(s), {} free of {} (one job per GPU)",
                free.len(),
                all.len()
            ));
        }
        Ok(free.iter().take(n).map(|g| (*g).clone()).collect())
    };
    match want {
        Gpus::None | Gpus::Count(0) => Ok(vec![]),
        Gpus::All => {
            if all.is_empty() {
                return Err("asks for GPUs but this node has none".into());
            }
            n_free(all.len())
        }
        Gpus::Count(n) => n_free(*n as usize),
        Gpus::Spec(spec) => {
            let v = spec.trim().trim_matches('"').trim();
            if v == "all" {
                return pick_gpus(&Gpus::All, all, taken);
            }
            if let Ok(n) = v.parse::<u32>() {
                // A bare number is a count here, as for `docker --gpus 2`.
                return n_free(n as usize);
            }
            let ids = v.strip_prefix("device=").unwrap_or(v);
            let mut out: Vec<GpuInfo> = Vec::new();
            for id in ids.split(',').map(str::trim).filter(|i| !i.is_empty()) {
                let g = by_id(id)?;
                if !out.contains(&g) {
                    out.push(g);
                }
            }
            if out.is_empty() {
                return Err(format!("GPU spec {spec:?} names no GPU"));
            }
            Ok(out)
        }
    }
}

/// The docker `config.json` that logs in to `registry` as `user`, for a
/// fresh instance: written on the host (mode 0600 by the caller) and pushed
/// into the instance, so the credential never reaches an argv.
pub fn docker_config_json(registry: &str, user: &str, password: &str) -> String {
    use base64::Engine as _;
    let key = match registry {
        "docker.io" | "index.docker.io" | "registry-1.docker.io" => {
            "https://index.docker.io/v1/".to_string()
        }
        r => r.to_string(),
    };
    let auth = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}"));
    serde_json::json!({ "auths": { key: { "auth": auth } } }).to_string()
}

/// What one job instance needs.
#[derive(Debug, Clone)]
pub struct InstanceSpec {
    /// The job's container name; the instance name derives from it.
    pub job: String,
    /// The admitted limits (the instance's boundary).
    pub limits: Limits,
    pub disk_bytes: u64,
    /// PCI addresses of the GPUs to attach (already picked).
    pub gpus: Vec<String>,
    /// `(host path, path inside the instance)`.
    pub mounts: Vec<(String, String)>,
}

/// One `zk-job-*` instance as listed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobInstance {
    pub name: String,
    pub status: String,
    pub owner_pid: Option<u32>,
    pub budget: Option<String>,
    pub gpus: Vec<String>,
}

/// Parse `incus list zk-job- -f json`.
pub fn parse_job_instances(json: &str) -> Vec<JobInstance> {
    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(json)
    else {
        return vec![];
    };
    items
        .iter()
        .filter_map(|i| {
            let name = i.get("name")?.as_str()?.to_string();
            if !name.starts_with(JOB_PREFIX) {
                return None;
            }
            let cfg = i.get("config");
            let get = |k: &str| {
                cfg.and_then(|c| c.get(k))
                    .and_then(|v| v.as_str())
                    .map(str::to_string)
            };
            Some(JobInstance {
                status: i
                    .get("status")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                owner_pid: get(CFG_OWNER).and_then(|p| p.parse().ok()),
                budget: get(CFG_BUDGET),
                gpus: get(CFG_GPUS)
                    .map(|g| {
                        g.split(',')
                            .filter(|x| !x.is_empty())
                            .map(str::to_string)
                            .collect()
                    })
                    .unwrap_or_default(),
                name,
            })
        })
        .collect()
}

/// First IPv4 of `incus list NAME -f csv -c 4` (`10.1.2.3 (eth0)`).
pub fn parse_ipv4(csv: &str) -> Option<String> {
    csv.split(['\n', '"']).map(str::trim).find_map(|l| {
        let ip = l.split_whitespace().next()?;
        (ip.split('.').count() == 4 && ip.split('.').all(|o| o.parse::<u8>().is_ok()))
            .then(|| ip.to_string())
    })
}

/// Names of instances this process is launching or running, so the reaper
/// never deletes one under a job that is still starting.
fn live_names() -> &'static Mutex<HashSet<String>> {
    static LIVE: std::sync::OnceLock<Mutex<HashSet<String>>> = std::sync::OnceLock::new();
    LIVE.get_or_init(|| Mutex::new(HashSet::new()))
}

#[cfg(unix)]
fn pid_alive(pid: u32) -> bool {
    // SAFETY: `kill(pid, 0)` sends no signal; it only checks existence.
    let rc = unsafe { libc::kill(pid as libc::pid_t, 0) };
    rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
fn pid_alive(_pid: u32) -> bool {
    true
}

/// The per-job instance manager.
#[derive(Clone)]
pub struct Ephemeral {
    cli: Arc<dyn IncusCli>,
    base_image: String,
    size: Result<SandboxSize, String>,
    /// Pause between readiness polls (zero in tests).
    poll: Duration,
    /// Readiness polls before a started instance is declared broken.
    polls: u32,
    /// The pid recorded as owner (tests pin it).
    pid: u32,
}

impl Ephemeral {
    pub fn new(
        cli: Arc<dyn IncusCli>,
        base_image: &str,
        size: Result<SandboxSize, String>,
    ) -> Self {
        Self {
            cli,
            base_image: base_image.to_string(),
            size,
            poll: Duration::from_secs(1),
            polls: 90,
            pid: std::process::id(),
        }
    }

    /// Against the real CLI, sized from the node budget in the environment.
    pub fn from_env(get: &dyn Fn(&str) -> Option<String>) -> Self {
        let rt = lxc::LxcRuntime::from_env(Arc::new(lxc::IncusShell), get);
        Self::new(Arc::new(lxc::IncusShell), rt.image(), rt.size().clone())
    }

    #[cfg(test)]
    fn fast(mut self) -> Self {
        self.poll = Duration::ZERO;
        self.polls = 3;
        self.pid = 4242;
        self
    }

    fn run(&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)
    }

    /// The golden image's alias, ready: built when absent or built from an
    /// older provisioning version. Serialised across processes, and idempotent
    /// (a second caller finds the image the first one built).
    pub fn ensure_golden(&self) -> Result<String, String> {
        let want = provision_version(&self.base_image);
        if self.golden_version().as_deref() == Some(want.as_str()) {
            return Ok(GOLDEN_ALIAS.to_string());
        }
        let _guard = super::lock::provision_lock(Duration::from_secs(900))?;
        if self.golden_version().as_deref() == Some(want.as_str()) {
            return Ok(GOLDEN_ALIAS.to_string());
        }
        self.build_golden(&want)?;
        Ok(GOLDEN_ALIAS.to_string())
    }

    fn golden_version(&self) -> Option<String> {
        self.run(&["image", "get-property", GOLDEN_ALIAS, PROVISION_PROP])
            .ok()
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
    }

    fn build_golden(&self, version: &str) -> Result<(), String> {
        let b = BUILD_INSTANCE;
        // A leftover from a crashed build, and the stale image, go first.
        let _ = self.run(&["delete", "-f", b]);
        let _ = self.run(&["image", "delete", GOLDEN_ALIAS]);
        self.run(&[
            "launch",
            &self.base_image,
            b,
            "-c",
            "security.privileged=false",
            "-c",
            "security.nesting=true",
        ])
        .map_err(|e| format!("golden image: launching {b} failed: {e}"))?;
        let built = (|| {
            self.run(&["exec", b, "--", "sh", "-c", &lxc::provision_script()])
                .map_err(|e| format!("provisioning containerd in {b} failed: {e}"))?;
            // Keep the image small and the first boot of every job clean.
            let _ = self.run(&[
                "exec",
                b,
                "--",
                "sh",
                "-c",
                "apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/*",
            ]);
            self.run(&["stop", b])
                .map_err(|e| format!("stopping {b} failed: {e}"))?;
            self.run(&[
                "publish",
                b,
                "--alias",
                GOLDEN_ALIAS,
                &format!("{PROVISION_PROP}={version}"),
            ])
            .map_err(|e| format!("publishing {GOLDEN_ALIAS} failed: {e}"))?;
            Ok::<(), String>(())
        })();
        let _ = self.run(&["delete", "-f", b]);
        built
    }

    fn config_args(&self, spec: &InstanceSpec) -> Vec<String> {
        let mut a: Vec<String> = Vec::new();
        let mut limits = spec.limits.clone();
        // The boundary passes a GPU through only when one was picked.
        limits.gpus = if spec.gpus.is_empty() {
            Gpus::None
        } else {
            Gpus::All
        };
        for (k, v) in lxc::sandbox_config(&limits) {
            a.push("-c".into());
            a.push(format!("{k}={v}"));
        }
        for (k, v) in [
            (CFG_BUDGET, spec.limits.budget_label()),
            (CFG_OWNER, self.pid.to_string()),
            (CFG_GPUS, spec.gpus.join(",")),
            (CFG_LEASE, spec.job.clone()),
        ] {
            a.push("-c".into());
            a.push(format!("{k}={v}"));
        }
        a
    }

    /// Create and start the job's instance. Returns its name; on any failure
    /// the instance is deleted again, so a refused start leaves nothing.
    pub fn launch(&self, spec: &InstanceSpec) -> Result<String, String> {
        // `size` is the whole-node sizing: its error (an invalid budget) means
        // nothing may start, exactly as for the shared sandbox.
        let node = self.size.clone()?;
        let image = self.ensure_golden()?;
        let name = instance_name(&spec.job);
        live_names().lock().unwrap().insert(name.clone());
        let r = self.launch_inner(spec, &image, &name, node.disk_bytes);
        if r.is_err() {
            let _ = self.destroy(&name);
        }
        r.map(|_| name)
    }

    fn launch_inner(
        &self,
        spec: &InstanceSpec,
        image: &str,
        name: &str,
        node_disk: u64,
    ) -> Result<(), String> {
        let disk = spec.disk_bytes.min(node_disk).max(1 << 30);
        // A name left by an earlier run of the same job is stale by definition.
        let _ = self.run(&["delete", "-f", name]);
        let mut init = s(&["incus", "init", image, name, "--ephemeral"]);
        init.extend(self.config_args(spec));
        init.push("-d".into());
        init.push(format!("root,size={}MiB", (disk / MIB).max(6)));
        self.cli
            .run(&init)
            .map_err(|e| format!("incus init {name} failed: {e}"))?;
        for (i, pci) in spec.gpus.iter().enumerate() {
            self.run(&[
                "config",
                "device",
                "add",
                name,
                &format!("zakuro-gpu-{i}"),
                "gpu",
                "gputype=physical",
                &format!("pci={pci}"),
            ])
            .map_err(|e| format!("attaching GPU {pci} to {name} failed: {e}"))?;
        }
        for (i, (host, inner)) in spec.mounts.iter().enumerate() {
            self.run(&[
                "config",
                "device",
                "add",
                name,
                &format!("zakuro-mnt-{i}"),
                "disk",
                &format!("source={host}"),
                &format!("path={inner}"),
                "shift=true",
            ])
            .map_err(|e| format!("mounting {host} into {name} failed: {e}"))?;
        }
        self.run(&["start", name])
            .map_err(|e| format!("incus start {name} failed: {e}"))?;
        self.wait_ready(name)
    }

    /// containerd up inside the fresh instance (its first boot).
    fn wait_ready(&self, name: &str) -> Result<(), String> {
        let mut last = String::new();
        for _ in 0..self.polls {
            match self.run(&[
                "exec",
                name,
                "--",
                "sh",
                "-c",
                "systemctl is-active --quiet containerd && nerdctl version >/dev/null 2>&1",
            ]) {
                Ok(_) => return Ok(()),
                Err(e) => last = e,
            }
            if !self.poll.is_zero() {
                std::thread::sleep(self.poll);
            }
        }
        Err(format!(
            "{name} did not become ready (containerd): {}",
            last.lines().next().unwrap_or("no answer")
        ))
    }

    /// `incus exec NAME -- nerdctl <docker args>`.
    pub fn exec_argv(name: &str, docker_args: &[String]) -> Vec<String> {
        let mut a = s(&["incus", "exec", name, "--", "nerdctl"]);
        let rest = match docker_args.first().map(String::as_str) {
            Some("docker") => &docker_args[1..],
            _ => docker_args,
        };
        a.extend(rest.iter().cloned());
        a
    }

    /// Run `docker args` (as nerdctl) inside instance `name`.
    pub fn nerdctl(&self, name: &str, docker_args: &[String]) -> Result<String, String> {
        self.cli.run(&Self::exec_argv(name, docker_args))
    }

    /// Put a docker `config.json` in the instance's `~/.docker`.
    pub fn push_docker_config(
        &self,
        name: &str,
        host_file: &std::path::Path,
    ) -> Result<(), String> {
        self.run(&[
            "file",
            "push",
            "--create-dirs",
            "--mode",
            "0600",
            &host_file.display().to_string(),
            &format!("{name}/root/.docker/config.json"),
        ])
        .map(|_| ())
    }

    /// The container the job runs, started inside instance `name` from
    /// `spec` (mounts already mapped to the instance's paths): the same
    /// `run_argv` flags as every other path, with the inner limits.
    pub fn run_container(&self, name: &str, spec: &StartSpec) -> Result<String, String> {
        let mut run = vec!["docker".to_string()];
        run.extend(docker::run_argv(spec));
        self.nerdctl(name, &run)
    }

    /// Delete the instance (stop first: it is ephemeral, so stopping already
    /// deletes it; `delete -f` covers a half-created one). Idempotent.
    pub fn destroy(&self, name: &str) -> Result<(), String> {
        live_names().lock().unwrap().remove(name);
        match self.run(&["delete", "-f", name]) {
            Ok(_) => Ok(()),
            Err(e)
                if e.contains("not found")
                    || e.contains("Not Found")
                    || e.contains("does not exist") =>
            {
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    pub fn list(&self) -> Result<Vec<JobInstance>, String> {
        let out = self.run(&["list", JOB_PREFIX, "-f", "json"])?;
        Ok(parse_job_instances(&out))
    }

    /// Every job instance's share of the node budget.
    pub fn allocations(&self) -> Result<Vec<Allocation>, String> {
        Ok(self
            .list()?
            .iter()
            .filter_map(|i| Allocation::from_label(&i.name, i.budget.as_deref()?))
            .collect())
    }

    /// PCI addresses held by running job instances.
    pub fn taken_gpus(&self) -> Result<HashSet<String>, String> {
        Ok(self.list()?.into_iter().flat_map(|i| i.gpus).collect())
    }

    /// The instance's bridge address: reachable from the host.
    pub fn address(&self, name: &str) -> Option<String> {
        parse_ipv4(&self.run(&["list", name, "-f", "csv", "-c", "4"]).ok()?)
    }

    /// Delete every `zk-job-*` instance no live job owns: its owner process is
    /// gone, it has no owner at all, or this process owns it but is not
    /// running it (`live`). Returns the names removed.
    pub fn reap(&self, alive: &dyn Fn(u32) -> bool, live: &HashSet<String>) -> Vec<String> {
        let Ok(all) = self.list() else {
            return vec![];
        };
        let mut gone = Vec::new();
        for i in all {
            let orphan = match i.owner_pid {
                None => true,
                Some(p) if p == self.pid => !live.contains(&i.name),
                Some(p) => !alive(p),
            };
            if orphan && self.destroy(&i.name).is_ok() {
                gone.push(i.name);
            }
        }
        gone
    }

    /// [`Self::reap`] with the real process table and this process's jobs.
    pub fn reap_leaked(&self) -> Vec<String> {
        let live = live_names().lock().unwrap().clone();
        self.reap(&pid_alive, &live)
    }
}

/// The container id a per-job start returns: it names the instance too, so
/// every later call (stop, inspect, logs) finds the boundary from the id alone.
pub const JOB_ID_PREFIX: &str = "t2:";

pub fn job_id(instance: &str, container: &str) -> String {
    format!("{JOB_ID_PREFIX}{instance}/{container}")
}

/// `t2:<instance>/<container>` back to `(instance, container)`.
pub fn parse_job_id(id: &str) -> Option<(&str, &str)> {
    let (inst, name) = id.strip_prefix(JOB_ID_PREFIX)?.split_once('/')?;
    (!inst.is_empty() && !name.is_empty()).then_some((inst, name))
}

/// What one per-job start runs.
#[derive(Debug, Clone)]
pub struct JobRun {
    /// The container's name (and what the instance name derives from).
    pub name: String,
    pub image: String,
    pub labels: Vec<(String, String)>,
    /// `(host path, container path)`.
    pub mounts: Vec<(String, String)>,
    pub env: Vec<(String, String)>,
    pub cmd: Vec<String>,
    /// The ADMITTED limits: the instance's boundary.
    pub limits: Limits,
    pub disk_bytes: u64,
    pub hardened: bool,
    /// A host dir holding a docker `config.json` to pull with.
    pub pull_config: Option<std::path::PathBuf>,
}

/// `nvidia-smi` as the GPU picker reads it.
pub fn real_nvidia_smi() -> Result<String, String> {
    let out = std::process::Command::new("nvidia-smi")
        .args(["--query-gpu=index,uuid,pci.bus_id", "--format=csv,noheader"])
        .output()
        .map_err(|e| format!("nvidia-smi not available: {e}"))?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).to_string())
    } else {
        Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
    }
}

/// Start a job in its own instance: pick its GPUs (one job per GPU), launch
/// the instance with the admitted limits, pull the image inside it, run the
/// container under the inner limits. Returns the `t2:` container id. Any
/// failure after the instance exists deletes it again.
pub fn start_job(
    eph: &Ephemeral,
    run: &JobRun,
    nvidia_smi: &dyn Fn() -> Result<String, String>,
) -> Result<String, String> {
    let picked = if run.limits.gpus.flag_value().is_some() {
        let all = parse_nvidia_smi(&nvidia_smi()?);
        pick_gpus(&run.limits.gpus, &all, &eph.taken_gpus()?)
            .map_err(|e| format!("{}: {e}", run.name))?
    } else {
        vec![]
    };
    let mut inner_mounts = Vec::new();
    let mut inst_mounts = Vec::new();
    for (host, container) in &run.mounts {
        let at = format!(
            "/zakuro/mnt/{}",
            &crate::dataset::sha256_hex(host.as_bytes())[..16]
        );
        inst_mounts.push((host.clone(), at.clone()));
        inner_mounts.push((at, container.clone()));
    }
    let instance = eph.launch(&InstanceSpec {
        job: run.name.clone(),
        limits: run.limits.clone(),
        disk_bytes: run.disk_bytes,
        gpus: picked.iter().map(|g| g.pci.clone()).collect(),
        mounts: inst_mounts,
    })?;
    let started = (|| {
        if let Some(dir) = &run.pull_config {
            let f = dir.join("config.json");
            if f.exists() {
                eph.push_docker_config(&instance, &f)?;
            }
        }
        eph.nerdctl(&instance, &s(&["pull", "--quiet", &run.image]))
            .map_err(|e| format!("pull {} failed: {e}", run.image))?;
        eph.run_container(
            &instance,
            &StartSpec {
                name: run.name.clone(),
                image: run.image.clone(),
                network: None,
                create_network: false,
                labels: run.labels.clone(),
                mounts: inner_mounts,
                publish: vec![],
                env: run.env.clone(),
                cmd: run.cmd.clone(),
                limits: inner_limits(&run.limits, !picked.is_empty()),
                remove_on_exit: false,
                hardened: run.hardened,
            },
        )
    })();
    match started {
        Ok(_) => Ok(job_id(&instance, &run.name)),
        Err(e) => {
            let _ = eph.destroy(&instance);
            Err(e)
        }
    }
}

/// How often the background reaper runs.
pub const REAP_EVERY: Duration = Duration::from_secs(120);

/// Start the periodic reaper once per process (the first T2 start calls it;
/// that start also reaps at once, so a restart cleans up after a crash).
pub fn start_reaper_once(eph: &Ephemeral) {
    static STARTED: std::sync::Once = std::sync::Once::new();
    let eph = eph.clone();
    let first = eph.clone();
    STARTED.call_once(move || {
        for n in first.reap_leaked() {
            eprintln!("  [SANDBOX] removed leaked job instance {n}");
        }
        let _ = std::thread::Builder::new()
            .name("sandbox-reaper".into())
            .spawn(move || loop {
                std::thread::sleep(REAP_EVERY);
                for n in eph.reap_leaked() {
                    eprintln!("  [SANDBOX] removed leaked job instance {n}");
                }
            });
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sandbox::lxc::DEFAULT_IMAGE;

    #[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 eph(rec: &Arc<Rec>) -> Ephemeral {
        Ephemeral::new(
            rec.clone(),
            DEFAULT_IMAGE,
            Ok(SandboxSize {
                limits: Limits::new(8.0, 16.0, Gpus::None),
                disk_bytes: 20 << 30,
            }),
        )
        .fast()
    }

    fn spec(gpus: Vec<String>) -> InstanceSpec {
        spec_for("zk-space-abc", gpus)
    }

    fn spec_for(job: &str, gpus: Vec<String>) -> InstanceSpec {
        InstanceSpec {
            job: job.into(),
            limits: Limits::new(1.5, 2.0, Gpus::None),
            disk_bytes: 10 << 30,
            gpus,
            mounts: vec![(
                "/home/u/.zakuro/spaces/abc.sock".into(),
                "/zakuro/sock".into(),
            )],
        }
    }

    fn golden_ok(rec: &Rec) {
        rec.on(
            "image get-property zakuro-sandbox-base",
            Ok(Box::leak(provision_version(DEFAULT_IMAGE).into_boxed_str())),
        );
    }

    #[test]
    fn a_job_instance_is_ephemeral_limited_and_owned() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let name = eph(&rec).launch(&spec(vec![])).unwrap();
        assert_eq!(name, instance_name("zk-space-abc"));
        assert!(name.starts_with("zk-job-") && name.len() == 15, "{name}");
        let calls = rec.calls();
        let init = calls.iter().find(|c| c.starts_with("incus init")).unwrap();
        assert_eq!(
            init,
            &format!(
                "incus init zakuro-sandbox-base {name} --ephemeral \
                 -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 \
                 -c user.zakuro.budget=1500m,2147483648 -c user.zakuro.owner=4242 \
                 -c user.zakuro.gpus= -c user.zakuro.lease=zk-space-abc -d root,size=10240MiB"
            )
        );
        // The job's directory is a disk device, added before the start.
        let mnt = calls
            .iter()
            .position(|c| c.contains("zakuro-mnt-0"))
            .unwrap();
        let start = calls
            .iter()
            .position(|c| c == &format!("incus start {name}"))
            .unwrap();
        assert!(mnt < start, "{calls:#?}");
        assert!(calls[mnt]
            .contains("source=/home/u/.zakuro/spaces/abc.sock path=/zakuro/sock shift=true"));
        assert!(!calls.iter().any(|c| c.contains(" gpu ")), "no GPU unasked");
        assert!(calls
            .iter()
            .any(|c| c.contains("systemctl is-active --quiet containerd")));
        live_names().lock().unwrap().remove(&name);
    }

    #[test]
    fn a_picked_gpu_is_attached_by_pci_address_and_enables_the_nvidia_runtime() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let name = eph(&rec)
            .launch(&spec(vec!["0000:01:00.0".into()]))
            .unwrap();
        let calls = rec.calls();
        assert!(calls.iter().any(|c| c
            == &format!(
                "incus config device add {name} zakuro-gpu-0 gpu gputype=physical pci=0000:01:00.0"
            )));
        let init = calls.iter().find(|c| c.starts_with("incus init")).unwrap();
        assert!(init.contains("-c nvidia.runtime=true"), "{init}");
        assert!(init.contains("-c user.zakuro.gpus=0000:01:00.0"), "{init}");
        live_names().lock().unwrap().remove(&name);
    }

    #[test]
    fn a_failed_start_deletes_the_instance_and_says_why() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on("incus start", Err("no space left on device"));
        let e = eph(&rec)
            .launch(&spec_for("zk-space-fail", vec![]))
            .unwrap_err();
        assert!(
            e.contains("incus start") && e.contains("no space left"),
            "{e}"
        );
        let calls = rec.calls();
        assert!(
            calls.last().unwrap().starts_with("incus delete -f zk-job-"),
            "{calls:#?}"
        );
        assert!(!live_names()
            .lock()
            .unwrap()
            .contains(&instance_name("zk-space-fail")));
    }

    #[test]
    fn an_instance_that_never_gets_containerd_is_deleted() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on("systemctl is-active", Err("Failed to connect to bus"));
        let e = eph(&rec).launch(&spec(vec![])).unwrap_err();
        assert!(e.contains("did not become ready"), "{e}");
        assert!(rec.calls().last().unwrap().starts_with("incus delete -f"));
    }

    #[test]
    fn an_invalid_budget_refuses_every_instance() {
        let rec = Arc::new(Rec::default());
        let e = Ephemeral::new(
            rec.clone(),
            DEFAULT_IMAGE,
            Err("ZAKURO_BUDGET_CPU=bad".into()),
        )
        .launch(&spec(vec![]))
        .unwrap_err();
        assert_eq!(e, "ZAKURO_BUDGET_CPU=bad");
        assert!(rec.calls().is_empty());
    }

    #[test]
    fn the_golden_image_is_built_once_from_the_provisioning_and_versioned() {
        let rec = Arc::new(Rec::default());
        rec.on("image get-property", Err("Image not found"));
        eph(&rec).ensure_golden().unwrap();
        let calls = rec.calls();
        let ver = provision_version(DEFAULT_IMAGE);
        let pos = |needle: &str| {
            calls
                .iter()
                .position(|c| c.contains(needle))
                .unwrap_or_else(|| panic!("{needle} missing in {calls:#?}"))
        };
        assert!(pos("incus launch images:ubuntu/24.04 zk-golden-build") < pos("sh -c set -e;"));
        assert!(calls[pos("sh -c set -e;")].contains("sha256sum -c"));
        assert!(pos("sh -c set -e;") < pos("incus stop zk-golden-build"));
        assert_eq!(
            calls[pos("incus publish")],
            format!(
                "incus publish zk-golden-build --alias zakuro-sandbox-base zakuro.provision={ver}"
            )
        );
        assert!(calls.last().unwrap() == "incus delete -f zk-golden-build");
    }

    #[test]
    fn a_current_golden_image_is_reused_and_an_old_one_rebuilt() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        eph(&rec).ensure_golden().unwrap();
        assert_eq!(rec.calls().len(), 1, "{:#?}", rec.calls());
        let old = Arc::new(Rec::default());
        old.on("image get-property", Ok("0123456789ab"));
        eph(&old).ensure_golden().unwrap();
        assert!(old
            .calls()
            .iter()
            .any(|c| c == "incus image delete zakuro-sandbox-base"));
        assert!(old.calls().iter().any(|c| c.starts_with("incus publish")));
        // Another base image is another version.
        assert_ne!(
            provision_version("images:debian/12"),
            provision_version(DEFAULT_IMAGE)
        );
    }

    #[test]
    fn a_failed_golden_build_leaves_no_scratch_instance() {
        let rec = Arc::new(Rec::default());
        rec.on("image get-property", Err("not found"));
        rec.on("sha256sum", Err("curl: (6) Could not resolve host"));
        let e = eph(&rec).ensure_golden().unwrap_err();
        assert!(e.contains("provisioning containerd"), "{e}");
        assert_eq!(
            rec.calls().last().unwrap(),
            "incus delete -f zk-golden-build"
        );
        assert!(!rec.calls().iter().any(|c| c.starts_with("incus publish")));
    }

    #[test]
    fn the_inner_container_is_capped_below_the_boundary() {
        let l = Limits::new(2.0, 4.0, Gpus::None);
        let i = inner_limits(&l, false);
        assert_eq!(i.cpu_millis, 2000);
        assert_eq!(i.memory_bytes, 4 * 1024 * MIB - 256 * MIB);
        let tiny = inner_limits(&Limits::new(1.0, 0.5, Gpus::None), true);
        assert_eq!(tiny.memory_bytes, 384 * MIB);
        assert_eq!(tiny.gpus, Gpus::All);
    }

    #[test]
    fn allocations_come_from_the_instances_own_budget_key() {
        let rec = Arc::new(Rec::default());
        rec.on(
            "list zk-job- -f json",
            Ok(r#"[{"name":"zk-job-aaaaaaaa","status":"Running","config":{"user.zakuro.budget":"1500m,2147483648","user.zakuro.owner":"7","user.zakuro.gpus":"0000:01:00.0,0000:02:00.0"}},
                   {"name":"zk-job-bbbbbbbb","status":"Running","config":{}},
                   {"name":"other","status":"Running","config":{"user.zakuro.budget":"1m,1"}}]"#),
        );
        let e = eph(&rec);
        assert_eq!(
            e.allocations().unwrap(),
            vec![Allocation {
                name: "zk-job-aaaaaaaa".into(),
                cpu_millis: 1500,
                memory_bytes: 2 << 30
            }]
        );
        assert_eq!(
            e.taken_gpus().unwrap(),
            HashSet::from(["0000:01:00.0".to_string(), "0000:02:00.0".to_string()])
        );
    }

    #[test]
    fn the_reaper_removes_dead_owners_and_unowned_but_not_live_jobs() {
        let rec = Arc::new(Rec::default());
        rec.on(
            "list zk-job- -f json",
            Ok(r#"[{"name":"zk-job-dead0000","status":"Running","config":{"user.zakuro.owner":"111"}},
                   {"name":"zk-job-live1111","status":"Running","config":{"user.zakuro.owner":"222"}},
                   {"name":"zk-job-mine2222","status":"Running","config":{"user.zakuro.owner":"4242"}},
                   {"name":"zk-job-mine3333","status":"Running","config":{"user.zakuro.owner":"4242"}},
                   {"name":"zk-job-noown444","status":"Stopped","config":{}}]"#),
        );
        let e = eph(&rec);
        let live = HashSet::from(["zk-job-mine2222".to_string()]);
        let gone = e.reap(&|p| p == 222, &live);
        assert_eq!(
            gone,
            vec!["zk-job-dead0000", "zk-job-mine3333", "zk-job-noown444"]
        );
        let calls = rec.calls();
        assert!(!calls
            .iter()
            .any(|c| c.contains("delete -f zk-job-live1111")));
        assert!(!calls
            .iter()
            .any(|c| c.contains("delete -f zk-job-mine2222")));
    }

    #[test]
    fn destroying_a_gone_instance_is_not_an_error() {
        let rec = Arc::new(Rec::default());
        rec.on("incus delete", Err("Instance not found"));
        assert!(eph(&rec).destroy("zk-job-x").is_ok());
        let rec = Arc::new(Rec::default());
        rec.on("incus delete", Err("permission denied"));
        assert!(eph(&rec).destroy("zk-job-x").is_err());
    }

    fn gpus() -> Vec<GpuInfo> {
        parse_nvidia_smi("0, GPU-aaaa-1111, 00000000:01:00.0\n1, GPU-bbbb-2222, 00000000:41:00.0\n")
    }

    #[test]
    fn nvidia_smi_output_gives_index_uuid_and_a_sysfs_pci_address() {
        let g = gpus();
        assert_eq!(g.len(), 2);
        assert_eq!(g[1].pci, "0000:41:00.0");
        assert_eq!(g[0].uuid, "GPU-aaaa-1111");
        assert!(parse_nvidia_smi("garbage\n,,\n").is_empty());
    }

    #[test]
    fn a_uuid_pin_resolves_to_its_card_and_one_job_gets_one_gpu() {
        let g = gpus();
        let none = HashSet::new();
        let one = pick_gpus(&Gpus::Spec("device=GPU-bbbb-2222".into()), &g, &none).unwrap();
        assert_eq!(one.len(), 1);
        assert_eq!(one[0].pci, "0000:41:00.0");
        let by_index = pick_gpus(&Gpus::Spec("device=0".into()), &g, &none).unwrap();
        assert_eq!(by_index[0].uuid, "GPU-aaaa-1111");
        // A count takes free cards only.
        let taken = HashSet::from(["0000:01:00.0".to_string()]);
        let c = pick_gpus(&Gpus::Count(1), &g, &taken).unwrap();
        assert_eq!(c[0].pci, "0000:41:00.0");
        assert!(pick_gpus(&Gpus::Count(2), &g, &taken)
            .unwrap_err()
            .contains("one job per GPU"));
        // A pinned card another job holds is refused, never shared.
        assert!(pick_gpus(&Gpus::Spec("device=0".into()), &g, &taken)
            .unwrap_err()
            .contains("held by another job"));
        assert!(pick_gpus(&Gpus::Spec("device=GPU-nope".into()), &g, &none).is_err());
        assert!(pick_gpus(&Gpus::None, &g, &none).unwrap().is_empty());
        assert_eq!(pick_gpus(&Gpus::All, &g, &none).unwrap().len(), 2);
        assert!(pick_gpus(&Gpus::All, &[], &none).is_err());
    }

    #[test]
    fn the_registry_login_is_a_docker_config_not_an_argv() {
        let j = docker_config_json("docker.io", "zak", "s3cret");
        let v: serde_json::Value = serde_json::from_str(&j).unwrap();
        let auth = v["auths"]["https://index.docker.io/v1/"]["auth"]
            .as_str()
            .unwrap();
        use base64::Engine as _;
        assert_eq!(
            base64::engine::general_purpose::STANDARD
                .decode(auth)
                .unwrap(),
            b"zak:s3cret"
        );
        let r = docker_config_json("registry.example.com", "u", "p");
        assert!(r.contains("registry.example.com"));
        let rec = Arc::new(Rec::default());
        eph(&rec)
            .push_docker_config("zk-job-1", std::path::Path::new("/tmp/cfg/config.json"))
            .unwrap();
        let c = rec.calls().pop().unwrap();
        assert_eq!(
            c,
            "incus file push --create-dirs --mode 0600 /tmp/cfg/config.json zk-job-1/root/.docker/config.json"
        );
    }

    #[test]
    fn instance_addresses_and_names() {
        assert_eq!(
            parse_ipv4("10.20.30.4 (eth0)\nfd42::1 (eth0)"),
            Some("10.20.30.4".into())
        );
        assert_eq!(
            parse_ipv4("\"10.0.0.9 (eth0)\n172.17.0.1 (docker0)\""),
            Some("10.0.0.9".into())
        );
        assert_eq!(parse_ipv4(""), None);
        assert_eq!(instance_name("a"), instance_name("a"));
        assert_ne!(instance_name("a"), instance_name("b"));
    }

    #[test]
    fn the_container_runs_under_nerdctl_in_its_instance_with_the_same_flags() {
        let rec = Arc::new(Rec::default());
        let e = eph(&rec);
        let spec = StartSpec {
            name: "zk-space-abc".into(),
            image: "img@sha256:ab".into(),
            network: None,
            create_network: false,
            labels: vec![],
            mounts: vec![("/zakuro/sock".into(), "/run/zakuro/space.sock".into())],
            publish: vec![],
            env: vec![],
            cmd: vec![],
            limits: inner_limits(&Limits::new(1.0, 2.0, Gpus::None), false),
            remove_on_exit: false,
            hardened: true,
        };
        e.run_container("zk-job-1", &spec).unwrap();
        let c = rec.calls().pop().unwrap();
        assert!(
            c.starts_with("incus exec zk-job-1 -- nerdctl run -d --name zk-space-abc"),
            "{c}"
        );
        assert!(c.contains("--cpus 1 --memory 1792m"), "{c}");
        assert!(
            c.contains("--pids-limit 4096 --security-opt no-new-privileges"),
            "{c}"
        );
    }

    #[test]
    fn a_job_start_pulls_inside_runs_capped_and_returns_a_routable_id() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let run = JobRun {
            name: "zk-space-run1".into(),
            image: "reg.example.com/space@sha256:ab".into(),
            labels: vec![("zakuro.space".into(), "s1".into())],
            mounts: vec![("/h/s1.sock".into(), "/run/zakuro/space.sock".into())],
            env: vec![("ZAKURO_SPACE_ID".into(), "s1".into())],
            cmd: vec![],
            limits: Limits::new(1.0, 2.0, Gpus::None),
            disk_bytes: 5 << 30,
            hardened: true,
            pull_config: Some(std::path::PathBuf::from("/nonexistent-cfg")),
        };
        let id = start_job(&eph(&rec), &run, &|| Err("no gpus asked".into())).unwrap();
        let (inst, name) = parse_job_id(&id).unwrap();
        assert_eq!(
            (inst, name),
            (instance_name("zk-space-run1").as_str(), "zk-space-run1")
        );
        let calls = rec.calls();
        let pull = calls
            .iter()
            .position(|c| c.contains("nerdctl pull --quiet reg.example.com/space@sha256:ab"))
            .unwrap();
        let run_at = calls
            .iter()
            .position(|c| c.contains("nerdctl run -d --name zk-space-run1"))
            .unwrap();
        assert!(pull < run_at, "{calls:#?}");
        let r = &calls[run_at];
        assert!(r.contains("--cpus 1 --memory 1792m"), "{r}");
        assert!(r.contains("--pids-limit 4096"), "{r}");
        assert!(!r.contains("--gpus"), "{r}");
        assert!(r.contains("-v /zakuro/mnt/"), "{r}");
        assert!(r.contains(":/run/zakuro/space.sock"), "{r}");
        live_names().lock().unwrap().remove(inst);
    }

    #[test]
    fn a_pull_that_fails_inside_deletes_the_instance() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on("nerdctl pull", Err("manifest unknown"));
        let run = JobRun {
            name: "zk-space-pullfail".into(),
            image: "img".into(),
            labels: vec![],
            mounts: vec![],
            env: vec![],
            cmd: vec![],
            limits: Limits::new(1.0, 1.0, Gpus::None),
            disk_bytes: 5 << 30,
            hardened: true,
            pull_config: None,
        };
        let e = start_job(&eph(&rec), &run, &|| Err(String::new())).unwrap_err();
        assert!(e.contains("pull img failed: manifest unknown"), "{e}");
        assert!(rec
            .calls()
            .last()
            .unwrap()
            .starts_with("incus delete -f zk-job-"));
    }

    #[test]
    fn a_gpu_job_gets_a_free_card_by_pci_and_a_refusal_when_none_is_free() {
        let smi =
            || Ok("0, GPU-aaaa, 00000000:01:00.0\n1, GPU-bbbb, 00000000:41:00.0\n".to_string());
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on(
            "list zk-job- -f json",
            Ok(r#"[{"name":"zk-job-other000","status":"Running","config":{"user.zakuro.gpus":"0000:01:00.0","user.zakuro.owner":"1"}}]"#),
        );
        let mut run = JobRun {
            name: "zk-space-gpu1".into(),
            image: "img".into(),
            labels: vec![],
            mounts: vec![],
            env: vec![],
            cmd: vec![],
            limits: Limits::new(1.0, 2.0, Gpus::Spec("device=GPU-bbbb".into())),
            disk_bytes: 5 << 30,
            hardened: true,
            pull_config: None,
        };
        let id = start_job(&eph(&rec), &run, &smi).unwrap();
        let calls = rec.calls();
        assert!(
            calls
                .iter()
                .any(|c| c.contains("gputype=physical pci=0000:41:00.0")),
            "{calls:#?}"
        );
        assert!(calls
            .iter()
            .any(|c| c.contains("nerdctl run") && c.contains("--gpus all")));
        live_names()
            .lock()
            .unwrap()
            .remove(parse_job_id(&id).unwrap().0);
        // The card another job holds is refused, and nothing is launched.
        run.name = "zk-space-gpu2".into();
        run.limits = Limits::new(1.0, 2.0, Gpus::Spec("device=0".into()));
        let before = rec.calls().len();
        let e = start_job(&eph(&rec), &run, &smi).unwrap_err();
        assert!(e.contains("held by another job"), "{e}");
        assert!(!rec.calls()[before..]
            .iter()
            .any(|c| c.starts_with("incus init")));
    }

    #[test]
    fn job_ids_round_trip_and_plain_ids_are_not_jobs() {
        let id = job_id("zk-job-abcd1234", "zk-space-x");
        assert_eq!(parse_job_id(&id), Some(("zk-job-abcd1234", "zk-space-x")));
        for plain in ["abc123", "t2:", "t2:/x", "t2:i/", ""] {
            assert_eq!(parse_job_id(plain), None, "{plain:?}");
        }
    }

    /// The real thing: needs Incus (or LXD) on the machine, root-equivalent
    /// access to it and network. `ZAKURO_TEST_REAL_INCUS=1 cargo test -p zc2
    /// real_incus -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn real_incus_job_instance_end_to_end() {
        if std::env::var("ZAKURO_TEST_REAL_INCUS").ok().as_deref() != Some("1") {
            eprintln!("skipped: set ZAKURO_TEST_REAL_INCUS=1");
            return;
        }
        let cli: Arc<dyn IncusCli> = Arc::new(lxc::IncusShell);
        let image = std::env::var("ZAKURO_SANDBOX_IMAGE")
            .unwrap_or_else(|_| lxc::default_image(lxc::cli_binary()).to_string());
        let e = Ephemeral::new(
            cli.clone(),
            &image,
            Ok(SandboxSize {
                limits: Limits::new(2.0, 4.0, Gpus::None),
                disk_bytes: 10 << 30,
            }),
        );
        let t = std::time::Instant::now();
        e.ensure_golden().expect("golden image");
        println!("REAL golden image ready in {:?}", t.elapsed());
        let job = format!("zk-real-{}", std::process::id());
        let limits = Limits::new(1.0, 1.0, Gpus::None);
        let name = e
            .launch(&InstanceSpec {
                job: job.clone(),
                limits: limits.clone(),
                disk_bytes: 5 << 30,
                gpus: vec![],
                mounts: vec![],
            })
            .expect("launch");
        println!("REAL instance {name} running");
        let inner = inner_limits(&limits, false);
        let spec = StartSpec {
            name: "real-job".into(),
            image: "docker.io/library/busybox:latest".into(),
            network: None,
            create_network: false,
            labels: vec![],
            mounts: vec![],
            publish: vec![],
            env: vec![],
            cmd: vec!["sleep".into(), "120".into()],
            limits: inner.clone(),
            remove_on_exit: false,
            hardened: true,
        };
        e.nerdctl(&name, &s(&["pull", "--quiet", &spec.image]))
            .expect("pull inside");
        e.run_container(&name, &spec).expect("run container");
        let cg = e
            .nerdctl(
                &name,
                &s(&[
                    "exec",
                    "real-job",
                    "sh",
                    "-c",
                    "cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.max",
                ]),
            )
            .expect("read cgroup");
        let read = lxc::parse_cgroup_limits(&cg).expect("limits are set");
        println!("REAL container limits read back from inside: {read}");
        assert_eq!(read.cpu_millis, inner.cpu_millis);
        assert_eq!(read.memory_bytes, inner.memory_bytes);
        let inst_mem = e.run(&["config", "get", &name, "limits.memory"]).unwrap();
        println!("REAL instance limits.memory={inst_mem}");
        assert_eq!(inst_mem.trim(), "1024MiB");
        let out = e
            .nerdctl(
                &name,
                &s(&[
                    "run",
                    "--rm",
                    "docker.io/library/busybox:latest",
                    "echo",
                    "hello-from-t2",
                ]),
            )
            .expect("echo");
        println!("REAL echo: {out}");
        assert!(out.contains("hello-from-t2"));
        assert!(e.allocations().unwrap().iter().any(|a| a.name == name));

        e.destroy(&name).expect("destroy");
        assert!(!e.list().unwrap().iter().any(|i| i.name == name));
        println!("REAL instance {name} gone after destroy");

        // A leaked instance (owner pid long dead) is reaped.
        let leaked = format!("{JOB_PREFIX}leak{:04}", std::process::id() % 10000);
        e.run(&[
            "init",
            GOLDEN_ALIAS,
            &leaked,
            "--ephemeral",
            "-c",
            "user.zakuro.owner=2147483646",
            "-c",
            "user.zakuro.budget=1000m,1073741824",
        ])
        .expect("create leaked");
        assert!(e.list().unwrap().iter().any(|i| i.name == leaked));
        let gone = e.reap_leaked();
        println!("REAL reaper removed {gone:?}");
        assert!(gone.contains(&leaked));
        assert!(!e.list().unwrap().iter().any(|i| i.name == leaked));
    }
}