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
//! Pass-2 data model: graph output struct + inbound-builder state.

#![allow(dead_code)]

use std::{
    cmp::Reverse,
    collections::HashMap,
    io::{self, ErrorKind},
};

use crate::{reader::HprofReader, types::tags, vbyte};

/// Per class-pair edge: top-3 field names (name, occurrence count), sorted desc.
type PairFieldTally = HashMap<(u32, u32), Vec<(String, u32)>>;

use super::Pass2;

/// Inbound CSR block size: one sampled byte-offset per INB_BLOCK nodes.
/// Each node's predecessor slice is count-prefixed so it is self-delimiting;
/// dominator Phase-1 seeks to the block start then scans-skips to node w.
/// Trades ~K/2 extra vbyte skips per lookup for dropping the full per-node
/// offset array (n+1 u32 = ~2GB) down to (n/K) u32.
pub const INB_BLOCK: usize = 16;

// ── Graph output struct ────────────────────────────────────────────────────

/// A resolved thread stack trace, produced at Graph-build time by resolving
/// STACK_TRACE/STACK_FRAME string-ids and class-serials against pass1 tables
/// (which are dropped before the report stage). Small (one per thread), off the
/// per-object RSS budget.
#[derive(Debug, Clone, Default)]
pub struct ThreadStack {
    /// HPROF thread serial from the STACK_TRACE record (0 = none).
    pub thread_serial: u32,
    /// Object index of the owning `java.lang.Thread` (u32::MAX = unresolved).
    pub thread_obj_idx: u32,
    /// Frames top-first, each pre-rendered as `class.method (source:line)`.
    pub frames: Vec<String>,
}

/// Per-thread properties decoded from the `java.lang.Thread` instance blob
/// (name + the always-on overview scalars). Bounded by #threads. The
/// `context_loader_addr` is left as a raw object address here and resolved to a
/// display label at report-build time (where the loader tables live).
#[derive(Debug, Clone, Default)]
pub struct ThreadProps {
    /// Decoded thread name (empty if the name String could not be resolved).
    pub name: String,
    /// `java.lang.Thread.daemon` (defaults false if the field is absent).
    pub is_daemon: bool,
    /// `java.lang.Thread.priority` (defaults 0 if the field is absent).
    pub priority: i32,
    /// `java.lang.Thread.threadStatus` raw JVMTI status bits (0 if absent).
    pub thread_status: i32,
    /// `java.lang.Thread.contextClassLoader` object address (0 = none/absent).
    pub context_loader_addr: u64,
}

/// Raw HPROF record-type census for the dump: top-level record counts plus a
/// per-GC-root-tag breakdown. Additive metadata surfaced in System Overview;
/// not parity-compared. Populated from pass1 counters.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct RecordCensus {
    pub utf8_records: u64,
    pub load_class_records: u64,
    pub unload_class_records: u64,
    pub stack_frame_records: u64,
    pub stack_trace_records: u64,
    pub heap_dump_segments: u64,
    pub instance_dumps: u64,
    pub obj_array_dumps: u64,
    pub prim_array_dumps: u64,
    pub class_dumps: u64,
    /// (root sub-tag byte, count), sorted by count desc then tag asc for stable output.
    pub gc_root_tag_counts: Vec<(u8, u64)>,
}

/// Approximate duplicate-`java.lang.String` analysis. Each String value is
/// decoded, hashed to a 64-bit value, and only the hash + length + occurrence
/// count is retained — the decoded bytes are dropped immediately, so RSS stays
/// bounded regardless of dump size. Hash collisions merge distinct values (an
/// accepted approximation). The unit of dedup is the String INSTANCE: two
/// String instances with the same decoded value count as a duplicate even
/// though they usually hold separate backing arrays. Opt-in via `--find-duplicates`.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct DupStrings {
    /// Distinct decoded String values (by 64-bit hash; collisions merge — accepted approximation).
    pub distinct_values: u64,
    /// Distinct values that occur in more than one String instance.
    pub duplicated_values: u64,
    /// Total java.lang.String instances scanned.
    pub total_string_instances: u64,
    /// Approx bytes wasted by duplication: Σ over duplicated values of (count-1)*first_seen_len.
    pub approx_wasted_bytes: u64,
    /// Top-N most-duplicated String values with exact (truncated) text, sorted by
    /// occurrence count desc then text asc. Only values with count > 1.
    #[serde(default)]
    pub top_duplicated: Vec<DupStringSample>,
    /// Power-of-two histogram of decoded String lengths (bytes), one entry per
    /// distinct value. Sorted by `upper_len` ascending.
    #[serde(default)]
    pub length_histogram: Vec<StrLenBucket>,
    /// Summary stats over distinct-value lengths (bytes).
    #[serde(default)]
    pub length_stats: StrLenStats,
    /// Top-N owning classes by the number of `java.lang.String` instances their
    /// instances reference. Sorted by `string_refs` desc then class name asc.
    #[serde(default)]
    pub top_string_holders: Vec<StringHolder>,
    /// Top-N longest distinct String values by decoded byte length, sorted by
    /// len desc then text asc. Only populated with `--find-duplicates`.
    #[serde(default)]
    pub top_by_length: Vec<DupStringSample>,
    /// Wasted space in char[]/byte[] arrays backing Strings. `None` unless
    /// `--find-duplicates` computed it.
    #[serde(default)]
    pub char_array_waste: Option<CharArrayWaste>,
}

/// One of the most-duplicated String values: its exact text (truncated to
/// `MAX_STR_SAMPLE` bytes), how many String instances share the value, the
/// decoded byte length of the value, and the approximate wasted bytes.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct DupStringSample {
    /// Exact decoded text, truncated to at most `MAX_STR_SAMPLE` bytes on a char boundary.
    pub text: String,
    /// Number of String instances sharing this value.
    pub count: u64,
    /// Decoded byte length of the value (pre-truncation).
    pub len: u32,
    /// Approx wasted bytes for this value: (count - 1) * len.
    pub wasted_bytes: u64,
}

/// One wasteful char[] backing a String (String uses fewer bytes than the
/// array length). Additive.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct CharArrayWasteRow {
    pub array_obj_1based: usize,
    pub length: u64,
    pub used: u64,
    pub wasted_bytes: u64,
}

/// Waste in char[]/byte[] arrays backing Strings. `top` sorted by
/// wasted_bytes desc, capped. Additive.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct CharArrayWaste {
    pub arrays_examined: u64,
    pub wasteful_arrays: u64,
    pub total_wasted_bytes: u64,
    pub top: Vec<CharArrayWasteRow>,
}

/// One power-of-two bucket of the String-length histogram. `upper_len` is the
/// inclusive upper bound (a power of two); a value of length `l` falls in the
/// smallest bucket whose `upper_len >= l`. `count` is the number of distinct
/// String values in this bucket.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct StrLenBucket {
    pub upper_len: u32,
    pub count: u64,
}

/// Summary stats over distinct-value String lengths (bytes). `Default` = zeros.
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct StrLenStats {
    pub min: u32,
    pub max: u32,
    pub median: u32,
    /// Sum of all distinct-value lengths (bytes).
    pub total: u64,
}

/// One owning class and how many `java.lang.String` instances its instances
/// reference (across all object-reference fields).
#[derive(
    Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct StringHolder {
    pub class_name: String,
    pub string_refs: u64,
}

/// The complete reference graph plus all report-facing metadata produced by
/// pass 2. Its large per-object arrays (`shallow`, `class_idx`, the forward CSR)
/// are the dominant RSS consumers, so several are compressed/freed early during
/// `build` — see the field docs. The dominator/retained stages fill `idom`,
/// `retained`, and `has_same_class_ancestor` afterward.
/// One raw container-attribution record produced by field-decode under
/// `--collections`. Carries the DENSE object index (retained size is filled
/// later and looked up in build_model) plus pre-resolved owned name Strings
/// (class_map/strings die right after field-decode). Runtime-only, not serialized.
#[derive(Clone)]
pub struct AttributionRaw {
    pub container_idx: u32,
    pub holder_class: String,
    pub field: String,
    pub container_kind: u8,
    pub container_class: String,
    pub elements: u64,
    /// Backing-array length (slots): `elements` = used, `capacity` = slots.
    /// Real for arrays; equals `elements` for classified collections (see the
    /// field-decode container-insert note).
    pub capacity: u64,
}

/// One raw `Class#field` group produced by field-decode under `--collections`:
/// a holder class + field and the DENSE indices of the distinct objects that
/// field points at. Retained size and the dominant runtime pointee type are
/// computed later in build_model (where `idom`/`retained`/`class_idx` are
/// known). Bounded by caps applied in field-decode. Runtime-only, not serialized.
#[derive(Clone)]
pub struct FieldSizeRaw {
    pub holder_class: String,
    pub field: String,
    /// Distinct pointee dense object indices (deduped, capped).
    pub pointee_indices: Vec<u32>,
}

/// Raw per-collection element/value tally produced by field-decode under
/// `--collections`. Carries the collection instance's DENSE object index, its
/// kind byte and pretty container-class name, plus the DENSE object indices of
/// its non-null element slots (deduped is NOT required — counts matter). Runtime
/// element types are resolved later in build_model from `class_idx`. Bounded by
/// a per-collection slot cap. Runtime-only, not serialized.
#[derive(Clone)]
pub struct CollValuesRaw {
    pub container_idx: u32,
    pub kind: u8,
    pub container_class: String,
    /// Primary incoming `Class#field` referrer, resolved from the holder-edge
    /// map at emit time. `None` when the collection has no attributed owner.
    pub owner: Option<String>,
    /// Dense object indices of non-null element slots (capped per collection).
    pub value_indices: Vec<u32>,
}

pub struct Graph {
    /// Object count = number of live nodes in the graph (indexes 0..n).
    pub n: usize,
    /// Dump format string from the HPROF header (e.g. "JAVA PROFILE 1.0.2").
    pub format: String,
    /// Total size of the dump file in bytes.
    pub file_size: u64,
    /// File basename the dump was opened from (see `file_path` for the full path).
    pub source_name: String,
    /// Full path/name the dump was opened from (Pass1::run's `path`). Distinct
    /// from `source_name`, which is only the file basename.
    pub file_path: String,
    /// HPROF identifier size in bytes (4 or 8), straight from the header.
    pub id_size: u8,
    /// Object-reference size in bytes as detected in pass2. Equals `id_size`
    /// unless compressed OOPs shrink 8-byte ids to 4-byte refs.
    pub ref_size: u8,
    /// Header base timestamp (millis since Unix epoch), 0 if absent/unknown.
    pub header_timestamp_ms: u64,
    /// Object indices that are GC roots, sorted ascending. Includes both real
    /// HPROF roots and synthetic system-class roots (`synthetic_root_count` of
    /// the latter).
    pub gc_root_indices: Vec<u32>,
    /// Per-root HPROF sub-tag, aligned 1:1 with `gc_root_indices` (same order).
    /// A representative type when an index has multiple root records (the
    /// minimum sub-tag, deterministically). `heap::ROOT_SYSTEM_CLASS` (0x00)
    /// marks synthetic system-class roots. Powers `gc_roots_by_type` (B1) and
    /// the default why-alive line, so it is carried unconditionally.
    #[allow(dead_code)]
    pub gc_root_types: Vec<u8>,
    /// Per-object MAT shallow size in bytes, 1:1 with object indices 0..n.
    /// Compressed + emptied early in `build` (its dense ~2GB Vec is restored
    /// from the blob before the retained stage) to keep it off the RSS peak.
    pub shallow: Vec<u32>,
    /// Per-object class-histogram row index, 1:1 with objects. Keyed by
    /// CLASS-OBJECT identity (loader-distinct), so `class_names[class_idx[i]]`
    /// is object i's class name. Also compressed/emptied early like `shallow`.
    pub class_idx: Vec<u32>,
    /// Class-histogram row names, indexed by the values in `class_idx`.
    pub class_names: Vec<String>,
    /// Class-loader object address per histogram row, aligned 1:1 with
    /// `class_names`. 0 = boot/bootstrap loader. Synthetic rows (primitive
    /// arrays, the single java/lang/Class row) are boot-loaded (0). Powers the
    /// class-loader count and per-loader grouping; a per-ROW array (not
    /// per-object) so it costs O(#classes), never O(#objects).
    pub class_loader_id: Vec<u64>,
    /// Class-loader OBJECT address -> class NAME of that loader object, for the
    /// distinct non-boot loaders seen across histogram rows (`class_loader_id`).
    /// Lets the report layer render a human loader label instead of a raw
    /// address. Boot loader (addr 0) is absent here and labeled `<boot>` by the
    /// report layer. Bounded by #distinct loaders, so O(#loaders), not O(#objects).
    pub loader_labels: std::collections::HashMap<u64, String>,
    /// Resolved thread stack traces (one per STACK_TRACE with frames), built
    /// from pass1's STACK_FRAME/STACK_TRACE tables. Small; feeds Thread Overview
    /// and leak-suspect stack context. Empty when the dump carries no traces.
    pub thread_stacks: Vec<ThreadStack>,
    /// Decoded `java.lang.Thread` properties per HPROF thread serial: name plus
    /// the always-on overview scalars (daemon / priority / threadStatus /
    /// contextClassLoader address). Populated by a bounded multi-pass worklist in
    /// `Pass2::build` (thread objects → their name String → the String's
    /// char/byte array → decoded text; scalars read straight from the thread
    /// blob). Bounded by the number of threads (hundreds), so it never touches the
    /// per-object RSS budget. Absent serials render as an unnamed thread.
    pub thread_props: std::collections::HashMap<u32, ThreadProps>,
    /// Per-thread count of GC-thread-local roots that resolved to a live object
    /// (thread_serial -> #resolved locals). Filled from `p1.thread_local_pairs`
    /// during synthetic-edge resolution, using the SAME guard (thread/local both
    /// resolve to indices and are distinct). Bounded by #threads (hundreds), so
    /// it never touches the per-object RSS budget on multi-GB dumps.
    pub thread_local_counts: std::collections::HashMap<u32, u64>,
    /// Bounded per-thread sample of GC-thread-local root object indices
    /// (thread_serial -> Vec of local object indices, capped at
    /// `opts.thread_locals_per_thread`). ONLY populated when the opt-in
    /// `--thread-locals` flag is set; otherwise stays empty (zero memory on the
    /// default path). Bounded by #threads * cap, so off the per-object budget.
    pub thread_local_samples: std::collections::HashMap<u32, Vec<u32>>,
    /// Gated per-thread (frame_number, local object index) pairs used to build
    /// MAT's per-frame significant-locals interleave. `frame_number == u32::MAX`
    /// means the local has no associated stack frame (JNI local / native stack /
    /// thread block). ONLY populated when `--thread-locals` is set; otherwise
    /// empty (zero cost on the default path). Bounded by #threads * cap.
    pub thread_local_frame_samples: std::collections::HashMap<u32, Vec<(u32, u32)>>,
    /// Decoded JVM system properties (java.lang.System static `props`), as
    /// (key, value) pairs sorted by key. Captured by `resolve_system_properties`
    /// via a bounded multi-pass worklist over ONE Properties/Hashtable object.
    /// Capped at 4096 entries. Empty when the props object is absent or its
    /// layout does not match the Hashtable form (graceful fallback — never
    /// garbage). Bounded, so off the per-object RSS budget on multi-GB dumps.
    pub system_properties: Vec<(String, String)>,
    /// Derived JVM version string: prefers the `java.vm.version` property, else
    /// `java.version`, else None. Populated even when the full property table
    /// could not be decoded (both keys are extracted from `system_properties`).
    pub jvm_version: Option<String>,
    /// Object index of a class object -> the histogram row of the class it
    /// represents. Sparse: absent for non-class objects.
    pub class_obj_class_idx: HashMap<u32, u32>, // class-obj index -> class-histogram row (sparse; absent = not a class obj)
    // Forward CSR: node i's out-edges are `fwd_targets[fwd_offsets[i]..fwd_offsets[i+1]]`.
    /// CSR row pointers, len n+1: `fwd_offsets[i]..fwd_offsets[i+1]` slices node
    /// i's out-edge targets in `fwd_targets`. Built via prefix-sum of out-degrees.
    pub fwd_offsets: Vec<u32>,
    /// Flat concatenation of every node's out-edge target indices, sliced by
    /// `fwd_offsets`. Chunked so the transpose can free consumed chunks incrementally,
    /// capping the (fwd_targets + inb_flat) coexistence peak.
    pub fwd_targets: crate::chunkvec::ChunkU32,
    /// Number of GC roots added synthetically (system class roots, etc.)
    /// Reported GC roots = gc_root_indices.len() - synthetic_root_count
    pub synthetic_root_count: usize,
    /// MAT-formula instance shallow size of `java/lang/ClassLoader`, if that
    /// class exists in the dump. MAT materializes a synthetic bootstrap
    /// `<system class loader>` object at address 0x0 (no HPROF record) of this
    /// class; the report layer injects one such object's count + shallow so
    /// `total_objects`/`total_shallow` match MAT bit-exactly. `None` = the
    /// class is absent, inject nothing.
    pub system_classloader_shallow: Option<u32>,
    // Filled by later passes (dominator / retained-size stages).
    /// Immediate-dominator index per object (dominator tree). Empty until the
    /// dominator stage fills it.
    pub idom: Vec<u32>,
    /// Retained size in bytes per object. Empty until the retained-size stage.
    pub retained: Vec<u64>,
    /// Marks objects that have an ancestor of the same class in the dominator
    /// tree (used to suppress double-counting in class-level retained roll-ups).
    pub has_same_class_ancestor: crate::bitset::Bitset,
    /// Per-object HPROF allocation stack-trace serial, 1:1 with objects. Only
    /// populated when `--alloc-sites` is set (moved out of `p1` during build);
    /// empty otherwise. Consumed by the report's alloc-site aggregation and not
    /// needed afterward.
    pub alloc_stack_serial: Vec<u32>,
    /// Distinct non-zero alloc stack-trace serials pre-resolved into their frame
    /// lines, built during `build` while the STACK_FRAME/STACK_TRACE tables are
    /// still alive. `Some` only when `--alloc-sites` is set; `None` otherwise.
    pub alloc_frames_by_serial: Option<std::collections::HashMap<u32, Vec<String>>>,
    /// Raw HPROF record-type census (per-record-type + per-GC-root-tag counts)
    /// carried from pass1's cheap scalar counters. Additive; not parity-compared.
    pub record_census: RecordCensus,
    /// Approximate duplicate-`java.lang.String` analysis. `Some` only when the
    /// opt-in `--find-duplicates` flag is set; `None` otherwise (zero extra work,
    /// zero RSS on the default path). See [`DupStrings`].
    pub dup_strings: Option<DupStrings>,
    /// Approximate duplicate-primitive-array analysis. `Some` only when
    /// `--find-duplicates` was passed; `None` otherwise.
    pub dup_prim_arrays: Option<super::DupPrimArrays>,
    /// Top classes holding the most references to boxed-number objects.
    /// Populated only when `--collections` was passed; empty otherwise.
    pub boxed_number_holders: Vec<crate::report::BoxedNumberHolder>,
    /// Power-of-two array-length histogram (object vs primitive arrays), folded
    /// during pass2 from `p1.elem_count`/`p1.kind` before those arrays are freed.
    /// Always populated; additive, not parity-compared.
    pub arrays_by_size: crate::report::ArraysBySize,
    /// Per-class incoming reference count: `incoming_refs_per_class[ci]` = total
    /// number of inbound edges pointing at instances of class `ci`. Summed from
    /// `in_degree` before the prefix-sum converts it to cursors. ~100 KB; always
    /// populated. Used by `build_system_overview` to fill `HistRow::incoming_ref_count`.
    pub incoming_refs_per_class: Vec<u64>,
    /// Field-decode collection & array analysis. Always populated; additive,
    /// not parity-compared. See [`crate::report::CollectionsAnalysis`].
    pub collections: crate::report::CollectionsAnalysis,
    /// Soft/weak/phantom reference statistics. Always populated; additive, not
    /// parity-compared. See [`crate::report::ReferencesAnalysis`].
    pub references: crate::report::ReferencesAnalysis,
    /// Capped referent object indices per reference kind [soft, weak, phantom],
    /// consumed in `build_model` to compute `only_weakly_retained` via `idom`.
    /// Not serialized (runtime-only helper).
    pub reference_referent_idx: [Vec<u32>; 3],
    /// Count of null referents per reference kind (0=Soft, 1=Weak, 2=Phantom).
    /// Populated at scan time in fielddecode.rs; used by build_references.
    /// Not serialized (runtime-only helper).
    pub reference_null_referent_count: [u64; 3],
    /// Raw container-attribution records from field-decode under `--collections`;
    /// `None` when the flag was off. Consumed in build_model to attach retained
    /// sizes and aggregate. Not serialized.
    pub collection_attribution_raw: Option<Vec<AttributionRaw>>,
    /// True when the holder-edge or container-record cap was hit (attribution
    /// data is a bounded sample). Not serialized.
    pub collection_attribution_truncated: bool,
    /// Raw `Class#field` → pointee-index records from field-decode under
    /// `--collections`; `None` when the flag was off. Consumed in build_model to
    /// sum retained size per field. Not serialized.
    pub fields_by_size_raw: Option<Vec<FieldSizeRaw>>,
    /// Raw per-collection element tallies (dense value indices). `None` when
    /// `--collections` was off. Consumed by build_model, then dropped.
    pub coll_values_raw: Option<Vec<CollValuesRaw>>,
    /// Node/Entry wrapper unwrap map: dense object index of a wrapper (e.g.
    /// `HashMap$Node`) → (key dense idx, value dense idx), where `u32::MAX`
    /// means null or unresolvable. `None` when `--collections` was off.
    /// Consumed by build_model to show real K/V types in Biggest Collections.
    pub node_kv: Option<std::collections::HashMap<u32, (u32, u32)>>,
    /// Per-edge field-name index, parallel to `fwd_targets` (same length).
    /// `fwd_field_name_idx[pos]` is the index into `field_name_pool` for the
    /// field that caused the edge at `fwd_targets[pos]`. 0 means "no name" (class
    /// edges, array element edges, synthetic thread-local edges). Populated only
    /// when `--ref-paths` is set; `None` on the default path (zero RSS).
    pub fwd_field_name_idx: Option<Vec<u16>>,
    /// Deduped field-name strings indexed by `fwd_field_name_idx`.
    /// Pool[0] is always "" (no name). Populated only when `--ref-paths` is set.
    pub field_name_pool: Option<Vec<String>>,
    /// Sum of `capacity` fields across all live `java/nio/DirectByteBuffer`
    /// instances. 0 when no such instances are found or the field cannot be
    /// resolved. Computed unconditionally during the pass2 field-decode scan.
    #[allow(dead_code)]
    pub direct_byte_buffer_capacity_sum: u64,
    /// Count of live `ThreadLocal$ThreadLocalMap$Entry` instances whose weak
    /// `referent` (the ThreadLocal key) is null — the classic thread-local leak
    /// signature (cleared key, value still strongly held). Computed during the
    /// pass2 field-decode scan, where referent nullness is directly observable;
    /// it cannot be recovered from the forward CSR because a null referent is
    /// simply an absent edge, indistinguishable from any other missing target.
    #[allow(dead_code)]
    pub thread_local_null_key_count: u64,
    /// Per-entry records for ThreadLocal$ThreadLocalMap$Entry objects: each
    /// element is `(is_stale, value_dense_idx)` where `is_stale` is true when
    /// the weak referent (the ThreadLocal key) is null, and `value_dense_idx`
    /// is the dense object index of the stored value (u32::MAX when absent/null).
    /// Captured at scan time (before id_map is consumed). Bounded by TL_ENTRY_CAP.
    /// Used by `build_threadlocal_analysis` in the report layer.
    pub tl_entry_records: Vec<(bool, u32)>,
    /// Retained sizes within the unreachable forest, computed by the
    /// `unreachable_retained` stage in `main.rs` while the forward CSR is still
    /// alive. `None` until that stage runs (or when there are no unreachable
    /// objects). Consumed by `build_system_overview`; a bounded per-class
    /// aggregate, so it carries no per-object RSS into the report phase.
    pub unreachable_retained: Option<crate::unreachable_retained::UnreachableRetained>,
    /// Bounded outbound-edge snapshot for object-graph click-through.
    /// Captured before `fwd_offsets`/`fwd_targets` are consumed during inbound
    /// CSR construction. `None` until `capture_obj_graph_edges` is called.
    pub obj_graph_edges: Option<ObjGraphCapture>,
    /// Class-pair edge-count map built by `capture_type_ref_graph` before the
    /// fwd-CSR is consumed. `(src_class_idx, dst_class_idx) → edge_count`.
    /// Carried on Graph so `build_type_ref_graph` can consume it without
    /// iterating the per-object capture (which is now sparse / bounded).
    pub type_ref_pairs: Option<HashMap<(u32, u32), u64>>,
    /// Top field names per class-pair edge, parallel to `type_ref_pairs`.
    /// `(src_ci, dst_ci) → [(field_name, count)]` sorted by count desc (up to 3).
    /// Optional: only populated when `fwd_field_name_idx` is present.
    pub type_ref_pair_fields: Option<PairFieldTally>,
    /// Per-class ordered reference-field names, indexed by class histogram row index.
    /// `class_ref_field_names[ci][k]` = name of the k-th reference field of class ci.
    /// Empty when `opts.field_stats` is false.
    pub class_ref_field_names: Vec<Vec<String>>,
}

// ── Object-graph click-through capture ──────────────────────────────────────

/// Sparse per-object edge snapshot used by `build_obj_graph_flat` to populate
/// the interactive click-through view.
///
/// Only edges for captured nodes (those with shallow ≥ capture_threshold) are
/// stored.  A `HashMap<u32, Box<[...]>>` is used instead of a full-universe CSR
/// because captured nodes are a small fraction of the total: the n+1 CSR offset
/// arrays cost 2 × 2 GB on the 34 GB dump for ~514 M objects, while a sparse map
/// for the top-200 K nodes by shallow costs ~a few MB of index overhead.
///
/// `build_type_ref_graph` no longer reads this structure; it uses the inline scan
/// `capture_type_ref_graph` instead, which aggregates class-pair counts directly
/// from the live fwd-CSR without storing per-object edges.
pub struct ObjGraphCapture {
    /// Total universe size (used for `captured.get()` bounds check).
    pub n: usize,
    /// Outbound edges for captured nodes only.
    pub edges: std::collections::HashMap<u32, Box<[(u32, u16)]>>,
    /// Inbound edges for captured nodes only.
    pub inbound: std::collections::HashMap<u32, Box<[(u32, u16)]>>,
    /// Nodes whose inbound edge list was cut at edge_cap (1 bit per object).
    pub inbound_truncated: crate::bitset::Bitset,
    /// Deduped field-name strings; index 0 is always "" (unnamed).
    pub field_name_pool: Vec<String>,
    /// Dense indices that were captured as sources (1 bit per object).
    pub captured: crate::bitset::Bitset,
}

impl ObjGraphCapture {
    pub fn empty() -> Self {
        Self {
            n: 0,
            edges: std::collections::HashMap::new(),
            inbound: std::collections::HashMap::new(),
            inbound_truncated: Default::default(),
            field_name_pool: vec![String::new()],
            captured: Default::default(),
        }
    }

    /// Outbound edge slice for object `i`.
    #[inline]
    pub fn edges_of(&self, i: usize) -> &[(u32, u16)] {
        self.edges
            .get(&(i as u32))
            .map(|b| b.as_ref())
            .unwrap_or(&[])
    }

    /// Inbound edge slice for object `i`.
    #[inline]
    pub fn inbound_of(&self, i: usize) -> &[(u32, u16)] {
        self.inbound
            .get(&(i as u32))
            .map(|b| b.as_ref())
            .unwrap_or(&[])
    }
}

fn name_idx_for(
    fwd_names: Option<&Vec<u16>>,
    name_pool: Option<&Vec<String>>,
    pos: usize,
    name_map: &mut std::collections::HashMap<String, u16>,
    field_name_pool: &mut Vec<String>,
) -> u16 {
    match (fwd_names, name_pool) {
        (Some(idx_vec), Some(pool)) => {
            let ni = idx_vec[pos] as usize;
            let name: &str = if ni < pool.len() { &pool[ni] } else { "" };
            if name.is_empty() {
                0u16
            } else {
                let next = name_map.len() as u16;
                let idx = *name_map.entry(name.to_owned()).or_insert(next);
                if idx as usize >= field_name_pool.len() {
                    field_name_pool.push(name.to_owned());
                }
                idx
            }
        }
        _ => 0u16,
    }
}

/// Build the type-level reference graph by aggregating class-pair edge counts
/// directly from the live fwd-CSR. Called before the fwd-CSR is consumed by
/// inbound construction. Returns `(src_ci, dst_ci) → (edge_count, retained_weight)`
/// where retained_weight uses the source object's retained size divided by its
/// out-degree. `g.retained` is not available yet (computed after dominators), so
/// `retained_weight` is 0 here; callers that have `g.retained` should call the
/// full version in `build.rs` instead. This version stores only class-pair totals,
/// avoiding the 20+ GB per-object edge arrays.
///
/// Also returns a per-pair field-name tally (top-3 field names by occurrence)
/// when `fwd_field_name_idx` is present.
pub fn capture_type_ref_graph(g: &Graph) -> (HashMap<(u32, u32), u64>, PairFieldTally) {
    let n = if g.shallow.is_empty() {
        g.n
    } else {
        g.shallow.len()
    };
    if n == 0 || g.fwd_offsets.is_empty() || g.class_idx.is_empty() {
        return (HashMap::new(), HashMap::new());
    }
    let has_names = g.fwd_field_name_idx.is_some() && g.field_name_pool.is_some();
    let mut pair_map: HashMap<(u32, u32), u64> = HashMap::new();
    // Per-pair field-name tally: (src_ci, dst_ci) → HashMap<name_idx, count>
    let mut field_tally: HashMap<(u32, u32), HashMap<u16, u32>> = HashMap::new();

    for src_idx in 0..n {
        let start = g.fwd_offsets[src_idx] as usize;
        let end = g.fwd_offsets[src_idx + 1] as usize;
        if start == end {
            continue;
        }
        if src_idx >= g.class_idx.len() {
            continue;
        }
        let src_ci = g.class_idx[src_idx];
        for pos in start..end {
            let dst_idx = g.fwd_targets.get(pos) as usize;
            if dst_idx >= g.class_idx.len() {
                continue;
            }
            let dst_ci = g.class_idx[dst_idx];
            *pair_map.entry((src_ci, dst_ci)).or_insert(0) += 1;
            if has_names {
                if let Some(name_idx) = g
                    .fwd_field_name_idx
                    .as_ref()
                    .and_then(|v| v.get(pos))
                    .copied()
                {
                    if name_idx != 0 {
                        *field_tally
                            .entry((src_ci, dst_ci))
                            .or_default()
                            .entry(name_idx)
                            .or_insert(0) += 1;
                    }
                }
            }
        }
    }

    // Convert field tally to sorted top-3 names
    let name_pool = g.field_name_pool.as_deref().unwrap_or(&[]);
    let pair_fields: std::collections::HashMap<(u32, u32), Vec<(String, u32)>> = field_tally
        .into_iter()
        .map(|(key, counts)| {
            let mut sorted: Vec<(String, u32)> = counts
                .into_iter()
                .filter_map(|(idx, cnt)| {
                    let name = name_pool.get(idx as usize)?;
                    if name.is_empty() {
                        return None;
                    }
                    Some((name.clone(), cnt))
                })
                .collect();
            sorted.sort_unstable_by_key(|a: &(String, u32)| Reverse(a.1));
            sorted.truncate(3);
            (key, sorted)
        })
        .filter(|(_, v)| !v.is_empty())
        .collect();

    (pair_map, pair_fields)
}

/// Sparse per-object edge snapshot for the click-through view.
///
/// Captures edges only for the top-`top_n` objects by shallow heap size
/// (the `build_obj_graph_flat` consumer only needs edges for significant
/// nodes that it BFS-expands from the dominator tree). Using a sparse
/// `HashMap<u32, Box<[...]>>` avoids the 2 × (n+1) × 4B = ~4 GB CSR offset
/// arrays that the old full-universe CSR required on the 34 GB dump.
///
/// Must be called while `g.fwd_offsets` and `g.fwd_targets` are still alive.
pub fn capture_obj_graph_edges(g: &Graph, top_n: usize, edge_cap: usize) -> ObjGraphCapture {
    let n = if g.shallow.is_empty() {
        g.n
    } else {
        g.shallow.len()
    };
    if n == 0 || g.fwd_offsets.is_empty() {
        return ObjGraphCapture::empty();
    }

    let mut cap = ObjGraphCapture::empty();
    cap.n = n;
    cap.captured = crate::bitset::Bitset::with_len(n);
    cap.inbound_truncated = crate::bitset::Bitset::with_len(n);

    let mut name_map: std::collections::HashMap<String, u16> = std::collections::HashMap::new();
    name_map.insert(String::new(), 0u16);

    let fwd_names = g.fwd_field_name_idx.as_ref();
    let name_pool = g.field_name_pool.as_ref();

    // Select captured source set: top-top_n by shallow size.
    // We can't know retained size yet (dominators not computed), so shallow is
    // the best available proxy. Objects with high retained but tiny shallow
    // get edges_unknown = true in the UI; this is acceptable because the
    // tradeoff vs. the previous 24 GB full-universe capture is stark.
    //
    // To avoid sorting all n elements (would require 2 GB Vec<u32> on the 34 GB
    // dump), we use a threshold approach:
    // 1. Sample shallow values to estimate the top-top_n threshold.
    // 2. Collect all objects with shallow >= threshold (may overshoot slightly).
    let captured_nodes: Vec<u32> = if top_n >= n {
        // Capture all — avoid materializing a Vec by using 0..n directly below.
        Vec::new()
    } else {
        // Step 1: find threshold via partial sort of a sample.
        let sample_step = (n / top_n.min(n)).max(1);
        let mut sample: Vec<u32> = g.shallow.iter().step_by(sample_step).copied().collect();
        // Sort descending, pick the top_n-th value as the threshold.
        sample.sort_unstable_by(|a, b| b.cmp(a));
        let threshold = sample
            .get(top_n.min(sample.len()).saturating_sub(1))
            .copied()
            .unwrap_or(0);
        drop(sample);
        // Step 2: collect objects above threshold (may include more than top_n).
        let mut nodes: Vec<u32> = g
            .shallow
            .iter()
            .enumerate()
            .filter_map(|(i, &s)| if s >= threshold { Some(i as u32) } else { None })
            .collect();
        // If we overshot, sort and truncate.
        if nodes.len() > top_n {
            nodes.sort_unstable_by(|&a, &b| g.shallow[b as usize].cmp(&g.shallow[a as usize]));
            nodes.truncate(top_n);
        }
        nodes
    };
    let all_captured = top_n >= n;

    // Mark captured bitset.
    if all_captured {
        for i in 0..n {
            cap.captured.set(i);
        }
    } else {
        for &s in &captured_nodes {
            cap.captured.set(s as usize);
        }
    }

    // ── Outbound edges (sparse) ───────────────────────────────────────────────
    {
        let iter: Box<dyn Iterator<Item = u32>> = if all_captured {
            Box::new(0u32..n as u32)
        } else {
            Box::new(captured_nodes.iter().copied())
        };
        for src in iter {
            let s = src as usize;
            let fwd_start = g.fwd_offsets[s] as usize;
            let fwd_end = g.fwd_offsets[s + 1] as usize;
            let take = (fwd_end - fwd_start).min(edge_cap);
            if take == 0 {
                continue;
            }
            let mut edges: Vec<(u32, u16)> = Vec::with_capacity(take);
            for pos in fwd_start..fwd_start + take {
                let dst = g.fwd_targets.get(pos);
                let name_idx = name_idx_for(
                    fwd_names,
                    name_pool,
                    pos,
                    &mut name_map,
                    &mut cap.field_name_pool,
                );
                edges.push((dst, name_idx));
            }
            cap.edges.insert(src, edges.into_boxed_slice());
        }
    }
    drop(captured_nodes);
    crate::trace::probe("capture_obj_graph: after outbound sparse built");

    // ── Inbound edges (sparse) ────────────────────────────────────────────────
    // For each captured dst, count how many inbound edges arrive, then fill.
    // We use a HashMap<u32, Vec<(u32,u16)>> accumulator to avoid large offset arrays.
    let mut inbound_acc: std::collections::HashMap<u32, Vec<(u32, u16)>> =
        std::collections::HashMap::new();
    for src in 0..n as u32 {
        let start = g.fwd_offsets[src as usize] as usize;
        let end = g.fwd_offsets[src as usize + 1] as usize;
        for pos in start..end {
            let dst = g.fwd_targets.get(pos) as usize;
            if !cap.captured.get(dst) {
                continue;
            }
            let bucket = inbound_acc.entry(dst as u32).or_default();
            if bucket.len() < edge_cap {
                let name_idx = name_idx_for(
                    fwd_names,
                    name_pool,
                    pos,
                    &mut name_map,
                    &mut cap.field_name_pool,
                );
                bucket.push((src, name_idx));
            } else {
                cap.inbound_truncated.set(dst);
            }
        }
    }
    for (dst, vec) in inbound_acc {
        cap.inbound.insert(dst, vec.into_boxed_slice());
    }
    crate::trace::probe("capture_obj_graph: after inbound sparse built");

    cap
}

/// Deferred inbound-CSR construction. Built by `Pass2::build` with everything
/// needed to run the inbound scan + delta-encode later (after rpo frees its
/// arrays), keeping the ~5.5GB inbound CSR off the rpo-phase RSS peak.
#[allow(dead_code)]
pub struct InboundBuilder {
    pub(crate) source: crate::source::HprofSource,
    pub(crate) id_size: u8,
    pub(crate) n: usize,
    /// Live id_map as constructed by `build`; taken by `compress_id_map`.
    pub(crate) id_map: Option<crate::id_map::IdMap>,
    /// Compressed id_map (blob, element_count); set by `compress_id_map`.
    pub(crate) id_map_c: Option<(Vec<u8>, usize)>,
    pub(crate) id_map_codec: crate::cvec::Codec,
    pub(crate) class_addr_to_hist: HashMap<u64, u32>,
    pub(crate) field_plans_dense: Vec<super::FieldPlan>,
    /// Prefix-summed inbound start cursors (in_degree after prefix-sum), len n.
    pub(crate) in_cursors: Vec<u32>,
    pub(crate) total_inb: u64,
    /// Synthetic thread->local edges (src,dst), already deduped.
    pub(crate) synthetic_edges: Vec<(u32, u32)>,
}

/// Captured from `InboundBuilder` before it is consumed by `build_mat_scan`,
/// so that a post-inbound HPROF rescan can rebuild the forward-edge CSR without
/// keeping `fwd_targets` alive across the inbound peak window.
pub struct MatOutboundRescanCtx {
    pub source: crate::source::HprofSource,
    pub id_size: u8,
    /// Compressed id_map blob + element count + codec.
    pub id_map_c: Option<(Vec<u8>, usize)>,
    pub id_map_codec: crate::cvec::Codec,
    pub class_addr_to_hist: HashMap<u64, u32>,
    pub field_plans_dense: Vec<super::FieldPlan>,
}

impl InboundBuilder {
    /// Extract the data needed for a later outbound-only HPROF rescan.
    /// Must be called after `compress_id_map`. id_map_c blob is cloned
    /// (~0.5 GB for large dumps). class_addr_to_hist and field_plans_dense are
    /// cloned (cheap: ~1 MB total). The builder retains full copies of all data.
    pub fn take_for_outbound_rescan(&mut self) -> MatOutboundRescanCtx {
        MatOutboundRescanCtx {
            source: self.source.clone(),
            id_size: self.id_size,
            id_map_c: self.id_map_c.clone(),
            id_map_codec: self.id_map_codec,
            class_addr_to_hist: self.class_addr_to_hist.clone(),
            field_plans_dense: self.field_plans_dense.clone(),
        }
    }

    /// Compress the live id_map into a blob and free the dense Vec, so the
    /// ~4.1GB addr array is off the rpo-phase RSS peak. No-op for Codec::None.
    pub fn compress_id_map(&mut self, codec: crate::cvec::Codec) -> io::Result<()> {
        self.id_map_codec = codec;
        if codec == crate::cvec::Codec::None {
            return Ok(());
        }
        if let Some(m) = self.id_map.take() {
            let (blob, len) = m.compress(codec)?;
            self.id_map_c = Some((blob, len));
        }
        Ok(())
    }

    /// Build the inbound CSR by transposing the already-computed forward CSR,
    /// avoiding a third full-file scan. Requires the forward CSR
    /// (fwd_offsets/fwd_targets) and dfn (pre-order) to still be alive.
    /// id_map, class_addrs, and field_plans stored in self are no longer needed
    /// and are freed before the Phase-4 encode.
    ///
    /// Memory peak: fwd_offsets + fwd_targets + inb_flat + in_cursors + dfn.
    /// On a 34 GB dump this is ~17 GB, well within the thinkstation's budget
    /// but higher than the old deferred-scan path (~9 GB). The trade-off is
    /// eliminating the ~234 s fourth full-file scan entirely.
    pub fn build_from_fwd(
        self,
        fwd_offsets: Vec<u32>,
        mut fwd_targets: crate::chunkvec::ChunkU32,
        dfn: &[u32],
    ) -> io::Result<(Vec<u64>, Vec<u8>)> {
        let InboundBuilder {
            n,
            in_cursors,
            total_inb,
            synthetic_edges: _,
            // The rest are only needed by the file-scan path; drop them early to
            // free the id_map (~4 GB) before the inb_flat alloc.
            id_map,
            id_map_c,
            class_addr_to_hist,
            field_plans_dense,
            ..
        } = self;
        crate::trace::probe("inbound fwd-transpose: after struct destructure (before any drop)");

        drop(id_map);
        crate::trace::probe("inbound fwd-transpose: after drop(id_map)");
        if let Some((blob, _)) = id_map_c {
            crate::trace::drop_vec(blob);
        }
        crate::trace::probe("inbound fwd-transpose: after drop(id_map_c blob)");
        drop(class_addr_to_hist);
        drop(field_plans_dense);
        crate::trace::probe(
            "inbound fwd-transpose: after drop(class_addr_to_hist+field_plans_dense)",
        );
        // Return freed heap pages to OS before the large inb_flat alloc, so
        // RSS reflects actual live data rather than glibc's dirty brk heap.
        crate::trace::trim();
        crate::trace::probe("inbound fwd-transpose: after trim (before inb_flat alloc)");

        let mut inb_flat = crate::chunkvec::ChunkU32::zeroed(total_inb as usize);
        if crate::trace::enabled() {
            eprintln!(
                "[trace-rss] inbound (fwd-transpose): total_inb={} edges, inb_flat={} MB",
                total_inb,
                (total_inb as usize * 4) / (1024 * 1024)
            );
        }
        crate::trace::probe("inbound fwd-transpose: after inb_flat alloc");

        let mut in_cursors = in_cursors;

        // Transpose the forward CSR: for each src and each of its fwd targets
        // dst, write src into inb_flat at in_cursors[dst] and advance the cursor.
        // `in_cursors[i]` starts as the cumulative prefix-sum START for node i
        // and advances to the END as edges are written.
        // fwd_targets chunks are freed as the read pointer advances past each
        // 256 MB boundary — capping (fwd_targets + inb_flat) coexistence peak.
        let n_nodes = fwd_offsets.len().saturating_sub(1);
        let mut buf: Vec<u32> = Vec::with_capacity(4096);
        let mut next_fwd_free: usize = 1 << 26; // first chunk boundary = 64 M u32 = 256 MB
        // MADV_FREE hint on consumed fwd_offsets pages as src advances.
        // fwd_offsets[0..src] is dead after processing src; the hint tells the
        // kernel it can reclaim those pages under pressure. MADV_FREE (not
        // MADV_DONTNEED) is used because DONTNEED zero-fills on next access and
        // corrupts glibc's free-list metadata on subsequent drops of this Vec.
        #[cfg(target_os = "linux")]
        let fwd_off_ptr = fwd_offsets.as_ptr();
        #[cfg(target_os = "linux")]
        let mut next_off_free: usize = 1 << 10; // first page boundary = 1024 u32 = 4 KB
        for src in 0..n_nodes {
            let lo = fwd_offsets[src] as usize;
            let hi = fwd_offsets[src + 1] as usize;
            if lo == hi {
                continue; // no out-edges — skip copy_range + buf iteration
            }
            // Free fully-consumed fwd_targets chunks as the lo pointer advances.
            if lo >= next_fwd_free {
                fwd_targets.free_below(lo);
                next_fwd_free = ((lo >> 26) + 1) << 26; // next chunk boundary
            }
            // MADV_FREE hint on consumed fwd_offsets pages.
            #[cfg(target_os = "linux")]
            if src >= next_off_free {
                let pages_end = src & !(1024 - 1); // align down to 4KB page
                let len = pages_end * std::mem::size_of::<u32>();
                if len > 0 {
                    unsafe {
                        libc::madvise(
                            fwd_off_ptr as *mut libc::c_void,
                            len,
                            8, /* MADV_FREE */
                        );
                    }
                }
                next_off_free = pages_end + 1024; // advance by one page
            }
            // Use range_slice for zero-copy access when the range fits in one
            // chunk; fall back to copy_range for cross-chunk adjacency lists.
            let targets: &[u32] = if let Some(sl) = fwd_targets.range_slice(lo, hi) {
                sl
            } else {
                fwd_targets.copy_range(lo, hi, &mut buf);
                &buf
            };
            for &dst in targets {
                let dst = dst as usize;
                inb_flat.set(in_cursors[dst] as usize, src as u32);
                in_cursors[dst] += 1;
            }
        }
        // fwd_offsets and fwd_targets are no longer needed; free them before
        // Phase 4 allocates inb_data to reduce the coexistence peak.
        crate::trace::drop_vec(fwd_offsets);
        drop(fwd_targets);
        crate::trace::trim();
        crate::trace::probe("inbound fwd-transpose: after transpose loop");

        // Synthetic edges are already included in fwd_targets (they were
        // appended before the B3 restore in pass2b), so we must NOT add them
        // again here — doing so would double-count them and overflow in_cursors.

        crate::trace::probe("inbound: before Phase-4 (after fwd-transpose)");
        Self::encode_phase4(n, total_inb, in_cursors, inb_flat, dfn)
    }

    /// Run the inbound scan + Phase-4 encode. Returns (inb_offsets, inb_data).
    #[cfg(test)]
    pub fn build(self, dfn: &[u32]) -> io::Result<(Vec<u64>, Vec<u8>)> {
        let InboundBuilder {
            source,
            id_size,
            n,
            id_map,
            id_map_c,
            id_map_codec,
            class_addr_to_hist,
            field_plans_dense,
            mut in_cursors,
            total_inb,
            synthetic_edges,
            ..
        } = self;

        // Reconstruct the id_map: either it was left live (Codec::None) or it
        // was compressed by `compress_id_map` and must be decompressed here.
        // This decompress spike lands at inbound-start, after rpo freed its
        // dfn/vertex arrays, so it stays below the rpo peak.
        let id_map = match id_map {
            Some(m) => m,
            None => {
                let (blob, len) = id_map_c.expect("id_map neither live nor compressed");
                crate::id_map::IdMap::from_compressed(&blob, len, id_map_codec)?
            }
        };

        // -- Alloc flat inbound array (deferred until after rpo freed its arrays) --
        // Chunked backing store so Phase-4 can free consumed chunks incrementally,
        // avoiding the inb_flat+inb_data coexistence that was the global RSS peak.
        let mut inb_flat = crate::chunkvec::ChunkU32::zeroed(total_inb as usize);
        if crate::trace::enabled() {
            eprintln!(
                "[trace-rss] inbound 2b: total_inb={} edges, inb_flat={} MB",
                total_inb,
                (total_inb as usize * 4) / (1024 * 1024)
            );
        }
        crate::trace::probe("inbound 2b: after inb_flat alloc");

        // -- Sub-pass 2b scan: fill INBOUND edges only --
        {
            let mut r = source.open()?;
            let mut scratch: Vec<u8> = Vec::with_capacity(4096);
            let mut fwd_t_stub: crate::chunkvec::ChunkU32 = crate::chunkvec::ChunkU32::zeroed(0);
            let mut fwd_offsets_stub: Vec<u32> = Vec::new();
            loop {
                let tag = match r.u1() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                };
                let _ts = match r.u4() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                };
                let length = match r.u4() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                } as u64;
                match tag {
                    tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                        Pass2::fill_heap_2b(
                            &mut r,
                            id_size,
                            length,
                            &id_map,
                            &class_addr_to_hist,
                            &field_plans_dense,
                            &[], // named plans not needed for inbound pass
                            false,
                            true,
                            &mut fwd_t_stub,
                            &mut fwd_offsets_stub,
                            &mut None, // no field name index for inbound pass
                            &mut Vec::new(),
                            &mut std::collections::HashMap::new(),
                            &mut inb_flat,
                            &mut in_cursors,
                            &mut scratch,
                        )?;
                    }
                    tags::HEAP_DUMP_END => break,
                    _ => match r.skip(length) {
                        Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                        other => other?,
                    },
                }
            }
        }

        // id_map / class_addr_to_hist / field_plans_dense are consumed only by the 2b scan
        // above. Free them now (id_map alone is ~4.1 GB at 514M objects) before
        // the Phase-4 encode allocates inb_data, trimming the global RSS peak.
        drop(id_map);
        drop(class_addr_to_hist);
        drop(field_plans_dense);

        // Synthetic thread->local INBOUND edges.
        for &(src, dst) in &synthetic_edges {
            inb_flat.set(in_cursors[dst as usize] as usize, src);
            in_cursors[dst as usize] += 1;
        }

        crate::trace::probe("inbound: before Phase-4 (after 2b scan + drops)");
        Self::encode_phase4(n, total_inb, in_cursors, inb_flat, dfn)
    }

    /// Phase 4: translate node indices to pre-order numbers via `dfn`, sort,
    /// dedup, and delta-encode into the blocked inbound CSR. Shared by both
    /// the file-scan path (`build`) and the fwd-transpose path (`build_from_fwd`).
    fn encode_phase4(
        n: usize,
        total_inb: u64,
        in_cursors: Vec<u32>,
        mut inb_flat: crate::chunkvec::ChunkU32,
        dfn: &[u32],
    ) -> io::Result<(Vec<u64>, Vec<u8>)> {
        #[allow(clippy::redundant_locals)]
        let in_cursors = in_cursors;
        // -- Phase 4: Build inbound CSR (blocked offsets + count-prefixed data) --
        // inb_block_off[b] = byte offset where node (b*INB_BLOCK)'s slice begins.
        // Each node's slice = vbyte(count) then `count` vbyte pre-order deltas.
        let mut inb_block_off: Vec<u64> = Vec::with_capacity(n / INB_BLOCK + 2);
        let mut inb_data: Vec<u8> = Vec::new();
        // Pre-allocate inb_data to 2.0 bytes/edge. Measured on the 34 GB dump:
        // final len=2134 MB at 1653 M edges = 1.29 B/edge, so 2.0× gives safe
        // headroom with no realloc, saving ~800 MB vs the old 2.5× reserve.
        // Cap at 6 GB so we don't over-commit on unusually dense small dumps.
        // On 32-bit targets (wasm32) usize::MAX is the upper bound instead.
        #[cfg(target_pointer_width = "64")]
        let six_gb: usize = 6 * 1024 * 1024 * 1024;
        #[cfg(not(target_pointer_width = "64"))]
        let six_gb: usize = usize::MAX;
        let inb_data_cap = ((total_inb as usize).saturating_mul(2)).min(six_gb);
        inb_data.reserve(inb_data_cap);

        // CSR is contiguous: start[i] = end of node i-1 = in_cursors[i-1] after fill.
        let mut start = 0usize;
        // Reusable per-node scratch: copy each node's inbound slice out of the
        // chunked store so we can sort/dedup it, then free chunks behind us.
        let mut nb: Vec<u32> = Vec::new();
        // Free consumed chunks every ~256 M slots crossed (one chunk).
        let mut next_free_at: usize = 1 << 26;
        for i in 0..n {
            let end = in_cursors[i] as usize; // in_cursors[i] = end offset after fill

            // Record a sampled block offset at each block boundary (BEFORE the
            // count-prefix), so a lookup for any node in the block can seek here
            // and scan-skip forward to the target node.
            if i % INB_BLOCK == 0 {
                inb_block_off.push(inb_data.len() as u64);
            }

            let count = end - start;
            if count == 0 {
                // No predecessors: emit vbyte(0) and move on — skip copy/sort/dfn.
                vbyte::encode(0, &mut inb_data);
                start = end;
                if start >= next_free_at {
                    inb_flat.free_below(start);
                    next_free_at = start + (1 << 26);
                }
                if i == n / 2 {
                    crate::trace::probe("inbound Phase-4: midpoint (inb_flat+inb_data coexist)");
                }
                continue;
            }

            // Translate each predecessor NODE -> pre-order number (dfn);
            // drop unreachable predecessors (dfn == UNDEFINED). Use range_slice
            // for a zero-copy read when the range fits in one chunk; fall back
            // to copy_range otherwise. Store translated values in nb.
            let mut w = 0usize;
            if let Some(raw) = inb_flat.range_slice(start, end) {
                nb.clear();
                nb.reserve(raw.len());
                for &raw_val in raw {
                    let node = (raw_val & 0x7fff_ffff) as usize;
                    let pre = dfn[node];
                    if pre != u32::MAX {
                        nb.push(pre);
                        w += 1;
                    }
                }
            } else {
                inb_flat.copy_range(start, end, &mut nb);
                for r in 0..nb.len() {
                    let node = (nb[r] & 0x7fff_ffff) as usize;
                    let pre = dfn[node];
                    if pre != u32::MAX {
                        nb[w] = pre;
                        w += 1;
                    }
                }
            }

            // Sort by pre-order and dedup. Short-circuit for 0/1 translated
            // entries — the overwhelming majority of nodes in a heap graph have
            // at most one live predecessor, so this saves hundreds of millions of
            // sort calls.
            let unique_end = if w <= 1 {
                w
            } else {
                let pre_slice = &mut nb[..w];
                pre_slice.sort_unstable();
                let mut write = 1usize;
                for read in 1..pre_slice.len() {
                    if pre_slice[read] != pre_slice[write - 1] {
                        pre_slice[write] = pre_slice[read];
                        write += 1;
                    }
                }
                write
            };

            // Count-prefix makes each node's slice self-delimiting.
            vbyte::encode(unique_end as u32, &mut inb_data);
            // Delta-encode pre-order values.
            let mut prev: u32 = 0;
            for &pre in &nb[..unique_end] {
                vbyte::encode(pre - prev, &mut inb_data);
                prev = pre;
            }
            start = end;
            if start >= next_free_at {
                inb_flat.free_below(start);
                next_free_at = start + (1 << 26);
            }
            if i == n / 2 {
                crate::trace::probe("inbound Phase-4: midpoint (inb_flat+inb_data coexist)");
            }
        }
        drop(nb);
        drop(inb_flat);
        drop(in_cursors); // inbound CSR done; end-offset cursors no longer needed

        // Trailing sentinel = total byte length (bounds the last block's scan).
        inb_block_off.push(inb_data.len() as u64);

        if crate::trace::enabled() {
            eprintln!(
                "[trace-rss] inbound Phase-4: inb_data len={} MB cap={} MB block_off len={}",
                inb_data.len() / (1024 * 1024),
                inb_data.capacity() / (1024 * 1024),
                inb_block_off.len()
            );
        }
        crate::trace::probe("inbound Phase-4: after inb_data built");
        Ok((inb_block_off, inb_data))
    }

    /// Like `build()` (HPROF rescan path for inbound) but also drives a
    /// per-object callback with the dense-id outbound edge list, so MAT outbound
    /// can be emitted during the same HPROF scan.
    ///
    /// `on_outbound(dense_src, dense_dsts) -> io::Result<()>` receives each
    /// object's outbound edges as a `Vec<u32>` (allocated per object; the callback
    /// can drain/reuse it). Called in HPROF file order (not MAT id order).
    ///
    /// Memory benefit vs build_from_fwd: `fwd_targets` (6+ GB) can be dropped
    /// BEFORE calling this, so inb_flat and fwd_targets never coexist.
    /// `fwd_tgt_c` is also eliminated from the emit_outbound peak window.
    ///
    /// Cost: one extra HPROF scan (~3 min on the 34 GB dump).
    pub fn build_mat_scan<F>(
        self,
        dfn: &[u32],
        mut on_outbound: F,
    ) -> io::Result<(Vec<u64>, Vec<u8>)>
    where
        F: FnMut(usize, Vec<u32>) -> io::Result<()>,
    {
        let InboundBuilder {
            source,
            id_size,
            n,
            id_map,
            id_map_c,
            id_map_codec,
            class_addr_to_hist,
            field_plans_dense,
            mut in_cursors,
            total_inb,
            synthetic_edges,
            ..
        } = self;

        let id_map = match id_map {
            Some(m) => m,
            None => {
                let (blob, len) = id_map_c.expect("id_map neither live nor compressed");
                crate::id_map::IdMap::from_compressed(&blob, len, id_map_codec)?
            }
        };

        let mut inb_flat = crate::chunkvec::ChunkU32::zeroed(total_inb as usize);
        if crate::trace::enabled() {
            eprintln!(
                "[trace-rss] inbound mat-scan: total_inb={} edges, inb_flat={} MB",
                total_inb,
                (total_inb as usize * 4) / (1024 * 1024)
            );
        }
        crate::trace::probe("inbound mat-scan: after inb_flat alloc");

        // Single HPROF scan: fill inb_flat (inbound) AND collect per-object
        // forward edges for the on_outbound callback.
        {
            let mut r = source.open()?;
            let mut scratch: Vec<u8> = Vec::with_capacity(4096);
            let ids = id_size as u64;
            let mut cache = crate::id_map::IndexCache::new();

            loop {
                let tag = match r.u1() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                };
                let _ts = match r.u4() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                };
                let length = match r.u4() {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                    other => other?,
                } as u64;
                match tag {
                    tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                        Self::scan_inb_and_outbound(
                            &mut r,
                            id_size,
                            ids,
                            length,
                            &id_map,
                            &class_addr_to_hist,
                            &field_plans_dense,
                            &mut inb_flat,
                            &mut in_cursors,
                            &mut scratch,
                            &mut cache,
                            &mut on_outbound,
                        )?;
                    }
                    tags::HEAP_DUMP_END => break,
                    _ => match r.skip(length) {
                        Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                        other => other?,
                    },
                }
            }
        }

        drop(id_map);
        drop(class_addr_to_hist);
        drop(field_plans_dense);

        for &(src, dst) in &synthetic_edges {
            inb_flat.set(in_cursors[dst as usize] as usize, src);
            in_cursors[dst as usize] += 1;
        }

        crate::trace::probe("inbound: before Phase-4 (after mat-scan + drops)");
        Self::encode_phase4(n, total_inb, in_cursors, inb_flat, dfn)
    }

    /// Combined inbound-fill + outbound-collect for one HEAP_DUMP[_SEGMENT] record.
    /// Fills inb_flat and calls on_outbound for each object with its dense targets.
    #[allow(clippy::too_many_arguments)]
    fn scan_inb_and_outbound(
        r: &mut HprofReader,
        id_size: u8,
        ids: u64,
        mut remaining: u64,
        id_map: &crate::id_map::IdMap,
        class_addr_to_hist: &HashMap<u64, u32>,
        field_plans_dense: &[super::FieldPlan],
        inb_flat: &mut crate::chunkvec::ChunkU32,
        in_cursors: &mut Vec<u32>,
        scratch: &mut Vec<u8>,
        cache: &mut crate::id_map::IndexCache,
        on_outbound: &mut dyn FnMut(usize, Vec<u32>) -> io::Result<()>,
    ) -> io::Result<()> {
        use crate::types::heap;

        macro_rules! checked_sub {
            ($rem:expr, $sz:expr) => {
                $rem = $rem
                    .checked_sub($sz)
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "segment overrun"))?;
            };
        }

        macro_rules! try_read {
            ($e:expr) => {
                match $e {
                    Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(()),
                    other => other?,
                }
            };
        }

        while remaining > 0 {
            let sub_tag = try_read!(r.u1());
            checked_sub!(remaining, 1u64);

            match sub_tag {
                // Root sub-records: skip (no edges to/from these for our purposes)
                heap::ROOT_SYSTEM_CLASS
                | heap::ROOT_UNKNOWN
                | heap::ROOT_MONITOR_USED
                | heap::ROOT_INTERNED_STRING
                | heap::ROOT_DEBUGGER
                | heap::ROOT_VM_INTERNAL => {
                    try_read!(r.skip(ids));
                    checked_sub!(remaining, ids);
                }
                heap::ROOT_JNI_GLOBAL => {
                    try_read!(r.skip(2 * ids));
                    checked_sub!(remaining, 2 * ids);
                }
                heap::ROOT_JNI_LOCAL | heap::ROOT_JAVA_FRAME | heap::ROOT_JNI_MONITOR => {
                    try_read!(r.skip(ids + 8));
                    checked_sub!(remaining, ids + 8);
                }
                heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                    try_read!(r.skip(ids + 4));
                    checked_sub!(remaining, ids + 4);
                }
                heap::ROOT_STICKY_CLASS | heap::ROOT_THREAD_OBJ => {
                    let skip = if sub_tag == heap::ROOT_THREAD_OBJ {
                        ids + 8
                    } else {
                        ids
                    };
                    try_read!(r.skip(skip));
                    checked_sub!(remaining, skip);
                }
                heap::CLASS_DUMP => {
                    // Reuse fill_class_dump_edges logic via fill_heap_2b helper.
                    // For class objects we still need inbound edges (class→fields).
                    // Outbound from class dumps: skip for MAT outbound (MAT doesn't
                    // include static fields in outbound the same way).
                    let consumed = match Pass2::fill_class_dump_edges(
                        r,
                        id_size,
                        id_map,
                        false, // do_fwd — don't collect for outbound
                        true,  // do_inb
                        &mut crate::chunkvec::ChunkU32::zeroed(0),
                        &mut Vec::new(),
                        &mut None,
                        inb_flat,
                        in_cursors,
                    ) {
                        Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(()),
                        other => other?,
                    };
                    checked_sub!(remaining, consumed);
                }
                heap::INSTANCE_DUMP => {
                    let addr = try_read!(r.id());
                    try_read!(r.skip(4)); // stack_trace_serial
                    let class_id = try_read!(r.id());
                    let data_len = try_read!(r.u4()) as u64;
                    try_read!(r.read_bytes_reuse(scratch, data_len as usize));
                    checked_sub!(remaining, ids + 4 + ids + 4 + data_len);

                    let src_idx = match id_map.index_of(addr) {
                        Some(i) => i,
                        None => continue,
                    };

                    let mut fwd: Vec<u32> = Vec::new();

                    // Edge: instance → class object (inbound + outbound)
                    if let Some(dst) = cache.index_of(id_map, class_id) {
                        // inbound
                        inb_flat.set(in_cursors[dst] as usize, src_idx as u32);
                        in_cursors[dst] += 1;
                        fwd.push(dst as u32);
                    }

                    // Object-type instance fields
                    if let Some(&cidx) = class_addr_to_hist.get(&class_id) {
                        if (cidx as usize) < field_plans_dense.len() {
                            for &(off, _excluded) in &field_plans_dense[cidx as usize] {
                                let off = off as usize;
                                if off + id_size as usize <= scratch.len() {
                                    let ref_val =
                                        super::read_ref(&scratch[off..], id_size as usize);
                                    if ref_val != 0 {
                                        if let Some(dst) = cache.index_of(id_map, ref_val) {
                                            inb_flat.set(in_cursors[dst] as usize, src_idx as u32);
                                            in_cursors[dst] += 1;
                                            fwd.push(dst as u32);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    on_outbound(src_idx, fwd)?;
                }
                heap::OBJ_ARRAY_DUMP => {
                    let addr = try_read!(r.id());
                    try_read!(r.skip(4)); // stack_trace_serial
                    let count = try_read!(r.u4()) as u64;
                    let _elem_class_id = try_read!(r.id());
                    let byte_len = count.saturating_mul(ids);
                    try_read!(r.read_bytes_reuse(scratch, byte_len as usize));
                    checked_sub!(remaining, ids + 4 + 4 + ids + byte_len);

                    let src_idx = match id_map.index_of(addr) {
                        Some(i) => i,
                        None => continue,
                    };

                    let mut fwd: Vec<u32> = Vec::new();
                    for i in 0..count as usize {
                        let off = i * id_size as usize;
                        if off + id_size as usize <= scratch.len() {
                            let ref_val = super::read_ref(&scratch[off..], id_size as usize);
                            if ref_val != 0 {
                                if let Some(dst) = cache.index_of(id_map, ref_val) {
                                    inb_flat.set(in_cursors[dst] as usize, src_idx as u32);
                                    in_cursors[dst] += 1;
                                    fwd.push(dst as u32);
                                }
                            }
                        }
                    }
                    on_outbound(src_idx, fwd)?;
                }
                heap::PRIM_ARRAY_NODATA_DUMP => {
                    // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                    try_read!(r.skip(ids + 4 + 4 + 1));
                    checked_sub!(remaining, ids + 4 + 4 + 1);
                }

                heap::PRIM_ARRAY_DUMP => {
                    // No reference edges in primitive arrays.
                    let addr = try_read!(r.id());
                    try_read!(r.skip(4));
                    let count = try_read!(r.u4()) as u64;
                    let elem_type = try_read!(r.u1());
                    let elem_size = crate::types::HprofType::from_code(elem_type)
                        .map(|t| t.byte_size() as u64)
                        .unwrap_or(1);
                    let byte_len = count.saturating_mul(elem_size);
                    try_read!(r.skip(byte_len));
                    checked_sub!(remaining, ids + 4 + 4 + 1 + byte_len);
                    if let Some(src_idx) = id_map.index_of(addr) {
                        on_outbound(src_idx, Vec::new())?;
                    }
                }
                heap::HEAP_DUMP_INFO => {
                    try_read!(r.skip(4 + ids));
                    checked_sub!(remaining, 4 + ids);
                }
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("unknown heap sub-tag {sub_tag:#x}"),
                    ));
                }
            }
        }
        Ok(())
    }
}

/// Scatter-fill `fwd_tgt` by scanning the HPROF file. Uses `fwd_off` as
/// per-object write cursors (modified in-place): on entry `fwd_off[d]` is the
/// start of object d's outbound range; on exit `fwd_off[d]` is the end of that
/// range (= `fwd_off_original[d+1]`). Caller can therefore reconstruct each
/// object's range as `fwd_off[d-1] .. fwd_off[d]` (with `fwd_off[-1] = 0`).
///
/// Memory: only O(1) transient state beyond the caller-supplied Vecs.
pub fn rescan_outbound(
    ctx: &MatOutboundRescanCtx,
    fwd_off: &mut Vec<u32>,
    fwd_tgt: &mut Vec<u32>,
) -> io::Result<()> {
    use crate::types::tags;
    use std::io::ErrorKind;

    // Restore id_map from compressed blob (or live copy).
    let id_map = match ctx.id_map_c.as_ref() {
        Some((blob, len)) => crate::id_map::IdMap::from_compressed(blob, *len, ctx.id_map_codec)?,
        None => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "rescan_outbound: id_map not compressed (unexpected)",
            ));
        }
    };
    let ids = ctx.id_size as u64;
    let mut scratch: Vec<u8> = Vec::with_capacity(4096);
    let mut cache = crate::id_map::IndexCache::new();

    let mut r = ctx.source.open()?;
    loop {
        let tag = match r.u1() {
            Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
            other => other?,
        };
        let _ts = match r.u4() {
            Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
            other => other?,
        };
        let length = match r.u4() {
            Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
            other => other?,
        } as u64;
        match tag {
            tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                scan_fwd_segment(
                    &mut r,
                    ctx.id_size,
                    ids,
                    length,
                    &id_map,
                    &ctx.class_addr_to_hist,
                    &ctx.field_plans_dense,
                    fwd_off,
                    fwd_tgt,
                    &mut scratch,
                    &mut cache,
                )?;
            }
            tags::HEAP_DUMP_END => break,
            _ => match r.skip(length) {
                Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
                other => other?,
            },
        }
    }
    Ok(())
}

/// Skip one CLASS_DUMP sub-record, returning the number of bytes consumed.
fn skip_class_dump(r: &mut HprofReader, id_size: u8, ids: u64) -> io::Result<u64> {
    use super::scan::value_size;
    let mut consumed = 0u64;
    // class_addr (id) + stack_trace_serial (u32) + super_id (id) + loader_id (id)
    //   + signers_id + domain_id + reserved1 + reserved2 (4×ids) + instance_size (u32)
    r.skip(ids + 4 + ids + ids + ids * 4 + 4)?;
    consumed += ids + 4 + ids + ids + ids * 4 + 4;
    // constant pool
    let cp = r.u2()? as u64;
    consumed += 2;
    for _ in 0..cp {
        r.skip(2)?;
        consumed += 2; // cp_index
        let tp = r.u1()?;
        consumed += 1;
        let vs = value_size(tp, id_size);
        r.skip(vs)?;
        consumed += vs;
    }
    // static fields
    let sc = r.u2()? as u64;
    consumed += 2;
    for _ in 0..sc {
        r.skip(ids)?;
        consumed += ids; // name_id
        let tp = r.u1()?;
        consumed += 1;
        let vs = value_size(tp, id_size);
        r.skip(vs)?;
        consumed += vs;
    }
    // instance fields (just descriptors, no values)
    let ic = r.u2()? as u64;
    consumed += 2;
    let ic_skip = ic.saturating_mul(ids + 1);
    r.skip(ic_skip)?;
    consumed += ic_skip;
    Ok(consumed)
}

/// Scatter outbound edges from one HEAP_DUMP[_SEGMENT] record into `fwd_tgt`,
/// using `fwd_off[d]` as per-object write cursor (incremented in-place).
#[allow(clippy::too_many_arguments)]
fn scan_fwd_segment(
    r: &mut HprofReader,
    id_size: u8,
    ids: u64,
    mut remaining: u64,
    id_map: &crate::id_map::IdMap,
    class_addr_to_hist: &HashMap<u64, u32>,
    field_plans_dense: &[super::FieldPlan],
    fwd_off: &mut Vec<u32>,
    fwd_tgt: &mut Vec<u32>,
    scratch: &mut Vec<u8>,
    cache: &mut crate::id_map::IndexCache,
) -> io::Result<()> {
    use crate::types::heap;

    macro_rules! checked_sub {
        ($rem:expr, $sz:expr) => {
            $rem = $rem
                .checked_sub($sz)
                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "segment overrun"))?;
        };
    }

    while remaining > 0 {
        let sub_tag = r.u1()?;
        checked_sub!(remaining, 1u64);

        match sub_tag {
            heap::ROOT_SYSTEM_CLASS
            | heap::ROOT_UNKNOWN
            | heap::ROOT_MONITOR_USED
            | heap::ROOT_INTERNED_STRING
            | heap::ROOT_DEBUGGER
            | heap::ROOT_VM_INTERNAL => {
                r.skip(ids)?;
                checked_sub!(remaining, ids);
            }
            heap::ROOT_JNI_GLOBAL => {
                r.skip(2 * ids)?;
                checked_sub!(remaining, 2 * ids);
            }
            heap::ROOT_JNI_LOCAL | heap::ROOT_JAVA_FRAME | heap::ROOT_JNI_MONITOR => {
                r.skip(ids + 8)?;
                checked_sub!(remaining, ids + 8);
            }
            heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                r.skip(ids + 4)?;
                checked_sub!(remaining, ids + 4);
            }
            heap::ROOT_STICKY_CLASS | heap::ROOT_THREAD_OBJ => {
                let skip = if sub_tag == heap::ROOT_THREAD_OBJ {
                    ids + 8
                } else {
                    ids
                };
                r.skip(skip)?;
                checked_sub!(remaining, skip);
            }
            heap::CLASS_DUMP => {
                // Class dumps don't contribute outbound edges in the MAT model.
                // Skip by parsing the variable-length structure.
                let consumed = skip_class_dump(r, id_size, ids)?;
                checked_sub!(remaining, consumed);
            }
            heap::INSTANCE_DUMP => {
                let addr = r.id()?;
                r.skip(4)?;
                let class_id = r.id()?;
                let data_len = r.u4()? as u64;
                r.read_bytes_reuse(scratch, data_len as usize)?;
                checked_sub!(remaining, ids + 4 + ids + 4 + data_len);

                let src_idx = match id_map.index_of(addr) {
                    Some(i) => i,
                    None => continue,
                };

                // Edge: instance → class object
                if let Some(dst) = cache.index_of(id_map, class_id) {
                    scatter_edge(fwd_off, fwd_tgt, src_idx, dst);
                }

                // Object-type instance fields
                if let Some(&cidx) = class_addr_to_hist.get(&class_id) {
                    if (cidx as usize) < field_plans_dense.len() {
                        for &(off, _excluded) in &field_plans_dense[cidx as usize] {
                            let off = off as usize;
                            if off + id_size as usize <= scratch.len() {
                                let ref_val = super::read_ref(&scratch[off..], id_size as usize);
                                if ref_val != 0 {
                                    if let Some(dst) = cache.index_of(id_map, ref_val) {
                                        scatter_edge(fwd_off, fwd_tgt, src_idx, dst);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            heap::OBJ_ARRAY_DUMP => {
                let addr = r.id()?;
                r.skip(4)?;
                let count = r.u4()? as u64;
                let _elem_class_id = r.id()?;
                let byte_len = count.saturating_mul(ids);
                r.read_bytes_reuse(scratch, byte_len as usize)?;
                checked_sub!(remaining, ids + 4 + 4 + ids + byte_len);

                let src_idx = match id_map.index_of(addr) {
                    Some(i) => i,
                    None => continue,
                };

                for i in 0..count as usize {
                    let off = i * id_size as usize;
                    if off + id_size as usize <= scratch.len() {
                        let ref_val = super::read_ref(&scratch[off..], id_size as usize);
                        if ref_val != 0 {
                            if let Some(dst) = cache.index_of(id_map, ref_val) {
                                scatter_edge(fwd_off, fwd_tgt, src_idx, dst);
                            }
                        }
                    }
                }
            }
            heap::PRIM_ARRAY_NODATA_DUMP => {
                // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                r.skip(ids + 4 + 4 + 1)?;
                checked_sub!(remaining, ids + 4 + 4 + 1);
            }

            heap::PRIM_ARRAY_DUMP => {
                let addr = r.id()?;
                r.skip(4)?;
                let count = r.u4()? as u64;
                let elem_type = r.u1()?;
                let elem_size = crate::types::HprofType::from_code(elem_type)
                    .map(|t| t.byte_size() as u64)
                    .unwrap_or(1);
                r.skip(count.saturating_mul(elem_size))?;
                checked_sub!(remaining, ids + 4 + 4 + 1 + count.saturating_mul(elem_size));
                let _ = addr; // no outbound from prim arrays
            }
            heap::HEAP_DUMP_INFO => {
                r.skip(4 + ids)?;
                checked_sub!(remaining, 4 + ids);
            }
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("unknown heap sub-tag {sub_tag:#x}"),
                ));
            }
        }
    }
    Ok(())
}

/// Scatter one edge `(src_idx → dst)` into `fwd_tgt` using `fwd_off[src_idx]`
/// as the write cursor (incremented in-place after writing).
#[inline]
fn scatter_edge(fwd_off: &mut Vec<u32>, fwd_tgt: &mut Vec<u32>, src_idx: usize, dst: usize) {
    let pos = fwd_off[src_idx] as usize;
    if pos < fwd_tgt.len() {
        fwd_tgt[pos] = dst as u32;
        fwd_off[src_idx] += 1;
    }
}

#[cfg(test)]
mod obj_graph_tests {
    use super::*;

    fn make_graph(fwd_offsets: Vec<u32>, fwd_targets_data: Vec<u32>) -> Graph {
        let n = fwd_offsets.len() - 1;
        Graph {
            n,
            format: String::new(),
            file_size: 0,
            source_name: String::new(),
            file_path: String::new(),
            id_size: 4,
            ref_size: 4,
            header_timestamp_ms: 0,
            gc_root_indices: vec![],
            gc_root_types: vec![],
            shallow: vec![100u32; n],
            class_idx: vec![],
            class_names: vec![],
            class_loader_id: vec![],
            loader_labels: Default::default(),
            thread_stacks: vec![],
            thread_props: Default::default(),
            thread_local_counts: Default::default(),
            thread_local_samples: Default::default(),
            thread_local_frame_samples: Default::default(),
            system_properties: vec![],
            jvm_version: None,
            class_obj_class_idx: Default::default(),
            fwd_offsets,
            fwd_targets: crate::chunkvec::ChunkU32::from_vec(fwd_targets_data),
            synthetic_root_count: 0,
            system_classloader_shallow: None,
            idom: vec![],
            retained: vec![],
            has_same_class_ancestor: crate::bitset::Bitset::default(),
            alloc_stack_serial: vec![],
            alloc_frames_by_serial: None,
            record_census: Default::default(),
            dup_strings: None,
            dup_prim_arrays: None,
            boxed_number_holders: vec![],
            arrays_by_size: Default::default(),
            incoming_refs_per_class: vec![],
            collections: Default::default(),
            references: Default::default(),
            reference_referent_idx: Default::default(),
            reference_null_referent_count: Default::default(),
            collection_attribution_raw: None,
            collection_attribution_truncated: false,
            fields_by_size_raw: None,
            coll_values_raw: None,
            node_kv: None,
            fwd_field_name_idx: None,
            field_name_pool: None,
            direct_byte_buffer_capacity_sum: 0,
            thread_local_null_key_count: 0,
            tl_entry_records: vec![],
            unreachable_retained: None,
            obj_graph_edges: None,
            type_ref_pairs: None,
            type_ref_pair_fields: None,
            class_ref_field_names: vec![],
        }
    }

    #[test]
    fn inbound_edges_captured_for_captured_dst() {
        // Objects: 0→1, 0→2, 1→2. All captured (top_n=usize::MAX).
        let g = make_graph(vec![0, 2, 3, 3], vec![1, 2, 2]);
        let cap = capture_obj_graph_edges(&g, usize::MAX, 100);
        // Object 2 has two inbound: from 0 and from 1.
        let inb2 = cap.inbound_of(2);
        let srcs: Vec<u32> = inb2.iter().map(|&(s, _)| s).collect();
        assert!(srcs.contains(&0), "0→2 should be captured as inbound");
        assert!(srcs.contains(&1), "1→2 should be captured as inbound");
        // Object 1 has one inbound: from 0.
        let inb1 = cap.inbound_of(1);
        assert_eq!(inb1.len(), 1);
        assert_eq!(inb1[0].0, 0);
    }

    #[test]
    fn inbound_truncated_at_edge_cap() {
        // Object 0 has 3 outbound edges to object 1. edge_cap=2.
        let g = make_graph(vec![0, 3, 3], vec![1, 1, 1]);
        let cap = capture_obj_graph_edges(&g, usize::MAX, 2);
        assert!(
            cap.inbound_truncated.get(1),
            "inbound for 1 should be truncated"
        );
        assert_eq!(cap.inbound_of(1).len(), 2);
    }

    #[test]
    fn inbound_not_captured_for_uncaptured_dst() {
        // top_n=1: only object with highest shallow (all same, so object 0 by sort order).
        // Edges 0→1. Object 1 NOT in captured set, so no inbound for 1.
        let g = make_graph(vec![0, 1, 1], vec![1]);
        let cap = capture_obj_graph_edges(&g, 1, 100);
        // Object 0 is captured (only one), object 1 is not.
        // Since 1 is not captured, no inbound entry for 1.
        assert_eq!(cap.inbound_of(1).len(), 0);
    }
}