zc2 0.0.53

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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
//! 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";
/// What kind of job the instance hosts (`atelier`); a Space lease has none.
pub const CFG_KIND: &str = "user.zakuro.kind";
/// Set on a warm-pool instance to the golden version it was launched from.
pub const CFG_WARM: &str = "user.zakuro.warm";
/// Name prefix of a warm-pool instance (it also starts with [`JOB_PREFIX`],
/// so `incus list zk-job-` sees it; `w` is not a hex digit, so it never
/// collides with [`instance_name`]).
pub const WARM_PREFIX: &str = "zk-job-w";
/// Alias prefix of a derived image: golden + one pulled or built image.
pub const IMG_PREFIX: &str = "zk-img-";

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{}\n{}",
        lxc::NERDCTL_VERSION,
        lxc::provision_script(),
        job_egress_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 guest-side egress rules of a job instance, run INSIDE it at every
/// start (zc#593; the same approach as the Lima VM's, `lima::egress_script`,
/// verified for real there). The job container lives in the instance's own
/// network namespace behind CNI's bridge, so the rules that bound it are the
/// instance's own iptables: containers reach DNS and the internet, and not the
/// instance's host (its gateway and subnet), the host's LAN, RFC1918,
/// link-local and CGNAT ranges, the mesh subnet `10.13.13.0/24`, or the
/// instance itself. They hook CNI's `CNI-ADMIN` chain (a plain FORWARD rule
/// ends up behind CNI's accept once the first container starts) and are
/// flushed and refilled on every run, so they are idempotent. IPv6 is not
/// filtered (CNI hands containers v4 only).
///
/// `$1` is the container CIDR (nerdctl's default pool).
pub fn job_egress_script() -> String {
    "set -e; C=${1:-10.4.0.0/16}; \
     NS=$(awk '/^nameserver/{print $2}' /etc/resolv.conf /run/systemd/resolve/resolv.conf 2>/dev/null | grep -E '^[0-9.]+$' | sort -u); \
     DEV=$(ip -4 route show default | awk '{print $5; exit}'); \
     GW=$(ip -4 route show default | awk '{print $3; exit}'); \
     SUB=$( [ -n \"$DEV\" ] && ip -4 -o addr show dev $DEV | awk '{print $4; exit}' || true); \
     iptables -N ZAKURO-EGRESS 2>/dev/null || true; iptables -F ZAKURO-EGRESS; \
     iptables -A ZAKURO-EGRESS -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN; \
     for ns in $NS; do \
       iptables -A ZAKURO-EGRESS -d $ns -p udp --dport 53 -j RETURN; \
       iptables -A ZAKURO-EGRESS -d $ns -p tcp --dport 53 -j RETURN; \
     done; \
     [ -z \"$GW\" ] || iptables -A ZAKURO-EGRESS -d $GW -j REJECT; \
     [ -z \"$SUB\" ] || iptables -A ZAKURO-EGRESS -d $SUB -j REJECT; \
     iptables -A ZAKURO-EGRESS -d $C -j RETURN; \
     for r in 10.13.13.0/24 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16 100.64.0.0/10; do \
       iptables -A ZAKURO-EGRESS -d $r -j REJECT; \
     done; \
     iptables -N CNI-ADMIN 2>/dev/null || true; \
     iptables -C CNI-ADMIN -s $C -j ZAKURO-EGRESS 2>/dev/null || iptables -A CNI-ADMIN -s $C -j ZAKURO-EGRESS; \
     iptables -C FORWARD -s $C -j ZAKURO-EGRESS 2>/dev/null || iptables -I FORWARD 1 -s $C -j ZAKURO-EGRESS; \
     iptables -N ZAKURO-IN 2>/dev/null || true; iptables -F ZAKURO-IN; \
     for ns in $NS; do \
       iptables -A ZAKURO-IN -d $ns -p udp --dport 53 -j RETURN; \
       iptables -A ZAKURO-IN -d $ns -p tcp --dport 53 -j RETURN; \
     done; \
     iptables -A ZAKURO-IN -d $C -j RETURN; \
     iptables -A ZAKURO-IN -m addrtype --dst-type LOCAL -j REJECT; \
     iptables -C INPUT -s $C -j ZAKURO-IN 2>/dev/null || iptables -I INPUT 1 -s $C -j ZAKURO-IN"
        .to_string()
}

/// 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)>,
    /// Launch from this local image (a derived `zk-img-*`) instead of the
    /// golden one.
    pub image: Option<String>,
    /// Ephemeral instances delete themselves when they stop; the builder that
    /// is published as a derived image is not (it must stop first).
    pub persistent: bool,
    /// Extra instance config (`user.zakuro.kind=atelier`).
    pub config: Vec<(String, String)>,
    /// Mounts are idmapped (`shift=true`) so the instance sees the owner's
    /// files as theirs. Off only where the kernel cannot (the nested CI
    /// slot, where idmapped mounts need the initial user namespace).
    pub shift: bool,
}

impl InstanceSpec {
    /// A plain job instance from the golden image.
    pub fn new(
        job: &str,
        limits: Limits,
        disk_bytes: u64,
        gpus: Vec<String>,
        mounts: Vec<(String, String)>,
    ) -> Self {
        Self {
            job: job.to_string(),
            limits,
            disk_bytes,
            gpus,
            mounts,
            image: None,
            persistent: false,
            config: vec![],
            shift: true,
        }
    }
}

/// 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>,
    /// `user.zakuro.kind` (`atelier`).
    pub kind: Option<String>,
    /// The job this instance hosts (`user.zakuro.lease`).
    pub lease: Option<String>,
    /// Golden version of a warm-pool instance.
    pub warm: Option<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),
                kind: get(CFG_KIND).filter(|v| !v.is_empty()),
                lease: get(CFG_LEASE).filter(|v| !v.is_empty()),
                warm: get(CFG_WARM).filter(|v| !v.is_empty()),
                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())
    })
}

/// Seven hex digits that differ per call (a warm instance's name).
fn warm_suffix() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static N: AtomicU64 = AtomicU64::new(0);
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let m = format!(
        "{now}-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::Relaxed)
    );
    crate::dataset::sha256_hex(m.as_bytes())[..7].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,
    /// Warm-pool size (`ZAKURO_SANDBOX_WARM_POOL`); 0 is off.
    warm: usize,
    /// Run the pool top-up on this thread (tests).
    inline_topup: bool,
    /// Derived-image cache caps.
    cache: CacheCaps,
}

/// How much derived image the node keeps (`zk-img-*`), least recently used
/// out first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheCaps {
    pub max_images: usize,
    pub max_bytes: u64,
}

pub const DEFAULT_CACHE_IMAGES: usize = 8;
pub const DEFAULT_CACHE_BYTES: u64 = 60 << 30;

impl CacheCaps {
    /// `ZAKURO_SANDBOX_IMG_CACHE_MAX` (images), `ZAKURO_SANDBOX_IMG_CACHE_GB`.
    pub fn from_env(get: &dyn Fn(&str) -> Option<String>) -> Self {
        let n = get("ZAKURO_SANDBOX_IMG_CACHE_MAX")
            .and_then(|v| v.trim().parse::<usize>().ok())
            .unwrap_or(DEFAULT_CACHE_IMAGES);
        let gb = get("ZAKURO_SANDBOX_IMG_CACHE_GB")
            .and_then(|v| v.trim().parse::<f64>().ok())
            .filter(|g| *g >= 0.0)
            .map(|g| (g * (1u64 << 30) as f64) as u64)
            .unwrap_or(DEFAULT_CACHE_BYTES);
        Self {
            max_images: n,
            max_bytes: gb,
        }
    }
}

/// `ZAKURO_SANDBOX_WARM_POOL`: how many stopped instances to keep (default 0).
pub fn warm_pool_size(get: &dyn Fn(&str) -> Option<String>) -> usize {
    get("ZAKURO_SANDBOX_WARM_POOL")
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(0)
        .min(8)
}

/// One derived image as `incus image list -f json` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedImage {
    pub alias: String,
    pub size: u64,
    /// Last launch from it, else its upload time (RFC 3339: sorts as text).
    pub last_used: String,
    /// The golden version it was built on.
    pub golden: String,
    pub digest: String,
    pub tag: String,
    /// Built from a digest-pinned reference (never goes stale).
    pub pinned: bool,
    /// Unix seconds it was built.
    pub cached_at: u64,
}

/// Parse `incus image list -f json`: the `zk-img-*` entries.
pub fn parse_cached_images(json: &str) -> Vec<CachedImage> {
    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(json)
    else {
        return vec![];
    };
    items
        .iter()
        .filter_map(|i| {
            let alias = i
                .get("aliases")?
                .as_array()?
                .iter()
                .filter_map(|a| a.get("name")?.as_str())
                .find(|n| n.starts_with(IMG_PREFIX))?
                .to_string();
            let prop = |k: &str| {
                i.get("properties")
                    .and_then(|p| p.get(k))
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string()
            };
            let when = |k: &str| {
                i.get(k)
                    .and_then(|v| v.as_str())
                    .filter(|v| !v.starts_with("0001-"))
                    .map(str::to_string)
            };
            Some(CachedImage {
                size: i.get("size").and_then(|v| v.as_u64()).unwrap_or(0),
                last_used: when("last_used_at")
                    .or_else(|| when("uploaded_at"))
                    .or_else(|| when("created_at"))
                    .unwrap_or_default(),
                golden: prop("zakuro.golden"),
                digest: prop("zakuro.digest"),
                tag: prop("zakuro.tag"),
                pinned: prop("zakuro.pinned") == "1",
                cached_at: prop("zakuro.cached_at").parse().unwrap_or(0),
                alias,
            })
        })
        .collect()
}

/// Which images to delete so at most `caps.max_images` and `caps.max_bytes`
/// remain, least recently used first, never `keep`.
pub fn lru_victims(images: &[CachedImage], caps: CacheCaps, keep: &str) -> Vec<String> {
    let mut by_age: Vec<&CachedImage> = images.iter().collect();
    by_age.sort_by(|a, b| a.last_used.cmp(&b.last_used).then(a.alias.cmp(&b.alias)));
    let mut count = images.len();
    let mut bytes: u64 = images.iter().map(|i| i.size).sum();
    let mut out = vec![];
    for i in by_age {
        if count <= caps.max_images && bytes <= caps.max_bytes {
            break;
        }
        if i.alias == keep {
            continue;
        }
        count -= 1;
        bytes = bytes.saturating_sub(i.size);
        out.push(i.alias.clone());
    }
    out
}

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(),
            warm: 0,
            inline_topup: false,
            cache: CacheCaps {
                max_images: DEFAULT_CACHE_IMAGES,
                max_bytes: DEFAULT_CACHE_BYTES,
            },
        }
    }

    pub fn with_warm_pool(mut self, n: usize) -> Self {
        self.warm = n;
        self
    }

    pub fn with_cache_caps(mut self, c: CacheCaps) -> Self {
        self.cache = c;
        self
    }

    /// 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())
            .with_warm_pool(warm_pool_size(get))
            .with_cache_caps(CacheCaps::from_env(get))
    }

    #[cfg(test)]
    pub(crate) fn fast_for_tests(&mut self) {
        self.poll = Duration::ZERO;
        self.polls = 3;
        self.pid = 4242;
        self.inline_topup = true;
    }

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

    /// `incus <rest>` through the CLI.
    pub 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
    }

    /// The instance's config as key/value pairs: the limits, the budget share,
    /// the owner, the GPUs it holds and its job.
    fn config_pairs(&self, spec: &InstanceSpec) -> Vec<(String, String)> {
        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
        };
        let mut v: Vec<(String, String)> = lxc::sandbox_config(&limits);
        for (k, val) in [
            (CFG_BUDGET, spec.limits.budget_label()),
            (CFG_OWNER, self.pid.to_string()),
            (CFG_GPUS, spec.gpus.join(",")),
            (CFG_LEASE, spec.job.clone()),
        ] {
            v.push((k.to_string(), val));
        }
        v.extend(spec.config.iter().cloned());
        v
    }

    fn config_args(&self, spec: &InstanceSpec) -> Vec<String> {
        let mut a: Vec<String> = Vec::new();
        for (k, v) in self.config_pairs(spec) {
            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 golden = self.ensure_golden()?;
        let image = spec.image.clone().unwrap_or_else(|| golden.clone());
        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 warm = spec.image.is_none() && !spec.persistent && self.warm > 0;
        if !(warm && self.take_warm(spec, name, disk)) {
            let mut init = s(&["incus", "init", image, name]);
            if !spec.persistent {
                init.push("--ephemeral".into());
            }
            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}"),
                &format!("shift={}", spec.shift),
            ])
            .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)?;
        // Before any job container exists: a job that cannot be fenced does
        // not run (fail closed).
        self.apply_egress(name)?;
        if warm {
            self.spawn_topup();
        }
        Ok(())
    }

    /// 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")
        ))
    }

    /// Run [`job_egress_script`] inside the instance.
    pub fn apply_egress(&self, name: &str) -> Result<(), String> {
        self.run(&[
            "exec",
            name,
            "--",
            "sh",
            "-c",
            &job_egress_script(),
            "zakuro-egress",
        ])
        .map(|_| ())
        .map_err(|e| format!("egress rules in {name} failed (the job is not started): {e}"))
    }

    // ---- warm pool -------------------------------------------------------

    /// Take one stopped warm instance (launched from the current golden
    /// image) as `name` and give it this job's config. `false` when there is
    /// none or anything fails: the caller then launches cold, and a warm
    /// instance that failed half-way is deleted.
    fn take_warm(&self, spec: &InstanceSpec, name: &str, disk: u64) -> bool {
        let want = provision_version(&self.base_image);
        let Ok(all) = self.list() else {
            return false;
        };
        for w in all.iter().filter(|i| {
            i.warm.as_deref() == Some(want.as_str()) && i.status.eq_ignore_ascii_case("stopped")
        }) {
            // `rename` is the claim: of two takers only one succeeds.
            if self.run(&["rename", &w.name, name]).is_err() {
                continue;
            }
            let owner = format!("{CFG_OWNER}={}", self.pid);
            let applied = (|| {
                // Owner first, then the warm flag off: never an unowned,
                // unflagged instance the reaper could take for a leak.
                self.run(&["config", "set", name, &owner])?;
                self.run(&["config", "unset", name, CFG_WARM])?;
                for (k, v) in self.config_pairs(spec) {
                    self.run(&["config", "set", name, &format!("{k}={v}")])?;
                }
                self.run(&[
                    "config",
                    "device",
                    "set",
                    name,
                    "root",
                    &format!("size={}MiB", (disk / MIB).max(6)),
                ])?;
                Ok::<(), String>(())
            })();
            match applied {
                Ok(()) => return true,
                Err(_) => {
                    let _ = self.destroy(name);
                    return false;
                }
            }
        }
        false
    }

    fn spawn_topup(&self) {
        if self.inline_topup {
            self.topup();
        } else {
            let me = self.clone();
            let _ = std::thread::Builder::new()
                .name("sandbox-warm-pool".into())
                .spawn(move || me.topup());
        }
    }

    /// Bring the warm pool to its size: delete warm instances of an older
    /// golden version or beyond the size, create the missing ones (stopped,
    /// unprivileged + nesting, from the current golden image; limits come
    /// when a job takes one). Never builds the golden image itself.
    pub fn topup(&self) {
        static BUSY: Mutex<()> = Mutex::new(());
        let Ok(_one_at_a_time) = BUSY.try_lock() else {
            return;
        };
        let want = provision_version(&self.base_image);
        let Ok(all) = self.list() else {
            return;
        };
        let mut have = 0usize;
        for w in all.iter().filter(|i| i.warm.is_some()) {
            if w.warm.as_deref() == Some(want.as_str()) && have < self.warm {
                have += 1;
            } else {
                let _ = self.destroy(&w.name);
            }
        }
        if self.warm == 0 || have >= self.warm || self.golden_version().as_deref() != Some(&want) {
            return;
        }
        let disk = self.size.as_ref().map(|n| n.disk_bytes).unwrap_or(0);
        for _ in have..self.warm {
            let name = format!("{WARM_PREFIX}{}", warm_suffix());
            let mut init = s(&["incus", "init", GOLDEN_ALIAS, &name]);
            for (k, v) in [
                ("security.privileged", "false".to_string()),
                ("security.nesting", "true".to_string()),
                (CFG_WARM, want.clone()),
            ] {
                init.push("-c".into());
                init.push(format!("{k}={v}"));
            }
            if disk > 0 {
                init.push("-d".into());
                init.push(format!("root,size={}MiB", (disk / MIB).max(6)));
            }
            if self.cli.run(&init).is_err() {
                let _ = self.destroy(&name);
                return;
            }
        }
    }

    // ---- derived images (zk-img-*) ---------------------------------------

    /// Every derived image on this node.
    pub fn cached_images(&self) -> Vec<CachedImage> {
        self.run(&["image", "list", "-f", "json"])
            .map(|o| parse_cached_images(&o))
            .unwrap_or_default()
    }

    /// The derived image `alias` when it is usable: built on the CURRENT
    /// golden image, and (when built from a mutable tag) younger than `ttl`.
    pub fn cached_image(&self, alias: &str, ttl: Duration, now_unix: u64) -> Option<CachedImage> {
        let want = provision_version(&self.base_image);
        let hit = self
            .cached_images()
            .into_iter()
            .find(|i| i.alias == alias)?;
        let fresh = hit.pinned || now_unix.saturating_sub(hit.cached_at) <= ttl.as_secs();
        if hit.golden == want && fresh {
            Some(hit)
        } else {
            let _ = self.run(&["image", "delete", alias]);
            None
        }
    }

    /// Publish stopped instance `from` as derived image `alias`, replacing an
    /// older one of that name, then evict down to the caps (never `alias`).
    pub fn publish_derived(
        &self,
        from: &str,
        alias: &str,
        digest: &str,
        tag: &str,
        pinned: bool,
        now_unix: u64,
    ) -> Result<(), String> {
        let _ = self.run(&["image", "delete", alias]);
        self.run(&[
            "publish",
            from,
            "--alias",
            alias,
            &format!("zakuro.golden={}", provision_version(&self.base_image)),
            &format!("zakuro.digest={digest}"),
            &format!("zakuro.tag={tag}"),
            &format!("zakuro.pinned={}", u8::from(pinned)),
            &format!("zakuro.cached_at={now_unix}"),
        ])
        .map_err(|e| format!("publishing {alias} failed: {e}"))?;
        self.evict(alias);
        Ok(())
    }

    /// Delete derived images past the caps, least recently used first.
    pub fn evict(&self, keep: &str) -> Vec<String> {
        let mut gone = vec![];
        for alias in lru_victims(&self.cached_images(), self.cache, keep) {
            if self.run(&["image", "delete", &alias]).is_ok() {
                gone.push(alias);
            }
        }
        gone
    }

    /// The node's disk budget (the root disk of a job instance).
    pub fn node_disk(&self) -> Result<u64, String> {
        self.size.clone().map(|n| n.disk_bytes)
    }

    /// `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();
        // Warm-pool instances belong to the pool ([`Self::topup`]), not a job.
        for i in all.into_iter().filter(|i| i.warm.is_none()) {
            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();
        let gone = self.reap(&pid_alive, &live);
        // The pool is kept at size (and an older golden's instances dropped)
        // on the same tick.
        self.topup();
        gone
    }
}

/// 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::new(
        &run.name,
        run.limits.clone(),
        run.disk_bytes,
        picked.iter().map(|g| g.pci.clone()).collect(),
        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::new(
            job,
            Limits::new(1.5, 2.0, Gpus::None),
            10 << 30,
            gpus,
            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:?}");
        }
    }

    #[test]
    fn the_egress_script_fences_the_instance_host_the_lan_and_the_mesh() {
        let s = job_egress_script();
        // The same hook point the Lima VM uses (verified there).
        assert!(s.contains("CNI-ADMIN"), "{s}");
        assert!(s.contains("iptables -F ZAKURO-EGRESS"), "idempotent refill");
        for range in [
            "10.13.13.0/24",
            "10.0.0.0/8",
            "172.16.0.0/12",
            "192.168.0.0/16",
            "169.254.0.0/16",
            "100.64.0.0/10",
        ] {
            assert!(s.contains(range), "{range} missing");
        }
        // DNS to the instance's resolvers is let through BEFORE any reject,
        // and the gateway/subnet are rejected before the container pool.
        let dns = s.find("--dport 53 -j RETURN").unwrap();
        let first_reject = s.find("-j REJECT").unwrap();
        assert!(dns < first_reject);
        assert!(s.find("-d $GW -j REJECT").unwrap() < s.find("-d $C -j RETURN").unwrap());
        // The instance itself is not reachable from a job container either.
        assert!(s.contains("--dst-type LOCAL -j REJECT"));
        assert!(s.contains("iptables -I INPUT 1"));
        // Rules are part of the golden version: changing them rebuilds it.
        assert_ne!(provision_version("a"), provision_version("b"));
    }

    #[test]
    fn every_job_instance_gets_the_egress_rules_after_boot_and_before_any_container() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let name = eph(&rec).launch(&spec(vec![])).unwrap();
        let calls = rec.calls();
        let ready = calls
            .iter()
            .position(|c| c.contains("systemctl is-active --quiet containerd"))
            .unwrap();
        let egress = calls
            .iter()
            .position(|c| c.starts_with(&format!("incus exec {name} -- sh -c set -e; C=")))
            .unwrap_or_else(|| panic!("{calls:#?}"));
        assert!(ready < egress, "rules go in once the instance is up");
        assert!(calls[egress].ends_with("zakuro-egress"));
        live_names().lock().unwrap().remove(&name);

        // Fail closed: an instance that cannot be fenced is deleted, not run.
        let bad = Arc::new(Rec::default());
        golden_ok(&bad);
        bad.on("ZAKURO-EGRESS", Err("iptables: Operation not permitted"));
        let e = eph(&bad)
            .launch(&spec_for("zk-space-nofence", vec![]))
            .unwrap_err();
        assert!(
            e.contains("egress rules") && e.contains("not started"),
            "{e}"
        );
        assert!(bad.calls().last().unwrap().starts_with("incus delete -f"));
    }

    fn warm_json(rows: &[(&str, &str, &str)]) -> &'static str {
        let items: Vec<String> = rows
            .iter()
            .map(|(n, st, ver)| {
                format!(
                    r#"{{"name":"{n}","status":"{st}","config":{{"user.zakuro.warm":"{ver}"}}}}"#
                )
            })
            .collect();
        Box::leak(format!("[{}]", items.join(",")).into_boxed_str())
    }

    #[test]
    fn the_warm_pool_size_is_opt_in_and_bounded() {
        let g = |v: &'static str| {
            move |k: &str| (k == "ZAKURO_SANDBOX_WARM_POOL").then(|| v.to_string())
        };
        assert_eq!(warm_pool_size(&|_| None), 0, "off by default");
        assert_eq!(warm_pool_size(&g("2")), 2);
        assert_eq!(warm_pool_size(&g("junk")), 0);
        assert_eq!(warm_pool_size(&g("500")), 8, "a pool is not a fleet");
    }

    #[test]
    fn a_job_takes_a_warm_instance_instead_of_creating_one_and_the_pool_is_refilled() {
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let ver = provision_version(DEFAULT_IMAGE);
        rec.on(
            "list zk-job-",
            Ok(warm_json(&[
                ("zk-job-wold0000", "Stopped", "0123456789ab"),
                (
                    "zk-job-wnew1111",
                    "Stopped",
                    Box::leak(ver.clone().into_boxed_str()),
                ),
            ])),
        );
        let name = eph(&rec).with_warm_pool(1).launch(&spec(vec![])).unwrap();
        let calls = rec.calls();
        assert!(
            !calls
                .iter()
                .any(|c| c.starts_with("incus init") && c.contains(&name)),
            "no cold create when a warm one is there: {calls:#?}"
        );
        let pos = |n: &str| {
            calls
                .iter()
                .position(|c| c.contains(n))
                .unwrap_or_else(|| panic!("{n} missing: {calls:#?}"))
        };
        assert_eq!(
            calls[pos("incus rename")],
            format!("incus rename zk-job-wnew1111 {name}")
        );
        // The owner is set before the warm flag is cleared: never an
        // unowned, unflagged instance the reaper takes for a leak.
        assert!(pos("config set") < pos("config unset"));
        assert!(calls[pos("config set")].contains("user.zakuro.owner=4242"));
        assert!(calls[pos("config unset")].ends_with(&format!("{name} user.zakuro.warm")));
        assert!(calls
            .iter()
            .any(|c| c.contains("config set") && c.contains("limits.memory=2048MiB")));
        assert!(calls
            .iter()
            .any(|c| c.contains("config set") && c.contains("user.zakuro.lease=zk-space-abc")));
        assert!(calls
            .iter()
            .any(|c| c == &format!("incus config device set {name} root size=10240MiB")));
        assert!(pos("incus rename") < pos(&format!("incus start {name}")));
        // The pool is replenished (inline in tests): the stale-version
        // instance is dropped and the golden image is not rebuilt.
        assert!(calls.iter().any(|c| c == "incus delete -f zk-job-wold0000"));
        assert!(!calls.iter().any(|c| c.starts_with("incus publish")));
        live_names().lock().unwrap().remove(&name);
    }

    #[test]
    fn without_a_warm_instance_the_job_launches_cold_and_a_failed_take_falls_back() {
        // Pool on, none stopped: a normal create.
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on("list zk-job-", Ok("[]"));
        let name = eph(&rec).with_warm_pool(2).launch(&spec(vec![])).unwrap();
        let calls = rec.calls();
        assert!(calls.iter().any(|c| c.starts_with(&format!(
            "incus init zakuro-sandbox-base {name} --ephemeral"
        ))));
        // ... and the pool is topped up with two stopped, flagged instances.
        let ver = provision_version(DEFAULT_IMAGE);
        let warm: Vec<&String> = calls
            .iter()
            .filter(|c| c.starts_with("incus init zakuro-sandbox-base zk-job-w"))
            .collect();
        assert_eq!(warm.len(), 2, "{calls:#?}");
        assert!(warm[0].contains(&format!("-c user.zakuro.warm={ver}")));
        assert!(warm[0].contains("-c security.privileged=false -c security.nesting=true"));
        assert!(
            !warm[0].contains("--ephemeral"),
            "a stopped ephemeral instance would be deleted"
        );
        live_names().lock().unwrap().remove(&name);

        // The take fails half-way (disk cannot shrink): that instance goes,
        // the job still starts, cold.
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let ver2 = Box::leak(ver.into_boxed_str());
        rec.on(
            "list zk-job-",
            Ok(warm_json(&[("zk-job-wnew2222", "Stopped", ver2)])),
        );
        rec.on("device set", Err("cannot shrink"));
        let name = eph(&rec)
            .with_warm_pool(1)
            .launch(&spec_for("zk-space-two", vec![]))
            .unwrap();
        let calls = rec.calls();
        assert!(
            calls.iter().any(|c| c.starts_with(&format!(
                "incus init zakuro-sandbox-base {name} --ephemeral"
            ))),
            "{calls:#?}"
        );
        live_names().lock().unwrap().remove(&name);

        // Off: no listing of the pool, no rename.
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        let name = eph(&rec)
            .launch(&spec_for("zk-space-three", vec![]))
            .unwrap();
        assert!(!rec
            .calls()
            .iter()
            .any(|c| c.contains("rename") || c.contains("zk-job-w")));
        live_names().lock().unwrap().remove(&name);
    }

    #[test]
    fn the_pool_is_kept_at_size_and_the_reaper_never_takes_a_warm_instance_for_a_leak() {
        let ver = provision_version(DEFAULT_IMAGE);
        let ver: &'static str = Box::leak(ver.into_boxed_str());
        let rec = Arc::new(Rec::default());
        golden_ok(&rec);
        rec.on(
            "list zk-job-",
            Ok(warm_json(&[
                ("zk-job-wa000000", "Stopped", ver),
                ("zk-job-wb000000", "Stopped", ver),
                ("zk-job-wc000000", "Stopped", "0123456789ab"),
            ])),
        );
        let e = eph(&rec).with_warm_pool(1);
        // The reaper (no owner pid on a warm instance) leaves them alone.
        assert!(e.reap(&|_| false, &HashSet::new()).is_empty());
        assert!(!rec.calls().iter().any(|c| c.contains("delete")));
        // The pool tick drops the stale and the surplus.
        e.topup();
        let calls = rec.calls();
        assert!(
            calls.contains(&"incus delete -f zk-job-wb000000".to_string()),
            "{calls:#?}"
        );
        assert!(calls.contains(&"incus delete -f zk-job-wc000000".to_string()));
        assert!(!calls.contains(&"incus delete -f zk-job-wa000000".to_string()));
        assert!(
            !calls.iter().any(|c| c.starts_with("incus init")),
            "already at size"
        );
        // Pool turned off: every warm instance goes.
        let off = Arc::new(Rec::default());
        golden_ok(&off);
        off.on(
            "list zk-job-",
            Ok(warm_json(&[("zk-job-wa000000", "Stopped", ver)])),
        );
        eph(&off).topup();
        assert!(off
            .calls()
            .contains(&"incus delete -f zk-job-wa000000".to_string()));
    }

    fn image_row(alias: &str, size: u64, used: &str) -> CachedImage {
        CachedImage {
            alias: alias.into(),
            size,
            last_used: used.into(),
            golden: "g".into(),
            digest: String::new(),
            tag: String::new(),
            pinned: true,
            cached_at: 0,
        }
    }

    #[test]
    fn the_derived_image_cache_evicts_least_recently_used_by_count_and_by_bytes() {
        let imgs = vec![
            image_row("zk-img-a", 10 << 30, "2026-11-01T00:00:00Z"),
            image_row("zk-img-b", 10 << 30, "2026-11-03T00:00:00Z"),
            image_row("zk-img-c", 10 << 30, "2026-11-02T00:00:00Z"),
        ];
        let caps = |n, gb: u64| CacheCaps {
            max_images: n,
            max_bytes: gb << 30,
        };
        assert!(
            lru_victims(&imgs, caps(3, 30), "").is_empty(),
            "at the caps is fine"
        );
        assert_eq!(lru_victims(&imgs, caps(2, 100), ""), vec!["zk-img-a"]);
        assert_eq!(
            lru_victims(&imgs, caps(8, 15), ""),
            vec!["zk-img-a", "zk-img-c"]
        );
        // The image just built is never its own victim.
        assert_eq!(
            lru_victims(&imgs, caps(2, 100), "zk-img-a"),
            vec!["zk-img-c"]
        );
        assert_eq!(
            lru_victims(&imgs, caps(0, 0), "zk-img-b"),
            vec!["zk-img-a", "zk-img-c"]
        );
    }

    #[test]
    fn derived_images_are_listed_from_incus_json_and_published_then_evicted() {
        let json = r#"[
          {"size":100,"last_used_at":"0001-01-01T00:00:00Z","uploaded_at":"2026-11-05T01:00:00Z",
           "aliases":[{"name":"zk-img-aaaaaaaaaaaa"}],
           "properties":{"zakuro.golden":"g1","zakuro.digest":"sha256:d","zakuro.tag":"r:t","zakuro.pinned":"1","zakuro.cached_at":"77"}},
          {"size":5,"aliases":[{"name":"zakuro-sandbox-base"}],"properties":{}}
        ]"#;
        let got = parse_cached_images(json);
        assert_eq!(got.len(), 1, "only zk-img-* images");
        assert_eq!(got[0].alias, "zk-img-aaaaaaaaaaaa");
        assert_eq!(
            got[0].last_used, "2026-11-05T01:00:00Z",
            "never launched: upload time"
        );
        assert!(got[0].pinned && got[0].cached_at == 77 && got[0].digest == "sha256:d");
        assert!(parse_cached_images("not json").is_empty());

        let rec = Arc::new(Rec::default());
        rec.on(
            "image list -f json",
            Ok(Box::leak(
                r#"[{"size":1,"last_used_at":"2026-11-01T00:00:00Z","aliases":[{"name":"zk-img-old"}],"properties":{}},
                    {"size":1,"last_used_at":"2026-11-09T00:00:00Z","aliases":[{"name":"zk-img-new"}],"properties":{}}]"#
                    .to_string()
                    .into_boxed_str(),
            )),
        );
        let e = eph(&rec).with_cache_caps(CacheCaps {
            max_images: 1,
            max_bytes: 1 << 30,
        });
        e.publish_derived("b", "zk-img-new", "sha256:d", "r:t", true, 9)
            .unwrap();
        let calls = rec.calls();
        let publish = calls
            .iter()
            .position(|c| c.starts_with("incus publish b --alias zk-img-new"))
            .unwrap();
        assert!(calls[publish].contains("zakuro.golden="));
        assert!(
            calls
                .iter()
                .position(|c| c == "incus image delete zk-img-old")
                .unwrap()
                > publish
        );
        assert!(!calls.iter().any(|c| c == "incus image delete zk-img-new"
            && calls.iter().position(|x| x == c).unwrap() > publish));
    }

    #[test]
    fn cache_caps_read_the_environment() {
        let get = |k: &str| match k {
            "ZAKURO_SANDBOX_IMG_CACHE_MAX" => Some("3".to_string()),
            "ZAKURO_SANDBOX_IMG_CACHE_GB" => Some("1.5".to_string()),
            _ => None,
        };
        assert_eq!(
            CacheCaps::from_env(&get),
            CacheCaps {
                max_images: 3,
                max_bytes: 3 << 29
            }
        );
        assert_eq!(
            CacheCaps::from_env(&|_| None),
            CacheCaps {
                max_images: DEFAULT_CACHE_IMAGES,
                max_bytes: DEFAULT_CACHE_BYTES
            }
        );
    }

    /// 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::new(
                &job,
                limits.clone(),
                5 << 30,
                vec![],
                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));

        // Egress default-deny (zc#593): a listener on this machine, which is
        // the instance's gateway, is reachable from the instance itself and
        // not from a job container in it; the internet and DNS work.
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = std::net::TcpListener::bind("0.0.0.0:0").expect("listener");
        let port = listener.local_addr().unwrap().port();
        let hits = Arc::new(AtomicUsize::new(0));
        let h2 = hits.clone();
        std::thread::spawn(move || {
            for c in listener.incoming().flatten() {
                h2.fetch_add(1, Ordering::SeqCst);
                drop(c);
            }
        });
        let gw = e
            .run(&[
                "exec",
                &name,
                "--",
                "sh",
                "-c",
                "ip -4 route show default | awk '{print $3; exit}'",
            ])
            .expect("gateway");
        let bb = "docker.io/library/busybox:latest";
        let from_instance = e.run(&[
            "exec",
            &name,
            "--",
            "bash",
            "-c",
            &format!("timeout 5 bash -c 'exec 3<>/dev/tcp/{gw}/{port}'"),
        ]);
        println!(
            "REAL egress: instance -> {gw}:{port} {}",
            if from_instance.is_ok() {
                "reachable"
            } else {
                "BLOCKED"
            }
        );
        assert!(
            from_instance.is_ok(),
            "the instance reaches its host: {from_instance:?}"
        );
        let before = hits.load(Ordering::SeqCst);
        assert!(before >= 1, "the listener saw the instance");
        let nc = |target: &str, p: &str| {
            e.nerdctl(
                &name,
                &s(&[
                    "run",
                    "--rm",
                    bb,
                    "sh",
                    "-c",
                    &format!("nc -w 4 {target} {p} </dev/null"),
                ]),
            )
        };
        let to_gw = nc(&gw, &port.to_string());
        println!(
            "REAL egress: job container -> {gw}:{port} {}",
            if to_gw.is_ok() {
                "REACHABLE"
            } else {
                "blocked"
            }
        );
        assert!(
            to_gw.is_err(),
            "a job container must not reach the instance's host"
        );
        assert_eq!(
            hits.load(Ordering::SeqCst),
            before,
            "the listener saw no job traffic"
        );
        for lan in ["10.13.13.1", "192.168.1.1", "169.254.169.254"] {
            let r = nc(lan, "80");
            println!(
                "REAL egress: job container -> {lan}:80 {}",
                if r.is_ok() { "REACHABLE" } else { "blocked" }
            );
            assert!(r.is_err(), "{lan} must be unreachable");
        }
        // Control: with the rules flushed the same container reaches the same
        // listener, so the block above comes from the rules and nothing else.
        e.run(&[
            "exec",
            &name,
            "--",
            "sh",
            "-c",
            "iptables -F ZAKURO-EGRESS; iptables -F ZAKURO-IN",
        ])
        .expect("flush");
        let open = nc(&gw, &port.to_string());
        println!(
            "REAL egress control (rules flushed): job container -> {gw}:{port} {}",
            if open.is_ok() { "reachable" } else { "BLOCKED" }
        );
        assert!(open.is_ok(), "without the rules it connects: {open:?}");
        assert!(hits.load(Ordering::SeqCst) > before);
        e.apply_egress(&name).expect("re-apply");
        let again = nc(&gw, &port.to_string());
        println!(
            "REAL egress re-applied: job container -> {gw}:{port} {}",
            if again.is_ok() {
                "REACHABLE"
            } else {
                "blocked"
            }
        );
        assert!(again.is_err());
        let net = nc("1.1.1.1", "443");
        println!(
            "REAL egress: job container -> 1.1.1.1:443 {}",
            if net.is_ok() { "reachable" } else { "BLOCKED" }
        );
        assert!(net.is_ok(), "the internet works: {net:?}");
        let dns = e.nerdctl(&name, &s(&["run", "--rm", bb, "nslookup", "example.com"]));
        println!(
            "REAL egress: job container DNS example.com {}",
            if dns.is_ok() { "resolves" } else { "FAILS" }
        );
        assert!(dns.is_ok(), "DNS works: {dns:?}");

        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));
    }
}