hprof-analyzer 0.2.0

Fast, low-memory Java HPROF heap-dump analyzer with Eclipse MAT-parity reports (System Overview, Leak Suspects, Top Consumers).
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
//! OOM-triage rule framework: the single source of truth for the "OOM Triage"
//! section. Each rule reads the finished [`Report`] and either fires (emitting a
//! [`TriageSignal`]) or stays silent. [`evaluate_triage`] runs every rule once,
//! in registry order, and the result is stored on `Report.triage`. Both the
//! Markdown and HTML renderers are dumb formatters over that list, so rule logic
//! lives in exactly one place.
//!
//! A rule "declares the data it needs" implicitly by which `Report` fields it
//! reads in `eval`; each rule's doc-comment states that dependency explicitly.

use crate::report::format::{fmt_count, format_bytes};
use crate::report::model::{Report, TriageSeverity, TriageSignal};

// ── Thresholds ────────────────────────────────────────────────────────────────
// Each rule fires only when its signal crosses one of these. Kept together so
// the whole triage policy is visible in one place.

/// If the single largest suspect retains at least this share of the reachable
/// heap, the heap is called "highly concentrated".
const CONCENTRATION_PCT: f64 = 50.0;
/// DirectByteBuffer capacity floor (bytes) before the off-heap rule fires.
const DBB_FLOOR_BYTES: u64 = 64 * 1024 * 1024;
/// Unreachable-shallow share of total heap at which the GC-waste rule fires.
const GC_WASTE_RATIO: f64 = 0.10;
/// A single thread retaining at least this share of the heap flags pinning.
const THREAD_PIN_PCT: f64 = 20.0;
/// …or a thread holding at least this many live thread-local roots, provided it
/// also retains at least [`THREAD_PIN_LOCALS_MIN_PCT`] of the heap (the min-share
/// gate keeps normal threads like `main`, which hold many roots at trivial
/// retention, from tripping the rule).
const THREAD_PIN_LOCALS: u64 = 100;
/// Minimum retained share for the many-local-roots branch to fire.
const THREAD_PIN_LOCALS_MIN_PCT: f64 = 10.0;
/// Top GC-root type retaining at least this share of the heap.
const GC_ROOT_DOMINANT_PCT: f64 = 50.0;
/// Anonymous/generated classes as a share of all loaded classes.
const PROXY_BLOAT_PCT: f64 = 50.0;
/// Ignore proxy/lambda bloat on dumps with fewer than this many classes.
const PROXY_MIN_CLASSES: u64 = 200;
/// Objects reachable only via soft/weak/phantom refs before the escape rule.
const WEAKREF_FLOOR: u64 = 1000;
/// Retained bytes reachable only via soft/weak/phantom refs before the escape rule.
const WEAKREF_BYTES_FLOOR: u64 = 5 * 1024 * 1024; // 5 MB
/// Wasted collection backing-array bytes as a share of heap.
const OVERCAP_WASTE_PCT: f64 = 5.0;
/// Total shallow bytes in constant-value primitive arrays before the rule.
const CONSTARR_FLOOR: u64 = 8 * 1024 * 1024;
/// Fill ratio (basis points) below which a collection counts as "under-filled".
const OVERCAP_FILL_BP: u32 = 5000;
/// Duplicate-String waste floor (bytes) before the duplicate-strings rule fires.
const DUP_STRINGS_FLOOR_BYTES: u64 = 16 * 1024 * 1024;
/// …or duplicate-String waste as a share of the heap.
const DUP_STRINGS_PCT: f64 = 5.0;
/// char[]/byte[] backing-array slack floor (bytes) for the char-array-slack rule.
const CHAR_SLACK_FLOOR_BYTES: u64 = 16 * 1024 * 1024;
/// …and a minimum count of wasteful arrays, so a handful of big ones don't fire.
const CHAR_SLACK_MIN_ARRAYS: u64 = 1000;
/// Boxed-primitive instance-count floor before the boxed-bloat rule fires.
const BOXED_FLOOR_INSTANCES: u64 = 5_000_000;
/// …or boxed-primitive shallow as a share of the heap.
const BOXED_PCT: f64 = 5.0;
/// A single collection with at least this many elements is called "unbounded".
const UNBOUNDED_COLL_ELEMENTS: u64 = 1_000_000;
/// …or one collection retaining at least this share of the heap.
const UNBOUNDED_COLL_PCT: f64 = 20.0;
/// Live-instance floor for the object-swarm rule (one tiny class, huge count).
const SWARM_FLOOR_INSTANCES: u64 = 10_000_000;
/// …its aggregate shallow as a share of the heap.
const SWARM_PCT: f64 = 10.0;
/// …and a per-instance shallow ceiling (bytes): swarms are many *small* objects.
const SWARM_MAX_INSTANCE_BYTES: u64 = 64;
/// Live ClassLoader-instance count before the classloader-explosion rule fires.
const CLASSLOADER_EXPLOSION_FLOOR: u64 = 1000;
/// Live-thread count before the thread-swarm rule fires.
const THREAD_SWARM_FLOOR: usize = 1000;
/// `java.lang.ref.Finalizer` instance count that signals a backed-up queue.
const FINALIZER_FLOOR: u64 = 10_000;
/// Loaded-class count above which Metaspace pressure is likely.
const METASPACE_CLASS_FLOOR: u64 = 50_000;
/// Combined reflect.{Method,Field,Constructor} instances suggesting unbounded caches.
const REFLECT_FLOOR: u64 = 500_000;
/// "JNI Global" root count that, together with a retained-share threshold,
/// indicates a JNI global-reference leak.
const JNI_GLOBAL_FLOOR: u64 = 5_000;
/// Minimum retained share for the JNI-global rule to fire.
const JNI_GLOBAL_RETAINED_PCT: f64 = 5.0;
/// Single heap-composition kind share that constitutes "skew".
const HEAP_SKEW_PCT: f64 = 70.0;
/// Suspect retained share at which the static-field-anchor rule fires.
const STATIC_ANCHOR_PCT: f64 = 20.0;
/// Session/request-scope class instance floor (name-pattern gate).
const SESSION_FLOOR: u64 = 100_000;
/// Connection/socket class instance floor (name-pattern gate).
const CONNECTION_FLOOR: u64 = 1_000;
/// Listener/observer class instance floor (name-pattern gate).
const LISTENER_FLOOR: u64 = 100_000;
/// Parser-output class instance floor (package-pattern gate).
const PARSER_FLOOR: u64 = 100_000;
/// String instance count + JNI global count that together signal intern() abuse.
const INTERNED_STRING_FLOOR: u64 = 2_000_000;
const INTERNED_JNI_FLOOR: u64 = 1_000;
/// Object-array fill ratio (bp) below which arrays are "sparse"; must have
/// >= this many tracked arrays and wasted share >= SPARSE_ARRAY_WASTED_PCT.
const SPARSE_ARRAY_FILL_BP: u32 = 2_000; // 20%
const SPARSE_ARRAY_MIN_TRACKED: u64 = 10_000;
const SPARSE_ARRAY_WASTED_PCT: f64 = 5.0;
/// Big-drop node drop_bytes as share of total shallow heap.
const BIG_DROP_PCT: f64 = 5.0;
/// Big-drop absolute floor (bytes).
const BIG_DROP_FLOOR: u64 = 64 * 1024 * 1024;
/// Object header overhead share above which the fixed-per-object rule fires.
const HEADER_OVERHEAD_PCT: f64 = 20.0;
/// Hash-map collision ratio (load-factor proxy in bp) above which hotspot fires.
/// Bucket upper_ratio_bp > COLLISION_HIGH_BP means the map is very dense.
const COLLISION_HIGH_BP: u32 = 9_000; // > 90% load → chain collisions likely
/// Minimum collision-ratio tracked maps for the rule to fire.
const COLLISION_MIN_TRACKED: u64 = 100;
/// Empty-collection share above which the cemetery rule fires.
const EMPTY_COLL_SHARE_PCT: f64 = 60.0;
/// Absolute empty-collection count floor.
const EMPTY_COLL_FLOOR: u64 = 500_000;
/// Single primitive array shallow bytes as share of heap.
const OVERSIZED_PRIM_ARRAY_PCT: f64 = 5.0;
/// Absolute floor for the oversized-primitive-array rule.
const OVERSIZED_PRIM_ARRAY_FLOOR: u64 = 64 * 1024 * 1024;
/// Duplicate-primitive-array wasted bytes as share of heap.
const DUP_PRIM_ARRAYS_PCT: f64 = 5.0;
/// Duplicate-primitive-array absolute wasted-bytes floor.
const DUP_PRIM_ARRAYS_FLOOR: u64 = 16 * 1024 * 1024;

// ── Framework ─────────────────────────────────────────────────────────────────

/// A single OOM-triage rule. Reads the finished report; returns `Some` when the
/// signal fires, `None` when it does not.
pub trait Rule {
    fn eval(&self, r: &Report) -> Option<TriageSignal>;
}

/// Ordered rule registry. **Order here is the render order** (show-all-that-fire).
fn rules() -> Vec<Box<dyn Rule>> {
    vec![
        Box::new(HeadlineRetainer),
        Box::new(Concentration),
        Box::new(DominantGcRootType),
        Box::new(Shape),
        Box::new(OneLeakOrMany),
        Box::new(ObjectSwarm),
        Box::new(BoxedPrimitiveBloat),
        Box::new(ClassloaderLeak),
        Box::new(ClassloaderExplosion),
        Box::new(MetaspacePressure),
        Box::new(ThreadLocalLeak),
        Box::new(ThreadPinning),
        Box::new(ThreadSwarm),
        Box::new(WeakRefEscape),
        Box::new(ProxyLambdaBloat),
        Box::new(OffHeap),
        Box::new(GcWaste),
        Box::new(StaticFieldAnchor),
        Box::new(JniGlobalRefLeak),
        Box::new(HeapCompositionSkew),
        Box::new(FinalizerQueueBacklog),
        Box::new(CachedReflectionMetadata),
        Box::new(SessionScopeLeak),
        Box::new(ConnectionLeak),
        Box::new(EventListenerAccumulation),
        Box::new(ParserOutputAccumulation),
        Box::new(InternedStringBloat),
        Box::new(DuplicateStrings),
        Box::new(CharArraySlack),
        Box::new(OverCapacityCollections),
        Box::new(LargeUnboundedCollection),
        Box::new(SparseObjectArrays),
        Box::new(ConstantValueArrays),
        Box::new(BigDropConcentration),
        Box::new(FixedPerObjectOverhead),
        Box::new(HashCollisionHotspot),
        Box::new(EmptyCollectionCemetery),
        Box::new(OversizedPrimArray),
        Box::new(DuplicatePrimArrays),
    ]
}

/// Evaluate every rule once, in registry order, collecting the ones that fire.
pub fn evaluate_triage(r: &Report) -> Vec<TriageSignal> {
    let mut signals: Vec<TriageSignal> = rules().iter().filter_map(|rule| rule.eval(r)).collect();
    if r.collection_attribution.is_none() {
        signals.push(signal(
            "collections-not-analyzed",
            TriageSeverity::Info,
            "Collection Waste Not Analyzed",
            "Collection waste not analyzed — re-run with `--collections` to check for wasted capacity."
                .to_string(),
            None,
        ));
    }
    signals
}

/// Percentage of total reachable shallow heap. Basis matches the report tables.
fn pct_of(retained: u64, total: u64) -> f64 {
    if total > 0 {
        retained as f64 / total as f64 * 100.0
    } else {
        0.0
    }
}

/// Small `TriageSignal` builder for the common linked case.
fn signal(
    id: &str,
    severity: TriageSeverity,
    title: &str,
    detail: String,
    anchor: Option<(&str, &str)>,
) -> TriageSignal {
    let (anchor, anchor_label) = match anchor {
        Some((a, l)) => (Some(a.to_string()), Some(l.to_string())),
        None => (None, None),
    };
    TriageSignal {
        id: id.to_string(),
        severity,
        title: title.to_string(),
        detail,
        anchor,
        anchor_label,
        bytes: None,
        nav_class: None,
    }
}

fn signal_cls(
    id: &str,
    severity: TriageSeverity,
    title: &str,
    detail: String,
    anchor: Option<(&str, &str)>,
    nav_class: impl Into<String>,
) -> TriageSignal {
    let mut s = signal(id, severity, title, detail, anchor);
    s.nav_class = Some(nav_class.into());
    s
}

// ── Rules (ported from the former render_md.rs hand-written logic) ─────────────

/// Headline retainer. Reads `leaks.suspects` / `top.biggest_objects`. Always
/// fires (the fallback variant names no offender).
struct HeadlineRetainer;
impl Rule for HeadlineRetainer {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.leaks.total_shallow;
        if let Some(s) = r.leaks.suspects.first() {
            let kind = if s.is_single {
                "a single object"
            } else {
                "a class group"
            };
            Some(signal_cls(
                "headline-retainer",
                TriageSeverity::Critical,
                "Headline Retainer",
                format!(
                    "`{}` ({}) retains {} ({:.1}% of reachable heap).",
                    s.pretty_class,
                    kind,
                    format_bytes(s.retained),
                    pct_of(s.retained, total),
                ),
                Some(("leak-suspects", "Leak Suspects")),
                &s.pretty_class,
            ))
        } else if let Some(o) = r.top.biggest_objects.first() {
            Some(signal_cls(
                "headline-retainer",
                TriageSeverity::Warning,
                "Headline Retainer",
                format!(
                    "`{}` retains {} ({:.1}% of reachable heap).",
                    o.display_class,
                    format_bytes(o.retained),
                    pct_of(o.retained, total),
                ),
                Some(("top-consumers", "Top Consumers")),
                &o.display_class,
            ))
        } else {
            Some(signal(
                "headline-retainer",
                TriageSeverity::Info,
                "Headline Retainer",
                "No dominant retainer found.".to_string(),
                None,
            ))
        }
    }
}

/// Concentration. Reads `leaks.suspects` and (for the owner join) the biggest
/// object's `owner`. Always fires (concentrated vs. diffuse variants).
struct Concentration;
impl Rule for Concentration {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.leaks.total_shallow;
        let sig = match r.leaks.suspects.first() {
            Some(s) if pct_of(s.retained, total) >= CONCENTRATION_PCT => {
                let kind = if s.is_single {
                    "a single object".to_string()
                } else {
                    format!("a class group of {} instances", s.instance_count)
                };
                let owner = if s.is_single {
                    r.top.biggest_objects.first().and_then(|o| {
                        if o.display_class == s.pretty_class {
                            o.owner.as_deref()
                        } else {
                            None
                        }
                    })
                } else {
                    None
                };
                let held_by = match owner {
                    Some(o) => format!(" held by `{o}`"),
                    None => String::new(),
                };
                signal_cls(
                    "concentration",
                    TriageSeverity::Critical,
                    "Concentration",
                    format!(
                        "highly concentrated — `{}` ({}){} holds {:.1}% of the heap; freeing this object would reclaim most of the heap.",
                        s.pretty_class,
                        kind,
                        held_by,
                        pct_of(s.retained, total),
                    ),
                    Some(("leak-suspects", "Leak Suspects")),
                    &s.pretty_class,
                )
            }
            Some(_) => signal(
                "concentration",
                TriageSeverity::Info,
                "Concentration",
                "diffuse — no suspect exceeds the threshold; retention is spread across multiple roots. Inspect individual suspects to find the most impactful target.".to_string(),
                Some(("leak-suspects", "Leak Suspects")),
            ),
            None => signal(
                "concentration",
                TriageSeverity::Info,
                "Concentration",
                "diffuse — no dominant retainer found; retention is spread evenly across many roots.".to_string(),
                None,
            ),
        };
        Some(sig)
    }
}

/// Dominant GC-root type. Reads `overview.gc_roots_retained_by_type`.
struct DominantGcRootType;
impl Rule for DominantGcRootType {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.leaks.total_shallow;
        let top = r.overview.gc_roots_retained_by_type.first()?;
        let pct = pct_of(top.retained, total);
        if pct < GC_ROOT_DOMINANT_PCT {
            return None;
        }
        Some(signal(
            "gc-root-type",
            TriageSeverity::Warning,
            "Dominant GC-Root Type",
            format!(
                "{:.1}% of the heap is held by \"{}\" roots — the GC Roots by Type table shows the per-class breakdown.",
                pct, top.root_type,
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Shape. Reads `overview.dominator_depth_histogram`.
struct Shape;
impl Rule for Shape {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let hist = &r.overview.dominator_depth_histogram;
        if hist.is_empty() {
            return None;
        }
        let total: u64 = hist.iter().map(|b| b.objects).sum();
        let max_depth = hist.iter().map(|b| b.depth).max().unwrap_or(0);
        let mut cum = 0u64;
        let mut p90 = max_depth;
        for b in hist {
            cum += b.objects;
            if cum * 10 >= total * 9 {
                p90 = b.depth;
                break;
            }
        }
        let shape = if p90 <= 3 {
            "shallow (most objects are held within a few hops of a GC root)"
        } else {
            "deep — long dominator chains suggest nested collections or linked structures; the depth histogram shows the distribution; use the Big Drops table to find the retaining objects"
        };
        Some(signal(
            "shape",
            TriageSeverity::Info,
            "Heap Shape",
            format!("{shape} — 90% of objects within depth {p90}, max depth {max_depth}."),
            Some((
                "dominator-depth-distribution",
                "Dominator-Depth Distribution",
            )),
        ))
    }
}

/// One leak or many. Reads `overview.retention_concentration` and the biggest
/// object's `owner`.
struct OneLeakOrMany;
impl Rule for OneLeakOrMany {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let rc = &r.overview.retention_concentration;
        if rc.top1_bp == 0 && rc.num_objects_ge_1pct == 0 {
            return None;
        }
        let top1_pct = rc.top1_bp as f64 / 100.0;
        let top10_pct = rc.top10_bp as f64 / 100.0;
        let top_obj = r.top.biggest_objects.first();
        let detail = match top_obj.map(|o| match o.owner.as_deref() {
            Some(owner) => format!("`{}` (held by `{}`)", o.display_class, owner),
            None => format!("`{}`", o.display_class),
        }) {
            Some(name) => format!(
                "the single biggest object, {}, retains {:.1}% and the top 10 retain {:.1}% of the heap; {} objects each hold ≥1%.",
                name, top1_pct, top10_pct, rc.num_objects_ge_1pct,
            ),
            None => format!(
                "the single biggest object retains {:.1}% and the top 10 retain {:.1}% of the heap; {} objects each hold ≥1%.",
                top1_pct, top10_pct, rc.num_objects_ge_1pct,
            ),
        };
        let nav_class = top_obj
            .filter(|o| o.owner.is_none())
            .map(|o| o.display_class.clone());
        let mut sig = signal(
            "one-leak-or-many",
            TriageSeverity::Info,
            "One Leak or Many",
            detail,
            Some(("top-consumers", "Top Consumers")),
        );
        sig.nav_class = nav_class;
        Some(sig)
    }
}

// ── New rules ──────────────────────────────────────────────────────────────

/// Classloader leak. Reads `overview.duplicate_classes`.
struct ClassloaderLeak;
impl Rule for ClassloaderLeak {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let dup = r
            .overview
            .duplicate_classes
            .iter()
            .max_by_key(|d| d.total_retained)?;
        if dup.total_retained < 524_288 {
            return None;
        }
        if dup.loader_count < 5 {
            return Some(signal_cls(
                "classloader-leak",
                TriageSeverity::Info,
                "Class-Loader Reload (Low Count)",
                format!(
                    "`{}` is loaded by {} class loaders ({} retained) — possible reload, but count is low; investigate only if count grows.",
                    dup.pretty_class,
                    dup.loader_count,
                    format_bytes(dup.total_retained),
                ),
                Some(("duplicate-classes", "Duplicate Classes")),
                &dup.pretty_class,
            ));
        }
        Some(signal_cls(
            "classloader-leak",
            TriageSeverity::Warning,
            "Class-Loader Leak",
            format!(
                "`{}` is loaded by {} class loaders ({} retained) — classic redeploy/hot-reload leak; the old loader is still live. Check for static fields, ThreadLocals, or JNI globals referencing the old class.",
                dup.pretty_class,
                dup.loader_count,
                format_bytes(dup.total_retained),
            ),
            Some(("duplicate-classes", "Duplicate Classes")),
            &dup.pretty_class,
        ))
    }
}

/// ThreadLocal leak. Reads `leak_indicators.thread_local_null_key_count`.
struct ThreadLocalLeak;
impl Rule for ThreadLocalLeak {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let n = r.leak_indicators.thread_local_null_key_count;
        if n == 0 {
            return None;
        }
        Some(signal(
            "threadlocal-leak",
            TriageSeverity::Warning,
            "ThreadLocal Leak",
            format!(
                "{} ThreadLocalMap entries have a cleared key — the `ThreadLocal` object was GC'd but the value was never removed. Values accumulate until the thread terminates or `ThreadLocal.remove()` is called. Common in thread-pooled servers.",
                fmt_count(n),
            ),
            Some(("leak-indicators", "Leak Indicators")),
        ))
    }
}

/// Thread pinning. Reads `threads.threads` (retained + local_root_count).
struct ThreadPinning;
impl Rule for ThreadPinning {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.leaks.total_shallow;
        let t = r.threads.threads.iter().max_by_key(|t| t.retained)?;
        let share = pct_of(t.retained, total);
        if share < THREAD_PIN_PCT
            && !(t.local_root_count >= THREAD_PIN_LOCALS && share >= THREAD_PIN_LOCALS_MIN_PCT)
        {
            return None;
        }
        let who = t
            .name
            .as_deref()
            .or(t.class_name.as_deref())
            .unwrap_or("<unknown thread>");
        Some(signal(
            "thread-pinning",
            TriageSeverity::Warning,
            "Thread Pinning",
            format!(
                "thread `{}` retains {} ({:.1}% of heap) via {} thread-local GC root references — a running thread is pinning a disproportionate share of the heap. Inspect the thread's stack frames and ThreadLocal values.",
                who,
                format_bytes(t.retained),
                share,
                fmt_count(t.local_root_count),
            ),
            Some(("threads", "Threads")),
        ))
    }
}

/// Weak-ref escape. Reads `references.{soft,weak,phantom}.only_weakly_retained`.
struct WeakRefEscape;
impl Rule for WeakRefEscape {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let refs = &r.references;
        let only_weak_objects: u64 = [&refs.soft, &refs.weak, &refs.phantom]
            .into_iter()
            .flatten()
            .flat_map(|s| s.only_weakly_retained.iter())
            .map(|row| row.objects)
            .sum();
        let only_weak_retained: u64 = [&refs.soft, &refs.weak, &refs.phantom]
            .into_iter()
            .flatten()
            .flat_map(|s| s.only_weakly_retained.iter())
            .map(|row| row.retained)
            .sum();
        if only_weak_objects < WEAKREF_FLOOR && only_weak_retained < WEAKREF_BYTES_FLOOR {
            return None;
        }
        Some(signal(
            "weak-ref-escape",
            TriageSeverity::Info,
            "Only-Weakly Retained Objects",
            format!(
                "{} objects only weakly, softly, or phantom-retained, totaling {} — no strong path keeps them alive; GC will reclaim weak referents at the next collection and soft referents under memory pressure. If the count is unexpectedly high, check that no strong reference is silently held alongside the weak one.",
                fmt_count(only_weak_objects),
                format_bytes(only_weak_retained),
            ),
            Some(("references", "References")),
        ))
    }
}

/// Proxy/lambda bloat. Reads `leak_indicators.anonymous_class_count` and
/// `overview.classes_loaded`.
struct ProxyLambdaBloat;
impl Rule for ProxyLambdaBloat {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let anon = r.leak_indicators.anonymous_class_count;
        let loaded = r.overview.classes_loaded;
        if loaded < PROXY_MIN_CLASSES {
            return None;
        }
        let share = anon as f64 / loaded as f64 * 100.0;
        if share < PROXY_BLOAT_PCT {
            return None;
        }
        Some(signal(
            "proxy-lambda-bloat",
            TriageSeverity::Info,
            "Proxy/Lambda Bloat",
            format!(
                "{} of {} loaded classes ({:.1}%) are anonymous/generated (lambda/proxy) — possible class-loader churn; cache generated proxies or upgrade to newer Java where lambdas are method handles.",
                fmt_count(anon),
                fmt_count(loaded),
                share,
            ),
            Some(("leak-indicators", "Leak Indicators")),
        ))
    }
}

/// Off-heap (DirectByteBuffer). Reads `leak_indicators.direct_byte_buffer_capacity_sum`.
struct OffHeap;
impl Rule for OffHeap {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let cap = r.leak_indicators.direct_byte_buffer_capacity_sum;
        if cap < DBB_FLOOR_BYTES {
            return None;
        }
        Some(signal(
            "off-heap",
            TriageSeverity::Warning,
            "Off-Heap (DirectByteBuffer)",
            format!(
                "{} of native memory is held by live DirectByteBuffers — not reflected in the on-heap totals, but counts against process RSS and can trigger OS-level OOM.",
                format_bytes(cap),
            ),
            Some(("off-heap-nio", "Off-Heap NIO")),
        ))
    }
}

/// `unreachable_retained`, `unreachable_garbage_roots`.
struct GcWaste;
impl Rule for GcWaste {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let o = &r.overview;
        if o.heap_fragmentation_ratio < GC_WASTE_RATIO {
            return None;
        }
        let pct = o.heap_fragmentation_ratio * 100.0;
        let cluster = o
            .unreachable_garbage_roots
            .first()
            .map(|g| {
                format!(
                    " — largest garbage cluster rooted at `{}` ({})",
                    g.pretty_class,
                    format_bytes(g.retained),
                )
            })
            .unwrap_or_default();
        let size_desc =
            if o.unreachable_retained > o.unreachable_shallow + o.unreachable_shallow / 20 {
                format!(
                    "{} shallow, {} retained",
                    format_bytes(o.unreachable_shallow),
                    format_bytes(o.unreachable_retained)
                )
            } else {
                format_bytes(o.unreachable_shallow)
            };
        Some(signal(
            "gc-waste",
            TriageSeverity::Warning,
            "GC Waste",
            format!(
                "{:.1}% of the heap is unreachable ({}){}; the GC has not yet collected it. Trigger a full GC (`jcmd <pid> GC.run`) and re-dump — if the count drops sharply, the dump was taken mid-collection.",
                pct, size_desc, cluster,
            ),
            Some(("unreachable-objects", "Unreachable Objects")),
        ))
    }
}

/// Over-capacity collections (--collections only). Reads
/// `collections.collection_fill_ratio`. `tracked == 0` when --collections was off.
struct OverCapacityCollections;
impl Rule for OverCapacityCollections {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.leaks.total_shallow;
        let cfr = &r.collections.collection_fill_ratio;
        if cfr.tracked == 0 || total == 0 {
            return None;
        }
        let wasted: u64 = cfr
            .buckets
            .iter()
            .filter(|b| b.upper_ratio_bp <= OVERCAP_FILL_BP)
            .map(|b| b.wasted)
            .sum();
        if wasted as f64 / total as f64 * 100.0 < OVERCAP_WASTE_PCT {
            return None;
        }
        Some(signal(
            "over-capacity-collections",
            TriageSeverity::Info,
            "Over-Capacity Collections",
            format!(
                "{} wasted by under-filled collections (≤50% full across {} tracked) — for lists call `trimToSize()` after bulk population; for all types right-size initial capacity so the backing array is not over-allocated at construction.",
                format_bytes(wasted),
                fmt_count(cfr.tracked),
            ),
            Some(("collections", "Collections")),
        ))
    }
}

/// Constant-value arrays (--collections only). Reads
/// `collections.constant_primitive_arrays`. Empty rows when --collections was off.
struct ConstantValueArrays;
impl Rule for ConstantValueArrays {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let cpa = &r.collections.constant_primitive_arrays;
        if cpa.rows.is_empty() {
            return None;
        }
        let sum: u64 = cpa.rows.iter().map(|row| row.shallow).sum();
        if sum < CONSTARR_FLOOR {
            return None;
        }
        let big = cpa.rows.iter().max_by_key(|row| row.shallow)?;
        Some(signal_cls(
            "constant-value-arrays",
            TriageSeverity::Info,
            "Constant-Value Arrays",
            format!(
                "{} in single-value primitive arrays; biggest group `{}` × {} instances — replace duplicates with a shared constant (e.g. `static final byte[] EMPTY = new byte[0]`).",
                format_bytes(sum),
                big.array_class,
                fmt_count(big.objects),
            ),
            Some(("collections", "Collections")),
            &big.array_class,
        ))
    }
}

// ── New rules (batch 2) ───────────────────────────────────────────────────────

/// Object swarm. Reads `overview.histogram`. Fires when a single non-array class
/// has >= SWARM_FLOOR_INSTANCES live instances that are individually tiny but
/// collectively consume a large heap share — the signature of an unbounded
/// event/log/DTO accumulation.
struct ObjectSwarm;
impl Rule for ObjectSwarm {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.overview.total_shallow;
        let row = r
            .overview
            .histogram
            .iter()
            .filter(|h| {
                !h.pretty_class.ends_with("[]")
                    && h.instances >= SWARM_FLOOR_INSTANCES
                    && (h.instances == 0 || h.shallow / h.instances <= SWARM_MAX_INSTANCE_BYTES)
            })
            .max_by_key(|h| h.shallow)?;
        if pct_of(row.shallow, total) < SWARM_PCT {
            return None;
        }
        Some(signal_cls(
            "object-swarm",
            TriageSeverity::Warning,
            "Object Swarm",
            format!(
                "{} live `{}` instances ({} shallow, {:.1}% of heap) — many tiny objects accumulating; check for an unbounded queue, growing log buffer, or DTO/event accumulation. Either cap the collection or process and discard entries on-the-fly.",
                fmt_count(row.instances),
                row.pretty_class,
                format_bytes(row.shallow),
                pct_of(row.shallow, total),
            ),
            Some(("system-overview", "System Overview")),
            &row.pretty_class,
        ))
    }
}

/// Boxed-primitive bloat. Reads `overview.histogram`. Fires when the total
/// live count of `java.lang.{Integer,Long,Double,…}` wrapper objects is very
/// high — often a Map/List that should use a primitive-specialized collection.
struct BoxedPrimitiveBloat;
impl Rule for BoxedPrimitiveBloat {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        const BOXED: &[&str] = &[
            "java.lang.Integer",
            "java.lang.Long",
            "java.lang.Double",
            "java.lang.Float",
            "java.lang.Short",
            "java.lang.Byte",
            "java.lang.Character",
            "java.lang.Boolean",
        ];
        let total = r.overview.total_shallow;
        let (instances, shallow, worst_class) = r
            .overview
            .histogram
            .iter()
            .filter(|h| BOXED.iter().any(|b| h.pretty_class == *b))
            .fold((0u64, 0u64, ""), |(inst, sh, worst), h| {
                let new_worst = if h.instances > inst || worst.is_empty() {
                    h.pretty_class.as_str()
                } else {
                    worst
                };
                (inst + h.instances, sh + h.shallow, new_worst)
            });
        if instances < BOXED_FLOOR_INSTANCES && pct_of(shallow, total) < BOXED_PCT {
            return None;
        }
        Some(signal(
            "boxed-primitive-bloat",
            TriageSeverity::Info,
            "Boxed-Primitive Bloat",
            format!(
                "{} boxed-primitive objects ({} shallow, led by `{}`) — consider primitive-specialized collections (e.g. Eclipse Collections, Koloboke).",
                fmt_count(instances),
                format_bytes(shallow),
                worst_class,
            ),
            Some(("boxed-numbers", "Boxed Numbers")),
        ))
    }
}

/// Classloader explosion. Reads `overview.classloaders_loaded`. Fires when the
/// live ClassLoader count is abnormally high — dynamic scripting (Groovy/JSP),
/// repeated redeployments, or proxy generators leaking loaders.
struct ClassloaderExplosion;
impl Rule for ClassloaderExplosion {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let n = r.overview.classloaders_loaded;
        if n < CLASSLOADER_EXPLOSION_FLOOR {
            return None;
        }
        Some(signal(
            "classloader-explosion",
            TriageSeverity::Warning,
            "Class-Loader Explosion",
            format!(
                "{} live class-loader instances — abnormally high; typical apps use tens. Likely dynamic-class or redeploy leak: check for Groovy/JSP script-engine leaks, CGLIB proxy caching, or undischarged application-server contexts.",
                fmt_count(n),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Thread swarm. Reads `threads.threads`. Fires when the live thread count is
/// abnormally high — unbounded thread creation or a leaking
/// ExecutorService/ThreadPoolExecutor per request. The aggregate-share path is
/// intentionally omitted: a high aggregate caused by *one* dominant thread is
/// already surfaced by ThreadPinning; thread-swarm targets *count*.
struct ThreadSwarm;
impl Rule for ThreadSwarm {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let threads = &r.threads.threads;
        let count = threads.len();
        if count < THREAD_SWARM_FLOOR {
            return None;
        }
        let aggregate_retained: u64 = threads.iter().map(|t| t.retained).sum();
        Some(signal(
            "thread-swarm",
            TriageSeverity::Warning,
            "Thread Swarm",
            format!(
                "{} live threads retaining {} in aggregate — likely unbounded thread creation or a leaking thread pool. Ensure ExecutorServices are shut down when no longer needed; on Java 21+ prefer virtual threads for I/O-bound workloads.",
                fmt_count(count as u64),
                format_bytes(aggregate_retained),
            ),
            Some(("threads", "Threads")),
        ))
    }
}

/// Duplicate strings (--find-duplicates only). Reads
/// `overview.duplicate_strings.{approx_wasted_bytes, top_duplicated}`.
/// Silent when `--find-duplicates` was not passed.
struct DuplicateStrings;
impl Rule for DuplicateStrings {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let ds = r.overview.duplicate_strings.as_ref()?;
        let total = r.overview.total_shallow;
        if ds.approx_wasted_bytes < DUP_STRINGS_FLOOR_BYTES
            && pct_of(ds.approx_wasted_bytes, total) < DUP_STRINGS_PCT
        {
            return None;
        }
        let top = ds.top_duplicated.first();
        let example = top
            .map(|t| format!("; `\"{}\"` repeated {}×", t.text, fmt_count(t.count),))
            .unwrap_or_default();
        Some(signal(
            "duplicate-strings",
            TriageSeverity::Info,
            "Duplicate Strings",
            format!(
                "~{} wasted by {} duplicated String values ({} total instances){}. Enable JVM string deduplication (`-XX:+UseStringDeduplication` with G1GC), or intern/pool strings at creation time.",
                format_bytes(ds.approx_wasted_bytes),
                fmt_count(ds.duplicated_values),
                fmt_count(ds.total_string_instances),
                example,
            ),
            Some(("duplicate-strings", "Duplicate Strings")),
        ))
    }
}

/// Char-array slack (--find-duplicates only). Reads
/// `overview.duplicate_strings.char_array_waste`. Silent when `--find-duplicates`
/// was not passed or no char-array waste was computed.
struct CharArraySlack;
impl Rule for CharArraySlack {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let caw = r
            .overview
            .duplicate_strings
            .as_ref()
            .and_then(|ds| ds.char_array_waste.as_ref())?;
        if caw.total_wasted_bytes < CHAR_SLACK_FLOOR_BYTES
            || caw.wasteful_arrays < CHAR_SLACK_MIN_ARRAYS
        {
            return None;
        }
        Some(signal(
            "char-array-slack",
            TriageSeverity::Info,
            "Char-Array Slack",
            format!(
                "~{} slack in {} over-allocated char[]/byte[] String backing arrays — common from pre-sized `StringBuilder` allocations that are never fully filled, or `String(byte[], offset, length)` where the source array is larger than the result. Use `new String(str)` to copy-compact, or size StringBuilder capacity to the expected output length.",
                format_bytes(caw.total_wasted_bytes),
                fmt_count(caw.wasteful_arrays),
            ),
            Some(("duplicate-strings", "Duplicate Strings")),
        ))
    }
}

/// Large unbounded collection (--collections only). Reads `biggest_collections`.
/// Fires when a single collection instance has an extreme element count or
/// dominates the heap — the archetypal static/unbounded cache.
struct LargeUnboundedCollection;
impl Rule for LargeUnboundedCollection {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let bc = r.biggest_collections.as_ref()?;
        let row = bc.combined.iter().max_by_key(|c| c.elements)?;
        if row.elements < UNBOUNDED_COLL_ELEMENTS {
            // Also check by retained share when available.
            let retained_ok = row
                .retained
                .map(|ret| pct_of(ret, r.leaks.total_shallow) >= UNBOUNDED_COLL_PCT)
                .unwrap_or(false);
            if !retained_ok {
                return None;
            }
        }
        let retained_str = row
            .retained
            .map(|ret| format!(", retaining {}", format_bytes(ret)))
            .unwrap_or_default();
        let owner_str = row
            .owner
            .as_deref()
            .map(|o| format!(" (held by `{}`)", o))
            .unwrap_or_default();
        Some(signal_cls(
            "large-unbounded-collection",
            TriageSeverity::Warning,
            "Large Unbounded Collection",
            format!(
                "one `{}` holds {} elements{}{} — likely a static or unbounded cache that never evicts. Add a maximum-size eviction policy (e.g. Caffeine/Guava `maximumSize`, `LinkedHashMap` LRU override, or `removeEldestEntry`).",
                row.container_class,
                fmt_count(row.elements),
                retained_str,
                owner_str,
            ),
            Some(("biggest-collections", "Biggest Collections")),
            &row.container_class,
        ))
    }
}

// ── New rules (batch 3) ───────────────────────────────────────────────────────

/// Finalizer queue backlog. Reads `overview.histogram` for `java.lang.ref.Finalizer`.
/// Fires when the finalizer thread cannot drain the queue as fast as objects are
/// promoted to it.
struct FinalizerQueueBacklog;
impl Rule for FinalizerQueueBacklog {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let row = r
            .overview
            .histogram
            .iter()
            .find(|h| h.pretty_class == "java.lang.ref.Finalizer")?;
        if row.instances < FINALIZER_FLOOR {
            return None;
        }
        Some(signal(
            "finalizer-queue-backlog",
            TriageSeverity::Warning,
            "Finalizer Queue Backlog",
            format!(
                "{} live `java.lang.ref.Finalizer` instances — the finalizer thread is falling behind; objects with `finalize()` (e.g. `Deflater`, JDBC connections) accumulate faster than they are drained. Prefer explicit `close()` over relying on `finalize()`.",
                fmt_count(row.instances),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Metaspace pressure. Reads `overview.classes_loaded`. Fires when the absolute
/// loaded-class count is abnormally high, indicating CGLIB/Byte Buddy/Groovy
/// proxy generation without caching that will exhaust Metaspace.
struct MetaspacePressure;
impl Rule for MetaspacePressure {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let n = r.overview.classes_loaded;
        if n < METASPACE_CLASS_FLOOR {
            return None;
        }
        Some(signal(
            "metaspace-pressure",
            TriageSeverity::Warning,
            "Metaspace Pressure",
            format!(
                "{} classes loaded — far above normal; class metadata is likely exhausting Metaspace. Typical cause: CGLIB/Byte Buddy/Groovy proxy generation without caching. Add `-XX:MaxMetaspaceSize` to cap growth, enable proxy caching, and look for repeated `defineClass` call sites.",
                fmt_count(n),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Cached reflection metadata. Reads `overview.histogram` for
/// `java.lang.reflect.{Method,Field,Constructor}`. Fires when framework
/// reflective caches accumulate unbounded reflection objects.
struct CachedReflectionMetadata;
impl Rule for CachedReflectionMetadata {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        const REFLECT_CLASSES: &[&str] = &[
            "java.lang.reflect.Method",
            "java.lang.reflect.Field",
            "java.lang.reflect.Constructor",
        ];
        let total: u64 = r
            .overview
            .histogram
            .iter()
            .filter(|h| REFLECT_CLASSES.iter().any(|&c| h.pretty_class == c))
            .map(|h| h.instances)
            .sum();
        if total < REFLECT_FLOOR {
            return None;
        }
        Some(signal(
            "cached-reflection-metadata",
            TriageSeverity::Info,
            "Cached Reflection Metadata",
            format!(
                "{} live `java.lang.reflect.{{Method,Field,Constructor}}` objects — framework reflection caches are unbounded (typically Spring/Hibernate accumulating per scanned class). Check for uncapped `ReflectionUtils` caches or scanner loops calling `getDeclaredMethods()` without caching the result.",
                fmt_count(total),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// JNI global-reference leak. Reads `overview.gc_roots_by_type` (count) and
/// `overview.gc_roots_retained_by_type` (retained share). Fires when native
/// code accumulates JNI global references without releasing them.
struct JniGlobalRefLeak;
impl Rule for JniGlobalRefLeak {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let count = r
            .overview
            .gc_roots_by_type
            .iter()
            .find(|row| row.root_type == "JNI Global")
            .map(|row| row.count)
            .unwrap_or(0);
        if count < JNI_GLOBAL_FLOOR {
            return None;
        }
        let total = r.overview.total_shallow;
        let retained = r
            .overview
            .gc_roots_retained_by_type
            .iter()
            .find(|row| row.root_type == "JNI Global")
            .map(|row| row.retained)
            .unwrap_or(0);
        if pct_of(retained, total) < JNI_GLOBAL_RETAINED_PCT {
            return None;
        }
        Some(signal(
            "jni-global-ref-leak",
            TriageSeverity::Warning,
            "JNI Global-Reference Leak",
            format!(
                "{} JNI Global roots retaining {} ({:.1}% of heap) — native code is accumulating global references without releasing them; audit `JNI_DeleteGlobalRef` call sites.",
                fmt_count(count),
                format_bytes(retained),
                pct_of(retained, total),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Heap composition skew. Reads `overview.heap_composition.by_kind`. Fires when
/// a single kind (e.g. primitive arrays) dominates the heap, pointing at
/// bulk-data caches, NIO buffers, or sparse object-array structures.
struct HeapCompositionSkew;
impl Rule for HeapCompositionSkew {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.overview.total_shallow;
        if total == 0 {
            return None;
        }
        let dominant = r
            .overview
            .heap_composition
            .by_kind
            .iter()
            .max_by_key(|k| k.shallow_heap)?;
        let pct = pct_of(dominant.shallow_heap, total);
        if pct < HEAP_SKEW_PCT {
            return None;
        }
        let hint = match dominant.kind.as_str() {
            "Primitive Arrays" => {
                "check for bulk-data buffers (NIO, image, audio) or oversized backing stores"
            }
            "Instances" => "too many small objects — see Object Swarm or Boxed-Primitive Bloat",
            "Object Arrays" => {
                "sparse arrays or container backing stores; check collection fill ratios"
            }
            "Class Objects" => {
                "many dynamically generated classes — see Class-Loader Explosion or Metaspace Pressure"
            }
            _ => "inspect the Class Histogram for the dominant contributors",
        };
        Some(signal(
            "heap-composition-skew",
            TriageSeverity::Info,
            "Heap Composition Skew",
            format!(
                "{} account for {:.1}% of reachable heap — unusually skewed; {}.",
                dominant.kind, pct, hint,
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Static-field anchor. Reads `leaks.suspects`. Fires when the top suspect is
/// anchored by a `Sticky Class` GC root (i.e. a static field) and retains a
/// large heap share — classic "static cache that never evicts".
struct StaticFieldAnchor;
impl Rule for StaticFieldAnchor {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let s = r.leaks.suspects.first()?;
        if s.root_type_label != "Sticky Class" {
            return None;
        }
        let total = r.leaks.total_shallow;
        let pct = pct_of(s.retained, total);
        if pct < STATIC_ANCHOR_PCT {
            return None;
        }
        Some(signal_cls(
            "static-field-anchor",
            TriageSeverity::Warning,
            "Static-Field Anchor",
            format!(
                "`{}` is anchored via a static field (`Sticky Class` root) and retains {} ({:.1}% of heap) — the object lives for the class-loader lifetime; add eviction, null out the field after use, or replace with a `WeakReference` if the data should be reclaimable.",
                s.pretty_class,
                format_bytes(s.retained),
                pct,
            ),
            Some(("leak-suspects", "Leak Suspects")),
            &s.pretty_class,
        ))
    }
}

/// Session / request-scope leak. Reads `overview.histogram`. Fires when a class
/// whose name suggests session or request scope accumulates in very large numbers
/// — sessions that are never invalidated or request contexts that are never freed.
struct SessionScopeLeak;
impl Rule for SessionScopeLeak {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let row = r
            .overview
            .histogram
            .iter()
            .filter(|h| {
                let c = &h.pretty_class;
                (c.contains("Session") || c.contains("session"))
                    && !c.contains("[]")
                    && h.instances >= SESSION_FLOOR
            })
            .max_by_key(|h| h.instances)?;
        Some(signal_cls(
            "session-scope-leak",
            TriageSeverity::Warning,
            "Session-Scope Leak",
            format!(
                "{} live `{}` instances — session objects accumulating without invalidation; check that sessions are expired/invalidated on logout and that an idle-timeout is configured.",
                fmt_count(row.instances),
                row.pretty_class,
            ),
            Some(("system-overview", "System Overview")),
            &row.pretty_class,
        ))
    }
}

/// Connection / socket leak. Reads `overview.histogram`. Fires when a class
/// whose name suggests a connection or socket accumulates beyond a reasonable
/// pool size — connections acquired but never returned or closed.
struct ConnectionLeak;
impl Rule for ConnectionLeak {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        // Include Connection/Socket/Statement/ResultSet; exclude weak-ref wrappers and arrays.
        let row = r
            .overview
            .histogram
            .iter()
            .filter(|h| {
                let c = &h.pretty_class;
                !c.ends_with("[]")
                    && !c.contains("Weak")
                    && !c.contains("Reference")
                    && (c.contains("Connection") || c.contains("Socket"))
                    && h.instances >= CONNECTION_FLOOR
            })
            .max_by_key(|h| h.instances)?;
        Some(signal_cls(
            "connection-leak",
            TriageSeverity::Warning,
            "Connection / Socket Leak",
            format!(
                "{} live `{}` objects — exceeds any reasonable pool or connection limit. Wrap acquisitions in try-with-resources, or enable connection-pool leak detection (e.g. HikariCP `leakDetectionThreshold`, c3p0 `unreturnedConnectionTimeout`).",
                fmt_count(row.instances),
                row.pretty_class,
            ),
            Some(("system-overview", "System Overview")),
            &row.pretty_class,
        ))
    }
}

/// Event-listener accumulation. Reads `overview.histogram`. Fires when a class
/// whose name suggests an event listener or observer accumulates in large numbers
/// — listeners registered to a long-lived publisher but never unregistered.
struct EventListenerAccumulation;
impl Rule for EventListenerAccumulation {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let row = r
            .overview
            .histogram
            .iter()
            .filter(|h| {
                let c = &h.pretty_class;
                !c.ends_with("[]")
                    && (c.contains("Listener")
                        || c.contains("Observer")
                        || c.contains("Subscriber"))
                    && h.instances >= LISTENER_FLOOR
            })
            .max_by_key(|h| h.instances)?;
        Some(signal_cls(
            "event-listener-accumulation",
            TriageSeverity::Warning,
            "Event-Listener Accumulation",
            format!(
                "{} live `{}` instances — listeners accumulating without removal; call `removeListener()` / `unsubscribe()` when the component is disposed, or use weak-reference listener registries.",
                fmt_count(row.instances),
                row.pretty_class,
            ),
            Some(("system-overview", "System Overview")),
            &row.pretty_class,
        ))
    }
}

/// Parser-output accumulation. Reads `overview.histogram`. Fires when classes
/// from XML/JSON parser output packages accumulate in large numbers — parsed
/// documents retained in caches instead of being discarded after processing.
struct ParserOutputAccumulation;
impl Rule for ParserOutputAccumulation {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        const PARSER_PKGS: &[&str] = &[
            "org.w3c.dom.",
            "com.fasterxml.jackson.",
            "com.google.gson.",
            "org.dom4j.",
            "org.jdom.",
            "nu.xom.",
            "javax.xml.",
            "jakarta.xml.",
        ];
        let row = r
            .overview
            .histogram
            .iter()
            .filter(|h| {
                !h.pretty_class.ends_with("[]")
                    && PARSER_PKGS
                        .iter()
                        .any(|pkg| h.pretty_class.starts_with(pkg))
                    && h.instances >= PARSER_FLOOR
            })
            .max_by_key(|h| h.instances)?;
        Some(signal_cls(
            "parser-output-accumulation",
            TriageSeverity::Info,
            "Parser-Output Accumulation",
            format!(
                "{} live `{}` instances — XML/JSON parse results are accumulating; discard documents after processing, or use a streaming parser (SAX/StAX/Jackson streaming) instead of building a full in-memory tree.",
                fmt_count(row.instances),
                row.pretty_class,
            ),
            Some(("system-overview", "System Overview")),
            &row.pretty_class,
        ))
    }
}

/// Interned-string bloat. Reads `overview.histogram` (String count) and
/// `overview.gc_roots_by_type` (JNI Global count). Fires when both are elevated,
/// suggesting `String.intern()` is called at scale on dynamically generated values,
/// causing the intern table to grow without bound.
struct InternedStringBloat;
impl Rule for InternedStringBloat {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let string_count = r
            .overview
            .histogram
            .iter()
            .find(|h| h.pretty_class == "java.lang.String")
            .map(|h| h.instances)
            .unwrap_or(0);
        if string_count < INTERNED_STRING_FLOOR {
            return None;
        }
        let jni_global_count = r
            .overview
            .gc_roots_by_type
            .iter()
            .find(|row| row.root_type == "JNI Global")
            .map(|row| row.count)
            .unwrap_or(0);
        if jni_global_count < INTERNED_JNI_FLOOR {
            return None;
        }
        Some(signal(
            "interned-string-bloat",
            TriageSeverity::Warning,
            "Interned-String Bloat",
            format!(
                "{} live `java.lang.String` instances with {} JNI Global roots — the intern table may be growing without bound from calls to `String.intern()` on dynamic or user-supplied values. Replace with a bounded cache (e.g. Guava `Interner` or `ConcurrentHashMap`) and avoid `intern()` on strings that are not truly constants.",
                fmt_count(string_count),
                fmt_count(jni_global_count),
            ),
            Some(("system-overview", "System Overview")),
        ))
    }
}

/// Sparse object arrays (--collections only). Reads `collections.array_fill_ratio`.
/// Fires when many tracked object arrays are very sparsely populated, wasting
/// memory on null slots — common with multi-dimensional or pre-sized sparse arrays.
struct SparseObjectArrays;
impl Rule for SparseObjectArrays {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let afr = &r.collections.array_fill_ratio;
        if afr.tracked < SPARSE_ARRAY_MIN_TRACKED {
            return None;
        }
        let total_heap = r.leaks.total_shallow;
        // Sum wasted bytes across buckets with fill <= SPARSE_ARRAY_FILL_BP.
        let (sparse_objects, wasted): (u64, u64) = afr
            .buckets
            .iter()
            .filter(|b| b.upper_ratio_bp <= SPARSE_ARRAY_FILL_BP)
            .fold((0, 0), |(obj, w), b| (obj + b.objects, w + b.wasted));
        if sparse_objects < SPARSE_ARRAY_MIN_TRACKED
            || pct_of(wasted, total_heap) < SPARSE_ARRAY_WASTED_PCT
        {
            return None;
        }
        Some(signal(
            "sparse-object-arrays",
            TriageSeverity::Info,
            "Sparse Object Arrays",
            format!(
                "{} object arrays are ≤{}% full ({} wasted on null slots) — sparse or multi-dimensional array structures consuming excess memory. Replace with a `HashMap` / `SparseArray`, a `List` that grows on demand, or a dedicated sparse-matrix library.",
                fmt_count(sparse_objects),
                SPARSE_ARRAY_FILL_BP / 100,
                format_bytes(wasted),
            ),
            Some(("collections", "Collections")),
        ))
    }
}

// ── Batch 4: JXRay-inspired + queued rules ────────────────────────────────────

/// Big-drop concentration. Reads `dominator_analysis.big_drops` and
/// `overview.total_shallow`. Always-on. Fires when the top dominator-tree node
/// drops at least BIG_DROP_PCT of the heap AND at least BIG_DROP_FLOOR bytes —
/// a single object is acting as a giant memory bucket.
struct BigDropConcentration;
impl Rule for BigDropConcentration {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.overview.total_shallow;
        let row = r.dominator_analysis.big_drops.rows.first()?;
        if row.drop_bytes < BIG_DROP_FLOOR {
            return None;
        }
        let pct = pct_of(row.drop_bytes, total);
        if pct < BIG_DROP_PCT {
            return None;
        }
        Some(signal_cls(
            "big-drop-concentration",
            TriageSeverity::Critical,
            "Dominator-Tree Big Drop",
            format!(
                "`{}` is the single largest memory bucket: {:.1}% ({}) of the heap \
                 drops here in the dominator tree — every path from a GC root to those objects \
                 passes through this one node. Follow the retaining chain to find the GC root that keeps it alive.",
                row.display_class,
                pct,
                format_bytes(row.drop_bytes),
            ),
            Some(("dominator-analysis", "Dominator Analysis")),
            &row.display_class,
        ))
    }
}

/// Fixed per-object overhead. Reads `overview.{total_objects, total_shallow,
/// identifier_size_bits, compressed_oops}`. Always-on. Fires when the aggregate
/// 12-or-16-byte object header cost exceeds HEADER_OVERHEAD_PCT of the heap —
/// the signature of a design using millions of tiny wrapper objects.
struct FixedPerObjectOverhead;
impl Rule for FixedPerObjectOverhead {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.overview.total_shallow;
        if total == 0 {
            return None;
        }
        // Header = 12 bytes for compressed-oops or 32-bit JVM, 16 bytes otherwise.
        let header_bytes: u64 = if r.overview.identifier_size_bits == 32
            || r.overview.compressed_oops.unwrap_or(true)
        {
            12
        } else {
            16
        };
        let overhead = r.overview.total_objects.saturating_mul(header_bytes);
        let pct = overhead as f64 / total as f64 * 100.0;
        if pct < HEADER_OVERHEAD_PCT {
            return None;
        }
        Some(signal(
            "fixed-per-object-overhead",
            TriageSeverity::Warning,
            "Fixed per-Object Header Overhead",
            format!(
                "{} ({:.1}% of heap) consumed by JVM object headers alone \
                 ({} objects × {} B each) — consider replacing wrapper objects with \
                 primitive arrays, off-heap buffers, or primitive-specialized collections.",
                format_bytes(overhead),
                pct,
                fmt_count(r.overview.total_objects),
                header_bytes,
            ),
            Some(("object-header-overhead", "Object Header Overhead")),
        ))
    }
}

/// Hash-map collision hotspot. Reads `collections.map_collision_ratio`. Always-on
/// (the collision ratio is computed in the always-on field-decode pass). Fires
/// when a significant fraction of tracked maps are over-full (load > 90%), which
/// causes O(n) key-lookup chains and inflates retained memory.
struct HashCollisionHotspot;
impl Rule for HashCollisionHotspot {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let mcr = &r.collections.map_collision_ratio;
        if mcr.tracked < COLLISION_MIN_TRACKED {
            return None;
        }
        let hot: u64 = mcr
            .buckets
            .iter()
            .filter(|b| b.lower_ratio_bp >= COLLISION_HIGH_BP)
            .map(|b| b.objects)
            .sum();
        if hot == 0 {
            return None;
        }
        let pct = pct_of(hot, mcr.tracked);
        Some(signal(
            "hash-collision-hotspot",
            TriageSeverity::Warning,
            "Hash-Map Collision Hotspot",
            format!(
                "{} of {} tracked maps ({:.1}%) have a load factor > {}% — \
                 over-packed hash tables cause long collision chains and degrade \
                 lookup performance. Increase initial capacity or lower the load factor \
                 (pass `initialCapacity` and `loadFactor` to the constructor, default is 0.75).",
                fmt_count(hot),
                fmt_count(mcr.tracked),
                pct,
                COLLISION_HIGH_BP / 100,
            ),
            Some(("collections", "Collections")),
        ))
    }
}

/// Empty-collection cemetery. Reads `collections.collections_by_size`. Always-on.
/// Fires when most (or very many) tracked collections are empty — allocated but
/// never populated, wasting object-header overhead at scale.
struct EmptyCollectionCemetery;
impl Rule for EmptyCollectionCemetery {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let cbs = &r.collections.collections_by_size;
        if cbs.tracked == 0 {
            return None;
        }
        let share_pct = pct_of(cbs.empty_count, cbs.tracked);
        if share_pct < EMPTY_COLL_SHARE_PCT && cbs.empty_count < EMPTY_COLL_FLOOR {
            return None;
        }
        Some(signal(
            "empty-collection-cemetery",
            TriageSeverity::Info,
            "Empty-Collection Cemetery",
            format!(
                "{} of {} tracked collections ({:.1}%) are empty — \
                 pre-allocated but never populated containers waste object-header \
                 overhead at scale. Use lazy initialization (allocate only when the \
                 first element is added) or return `Collections.emptyList()` / \
                 `List.of()` sentinels for the read-only empty case.",
                fmt_count(cbs.empty_count),
                fmt_count(cbs.tracked),
                share_pct,
            ),
            Some(("collections", "Collections")),
        ))
    }
}

/// Oversized primitive array. Reads `collections.top_prim_arrays.top_individual`
/// and `overview.total_shallow`. Always-on (top_prim_arrays is always computed).
/// Fires when a single primitive array is individually >= OVERSIZED_PRIM_ARRAY_PCT
/// of the heap AND >= OVERSIZED_PRIM_ARRAY_FLOOR bytes.
struct OversizedPrimArray;
impl Rule for OversizedPrimArray {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let total = r.overview.total_shallow;
        let row = r.collections.top_prim_arrays.top_individual.first()?;
        if row.shallow < OVERSIZED_PRIM_ARRAY_FLOOR {
            return None;
        }
        let pct = pct_of(row.shallow, total);
        if pct < OVERSIZED_PRIM_ARRAY_PCT {
            return None;
        }
        let owner_clause = match &row.owner {
            Some(o) => format!(" held by `{o}`"),
            None => String::new(),
        };
        Some(signal_cls(
            "oversized-prim-array",
            TriageSeverity::Warning,
            "Oversized Primitive Array",
            format!(
                "A single `{}` ({} elements, {}){} accounts for {:.1}% of the heap — \
                 consider chunking, memory-mapping, or off-heap storage.",
                row.array_class,
                fmt_count(row.length),
                format_bytes(row.shallow),
                owner_clause,
                pct,
            ),
            Some(("arrays-by-size", "Arrays by Size")),
            &row.array_class,
        ))
    }
}

/// Duplicate primitive arrays. Reads `overview.duplicate_prim_arrays`
/// (populated only when `--find-duplicates` is active). Fires when content-identical
/// prim arrays waste at least DUP_PRIM_ARRAYS_PCT of the heap or DUP_PRIM_ARRAYS_FLOOR
/// bytes — arrays sharing the same payload could be deduplicated or interned.
struct DuplicatePrimArrays;
impl Rule for DuplicatePrimArrays {
    fn eval(&self, r: &Report) -> Option<TriageSignal> {
        let dpa = r.overview.duplicate_prim_arrays.as_ref()?;
        let wasted = dpa.total_wasted_bytes;
        if wasted == 0 {
            return None;
        }
        let total = r.overview.total_shallow;
        if wasted < DUP_PRIM_ARRAYS_FLOOR && pct_of(wasted, total) < DUP_PRIM_ARRAYS_PCT {
            return None;
        }
        Some(signal(
            "dup-prim-arrays",
            TriageSeverity::Warning,
            "Duplicate Primitive Arrays",
            format!(
                "{} ({:.1}% of heap) wasted by content-identical primitive arrays — \
                 multiple copies of the same byte[]/int[]/etc. payload could be \
                 deduplicated or replaced with a shared constant.",
                format_bytes(wasted),
                pct_of(wasted, total),
            ),
            Some(("duplicate-prim-arrays", "Duplicate Primitive Arrays")),
        ))
    }
}

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

    /// Minimal all-zero report the rules can be poked at individually.
    fn base_report() -> Report {
        Report {
            schema_version: SCHEMA_VERSION,
            generated: String::new(),
            truncated_input: false,
            overview: SystemOverview::default(),
            leaks: LeakSuspects::default(),
            top: TopConsumers::default(),
            threads: ThreadOverview::default(),
            top_components: TopComponents::default(),
            alloc_sites: None,
            arrays_by_size: ArraysBySize::default(),
            dominator_analysis: DominatorAnalysis::default(),
            collections: CollectionsAnalysis::default(),
            references: ReferencesAnalysis::default(),
            collection_attribution: None,
            fields_by_size: None,
            biggest_collections: None,
            collection_contents: None,
            leak_indicators: LeakIndicators::default(),
            triage: Vec::new(),
            waste_summary: None,
            top_retainers: Vec::new(),
            queries: Vec::new(),
            analysis_flags: Default::default(),
            obj_graph_flat: None,
            type_ref_graph: vec![],
            thread_local_analysis: Vec::new(),
            framework_analysis: Vec::new(),
            field_stats: None,
        }
    }

    #[test]
    fn off_heap_fires_above_floor_not_below() {
        let mut r = base_report();
        r.leak_indicators.direct_byte_buffer_capacity_sum = 1024;
        assert!(OffHeap.eval(&r).is_none(), "1 KiB must not fire off-heap");

        r.leak_indicators.direct_byte_buffer_capacity_sum = 128 * 1024 * 1024;
        let s = OffHeap.eval(&r).expect("128 MiB must fire off-heap");
        assert_eq!(s.id, "off-heap");
        assert_eq!(s.anchor.as_deref(), Some("off-heap-nio"));
    }

    #[test]
    fn thread_pinning_by_share_and_by_local_count() {
        let mut r = base_report();
        r.leaks.total_shallow = 1000;

        // By retained share (25% >= 20%).
        r.threads.threads = vec![ThreadInfo {
            retained: 250,
            local_root_count: 0,
            name: Some("worker-1".into()),
            ..Default::default()
        }];
        let s = ThreadPinning.eval(&r).expect("25% share must fire");
        assert!(s.detail.contains("worker-1"));

        // Many local roots AND non-trivial share (150 locals, 12% >= 10%).
        r.threads.threads = vec![ThreadInfo {
            retained: 120,
            local_root_count: 150,
            name: Some("pinner".into()),
            ..Default::default()
        }];
        assert!(
            ThreadPinning.eval(&r).is_some(),
            "150 locals at 12% share must fire"
        );

        // Many local roots but trivial share (150 locals, 1% < 10%): the
        // min-share gate keeps normal threads like `main` from firing.
        r.threads.threads = vec![ThreadInfo {
            retained: 10,
            local_root_count: 150,
            name: Some("main".into()),
            ..Default::default()
        }];
        assert!(
            ThreadPinning.eval(&r).is_none(),
            "150 locals at 1% share must not fire"
        );

        // Neither condition met.
        r.threads.threads = vec![ThreadInfo {
            retained: 10,
            local_root_count: 5,
            name: Some("idle".into()),
            ..Default::default()
        }];
        assert!(ThreadPinning.eval(&r).is_none());
    }

    #[test]
    fn gc_waste_names_the_garbage_root_class() {
        let mut r = base_report();
        r.overview.heap_fragmentation_ratio = 0.05;
        assert!(GcWaste.eval(&r).is_none(), "5% must not fire");

        r.overview.heap_fragmentation_ratio = 0.25;
        r.overview.unreachable_shallow = 500;
        r.overview.unreachable_retained = 900;
        r.overview.unreachable_garbage_roots = vec![UnreachableGarbageRoot {
            pretty_class: "com.example.Cache".into(),
            retained: 800,
            objects: 3,
            children: vec![],
        }];
        let s = GcWaste.eval(&r).expect("25% must fire");
        assert!(s.detail.contains("com.example.Cache"));
        assert!(s.detail.contains("25.0%"));
    }

    #[test]
    fn concentration_owner_join_when_single_suspect_matches_biggest() {
        let mut r = base_report();
        r.leaks.total_shallow = 1000;
        r.leaks.suspects = vec![Suspect {
            is_single: true,
            pretty_class: "com.example.Big".into(),
            instance_count: 1,
            retained: 800,
            ..Default::default()
        }];
        r.top.biggest_objects = vec![ObjRow {
            display_class: "com.example.Big".into(),
            retained: 800,
            owner: Some("com.example.Holder#field".into()),
            ..Default::default()
        }];
        let s = Concentration.eval(&r).expect("always fires");
        assert!(s.detail.contains("highly concentrated"));
        assert!(s.detail.contains("held by `com.example.Holder#field`"));
    }

    #[test]
    fn over_capacity_and_constant_arrays_silent_without_collections() {
        // Default CollectionsAnalysis => tracked == 0, empty constant arrays.
        let r = base_report();
        assert!(OverCapacityCollections.eval(&r).is_none());
        assert!(ConstantValueArrays.eval(&r).is_none());
    }

    #[test]
    fn evaluate_triage_preserves_registry_order() {
        // Build a report that fires headline + concentration + gc-waste, and
        // assert they appear in registry order.
        let mut r = base_report();
        r.leaks.total_shallow = 1000;
        r.leaks.suspects = vec![Suspect {
            is_single: true,
            pretty_class: "A".into(),
            instance_count: 1,
            retained: 900,
            ..Default::default()
        }];
        r.overview.heap_fragmentation_ratio = 0.5;
        r.overview.unreachable_shallow = 500;
        let fired = evaluate_triage(&r);
        let ids: Vec<&str> = fired.iter().map(|s| s.id.as_str()).collect();
        let hp = ids.iter().position(|&x| x == "headline-retainer").unwrap();
        let cp = ids.iter().position(|&x| x == "concentration").unwrap();
        let gp = ids.iter().position(|&x| x == "gc-waste").unwrap();
        assert!(hp < cp && cp < gp, "order was {ids:?}");
    }

    #[test]
    fn object_swarm_fires_on_tiny_class_with_huge_count() {
        let mut r = base_report();
        r.overview.total_shallow = 1_000_000;
        r.overview.histogram = vec![HistRow {
            pretty_class: "com.app.Event".into(),
            instances: 15_000_000,
            shallow: 200_000, // avg 13 bytes — well under SWARM_MAX_INSTANCE_BYTES
            retained: 200_000,
            max_instance_shallow: 13,
            incoming_ref_count: 0,
            loader_id: 0,
            loader_label: None,
            root_path: None,
        }];
        let s = ObjectSwarm
            .eval(&r)
            .expect("15M tiny objects at 20% must fire");
        assert!(s.detail.contains("com.app.Event"));

        // Under threshold: only 1M instances.
        r.overview.histogram[0].instances = 1_000_000;
        assert!(ObjectSwarm.eval(&r).is_none());
    }

    #[test]
    fn boxed_primitive_bloat_fires_on_many_long_instances() {
        let mut r = base_report();
        r.overview.total_shallow = 1_000_000;
        r.overview.histogram = vec![HistRow {
            pretty_class: "java.lang.Long".into(),
            instances: 8_000_000,
            shallow: 128_000_000,
            retained: 128_000_000,
            max_instance_shallow: 16,
            incoming_ref_count: 0,
            loader_id: 0,
            loader_label: None,
            root_path: None,
        }];
        let s = BoxedPrimitiveBloat
            .eval(&r)
            .expect("8M Long instances must fire");
        assert!(s.detail.contains("java.lang.Long"));

        // Non-boxed class doesn't trigger.
        r.overview.histogram[0].pretty_class = "com.example.Foo".into();
        assert!(BoxedPrimitiveBloat.eval(&r).is_none());
    }

    #[test]
    fn classloader_explosion_fires_above_threshold() {
        let mut r = base_report();
        r.overview.classloaders_loaded = 2000;
        assert!(ClassloaderExplosion.eval(&r).is_some());
        r.overview.classloaders_loaded = 50;
        assert!(ClassloaderExplosion.eval(&r).is_none());
    }

    #[test]
    fn thread_swarm_fires_on_high_count() {
        let mut r = base_report();
        r.leaks.total_shallow = 1_000_000;
        // By count >= 1000.
        r.threads.threads = (0..1500)
            .map(|i| ThreadInfo {
                retained: 100,
                name: Some(format!("worker-{i}")),
                ..Default::default()
            })
            .collect();
        assert!(ThreadSwarm.eval(&r).is_some(), "1500 threads must fire");

        // Below count floor: silent even with high aggregate share.
        r.threads.threads = r.threads.threads[0..10].to_vec();
        assert!(ThreadSwarm.eval(&r).is_none());
    }

    #[test]
    fn duplicate_strings_fires_and_silent_without_data() {
        let mut r = base_report();
        // No --find-duplicates data: silent.
        assert!(DuplicateStrings.eval(&r).is_none());

        r.overview.duplicate_strings = Some(crate::pass2::DupStrings {
            approx_wasted_bytes: 32 * 1024 * 1024,
            duplicated_values: 50_000,
            total_string_instances: 200_000,
            ..Default::default()
        });
        let s = DuplicateStrings.eval(&r).expect("32 MiB must fire");
        assert_eq!(s.id, "duplicate-strings");

        // Below floor and below pct: silent.
        r.overview
            .duplicate_strings
            .as_mut()
            .unwrap()
            .approx_wasted_bytes = 1024;
        assert!(DuplicateStrings.eval(&r).is_none());
    }

    #[test]
    fn char_array_slack_fires_and_silent_without_data() {
        let mut r = base_report();
        assert!(CharArraySlack.eval(&r).is_none());

        r.overview.duplicate_strings = Some(crate::pass2::DupStrings {
            char_array_waste: Some(crate::pass2::CharArrayWaste {
                arrays_examined: 100_000,
                wasteful_arrays: 50_000,
                total_wasted_bytes: 32 * 1024 * 1024,
                top: Vec::new(),
            }),
            ..Default::default()
        });
        let s = CharArraySlack.eval(&r).expect("32 MiB slack must fire");
        assert_eq!(s.id, "char-array-slack");

        // Too few wasteful arrays: silent.
        r.overview
            .duplicate_strings
            .as_mut()
            .unwrap()
            .char_array_waste
            .as_mut()
            .unwrap()
            .wasteful_arrays = 10;
        assert!(CharArraySlack.eval(&r).is_none());
    }

    #[test]
    fn large_unbounded_collection_fires_on_element_count() {
        let mut r = base_report();
        r.leaks.total_shallow = 10_000_000;
        // No biggest_collections: silent.
        assert!(LargeUnboundedCollection.eval(&r).is_none());

        r.biggest_collections = Some(BiggestCollections {
            combined: vec![BiggestCollectionRow {
                kind: "Map".into(),
                container_class: "java.util.HashMap".into(),
                elements: 2_000_000,
                retained: Some(4_000_000),
                owner: None,
                dominant_value_type: None,
                value_type_breakdown: Vec::new(),
                obj_index_1based: None,
            }],
            by_kind: Vec::new(),
            truncated: false,
        });
        let s = LargeUnboundedCollection
            .eval(&r)
            .expect("2M elements must fire");
        assert!(s.detail.contains("java.util.HashMap"));

        // Below 1M elements and below retained share: silent.
        r.biggest_collections.as_mut().unwrap().combined[0].elements = 100;
        r.biggest_collections.as_mut().unwrap().combined[0].retained = Some(100);
        assert!(LargeUnboundedCollection.eval(&r).is_none());
    }

    // ── Batch-3 tests ────────────────────────────────────────────────────────

    fn hist_row(class: &str, instances: u64, shallow: u64) -> HistRow {
        HistRow {
            pretty_class: class.into(),
            instances,
            shallow,
            retained: shallow,
            max_instance_shallow: shallow.checked_div(instances).unwrap_or(0),
            incoming_ref_count: 0,
            loader_id: 0,
            loader_label: None,
            root_path: None,
        }
    }

    #[test]
    fn finalizer_fires_on_high_count() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row("java.lang.ref.Finalizer", 20_000, 640_000)];
        assert!(FinalizerQueueBacklog.eval(&r).is_some());
        r.overview.histogram[0].instances = 100;
        assert!(FinalizerQueueBacklog.eval(&r).is_none());
        // Not present at all: silent.
        r.overview.histogram = vec![];
        assert!(FinalizerQueueBacklog.eval(&r).is_none());
    }

    #[test]
    fn metaspace_pressure_fires_on_high_class_count() {
        let mut r = base_report();
        r.overview.classes_loaded = 60_000;
        assert!(MetaspacePressure.eval(&r).is_some());
        r.overview.classes_loaded = 5_000;
        assert!(MetaspacePressure.eval(&r).is_none());
    }

    #[test]
    fn cached_reflection_fires_on_method_count() {
        let mut r = base_report();
        r.overview.histogram = vec![
            hist_row("java.lang.reflect.Method", 400_000, 25_600_000),
            hist_row("java.lang.reflect.Field", 200_000, 9_600_000),
        ];
        let s = CachedReflectionMetadata
            .eval(&r)
            .expect("600k reflect objects must fire");
        assert!(s.detail.contains("600,000"));
        r.overview.histogram[0].instances = 100;
        r.overview.histogram[1].instances = 100;
        assert!(CachedReflectionMetadata.eval(&r).is_none());
    }

    #[test]
    fn jni_global_ref_fires_on_count_and_share() {
        let mut r = base_report();
        r.overview.total_shallow = 1_000_000;
        r.overview.gc_roots_by_type = vec![crate::report::model::GcRootTypeRow {
            root_type: "JNI Global".into(),
            count: 8_000,
        }];
        r.overview.gc_roots_retained_by_type = vec![crate::report::model::GcRootRetainedRow {
            root_type: "JNI Global".into(),
            count: 8_000,
            retained: 100_000, // 10%
            top_classes: Vec::new(),
        }];
        assert!(JniGlobalRefLeak.eval(&r).is_some());

        // Count too low.
        r.overview.gc_roots_by_type[0].count = 10;
        assert!(JniGlobalRefLeak.eval(&r).is_none());

        // Count high but share too low.
        r.overview.gc_roots_by_type[0].count = 8_000;
        r.overview.gc_roots_retained_by_type[0].retained = 10; // 0.001%
        assert!(JniGlobalRefLeak.eval(&r).is_none());
    }

    #[test]
    fn heap_composition_skew_fires_on_dominant_kind() {
        let mut r = base_report();
        r.overview.total_shallow = 1_000_000;
        r.overview.heap_composition.by_kind = vec![
            crate::report::model::KindStat {
                kind: "Primitive Arrays".into(),
                objects: 10_000,
                shallow_heap: 750_000,
            },
            crate::report::model::KindStat {
                kind: "Instances".into(),
                objects: 50_000,
                shallow_heap: 250_000,
            },
        ];
        let s = HeapCompositionSkew
            .eval(&r)
            .expect("75% primitive arrays must fire");
        assert!(s.detail.contains("Primitive Arrays"));

        // Not dominant enough.
        r.overview.heap_composition.by_kind[0].shallow_heap = 500_000; // 50%
        assert!(HeapCompositionSkew.eval(&r).is_none());
    }

    #[test]
    fn static_field_anchor_fires_when_sticky_class_dominates() {
        let mut r = base_report();
        r.leaks.total_shallow = 1_000_000;
        r.leaks.suspects = vec![Suspect {
            pretty_class: "com.example.AppConfig".into(),
            is_single: true,
            instance_count: 1,
            retained: 400_000,
            root_type_label: "Sticky Class".into(),
            ..Default::default()
        }];
        let s = StaticFieldAnchor
            .eval(&r)
            .expect("40% sticky class must fire");
        assert!(s.detail.contains("AppConfig"));

        // Different root type: silent.
        r.leaks.suspects[0].root_type_label = "Thread".into();
        assert!(StaticFieldAnchor.eval(&r).is_none());

        // Sticky class but low share.
        r.leaks.suspects[0].root_type_label = "Sticky Class".into();
        r.leaks.suspects[0].retained = 100; // 0.01%
        assert!(StaticFieldAnchor.eval(&r).is_none());
    }

    #[test]
    fn session_scope_leak_fires_on_name_pattern() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row("com.example.UserSession", 200_000, 3_200_000)];
        let s = SessionScopeLeak
            .eval(&r)
            .expect("200k UserSession must fire");
        assert!(s.detail.contains("UserSession"));
        r.overview.histogram[0].instances = 10;
        assert!(SessionScopeLeak.eval(&r).is_none());
    }

    #[test]
    fn connection_leak_fires_on_name_pattern() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row("com.mysql.jdbc.ConnectionImpl", 5_000, 800_000)];
        let s = ConnectionLeak
            .eval(&r)
            .expect("5000 ConnectionImpl must fire");
        assert!(s.detail.contains("ConnectionImpl"));
        r.overview.histogram[0].instances = 5;
        assert!(ConnectionLeak.eval(&r).is_none());
    }

    #[test]
    fn event_listener_fires_on_name_pattern() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row("com.example.MessageListener", 150_000, 2_400_000)];
        assert!(EventListenerAccumulation.eval(&r).is_some());
        r.overview.histogram[0].instances = 1_000;
        assert!(EventListenerAccumulation.eval(&r).is_none());
    }

    #[test]
    fn parser_output_fires_on_package_pattern() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row(
            "com.fasterxml.jackson.databind.node.ObjectNode",
            200_000,
            6_400_000,
        )];
        assert!(ParserOutputAccumulation.eval(&r).is_some());
        r.overview.histogram[0].instances = 10;
        assert!(ParserOutputAccumulation.eval(&r).is_none());
        // Non-parser package: silent.
        r.overview.histogram[0].instances = 500_000;
        r.overview.histogram[0].pretty_class = "com.example.Node".into();
        assert!(ParserOutputAccumulation.eval(&r).is_none());
    }

    #[test]
    fn interned_string_bloat_requires_both_conditions() {
        let mut r = base_report();
        r.overview.histogram = vec![hist_row("java.lang.String", 3_000_000, 96_000_000)];
        r.overview.gc_roots_by_type = vec![crate::report::model::GcRootTypeRow {
            root_type: "JNI Global".into(),
            count: 5_000,
        }];
        assert!(InternedStringBloat.eval(&r).is_some());

        // Too few strings.
        r.overview.histogram[0].instances = 100;
        assert!(InternedStringBloat.eval(&r).is_none());

        // Enough strings but too few JNI globals.
        r.overview.histogram[0].instances = 3_000_000;
        r.overview.gc_roots_by_type[0].count = 5;
        assert!(InternedStringBloat.eval(&r).is_none());
    }

    #[test]
    fn sparse_object_arrays_fires_on_low_fill() {
        let mut r = base_report();
        r.leaks.total_shallow = 1_000_000;
        // No --collections data: silent.
        assert!(SparseObjectArrays.eval(&r).is_none());

        r.collections.array_fill_ratio = crate::report::model::ArrayFillRatio {
            tracked: 50_000,
            buckets: vec![crate::report::model::FillRatioBucket {
                lower_ratio_bp: 0,
                upper_ratio_bp: 2_000, // ≤20%
                objects: 30_000,
                shallow: 600_000,
                wasted: 100_000, // 10% of heap
            }],
        };
        assert!(SparseObjectArrays.eval(&r).is_some());

        // Wasted share too low.
        r.collections.array_fill_ratio.buckets[0].wasted = 10;
        assert!(SparseObjectArrays.eval(&r).is_none());
    }

    #[test]
    fn big_drop_concentration_fires_on_large_drop() {
        let mut r = base_report();
        r.overview.total_shallow = 200 * 1024 * 1024;
        r.dominator_analysis.big_drops.rows = vec![crate::report::model::BigDropRow {
            obj_index_1based: 1,
            display_class: "com.example.Cache".into(),
            retained: 150 * 1024 * 1024,
            child_count: 5,
            largest_child_retained: 10 * 1024 * 1024,
            largest_child_class: "java.util.HashMap".into(),
            drop_bytes: 140 * 1024 * 1024, // 70% — fires
        }];
        let s = BigDropConcentration.eval(&r).expect("large drop must fire");
        assert!(s.detail.contains("Cache"));

        // Drop too small relative to heap.
        r.overview.total_shallow = 10_000 * 1024 * 1024;
        assert!(BigDropConcentration.eval(&r).is_none());
    }

    #[test]
    fn big_drop_concentration_requires_floor() {
        let mut r = base_report();
        r.overview.total_shallow = 200 * 1024 * 1024;
        // Drop is only 40 MiB (below 64 MiB floor) even though share is 20%.
        r.dominator_analysis.big_drops.rows = vec![crate::report::model::BigDropRow {
            obj_index_1based: 1,
            display_class: "com.example.Foo".into(),
            retained: 50 * 1024 * 1024,
            child_count: 1,
            largest_child_retained: 10 * 1024 * 1024,
            largest_child_class: "java.util.ArrayList".into(),
            drop_bytes: 40 * 1024 * 1024,
        }];
        assert!(BigDropConcentration.eval(&r).is_none());
    }

    #[test]
    fn fixed_per_object_overhead_fires_on_many_small_objects() {
        let mut r = base_report();
        // 5M objects × 16 bytes header = 80 MB; total shallow 200 MB → 40%
        r.overview.total_objects = 5_000_000;
        r.overview.total_shallow = 200 * 1024 * 1024;
        r.overview.identifier_size_bits = 64;
        r.overview.compressed_oops = Some(false);
        let s = FixedPerObjectOverhead
            .eval(&r)
            .expect("40% header overhead must fire");
        assert!(s.detail.contains("5,000,000"));

        // Few objects → overhead low.
        r.overview.total_objects = 10;
        assert!(FixedPerObjectOverhead.eval(&r).is_none());
    }

    #[test]
    fn hash_collision_hotspot_fires_on_dense_maps() {
        let mut r = base_report();
        r.collections.map_collision_ratio = crate::report::model::MapCollisionRatio {
            tracked: 500,
            total: 0,
            buckets: vec![crate::report::model::FillRatioBucket {
                lower_ratio_bp: 9_000,
                upper_ratio_bp: 10_000,
                objects: 400,
                shallow: 0,
                wasted: 0,
            }],
        };
        assert!(HashCollisionHotspot.eval(&r).is_some());

        // Too few tracked maps.
        r.collections.map_collision_ratio.tracked = 5;
        assert!(HashCollisionHotspot.eval(&r).is_none());
    }

    #[test]
    fn empty_collection_cemetery_fires_on_high_empty_share() {
        let mut r = base_report();
        r.collections.collections_by_size = crate::report::model::CollectionsBySize {
            tracked: 1_000,
            empty_count: 800, // 80% — fires
            buckets: vec![],
        };
        assert!(EmptyCollectionCemetery.eval(&r).is_some());

        // Below threshold.
        r.collections.collections_by_size.empty_count = 50;
        assert!(EmptyCollectionCemetery.eval(&r).is_none());
    }

    #[test]
    fn empty_collection_cemetery_fires_on_absolute_count() {
        let mut r = base_report();
        r.collections.collections_by_size = crate::report::model::CollectionsBySize {
            tracked: 2_000_000,
            empty_count: 600_000, // only 30% but > 500k floor
            buckets: vec![],
        };
        assert!(EmptyCollectionCemetery.eval(&r).is_some());
    }

    #[test]
    fn oversized_prim_array_fires_on_huge_array() {
        let mut r = base_report();
        r.overview.total_shallow = 200 * 1024 * 1024;
        r.collections.top_prim_arrays.top_individual = vec![crate::report::model::TopArrayRow {
            array_class: "byte[]".into(),
            length: 100_000_000,
            shallow: 100 * 1024 * 1024, // 50% — fires
            obj_index_1based: 1,
            owner: None,
            non_null: None,
        }];
        let s = OversizedPrimArray.eval(&r).expect("huge array must fire");
        assert!(s.detail.contains("byte[]"));

        // Too small.
        r.collections.top_prim_arrays.top_individual[0].shallow = 1024;
        assert!(OversizedPrimArray.eval(&r).is_none());
    }

    #[test]
    fn duplicate_prim_arrays_fires_on_wasted_bytes() {
        let mut r = base_report();
        r.overview.total_shallow = 200 * 1024 * 1024;
        r.overview.duplicate_prim_arrays = Some(crate::pass2::DupPrimArrays {
            total_wasted_bytes: 20 * 1024 * 1024, // 10% — fires
            rows: vec![],
            top_array_holders: vec![],
        });
        let s = DuplicatePrimArrays
            .eval(&r)
            .expect("large dup-prim waste must fire");
        assert!(s.detail.contains("20.0 MB"));

        // Below floor.
        r.overview
            .duplicate_prim_arrays
            .as_mut()
            .unwrap()
            .total_wasted_bytes = 1024;
        assert!(DuplicatePrimArrays.eval(&r).is_none());
    }
}