oomtop-core 0.2.0

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
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
//! Containers, local Kubernetes and VM slack (SPEC §8.3, §11). Pure: inputs come from the snapshot
//! (processes and their cgroup paths, `Snapshot::cgroups`, sandboxes) and from the adapters
//! ([`Isolation::containers`] from the container engines, [`Isolation::kube`] / [`Isolation::kube_contexts`]
//! from the optional Kubernetes adapter); [`IsolationTracker::update`] derives everything else:
//!
//! - **cluster tree** node → namespace → pod → container ([`Cluster`]), merged from three sources, each
//!   optional: kubelet cgroup paths (Linux, [`crate::attribution::parse_kube_cgroup`]: QoS, pod UID, full
//!   container id, per-pod/container memory from cgroup files), engine labels (`io.kubernetes.*` from
//!   cri-dockerd, kind / k3d / minikube node containers) and the API server (names, limits, restarts, last
//!   termination reason, kubelet working sets);
//! - **per-limit forecast** ([`crate::limits`]) for every container, pod, cgroup and engine VM with a limit;
//! - **VM slack** ([`VmSlack`]): host footprint of an engine VM minus what its containers use — memory held
//!   by the VM, not by any container. An estimate, never counted as safe reclaim;
//! - **namespace sets** ([`crate::namespaces`]);
//! - **stale containers** ([`StaleContainer`]): running with ~0 CPU over the observed window, or stopped
//!   and still holding a writable layer. Data only; scoring is `crate::staleness`'s job.

use crate::attribution::{parse_cgroup, parse_kube_cgroup, CgroupScope, KubeCgroup, QosClass};
use crate::limits::{evaluate, CgroupMem, LimitInput, LimitKind, LimitStatus, LimitTarget, LimitTracker};
use crate::measured::sum_bytes;
use crate::model::{Measured, ProcId, SandboxKind, Snapshot, SourceStatus};
use crate::namespaces::{namespace_sets, NamespaceReport};
use crate::units::{format_bytes, UnitSystem};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Engine label keys kept in [`ContainerInfo::labels`] (everything else is dropped: labels are free-form
/// and may carry anything).
pub const LABEL_PREFIXES: &[&str] = &[
    "io.kubernetes.",
    "io.x-k8s.kind.",
    "k3d.cluster",
    "k3d.role",
    "name.minikube.sigs.k8s.io",
    "role.minikube.sigs.k8s.io",
    "mode.minikube.sigs.k8s.io",
    "com.docker.compose.project",
    "com.docker.compose.service",
];

/// Whether an engine label is kept (see [`LABEL_PREFIXES`]).
pub fn keep_label(key: &str) -> bool {
    LABEL_PREFIXES.iter().any(|p| key.starts_with(p))
}

/// The sentence of every [`VmSlack`] finding.
pub const VM_SLACK_SENTENCE: &str =
    "held by the VM, not used by containers; restarting the engine returns it";
/// Slack below `max(this, 10 % of the VM footprint)` is not reported (guest kernel and engine overhead).
pub const VM_SLACK_MIN_BYTES: u64 = 256 << 20;
/// A running container is "idle" below this average CPU (percent of one core) …
pub const STALE_CPU_PCT: f64 = 0.5;
/// … observed over at least this long.
pub const STALE_MIN_OBSERVED_S: u64 = 120;

// ---------------------------------------------------------------------------------------------------------
// Inputs (filled by the adapters)
// ---------------------------------------------------------------------------------------------------------

/// What a container engine (Docker API: Docker, Docker Desktop, OrbStack, Colima, Rancher Desktop, Podman)
/// reports about one container, running or not. Running containers are also [`crate::model::Sandbox`]es
/// with the same `sandbox_id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ContainerInfo {
    /// `<runtime>:<12 hex>`, as [`crate::model::Sandbox::id`].
    pub sandbox_id: String,
    /// Full container id.
    pub id: String,
    /// Engine runtime ("docker", "docker-desktop", "orbstack", "colima", "rancher-desktop", "podman").
    pub engine: String,
    /// The engine runs containers inside a VM (its host cost is the VM's).
    pub vm_hosted: bool,
    pub name: String,
    pub image: String,
    /// "running" | "exited" | "created" | "paused" | "restarting" | "dead".
    pub state: String,
    /// Engine status text ("Up 3 hours", "Exited (137) 2 days ago").
    pub status_text: String,
    pub created_ms: Option<u64>,
    pub started_ms: Option<u64>,
    pub finished_ms: Option<u64>,
    pub exit_code: Option<i64>,
    /// `State.OOMKilled`: the container's last run ended in a kernel OOM kill.
    pub oom_killed: Option<bool>,
    pub restart_count: Option<u32>,
    /// Cumulative CPU time (`cpu_stats.cpu_usage.total_usage`, ns) and when it was read.
    pub cpu_total_ns: Option<u64>,
    pub stats_at_ms: Option<u64>,
    /// Writable layer / whole filesystem size, only when the engine reported them (`size=1` listings).
    pub size_rw: Option<u64>,
    pub size_root_fs: Option<u64>,
    /// Allowlisted labels only ([`LABEL_PREFIXES`]).
    pub labels: BTreeMap<String, String>,
}

/// A local Kubernetes distribution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum KubeDistro {
    Kind,
    Minikube,
    K3d,
    K3s,
    DockerDesktop,
    #[serde(rename = "orbstack")]
    OrbStack,
    RancherDesktop,
    Colima,
    Microk8s,
    #[default]
    Unknown,
}

impl KubeDistro {
    pub fn title(self) -> &'static str {
        match self {
            KubeDistro::Kind => "kind",
            KubeDistro::Minikube => "minikube",
            KubeDistro::K3d => "k3d",
            KubeDistro::K3s => "k3s",
            KubeDistro::DockerDesktop => "Docker Desktop",
            KubeDistro::OrbStack => "OrbStack",
            KubeDistro::RancherDesktop => "Rancher Desktop",
            KubeDistro::Colima => "Colima",
            KubeDistro::Microk8s => "MicroK8s",
            KubeDistro::Unknown => "Kubernetes",
        }
    }

    /// The distribution a kubeconfig context name implies, by the names the tools write
    /// (`kind-<name>`, `k3d-<name>`, `minikube`, `docker-desktop`, `orbstack`, `rancher-desktop`, `colima`,
    /// `microk8s`).
    pub fn from_context(name: &str) -> Option<KubeDistro> {
        Some(match name {
            n if n.starts_with("kind-") => KubeDistro::Kind,
            n if n.starts_with("k3d-") => KubeDistro::K3d,
            "minikube" => KubeDistro::Minikube,
            "docker-desktop" | "docker-for-desktop" => KubeDistro::DockerDesktop,
            "orbstack" => KubeDistro::OrbStack,
            "rancher-desktop" => KubeDistro::RancherDesktop,
            n if n == "colima" || n.starts_with("colima-") => KubeDistro::Colima,
            "microk8s" => KubeDistro::Microk8s,
            _ => return None,
        })
    }

    /// Cluster name inside its distribution for a context name (`kind-dev` → `dev`).
    pub fn cluster_name_from_context(self, ctx: &str) -> String {
        match self {
            KubeDistro::Kind => ctx.strip_prefix("kind-").unwrap_or(ctx).to_string(),
            KubeDistro::K3d => ctx.strip_prefix("k3d-").unwrap_or(ctx).to_string(),
            KubeDistro::Colima => ctx.strip_prefix("colima-").unwrap_or("default").to_string(),
            _ => ctx.to_string(),
        }
    }
}

/// One kubeconfig context as the Kubernetes adapter judged it (SPEC §13 kube safety rules). Refused
/// contexts never carry their server URL.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContextSummary {
    pub name: String,
    pub current: bool,
    pub distro: Option<KubeDistro>,
    /// The server is loopback (literal 127.0.0.0/8, ::1, `localhost`, `*.localhost`).
    pub local: bool,
    /// oomtop can and may call its API (loopback + plain HTTP + no credential plugin).
    pub live: bool,
    /// Why (not): "loopback http, token" / "refused: exec credential plugin (never run)" / …
    pub verdict: String,
}

/// Kubelet `stats/summary` of one node (through the API server's node proxy).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNodeStats {
    pub name: String,
    pub working_set: Option<u64>,
    pub available: Option<u64>,
    pub pods: Vec<KubePodStats>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePodStats {
    pub namespace: String,
    pub name: String,
    pub uid: String,
    pub working_set: Option<u64>,
    pub containers: Vec<KubeContainerStats>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainerStats {
    pub name: String,
    pub working_set: Option<u64>,
    pub usage: Option<u64>,
    /// `availableBytes`: present only when the container has a memory limit (limit = working set + this).
    pub available: Option<u64>,
    pub start_ms: Option<u64>,
}

/// One pod from `GET /api/v1/pods`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePodInfo {
    pub namespace: String,
    pub name: String,
    pub uid: String,
    pub node: Option<String>,
    pub phase: Option<String>,
    pub qos: Option<QosClass>,
    pub created_ms: Option<u64>,
    pub containers: Vec<KubeContainerSpec>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainerSpec {
    pub name: String,
    /// Container id without the `containerd://` prefix.
    pub id: Option<String>,
    /// `containerd` | `cri-o` | `docker` (the prefix).
    pub runtime: Option<String>,
    pub mem_limit: Option<u64>,
    pub mem_request: Option<u64>,
    pub restarts: Option<u32>,
    /// "running" | "waiting" | "terminated".
    pub state: Option<String>,
    /// `lastState.terminated.reason` ("OOMKilled", "Error", "Completed").
    pub last_termination_reason: Option<String>,
    pub last_termination_ms: Option<u64>,
    pub last_exit_code: Option<i64>,
}

/// What the Kubernetes adapter read from one context's API server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeApiData {
    pub context: String,
    pub distro: Option<KubeDistro>,
    pub status: SourceStatus,
    pub at_ms: u64,
    pub nodes: Vec<KubeNodeStats>,
    pub pods: Vec<KubePodInfo>,
}

// ---------------------------------------------------------------------------------------------------------
// Outputs
// ---------------------------------------------------------------------------------------------------------

/// A local cluster: node → namespace → pod → container.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Cluster {
    /// `host`, `kind:<name>`, `k3d:<name>`, `minikube:<profile>`, `docker-desktop`, `context:<name>`…
    pub id: String,
    pub name: String,
    pub distro: KubeDistro,
    pub context: Option<String>,
    /// How it was recognised ("process k3s", "label io.x-k8s.kind.cluster", "kubeconfig context", "kubelet
    /// cgroups").
    pub evidence: Vec<String>,
    /// API data status, when an API was read for it.
    pub api: Option<SourceStatus>,
    pub nodes: Vec<KubeNode>,
    /// Why the tree is empty or partial ("pods run inside the VM; …").
    pub notes: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNode {
    pub name: String,
    /// The node's container (kind, k3d, minikube) or VM sandbox.
    pub sandbox_id: Option<String>,
    /// Node memory: its container's/VM's, else the kubelet's node working set, else Σ pods.
    pub mem: Measured<u64>,
    pub namespaces: Vec<KubeNamespace>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNamespace {
    /// Empty when only cgroup paths are known (no names without the API or engine labels).
    pub name: String,
    pub mem: Measured<u64>,
    pub pods: Vec<KubePod>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePod {
    pub uid: Option<String>,
    pub name: Option<String>,
    pub qos: Option<QosClass>,
    pub phase: Option<String>,
    pub mem: Measured<u64>,
    /// Pod-level cgroup `memory.max`.
    pub limit: Option<u64>,
    pub cgroup: Option<String>,
    /// [`LimitStatus::id`] of the pod's limit, when it has one.
    pub limit_id: Option<String>,
    pub containers: Vec<KubeContainer>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainer {
    pub name: Option<String>,
    /// Full container id.
    pub id: Option<String>,
    pub runtime: Option<String>,
    pub mem: Measured<u64>,
    pub limit: Measured<u64>,
    pub restarts: Option<u32>,
    /// Last termination reason ("OOMKilled").
    pub last_termination: Option<String>,
    pub host_pids: Vec<ProcId>,
    pub sandbox_id: Option<String>,
    pub cgroup: Option<String>,
    /// [`LimitStatus::id`] of this container's limit, when it has one.
    pub limit_id: Option<String>,
}

/// Memory an engine VM holds that none of its containers uses (SPEC §11 "VM slack").
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct VmSlack {
    pub sandbox_id: String,
    pub label: String,
    pub runtime: String,
    /// Host footprint of the VM process(es).
    pub vm_footprint: Measured<u64>,
    /// Σ container memory inside it (engine stats).
    pub containers: Measured<u64>,
    /// The VM's configured memory, when known.
    pub configured: Option<u64>,
    /// `vm_footprint − containers`; always an estimate.
    pub slack: Measured<u64>,
    /// "<label>: 3.1 GiB held by the VM, not used by containers; restarting the engine returns it".
    pub summary: String,
    /// Caveats (footprint is a lower bound, container sum incomplete).
    pub notes: Vec<String>,
    /// Always false: restarting an engine stops every container, so this is never offered as safe reclaim.
    pub counts_as_reclaim: bool,
}

/// A container that is running but idle, or stopped and still on disk.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct StaleContainer {
    pub sandbox_id: String,
    pub name: String,
    pub engine: String,
    pub image: String,
    pub state: String,
    pub created_ms: Option<u64>,
    pub started_ms: Option<u64>,
    pub finished_ms: Option<u64>,
    /// Seconds since it started (running) or stopped (not running).
    pub age_s: Option<u64>,
    /// Average CPU over the observed window, percent of one core (running containers).
    pub cpu_pct: Measured<f64>,
    pub observed_s: u64,
    pub mem: Measured<u64>,
    /// Writable layer size (stopped containers), when the engine reported it.
    pub disk: Measured<u64>,
    pub exit_code: Option<i64>,
    pub oom_killed: Option<bool>,
    /// "running, ~0 CPU for 12 min" / "exited (137) 2 days ago".
    pub reason: String,
}

/// Everything container/cluster-shaped in one snapshot (`Snapshot::isolation`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Isolation {
    /// Engine data per container (input from the adapters).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub containers: Vec<ContainerInfo>,
    /// kubeconfig contexts and the safety verdict on each (input from the Kubernetes adapter).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub kube_contexts: Vec<KubeContextSummary>,
    /// API data per live context (input from the Kubernetes adapter).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub kube: Vec<KubeApiData>,
    /// Every limit, most urgent first.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub limits: Vec<LimitStatus>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub clusters: Vec<Cluster>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub vm_slack: Vec<VmSlack>,
    #[serde(skip_serializing_if = "NamespaceReport::is_empty")]
    pub namespaces: NamespaceReport,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub stale_containers: Vec<StaleContainer>,
}

impl Isolation {
    pub fn is_empty(&self) -> bool {
        self.containers.is_empty()
            && self.kube_contexts.is_empty()
            && self.kube.is_empty()
            && self.limits.is_empty()
            && self.clusters.is_empty()
            && self.vm_slack.is_empty()
            && self.namespaces.is_empty()
            && self.stale_containers.is_empty()
    }

    pub fn limit(&self, id: &str) -> Option<&LimitStatus> {
        self.limits.iter().find(|l| l.id == id)
    }

    pub fn container(&self, sandbox_id: &str) -> Option<&ContainerInfo> {
        self.containers.iter().find(|c| c.sandbox_id == sandbox_id)
    }
}

/// Export redaction (called by [`crate::redact::redact_snapshot`]): free text that comes from engines or
/// processes goes through [`crate::redact::redact_text`]; group ids are renamed like everywhere else.
pub fn redact(iso: &mut Isolation, rename: &dyn Fn(&mut Option<String>)) {
    use crate::redact::redact_text;
    for c in &mut iso.containers {
        c.name = redact_text(&c.name);
        c.image = redact_text(&c.image);
        c.status_text = redact_text(&c.status_text);
        for v in c.labels.values_mut() {
            *v = redact_text(v);
        }
    }
    for l in &mut iso.limits {
        l.label = redact_text(&l.label);
        l.summary = redact_text(&l.summary);
    }
    for v in &mut iso.vm_slack {
        v.label = redact_text(&v.label);
        v.summary = redact_text(&v.summary);
    }
    for s in &mut iso.stale_containers {
        s.name = redact_text(&s.name);
        s.image = redact_text(&s.image);
        s.reason = redact_text(&s.reason);
    }
    for n in &mut iso.namespaces.sets {
        n.label = redact_text(&n.label);
        rename(&mut n.group);
        rename(&mut n.owner_group);
    }
}

// ---------------------------------------------------------------------------------------------------------
// Small parsers shared with the adapters
// ---------------------------------------------------------------------------------------------------------

fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m as i64 + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// RFC 3339 timestamp (`2026-12-05T10:11:12.123456789Z`, `…+01:00`) → ms since the epoch. Docker's zero
/// time (`0001-01-01T00:00:00Z`) and anything before 1970 → `None`.
pub fn parse_rfc3339_ms(s: &str) -> Option<u64> {
    let s = s.trim();
    if s.len() < 20 {
        return None;
    }
    let num = |a: usize, b: usize| s.get(a..b)?.parse::<i64>().ok();
    let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
    let (h, mi, se) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
    if s.as_bytes()[4] != b'-' || !matches!(s.as_bytes()[10], b'T' | b't' | b' ') {
        return None;
    }
    let mut rest = &s[19..];
    let mut ms = 0i64;
    if let Some(frac) = rest.strip_prefix('.') {
        let digits: String = frac.chars().take_while(|c| c.is_ascii_digit()).collect();
        let first3: String = digits.chars().chain("000".chars()).take(3).collect();
        ms = first3.parse().ok()?;
        rest = &frac[digits.len()..];
    }
    let offset_s = match rest {
        "Z" | "z" => 0,
        o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) => {
            let sign = if o.starts_with('-') { -1 } else { 1 };
            sign * (o.get(1..3)?.parse::<i64>().ok()? * 3600 + o.get(4..6)?.parse::<i64>().ok()? * 60)
        }
        _ => return None,
    };
    if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {
        return None;
    }
    let days = days_from_civil(y, mo as u32, d as u32);
    let secs = days * 86_400 + h * 3600 + mi * 60 + se - offset_s;
    (secs > 0).then(|| secs as u64 * 1000 + ms as u64)
}

/// Kubernetes resource quantity → bytes (`128Mi`, `1Gi`, `1G`, `500M`, `1e9`, `1.5Gi`, `100k`, `129e6`,
/// `1000m` = 1 byte). `None` for anything else.
pub fn parse_k8s_quantity(s: &str) -> Option<u64> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }
    let bin = |e: i32| 1024f64.powi(e);
    let dec = |e: i32| 1000f64.powi(e);
    let suffixes: [(&str, f64); 13] = [
        ("Ki", bin(1)),
        ("Mi", bin(2)),
        ("Gi", bin(3)),
        ("Ti", bin(4)),
        ("Pi", bin(5)),
        ("Ei", bin(6)),
        ("k", dec(1)),
        ("M", dec(2)),
        ("G", dec(3)),
        ("T", dec(4)),
        ("P", dec(5)),
        ("E", dec(6)),
        ("m", 0.001),
    ];
    let (num, mult) = suffixes
        .iter()
        .find_map(|(suf, m)| s.strip_suffix(suf).map(|n| (n, *m)))
        .unwrap_or((s, 1.0));
    // Plain numbers may carry a decimal exponent (`1e9`, `129e6`).
    if !num
        .bytes()
        .all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-'))
    {
        return None;
    }
    let v: f64 = num.parse().ok()?;
    let bytes = v * mult;
    (bytes.is_finite() && bytes >= 0.0).then(|| bytes.round() as u64)
}

// ---------------------------------------------------------------------------------------------------------
// The tracker
// ---------------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, Default)]
struct CpuObs {
    first: (u64, u64),
    last: (u64, u64),
}

/// The only state behind [`Isolation`]: limit histories and per-container CPU counters. The engine owns
/// one and calls [`IsolationTracker::update`] after attribution and adapters.
#[derive(Debug, Clone, Default)]
pub struct IsolationTracker {
    pub limits: LimitTracker,
    cpu: BTreeMap<String, CpuObs>,
}

impl IsolationTracker {
    pub fn new() -> Self {
        Self::default()
    }

    /// Fills `s.isolation`'s derived parts (namespaces, clusters, limits, VM slack, stale containers) from
    /// the snapshot and the adapters' inputs already in `s.isolation`.
    pub fn update(&mut self, s: &mut Snapshot) {
        let now = s.taken_at_ms;
        let namespaces = namespace_sets(s);
        let mut clusters = build_clusters(s);
        let inputs = limit_inputs(s, &clusters);
        let limits = evaluate(&mut self.limits, inputs, now);
        link_limits(&mut clusters, &limits);
        let vm_slack = vm_slack(s);
        let stale = self.stale(s, now);
        let iso = &mut s.isolation;
        iso.namespaces = namespaces;
        iso.clusters = clusters;
        iso.limits = limits;
        iso.vm_slack = vm_slack;
        iso.stale_containers = stale;
    }

    fn stale(&mut self, s: &Snapshot, now: u64) -> Vec<StaleContainer> {
        let mut out = Vec::new();
        let mut seen = Vec::new();
        for c in &s.isolation.containers {
            let age_from = |t: Option<u64>| t.map(|t| now.saturating_sub(t) / 1000);
            if c.state == "running" {
                seen.push(c.sandbox_id.clone());
                let (Some(ns), Some(at)) = (c.cpu_total_ns, c.stats_at_ms) else {
                    continue;
                };
                let e = self.cpu.entry(c.sandbox_id.clone()).or_insert(CpuObs {
                    first: (at, ns),
                    last: (at, ns),
                });
                if ns < e.last.1 {
                    // Counter went back: the container restarted under the same id.
                    *e = CpuObs {
                        first: (at, ns),
                        last: (at, ns),
                    };
                } else if at > e.last.0 {
                    e.last = (at, ns);
                }
                let dt_ms = e.last.0.saturating_sub(e.first.0);
                let observed_s = dt_ms / 1000;
                if observed_s < STALE_MIN_OBSERVED_S {
                    continue;
                }
                let pct = (e.last.1 - e.first.1) as f64 / (dt_ms as f64 * 1e6) * 100.0;
                if pct >= STALE_CPU_PCT {
                    continue;
                }
                let mem = s
                    .sandboxes
                    .iter()
                    .find(|sb| sb.id == c.sandbox_id)
                    .map(|sb| sb.guest_mem.clone())
                    .unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
                out.push(StaleContainer {
                    sandbox_id: c.sandbox_id.clone(),
                    name: c.name.clone(),
                    engine: c.engine.clone(),
                    image: c.image.clone(),
                    state: c.state.clone(),
                    created_ms: c.created_ms,
                    started_ms: c.started_ms,
                    finished_ms: c.finished_ms,
                    age_s: age_from(c.started_ms.or(c.created_ms)),
                    cpu_pct: Measured::estimate(
                        pct,
                        format!("{} Δ cpu_stats.total_usage over {observed_s} s", c.engine),
                    ),
                    observed_s,
                    mem,
                    disk: size_measured(c),
                    exit_code: None,
                    oom_killed: c.oom_killed,
                    reason: format!(
                        "running, {pct:.1}% CPU over {}",
                        crate::units::format_duration(observed_s)
                    ),
                });
            } else if matches!(c.state.as_str(), "exited" | "created" | "dead") {
                let since = c.finished_ms.filter(|_| c.state != "created").or(c.created_ms);
                out.push(StaleContainer {
                    sandbox_id: c.sandbox_id.clone(),
                    name: c.name.clone(),
                    engine: c.engine.clone(),
                    image: c.image.clone(),
                    state: c.state.clone(),
                    created_ms: c.created_ms,
                    started_ms: c.started_ms,
                    finished_ms: c.finished_ms,
                    age_s: age_from(since),
                    cpu_pct: Measured::unavailable(c.engine.clone(), "not running"),
                    observed_s: 0,
                    mem: Measured::exact(0, format!("{} (not running)", c.engine)),
                    disk: size_measured(c),
                    exit_code: c.exit_code,
                    oom_killed: c.oom_killed,
                    reason: if c.status_text.is_empty() {
                        c.state.clone()
                    } else {
                        c.status_text.to_ascii_lowercase()
                    },
                });
            }
        }
        self.cpu.retain(|k, _| seen.contains(k));
        out.sort_by(|a, b| {
            (a.state != "running")
                .cmp(&(b.state != "running"))
                .then(b.age_s.cmp(&a.age_s))
                .then(a.sandbox_id.cmp(&b.sandbox_id))
        });
        out
    }
}

fn size_measured(c: &ContainerInfo) -> Measured<u64> {
    match c.size_rw {
        Some(v) => Measured::exact(v, format!("{} SizeRw", c.engine)),
        None => Measured::unavailable(
            c.engine.clone(),
            "engine lists sizes only on request (size=1 walks every layer; not requested)",
        ),
    }
}

// ---------------------------------------------------------------------------------------------------------
// Cluster tree
// ---------------------------------------------------------------------------------------------------------

#[derive(Default)]
struct PodAcc {
    pod: KubePod,
    namespace: String,
    /// container key (id, else name) → container
    containers: BTreeMap<String, KubeContainer>,
}

#[derive(Default)]
struct NodeAcc {
    sandbox_id: Option<String>,
    mem: Measured<u64>,
    /// pod key (uid, else ns/name) → pod
    pods: BTreeMap<String, PodAcc>,
}

#[derive(Default)]
struct ClusterAcc {
    c: Cluster,
    nodes: BTreeMap<String, NodeAcc>,
}

fn cgroup_mem<'a>(s: &'a Snapshot, path: &str) -> Option<&'a CgroupMem> {
    s.cgroups.iter().find(|c| c.path == path)
}

/// Container id inside a node prefix (`/system.slice/docker-<id>.scope/kubelet.slice` → id).
fn node_container_id(prefix: &str) -> Option<String> {
    prefix.split('/').find_map(|seg| {
        let s = seg.strip_suffix(".scope")?;
        ["docker-", "libpod-", "cri-containerd-"]
            .iter()
            .find_map(|p| s.strip_prefix(p))
            .filter(|id| id.len() >= 12 && id.bytes().all(|b| b.is_ascii_hexdigit()))
            .map(str::to_string)
    })
}

/// Cluster identity of a node container from its labels.
fn node_cluster_of(c: &ContainerInfo) -> Option<(String, String, KubeDistro, String)> {
    let l = &c.labels;
    if let Some(name) = l.get("io.x-k8s.kind.cluster") {
        let distro = if c.engine == "docker-desktop" && name == "desktop" {
            KubeDistro::DockerDesktop
        } else {
            KubeDistro::Kind
        };
        let id = if distro == KubeDistro::DockerDesktop {
            "docker-desktop".to_string()
        } else {
            format!("kind:{name}")
        };
        return Some((id, name.clone(), distro, "label io.x-k8s.kind.cluster".into()));
    }
    if let Some(name) = l.get("k3d.cluster") {
        if matches!(
            l.get("k3d.role").map(String::as_str),
            Some("loadbalancer" | "registry" | "noRole")
        ) {
            return None;
        }
        return Some((
            format!("k3d:{name}"),
            name.clone(),
            KubeDistro::K3d,
            "label k3d.cluster".into(),
        ));
    }
    if let Some(name) = l.get("name.minikube.sigs.k8s.io") {
        return Some((
            format!("minikube:{name}"),
            name.clone(),
            KubeDistro::Minikube,
            "label name.minikube.sigs.k8s.io".into(),
        ));
    }
    None
}

fn proc_matches(s: &Snapshot, f: impl Fn(&crate::model::Process) -> bool) -> bool {
    s.processes.iter().any(f)
}

fn base(exe: &str) -> &str {
    exe.rsplit('/').next().unwrap_or(exe)
}

/// The distribution running directly on this host, from its processes.
fn host_distro(s: &Snapshot) -> (KubeDistro, Option<String>) {
    if proc_matches(s, |p| p.name == "kubelite" || p.exe.contains("/snap/microk8s/")) {
        return (KubeDistro::Microk8s, Some("process kubelite (microk8s)".into()));
    }
    if proc_matches(s, |p| {
        (p.name == "k3s" || base(&p.exe) == "k3s" || p.name.starts_with("k3s-"))
            && !p
                .cmdline
                .iter()
                .any(|a| a == "kubectl" || a == "crictl" || a == "ctr")
    }) {
        return (KubeDistro::K3s, Some("process k3s".into()));
    }
    if proc_matches(s, |p| p.name == "kubelet" || base(&p.exe) == "kubelet") {
        return (KubeDistro::Unknown, Some("process kubelet".into()));
    }
    (KubeDistro::Unknown, None)
}

/// Clusters that run inside an app's VM (no pods visible from the host), from processes and contexts.
fn vm_clusters(s: &Snapshot) -> Vec<(String, String, KubeDistro, String, Option<String>)> {
    let ctx = |name: &str| s.isolation.kube_contexts.iter().any(|c| c.name == name);
    let app = |needle: &str| proc_matches(s, |p| p.exe.contains(needle));
    let vm_of = |runtime_pred: &dyn Fn(&crate::model::Sandbox) -> bool| {
        s.sandboxes
            .iter()
            .find(|sb| sb.kind == SandboxKind::Vm && runtime_pred(sb))
            .map(|sb| sb.id.clone())
    };
    let mut out = Vec::new();
    if ctx("docker-desktop") && app("/Docker.app/") {
        out.push((
            "docker-desktop".into(),
            "docker-desktop".into(),
            KubeDistro::DockerDesktop,
            "kubeconfig context docker-desktop + Docker Desktop running".into(),
            vm_of(&|sb| sb.label.starts_with("Docker") || sb.runtime == "docker-desktop"),
        ));
    }
    if ctx("orbstack") && app("/OrbStack.app/") {
        out.push((
            "orbstack".into(),
            "orbstack".into(),
            KubeDistro::OrbStack,
            "kubeconfig context orbstack + OrbStack running".into(),
            vm_of(&|sb| sb.runtime == "orbstack" || sb.label.starts_with("OrbStack")),
        ));
    }
    if ctx("rancher-desktop") && app("/Rancher Desktop.app/") {
        out.push((
            "rancher-desktop".into(),
            "rancher-desktop".into(),
            KubeDistro::RancherDesktop,
            "kubeconfig context rancher-desktop + Rancher Desktop running".into(),
            vm_of(&|sb| sb.label.starts_with("Rancher Desktop")),
        ));
    }
    let colima_k8s = proc_matches(s, |p| {
        (p.name == "colima" || base(&p.exe) == "colima")
            && p.cmdline.iter().any(|a| a == "--kubernetes" || a == "-k")
    });
    if colima_k8s || (ctx("colima") && proc_matches(s, |p| p.name == "colima" || base(&p.exe) == "colima")) {
        out.push((
            "colima".into(),
            "colima".into(),
            KubeDistro::Colima,
            if colima_k8s {
                "process colima --kubernetes".into()
            } else {
                "kubeconfig context colima + colima running".into()
            },
            vm_of(&|sb| sb.runtime == "colima" || sb.label.contains("olima")),
        ));
    }
    // minikube with a VM driver (qemu, vfkit, hyperkit, virtualbox): its VM process names the profile.
    if proc_matches(s, |p| {
        !p.name.starts_with("minikube") && p.cmdline.iter().any(|a| a.contains("/.minikube/machines/"))
    }) {
        out.push((
            "minikube:minikube".into(),
            "minikube".into(),
            KubeDistro::Minikube,
            "minikube VM process".into(),
            None,
        ));
    }
    out
}

impl ClusterAcc {
    fn new(id: &str, name: &str, distro: KubeDistro, evidence: String) -> Self {
        ClusterAcc {
            c: Cluster {
                id: id.into(),
                name: name.into(),
                distro,
                evidence: vec![evidence],
                ..Default::default()
            },
            nodes: BTreeMap::new(),
        }
    }

    fn evidence(&mut self, e: String) {
        if !self.c.evidence.contains(&e) {
            self.c.evidence.push(e);
        }
    }
}

fn pod_entry<'a>(node: &'a mut NodeAcc, uid: Option<&str>, ns: &str, name: Option<&str>) -> &'a mut PodAcc {
    // Find by uid, then by ns/name.
    let key = match uid {
        Some(u) => u.to_string(),
        None => format!("{ns}/{}", name.unwrap_or("?")),
    };
    if !node.pods.contains_key(&key) {
        if let Some(n) = name {
            if let Some(k) = node
                .pods
                .iter()
                .find(|(_, p)| p.pod.name.as_deref() == Some(n) && p.namespace == ns)
                .map(|(k, _)| k.clone())
            {
                return node.pods.get_mut(&k).expect("present");
            }
        }
    }
    node.pods.entry(key).or_insert_with(|| PodAcc {
        pod: KubePod {
            uid: uid.map(str::to_string),
            ..Default::default()
        },
        ..Default::default()
    })
}

fn container_entry<'a>(pod: &'a mut PodAcc, id: Option<&str>, name: Option<&str>) -> &'a mut KubeContainer {
    let found = pod
        .containers
        .iter()
        .find(|(_, c)| {
            (id.is_some() && c.id.as_deref() == id)
                || (name.is_some() && c.name.as_deref() == name && (id.is_none() || c.id.is_none()))
        })
        .map(|(k, _)| k.clone());
    let key = found.unwrap_or_else(|| id.or(name).unwrap_or("?").to_string());
    pod.containers.entry(key).or_default()
}

/// Builds the cluster tree from cgroup paths, engine labels and API data (module docs).
pub fn build_clusters(s: &Snapshot) -> Vec<Cluster> {
    let mut acc: BTreeMap<String, ClusterAcc> = BTreeMap::new();
    let host_name = if s.host.hostname.is_empty() {
        "this host".to_string()
    } else {
        s.host.hostname.clone()
    };
    let sandbox_mem = |id: &str| {
        s.sandboxes
            .iter()
            .find(|sb| sb.id == id)
            .map(|sb| sb.guest_mem.clone())
    };

    // 1. Node containers (kind / k3d / minikube) from engine labels.
    for c in &s.isolation.containers {
        if c.state != "running" {
            continue;
        }
        let Some((id, name, distro, ev)) = node_cluster_of(c) else {
            continue;
        };
        let a = acc
            .entry(id.clone())
            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
        a.evidence(ev);
        let n = a.nodes.entry(c.name.clone()).or_default();
        n.sandbox_id = Some(c.sandbox_id.clone());
        n.mem =
            sandbox_mem(&c.sandbox_id).unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
    }

    // 2. Pod containers from cri-dockerd labels (Docker Desktop / native docker runtime).
    for c in &s.isolation.containers {
        let l = &c.labels;
        let Some(uid) = l.get("io.kubernetes.pod.uid") else {
            continue;
        };
        if c.state != "running"
            || l.get("io.kubernetes.docker.type").map(String::as_str) == Some("podsandbox")
        {
            continue;
        }
        let (cid, node) = if c.vm_hosted {
            let id = if c.engine == "docker-desktop" {
                "docker-desktop".to_string()
            } else {
                c.engine.clone()
            };
            (id.clone(), id)
        } else {
            ("host".to_string(), host_name.clone())
        };
        let distro = if c.engine == "docker-desktop" {
            KubeDistro::DockerDesktop
        } else {
            KubeDistro::Unknown
        };
        let a = acc.entry(cid.clone()).or_insert_with(|| {
            ClusterAcc::new(&cid, &cid, distro, "labels io.kubernetes.* (cri-dockerd)".into())
        });
        a.evidence("labels io.kubernetes.* (cri-dockerd)".into());
        let n = a.nodes.entry(node).or_default();
        let ns = l.get("io.kubernetes.pod.namespace").cloned().unwrap_or_default();
        let pname = l.get("io.kubernetes.pod.name").cloned();
        let p = pod_entry(n, Some(uid), &ns, pname.as_deref());
        p.namespace = ns;
        p.pod.name = p.pod.name.take().or(pname);
        let cname = l.get("io.kubernetes.container.name").cloned();
        let k = container_entry(p, Some(&c.id), cname.as_deref());
        k.id = Some(c.id.clone());
        k.name = cname;
        k.runtime = Some("docker".into());
        k.sandbox_id = Some(c.sandbox_id.clone());
        k.restarts = c.restart_count;
        if let Some(m) = sandbox_mem(&c.sandbox_id) {
            k.mem = m;
        }
        if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id == c.sandbox_id) {
            k.host_pids = sb.host_pids.clone();
            k.limit = sb.configured_mem.clone();
        }
    }

    // 3. Kubelet cgroup paths of host processes (Linux).
    let mut kube_procs: Vec<(&crate::model::Process, KubeCgroup)> = s
        .processes
        .iter()
        .filter_map(|p| Some((p, parse_kube_cgroup(p.cgroup.as_deref()?)?)))
        .collect();
    kube_procs.sort_by_key(|(p, _)| (p.id.start_time, p.id.pid));
    if !kube_procs.is_empty() {
        let (hd, hev) = host_distro(s);
        for (p, k) in &kube_procs {
            let (cid, node) = if k.node_prefix.is_empty() {
                let a = acc.entry("host".into()).or_insert_with(|| {
                    ClusterAcc::new("host", &host_name, hd, "kubelet cgroups on this host".into())
                });
                if let Some(e) = &hev {
                    a.evidence(e.clone());
                }
                if a.c.distro == KubeDistro::Unknown {
                    a.c.distro = hd;
                }
                ("host".to_string(), host_name.clone())
            } else {
                let nid = node_container_id(&k.node_prefix);
                let node_ci = nid.as_ref().and_then(|id| {
                    s.isolation
                        .containers
                        .iter()
                        .find(|c| c.id.starts_with(id.as_str()) || id.starts_with(c.id.as_str()))
                });
                match node_ci.and_then(|c| node_cluster_of(c).map(|x| (x, c))) {
                    Some(((id, name, distro, ev), c)) => {
                        let a = acc
                            .entry(id.clone())
                            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev));
                        a.evidence("kubelet cgroups inside the node container".into());
                        (id, c.name.clone())
                    }
                    None => {
                        let short: String = nid.clone().unwrap_or_default().chars().take(12).collect();
                        let id = format!("nested:{short}");
                        acc.entry(id.clone()).or_insert_with(|| {
                            ClusterAcc::new(
                                &id,
                                &format!("cluster in container {short}"),
                                KubeDistro::Unknown,
                                "kubelet cgroups inside a container".into(),
                            )
                        });
                        (id, format!("container {short}"))
                    }
                }
            };
            let a = acc.get_mut(&cid).expect("inserted");
            let n = a.nodes.entry(node).or_default();
            let pa = pod_entry(n, Some(&k.pod_uid), "", None);
            pa.pod.qos = Some(k.qos);
            if pa.pod.cgroup.is_none() {
                pa.pod.cgroup = Some(k.pod_cgroup.clone());
                if let Some(cg) = cgroup_mem(s, &k.pod_cgroup) {
                    pa.pod.mem = cg.working_set_measured();
                    pa.pod.limit = cg.max;
                }
            }
            let Some(id) = k.container_id.as_deref().filter(|_| !k.conmon) else {
                continue;
            };
            let c = container_entry(pa, Some(id), None);
            c.id = Some(id.to_string());
            c.runtime = c.runtime.take().or(k.runtime.clone());
            if !c.host_pids.contains(&p.id) {
                c.host_pids.push(p.id);
            }
            if c.name.is_none() && p.name == "pause" {
                c.name = Some("pause".into());
            }
            if let Some(cg) = k.container_cgroup.as_deref() {
                c.cgroup = Some(cg.to_string());
                if let Some(m) = cgroup_mem(s, cg) {
                    c.mem = m.working_set_measured();
                    c.limit = match m.max {
                        Some(v) => Measured::exact(v, "cgroup memory.max"),
                        None if m.limits_read => Measured::unavailable("cgroup memory.max", "no limit"),
                        None => Measured::unavailable("cgroup memory.max", "not read"),
                    };
                }
            }
        }
        // Containers without cgroup numbers: Σ their processes (an estimate).
        for a in acc.values_mut() {
            for n in a.nodes.values_mut() {
                for pa in n.pods.values_mut() {
                    for c in pa.containers.values_mut() {
                        if !c.mem.is_available() && !c.host_pids.is_empty() {
                            let mems: Vec<&Measured<u64>> = c
                                .host_pids
                                .iter()
                                .filter_map(|id| s.process(*id).map(|p| &p.mem.footprint_or_pss))
                                .collect();
                            c.mem = sum_bytes(mems, "Σ process PSS (cgroup not read)").into_estimate();
                        }
                    }
                }
            }
        }
    }

    // 4. API data: names, limits, restarts, termination reasons, kubelet working sets.
    for d in &s.isolation.kube {
        let node_names: Vec<String> = d
            .pods
            .iter()
            .filter_map(|p| p.node.clone())
            .chain(d.nodes.iter().map(|n| n.name.clone()))
            .collect();
        // The cluster that already has one of these nodes, else one keyed by the context.
        let existing = acc
            .iter()
            .find(|(_, a)| node_names.iter().any(|n| a.nodes.contains_key(n)))
            .map(|(k, _)| k.clone());
        let distro = d.distro.or_else(|| KubeDistro::from_context(&d.context));
        let cid = existing.unwrap_or_else(|| match distro {
            Some(KubeDistro::Kind) => {
                format!("kind:{}", KubeDistro::Kind.cluster_name_from_context(&d.context))
            }
            Some(KubeDistro::K3d) => format!("k3d:{}", KubeDistro::K3d.cluster_name_from_context(&d.context)),
            Some(KubeDistro::Minikube) => "minikube:minikube".into(),
            Some(KubeDistro::DockerDesktop) => "docker-desktop".into(),
            Some(KubeDistro::OrbStack) => "orbstack".into(),
            Some(KubeDistro::RancherDesktop) => "rancher-desktop".into(),
            Some(KubeDistro::Colima) => "colima".into(),
            _ => format!("context:{}", d.context),
        });
        let a = acc.entry(cid.clone()).or_insert_with(|| {
            ClusterAcc::new(
                &cid,
                &distro.map_or(d.context.clone(), |x| x.cluster_name_from_context(&d.context)),
                distro.unwrap_or_default(),
                "kubeconfig context".into(),
            )
        });
        a.evidence(format!("API via context {}", d.context));
        a.c.context = Some(d.context.clone());
        a.c.api = Some(d.status.clone());
        for p in &d.pods {
            let node = p.node.clone().unwrap_or_else(|| "(unscheduled)".into());
            let n = a.nodes.entry(node).or_default();
            let pa = pod_entry(n, Some(&p.uid), &p.namespace, Some(&p.name));
            pa.namespace = p.namespace.clone();
            pa.pod.name = Some(p.name.clone());
            pa.pod.phase = p.phase.clone();
            pa.pod.qos = p.qos.or(pa.pod.qos);
            for cs in &p.containers {
                let c = container_entry(pa, cs.id.as_deref(), Some(&cs.name));
                c.name = Some(cs.name.clone());
                c.id = c.id.take().or(cs.id.clone());
                c.runtime = c.runtime.take().or(cs.runtime.clone());
                c.restarts = cs.restarts;
                c.last_termination = cs.last_termination_reason.clone();
                if !c.limit.is_available() {
                    c.limit = match cs.mem_limit {
                        Some(l) => Measured::exact(l, "pod spec resources.limits.memory"),
                        None => Measured::unavailable("pod spec", "no memory limit"),
                    };
                }
            }
        }
        for ns in &d.nodes {
            let n = a.nodes.entry(ns.name.clone()).or_default();
            if !n.mem.is_available() {
                if let Some(ws) = ns.working_set {
                    n.mem = Measured::exact(ws, "kubelet stats/summary node workingSetBytes");
                }
            }
            for ps in &ns.pods {
                let pa = pod_entry(n, Some(&ps.uid), &ps.namespace, Some(&ps.name));
                pa.namespace = ps.namespace.clone();
                pa.pod.name = pa.pod.name.take().or(Some(ps.name.clone()));
                if !pa.pod.mem.is_available() {
                    if let Some(ws) = ps.working_set {
                        pa.pod.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
                    }
                }
                for cs in &ps.containers {
                    let c = container_entry(pa, None, Some(&cs.name));
                    c.name = Some(cs.name.clone());
                    if !c.mem.is_available() {
                        if let Some(ws) = cs.working_set {
                            c.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
                        }
                    }
                }
            }
        }
    }

    // 5. Clusters inside app VMs (no pods visible from the host without the API).
    for (id, name, distro, ev, vm) in vm_clusters(s) {
        let a = acc
            .entry(id.clone())
            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
        a.evidence(ev);
        if a.nodes.is_empty() {
            let n = a.nodes.entry(name.clone()).or_default();
            if let Some(v) = &vm {
                n.sandbox_id = Some(v.clone());
                n.mem = s
                    .sandboxes
                    .iter()
                    .find(|sb| &sb.id == v)
                    .and_then(|sb| {
                        let fp: Vec<&Measured<u64>> = sb
                            .host_pids
                            .iter()
                            .filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
                            .collect();
                        (!fp.is_empty()).then(|| sum_bytes(fp, "VM host footprint"))
                    })
                    .unwrap_or_else(|| Measured::unavailable("vm", "VM process not found"));
            }
        }
    }

    // Contexts: attach names; note what is missing.
    for a in acc.values_mut() {
        if a.c.context.is_none() {
            a.c.context = s
                .isolation
                .kube_contexts
                .iter()
                .find(|c| match a.c.distro {
                    KubeDistro::Kind => c.name == format!("kind-{}", a.c.name),
                    KubeDistro::K3d => c.name == format!("k3d-{}", a.c.name),
                    KubeDistro::Unknown => false,
                    d => c.distro == Some(d),
                })
                .map(|c| c.name.clone());
        }
        let has_pods = a.nodes.values().any(|n| !n.pods.is_empty());
        let named = a
            .nodes
            .values()
            .flat_map(|n| n.pods.values())
            .any(|p| p.pod.name.is_some());
        if !has_pods {
            a.c.notes.push(
                "pods run inside the node container or VM: names and per-pod memory need the API server \
                 (oomtop calls it only for loopback plain-HTTP contexts; see `oomtop doctor`)"
                    .into(),
            );
        } else if !named {
            a.c.notes.push(
                "pod and container names need the API server or engine labels; cgroup paths give QoS, pod \
                 UID and container id only"
                    .into(),
            );
        }
    }

    acc.into_values().map(finish_cluster).collect()
}

fn finish_cluster(a: ClusterAcc) -> Cluster {
    let mut c = a.c;
    for (name, n) in a.nodes {
        let mut by_ns: BTreeMap<String, Vec<KubePod>> = BTreeMap::new();
        for (_, pa) in n.pods {
            let mut pod = pa.pod;
            pod.containers = pa.containers.into_values().collect();
            pod.containers
                .sort_by(|x, y| x.name.cmp(&y.name).then(x.id.cmp(&y.id)));
            if !pod.mem.is_available() && !pod.containers.is_empty() {
                pod.mem = sum_bytes(pod.containers.iter().map(|c| &c.mem), "Σ container working sets");
            }
            by_ns.entry(pa.namespace).or_default().push(pod);
        }
        let mut namespaces: Vec<KubeNamespace> = by_ns
            .into_iter()
            .map(|(name, mut pods)| {
                pods.sort_by(|x, y| x.name.cmp(&y.name).then(x.uid.cmp(&y.uid)));
                KubeNamespace {
                    mem: sum_bytes(pods.iter().map(|p| &p.mem), "Σ pod memory"),
                    name,
                    pods,
                }
            })
            .collect();
        namespaces.sort_by(|a, b| a.name.cmp(&b.name));
        let mem = if n.mem.is_available() || namespaces.is_empty() {
            n.mem
        } else {
            sum_bytes(namespaces.iter().map(|x| &x.mem), "Σ pod memory")
        };
        c.nodes.push(KubeNode {
            name,
            sandbox_id: n.sandbox_id,
            mem,
            namespaces,
        });
    }
    c
}

/// Sets `limit_id` on pods and containers that have a [`LimitStatus`].
fn link_limits(clusters: &mut [Cluster], limits: &[LimitStatus]) {
    for c in clusters {
        for n in &mut c.nodes {
            for ns in &mut n.namespaces {
                for p in &mut ns.pods {
                    if let Some(cg) = &p.cgroup {
                        let id = format!("cgroup:{cg}");
                        if limits.iter().any(|l| l.id == id) {
                            p.limit_id = Some(id);
                        }
                    }
                    for k in &mut p.containers {
                        k.limit_id = limits
                            .iter()
                            .find(|l| {
                                k.cgroup.as_ref().is_some_and(|cg| l.cgroup.as_ref() == Some(cg))
                                    || k.sandbox_id
                                        .as_ref()
                                        .is_some_and(|sb| l.sandbox_id.as_ref() == Some(sb))
                                    || (l.pod.as_deref()
                                        == Some(&format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("")))
                                        && l.label == k.name.clone().unwrap_or_default()
                                        && l.id.starts_with("k8s:"))
                            })
                            .map(|l| l.id.clone());
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------------------
// Limit inputs
// ---------------------------------------------------------------------------------------------------------

fn unit_label(path: &str) -> String {
    path.rsplit('/')
        .find(|s| !s.is_empty())
        .unwrap_or(path)
        .to_string()
}

/// Every limit in the snapshot, de-duplicated: cgroup files (Linux, freshest) first, then engine limits
/// of containers without a cgroup entry, engine VMs, then API-only Kubernetes containers.
pub fn limit_inputs(s: &Snapshot, clusters: &[Cluster]) -> Vec<LimitInput> {
    let mut out: Vec<LimitInput> = Vec::new();
    // Names of Kubernetes containers / pods by container id / pod cgroup.
    let mut kube_names: BTreeMap<String, (String, String)> = BTreeMap::new();
    let mut pod_names: BTreeMap<String, String> = BTreeMap::new();
    for c in clusters {
        for n in &c.nodes {
            for ns in &n.namespaces {
                for p in &ns.pods {
                    let pod = format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("?"));
                    if let Some(cg) = &p.cgroup {
                        pod_names.insert(cg.clone(), pod.clone());
                    }
                    for k in &p.containers {
                        if let Some(id) = &k.id {
                            kube_names.insert(id.clone(), (pod.clone(), k.name.clone().unwrap_or_default()));
                        }
                    }
                }
            }
        }
    }
    let ci_by_id = |id: &str| {
        s.isolation
            .containers
            .iter()
            .find(|c| c.id.starts_with(id) || (!c.id.is_empty() && id.starts_with(c.id.as_str())))
    };
    let mut covered_sandboxes: Vec<String> = Vec::new();
    let mut covered_kube_ids: Vec<String> = Vec::new();
    for cg in s.cgroups.iter().filter(|c| c.has_limit()) {
        let (limit, target) = match (cg.max, cg.high) {
            (Some(m), _) => (Measured::exact(m, "cgroup memory.max"), LimitTarget::Max),
            (None, Some(h)) => (Measured::exact(h, "cgroup memory.high"), LimitTarget::High),
            _ => continue,
        };
        let mut i = LimitInput {
            id: format!("cgroup:{}", cg.path),
            kind: LimitKind::Cgroup,
            label: unit_label(&cg.path),
            runtime: None,
            cgroup: Some(cg.path.clone()),
            usage: cg.working_set_measured(),
            read_at_ms: (cg.current.is_some() && cg.at_ms > 0).then_some(cg.at_ms),
            limit,
            target,
            high: cg.high.filter(|h| cg.max.is_none_or(|m| *h < m)),
            peak: match cg.peak {
                Some(p) => Measured::exact(p, "cgroup memory.peak"),
                None => Measured::unavailable("cgroup memory.peak", "not available (kernel < 5.19)"),
            },
            events: cg.events,
            ..Default::default()
        };
        if let Some(k) = parse_kube_cgroup(&cg.path) {
            i.runtime = Some("kubernetes".into());
            match &k.container_id {
                Some(id) => {
                    i.kind = LimitKind::Container;
                    covered_kube_ids.push(id.clone());
                    if let Some((pod, name)) = kube_names.get(id) {
                        i.pod = Some(pod.clone());
                        if !name.is_empty() {
                            i.label = name.clone();
                        }
                    } else {
                        i.label = id.chars().take(12).collect();
                    }
                }
                None => {
                    i.kind = LimitKind::Pod;
                    i.label = pod_names
                        .get(&k.pod_cgroup)
                        .cloned()
                        .unwrap_or_else(|| format!("pod {}", k.pod_uid));
                    i.pod = pod_names.get(&k.pod_cgroup).cloned();
                }
            }
        } else if let Some(CgroupScope::Container { runtime, id }) = parse_cgroup(&cg.path) {
            i.kind = LimitKind::Container;
            i.runtime = Some(runtime.clone());
            if let Some(ci) = ci_by_id(&id) {
                i.label = ci.name.clone();
                i.sandbox_id = Some(ci.sandbox_id.clone());
                i.oom_killed_last_exit = ci.oom_killed;
                i.restarts = ci.restart_count;
                covered_sandboxes.push(ci.sandbox_id.clone());
            } else if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id.ends_with(&format!(":{id}"))) {
                i.label = sb.label.clone();
                i.sandbox_id = Some(sb.id.clone());
                covered_sandboxes.push(sb.id.clone());
            } else {
                i.label = format!("{runtime} {id}");
            }
        } else if cg.path.ends_with(".service") || cg.path.ends_with(".scope") || cg.path.ends_with(".slice")
        {
            i.runtime = Some("systemd".into());
        }
        out.push(i);
    }
    // Engine containers with a limit and no cgroup entry (VM-hosted engines, or cgroups not readable).
    for sb in &s.sandboxes {
        if sb.kind != SandboxKind::Container || covered_sandboxes.contains(&sb.id) {
            continue;
        }
        let Some(limit) = sb.limits.mem_max else {
            continue;
        };
        let ci = s.isolation.container(&sb.id);
        if let Some(c) = ci {
            if c.labels.contains_key("io.kubernetes.pod.uid") {
                covered_kube_ids.push(c.id.clone());
            }
        }
        out.push(LimitInput {
            id: sb.id.clone(),
            kind: LimitKind::Container,
            label: sb.label.clone(),
            runtime: Some(sb.runtime.clone()),
            sandbox_id: Some(sb.id.clone()),
            usage: sb.guest_mem.clone(),
            // Only a fresh engine reading is a new trend point (carried-over values are estimates).
            read_at_ms: ci
                .and_then(|c| c.stats_at_ms)
                .filter(|_| sb.guest_mem.quality == crate::model::Quality::Exact),
            limit: if sb.configured_mem.is_available() {
                sb.configured_mem.clone()
            } else {
                Measured::exact(limit, format!("{} HostConfig.Memory", sb.runtime))
            },
            peak: Measured::unavailable(sb.runtime.clone(), "engines do not report a peak"),
            oom_killed_last_exit: ci.and_then(|c| c.oom_killed),
            restarts: ci.and_then(|c| c.restart_count),
            ..Default::default()
        });
    }
    // Engine VMs: Σ containers against the VM's memory.
    for sb in &s.sandboxes {
        if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
            continue;
        }
        let Some(size) = sb.configured_mem.value else {
            continue;
        };
        let complete = sb.guest_mem.source == "Σ container memory (engine stats)";
        let read_at = s
            .isolation
            .containers
            .iter()
            .filter(|c| c.engine == sb.runtime || sb.started_by_group.is_some())
            .filter_map(|c| c.stats_at_ms)
            .max();
        out.push(LimitInput {
            id: sb.id.clone(),
            kind: LimitKind::Vm,
            label: sb.label.clone(),
            runtime: Some(sb.runtime.clone()),
            sandbox_id: Some(sb.id.clone()),
            usage: sb.guest_mem.clone(),
            read_at_ms: read_at.filter(|_| complete),
            limit: Measured::exact(size, sb.configured_mem.source.clone()),
            peak: Measured::unavailable(sb.runtime.clone(), "not reported"),
            ..Default::default()
        });
    }
    // Kubernetes containers known only from the API (pods inside a VM or node container).
    for d in &s.isolation.kube {
        let stats: BTreeMap<(String, String, String), &KubeContainerStats> = d
            .nodes
            .iter()
            .flat_map(|n| n.pods.iter())
            .flat_map(|p| {
                p.containers
                    .iter()
                    .map(move |c| ((p.namespace.clone(), p.name.clone(), c.name.clone()), c))
            })
            .collect();
        for p in &d.pods {
            for c in &p.containers {
                let Some(limit) = c.mem_limit else { continue };
                if c.id
                    .as_ref()
                    .is_some_and(|id| covered_kube_ids.iter().any(|x| x == id))
                {
                    continue;
                }
                let st = stats.get(&(p.namespace.clone(), p.name.clone(), c.name.clone()));
                out.push(LimitInput {
                    id: format!("k8s:{}/{}/{}/{}", d.context, p.namespace, p.name, c.name),
                    kind: LimitKind::Container,
                    label: c.name.clone(),
                    runtime: Some("kubernetes".into()),
                    pod: Some(format!("{}/{}", p.namespace, p.name)),
                    usage: match st.and_then(|s| s.working_set) {
                        Some(ws) => Measured::exact(ws, "kubelet stats/summary workingSetBytes"),
                        None => Measured::unavailable("kubelet stats/summary", "no stats for this container"),
                    },
                    read_at_ms: st.and_then(|s| s.working_set).map(|_| d.at_ms),
                    limit: Measured::exact(limit, "pod spec resources.limits.memory"),
                    peak: Measured::unavailable("kubelet", "not reported"),
                    oom_killed_last_exit: c.last_termination_reason.as_ref().map(|r| r == "OOMKilled"),
                    restarts: c.restarts,
                    ..Default::default()
                });
            }
        }
    }
    out
}

// ---------------------------------------------------------------------------------------------------------
// VM slack
// ---------------------------------------------------------------------------------------------------------

/// VM slack of every engine VM whose containers were measured (module docs).
pub fn vm_slack(s: &Snapshot) -> Vec<VmSlack> {
    let mut out = Vec::new();
    for sb in &s.sandboxes {
        if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
            continue;
        }
        let Some(sum) = sb.guest_mem.value else { continue };
        let fps: Vec<&Measured<u64>> = sb
            .host_pids
            .iter()
            .filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
            .collect();
        if fps.is_empty() {
            continue;
        }
        let vm_fp = sum_bytes(fps, "VM host footprint");
        let Some(fp) = vm_fp.value else { continue };
        let slack = fp.saturating_sub(sum);
        if slack < VM_SLACK_MIN_BYTES.max(fp / 10) {
            continue;
        }
        let mut notes = Vec::new();
        if sb.footprint_lower_bound {
            notes.push(
                "the VM's host footprint is a lower bound (compressed guest memory is not in it), so the \
                 slack may be larger"
                    .to_string(),
            );
        }
        if sb.guest_mem.source.contains("lower bound") {
            notes.push("not every container was measured, so the slack may be smaller".to_string());
        }
        if sb.guest_mem.source.contains("earlier refresh") {
            notes.push("some container values are from an earlier refresh".to_string());
        }
        notes.push("includes the guest kernel, page cache and the engine's own services".to_string());
        out.push(VmSlack {
            sandbox_id: sb.id.clone(),
            label: sb.label.clone(),
            runtime: sb.runtime.clone(),
            vm_footprint: vm_fp,
            containers: sb.guest_mem.clone(),
            configured: sb.configured_mem.value,
            slack: Measured::estimate(slack, "VM host footprint − Σ container memory"),
            summary: format!(
                "{}: {} {VM_SLACK_SENTENCE}",
                sb.label,
                format_bytes(slack, UnitSystem::Iec, 1)
            ),
            notes,
            counts_as_reclaim: false,
        });
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forecast::MemoryEvents;
    use crate::model::{MemBreakdown, Process, Sandbox, SandboxLimits};

    const GIB: u64 = 1 << 30;
    const MIB: u64 = 1 << 20;
    const CID: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
    const UID: &str = "8f6c1c3e-3b5a-4b8e-9d55-0a1b2c3d4e5f";

    fn proc(pid: u32, name: &str, cgroup: &str, mib: u64) -> Process {
        Process {
            id: ProcId::new(pid, pid as u64),
            ppid: Some(1),
            name: name.into(),
            cgroup: Some(cgroup.into()),
            mem: MemBreakdown {
                footprint_or_pss: Measured::exact(mib * MIB, "t"),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn parsers() {
        assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:01Z"), Some(1000));
        assert_eq!(
            parse_rfc3339_ms("2026-12-05T10:11:12.123456789Z"),
            Some(1_796_465_472_123)
        );
        assert_eq!(
            parse_rfc3339_ms("2026-12-05T11:11:12+01:00"),
            parse_rfc3339_ms("2026-12-05T10:11:12Z")
        );
        assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None, "docker zero time");
        assert_eq!(parse_rfc3339_ms("yesterday"), None);
        for (q, v) in [
            ("128Mi", 128 * MIB),
            ("1Gi", GIB),
            ("1G", 1_000_000_000),
            ("500M", 500_000_000),
            ("1e9", 1_000_000_000),
            ("129e6", 129_000_000),
            ("1.5Gi", 3 * GIB / 2),
            ("100k", 100_000),
            ("64Ki", 65536),
            ("12345", 12345),
            ("1000m", 1),
        ] {
            assert_eq!(parse_k8s_quantity(q), Some(v), "{q}");
        }
        assert_eq!(parse_k8s_quantity("lots"), None);
        assert_eq!(parse_k8s_quantity(""), None);
        assert!(keep_label("io.kubernetes.pod.name"));
        assert!(!keep_label("org.opencontainers.image.source"));
        assert_eq!(KubeDistro::from_context("kind-dev"), Some(KubeDistro::Kind));
        assert_eq!(KubeDistro::Kind.cluster_name_from_context("kind-dev"), "dev");
        assert_eq!(KubeDistro::from_context("prod-eu"), None);
    }

    /// A k3s host: cgroup paths give the tree and per-container limits; the API (when present) names them.
    #[test]
    fn host_cluster_from_cgroups_with_limits_and_api_names() {
        let pod_cg = format!("/kubepods/burstable/pod{UID}");
        let ctr_cg = format!("{pod_cg}/{CID}");
        let mut s = Snapshot {
            taken_at_ms: 1_000_000,
            processes: vec![
                Process {
                    name: "k3s".into(),
                    exe: "/usr/local/bin/k3s".into(),
                    cmdline: vec!["/usr/local/bin/k3s".into(), "server".into()],
                    ..proc(100, "k3s", "/system.slice/k3s.service", 500)
                },
                proc(200, "nginx", &ctr_cg, 40),
                proc(201, "nginx", &ctr_cg, 10),
            ],
            ..Default::default()
        };
        s.host.hostname = "box".into();
        s.cgroups = vec![
            CgroupMem {
                path: ctr_cg.clone(),
                current: Some(300 * MIB),
                inactive_file: Some(100 * MIB),
                max: Some(256 * MIB),
                limits_read: true,
                events: Some(MemoryEvents {
                    oom_kill: 2,
                    ..Default::default()
                }),
                at_ms: 1_000_000,
                ..Default::default()
            },
            CgroupMem {
                path: pod_cg.clone(),
                current: Some(310 * MIB),
                inactive_file: Some(100 * MIB),
                limits_read: true,
                at_ms: 1_000_000,
                ..Default::default()
            },
        ];
        let mut tr = IsolationTracker::new();
        tr.update(&mut s);
        let iso = &s.isolation;
        assert_eq!(iso.clusters.len(), 1);
        let c = &iso.clusters[0];
        assert_eq!((c.id.as_str(), c.distro), ("host", KubeDistro::K3s));
        assert!(c.evidence.iter().any(|e| e == "process k3s"), "{:?}", c.evidence);
        let pod = &c.nodes[0].namespaces[0].pods[0];
        assert_eq!(c.nodes[0].name, "box");
        assert_eq!(pod.uid.as_deref(), Some(UID));
        assert_eq!(pod.qos, Some(QosClass::Burstable));
        assert_eq!(pod.mem.value, Some(210 * MIB));
        let k = &pod.containers[0];
        assert_eq!(k.id.as_deref(), Some(CID));
        assert_eq!(k.mem.value, Some(200 * MIB));
        assert_eq!(k.host_pids.len(), 2);
        assert_eq!(k.limit.value, Some(256 * MIB));
        assert_eq!(k.limit_id.as_deref(), Some(format!("cgroup:{ctr_cg}").as_str()));
        assert!(c.notes[0].contains("names need the API"));
        let l = &iso.limits[0];
        assert_eq!(l.kind, LimitKind::Container);
        assert_eq!(l.oom_kills.value, Some(2));
        assert_eq!(l.pct.map(|p| p.round()), Some(78.0));

        // Now the API names the pod (same uid, container id with runtime prefix stripped by the adapter).
        s.isolation.kube = vec![KubeApiData {
            context: "default".into(),
            status: SourceStatus::Available,
            at_ms: 1_000_000,
            pods: vec![KubePodInfo {
                namespace: "shop".into(),
                name: "web-7d9f".into(),
                uid: UID.into(),
                node: Some("box".into()),
                phase: Some("Running".into()),
                qos: Some(QosClass::Burstable),
                containers: vec![KubeContainerSpec {
                    name: "nginx".into(),
                    id: Some(CID.into()),
                    runtime: Some("containerd".into()),
                    mem_limit: Some(256 * MIB),
                    restarts: Some(3),
                    last_termination_reason: Some("OOMKilled".into()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }];
        tr.update(&mut s);
        let c = &s.isolation.clusters[0];
        assert_eq!(
            s.isolation.clusters.len(),
            1,
            "merged into the host cluster by node name"
        );
        let ns = &c.nodes[0].namespaces[0];
        assert_eq!(ns.name, "shop");
        let pod = &ns.pods[0];
        assert_eq!(pod.name.as_deref(), Some("web-7d9f"));
        assert_eq!(pod.containers.len(), 1, "matched by id, not duplicated by name");
        assert_eq!(pod.containers[0].name.as_deref(), Some("nginx"));
        assert_eq!(pod.containers[0].last_termination.as_deref(), Some("OOMKilled"));
        let l = &s.isolation.limits[0];
        assert_eq!(l.label, "nginx");
        assert_eq!(l.pod.as_deref(), Some("shop/web-7d9f"));
        assert_eq!(
            s.isolation.limits.len(),
            1,
            "the API container is covered by its cgroup"
        );
    }

    /// macOS: a kind cluster in Docker Desktop: node containers by label, pods only via the API.
    #[test]
    fn kind_nodes_from_labels_and_api_only_limits() {
        let mut s = Snapshot {
            taken_at_ms: 5_000_000,
            ..Default::default()
        };
        let mut labels = BTreeMap::new();
        labels.insert("io.x-k8s.kind.cluster".to_string(), "dev".to_string());
        labels.insert("io.x-k8s.kind.role".to_string(), "control-plane".to_string());
        s.isolation.containers.push(ContainerInfo {
            sandbox_id: "docker-desktop:aaaa1111bbbb".into(),
            id: "aaaa1111bbbb2222".into(),
            engine: "docker-desktop".into(),
            vm_hosted: true,
            name: "dev-control-plane".into(),
            state: "running".into(),
            labels,
            ..Default::default()
        });
        s.sandboxes.push(Sandbox {
            id: "docker-desktop:aaaa1111bbbb".into(),
            kind: SandboxKind::Container,
            runtime: "docker-desktop".into(),
            label: "dev-control-plane".into(),
            guest_mem: Measured::exact(900 * MIB, "docker-desktop stats"),
            ..Default::default()
        });
        s.isolation.kube = vec![KubeApiData {
            context: "kind-dev".into(),
            distro: None,
            status: SourceStatus::Available,
            at_ms: 5_000_000,
            nodes: vec![KubeNodeStats {
                name: "dev-control-plane".into(),
                working_set: Some(800 * MIB),
                pods: vec![KubePodStats {
                    namespace: "default".into(),
                    name: "api".into(),
                    uid: "u1".into(),
                    containers: vec![KubeContainerStats {
                        name: "app".into(),
                        working_set: Some(120 * MIB),
                        ..Default::default()
                    }],
                    ..Default::default()
                }],
                ..Default::default()
            }],
            pods: vec![KubePodInfo {
                namespace: "default".into(),
                name: "api".into(),
                uid: "u1".into(),
                node: Some("dev-control-plane".into()),
                containers: vec![KubeContainerSpec {
                    name: "app".into(),
                    mem_limit: Some(128 * MIB),
                    ..Default::default()
                }],
                ..Default::default()
            }],
        }];
        let mut tr = IsolationTracker::new();
        tr.update(&mut s);
        let c = &s.isolation.clusters[0];
        assert_eq!((c.id.as_str(), c.distro), ("kind:dev", KubeDistro::Kind));
        assert_eq!(c.context.as_deref(), Some("kind-dev"));
        let n = &c.nodes[0];
        assert_eq!(n.sandbox_id.as_deref(), Some("docker-desktop:aaaa1111bbbb"));
        assert_eq!(n.mem.value, Some(900 * MIB), "the node container's memory");
        let k = &n.namespaces[0].pods[0].containers[0];
        assert_eq!(k.mem.value, Some(120 * MIB));
        assert_eq!(k.limit.value, Some(128 * MIB));
        let l = &s.isolation.limits[0];
        assert_eq!(l.id, "k8s:kind-dev/default/api/app");
        assert_eq!(l.state, crate::limits::LimitState::Near);
        assert_eq!(k.limit_id.as_deref(), Some("k8s:kind-dev/default/api/app"));
    }

    /// Docker Desktop VM: slack is reported as an estimate and never as reclaim; small slack is not.
    #[test]
    fn vm_slack_finding() {
        let vm = ProcId::new(900, 1);
        let mut s = Snapshot::default();
        s.processes.push(Process {
            id: vm,
            mem: MemBreakdown {
                footprint_or_pss: Measured::exact(6 * GIB, "t"),
                ..Default::default()
            },
            ..Default::default()
        });
        s.sandboxes.push(Sandbox {
            id: "vz:docker".into(),
            kind: SandboxKind::Vm,
            runtime: "virtualization.framework".into(),
            label: "Docker VM".into(),
            host_pids: vec![vm],
            configured_mem: Measured::exact(8 * GIB, "docker-desktop /info MemTotal"),
            guest_mem: Measured::estimate(2 * GIB, "Σ container memory (engine stats)"),
            limits: SandboxLimits {
                mem_max: Some(8 * GIB),
                cpus: None,
            },
            footprint_lower_bound: true,
            ..Default::default()
        });
        let v = vm_slack(&s);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].slack.value, Some(4 * GIB));
        assert_eq!(v[0].slack.quality, crate::model::Quality::Estimate);
        assert!(!v[0].counts_as_reclaim);
        assert_eq!(
            v[0].summary,
            "Docker VM: 4.0 GiB held by the VM, not used by containers; restarting the engine returns it"
        );
        assert!(v[0].notes[0].contains("lower bound"));
        // The VM is also a limit: Σ containers against its 8 GiB.
        let mut tr = IsolationTracker::new();
        tr.update(&mut s);
        let l = s.isolation.limit("vz:docker").unwrap();
        assert_eq!((l.kind, l.limit.value), (LimitKind::Vm, Some(8 * GIB)));
        // Containers use nearly everything: no finding.
        s.sandboxes[0].guest_mem = Measured::estimate(5900 * MIB, "Σ container memory (engine stats)");
        assert!(vm_slack(&s).is_empty());
    }

    #[test]
    fn stale_containers() {
        let mut s = Snapshot {
            taken_at_ms: 10_000_000,
            ..Default::default()
        };
        let run = |ns: u64, at: u64| ContainerInfo {
            sandbox_id: "docker:idle".into(),
            name: "idle".into(),
            engine: "docker".into(),
            state: "running".into(),
            started_ms: Some(1_000_000),
            cpu_total_ns: Some(ns),
            stats_at_ms: Some(at),
            ..Default::default()
        };
        s.isolation.containers = vec![
            run(1_000_000_000, 9_000_000),
            ContainerInfo {
                sandbox_id: "docker:old".into(),
                name: "old".into(),
                engine: "docker".into(),
                state: "exited".into(),
                status_text: "Exited (137) 2 days ago".into(),
                finished_ms: Some(10_000_000 - 2 * 3_600_000),
                exit_code: Some(137),
                ..Default::default()
            },
        ];
        let mut tr = IsolationTracker::new();
        tr.update(&mut s);
        assert_eq!(
            s.isolation.stale_containers.len(),
            1,
            "running: not observed long enough yet"
        );
        let old = &s.isolation.stale_containers[0];
        assert_eq!(old.reason, "exited (137) 2 days ago");
        assert!(old.disk.unavailable_reason().unwrap().contains("size=1"));
        // 3 min later, 20 ms of CPU used: 0.01 % → idle.
        s.isolation.containers[0] = run(1_020_000_000, 9_180_000);
        s.taken_at_ms = 10_180_000;
        tr.update(&mut s);
        let st = &s.isolation.stale_containers;
        assert_eq!(st[0].sandbox_id, "docker:idle", "running ones first");
        assert!(st[0].cpu_pct.value.unwrap() < 0.02);
        assert_eq!(st[0].observed_s, 180);
        assert_eq!(st[0].age_s, Some(9180));
        // Busy container: 30 s of CPU in 3 min → not stale.
        s.isolation.containers[0] = run(31_000_000_000, 9_360_000);
        tr.update(&mut s);
        assert!(s
            .isolation
            .stale_containers
            .iter()
            .all(|c| c.sandbox_id != "docker:idle"));
    }

    #[test]
    fn empty_snapshot_is_empty() {
        let mut s = Snapshot::default();
        IsolationTracker::new().update(&mut s);
        assert!(s.isolation.is_empty());
        let json = serde_json::to_value(&s).unwrap();
        assert!(json.get("isolation").is_none(), "left out of JSON when empty");
        assert!(json.get("cgroups").is_none());
    }
}