dbgscope 0.3.0

Typed WinDbg/DbgEng debug sessions, with kernel pool and user heap walkers built on them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use thiserror::Error;

use super::decode::{LfhBitmap, PoolHeaderLayout};
use crate::allocator::{LayoutProvenance, VsSemanticFamily, fingerprint};
use crate::dbgeng::{DbgEngError, DebugEngine, KernelImage, ModuleIdentity};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct SessionKey {
    /// Where the kernel is loaded **and which build it is**, from
    /// [crate::dbgeng::DebugEngine::kernel_image].
    ///
    /// The base alone is not enough for the layout cache, which is keyed on this and not on
    /// `target`. A programmatic host that switches to a different Windows build whose kernel
    /// happens to load at the same address receives no notification, so a base-keyed lookup
    /// hands back the previous build's type offsets and globals and the walker decodes the new
    /// target with them — silently, and confidently. Keyed on the image, entries are shared
    /// across engines looking at the same build, which is what keeps the cache from growing one
    /// entry per engine, and never shared across two builds.
    pub image: KernelImage,
    pub session: u64,
    /// Which target this is, from [crate::dbgeng::DebugEngine::target_identity].
    /// The kernel image does not distinguish two dumps from the same boot, and the
    /// generation only moves on debugger notifications a programmatic host never gets.
    pub target: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TypeLayout {
    pub size: u32,
    pub fields: HashMap<&'static str, u32>,
}

/// What a resolved [`PoolLayout`] actually depends on: the kernel image it was read out of.
///
/// Deliberately not a whole [`SessionKey`]. A layout describes the *image*, not which target
/// instance happens to be loaded, and keying it on the target inserted an entry per engine and
/// per `end_session` that nothing ever pruned (glslang/dbgscope#84). Deriving the key here
/// rather than asking each caller to blank a field is what keeps that from being one call
/// site's discipline — there is no key a caller can hand this cache that reintroduces it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct LayoutKey {
    pub image: KernelImage,
    pub session: u64,
}

impl From<SessionKey> for LayoutKey {
    fn from(key: SessionKey) -> Self {
        Self {
            image: key.image,
            session: key.session,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AllocatorSchema {
    pub key: LayoutKey,
    pub globals: HashMap<&'static str, u64>,
    pub types: HashMap<&'static str, TypeLayout>,
}

/// Kernel-facing compatibility name. User and kernel adapters both resolve the same
/// module-scoped allocator schema; the alias keeps the mature pool decoder terminology local.
pub(crate) type PoolLayout = AllocatorSchema;

#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LayoutError {
    #[error("missing allocator symbols ({item})")]
    Missing { item: String },
    #[error("unsupported allocator layout {fingerprint}: {detail}")]
    Unsupported { fingerprint: String, detail: String },
    #[error("allocator layout resolution was interrupted on request")]
    Interrupted,
    #[error("allocator layout resolution ran out of its walk budget")]
    BudgetExpired,
    #[error("polling allocator layout resolution failed: {detail}")]
    Poll { detail: String },
}

pub(crate) trait Symbols {
    fn poll(&self) -> Result<(), LayoutError> {
        Ok(())
    }

    fn symbol(&self, name: &str) -> Result<u64, DbgEngError>;
    fn type_id(&self, module: u64, name: &str) -> Result<u32, DbgEngError>;
    fn type_size(&self, module: u64, type_id: u32) -> Result<u32, DbgEngError>;
    fn field(&self, module: u64, type_id: u32, name: &str) -> Result<u32, DbgEngError>;
}

fn polled<T>(
    symbols: &impl Symbols,
    lookup: impl FnOnce() -> Result<T, DbgEngError>,
) -> Result<Result<T, DbgEngError>, LayoutError> {
    symbols.poll()?;
    let result = lookup();
    symbols.poll()?;
    Ok(result)
}

fn first_available<T>(
    symbols: &impl Symbols,
    aliases: &[&str],
    mut lookup: impl FnMut(&str) -> Result<T, DbgEngError>,
) -> Result<Option<T>, LayoutError> {
    for alias in aliases {
        if let Ok(value) = polled(symbols, || lookup(alias))? {
            return Ok(Some(value));
        }
    }
    Ok(None)
}

impl Symbols for DebugEngine {
    fn symbol(&self, name: &str) -> Result<u64, DbgEngError> {
        self.symbol_offset(name)
    }
    fn type_id(&self, module: u64, name: &str) -> Result<u32, DbgEngError> {
        DebugEngine::type_id(self, module, name)
    }
    fn type_size(&self, module: u64, type_id: u32) -> Result<u32, DbgEngError> {
        DebugEngine::type_size(self, module, type_id)
    }
    fn field(&self, module: u64, type_id: u32, name: &str) -> Result<u32, DbgEngError> {
        self.field_offset(module, type_id, name)
    }
}

struct TypeSpec {
    name: &'static str,
    fields: &'static [(&'static str, &'static [&'static str])],
}

const TYPES: &[TypeSpec] = &[
    TypeSpec {
        name: "_EX_POOL_HEAP_MANAGER_STATE",
        fields: &[
            ("PoolNode", &["PoolNode", "PoolNodes"]),
            ("NumberOfPools", &["NumberOfPools"]),
            ("SpecialHeaps", &["SpecialHeaps"]),
        ],
    },
    TypeSpec {
        name: "_EX_HEAP_POOL_NODE",
        fields: &[("Heaps", &["Heaps"])],
    },
    TypeSpec {
        name: "_SEGMENT_HEAP",
        fields: &[
            ("SegContexts", &["SegContexts", "SegmentContexts"]),
            ("VsContext", &["VsContext"]),
            ("LfhContext", &["LfhContext"]),
        ],
    },
    TypeSpec {
        name: "_HEAP_SEG_CONTEXT",
        fields: &[
            ("SegmentListHead", &["SegmentListHead"]),
            ("FreePageRanges", &["FreePageRanges", "FreePageRangeTree"]),
            ("UnitShift", &["UnitShift"]),
            ("FirstDescriptorIndex", &["FirstDescriptorIndex"]),
            ("SegmentMask", &["SegmentMask"]),
        ],
    },
    TypeSpec {
        name: "_HEAP_PAGE_SEGMENT",
        fields: &[
            ("ListEntry", &["ListEntry"]),
            ("DescArray", &["DescArray", "Descriptors"]),
            ("Signature", &["Signature"]),
        ],
    },
    TypeSpec {
        name: "_HEAP_PAGE_RANGE_DESCRIPTOR",
        fields: &[
            ("UnitSize", &["UnitSize"]),
            ("RangeFlags", &["RangeFlags", "Flags"]),
            ("TreeNode", &["TreeNode"]),
            ("TreeSignature", &["TreeSignature"]),
        ],
    },
    // Deliberately no *required* fields. The VS free-chunk state lives inside this
    // struct in one schema family and moved into a separately addressed
    // _HEAP_VS_AFFINITY_SLOT in another. Both shapes are resolved optionally below;
    // requiring either one here would refuse to walk half the world.
    TypeSpec {
        name: "_HEAP_VS_CONTEXT",
        fields: &[],
    },
    TypeSpec {
        name: "_HEAP_VS_DELAY_FREE_CONTEXT",
        fields: &[("ListHead", &["ListHead"])],
    },
    TypeSpec {
        name: "_HEAP_VS_SUBSEGMENT",
        fields: &[("Size", &["Size"]), ("Signature", &["Signature"])],
    },
    TypeSpec {
        name: "_HEAP_VS_CHUNK_HEADER",
        fields: &[("Sizes", &["Sizes", "HeaderBits"])],
    },
    TypeSpec {
        name: "_HEAP_VS_CHUNK_FREE_HEADER",
        fields: &[("TreeNode", &["TreeNode", "Node"])],
    },
    TypeSpec {
        name: "_HEAP_LFH_CONTEXT",
        fields: &[("Buckets", &["Buckets"])],
    },
    TypeSpec {
        name: "_HEAP_LFH_SUBSEGMENT",
        fields: &[
            ("BlockOffsets", &["BlockOffsets"]),
            ("BlockBitmap", &["BlockBitmap"]),
            ("BlockCount", &["BlockCount"]),
        ],
    },
    TypeSpec {
        name: "_HEAP_LFH_SUBSEGMENT_ENCODED_OFFSETS",
        fields: &[("EncodedData", &["EncodedData"])],
    },
    TypeSpec {
        name: "_RTLP_HP_HEAP_GLOBALS",
        fields: &[("HeapKey", &["HeapKey"]), ("LfhKey", &["LfhKey"])],
    },
    TypeSpec {
        name: "_RTL_RB_TREE",
        fields: &[("Root", &["Root", "EncodedRoot"])],
    },
    TypeSpec {
        name: "_RTL_BALANCED_NODE",
        fields: &[("Left", &["Left"]), ("Right", &["Right"])],
    },
    TypeSpec {
        name: "_POOL_HEADER",
        fields: &[
            ("PreviousSize", &["PreviousSize"]),
            ("PoolIndex", &["PoolIndex"]),
            ("BlockSize", &["BlockSize"]),
            ("PoolType", &["PoolType"]),
            ("PoolTag", &["PoolTag"]),
        ],
    },
    TypeSpec {
        name: "_SLIST_HEADER",
        fields: &[("Alignment", &["Alignment"]), ("Region", &["Region"])],
    },
];

const OPTIONAL_TYPES: &[TypeSpec] = &[
    // Affinity-slot family: the VS free-chunk tree, subsegment list and delay-free list live
    // outside _HEAP_VS_CONTEXT in one of these per-affinity slots. Absent in the inline family.
    //
    // The back-reference a slot uses to name its context is deliberately *not* required here, and
    // is resolved among the optional fields instead. It has been spelled two ways — `VsContext`
    // and `VsContextOffset` — and a required field that a build renames takes the whole type down
    // with it: `resolve_type` wants every field it lists, so one rename cost `FreeChunkTree` and
    // `DelayFreeContext` too and refused the build outright (`windbg-mcp` FOLLOWUPS item 78).
    // These two survive both spellings, so they are what the type is required to have.
    TypeSpec {
        name: "_HEAP_VS_AFFINITY_SLOT",
        fields: &[
            ("FreeChunkTree", &["FreeChunkTree"]),
            ("DelayFreeContext", &["DelayFreeContext"]),
        ],
    },
    // One entry per affinity; SlotRef locates the slot itself.
    TypeSpec {
        name: "_HEAP_VS_SLOT_MAP",
        fields: &[("SlotRef", &["SlotRef"])],
    },
    TypeSpec {
        name: "_RTL_DYNAMIC_LOOKASIDE",
        fields: &[("BucketCount", &["BucketCount"]), ("Buckets", &["Buckets"])],
    },
    TypeSpec {
        name: "_RTL_LOOKASIDE",
        fields: &[("ListHead", &["ListHead"])],
    },
    TypeSpec {
        name: "_POOL_TRACKER_BIG_PAGES",
        fields: &[
            ("Va", &["Va"]),
            ("Key", &["Key", "PoolTag"]),
            ("NumberOfBytes", &["NumberOfBytes", "Size"]),
        ],
    },
    TypeSpec {
        name: "_HEAP_LARGE_ALLOC_DATA",
        fields: &[
            ("TreeNode", &["TreeNode"]),
            ("VirtualAddress", &["VirtualAddress", "Address"]),
            ("AllocatedPages", &["AllocatedPages", "NumberOfPages"]),
        ],
    },
];

const OPTIONAL_FIELDS: &[(&str, &str, &[&str])] = &[
    ("_SEGMENT_HEAP", "Signature", &["Signature"]),
    ("_EX_HEAP_POOL_NODE", "Lookasides", &["Lookasides"]),
    ("_RTL_RB_TREE", "Encoded", &["Encoded"]),
    (
        "_SEGMENT_HEAP",
        "LargeAllocMetadata",
        &["LargeAllocMetadata"],
    ),
    (
        "_HEAP_LFH_CONTEXT",
        "AffinitySlots",
        &["AffinitySlots", "AffinitizedInfoArrays"],
    ),
    ("_RTL_LOOKASIDE", "Size", &["Size", "SizeClass"]),
    // Inline-family VS state.
    ("_HEAP_VS_CONTEXT", "FreeChunkTree", &["FreeChunkTree"]),
    (
        "_HEAP_VS_CONTEXT",
        "DelayFreeContext",
        &["DelayFreeContext"],
    ),
    // Affinity-slot family. Both references are self-relative to the VS context and
    // scaled by 64 bytes; the slot map holds AffinityMask + 1 entries.
    ("_HEAP_VS_CONTEXT", "SlotMapRef", &["SlotMapRef"]),
    ("_HEAP_VS_CONTEXT", "AffinityMask", &["AffinityMask"]),
    // `_RTL_HP_VS_CONFIG`, whose `Flags.PageAlignLargeAllocs` bit decides where a VS user block
    // begins when it would otherwise begin in the last sixteen bytes of a page — see
    // `snapshot::PoolRegion::vs_skips_page_end`. Optional so a PDB without it still walks: read
    // as unset then, with a diagnostic saying so.
    ("_HEAP_VS_CONTEXT", "Config", &["Config"]),
    // How an affinity slot names the context it belongs to. Two canonical names rather than two
    // aliases of one, because they are not two spellings of the same fact: `VsContext` holds the
    // context's address and `VsContextOffset` holds `slot - context`. Aliased, the newer build
    // would be decoded by the older rule — comparing a displacement against an address, matching
    // no context, and rejecting every slot. Separate names also make a PDB carrying both an
    // ambiguity to refuse rather than a coin toss.
    ("_HEAP_VS_AFFINITY_SLOT", "VsContext", &["VsContext"]),
    (
        "_HEAP_VS_AFFINITY_SLOT",
        "VsContextOffset",
        &["VsContextOffset"],
    ),
    ("_HEAP_LARGE_ALLOC_DATA", "UnusedBytes", &["UnusedBytes"]),
];

/// Where a heap keeps its entry on `ntdll`'s process heap list, which is where heap roots come
/// from on a build that keeps one (`crate::heap`). Resolved for the **user** schema only: the
/// kernel's `_SEGMENT_HEAP` carries the field too, and reading it there would move every kernel
/// fingerprint for a fact the pool walker never uses. Optional because a build that predates the
/// list need not have it, and such a build's PEB array is the whole answer.
const USER_OPTIONAL_FIELDS: &[(&str, &str, &[&str])] = &[
    ("_SEGMENT_HEAP", "UserContext", &["UserContext"]),
    ("_HEAP", "UserContext", &["UserContext"]),
];

const USER_TYPES: &[TypeSpec] = &[
    TypeSpec {
        name: "_PEB",
        fields: &[
            ("NumberOfHeaps", &["NumberOfHeaps"]),
            ("ProcessHeaps", &["ProcessHeaps"]),
        ],
    },
    TypeSpec {
        name: "_HEAP",
        fields: &[("Signature", &["Signature"])],
    },
];

const GLOBALS: &[(&str, &[&str])] = &[
    ("ExPoolState", &["nt!ExPoolState"]),
    ("RtlpHpHeapGlobals", &["nt!RtlpHpHeapGlobals"]),
];

const OPTIONAL_GLOBALS: &[(&str, &[&str])] = &[
    ("PoolBigPageTable", &["nt!PoolBigPageTable"]),
    ("PoolBigPageTableSize", &["nt!PoolBigPageTableSize"]),
];

fn resolve_type(
    symbols: &impl Symbols,
    module: u64,
    spec: &TypeSpec,
) -> Result<TypeLayout, LayoutError> {
    let type_id = polled(symbols, || symbols.type_id(module, spec.name))?.map_err(|_| {
        LayoutError::Missing {
            item: spec.name.into(),
        }
    })?;
    let size = polled(symbols, || symbols.type_size(module, type_id))?.map_err(|_| {
        LayoutError::Missing {
            item: spec.name.into(),
        }
    })?;
    let mut fields = HashMap::new();
    for &(canonical, aliases) in spec.fields {
        let offset = first_available(symbols, aliases, |field| {
            symbols.field(module, type_id, field)
        })?
        .ok_or_else(|| LayoutError::Missing {
            item: format!("{}.{canonical}", spec.name),
        })?;
        fields.insert(canonical, offset);
    }
    Ok(TypeLayout { size, fields })
}

fn apply_optional_fields(
    symbols: &impl Symbols,
    module: u64,
    types: &mut HashMap<&'static str, TypeLayout>,
    table: &[(&'static str, &'static str, &[&str])],
) -> Result<(), LayoutError> {
    for &(type_name, canonical, aliases) in table {
        let Some(layout) = types.get_mut(type_name) else {
            continue;
        };
        let Ok(type_id) = polled(symbols, || symbols.type_id(module, type_name))? else {
            continue;
        };
        if let Some(offset) = first_available(symbols, aliases, |field| {
            symbols.field(module, type_id, field)
        })? {
            layout.fields.insert(canonical, offset);
        }
    }
    Ok(())
}

/// How an affinity slot names the VS context it belongs to, and where that field sits.
///
/// The two are checked differently, which is the whole reason they are separate values: an
/// address is compared against the context, a displacement against `slot - context`. Getting
/// that backwards does not fail loudly — it rejects every slot and walks no VS evidence at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SlotBackReference {
    /// `_HEAP_VS_AFFINITY_SLOT::VsContext`: the context's own address.
    Address(usize),
    /// `_HEAP_VS_AFFINITY_SLOT::VsContextOffset`: `slot - context`, unscaled bytes.
    Displacement(usize),
}

/// Where a resolved schema keeps its VS free-chunk state, with the offsets that decided it.
///
/// Produced once, by [`AllocatorSchema::vs_shape`]. Both the provenance a caller is told about
/// and the walk that reads the target derive from this single judgement: they used to reach the
/// same conclusion independently, from two copies of the field list, which is two places for the
/// next rename to be handled in and one of them to be missed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VsShape {
    /// The context owns the tree, so there is exactly one root: the context itself.
    Inline { tree: usize, delay: Option<usize> },
    /// The tree lives in per-affinity slots reached through the context's slot map.
    AffinitySlots {
        slot_map_ref: usize,
        affinity_mask: usize,
        slot_ref: usize,
        tree: usize,
        delay: Option<usize>,
        back: SlotBackReference,
    },
}

impl VsShape {
    pub(crate) fn family(self) -> VsSemanticFamily {
        match self {
            Self::Inline { .. } => VsSemanticFamily::Inline,
            Self::AffinitySlots {
                back: SlotBackReference::Address(_),
                ..
            } => VsSemanticFamily::AffinitySlots,
            Self::AffinitySlots {
                back: SlotBackReference::Displacement(_),
                ..
            } => VsSemanticFamily::AffinitySlotsSelfRelative,
        }
    }
}

/// What the inline family needs, in the order a reader wants them named.
const INLINE_VS_FIELDS: &[(&str, &str)] = &[
    ("_HEAP_VS_CONTEXT", "FreeChunkTree"),
    ("_HEAP_VS_CONTEXT", "DelayFreeContext"),
];

/// What both affinity-slot families need. They differ only in how a slot names its context,
/// which is resolved separately because a missing back-reference and a renamed one are the
/// same absence here and different answers there.
const AFFINITY_VS_FIELDS: &[(&str, &str)] = &[
    ("_HEAP_VS_CONTEXT", "SlotMapRef"),
    ("_HEAP_VS_CONTEXT", "AffinityMask"),
    ("_HEAP_VS_AFFINITY_SLOT", "FreeChunkTree"),
    ("_HEAP_VS_AFFINITY_SLOT", "DelayFreeContext"),
    ("_HEAP_VS_SLOT_MAP", "SlotRef"),
];

/// The back-reference spellings, newest first. Order is presentation only — resolving more than
/// one is refused rather than resolved by precedence.
const SLOT_BACK_REFERENCES: &[&str] = &["VsContextOffset", "VsContext"];

impl AllocatorSchema {
    pub(crate) fn is_user(&self) -> bool {
        !self.globals.contains_key("ExPoolState") && self.globals.contains_key("RtlpHpHeapGlobals")
    }

    /// How this schema's allocator packs an LFH block bitmap: `ntdll` and `nt` differ, and
    /// nothing in either PDB says so — both type `BlockBitmap` as one `ULONGLONG`. So this is a
    /// fact about *which allocator the schema came from*, never about a build number.
    pub(crate) fn lfh_bitmap(&self) -> LfhBitmap {
        if self.is_user() {
            LfhBitmap::SplitWord
        } else {
            LfhBitmap::ContiguousBits
        }
    }

    pub(crate) fn type_layout(&self, name: &str) -> Result<&TypeLayout, LayoutError> {
        self.types
            .get(name)
            .ok_or_else(|| LayoutError::Missing { item: name.into() })
    }

    pub(crate) fn field(&self, type_name: &str, field: &str) -> Result<usize, LayoutError> {
        self.type_layout(type_name)?
            .fields
            .get(field)
            .copied()
            .map(|value| value as usize)
            .ok_or_else(|| LayoutError::Missing {
                item: format!("{type_name}.{field}"),
            })
    }

    pub(crate) fn pool_header_layout(&self) -> Result<PoolHeaderLayout, LayoutError> {
        // User Segment Heap blocks do not carry the kernel's `_POOL_HEADER`. A zero-sized
        // adapter lets the shared LFH/VS/page-range decoder report the block geometry without
        // inventing a tag header.
        if self.is_user() {
            return Ok(PoolHeaderLayout {
                size: 0,
                previous_size: 0,
                pool_index: 0,
                block_size: 0,
                pool_type: 0,
                tag: 0,
            });
        }
        Ok(PoolHeaderLayout {
            size: self.type_layout("_POOL_HEADER")?.size as usize,
            previous_size: self.field("_POOL_HEADER", "PreviousSize")?,
            pool_index: self.field("_POOL_HEADER", "PoolIndex")?,
            block_size: self.field("_POOL_HEADER", "BlockSize")?,
            pool_type: self.field("_POOL_HEADER", "PoolType")?,
            tag: self.field("_POOL_HEADER", "PoolTag")?,
        })
    }

    pub(crate) fn resolve(symbols: &impl Symbols, key: LayoutKey) -> Result<Self, LayoutError> {
        let mut globals = HashMap::new();
        for &(canonical, aliases) in GLOBALS {
            let value = first_available(symbols, aliases, |name| symbols.symbol(name))?
                .ok_or_else(|| LayoutError::Missing {
                    item: canonical.into(),
                })?;
            globals.insert(canonical, value);
        }
        for &(canonical, aliases) in OPTIONAL_GLOBALS {
            if let Some(value) = first_available(symbols, aliases, |name| symbols.symbol(name))? {
                globals.insert(canonical, value);
            }
        }
        let mut types = HashMap::new();
        for spec in TYPES {
            types.insert(spec.name, resolve_type(symbols, key.image.base, spec)?);
        }
        for spec in OPTIONAL_TYPES {
            match resolve_type(symbols, key.image.base, spec) {
                Ok(layout) => {
                    types.insert(spec.name, layout);
                }
                Err(LayoutError::Missing { .. }) => {}
                Err(error) => return Err(error),
            }
        }
        apply_optional_fields(symbols, key.image.base, &mut types, OPTIONAL_FIELDS)?;
        Ok(Self {
            key,
            globals,
            types,
        })
    }

    /// Resolve the same Segment Heap decoder schema from `ntdll` rather than `nt`.
    pub(crate) fn resolve_user(
        symbols: &impl Symbols,
        key: LayoutKey,
    ) -> Result<Self, LayoutError> {
        let mut globals = HashMap::new();
        let global =
            polled(symbols, || symbols.symbol("ntdll!RtlpHpHeapGlobals"))?.map_err(|_| {
                LayoutError::Missing {
                    item: "RtlpHpHeapGlobals".into(),
                }
            })?;
        globals.insert("RtlpHpHeapGlobals", global);

        let excluded = [
            "_EX_POOL_HEAP_MANAGER_STATE",
            "_EX_HEAP_POOL_NODE",
            "_POOL_HEADER",
        ];
        let mut types = HashMap::new();
        for spec in TYPES.iter().filter(|spec| !excluded.contains(&spec.name)) {
            types.insert(spec.name, resolve_type(symbols, key.image.base, spec)?);
        }
        for spec in USER_TYPES {
            types.insert(spec.name, resolve_type(symbols, key.image.base, spec)?);
        }
        // Kernel-only optional lookaside types are intentionally tolerated when `ntdll`
        // omits them. The big-page tracker alone is skipped explicitly because interpreting
        // it requires the kernel-only global table and dedicated discovery path.
        for spec in OPTIONAL_TYPES {
            if spec.name == "_POOL_TRACKER_BIG_PAGES" {
                continue;
            }
            match resolve_type(symbols, key.image.base, spec) {
                Ok(layout) => {
                    types.insert(spec.name, layout);
                }
                Err(LayoutError::Missing { .. }) => {}
                Err(error) => return Err(error),
            }
        }
        apply_optional_fields(symbols, key.image.base, &mut types, OPTIONAL_FIELDS)?;
        apply_optional_fields(symbols, key.image.base, &mut types, USER_OPTIONAL_FIELDS)?;
        if !types
            .get("_SEGMENT_HEAP")
            .is_some_and(|layout| layout.fields.contains_key("Signature"))
        {
            return Err(LayoutError::Missing {
                item: "_SEGMENT_HEAP.Signature".into(),
            });
        }
        Ok(Self {
            key,
            globals,
            types,
        })
    }

    /// Names the fields of `wanted` this schema does not carry, as `Type.Field`.
    fn absent(&self, wanted: &[(&str, &str)]) -> Vec<String> {
        wanted
            .iter()
            .filter(|(type_name, field)| self.field(type_name, field).is_err())
            .map(|(type_name, field)| format!("{type_name}.{field}"))
            .collect()
    }

    /// Which VS representation this schema describes, decided by the fields it carries.
    ///
    /// An `Err` is the `detail` of a [`LayoutError::Unsupported`], phrased for whoever reads it
    /// next. That reader is the point: the previous message said only that no family was
    /// complete, which reads as a symbol problem, and the first diagnosis of one renamed field
    /// went to `.reload /f nt` and a PDB check before anyone compared a field name. Naming what
    /// each family wanted and what was missing puts the rename in the message itself.
    pub(crate) fn vs_shape(&self) -> Result<VsShape, String> {
        let inline_absent = self.absent(INLINE_VS_FIELDS);
        let affinity_absent = self.absent(AFFINITY_VS_FIELDS);

        let backs: Vec<(&str, usize)> = SLOT_BACK_REFERENCES
            .iter()
            .filter_map(|field| {
                self.field("_HEAP_VS_AFFINITY_SLOT", field)
                    .ok()
                    .map(|offset| (*field, offset))
            })
            .collect();

        // A PDB spelling the back-reference both ways cannot say which one names the context, and
        // picking by precedence would be a guess. Asked only once the rest of the shape is there:
        // two back-references on a slot type whose other fields are missing is an affinity family
        // that is incomplete anyway, and refusing it would take an inline target down with it.
        if affinity_absent.is_empty() && backs.len() > 1 {
            return Err(format!(
                "_HEAP_VS_AFFINITY_SLOT carries {}, so which one names the context is \
                 ambiguous and the layout is ambiguous with it",
                backs
                    .iter()
                    .map(|(field, _)| *field)
                    .collect::<Vec<_>>()
                    .join(" and "),
            ));
        }

        // **The back-reference is part of the affinity family's completeness, not a detail read
        // after choosing it.** A slot that cannot name the context it was reached from is not a
        // slot this walk can use, so a schema carrying the slot map and tree without one is not an
        // affinity layout — and deciding the two families before consulting it made a *valid
        // inline* layout that also carried those fields read as ambiguous, where it had previously
        // selected `Inline`. Withdrawing support for a shape that still works is the one direction
        // this module must not fail in.
        let affinity = match backs.as_slice() {
            [("VsContext", offset)] => Some(SlotBackReference::Address(*offset)),
            [("VsContextOffset", offset)] => Some(SlotBackReference::Displacement(*offset)),
            _ => None,
        }
        .filter(|_| affinity_absent.is_empty());

        match (inline_absent.is_empty(), affinity) {
            (true, Some(_)) => Err(format!(
                "both VS structural families are present and the layout is ambiguous \
                 (inline: {}; affinity slots: {})",
                INLINE_VS_FIELDS
                    .iter()
                    .map(|(ty, field)| format!("{ty}.{field}"))
                    .collect::<Vec<_>>()
                    .join(", "),
                AFFINITY_VS_FIELDS
                    .iter()
                    .map(|(ty, field)| format!("{ty}.{field}"))
                    .collect::<Vec<_>>()
                    .join(", "),
            )),
            (true, None) => Ok(VsShape::Inline {
                tree: self
                    .field("_HEAP_VS_CONTEXT", "FreeChunkTree")
                    .map_err(|error| error.to_string())?,
                delay: self.field("_HEAP_VS_CONTEXT", "DelayFreeContext").ok(),
            }),
            (false, Some(back)) => Ok(VsShape::AffinitySlots {
                slot_map_ref: self
                    .field("_HEAP_VS_CONTEXT", "SlotMapRef")
                    .map_err(|error| error.to_string())?,
                affinity_mask: self
                    .field("_HEAP_VS_CONTEXT", "AffinityMask")
                    .map_err(|error| error.to_string())?,
                slot_ref: self
                    .field("_HEAP_VS_SLOT_MAP", "SlotRef")
                    .map_err(|error| error.to_string())?,
                tree: self
                    .field("_HEAP_VS_AFFINITY_SLOT", "FreeChunkTree")
                    .map_err(|error| error.to_string())?,
                delay: self
                    .field("_HEAP_VS_AFFINITY_SLOT", "DelayFreeContext")
                    .ok(),
                back,
            }),
            // The affinity half of this message distinguishes the two ways it falls short, because
            // they are different diagnoses: fields missing is a shape this build does not have,
            // while every field but the back-reference is the shape having been *renamed* again —
            // which is the case that cost a day the first time it happened.
            (false, None) => Err(if affinity_absent.is_empty() {
                format!(
                    "no recognized VS structural family is complete: the affinity-slot shape \
                     resolved except for how a slot names its context — _HEAP_VS_AFFINITY_SLOT \
                     carries none of {}",
                    SLOT_BACK_REFERENCES.join(", "),
                )
            } else {
                format!(
                    "no recognized VS structural family is complete: inline wants {}, affinity \
                     slots want {}",
                    inline_absent.join(", "),
                    affinity_absent.join(", "),
                )
            }),
        }
    }

    pub(crate) fn provenance(
        &self,
        module: ModuleIdentity,
    ) -> Result<LayoutProvenance, LayoutError> {
        let mut facts = Vec::new();
        for (type_name, layout) in &self.types {
            facts.push(format!("type:{type_name}:size:{:#x}", layout.size));
            for (field, offset) in &layout.fields {
                facts.push(format!("field:{type_name}.{field}:{offset:#x}"));
            }
        }
        facts.sort_unstable();
        let fingerprint = fingerprint(facts.iter().map(String::as_str));
        let semantic_family = match self.vs_shape() {
            Ok(shape) => shape.family(),
            Err(detail) => {
                return Err(LayoutError::Unsupported {
                    fingerprint,
                    detail,
                });
            }
        };
        Ok(LayoutProvenance {
            module,
            fingerprint,
            semantic_family,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum LayoutTarget {
    Kernel,
    User,
}

impl LayoutTarget {
    fn probe_type(self) -> &'static str {
        match self {
            Self::Kernel => "_POOL_HEADER",
            Self::User => "_PEB",
        }
    }
}

#[derive(Default)]
pub(crate) struct LayoutCache {
    entries: Mutex<HashMap<(LayoutTarget, LayoutKey), AllocatorSchema>>,
}

impl LayoutCache {
    pub(crate) fn global() -> &'static Self {
        static CACHE: OnceLock<LayoutCache> = OnceLock::new();
        CACHE.get_or_init(Self::default)
    }

    pub(crate) fn get_or_resolve(
        &self,
        symbols: &impl Symbols,
        key: impl Into<LayoutKey>,
        target: LayoutTarget,
    ) -> Result<AllocatorSchema, LayoutError> {
        let key = key.into();
        // A cached schema can be shared by multiple DebugEngine instances. Probe a required
        // type on this engine before accepting the hit so DbgEng loads deferred symbols here,
        // rather than trusting that the engine which populated the global cache loaded them.
        let probe = target.probe_type();
        polled(symbols, || symbols.type_id(key.image.base, probe))?
            .map_err(|_| LayoutError::Missing { item: probe.into() })?;
        let cache_key = (target, key);
        if let Some(layout) = self.entries.lock().unwrap().get(&cache_key).cloned() {
            return Ok(layout);
        }
        let layout = match target {
            LayoutTarget::Kernel => AllocatorSchema::resolve(symbols, key),
            LayoutTarget::User => AllocatorSchema::resolve_user(symbols, key),
        }?;
        self.entries
            .lock()
            .unwrap()
            .insert(cache_key, layout.clone());
        Ok(layout)
    }

    pub(crate) fn invalidate(&self) {
        self.entries.lock().unwrap().clear();
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use super::*;

    #[derive(Default)]
    struct FakeSymbols {
        /// How many times a layout has actually been resolved through these symbols, so a
        /// cache hit can be told from a re-resolution rather than inferred from equal results.
        resolutions: Cell<usize>,
        type_lookups: Cell<usize>,
        polls: Cell<usize>,
        budget_after_polls: Option<usize>,
        interrupt_after_polls: Option<usize>,
        fallback_aliases: bool,
        optional_fields: bool,
        missing_global: Option<&'static str>,
        missing_type: Option<&'static str>,
        missing_field: Option<(&'static str, &'static str)>,
        /// Fields this PDB does not carry, for a double that has to withhold more than one.
        ///
        /// `missing_field` withholds exactly one, which is all a test about a single tolerated
        /// field needs. Modelling a *build* takes several at once: this double answers every name
        /// in the tables, so left alone it completes two VS families and the layout is ambiguous —
        /// which no shipped PDB is. Naming the fields a build lacks is what makes a double one
        /// build rather than the union of all of them.
        missing_fields: &'static [(&'static str, &'static str)],
    }

    impl FakeSymbols {
        fn error<T>() -> Result<T, DbgEngError> {
            Err(DbgEngError::InvalidCommand)
        }

        fn withholds(&self, type_name: &str, canonical: &str) -> bool {
            self.missing_field == Some((type_name, canonical))
                || self.missing_fields.contains(&(type_name, canonical))
        }

        fn field_value(name: &str) -> u32 {
            name.bytes().map(u32::from).sum()
        }

        fn type_spec(type_id: u32) -> Option<&'static TypeSpec> {
            type_id.checked_sub(1).and_then(|index| {
                TYPES
                    .iter()
                    .chain(OPTIONAL_TYPES)
                    .chain(USER_TYPES)
                    .nth(index as usize)
            })
        }

        fn resolve_field(&self, spec: &TypeSpec, name: &str) -> Result<u32, DbgEngError> {
            if let Some(&(canonical, aliases)) = spec
                .fields
                .iter()
                .find(|(_, aliases)| aliases.contains(&name))
            {
                if self.withholds(spec.name, canonical)
                    || (self.fallback_aliases && aliases.len() > 1 && name == aliases[0])
                {
                    return Self::error();
                }
                return Ok(Self::field_value(name));
            }

            if self.optional_fields
                && let Some(&(_, canonical, aliases)) = OPTIONAL_FIELDS
                    .iter()
                    .chain(USER_OPTIONAL_FIELDS)
                    .find(|(type_name, _, aliases)| {
                        *type_name == spec.name && aliases.contains(&name)
                    })
            {
                if self.withholds(spec.name, canonical)
                    || (self.fallback_aliases && aliases.len() > 1 && name == aliases[0])
                {
                    return Self::error();
                }
                return Ok(Self::field_value(name));
            }

            Self::error()
        }
    }

    impl Symbols for FakeSymbols {
        fn poll(&self) -> Result<(), LayoutError> {
            let polls = self.polls.get();
            self.polls.set(polls + 1);
            if self
                .interrupt_after_polls
                .is_some_and(|allowed| polls >= allowed)
            {
                return Err(LayoutError::Interrupted);
            }
            if self
                .budget_after_polls
                .is_some_and(|allowed| polls >= allowed)
            {
                return Err(LayoutError::BudgetExpired);
            }
            Ok(())
        }

        fn symbol(&self, name: &str) -> Result<u64, DbgEngError> {
            self.resolutions.set(self.resolutions.get() + 1);
            if self.missing_global == Some(name) {
                return Self::error();
            }
            if name == "ntdll!RtlpHpHeapGlobals" {
                return Ok(0x0000_7ffb_1234_5000);
            }
            GLOBALS
                .iter()
                .chain(OPTIONAL_GLOBALS)
                .position(|(_, aliases)| aliases.contains(&name))
                .map(|index| 0xffff_8000_0000_0000 + (index as u64 + 1) * 0x1000)
                .ok_or(DbgEngError::InvalidCommand)
        }

        fn type_id(&self, _module: u64, name: &str) -> Result<u32, DbgEngError> {
            self.type_lookups.set(self.type_lookups.get() + 1);
            if self.missing_type == Some(name) {
                return Self::error();
            }
            TYPES
                .iter()
                .chain(OPTIONAL_TYPES)
                .chain(USER_TYPES)
                .position(|spec| spec.name == name)
                .map(|index| index as u32 + 1)
                .ok_or(DbgEngError::InvalidCommand)
        }

        fn type_size(&self, _module: u64, type_id: u32) -> Result<u32, DbgEngError> {
            Self::type_spec(type_id)
                .map(|_| 0x20 + type_id)
                .ok_or(DbgEngError::InvalidCommand)
        }

        fn field(&self, _module: u64, type_id: u32, name: &str) -> Result<u32, DbgEngError> {
            let Some(spec) = Self::type_spec(type_id) else {
                return Self::error();
            };
            self.resolve_field(spec, name)
        }
    }

    fn key() -> LayoutKey {
        LayoutKey {
            image: KernelImage {
                base: 0xffff_f800_0000_0000,
                size: 0x145_0000,
                timestamp: 0x65f5_7999,
                checksum: 0xc6f_ee6,
            },
            session: 7,
        }
    }

    /// glslang/dbgscope#84 and #87 are the two ways one key can be wrong, and the image
    /// answers both. Keyed on the target, the cache grew an entry per engine and per
    /// `end_session` that nothing ever pruned. Keyed on the base alone — which is what fixing
    /// that left — two Windows builds whose kernels load at the same address share a layout,
    /// and nothing tells a programmatic host the target changed, so the walker decodes one
    /// build with the other's type offsets and globals and says nothing about it.
    #[test]
    fn test_layouts_are_shared_by_image_and_never_across_builds() {
        let symbols = FakeSymbols::default();
        let cache = LayoutCache::default();
        let resolve = |key: LayoutKey| {
            let layout = cache
                .get_or_resolve(&symbols, key, LayoutTarget::Kernel)
                .unwrap();
            (symbols.resolutions.get(), layout.key.image)
        };
        let through_an_engine = |key: SessionKey| {
            let layout = cache
                .get_or_resolve(&symbols, key, LayoutTarget::Kernel)
                .unwrap();
            (symbols.resolutions.get(), layout.key.image)
        };

        let (first, image) = resolve(key());
        assert!(first > 0);
        assert_eq!(image, key().image);

        // The same image reached through a second engine, whose `SessionKey` carries a target
        // of its own. One entry, shared: keying on the target is the growth #84 was about, and
        // the narrowing that prevents it is the cache's, not the caller's.
        assert_eq!(
            through_an_engine(SessionKey {
                image: key().image,
                session: key().session,
                target: 99,
            }),
            (first, key().image)
        );

        // The same *address*, a different build.
        let other_build = KernelImage {
            timestamp: 0x1122_3344,
            ..key().image
        };
        let (again, resolved) = resolve(LayoutKey {
            image: other_build,
            ..key()
        });
        assert!(
            again > first,
            "a second build at one base must not be served the first build's layout"
        );
        assert_eq!(resolved, other_build);
    }

    #[test]
    fn test_layout_cache_keeps_kernel_and_user_resolvers_separate() {
        let symbols = FakeSymbols {
            optional_fields: true,
            ..FakeSymbols::default()
        };
        let cache = LayoutCache::default();
        let kernel = cache
            .get_or_resolve(&symbols, key(), LayoutTarget::Kernel)
            .unwrap();
        let resolved_after_kernel = symbols.resolutions.get();
        let user = cache
            .get_or_resolve(&symbols, key(), LayoutTarget::User)
            .unwrap();

        assert!(!kernel.is_user());
        assert!(user.is_user());
        assert_eq!(kernel.lfh_bitmap(), LfhBitmap::ContiguousBits);
        assert_eq!(user.lfh_bitmap(), LfhBitmap::SplitWord);
        assert!(
            symbols.resolutions.get() > resolved_after_kernel,
            "one image key may not alias two module-specific resolver modes"
        );
    }

    #[test]
    fn test_layout_cache_hit_still_probes_symbols_on_the_current_engine() {
        let cache = LayoutCache::default();
        cache
            .get_or_resolve(&FakeSymbols::default(), key(), LayoutTarget::Kernel)
            .unwrap();

        let deferred = FakeSymbols {
            missing_type: Some(LayoutTarget::Kernel.probe_type()),
            ..FakeSymbols::default()
        };
        assert_eq!(
            missing_item(cache.get_or_resolve(&deferred, key(), LayoutTarget::Kernel)),
            "_POOL_HEADER",
            "a cache hit must probe the current engine instead of inheriting another engine's \
             symbol-loaded state"
        );
        assert_eq!(deferred.type_lookups.get(), 1);

        cache
            .get_or_resolve(
                &FakeSymbols {
                    optional_fields: true,
                    ..FakeSymbols::default()
                },
                key(),
                LayoutTarget::User,
            )
            .unwrap();
        let deferred_user = FakeSymbols {
            missing_type: Some(LayoutTarget::User.probe_type()),
            ..FakeSymbols::default()
        };
        assert_eq!(
            missing_item(cache.get_or_resolve(&deferred_user, key(), LayoutTarget::User)),
            "_PEB"
        );
        assert_eq!(deferred_user.type_lookups.get(), 1);
    }

    #[test]
    fn test_layout_resolution_stops_on_budget_or_interrupt_polls() {
        let budgeted = FakeSymbols {
            optional_fields: true,
            budget_after_polls: Some(6),
            ..FakeSymbols::default()
        };
        assert_eq!(
            LayoutCache::default().get_or_resolve(&budgeted, key(), LayoutTarget::User),
            Err(LayoutError::BudgetExpired)
        );
        assert_eq!(budgeted.polls.get(), 7);

        let interrupted = FakeSymbols {
            optional_fields: true,
            interrupt_after_polls: Some(4),
            ..FakeSymbols::default()
        };
        assert_eq!(
            LayoutCache::default().get_or_resolve(&interrupted, key(), LayoutTarget::User),
            Err(LayoutError::Interrupted)
        );
        assert_eq!(interrupted.polls.get(), 5);
    }

    #[test]
    fn test_cached_layout_still_checks_the_current_resolution_budget() {
        let cache = LayoutCache::default();
        cache
            .get_or_resolve(
                &FakeSymbols {
                    optional_fields: true,
                    ..FakeSymbols::default()
                },
                key(),
                LayoutTarget::User,
            )
            .unwrap();

        let expired = FakeSymbols {
            budget_after_polls: Some(0),
            ..FakeSymbols::default()
        };
        assert_eq!(
            cache.get_or_resolve(&expired, key(), LayoutTarget::User),
            Err(LayoutError::BudgetExpired),
            "a cache hit may not bypass the caller's deadline"
        );
        assert_eq!(expired.type_lookups.get(), 0);
    }

    fn missing_item(result: Result<PoolLayout, LayoutError>) -> String {
        match result.unwrap_err() {
            LayoutError::Missing { item } => item,
            other => panic!("expected a missing symbol error, got {other}"),
        }
    }

    #[test]
    fn test_resolve_required_layout_and_optional_absence() {
        let layout = PoolLayout::resolve(&FakeSymbols::default(), key()).unwrap();

        assert_eq!(layout.key, key());
        assert_eq!(layout.globals.len(), GLOBALS.len() + OPTIONAL_GLOBALS.len());
        assert_eq!(layout.types.len(), TYPES.len() + OPTIONAL_TYPES.len());
        assert_eq!(
            layout.field("_POOL_HEADER", "PoolTag"),
            Ok(FakeSymbols::field_value("PoolTag") as usize)
        );
        assert!(layout.field("_RTL_LOOKASIDE", "Size").is_err());
    }

    #[test]
    fn test_resolve_alias_fallback_and_optional_fields() {
        let symbols = FakeSymbols {
            fallback_aliases: true,
            optional_fields: true,
            ..FakeSymbols::default()
        };
        let layout = PoolLayout::resolve(&symbols, key()).unwrap();

        assert_eq!(
            layout.field("_EX_POOL_HEAP_MANAGER_STATE", "PoolNode"),
            Ok(FakeSymbols::field_value("PoolNodes") as usize)
        );
        assert_eq!(
            layout.field("_RTL_LOOKASIDE", "Size"),
            Ok(FakeSymbols::field_value("SizeClass") as usize)
        );
        assert_eq!(
            layout.field("_HEAP_LFH_CONTEXT", "AffinitySlots"),
            Ok(FakeSymbols::field_value("AffinitizedInfoArrays") as usize)
        );
        assert_eq!(
            layout.field("_RTL_RB_TREE", "Encoded"),
            Ok(FakeSymbols::field_value("Encoded") as usize)
        );
    }

    #[test]
    fn test_resolve_reports_missing_required_items() {
        assert_eq!(
            missing_item(PoolLayout::resolve(
                &FakeSymbols {
                    missing_global: Some("nt!ExPoolState"),
                    ..FakeSymbols::default()
                },
                key(),
            )),
            "ExPoolState"
        );
        assert_eq!(
            missing_item(PoolLayout::resolve(
                &FakeSymbols {
                    missing_type: Some("_POOL_HEADER"),
                    ..FakeSymbols::default()
                },
                key(),
            )),
            "_POOL_HEADER"
        );
        assert_eq!(
            missing_item(PoolLayout::resolve(
                &FakeSymbols {
                    missing_field: Some(("_POOL_HEADER", "PoolTag")),
                    ..FakeSymbols::default()
                },
                key(),
            )),
            "_POOL_HEADER.PoolTag"
        );
    }

    #[test]
    fn test_user_schema_requires_ntdll_globals_peb_fields_and_segment_signature() {
        let symbols = FakeSymbols {
            optional_fields: true,
            ..FakeSymbols::default()
        };
        let layout = PoolLayout::resolve_user(&symbols, key()).unwrap();
        assert!(layout.is_user());
        assert_eq!(layout.pool_header_layout().unwrap().size, 0);
        assert!(layout.field("_PEB", "ProcessHeaps").is_ok());
        assert!(layout.field("_SEGMENT_HEAP", "Signature").is_ok());

        assert_eq!(
            missing_item(PoolLayout::resolve_user(
                &FakeSymbols {
                    optional_fields: true,
                    missing_global: Some("ntdll!RtlpHpHeapGlobals"),
                    ..FakeSymbols::default()
                },
                key(),
            )),
            "RtlpHpHeapGlobals"
        );
        assert_eq!(
            missing_item(PoolLayout::resolve_user(
                &FakeSymbols {
                    optional_fields: true,
                    missing_field: Some(("_PEB", "ProcessHeaps")),
                    ..FakeSymbols::default()
                },
                key(),
            )),
            "_PEB.ProcessHeaps"
        );
        assert_eq!(
            missing_item(PoolLayout::resolve_user(&FakeSymbols::default(), key(),)),
            "_SEGMENT_HEAP.Signature"
        );
    }

    /// Where a heap names its entry on `ntdll`'s heap list is read for the user schema only, and
    /// its absence refuses nothing.
    ///
    /// The kernel's `_SEGMENT_HEAP` carries `UserContext` too, so a shared table would put it in
    /// every kernel fingerprint — moving the digests pinned above for a field the pool walker
    /// never reads. And a PDB without it is a build whose PEB array is the whole answer, so it
    /// resolves rather than refusing the heap tools.
    #[test]
    fn test_the_heap_list_entry_is_a_user_field_and_an_optional_one() {
        let symbols = FakeSymbols {
            optional_fields: true,
            ..FakeSymbols::default()
        };
        let user = PoolLayout::resolve_user(&symbols, key()).unwrap();
        assert!(user.field("_SEGMENT_HEAP", "UserContext").is_ok());
        assert!(user.field("_HEAP", "UserContext").is_ok());

        let kernel = PoolLayout::resolve(&symbols, key()).unwrap();
        assert!(
            kernel.field("_SEGMENT_HEAP", "UserContext").is_err(),
            "the kernel schema read a user-only field, which moves every kernel fingerprint"
        );

        let without = PoolLayout::resolve_user(
            &FakeSymbols {
                optional_fields: true,
                missing_fields: &[("_SEGMENT_HEAP", "UserContext"), ("_HEAP", "UserContext")],
                ..FakeSymbols::default()
            },
            key(),
        )
        .unwrap();
        assert!(without.field("_SEGMENT_HEAP", "UserContext").is_err());
    }

    #[test]
    fn test_layout_accessors_report_typed_missing_items() {
        let mut layout = PoolLayout::resolve(&FakeSymbols::default(), key()).unwrap();

        assert_eq!(
            layout.type_layout("_MISSING").unwrap_err(),
            LayoutError::Missing {
                item: "_MISSING".into()
            }
        );
        assert_eq!(
            layout.field("_POOL_HEADER", "Missing").unwrap_err(),
            LayoutError::Missing {
                item: "_POOL_HEADER.Missing".into()
            }
        );

        layout.types.remove("_POOL_HEADER");
        assert_eq!(
            layout.pool_header_layout().unwrap_err(),
            LayoutError::Missing {
                item: "_POOL_HEADER".into()
            }
        );
    }

    #[test]
    fn test_resolve_does_not_require_unused_metadata() {
        for unused_type in [
            "_RTLP_HP_HEAP_MANAGER",
            "_RTLP_HP_ALLOC_TRACKER",
            "_RTL_CSPARSE_BITMAP",
        ] {
            PoolLayout::resolve(
                &FakeSymbols {
                    missing_type: Some(unused_type),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();
        }

        for (unused_type, unused_field) in [
            ("_EX_POOL_HEAP_MANAGER_STATE", "HeapManager"),
            ("_HEAP_SEG_CONTEXT", "PagesPerUnitShift"),
            ("_HEAP_VS_CONTEXT", "SubsegmentList"),
            ("_HEAP_VS_SUBSEGMENT", "ListEntry"),
            ("_HEAP_VS_CHUNK_HEADER", "EncodedSegmentPageOffset"),
            ("_HEAP_LFH_SUBSEGMENT", "ListEntry"),
            ("_RTL_RB_TREE", "Min"),
        ] {
            PoolLayout::resolve(
                &FakeSymbols {
                    missing_field: Some((unused_type, unused_field)),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();
        }

        for unused_global in ["nt!RtlpLfhBucketIndexMap", "nt!RtlpBucketBlockSizes"] {
            PoolLayout::resolve(
                &FakeSymbols {
                    missing_global: Some(unused_global),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();
        }
    }

    #[test]
    fn test_resolve_tolerates_missing_optional_large_metadata() {
        for missing_type in ["_HEAP_LARGE_ALLOC_DATA", "_POOL_TRACKER_BIG_PAGES"] {
            let layout = PoolLayout::resolve(
                &FakeSymbols {
                    optional_fields: true,
                    missing_type: Some(missing_type),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();

            assert!(layout.type_layout(missing_type).is_err());
            assert!(layout.type_layout("_POOL_HEADER").is_ok());
        }

        for missing_global in ["nt!PoolBigPageTable", "nt!PoolBigPageTableSize"] {
            let canonical = OPTIONAL_GLOBALS
                .iter()
                .find(|(_, aliases)| aliases.contains(&missing_global))
                .unwrap()
                .0;
            let layout = PoolLayout::resolve(
                &FakeSymbols {
                    missing_global: Some(missing_global),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();

            assert!(!layout.globals.contains_key(canonical));
        }

        let layout = PoolLayout::resolve(
            &FakeSymbols {
                optional_fields: true,
                missing_field: Some(("_SEGMENT_HEAP", "LargeAllocMetadata")),
                ..FakeSymbols::default()
            },
            key(),
        )
        .unwrap();
        assert!(layout.field("_SEGMENT_HEAP", "LargeAllocMetadata").is_err());

        let layout = PoolLayout::resolve(
            &FakeSymbols {
                missing_field: Some(("_HEAP_LARGE_ALLOC_DATA", "TreeNode")),
                ..FakeSymbols::default()
            },
            key(),
        )
        .unwrap();
        assert!(layout.type_layout("_HEAP_LARGE_ALLOC_DATA").is_err());
    }

    #[test]
    fn test_resolve_tolerates_missing_optional_cache_metadata() {
        for missing_type in ["_RTL_DYNAMIC_LOOKASIDE", "_RTL_LOOKASIDE"] {
            let layout = PoolLayout::resolve(
                &FakeSymbols {
                    missing_type: Some(missing_type),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();

            assert!(layout.type_layout(missing_type).is_err());
        }

        for missing_field in [
            ("_EX_HEAP_POOL_NODE", "Lookasides"),
            ("_HEAP_LFH_CONTEXT", "AffinitySlots"),
        ] {
            let layout = PoolLayout::resolve(
                &FakeSymbols {
                    optional_fields: true,
                    missing_field: Some(missing_field),
                    ..FakeSymbols::default()
                },
                key(),
            )
            .unwrap();

            assert!(layout.field(missing_field.0, missing_field.1).is_err());
        }
    }

    fn pdb_module(timestamp: u32) -> ModuleIdentity {
        ModuleIdentity {
            name: "nt".into(),
            image_name: "ntkrnlmp.exe".into(),
            loaded_image_name: r"C:\Windows\System32\ntoskrnl.exe".into(),
            symbol_file: r"C:\symbols\ntkrnlmp.pdb".into(),
            symbols: crate::dbgeng::SymbolKind::Pdb,
            base: key().image.base,
            size: key().image.size,
            timestamp,
            checksum: key().image.checksum,
        }
    }

    /// Compact structural fixture for the inline-VS family in Vergilius' public-PDB-derived
    /// `10.0.19045.2965-x64.yml` and `10.0.22631.2428-x64.yml` in
    /// <https://github.com/VergiliusProject/kernels-data>. Runtime selection is exclusively by
    /// these PDB fields, never by the build labels in this comment.
    fn inline_vs_fixture() -> PoolLayout {
        let mut layout = PoolLayout::resolve(&FakeSymbols::default(), key()).unwrap();
        let context = layout.types.get_mut("_HEAP_VS_CONTEXT").unwrap();
        context.size = 0xc0;
        context.fields.insert("FreeChunkTree", 0x10);
        context.fields.insert("DelayFreeContext", 0x40);
        layout
    }

    /// Compact structural fixture for the affinity-slot VS family in Vergilius'
    /// `10.0.26200.6584-x64.yml` in <https://github.com/VergiliusProject/kernels-data>. The same
    /// family is measured on the later 26100 kernel recorded in `snapshot.rs`; the earlier
    /// `10.0.26100.1742` YAML is still inline, which is exactly why runtime selection must not use
    /// a 26100 build threshold.
    fn affinity_vs_fixture() -> PoolLayout {
        let mut layout = PoolLayout::resolve(&FakeSymbols::default(), key()).unwrap();
        let context = layout.types.get_mut("_HEAP_VS_CONTEXT").unwrap();
        context.size = 0x60;
        context.fields.insert("SlotMapRef", 0);
        context.fields.insert("AffinityMask", 2);
        let slot = layout.types.get_mut("_HEAP_VS_AFFINITY_SLOT").unwrap();
        slot.size = 0x80;
        slot.fields.insert("VsContext", 0);
        slot.fields.insert("FreeChunkTree", 0x10);
        slot.fields.insert("DelayFreeContext", 0x40);
        let map = layout.types.get_mut("_HEAP_VS_SLOT_MAP").unwrap();
        map.size = 4;
        map.fields.insert("SlotRef", 0);
        layout
    }

    /// The same affinity-slot family as [`affinity_vs_fixture`], on a build that names the
    /// back-reference `VsContextOffset` and stores `slot - context` in it.
    fn self_relative_vs_fixture() -> PoolLayout {
        let mut layout = affinity_vs_fixture();
        let slot = layout.types.get_mut("_HEAP_VS_AFFINITY_SLOT").unwrap();
        slot.fields.remove("VsContext");
        slot.fields.insert("VsContextOffset", 0);
        layout
    }

    /// What one shipped build's PDB does not carry: a type it predates, and fields it spells
    /// differently or does not have.
    ///
    /// Needed because this double otherwise answers every name in the tables at once, which is no
    /// build at all: it completes two VS families and is refused as ambiguous.
    struct Build {
        absent_type: Option<&'static str>,
        absent_fields: &'static [(&'static str, &'static str)],
    }

    /// Pre-26100 and early 26100: the tree is in the context, and `_HEAP_VS_AFFINITY_SLOT` does
    /// not exist yet — which is the fact that distinguishes this build, rather than any field.
    const INLINE_BUILD: Build = Build {
        absent_type: Some("_HEAP_VS_AFFINITY_SLOT"),
        absent_fields: &[],
    };

    /// 26100 from the affinity-slot move to mid-2026: a slot names its context by address.
    const ADDRESS_SLOT_BUILD: Build = Build {
        absent_type: None,
        absent_fields: &[
            ("_HEAP_VS_CONTEXT", "FreeChunkTree"),
            ("_HEAP_VS_CONTEXT", "DelayFreeContext"),
            ("_HEAP_VS_AFFINITY_SLOT", "VsContextOffset"),
        ],
    };

    /// 26100.33438 and 26200: the same slot map, the back-reference a displacement.
    const DISPLACEMENT_SLOT_BUILD: Build = Build {
        absent_type: None,
        absent_fields: &[
            ("_HEAP_VS_CONTEXT", "FreeChunkTree"),
            ("_HEAP_VS_CONTEXT", "DelayFreeContext"),
            ("_HEAP_VS_AFFINITY_SLOT", "VsContext"),
        ],
    };

    fn build_symbols(build: &Build) -> FakeSymbols {
        FakeSymbols {
            optional_fields: true,
            missing_type: build.absent_type,
            missing_fields: build.absent_fields,
            ..FakeSymbols::default()
        }
    }

    /// Every shipped shape resolves, and each is decoded by its own rule.
    ///
    /// Three at once is the requirement, not a transition: a debugger host is pointed at whatever
    /// build it is pointed at, and support for one shape is never withdrawn because another
    /// appeared.
    #[test]
    fn test_every_shipped_vs_shape_resolves_from_the_fields_its_build_carries() {
        for (build, expected) in [
            (&INLINE_BUILD, VsSemanticFamily::Inline),
            (&ADDRESS_SLOT_BUILD, VsSemanticFamily::AffinitySlots),
            (
                &DISPLACEMENT_SLOT_BUILD,
                VsSemanticFamily::AffinitySlotsSelfRelative,
            ),
        ] {
            let layout = PoolLayout::resolve(&build_symbols(build), key()).unwrap();

            let provenance = layout.provenance(pdb_module(0x1111_2222)).unwrap();

            assert_eq!(
                provenance.semantic_family,
                expected,
                "the {} build should decode as {expected:?}",
                expected.as_str()
            );
        }
    }

    /// The fields an older build carries resolve to exactly what they resolved to before the
    /// self-relative shape existed — the same offsets, and therefore the same fingerprint.
    ///
    /// Pinned as literals recorded from the code *before* that shape was added, which is the only
    /// thing that makes this a back-compat check rather than a restatement of what the code now
    /// does. A digest that moves means an older target is being described differently, and a
    /// caller comparing two runs across this change would read the difference as the target's.
    ///
    /// Not pinned on `FakeSymbols::default()`: the default double answers no optional field, so
    /// an inline layout built on it used to pick up a stray `_HEAP_VS_AFFINITY_SLOT.VsContext`
    /// through the *required* table and no longer does. That moves the synthetic digest while no
    /// real build's moves, which is an artefact of the double rather than a regression.
    ///
    /// **Re-recorded 2026-10-14**, when `_HEAP_VS_CONTEXT.Config` joined the optional fields
    /// (windbg-mcp `FOLLOWUPS.md` item 101). Every build carries that field, so every digest
    /// moved — the resolver found one more fact about each, which is the resolver's change and
    /// not the target's — and the two below were taken from the code with the field added. The
    /// pin is therefore against any *later* change moving an older build's schema, and the move
    /// itself is recorded in the changelog, where a caller comparing runs across it will look.
    #[test]
    fn test_an_older_builds_schema_is_unchanged_by_the_self_relative_shape() {
        for (build, recorded) in [
            (&INLINE_BUILD, "fnv1a64:ef5b5fcd191a6c34"),
            (&ADDRESS_SLOT_BUILD, "fnv1a64:f94b1d5fd7db5427"),
        ] {
            let layout = PoolLayout::resolve(&build_symbols(build), key()).unwrap();

            let provenance = layout.provenance(pdb_module(0x1111_2222)).unwrap();

            assert_eq!(
                provenance.fingerprint,
                recorded,
                "the schema resolved for the {} build has changed",
                provenance.semantic_family.as_str()
            );
        }
    }

    /// An inline layout that *also* carries the slot map and tree, with no back-reference on the
    /// slot, is **inline** — not an ambiguity.
    ///
    /// The affinity shape is not complete without exactly one way for a slot to name its context,
    /// so a schema like this offers one complete family and one incomplete one. Deciding the two
    /// families from their field lists *before* consulting the back-reference made it read as two
    /// complete families, which refused a target the previous code decoded — the one direction
    /// this module must not fail in. Raised on dbgscope#167 and true: `VsContext` used to sit in
    /// the affinity completeness list, so the same schema selected `Inline` before the rename.
    #[test]
    fn test_an_inline_layout_carrying_slot_fields_without_a_back_reference_is_inline() {
        let mut layout = affinity_vs_fixture();
        let context = layout.types.get_mut("_HEAP_VS_CONTEXT").unwrap();
        context.fields.insert("FreeChunkTree", 0x10);
        context.fields.insert("DelayFreeContext", 0x40);
        layout
            .types
            .get_mut("_HEAP_VS_AFFINITY_SLOT")
            .unwrap()
            .fields
            .remove("VsContext");

        let provenance = layout.provenance(pdb_module(0x1111_2222)).unwrap();

        assert_eq!(provenance.semantic_family, VsSemanticFamily::Inline);
    }

    /// A PDB carrying both spellings is refused rather than decoded by precedence.
    ///
    /// No shipped build does this, which is the point: if one ever does, the two fields cannot
    /// both be the back-reference and picking one would be a guess. Refusing says so.
    #[test]
    fn test_a_slot_carrying_both_back_references_is_ambiguous() {
        let mut both = self_relative_vs_fixture();
        both.types
            .get_mut("_HEAP_VS_AFFINITY_SLOT")
            .unwrap()
            .fields
            .insert("VsContext", 0);

        let error = both
            .provenance(pdb_module(0xdead_beef))
            .unwrap_err()
            .to_string();

        assert!(error.contains("layout is ambiguous"), "{error}");
        assert!(error.contains("VsContextOffset"), "{error}");
    }

    /// The refusal names the fields that were missing, because the message is the diagnosis.
    ///
    /// One renamed field refused a whole build, and the message said only that no family was
    /// complete — which reads as a symbol problem. The first diagnosis of it went to
    /// `.reload /f nt` and a PDB check before anyone compared a field name (`windbg-mcp`
    /// FOLLOWUPS item 78). A message that names what it wanted ends that at the first read.
    #[test]
    fn test_an_unsupported_layout_names_the_fields_it_wanted() {
        let mut renamed = self_relative_vs_fixture();
        renamed
            .types
            .get_mut("_HEAP_VS_AFFINITY_SLOT")
            .unwrap()
            .fields
            .remove("VsContextOffset");

        let error = renamed
            .provenance(pdb_module(0xdead_beef))
            .unwrap_err()
            .to_string();

        assert!(
            error.contains("no recognized VS structural family is complete"),
            "{error}"
        );
        assert!(
            error.contains("VsContextOffset") && error.contains("VsContext"),
            "the refusal should name the back-references it looked for: {error}"
        );
    }

    #[test]
    fn test_provenance_selects_validated_vs_families_without_build_thresholds() {
        let inline = inline_vs_fixture()
            .provenance(pdb_module(0x1111_2222))
            .unwrap();
        let affinity = affinity_vs_fixture()
            .provenance(pdb_module(0x3333_4444))
            .unwrap();

        assert_eq!(inline.semantic_family, VsSemanticFamily::Inline);
        assert_eq!(affinity.semantic_family, VsSemanticFamily::AffinitySlots);
        assert_ne!(inline.fingerprint, affinity.fingerprint);
        assert_eq!(inline.module.symbol_file, r"C:\symbols\ntkrnlmp.pdb");
        let inline_fixture = inline_vs_fixture();
        assert_eq!(
            inline_fixture.type_layout("_HEAP_VS_CONTEXT").unwrap().size,
            0xc0
        );
        assert_eq!(
            inline_fixture.field("_HEAP_VS_CONTEXT", "DelayFreeContext"),
            Ok(0x40)
        );
        let affinity_fixture = affinity_vs_fixture();
        assert_eq!(
            affinity_fixture
                .type_layout("_HEAP_VS_AFFINITY_SLOT")
                .unwrap()
                .size,
            0x80
        );
        assert_eq!(
            affinity_fixture.field("_HEAP_VS_CONTEXT", "SlotMapRef"),
            Ok(0)
        );
    }

    #[test]
    fn test_provenance_fails_closed_for_missing_or_conflicting_families() {
        let unknown = PoolLayout::resolve(&FakeSymbols::default(), key()).unwrap();
        assert!(
            unknown
                .provenance(pdb_module(0xdead_beef))
                .unwrap_err()
                .to_string()
                .contains("no recognized VS structural family")
        );

        let mut conflicting = affinity_vs_fixture();
        conflicting
            .types
            .get_mut("_HEAP_VS_CONTEXT")
            .unwrap()
            .fields
            .insert("FreeChunkTree", 0x10);
        conflicting
            .types
            .get_mut("_HEAP_VS_CONTEXT")
            .unwrap()
            .fields
            .insert("DelayFreeContext", 0x40);
        assert!(
            conflicting
                .provenance(pdb_module(0xdead_beef))
                .unwrap_err()
                .to_string()
                .contains("layout is ambiguous")
        );
        let unknown_error = unknown
            .provenance(pdb_module(0xdead_beef))
            .unwrap_err()
            .to_string();
        assert!(unknown_error.contains("fnv1a64:"), "{unknown_error}");
    }

    #[test]
    fn test_fingerprint_changes_when_a_pdb_field_offset_changes() {
        let first = inline_vs_fixture()
            .provenance(pdb_module(0x1111_2222))
            .unwrap();
        let mut changed = inline_vs_fixture();
        changed
            .types
            .get_mut("_HEAP_VS_CONTEXT")
            .unwrap()
            .fields
            .insert("FreeChunkTree", 0x18);
        let changed = changed.provenance(pdb_module(0x3333_4444)).unwrap();

        assert_ne!(first.fingerprint, changed.fingerprint);
    }
}