fnx-classes 0.3.0

Core graph classes and data structures for FrankenNetworkX
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
#![forbid(unsafe_code)]

pub mod digraph;

use fnx_runtime::{
    CgseValue, CompatibilityMode, DecisionAction, DecisionRecord, EvidenceLedger, EvidenceTerm,
    RuntimePolicy, bool_evidence, count_evidence,
};
use indexmap::{
    IndexMap,
    map::{RawEntryApiV1, raw_entry_v1::RawEntryMut},
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::hash::BuildHasher;

// br-r37-c1-fxhash: the node (String) and edge ((usize,usize)) key->index maps use
// a FAST non-cryptographic hasher instead of std's SipHash. IndexMap keeps insertion
// order in its Vec, so iteration order (nodes/edges/edges_ordered) is UNCHANGED — only
// lookup/insert hashing gets faster. The (usize,usize) edge keys especially: SipHash on
// 16 bytes (~20ns) -> FxHash on a usize (~3ns). Speeds up every has_edge/edge_attrs/
// get_index_of/construction insert across the library.
pub(crate) type FxIndexMap<K, V> = IndexMap<K, V, rustc_hash::FxBuildHasher>;
/// br-r37-c1-4c29a: the set half of the same alias. `MultiDiGraph`'s adjacency
/// rows are `IndexMap<String, IndexSet<usize>>` nested inside an already-Fx
/// outer map, and the inner pair was missed by the original fxhash pass — they
/// were still on the default SipHash. Both containers are insertion-ordered, so
/// the hasher is invisible to iteration order.
pub(crate) type FxIndexSet<T> = indexmap::IndexSet<T, rustc_hash::FxBuildHasher>;
use std::collections::HashSet;
use std::fmt;

pub type AttrMap = BTreeMap<String, CgseValue>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GraphError {
    FailClosed {
        operation: &'static str,
        reason: String,
    },
}

impl fmt::Display for GraphError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FailClosed { operation, reason } => {
                write!(f, "operation `{operation}` failed closed: {reason}")
            }
        }
    }
}

impl std::error::Error for GraphError {}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EdgeSnapshot {
    pub left: String,
    pub right: String,
    pub attrs: AttrMap,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GraphSnapshot {
    pub mode: CompatibilityMode,
    pub nodes: Vec<String>,
    /// br-snapnodeattrs: node attributes keyed by node name. Preserved
    /// across the ``snapshot`` round-trip so a graph with
    /// ``add_node(n, attrs)`` doesn't lose those attrs when replayed.
    /// Defaults to empty for snapshots produced by old code paths;
    /// consumers that don't care can ignore it.
    #[serde(default)]
    pub node_attrs: BTreeMap<String, AttrMap>,
    pub edges: Vec<EdgeSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiEdgeSnapshot {
    pub left: String,
    pub right: String,
    pub key: usize,
    pub attrs: AttrMap,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiGraphSnapshot {
    pub mode: CompatibilityMode,
    pub nodes: Vec<String>,
    /// See ``GraphSnapshot::node_attrs``.
    #[serde(default)]
    pub node_attrs: BTreeMap<String, AttrMap>,
    pub edges: Vec<MultiEdgeSnapshot>,
}

#[derive(Debug)]
pub struct Graph {
    mode: CompatibilityMode,
    revision: u64,
    nodes: FxIndexMap<String, AttrMap>,
    // br-r37-c1-d58s8 P2(c) slice 2: the String adjacency rows are GONE —
    // adj_indices (order-faithful integer rows) is the single row store;
    // String views derive through the nodes name table.
    /// Integer-indexed adjacency list for O(1) traversal. Each entry
    /// `adj_indices[i]` contains the node indices of neighbors of node i.
    /// This mirrors `adjacency` but avoids string hashing during BFS/CC.
    adj_indices: Vec<Vec<usize>>,
    /// br-r37-c1-d58s8: revision-keyed all-int weights memo (see
    /// DiGraph::all_int_cache).
    all_int_cache: std::sync::Arc<std::sync::RwLock<Option<(u64, String, bool)>>>,
    /// Revision-keyed, row-order-faithful mapping from an adjacency position to
    /// its `edges` storage slot. Weighted readers visit integer adjacency rows
    /// already; carrying the slot reads attrs without re-hashing the `(u, v)`
    /// pair. It is built lazily and each structural mutation advances
    /// `revision`, making stale rows unusable without mutation-side repair.
    edge_slots_by_neighbor: std::sync::RwLock<Option<(u64, Vec<Vec<usize>>)>>,
    edge_index_endpoints: Vec<(usize, usize)>,
    // br-r37-c1-d58s8 edges-map flip: keyed by the INDEX-CANONICAL
    // (min_idx, max_idx) node pair — zero String allocs/hashes per
    // insert (the profiled remaining store tax). Node removal REKEYS
    // via the same remap as the row repair. edge_index_endpoints keeps
    // the string-canonical orientation for snapshot derivation.
    edges: FxIndexMap<(usize, usize), AttrMap>,
    runtime_policy: RuntimePolicy,
}

impl Clone for Graph {
    fn clone(&self) -> Self {
        Self {
            mode: self.mode,
            revision: self.revision,
            nodes: self.nodes.clone(),
            adj_indices: self.adj_indices.clone(),
            // Both caches are derived state. A clone must not share a cache:
            // independently mutated copies can reach the same revision with
            // different edge storage orders.
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: self.edge_index_endpoints.clone(),
            edges: self.edges.clone(),
            runtime_policy: self.runtime_policy.clone(),
        }
    }
}

impl Graph {
    #[must_use]
    pub fn new(mode: CompatibilityMode) -> Self {
        Self {
            mode,
            revision: 0,
            nodes: FxIndexMap::default(),
            adj_indices: Vec::new(),
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::new(),
            edges: FxIndexMap::default(),
            runtime_policy: RuntimePolicy::new(mode),
        }
    }

    #[must_use]
    pub fn with_runtime_policy(runtime_policy: RuntimePolicy) -> Self {
        let mode = runtime_policy.mode();
        Self {
            mode,
            revision: 0,
            nodes: FxIndexMap::default(),
            adj_indices: Vec::new(),
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::new(),
            edges: FxIndexMap::default(),
            runtime_policy,
        }
    }

    /// br-r37-c1-clearedgesinplace (cc): drop all edges in place, keeping nodes (and
    /// their index/order/attrs). O(E) teardown + O(V) row clears -- the binding's prior
    /// path rebuilt a fresh Graph with a per-node add_node loop (ledger record_decision
    /// tax + node-attr clone + old-inner drop), ~20x slower than nx. Sibling of
    /// MultiGraph::clear_edges. adj_indices keeps its N rows (one per node), emptied;
    /// the revision bump invalidates all_int_cache.
    pub fn clear_edges(&mut self) {
        if self.edges.is_empty() && self.edge_index_endpoints.is_empty() {
            return;
        }
        self.edges.clear();
        self.edge_index_endpoints.clear();
        for row in &mut self.adj_indices {
            row.clear();
        }
        self.revision = self.revision.saturating_add(1);
    }

    #[must_use]
    pub fn strict() -> Self {
        Self::new(CompatibilityMode::Strict)
    }

    #[must_use]
    pub fn complete_graph(mode: CompatibilityMode, n: usize) -> Self {
        let edge_capacity = n.saturating_mul(n.saturating_sub(1)) / 2;
        let revision = u64::try_from(n)
            .unwrap_or(u64::MAX)
            .saturating_add(u64::try_from(edge_capacity).unwrap_or(u64::MAX));
        let node_labels = (0..n).map(|node| node.to_string()).collect::<Vec<_>>();
        let mut graph = Self {
            mode,
            revision,
            nodes: FxIndexMap::with_capacity_and_hasher(n, rustc_hash::FxBuildHasher),
            adj_indices: vec![Vec::with_capacity(n.saturating_sub(1)); n],
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::with_capacity(edge_capacity),
            edges: FxIndexMap::with_capacity_and_hasher(edge_capacity, rustc_hash::FxBuildHasher),
            runtime_policy: RuntimePolicy::new(mode),
        };

        for node in &node_labels {
            graph.nodes.insert(node.clone(), AttrMap::new());
        }

        for left_index in 0..n {
            let _left = &node_labels[left_index];
            for (right_index, _right) in node_labels.iter().enumerate().skip(left_index + 1) {
                // Maintain integer adjacency
                graph.adj_indices[left_index].push(right_index);
                graph.adj_indices[right_index].push(left_index);
                graph.edge_index_endpoints.push((left_index, right_index));
                graph
                    .edges
                    .insert(Graph::canon_pair(left_index, right_index), AttrMap::new());
            }
        }

        graph.record_decision(
            "complete_graph_bulk",
            0.0,
            false,
            vec![EvidenceTerm {
                signal: "nodes".into(),
                observed_value: count_evidence(n),
                log_likelihood_ratio: 0.0,
            }],
        );
        graph
    }

    /// Build a non-periodic 2-D grid with NetworkX's node and edge insertion
    /// sequence. Canonical node keys are row-major all-int tuple strings like
    /// "(i, j)".
    #[must_use]
    pub fn grid_2d(mode: CompatibilityMode, m: usize, n: usize) -> Self {
        let node_count = m.saturating_mul(n);
        let edge_capacity = m
            .saturating_sub(1)
            .saturating_mul(n)
            .saturating_add(n.saturating_sub(1).saturating_mul(m));
        let revision = u64::try_from(node_count)
            .unwrap_or(u64::MAX)
            .saturating_add(u64::try_from(edge_capacity).unwrap_or(u64::MAX));
        let label = |i: usize, j: usize| format!("({i}, {j})");
        let idx = |i: usize, j: usize| i * n + j;
        let mut graph = Self {
            mode,
            revision,
            nodes: FxIndexMap::with_capacity_and_hasher(node_count, rustc_hash::FxBuildHasher),
            adj_indices: vec![Vec::with_capacity(4); node_count],
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::with_capacity(edge_capacity),
            edges: FxIndexMap::with_capacity_and_hasher(edge_capacity, rustc_hash::FxBuildHasher),
            runtime_policy: RuntimePolicy::new(mode),
        };
        for i in 0..m {
            for j in 0..n {
                let key = label(i, j);
                graph.nodes.insert(key.clone(), AttrMap::new());
            }
        }
        fn add_grid_edge(graph: &mut Graph, _u: String, _v: String, u_idx: usize, v_idx: usize) {
            // add_edge appends v to row[u] first, then u to row[v].
            graph.adj_indices[u_idx].push(v_idx);
            graph.adj_indices[v_idx].push(u_idx);
            graph.edge_index_endpoints.push((u_idx, v_idx));
            graph
                .edges
                .insert(Graph::canon_pair(u_idx, v_idx), AttrMap::new());
        }
        // Phase 1: for (pi, i) in pairwise(rows), for j in cols.
        for i in 1..m {
            for j in 0..n {
                add_grid_edge(
                    &mut graph,
                    label(i, j),
                    label(i - 1, j),
                    idx(i, j),
                    idx(i - 1, j),
                );
            }
        }
        // Phase 2: for i in rows, for (pj, j) in pairwise(cols).
        for i in 0..m {
            for j in 1..n {
                add_grid_edge(
                    &mut graph,
                    label(i, j),
                    label(i, j - 1),
                    idx(i, j),
                    idx(i, j - 1),
                );
            }
        }
        graph.record_decision(
            "grid_2d_bulk",
            0.0,
            false,
            vec![EvidenceTerm {
                signal: "nodes".into(),
                observed_value: count_evidence(node_count),
                log_likelihood_ratio: 0.0,
            }],
        );
        graph
    }

    /// Build NetworkX's n-dimensional integer grid graph in one bulk pass.
    ///
    /// NetworkX constructs this as repeated cartesian products of path/cycle
    /// graphs, then flattens the nested tuple labels. The product order matters:
    /// periodic axes use cycle edge-view order, not a simple coordinate loop.
    pub fn grid_nd(
        mode: CompatibilityMode,
        dimensions: &[usize],
        periodic: &[bool],
    ) -> Result<Self, GraphError> {
        if dimensions.len() != periodic.len() {
            return Err(GraphError::FailClosed {
                operation: "grid_nd",
                reason: format!(
                    "periodic flag count {} does not match dimension count {}",
                    periodic.len(),
                    dimensions.len()
                ),
            });
        }
        if dimensions.is_empty() {
            return Ok(Self::new(mode));
        }

        #[derive(Clone)]
        struct ProductState {
            node_count: usize,
            adjacency: Vec<Vec<usize>>,
            edge_set: HashSet<(usize, usize)>,
        }

        impl ProductState {
            fn empty() -> Self {
                Self {
                    node_count: 0,
                    adjacency: Vec::new(),
                    edge_set: HashSet::new(),
                }
            }

            fn axis(size: usize, periodic: bool) -> Self {
                let mut state = Self {
                    node_count: size,
                    adjacency: vec![Vec::new(); size],
                    edge_set: HashSet::new(),
                };
                if size == 0 {
                    return state;
                }
                if periodic {
                    if size == 1 {
                        state.add_edge(0, 0);
                    } else {
                        for node in 0..(size - 1) {
                            state.add_edge(node, node + 1);
                        }
                        state.add_edge(size - 1, 0);
                    }
                } else {
                    for node in 0..size.saturating_sub(1) {
                        state.add_edge(node, node + 1);
                    }
                }
                state
            }

            fn product(axis: &Self, old: &Self) -> Result<Self, GraphError> {
                let Some(node_count) = axis.node_count.checked_mul(old.node_count) else {
                    return Err(GraphError::FailClosed {
                        operation: "grid_nd",
                        reason: "node count overflow during cartesian product".to_owned(),
                    });
                };
                if node_count == 0 {
                    return Ok(Self::empty());
                }

                let axis_edges = axis.edges_view();
                let old_edges = old.edges_view();
                let mut state = Self {
                    node_count,
                    adjacency: vec![Vec::new(); node_count],
                    edge_set: HashSet::with_capacity(
                        axis_edges
                            .len()
                            .saturating_mul(old.node_count)
                            .saturating_add(old_edges.len().saturating_mul(axis.node_count)),
                    ),
                };

                for (axis_left, axis_right) in axis_edges {
                    let left_base = axis_left * old.node_count;
                    let right_base = axis_right * old.node_count;
                    for old_index in 0..old.node_count {
                        state.add_edge(left_base + old_index, right_base + old_index);
                    }
                }
                for axis_index in 0..axis.node_count {
                    let base = axis_index * old.node_count;
                    for &(old_left, old_right) in &old_edges {
                        state.add_edge(base + old_left, base + old_right);
                    }
                }
                Ok(state)
            }

            fn add_edge(&mut self, left: usize, right: usize) {
                let key = if left <= right {
                    (left, right)
                } else {
                    (right, left)
                };
                if !self.edge_set.insert(key) {
                    return;
                }
                self.adjacency[left].push(right);
                if left != right {
                    self.adjacency[right].push(left);
                }
            }

            fn edges_view(&self) -> Vec<(usize, usize)> {
                let mut edges = Vec::with_capacity(self.edge_set.len());
                let mut seen = vec![false; self.node_count];
                for left in 0..self.node_count {
                    for &right in &self.adjacency[left] {
                        if !seen[right] {
                            edges.push((left, right));
                        }
                    }
                    seen[left] = true;
                }
                edges
            }
        }

        fn coords_from_index(mut index: usize, sizes: &[usize]) -> Vec<usize> {
            let mut coords = vec![0; sizes.len()];
            for axis in (0..sizes.len()).rev() {
                let size = sizes[axis];
                coords[axis] = index % size;
                index /= size;
            }
            coords
        }

        fn tuple_canonical(coords: &[usize]) -> String {
            if let [value] = coords {
                return value.to_string();
            }
            let mut s = String::with_capacity(coords.len() * 6 + 2);
            s.push('(');
            for (i, value) in coords.iter().enumerate() {
                if i > 0 {
                    s.push_str(", ");
                }
                s.push_str(&value.to_string());
            }
            s.push(')');
            s
        }

        let mut state = ProductState::axis(dimensions[0], periodic[0]);
        for (&size, &periodic_axis) in dimensions.iter().zip(periodic).skip(1) {
            let axis = ProductState::axis(size, periodic_axis);
            state = ProductState::product(&axis, &state)?;
        }

        let output_sizes = dimensions.iter().rev().copied().collect::<Vec<_>>();
        let labels = (0..state.node_count)
            .map(|index| tuple_canonical(&coords_from_index(index, &output_sizes)))
            .collect::<Vec<_>>();
        let edge_view = state.edges_view();
        let mut final_adjacency = vec![Vec::new(); state.node_count];
        for &(left, right) in &edge_view {
            final_adjacency[left].push(right);
            if left != right {
                final_adjacency[right].push(left);
            }
        }
        let revision = u64::try_from(state.node_count)
            .unwrap_or(u64::MAX)
            .saturating_add(u64::try_from(edge_view.len()).unwrap_or(u64::MAX));
        let mut graph = Self {
            mode,
            revision,
            nodes: FxIndexMap::with_capacity_and_hasher(
                state.node_count,
                rustc_hash::FxBuildHasher,
            ),
            adj_indices: Vec::with_capacity(state.node_count),
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::with_capacity(edge_view.len()),
            edges: FxIndexMap::with_capacity_and_hasher(edge_view.len(), rustc_hash::FxBuildHasher),
            runtime_policy: RuntimePolicy::new(mode),
        };

        for (index, label) in labels.iter().enumerate() {
            graph.nodes.insert(label.clone(), AttrMap::new());
            graph.adj_indices.push(final_adjacency[index].clone());
        }

        for (left, right) in edge_view {
            graph.edge_index_endpoints.push((left, right));
            graph
                .edges
                .insert(Graph::canon_pair(left, right), AttrMap::new());
        }

        graph.record_decision(
            "grid_nd_bulk",
            0.0,
            false,
            vec![EvidenceTerm {
                signal: "nodes".into(),
                observed_value: count_evidence(state.node_count),
                log_likelihood_ratio: 0.0,
            }],
        );
        Ok(graph)
    }

    /// br-r37-c1-z2eaa: Kneser graph K(n, k) replicating NetworkX's exact
    /// construction sequence. Nodes are k-subsets of 0..n as all-int-tuple
    /// canonicals "(a, b, ...)" (br-r37-c1-y7m24). nx builds via
    /// `add_edges_from((s, t) for s in subsets for t in
    /// combinations(universe - set(s), k))` — node order is edge-DISCOVERY
    /// order (u then v per new edge) and each unordered edge is offered
    /// twice (the second add is a structural no-op). The complement
    /// `universe - set(s)` iterates ASCENDING whenever every value fits its
    /// exact CPython set slot — the Python wrapper gates this kernel on
    /// that condition, so lexicographic combinations over the sorted
    /// complement reproduce nx byte-for-byte. For `2k > n` nodes are
    /// pre-added in subset order and no edges exist.
    #[must_use]
    pub fn kneser(mode: CompatibilityMode, n: usize, k: usize) -> Self {
        fn tuple_canonical(c: &[usize]) -> String {
            let mut s = String::with_capacity(c.len() * 6 + 2);
            s.push('(');
            for (i, v) in c.iter().enumerate() {
                if i > 0 {
                    s.push_str(", ");
                }
                s.push_str(&v.to_string());
            }
            if c.len() == 1 {
                s.push(',');
            }
            s.push(')');
            s
        }
        fn lex_combinations(m: usize, k: usize) -> Vec<Vec<usize>> {
            let mut out = Vec::new();
            if k > m {
                return out;
            }
            let mut cur: Vec<usize> = (0..k).collect();
            loop {
                out.push(cur.clone());
                let mut advanced = false;
                let mut i = k;
                while i > 0 {
                    i -= 1;
                    if cur[i] != i + m - k {
                        cur[i] += 1;
                        for j in (i + 1)..k {
                            cur[j] = cur[j - 1] + 1;
                        }
                        advanced = true;
                        break;
                    }
                }
                if !advanced {
                    break;
                }
            }
            out
        }
        let subsets = lex_combinations(n, k);
        let canonicals: Vec<String> = subsets.iter().map(|c| tuple_canonical(c)).collect();
        let total = subsets.len();
        let mut graph = Self {
            mode,
            revision: u64::try_from(total).unwrap_or(u64::MAX),
            nodes: FxIndexMap::with_capacity_and_hasher(total, rustc_hash::FxBuildHasher),
            adj_indices: Vec::new(),
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: Vec::new(),
            edges: FxIndexMap::default(),
            runtime_policy: RuntimePolicy::new(mode),
        };
        if 2 * k > n {
            // No disjoint pairs exist — nx pre-adds all subsets as nodes.
            for canonical in &canonicals {
                graph.nodes.insert(canonical.clone(), AttrMap::new());
            }
            graph.adj_indices = vec![Vec::new(); total];
            return graph;
        }
        // Binomial table for lexicographic combination ranking.
        let mut binom = vec![vec![0usize; k + 1]; n + 1];
        for i in 0..=n {
            binom[i][0] = 1;
            for j in 1..=k.min(i) {
                binom[i][j] = if i == j {
                    1
                } else {
                    binom[i - 1][j - 1].saturating_add(binom[i - 1][j])
                };
            }
        }
        let lex_rank = |c: &[usize]| -> usize {
            let mut r = 0usize;
            let mut prev = 0usize;
            for (i, &ci) in c.iter().enumerate() {
                for j in prev..ci {
                    r = r.saturating_add(binom[n - 1 - j][k - 1 - i]);
                }
                prev = ci + 1;
            }
            r
        };
        let mut seen = HashSet::<(usize, usize)>::with_capacity(total * 2);
        // node first-touch insertion mirroring nx add_edge (u then v)
        let mut node_idx: Vec<usize> = vec![usize::MAX; total];
        let mut in_s = vec![false; n];
        let m = n - k;
        let picks = lex_combinations(m, k);
        for (s_idx, s) in subsets.iter().enumerate() {
            for &v in s {
                in_s[v] = true;
            }
            let complement: Vec<usize> = (0..n).filter(|&v| !in_s[v]).collect();
            for pick in &picks {
                let t: Vec<usize> = pick.iter().map(|&i| complement[i]).collect();
                let t_idx = lex_rank(&t);
                let pair = (s_idx.min(t_idx), s_idx.max(t_idx));
                if seen.insert(pair) {
                    for idx in [s_idx, t_idx] {
                        if node_idx[idx] == usize::MAX {
                            let entry = graph
                                .nodes
                                .insert_full(canonicals[idx].clone(), AttrMap::new())
                                .0;
                            node_idx[idx] = entry;
                            graph.adj_indices.push(Vec::new());
                        }
                    }
                    // br-r37-c1-kneserpush (cc): we are inside `if seen.insert(pair)` — a FIRST
                    // occurrence of this (s_idx,t_idx) edge — so it is provably not yet in either
                    // adjacency row. The old `!adj_indices[..].contains(..)` guards were O(degree)
                    // linear rescans always returning true here (redundant); push directly.
                    // Byte-identical (Kneser edges have no parallel edges; self-loop s==t handled
                    // by the != guard, exactly as before).
                    graph.adj_indices[node_idx[s_idx]].push(node_idx[t_idx]);
                    if node_idx[s_idx] != node_idx[t_idx] {
                        graph.adj_indices[node_idx[t_idx]].push(node_idx[s_idx]);
                    }
                    graph
                        .edge_index_endpoints
                        .push((node_idx[s_idx], node_idx[t_idx]));
                    graph.edges.insert(
                        Graph::canon_pair(node_idx[s_idx], node_idx[t_idx]),
                        AttrMap::new(),
                    );
                }
            }
            for &v in s {
                in_s[v] = false;
            }
        }
        // adj_indices maintained inline above (P2(c) slice 2).
        graph.revision = u64::try_from(graph.nodes.len() + graph.edges.len()).unwrap_or(u64::MAX);
        graph
    }

    #[must_use]
    pub fn hardened() -> Self {
        Self::new(CompatibilityMode::Hardened)
    }

    #[must_use]
    pub fn mode(&self) -> CompatibilityMode {
        self.mode
    }

    #[must_use]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    #[must_use]
    pub fn revision(&self) -> u64 {
        self.revision
    }

    #[must_use]
    pub fn has_node(&self, node: &str) -> bool {
        self.nodes.contains_key(node)
    }

    /// br-r37-c1-d58s8 edges-map flip: resolve a String pair to the
    /// index-canonical (min, max) key. None if either node is absent.
    #[inline]
    fn edge_pair_key(&self, left: &str, right: &str) -> Option<(usize, usize)> {
        let l = self.nodes.get_index_of(left)?;
        let r = self.nodes.get_index_of(right)?;
        Some(if l <= r { (l, r) } else { (r, l) })
    }

    #[inline]
    fn canon_pair(l: usize, r: usize) -> (usize, usize) {
        if l <= r { (l, r) } else { (r, l) }
    }

    /// br-r37-c1-indsub: build the induced subgraph over `order` (parent node
    /// indices, already in the caller's output order) without hashing a single
    /// node name.
    ///
    /// The per-edge `add_edge_with_attrs` path costs two `String` allocations,
    /// four name hashes and a `record_decision` ledger entry (which itself
    /// allocates two Strings and a Vec) — ~2.5us/edge, so materializing the
    /// 158k-edge k=10 core of ca-AstroPh took 393ms. Everything that loop
    /// re-derives is already known here: the surviving rows come straight out
    /// of `adj_indices`, and the new index of a kept node is its slot in
    /// `order`. All the invariants `add_edge_with_attrs` maintains are
    /// reproduced directly:
    ///
    ///  * `edges` is keyed by the INDEX-canonical pair of the NEW indices;
    ///  * `edge_index_endpoints` keeps the STRING-canonical orientation
    ///    (`left <= right` on names), matching the per-edge path;
    ///  * a row records its neighbor when the pair is first emitted, so
    ///    adjacency order is the walk order — which is exactly what nx's
    ///    `add_edges_from` over the induced walk produces;
    ///  * a self-loop appears once in its row.
    ///
    /// A pair is emitted from whichever endpoint comes FIRST in `order`, so
    /// each undirected edge is visited once. `order` must contain distinct,
    /// in-range parent indices.
    #[must_use]
    pub fn induced_subgraph_ordered(&self, order: &[usize], runtime_policy: RuntimePolicy) -> Self {
        let mut position = vec![usize::MAX; self.nodes.len()];
        for (slot, &parent_idx) in order.iter().enumerate() {
            position[parent_idx] = slot;
        }

        let mut nodes = FxIndexMap::default();
        nodes.reserve(order.len());
        for &parent_idx in order {
            let (name, attrs) = self
                .nodes
                .get_index(parent_idx)
                .expect("induced subgraph order must hold valid parent node indices");
            nodes.insert(name.clone(), attrs.clone());
        }

        let mut adj_indices = vec![Vec::new(); order.len()];
        let mut edges = FxIndexMap::default();
        let mut edge_index_endpoints = Vec::new();
        for (slot, &parent_idx) in order.iter().enumerate() {
            for &parent_neighbor in &self.adj_indices[parent_idx] {
                let other = position[parent_neighbor];
                if other == usize::MAX || other < slot {
                    continue;
                }
                let attrs = self
                    .edges
                    .get(&Self::canon_pair(parent_idx, parent_neighbor))
                    .cloned()
                    .unwrap_or_default();
                edges.insert(Self::canon_pair(slot, other), attrs);
                let left_name = nodes.get_index(slot).expect("slot inserted above").0;
                let right_name = nodes.get_index(other).expect("slot inserted above").0;
                if left_name <= right_name {
                    edge_index_endpoints.push((slot, other));
                } else {
                    edge_index_endpoints.push((other, slot));
                }
                adj_indices[slot].push(other);
                if slot != other {
                    adj_indices[other].push(slot);
                }
            }
        }

        Self {
            mode: runtime_policy.mode(),
            revision: 0,
            nodes,
            adj_indices,
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints,
            edges,
            runtime_policy,
        }
    }

    #[must_use]
    pub fn has_edge(&self, left: &str, right: &str) -> bool {
        self.edge_pair_key(left, right)
            .is_some_and(|k| self.edges.contains_key(&k))
    }

    /// cc-hasedgeintidx: true iff the node stored at `idx` IS the integer `idx`
    /// (its canonical string parses back to `idx`). Lets a caller VERIFY, per call
    /// and with no allocation, that an exact-int node lands at its own index before
    /// probing an edge by index — so any removal / re-add / remap that shifted
    /// indices simply returns false and the caller falls back to the string path.
    /// O(1) index access + a no-alloc `str::parse`.
    #[must_use]
    pub fn node_index_matches_int(&self, idx: usize) -> bool {
        self.nodes
            .get_index(idx)
            .is_some_and(|(k, _)| k.parse::<usize>() == Ok(idx))
    }

    /// cc-hasedgeintidx: undirected edge existence by node INDEX (canonical
    /// min/max pair). Caller must have validated both indices (e.g. via
    /// `node_index_matches_int`).
    #[must_use]
    pub fn has_edge_by_indices(&self, l: usize, r: usize) -> bool {
        self.edges.contains_key(&Self::canon_pair(l, r))
    }

    #[must_use]
    pub fn nodes_ordered(&self) -> Vec<&str> {
        self.nodes.keys().map(String::as_str).collect()
    }

    #[must_use]
    pub fn get_node_index(&self, node: &str) -> Option<usize> {
        self.nodes.get_index_of(node)
    }

    #[must_use]
    pub fn get_node_name(&self, index: usize) -> Option<&str> {
        self.nodes.get_index(index).map(|(k, _)| k.as_str())
    }

    #[must_use]
    pub fn neighbors(&self, node: &str) -> Option<Vec<&str>> {
        // br-r37-c1-d58s8 P2(a): serve from the integer rows + node-name
        // table — adj_indices is order-faithful through every mutator
        // (extends push in row order; remove_node repairs in place;
        // apply_row_orders and reorder_rows_for_nx_copy_walk both
        // resync). Migrating readers off the String rows is the
        // prerequisite for dropping their eager maintenance (P2(c)).
        let idx = self.nodes.get_index_of(node)?;
        Some(
            self.adj_indices[idx]
                .iter()
                .map(|&i| {
                    self.nodes
                        .get_index(i)
                        .expect("adj_indices entries are valid node indices")
                        .0
                        .as_str()
                })
                .collect::<Vec<&str>>(),
        )
    }

    #[must_use]
    pub fn neighbors_iter(&self, node: &str) -> Option<impl Iterator<Item = &str> + '_> {
        // br-r37-c1-d58s8 P2(a): index-backed (see neighbors()).
        let idx = self.nodes.get_index_of(node)?;
        Some(self.adj_indices[idx].iter().map(move |&i| {
            self.nodes
                .get_index(i)
                .expect("adj_indices entries are valid node indices")
                .0
                .as_str()
        }))
    }

    /// Return neighbor indices for O(1) traversal. Avoids string hashing
    /// during BFS/DFS. Returns None if node index is out of bounds.
    #[must_use]
    #[inline]
    pub fn neighbors_indices(&self, node_idx: usize) -> Option<&[usize]> {
        self.adj_indices.get(node_idx).map(Vec::as_slice)
    }

    /// br-r37-c1-7dpyg: structural clone with a FRESH RuntimePolicy —
    /// `Clone` deep-copies the unbounded decision ledger (copy() measured
    /// 2.3-2.8x slower on per-edge-ctor sources with identical structure);
    /// result graphs carry the MODE, not the history.
    #[must_use]
    pub fn clone_with_fresh_policy(&self) -> Self {
        Self {
            mode: self.mode,
            revision: self.revision,
            nodes: self.nodes.clone(),
            adj_indices: self.adj_indices.clone(),
            all_int_cache: std::sync::Arc::default(),
            edge_slots_by_neighbor: std::sync::RwLock::default(),
            edge_index_endpoints: self.edge_index_endpoints.clone(),
            edges: self.edges.clone(),
            runtime_policy: RuntimePolicy::new(self.mode),
        }
    }

    /// br-r37-c1-u3qyn: restore explicit adjacency row orders (pickle
    /// round-trip). Each entry is (node, neighbor order); rows are
    /// rebuilt in the given order with any unlisted survivors appended
    /// in their current order (robust to stale state). The integer
    /// `adj_indices` mirror is rebuilt to match.
    pub fn apply_row_orders(&mut self, orders: &[(String, Vec<String>)]) {
        // br-r37-c1-d58s8 P2(c) slice 2: reorder the integer rows directly.
        let mut changed = false;
        for (node, order) in orders {
            let Some(idx) = self.nodes.get_index_of(node.as_str()) else {
                continue;
            };
            let row = &self.adj_indices[idx];
            let row_set: std::collections::HashSet<usize> = row.iter().copied().collect();
            let mut new_row: Vec<usize> = Vec::with_capacity(row.len());
            let mut placed: std::collections::HashSet<usize> = std::collections::HashSet::new();
            for v in order {
                if let Some(v_idx) = self.nodes.get_index_of(v.as_str())
                    && row_set.contains(&v_idx)
                    && placed.insert(v_idx)
                {
                    new_row.push(v_idx);
                }
            }
            for &v_idx in row {
                if placed.insert(v_idx) {
                    new_row.push(v_idx);
                }
            }
            if self.adj_indices[idx] != new_row {
                self.adj_indices[idx] = new_row;
                changed = true;
            }
        }
        if changed {
            self.revision = self.revision.saturating_add(1);
        }
    }

    /// br-r37-c1-0ek49: reorder every adjacency row into NetworkX's
    /// `Graph.copy()` walk order. nx copy rebuilds via
    /// `add_edges_from((u, v, d) for u in _adj for v in _adj[u])`, so an
    /// unordered pair enters BOTH endpoint rows at its first touch —
    /// during the earlier endpoint's row scan. Row u therefore lists
    /// neighbors at a smaller node position first (ordered by that
    /// neighbor's scan time: `(pos(v), index of u within row v)`),
    /// followed by its remaining neighbors — self-loops included — in
    /// row u's original order. Call on a fresh clone inside copy-shaped
    /// constructors; graph content is unchanged, only row order moves.
    pub fn reorder_rows_for_nx_copy_walk(&mut self) {
        // br-r37-c1-predrebuild: rebuild rows in nx's copy-walk order in O(E),
        // replacing the per-early-neighbor linear search
        // `adj_indices[v].position(|w| w == pu)` (O(E * degree) — quadratic on
        // dense graphs; it erodes dense Graph.copy() wins 9.5x->5.9x as density
        // climbs). Early neighbors of pu (v < pu) sort by
        // (pos(v), index-of-pu-within-adj[v]); walking adj in (v, adj-index)
        // order and appending v to early[pu] when pu > v yields exactly that
        // order. Late neighbors (v >= pu) keep adj[pu]'s row order. Byte-
        // identical row order — no search, no sort.
        let n = self.adj_indices.len();
        let mut early: Vec<Vec<usize>> = vec![Vec::new(); n];
        for (v, row) in self.adj_indices.iter().enumerate() {
            for &pu in row {
                if pu > v {
                    early[pu].push(v);
                }
            }
        }
        let mut new_rows: Vec<Vec<usize>> = Vec::with_capacity(n);
        for (pu, row) in self.adj_indices.iter().enumerate() {
            let mut new_row = std::mem::take(&mut early[pu]);
            new_row.reserve(row.len());
            for &v in row {
                if v >= pu {
                    new_row.push(v);
                }
            }
            new_rows.push(new_row);
        }
        if self.adj_indices != new_rows {
            self.adj_indices = new_rows;
            self.revision = self.revision.saturating_add(1);
        }
    }

    pub fn edges_storage_order_index_iter(
        &self,
    ) -> impl Iterator<Item = (usize, usize, &AttrMap)> + '_ {
        self.edge_index_endpoints
            .iter()
            .copied()
            .zip(self.edges.values())
            .map(|((left, right), attrs)| (left, right, attrs))
    }

    #[must_use]
    pub fn neighbor_count(&self, node: &str) -> usize {
        // br-r37-c1-d58s8 P2(a): index-backed.
        self.nodes
            .get_index_of(node)
            .map_or(0, |idx| self.adj_indices[idx].len())
    }

    /// Return the degree of a node.
    /// Self-loops contribute 2 to the degree (NetworkX convention).
    #[must_use]
    pub fn degree(&self, node: &str) -> usize {
        let count = self.neighbor_count(node);
        // If node has a self-loop, add 1 extra (self-loop contributes 2 total)
        if self.has_edge(node, node) {
            count + 1
        } else {
            count
        }
    }

    /// br-r37-c1-degidx: degree by node INDEX — O(1), zero String
    /// hashing (the &str path costs 2 hashes/node: neighbor_count's
    /// get_index_of + the self-loop has_edge). Used by the DegreeView
    /// iterator which already walks nodes in index order.
    #[must_use]
    pub fn degree_by_index(&self, idx: usize) -> usize {
        // br-r37-c1-degselfloopidx (cc): the self-loop check was `adj_indices[idx].contains(&idx)`
        // — an O(degree) linear rescan of the adjacency row (which for the common no-self-loop node
        // scans the WHOLE row to return false), making this hot per-node accessor O(degree) despite
        // the "O(1)" claim. `has_edge_by_indices(idx, idx)` = `self.edges.contains_key(canon(idx,idx))`
        // is an O(1) HashMap probe deciding the SAME fact (a self-loop edge exists IFF idx is in its
        // own adjacency row — the maintained adj_indices<=>self.edges invariant). Byte-identical.
        let mut count = self.adj_indices[idx].len();
        if self.has_edge_by_indices(idx, idx) {
            count += 1; // self-loop contributes 2 to total degree
        }
        count
    }

    #[must_use]
    pub fn node_attrs(&self, node: &str) -> Option<&AttrMap> {
        self.nodes.get(node)
    }

    #[must_use]
    pub fn edge_attrs(&self, left: &str, right: &str) -> Option<&AttrMap> {
        self.edges.get(&self.edge_pair_key(left, right)?)
    }

    /// br-r37-c1-d58s8: index-keyed attr access — a DIRECT map get for
    /// callers that already hold node indices (kernels, CSR weight
    /// builders, compose walks). Zero node-map probes.
    #[must_use]
    #[inline]
    pub fn edge_attrs_by_indices(&self, left_idx: usize, right_idx: usize) -> Option<&AttrMap> {
        self.edges.get(&Self::canon_pair(left_idx, right_idx))
    }

    /// Read an edge's attributes by a storage slot supplied by the
    /// row-order-preserving edge-slot cache.
    #[must_use]
    #[inline]
    pub fn edge_attrs_by_slot(&self, edge_slot: usize) -> Option<&AttrMap> {
        self.edges.get_index(edge_slot).map(|(_, attrs)| attrs)
    }

    /// Give a reader the edge-storage slot for every entry in every adjacency
    /// row. The first reader after a structural revision resolves pairs once;
    /// steady-state readers avoid pair hashing entirely.
    pub fn with_edge_slots_by_neighbor<T>(&self, f: impl FnOnce(&[Vec<usize>]) -> T) -> T {
        if let Ok(guard) = self.edge_slots_by_neighbor.read()
            && let Some((revision, rows)) = guard.as_ref()
            && *revision == self.revision
        {
            return f(rows);
        }

        let mut guard = self
            .edge_slots_by_neighbor
            .write()
            .expect("edge slot cache lock poisoned");
        if !matches!(guard.as_ref(), Some((revision, _)) if *revision == self.revision) {
            let mut rows = Vec::with_capacity(self.adj_indices.len());
            for (node, neighbors) in self.adj_indices.iter().enumerate() {
                let mut slots = Vec::with_capacity(neighbors.len());
                for &neighbor in neighbors {
                    let slot = self
                        .edges
                        .get_index_of(&Self::canon_pair(node, neighbor))
                        .expect("adjacency entries have matching edge storage");
                    slots.push(slot);
                }
                rows.push(slots);
            }
            *guard = Some((self.revision, rows));
        }
        let (_, rows) = guard
            .as_ref()
            .expect("edge slot cache is initialized before use");
        f(rows)
    }

    /// br-r37-c1-hasattrlazyfix: does ANY edge carry the attribute `key` in the
    /// authoritative Rust storage? Unlike the `edge_py_attrs` Python mirror (which is
    /// LAZILY materialized — a batch-built graph leaves it empty), this scans the inner
    /// `edges` AttrMaps directly (no node-name resolution, no allocation), so a
    /// freshly-constructed weighted graph reports True. ~O(E) BTreeMap key checks.
    #[must_use]
    pub fn any_edge_has_attr(&self, key: &str) -> bool {
        self.edges.values().any(|attrs| attrs.contains_key(key))
    }

    /// True if EVERY inner edge attr value is a faithful scalar (Int/Float/Bool)
    /// — a String/Map value is a coerced non-scalar (repr/JSON) or genuine str,
    /// ambiguous for lossless cloning. Direct no-alloc scan over the edge store
    /// values (contrast `edges_ordered_borrowed`, which builds an O(E) dedup
    /// HashMap). Used by the compose store-read gate.
    #[must_use]
    pub fn all_edge_attr_values_scalar(&self) -> bool {
        self.edges.values().all(|attrs| {
            attrs.values().all(|v| {
                matches!(
                    v,
                    fnx_runtime::CgseValue::Int(_)
                        | fnx_runtime::CgseValue::Float(_)
                        | fnx_runtime::CgseValue::Bool(_)
                )
            })
        })
    }

    /// br-r37-c1-hasanyattrlazyfix: does ANY node carry a Python-visible attr, per the
    /// authoritative inner storage (not the lazy `node_py_attrs` mirror)?
    #[must_use]
    pub fn any_node_has_attrs(&self) -> bool {
        self.nodes.values().any(|attrs| !attrs.is_empty())
    }

    /// br-r37-c1-hasanyattrlazyfix: does ANY edge carry a Python-visible attr, per the
    /// authoritative inner storage (not the lazy `edge_py_attrs` mirror)?
    #[must_use]
    pub fn any_edge_has_attrs(&self) -> bool {
        self.edges.values().any(|attrs| !attrs.is_empty())
    }

    #[must_use]
    pub fn nodes_are_contiguous_int_prefix(&self) -> bool {
        self.nodes
            .keys()
            .enumerate()
            .all(|(index, key)| Self::decimal_key_matches_index(key, index))
    }

    fn decimal_key_matches_index(key: &str, index: usize) -> bool {
        let bytes = key.as_bytes();
        if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
            return false;
        }

        let mut parsed = 0usize;
        for &byte in bytes {
            if !byte.is_ascii_digit() {
                return false;
            }
            let digit = usize::from(byte - b'0');
            let Some(next) = parsed
                .checked_mul(10)
                .and_then(|value| value.checked_add(digit))
            else {
                return false;
            };
            parsed = next;
        }
        parsed == index
    }

    #[must_use]
    pub fn evidence_ledger(&self) -> &EvidenceLedger {
        self.runtime_policy.decision_log()
    }

    pub fn drain_decision_records(&mut self) -> Vec<DecisionRecord> {
        self.runtime_policy.drain_decision_records()
    }

    #[must_use]
    pub fn runtime_policy(&self) -> &RuntimePolicy {
        &self.runtime_policy
    }

    pub fn set_runtime_policy(&mut self, runtime_policy: RuntimePolicy) {
        self.mode = runtime_policy.mode();
        self.runtime_policy = runtime_policy;
    }

    /// Type identity: always `false` for undirected Graph.
    #[must_use]
    pub fn is_directed(&self) -> bool {
        false
    }

    /// Type identity: always `false` for Graph (not a multigraph).
    #[must_use]
    pub fn is_multigraph(&self) -> bool {
        false
    }

    pub fn add_node(&mut self, node: impl AsRef<str> + Into<String>) -> bool {
        self.add_node_with_attrs(node, AttrMap::new())
    }

    /// br-r37-c1-wa1b9: every storage effect of [`Self::add_node_with_attrs`]
    /// and none of its ledger record. Returns `(changed, existed, attrs_count,
    /// inserted_index)` so the caller can file the record itself if it is a
    /// user-visible `add_node`. `inserted_index` is present only for a newly
    /// inserted node, allowing an autocreating caller to reuse the `IndexMap`
    /// index it already paid to assign. Extracted rather than reimplemented so
    /// the recorded and unrecorded paths cannot drift: node insertion ORDER,
    /// the adjacency extension and the revision bump are literally the same
    /// code.
    /// br-r37-c1-jc9e4: the key is materialised only on the VACANT path.
    ///
    /// This used to open with `let node = node.into();`, so a `&str` caller
    /// allocated an owned `String` on every call — including the calls that
    /// insert nothing, where it was built purely to probe the map and then
    /// dropped by `entry` on the occupied branch. The allocation census
    /// measured that as one allocation per endpoint against a `has_node` read
    /// control at zero. Probing borrowed and owning only when the entry is
    /// genuinely new keeps the occupied path allocation-free.
    ///
    /// The raw entry keeps that single borrowed-key hash for a vacant insert,
    /// too. That retains the allocation-free occupied branch and turns the
    /// fresh branch's former lookup-plus-insert pair into one probe.
    fn add_node_with_attrs_unrecorded(
        &mut self,
        node: impl AsRef<str> + Into<String>,
        attrs: AttrMap,
    ) -> (bool, bool, usize, Option<usize>) {
        let node_hash = self.nodes.hasher().hash_one(node.as_ref());
        let (existed, changed, attrs_count, inserted_index) = match self
            .nodes
            .raw_entry_mut_v1()
            .from_key_hashed_nocheck(node_hash, node.as_ref())
        {
            RawEntryMut::Occupied(mut entry) => {
                let bucket = entry.get_mut();
                let changed = !attrs.is_empty()
                    && attrs
                        .iter()
                        .any(|(key, value)| bucket.get(key) != Some(value));
                bucket.extend(attrs);
                (true, changed, bucket.len(), None)
            }
            RawEntryMut::Vacant(entry) => {
                let index = entry.index();
                let (_, bucket) =
                    entry.insert_hashed_nocheck(node_hash, node.into(), AttrMap::new());
                bucket.extend(attrs);
                (false, true, bucket.len(), Some(index))
            }
        };
        // Extend integer adjacency list for new nodes
        if !existed {
            self.adj_indices.push(Vec::new());
        }
        if changed {
            self.revision = self.revision.saturating_add(1);
        }
        (changed, existed, attrs_count, inserted_index)
    }

    /// Resolve an endpoint for `add_edge_with_attrs`, creating an empty node
    /// bucket only when it is absent.
    ///
    /// `add_edge_with_attrs` receives borrowed endpoint names.  Sending a miss
    /// through `get_index_of` and then `add_node_with_attrs_unrecorded` used to
    /// hash that same borrowed name twice: once to discover the miss and once
    /// more for the raw-entry insert.  Keep the no-attribute specialization
    /// here so the edge path can decide and insert from one raw entry while the
    /// general `add_node_with_attrs_unrecorded` path continues to move an owned
    /// caller key into its vacant bucket.
    ///
    /// The storage effects deliberately match an empty-attribute call to
    /// `add_node_with_attrs_unrecorded`: an inserted node appends exactly one
    /// adjacency slot and advances `revision` once; an existing node is a
    /// no-op.  The caller owns the one operation-level ledger record.
    fn resolve_empty_node_for_edge_unrecorded(&mut self, node: &str) -> (usize, bool) {
        let node_hash = self.nodes.hasher().hash_one(node);
        match self
            .nodes
            .raw_entry_mut_v1()
            .from_key_hashed_nocheck(node_hash, node)
        {
            RawEntryMut::Occupied(entry) => (entry.index(), false),
            RawEntryMut::Vacant(entry) => {
                let index = entry.index();
                entry.insert_hashed_nocheck(node_hash, node.to_owned(), AttrMap::new());
                self.adj_indices.push(Vec::new());
                self.revision = self.revision.saturating_add(1);
                (index, true)
            }
        }
    }

    pub fn add_node_with_attrs(
        &mut self,
        node: impl AsRef<str> + Into<String>,
        attrs: AttrMap,
    ) -> bool {
        let (changed, existed, attrs_count, _) = self.add_node_with_attrs_unrecorded(node, attrs);
        self.record_decision(
            "add_node",
            0.0,
            false,
            vec![
                EvidenceTerm {
                    signal: "node_preexisting".into(),
                    observed_value: bool_evidence(existed),
                    log_likelihood_ratio: -3.0,
                },
                EvidenceTerm {
                    signal: "attrs_count".into(),
                    observed_value: count_evidence(attrs_count),
                    log_likelihood_ratio: -1.0,
                },
            ],
        );
        changed
    }

    /// Bulk node insertion for generated/batched construction paths where
    /// per-node compatibility evidence would be pure constant-factor overhead.
    #[must_use]
    pub fn extend_nodes_unrecorded<I, N>(&mut self, nodes: I) -> usize
    where
        I: IntoIterator<Item = N>,
        N: Into<String>,
    {
        let iterator = nodes.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.nodes.reserve(lower_bound);
        self.adj_indices.reserve(lower_bound);

        let mut inserted = 0usize;
        for node in iterator {
            let node = node.into();
            if self.nodes.contains_key(&node) {
                continue;
            }
            self.nodes.insert(node.clone(), AttrMap::new());
            self.adj_indices.push(Vec::new());
            inserted += 1;
        }
        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            self.record_decision(
                "extend_nodes_unrecorded",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "batch_node_count".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: -1.0,
                }],
            );
        }
        inserted
    }

    /// br-r37-c1-l5ve7: bulk node insert WITH attrs, one ledger record —
    /// mirror of DiGraph::extend_nodes_with_attrs_unrecorded. Existing
    /// nodes merge attrs (extend), matching add_node_with_attrs.
    pub fn extend_nodes_with_attrs_unrecorded<I>(&mut self, nodes: I) -> usize
    where
        I: IntoIterator<Item = (String, AttrMap)>,
    {
        let iterator = nodes.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.nodes.reserve(lower_bound);
        self.adj_indices.reserve(lower_bound);

        let mut inserted = 0usize;
        for (node, attrs) in iterator {
            if let Some(existing) = self.nodes.get_mut(&node) {
                existing.extend(attrs);
                continue;
            }
            self.nodes.insert(node.clone(), attrs);
            self.adj_indices.push(Vec::new());
            inserted += 1;
        }
        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            self.record_decision(
                "extend_nodes_with_attrs_unrecorded",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "batch_node_count".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: -1.0,
                }],
            );
        }
        inserted
    }

    pub fn apply_node_defaults(&mut self, defaults: &AttrMap) -> bool {
        if defaults.is_empty() {
            return false;
        }
        let mut inserted = 0usize;
        for attrs in self.nodes.values_mut() {
            for (key, value) in defaults {
                if !attrs.contains_key(key) {
                    attrs.insert(key.clone(), value.clone());
                    inserted += 1;
                }
            }
        }
        if inserted > 0 {
            self.revision = self.revision.saturating_add(1);
            self.record_decision(
                "apply_node_defaults",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "defaults_applied".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: 0.0,
                }],
            );
            return true;
        }
        false
    }

    pub fn add_edge(
        &mut self,
        left: impl AsRef<str>,
        right: impl AsRef<str>,
    ) -> Result<(), GraphError> {
        self.add_edge_with_attrs(left, right, AttrMap::new())
    }

    /// Bulk-add a sequence of attribute-free edges. Bypasses the
    /// per-edge `runtime_policy.record_decision` call that
    /// [`add_edge_with_attrs`] makes. Instead, emit one summary record
    /// for the whole batch.
    ///
    /// Intended for fnx-internal callers that build a fresh graph
    /// from a known-good edge list (e.g., `complement`,
    /// `transitive_closure`, etc.) where the per-edge
    /// incompatibility-probability accounting would just add
    /// constant-factor overhead and is uninteresting for the policy
    /// log.
    ///
    /// Nodes referenced by edges are auto-created if absent
    /// (matching `add_edge` semantics). br-r37-c1-4jd8m.
    #[must_use]
    pub fn extend_edges_unrecorded<I, L, R>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (L, R)>,
        L: Into<String>,
        R: Into<String>,
    {
        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.nodes.reserve(lower_bound);
        self.adj_indices.reserve(lower_bound);
        self.edges.reserve(lower_bound);
        self.edge_index_endpoints.reserve(lower_bound);

        let mut inserted = 0usize;
        let mut nodes_added = false;
        for (left, right) in iterator {
            let left = left.into();
            let right = right.into();
            let left_idx = match self.nodes.get_index_of(&left) {
                Some(index) => index,
                None => {
                    let index = self.nodes.len();
                    self.nodes.insert(left.clone(), AttrMap::new());
                    self.adj_indices.push(Vec::new());
                    nodes_added = true;
                    index
                }
            };
            let right_idx = if left == right {
                left_idx
            } else {
                match self.nodes.get_index_of(&right) {
                    Some(index) => index,
                    None => {
                        let index = self.nodes.len();
                        self.nodes.insert(right.clone(), AttrMap::new());
                        self.adj_indices.push(Vec::new());
                        nodes_added = true;
                        index
                    }
                }
            };
            let edge_key = Self::canon_pair(left_idx, right_idx);
            if self.edges.contains_key(&edge_key) {
                continue;
            }
            if left <= right {
                self.edge_index_endpoints.push((left_idx, right_idx));
            } else {
                self.edge_index_endpoints.push((right_idx, left_idx));
            }
            self.edges.insert(edge_key, AttrMap::new());

            self.adj_indices[left_idx].push(right_idx);
            if left_idx != right_idx {
                self.adj_indices[right_idx].push(left_idx);
            }
            inserted += 1;
        }
        self.record_bulk_edge_summary(inserted, nodes_added);
        inserted
    }

    /// Bulk-add attribute-free edges whose endpoints have already been
    /// resolved to existing node indices. This is the index-space sibling of
    /// [`extend_edges_unrecorded`]: it preserves duplicate handling, adjacency
    /// row order, edge storage order, and string-canonical endpoint orientation
    /// without per-edge node-name allocation or map lookup.
    #[must_use]
    pub fn extend_existing_index_edges_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (usize, usize)>,
    {
        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.edges.reserve(lower_bound);
        self.edge_index_endpoints.reserve(lower_bound);

        let mut inserted = 0usize;
        for (left_idx, right_idx) in iterator {
            debug_assert!(left_idx < self.nodes.len());
            debug_assert!(right_idx < self.nodes.len());

            let edge_key = Self::canon_pair(left_idx, right_idx);
            if self.edges.contains_key(&edge_key) {
                continue;
            }

            let left_name = self
                .nodes
                .get_index(left_idx)
                .expect("validated left node index")
                .0
                .as_str();
            let right_name = self
                .nodes
                .get_index(right_idx)
                .expect("validated right node index")
                .0
                .as_str();
            if left_name <= right_name {
                self.edge_index_endpoints.push((left_idx, right_idx));
            } else {
                self.edge_index_endpoints.push((right_idx, left_idx));
            }
            self.edges.insert(edge_key, AttrMap::new());

            self.adj_indices[left_idx].push(right_idx);
            if left_idx != right_idx {
                self.adj_indices[right_idx].push(left_idx);
            }
            inserted += 1;
        }
        self.record_bulk_edge_summary(inserted, false);
        inserted
    }

    /// br-r37-c1-dodattrbatch: bulk-add ATTRIBUTED edges by EXISTING node index
    /// — the attributed sibling of [`extend_existing_index_edges_unrecorded`].
    /// All endpoints MUST already exist (callers gate on a contiguous-int node
    /// prefix). A new edge takes the given AttrMap; a duplicate edge MERGES
    /// (last-writer-wins per key) exactly like `add_edge_with_attrs`. Replaces
    /// the per-edge ledger with one batch summary; no String hashing for the
    /// endpoints (they arrive as integer indices).
    pub fn extend_existing_index_edges_with_attrs_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (usize, usize, AttrMap)>,
    {
        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.edges.reserve(lower_bound);
        self.edge_index_endpoints.reserve(lower_bound);

        let mut inserted = 0usize;
        for (left_idx, right_idx, attrs) in iterator {
            debug_assert!(left_idx < self.nodes.len());
            debug_assert!(right_idx < self.nodes.len());

            let edge_key = Self::canon_pair(left_idx, right_idx);
            if let Some(existing) = self.edges.get_mut(&edge_key) {
                // Duplicate edge within the batch: merge attrs (last wins).
                for (key, value) in attrs {
                    existing.insert(key, value);
                }
                continue;
            }

            let left_name = self
                .nodes
                .get_index(left_idx)
                .expect("validated left node index")
                .0
                .as_str();
            let right_name = self
                .nodes
                .get_index(right_idx)
                .expect("validated right node index")
                .0
                .as_str();
            if left_name <= right_name {
                self.edge_index_endpoints.push((left_idx, right_idx));
            } else {
                self.edge_index_endpoints.push((right_idx, left_idx));
            }
            self.edges.insert(edge_key, attrs);

            self.adj_indices[left_idx].push(right_idx);
            if left_idx != right_idx {
                self.adj_indices[right_idx].push(left_idx);
            }
            inserted += 1;
        }
        self.record_bulk_edge_summary(inserted, false);
        inserted
    }

    /// br-r37-c1-pr8q6: bulk-add ATTRIBUTED edges without per-edge ledger
    /// records — the attributed sibling of [`extend_edges_unrecorded`].
    ///
    /// Semantics match a sequence of `add_edge_with_attrs` calls exactly:
    /// nodes auto-created in first-appearance order, duplicate edges MERGE
    /// their attrs into the existing map (`extend`), adjacency /
    /// `adj_indices` / `edge_index_endpoints` maintained identically. Only
    /// the per-edge `record_decision` push (timestamp + String allocs per
    /// edge, the dominant cost of attributed bulk construction) is replaced
    /// by one batch summary record.
    ///
    /// Callers MUST pre-screen attr keys starting with
    /// `"__fnx_incompatible"` and route those edges through
    /// `add_edge_with_attrs`, which owns the FailClosed contract for them.
    pub fn extend_edges_with_attrs_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (String, String, AttrMap)>,
    {
        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.nodes.reserve(lower_bound);
        self.adj_indices.reserve(lower_bound);
        self.edges.reserve(lower_bound);
        self.edge_index_endpoints.reserve(lower_bound);

        let mut inserted = 0usize;
        let mut nodes_added = false;
        let mut merged_changed = false;
        for (left, right, attrs) in iterator {
            let left_idx = match self.nodes.get_index_of(&left) {
                Some(index) => index,
                None => {
                    let index = self.nodes.len();
                    self.nodes.insert(left.clone(), AttrMap::new());
                    self.adj_indices.push(Vec::new());
                    nodes_added = true;
                    index
                }
            };
            let right_idx = if left == right {
                left_idx
            } else {
                match self.nodes.get_index_of(&right) {
                    Some(index) => index,
                    None => {
                        let index = self.nodes.len();
                        self.nodes.insert(right.clone(), AttrMap::new());
                        self.adj_indices.push(Vec::new());
                        nodes_added = true;
                        index
                    }
                }
            };
            let edge_key = Self::canon_pair(left_idx, right_idx);
            if let Some(existing) = self.edges.get_mut(&edge_key) {
                // Duplicate edge (pre-existing or earlier in this batch):
                // merge attrs, matching add_edge_with_attrs' `extend`.
                // An empty attr map merges to a no-op; returning early avoids
                // building and dropping a BTreeMap iterator per duplicate edge,
                // which dominates unweighted bulk loads.
                if attrs.is_empty() {
                    continue;
                }
                if attrs
                    .iter()
                    .any(|(key, value)| existing.get(key) != Some(value))
                {
                    merged_changed = true;
                }
                existing.extend(attrs);
                continue;
            }
            if left <= right {
                self.edge_index_endpoints.push((left_idx, right_idx));
            } else {
                self.edge_index_endpoints.push((right_idx, left_idx));
            }
            self.edges.insert(edge_key, attrs);

            self.adj_indices[left_idx].push(right_idx);
            if left_idx != right_idx {
                self.adj_indices[right_idx].push(left_idx);
            }
            inserted += 1;
        }
        if merged_changed {
            // Attr-merge on an existing edge mutates observable state even
            // when no new edge was inserted — bump revision so caches
            // invalidate (over-invalidation is safe; staleness is not).
            self.revision = self.revision.saturating_add(1);
        }
        self.record_bulk_edge_summary(inserted, nodes_added || merged_changed);
        inserted
    }

    /// Bulk-add attributed undirected edges into a fresh graph when the caller
    /// has already assigned NetworkX-compatible node indices in first-seen
    /// order.
    ///
    /// This is the fresh/indexed sibling of
    /// [`extend_edges_with_attrs_unrecorded`]. It preserves duplicate
    /// insert-or-merge semantics, adjacency row order, self-loop handling, and
    /// the public `edges()` orientation rule used by the string-key path.
    #[must_use]
    pub fn extend_fresh_index_edges_with_attrs_unrecorded<I, N>(
        &mut self,
        nodes: N,
        edges: I,
    ) -> usize
    where
        I: IntoIterator<Item = (usize, usize, AttrMap)>,
        N: IntoIterator<Item = String>,
    {
        if !self.nodes.is_empty()
            || !self.adj_indices.is_empty()
            || !self.edges.is_empty()
            || !self.edge_index_endpoints.is_empty()
        {
            return 0;
        }

        let node_labels: Vec<String> = nodes.into_iter().collect();
        self.nodes.reserve(node_labels.len());
        self.adj_indices = vec![Vec::new(); node_labels.len()];
        for node in &node_labels {
            self.nodes.insert(node.clone(), AttrMap::new());
        }

        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.edges.reserve(lower_bound);
        self.edge_index_endpoints.reserve(lower_bound);

        let node_count = node_labels.len();
        let mut inserted = 0usize;
        let mut merged_changed = false;
        for (left_idx, right_idx, attrs) in iterator {
            if left_idx >= node_count || right_idx >= node_count {
                continue;
            }

            let edge_key = Self::canon_pair(left_idx, right_idx);
            if let Some(existing) = self.edges.get_mut(&edge_key) {
                // An empty attr map merges to a no-op; returning early avoids
                // building and dropping a BTreeMap iterator per duplicate edge,
                // which dominates unweighted bulk loads.
                if attrs.is_empty() {
                    continue;
                }
                if attrs
                    .iter()
                    .any(|(key, value)| existing.get(key) != Some(value))
                {
                    merged_changed = true;
                }
                existing.extend(attrs);
                continue;
            }

            if node_labels[left_idx] <= node_labels[right_idx] {
                self.edge_index_endpoints.push((left_idx, right_idx));
            } else {
                self.edge_index_endpoints.push((right_idx, left_idx));
            }
            self.edges.insert(edge_key, attrs);
            self.adj_indices[left_idx].push(right_idx);
            if left_idx != right_idx {
                self.adj_indices[right_idx].push(left_idx);
            }
            inserted += 1;
        }

        self.record_bulk_edge_summary(inserted, node_count > 0 || merged_changed);
        inserted
    }

    fn record_bulk_edge_summary(&mut self, inserted: usize, nodes_added: bool) {
        if inserted == 0 && !nodes_added {
            return;
        }
        self.revision = self
            .revision
            .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
        // One summary record covers the whole batch and keeps the
        // policy ledger non-empty so existing diagnostics still
        // see the operation.
        self.record_decision(
            "extend_edges_unrecorded",
            0.0,
            false,
            vec![EvidenceTerm {
                signal: "batch_edge_count".into(),
                observed_value: count_evidence(inserted),
                log_likelihood_ratio: -1.0,
            }],
        );
    }

    /// br-r37-c1-jc9e4: the endpoint keys are never owned by this function.
    ///
    /// This used to open with `let left = left.into(); let right =
    /// right.into();`, then hand `left.clone()` / `right.clone()` to
    /// autocreation — up to four owned `String`s per call, none of which this
    /// function keeps. Every use below is a comparison, a map probe, or a
    /// forward to `add_node_with_attrs_unrecorded`, and that callee now owns
    /// the key only on the vacant path. So the keys stay borrowed here and the
    /// single allocation an insert genuinely needs happens once, inside the
    /// callee, exactly when a node is created.
    ///
    /// Comparison semantics are unchanged: `left == right` and `left <= right`
    /// on `&str` are the same byte-wise comparisons `String` performed, so the
    /// self-loop test and the `edge_index_endpoints` push order are identical.
    pub fn add_edge_with_attrs(
        &mut self,
        left: impl AsRef<str>,
        right: impl AsRef<str>,
        attrs: AttrMap,
    ) -> Result<(), GraphError> {
        let left = left.as_ref();
        let right = right.as_ref();

        let unknown_feature = attrs
            .keys()
            .any(|key| key.starts_with("__fnx_incompatible"));
        let incompatibility_probability = if unknown_feature {
            1.0
        } else if left == right {
            0.22
        } else {
            0.08
        };

        // br-r37-c1-eo88t: the gate decision earns a ledger record only when it
        // REFUSES. A refusal returns from here, so the outcome record at the end
        // of this function never runs and the gate record is the whole audit
        // trail for the rejected mutation. On the allow path the outcome record
        // carries the same operation/mode/action/incompatibility_probability
        // plus strictly richer evidence, so recording the gate as well wrote two
        // near-identical records for every edge on the hottest mutation path.
        let action = self
            .runtime_policy
            .action_for(incompatibility_probability, unknown_feature);

        if action == DecisionAction::FailClosed || action == DecisionAction::FullValidate {
            self.record_decision(
                "add_edge",
                incompatibility_probability,
                unknown_feature,
                vec![EvidenceTerm {
                    signal: "unknown_incompatible_feature".into(),
                    observed_value: bool_evidence(unknown_feature),
                    log_likelihood_ratio: 12.0,
                }],
            );
            return Err(GraphError::FailClosed {
                operation: "add_edge",
                reason: "incompatible edge metadata".to_owned(),
            });
        }

        // br-r37-c1-wa1b9: autocreating an endpoint is an internal STEP of this
        // add_edge, not a user-visible add_node, so it does not file its own
        // ledger record. The outcome record below already reports the event via
        // `left_autocreated` / `right_autocreated`, so no audit information is
        // lost. This matches the ledger's per-OPERATION contract, which the
        // bulk paths already assert (`extend_nodes_unrecorded` files ONE record
        // for N nodes), and follows br-r37-c1-eo88t, which removed the other
        // redundant record from this same function. A caller-visible
        // `add_node` still records — only this internal path is unrecorded.
        // br-r37-c1-jc9e4: resolve each endpoint with ONE raw-entry probe.
        // A missing endpoint formerly did `get_index_of` followed by
        // `add_node_with_attrs_unrecorded`, which probed the same borrowed key
        // a second time before it could insert.  The specialized resolver
        // returns the existing index or inserts the empty bucket from that
        // single raw entry. A self-loop is resolved without probing the second
        // endpoint at all, since `left == right` makes the indices equal by
        // construction.
        //
        // Order is untouched: the left endpoint is still resolved and
        // autocreated before the right one, and `IndexMap` appends, so
        // autocreating the right endpoint cannot move the left one's index.
        let (left_key_idx, left_autocreated) = self.resolve_empty_node_for_edge_unrecorded(left);
        let (right_key_idx, right_autocreated) = if left == right {
            (left_key_idx, left_autocreated)
        } else {
            self.resolve_empty_node_for_edge_unrecorded(right)
        };
        let edge_key = Self::canon_pair(left_key_idx, right_key_idx);
        let self_loop = left == right;
        // One `entry` probe decides both whether this is a fresh edge and
        // which attribute bucket receives the update.  The former
        // `contains_key` + `entry` sequence hashed the same index pair twice
        // on every add_edge call, including the dominant fresh-edge build arm.
        let (new_edge, changed, edge_attr_count) = match self.edges.entry(edge_key) {
            indexmap::map::Entry::Vacant(entry) => {
                let edge_attr_count = attrs.len();
                entry.insert(attrs);
                (true, true, edge_attr_count)
            }
            indexmap::map::Entry::Occupied(mut entry) => {
                let edge_attrs = entry.get_mut();
                let changed = !attrs.is_empty()
                    && attrs
                        .iter()
                        .any(|(key, value)| edge_attrs.get(key) != Some(value));
                edge_attrs.extend(attrs);
                (false, changed, edge_attrs.len())
            }
        };

        // Update integer adjacency (only for new edges, avoid duplicates)
        if changed {
            // br-r37-c1-jc9e4 (cc): reuse the indices resolved above instead of
            // re-running two String-keyed IndexMap lookups. `left_key_idx` /
            // `right_key_idx` came from the same `self.nodes` a few lines up and
            // nothing between them touches the node map — the intervening work
            // is the `self.edges` entry and the attr extend — so the old
            // `if let (Some(..), Some(..))` could never fail and never differed.
            // Byte-identical: same indices, same push order, same self-loop
            // single-push behaviour.
            if new_edge {
                if left <= right {
                    self.edge_index_endpoints
                        .push((left_key_idx, right_key_idx));
                } else {
                    self.edge_index_endpoints
                        .push((right_key_idx, left_key_idx));
                }
                // br-r37-c1-addedgenewedge (cc): adj_indices membership is EXACTLY edge
                // existence, which `new_edge` (= !self.edges.contains_key(edge_key)) already
                // decided in O(1). The old `!adj_indices[left_idx].contains(&right_idx)` guards
                // were an O(degree) linear rescan of the adjacency row computing the SAME
                // answer — O(n²) to build a star/hub via add_edge. Push only when new_edge
                // (byte-identical: existing edge ⇒ new_edge false ⇒ both endpoints already in
                // adj_indices ⇒ old guards were false too; self-loop ⇒ left_idx==right_idx ⇒
                // single push in both).
                self.adj_indices[left_key_idx].push(right_key_idx);
                if left_key_idx != right_key_idx {
                    self.adj_indices[right_key_idx].push(left_key_idx);
                }
            }
            self.revision = self.revision.saturating_add(1);
        }

        self.record_decision(
            "add_edge",
            incompatibility_probability,
            unknown_feature,
            vec![
                EvidenceTerm {
                    signal: "self_loop".into(),
                    observed_value: bool_evidence(self_loop),
                    log_likelihood_ratio: -0.5,
                },
                EvidenceTerm {
                    signal: "edge_attr_count".into(),
                    observed_value: count_evidence(edge_attr_count),
                    log_likelihood_ratio: -2.0,
                },
                EvidenceTerm {
                    signal: "left_autocreated".into(),
                    observed_value: bool_evidence(left_autocreated),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "right_autocreated".into(),
                    observed_value: bool_evidence(right_autocreated),
                    log_likelihood_ratio: -1.25,
                },
            ],
        );

        Ok(())
    }

    pub fn apply_edge_defaults(&mut self, defaults: &AttrMap) -> bool {
        if defaults.is_empty() {
            return false;
        }
        let mut inserted = 0usize;
        for attrs in self.edges.values_mut() {
            for (key, value) in defaults {
                if !attrs.contains_key(key) {
                    attrs.insert(key.clone(), value.clone());
                    inserted += 1;
                }
            }
        }
        if inserted > 0 {
            self.revision = self.revision.saturating_add(1);
            self.record_decision(
                "apply_edge_defaults",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "defaults_applied".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: 0.0,
                }],
            );
            return true;
        }
        false
    }

    /// br-r37-c1-sjf4t: overwrite the attribute map for an existing edge,
    /// matching post-creation Python-side mutations. Unlike
    /// `add_edge_with_attrs` which extends, this replaces. Returns
    /// `true` if the edge existed and was updated, `false` otherwise.
    pub fn replace_edge_attrs(&mut self, left: &str, right: &str, attrs: AttrMap) -> bool {
        let Some(edge_key) = self.edge_pair_key(left, right) else {
            return false;
        };
        if let Some(slot) = self.edges.get_mut(&edge_key) {
            if *slot != attrs {
                *slot = attrs;
                self.revision = self.revision.saturating_add(1);
            }
            true
        } else {
            false
        }
    }

    /// br-r37-c1-sjf4t: overwrite the attribute map for an existing node.
    pub fn replace_node_attrs(&mut self, node: &str, attrs: AttrMap) -> bool {
        if let Some(slot) = self.nodes.get_mut(node) {
            if *slot != attrs {
                *slot = attrs;
                self.revision = self.revision.saturating_add(1);
            }
            true
        } else {
            false
        }
    }

    pub fn remove_edge(&mut self, left: &str, right: &str) -> bool {
        // `shift_remove_full` returns the edge's index in `self.edges` *before*
        // removal so we can keep `edge_index_endpoints` (maintained strictly
        // parallel to `self.edges`: one entry per edge, same order — see
        // `add_edge_with_attrs` / `extend_edges_unrecorded`) in sync by dropping
        // the single corresponding entry, instead of the O(|E|) hashing
        // `rebuild_edge_index_endpoints()`. Bit-identical result (the parallel
        // vector ends up exactly as a full rebuild would leave it), but turns a
        // remove-heavy build like watts_strogatz from O(|E|^2) into O(|E|·shift).
        let Some(pair) = self.edge_pair_key(left, right) else {
            return false;
        };
        // br-r37-c1-vbwpl: swap_remove (O(1)) instead of shift_remove
        // (O(|E|)) — turns remove-heavy algos (double_edge_swap 188x,
        // watts) from O(k*|E|) into O(k). The edge's slot is filled by
        // the LAST edge; edge_index_endpoints does the SAME swap_remove
        // so the two vectors stay element-parallel. Output is unaffected:
        // edges_ordered() and all user-visible iteration order off
        // ADJACENCY (adj_indices), not edges-map storage order; the only
        // storage-order consumer is the COO matrix builder, where triple
        // order is irrelevant (scipy CSR canonicalises). Edge keys are
        // (node_idx,node_idx) so no key rekey is needed on edge removal.
        let removed = self.edges.swap_remove_full(&pair);
        if let Some((edge_pos, _, _)) = removed {
            // br-r37-c1-d58s8 P2(c) slice 2: integer rows are the single
            // row store — drop the pair entries there.
            if let (Some(left_idx), Some(right_idx)) = (
                self.nodes.get_index_of(left),
                self.nodes.get_index_of(right),
            ) {
                self.adj_indices[left_idx].retain(|&i| i != right_idx);
                if left_idx != right_idx {
                    self.adj_indices[right_idx].retain(|&i| i != left_idx);
                }
            }
            self.edge_index_endpoints.swap_remove(edge_pos);
            self.revision = self.revision.saturating_add(1);
            true
        } else {
            false
        }
    }

    pub fn remove_node(&mut self, node: &str) -> bool {
        let Some(idx) = self.nodes.get_index_of(node) else {
            return false;
        };

        // br-r37-c1-rmnode: incremental index maintenance. The previous version
        // called `rebuild_adj_indices()` + `rebuild_edge_index_endpoints()` —
        // two O(|E|) passes that do a `get_index_of` HashMap lookup for EVERY
        // neighbour of every node and every edge — on EVERY removal, so
        // `remove_node` was O(|V|+|E|)-with-hashing and `remove_nodes_from` was
        // O(k*(|V|+|E|)) (~50x slower than nx). Instead: drop all incident edges
        // in a single O(|E|) retain pass, then repair the integer caches in
        // place (drop dangling refs to the removed index, decrement indices that
        // shifted down) — no hashing, no full rebuild.

        // br-cc-rmnode-fuse: the previous version made ~9 separate O(|E|)
        // passes over the edge storage per removal (keep-mask, edges.retain,
        // endpoints.retain, adj retain, adj decrement, endpoint decrement,
        // full edges rekey). Since the removal ALWAYS rebuilds the edges map
        // (indices > idx shift down when `nodes.shift_remove` renumbers),
        // FUSE incident-drop + index-decrement + rekey into ONE order-
        // preserving rebuild pass, and FUSE the adjacency retain+decrement
        // into one pass per row. Survivor order is untouched (both the old
        // retain and the old rekey preserved insertion order), so
        // `edges_ordered()` — the only observed edge order, walked from the
        // adjacency rows — is byte-identical. Cuts the per-removal edge work
        // from ~9|E| to ~3|E| (the O(|V|+|E|) renumber floor stays; killing
        // it needs stable node ids, see docs/NEGATIVE_EVIDENCE.md).

        // br-r37-c1-qxtlj: the renumber exists because `nodes.shift_remove`
        // moves every position ABOVE `idx` down by one. When `idx` IS the last
        // position there is nothing above it, so no index changes anywhere; and
        // when the node is additionally isolated, no edge references it either.
        // Both of the O(|V|+|E|) repairs below are then provably no-ops over
        // their whole input, and the only real work is dropping two trailing
        // slots.
        //
        // This is not a dent in the compact-index wall - a node in the middle
        // still renumbers, and that floor needs stable ids (see
        // docs/NEGATIVE_EVIDENCE.md). It is the case the wall did not have to
        // cover, and it is the common one: a scratch node added and removed
        // again. Measured before this: removing ONE isolated node from a
        // 12800-node Graph cost 264.86us against networkx's 0.61us (0.0023x),
        // and cost the SAME whether the node sat at the first index or the
        // last - the fast path simply was not there.
        //
        // The isolation test reads the integer adjacency row, which is the same
        // source step 3 below treats as authoritative for incident edges. A
        // self-loop puts `idx` in its own row, so a looped node is non-empty
        // here and takes the general path.
        if idx + 1 == self.nodes.len() && self.adj_indices[idx].is_empty() {
            self.adj_indices.remove(idx);
            self.nodes.shift_remove(node);
            self.revision = self.revision.saturating_add(1);
            return true;
        }

        // 1. Drop the node's own adjacency-index vec (outer Vec shifts to stay
        //    aligned with `nodes` after the shift_remove below).
        self.adj_indices.remove(idx);
        // 2. Remove from the node map (renumbers positions > idx down by 1).
        self.nodes.shift_remove(node);
        // 3. Adjacency repair — ONE pass per row: drop any remaining reference
        //    to the removed index and decrement every index that shifted down.
        for nbrs in &mut self.adj_indices {
            let mut w = 0usize;
            for read in 0..nbrs.len() {
                let e = nbrs[read];
                if e == idx {
                    continue;
                }
                nbrs[w] = if e > idx { e - 1 } else { e };
                w += 1;
            }
            nbrs.truncate(w);
        }
        // 4. Edge storage — ONE fused pass over the element-parallel
        //    (edges, edge_index_endpoints): skip incident edges (either
        //    endpoint index == idx), decrement shifted indices, and rebuild
        //    both containers in the SAME survivor order they had before.
        let old_edges = std::mem::take(&mut self.edges);
        let old_endpoints = std::mem::take(&mut self.edge_index_endpoints);
        let mut new_edges =
            FxIndexMap::with_capacity_and_hasher(old_edges.len(), rustc_hash::FxBuildHasher);
        let mut new_endpoints = Vec::with_capacity(old_endpoints.len());
        for (((l, r), attrs), (le, re)) in old_edges.into_iter().zip(old_endpoints) {
            if le == idx || re == idx {
                continue;
            }
            new_edges.insert(
                (
                    if l > idx { l - 1 } else { l },
                    if r > idx { r - 1 } else { r },
                ),
                attrs,
            );
            new_endpoints.push((
                if le > idx { le - 1 } else { le },
                if re > idx { re - 1 } else { re },
            ));
        }
        self.edges = new_edges;
        self.edge_index_endpoints = new_endpoints;

        self.revision = self.revision.saturating_add(1);
        true
    }

    pub fn remove_nodes_from<'a, I>(&mut self, nodes: I) -> (usize, usize)
    where
        I: IntoIterator<Item = &'a str>,
    {
        let remove_set: HashSet<&str> = nodes
            .into_iter()
            .filter(|node| self.nodes.contains_key(*node))
            .collect();
        if remove_set.is_empty() {
            return (0, 0);
        }

        let old_node_count = self.nodes.len();
        let old_edge_count = self.edges.len();

        // br-r37-c1-d58s8 P2(c) slice 1: integer-side removal. Compute the
        // removed-index mask + old->new remap BEFORE any map shifts, then
        // filter edges via endpoint indices (no String hashing) and
        // rebuild adj_indices through the remap from the OLD integer rows
        // (the old rebuild_adj_indices re-hashed every neighbor String).
        let removed_mask: Vec<bool> = self
            .nodes
            .keys()
            .map(|k| remove_set.contains(k.as_str()))
            .collect();
        let mut remap: Vec<usize> = Vec::with_capacity(old_node_count);
        let mut next = 0usize;
        for &gone in &removed_mask {
            remap.push(next);
            if !gone {
                next += 1;
            }
        }
        let keep_edges: Vec<bool> = self
            .edge_index_endpoints
            .iter()
            .map(|&(l, r)| !removed_mask[l] && !removed_mask[r])
            .collect();

        self.nodes
            .retain(|node, _| !remove_set.contains(node.as_str()));
        let mut i = 0usize;
        self.edges.retain(|_, _| {
            let k = keep_edges[i];
            i += 1;
            k
        });
        let mut j = 0usize;
        self.edge_index_endpoints.retain(|_| {
            let k = keep_edges[j];
            j += 1;
            k
        });
        for endpoints in &mut self.edge_index_endpoints {
            endpoints.0 = remap[endpoints.0];
            endpoints.1 = remap[endpoints.1];
        }
        // br-r37-c1-d58s8 edges-map flip: rekey survivors through the remap.
        self.edges = std::mem::take(&mut self.edges)
            .into_iter()
            .map(|((l, r), attrs)| ((remap[l], remap[r]), attrs))
            .collect();
        let old_rows = std::mem::take(&mut self.adj_indices);
        self.adj_indices = old_rows
            .into_iter()
            .enumerate()
            .filter(|(old_idx, _)| !removed_mask[*old_idx])
            .map(|(_, row)| {
                row.into_iter()
                    .filter(|&nbr| !removed_mask[nbr])
                    .map(|nbr| remap[nbr])
                    .collect()
            })
            .collect();

        let removed_nodes = old_node_count - self.nodes.len();
        let removed_edges = old_edge_count - self.edges.len();
        self.revision = self
            .revision
            .saturating_add(u64::try_from(removed_nodes).unwrap_or(u64::MAX));
        (removed_nodes, removed_edges)
    }

    /// Rebuild integer adjacency from string adjacency. Called after node
    /// removal since indices shift.
    #[allow(dead_code)]
    /// br-r37-c1-d58s8: revision-keyed memo of "every edge's `attr`
    /// value is an integer (missing = default 1 = int)".
    #[must_use]
    pub fn edge_weights_all_int(&self, attr: &str) -> bool {
        if let Ok(guard) = self.all_int_cache.read()
            && let Some((rev, a, v)) = guard.as_ref()
            && *rev == self.revision
            && a == attr
        {
            return *v;
        }
        let v = self
            .edges
            .values()
            .all(|attrs| attrs.get(attr).is_none_or(fnx_runtime::CgseValue::is_int));
        if let Ok(mut guard) = self.all_int_cache.write() {
            *guard = Some((self.revision, attr.to_owned(), v));
        }
        v
    }

    pub fn edges_ordered(&self) -> Vec<EdgeSnapshot> {
        // br-r37-c1-d58s8 P2(b): index-native u-major walk — integer
        // pair dedup + an integer (min,max)->attr map built once from
        // edge_index_endpoints; zero String hashing in the loop. Walk
        // order (u-major over adj_indices rows) is identical to the
        // String-row walk (rows are order-faithful mirrors).
        let node_labels: Vec<&str> = self.nodes.keys().map(|s| s.as_str()).collect();
        let mut ordered = Vec::with_capacity(self.edges.len());
        let mut seen = vec![false; self.nodes.len()];
        for (u, row) in self.adj_indices.iter().enumerate() {
            for &v in row {
                if !seen[v] {
                    let pair = if u <= v { (u, v) } else { (v, u) };
                    if let Some(attrs) = self.edges.get(&pair) {
                        ordered.push(EdgeSnapshot {
                            left: node_labels[u].to_owned(),
                            right: node_labels[v].to_owned(),
                            attrs: attrs.clone(),
                        });
                    }
                }
            }
            seen[u] = true;
        }

        ordered
    }

    #[must_use]
    pub fn edges_ordered_borrowed(&self) -> Vec<(&str, &str, &AttrMap)> {
        // br-r37-c1-d58s8 P2(b): index-native (see edges_ordered).
        let node_labels: Vec<&str> = self.nodes.keys().map(|s| s.as_str()).collect();
        let mut ordered = Vec::with_capacity(self.edges.len());
        let mut seen = vec![false; self.nodes.len()];
        for (u, row) in self.adj_indices.iter().enumerate() {
            for &v in row {
                if !seen[v] {
                    let pair = if u <= v { (u, v) } else { (v, u) };
                    if let Some(attrs) = self.edges.get(&pair) {
                        ordered.push((node_labels[u], node_labels[v], attrs));
                    }
                }
            }
            seen[u] = true;
        }

        ordered
    }

    /// br-r37-c1-wsize (cc): integer `size(weight)` straight from the CgseValue
    /// store. `size(weight)` is `sum(degree(weight))/2`; the `/2` exactly cancels
    /// the double-endpoint counting, so the weighted size equals each stored
    /// edge's weight summed ONCE (a self-loop is one stored edge → counted once,
    /// matching nx's degree-counts-it-twice-then-halves). Each edge appears once
    /// in `self.edges`, so a single store walk is the whole answer — no per-node
    /// PyObject degree materialization. Returns `None` (caller falls back to the
    /// exact float/PyObject degree path) on ANY non-integer weight value; a
    /// missing weight defaults to nx's int `1`. Integer addition is associative,
    /// so iteration order is irrelevant.
    #[must_use]
    pub fn weighted_size_int(&self, weight: &str) -> Option<i128> {
        let mut total: i128 = 0;
        for attrs in self.edges.values() {
            let value = match attrs.get(weight) {
                Some(CgseValue::Int(v)) => i128::from(*v),
                Some(_) => return None,
                None => 1,
            };
            total = total.checked_add(value)?;
        }
        Some(total)
    }

    /// br-r37-c1-2a00r: index-space twin of `edges_ordered_borrowed` — yields
    /// `(u, v)` node indices in the SAME node-major traversed order/orientation,
    /// without resolving endpoints to `&str`. Lets the EdgeView iterate edges and
    /// look up the per-index Python node-key object directly (O(1) incref) instead
    /// of hashing the canonical String per endpoint via `py_node_key`.
    #[must_use]
    pub fn edges_ordered_indices(&self) -> Vec<(usize, usize)> {
        // cc-edgesnodeded: nx's O(N) first-encounter edge dedup — yield (u, v) when
        // v has NOT yet been processed as a source (so each undirected edge emits
        // once, from its earlier-processed endpoint). Replaces the O(E)
        // `HashSet<(usize,usize)>` pair-dedup + `present` membership set that made
        // `list(G.edges())` ~0.57x nx on dense graphs (37k edges = ~150k pair
        // hashes). Same node-major adjacency order and same orientation, so
        // byte-identical. A `vec![bool]` node marker is O(1) per neighbour, no
        // hashing. Falls back to the exact present/seen_pairs rebuild only if the
        // adjacency walk does not reproduce the full edge set (degenerate /
        // inconsistent adjacency), preserving the original contract there.
        let node_count = self.adj_indices.len();
        let mut ordered = Vec::with_capacity(self.edges.len());
        let mut seen_source = vec![false; node_count];
        for (u, row) in self.adj_indices.iter().enumerate() {
            for &v in row {
                if !seen_source[v] {
                    ordered.push((u, v));
                }
            }
            seen_source[u] = true;
        }
        if ordered.len() == self.edges.len() {
            return ordered;
        }
        // Fallback (degenerate adjacency): the exact present/seen_pairs rebuild.
        let mut present: HashSet<(usize, usize)> = HashSet::with_capacity(self.edges.len());
        for &(l, r) in &self.edge_index_endpoints {
            present.insert(if l <= r { (l, r) } else { (r, l) });
        }
        let mut ordered = Vec::with_capacity(self.edges.len());
        let mut seen_pairs = HashSet::<(usize, usize)>::with_capacity(self.edges.len());
        for (u, row) in self.adj_indices.iter().enumerate() {
            for &v in row {
                let pair = if u <= v { (u, v) } else { (v, u) };
                if !seen_pairs.insert(pair) {
                    continue;
                }
                if present.contains(&pair) {
                    ordered.push((u, v));
                }
            }
        }
        if ordered.len() < self.edges.len() {
            // Mirror edges_ordered_borrowed's fallback EXACTLY: iterate
            // self.edges with the raw (l, r) key orientation and dedup on the
            // raw key (not (min,max)) so degenerate cases stay byte-identical.
            for &(l, r) in self.edges.keys() {
                if seen_pairs.insert((l, r)) {
                    ordered.push((l, r));
                }
            }
        }
        ordered
    }

    #[must_use]
    pub fn edges_storage_order_borrowed(&self) -> Vec<(&str, &str, &AttrMap)> {
        // orientation from edge_index_endpoints (string-canonical, kept
        // element-parallel with edges).
        self.edge_index_endpoints
            .iter()
            .zip(self.edges.values())
            .map(|(&(l, r), attrs)| {
                (
                    self.nodes.get_index(l).expect("valid index").0.as_str(),
                    self.nodes.get_index(r).expect("valid index").0.as_str(),
                    attrs,
                )
            })
            .collect()
    }

    pub fn edges_storage_order_iter(&self) -> impl Iterator<Item = (&str, &str, &AttrMap)> + '_ {
        self.edge_index_endpoints
            .iter()
            .zip(self.edges.values())
            .map(|(&(l, r), attrs)| {
                (
                    self.nodes.get_index(l).expect("valid index").0.as_str(),
                    self.nodes.get_index(r).expect("valid index").0.as_str(),
                    attrs,
                )
            })
    }

    #[must_use]
    pub fn snapshot(&self) -> GraphSnapshot {
        // br-snapnodeattrs: preserve per-node attributes alongside the
        // bare node name list so callers replaying a snapshot don't lose
        // ``add_node(n, attrs)`` data.
        let node_attrs: BTreeMap<String, AttrMap> = self
            .nodes
            .iter()
            .filter(|(_, attrs)| !attrs.is_empty())
            .map(|(name, attrs)| (name.clone(), attrs.clone()))
            .collect();
        GraphSnapshot {
            mode: self.mode,
            nodes: self.nodes.keys().cloned().collect(),
            node_attrs,
            edges: self.edges_ordered(),
        }
    }

    fn record_decision(
        &mut self,
        operation: &'static str,
        incompatibility_probability: f64,
        unknown_incompatible_feature: bool,
        evidence: Vec<EvidenceTerm>,
    ) -> DecisionAction {
        let action = self
            .runtime_policy
            .action_for(incompatibility_probability, unknown_incompatible_feature);
        self.runtime_policy.record(
            operation,
            action,
            incompatibility_probability,
            "argmin expected loss over {allow,full_validate,fail_closed}",
            evidence,
        );
        action
    }
}

/// br-r37-c1-thp6w slice 1: revision-keyed integer-adjacency memo for MultiGraph. Holds the
/// integer neighbor rows (`get_node_index` of each adjacency-row neighbor, in row order),
/// lazily built from the authoritative stable-slot rows and reused until the graph mutates.
/// Interior mutability (RwLock) so it can populate on a `&self` read while staying `Sync`,
/// matching `Graph::all_int_cache`. Clone yields a FRESH (empty) memo — never shared — so a
/// clone that mutates independently can never serve another graph's rows.
#[derive(Debug, Default)]
struct IntAdjCache(std::sync::RwLock<Option<(u64, Vec<Vec<usize>>)>>);

impl Clone for IntAdjCache {
    fn clone(&self) -> Self {
        Self::default()
    }
}

/// br-r37-c1-thp6w S4: the structural row delta of one single-edge MultiGraph
/// mutation, used by `advance_int_adj_memo` to keep a warm integer-adjacency
/// memo live across the mutation instead of invalidating it.
enum IntAdjEdgeDelta<'a> {
    Add {
        left: &'a str,
        right: &'a str,
        left_new: bool,
        right_new: bool,
        pair_new: bool,
    },
    Remove {
        left: &'a str,
        right: &'a str,
        pair_gone: bool,
    },
}

/// Stable-slot storage for `MultiGraph`. Test-only positional prototypes stay
/// alongside it as parity and benchmark comparators for the storage cutover.
mod multigraph_storage {
    use super::{AttrMap, CompatibilityMode, MultiEdgeSnapshot, MultiGraphSnapshot};
    use indexmap::{IndexMap, IndexSet};

    /// Index-keyed analog of the MultiGraph storage core. Internal pair
    /// canonicalization is (min_idx, max_idx) — deliberately DIFFERENT from
    /// the String-lex `EdgeKey` canonical ("10" < "2" lex, 2 < 10 numeric) —
    /// because pair-key orientation is never observable: every public
    /// ordering derives from the rows walk + per-cell key sets, which the
    /// parity gates pin byte-for-byte.
    #[cfg(test)]
    #[derive(Debug, Default)]
    pub struct MgIntStorageProto {
        /// Node names in insertion order (the surviving String table).
        pub node_names: Vec<String>,
        /// name -> index resolution (the `nodes` map analog).
        pub node_index: IndexMap<String, usize, rustc_hash::FxBuildHasher>,
        /// node idx -> distinct-neighbor idx -> parallel-edge key set,
        /// insertion-ordered exactly like the String rows.
        pub rows: Vec<IndexMap<usize, IndexSet<usize>>>,
        /// (min_idx, max_idx) -> key -> attrs.
        pub edges: IndexMap<(usize, usize), IndexMap<usize, AttrMap>, rustc_hash::FxBuildHasher>,
        pub edge_count: usize,
    }

    #[cfg(test)]
    impl MgIntStorageProto {
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        fn ensure_node(&mut self, name: &str) -> usize {
            if let Some(&idx) = self.node_index.get(name) {
                return idx;
            }
            let idx = self.node_names.len();
            self.node_names.push(name.to_owned());
            self.node_index.insert(name.to_owned(), idx);
            self.rows.push(IndexMap::new());
            idx
        }

        /// Mirror of `MultiGraph::extend_keyed_edges_with_attrs_unrecorded`'s
        /// per-edge storage ops: endpoint nodes created on demand, an existing
        /// (pair, key) cell merges attrs, new cells count toward `edge_count`.
        pub fn add_keyed_edge(&mut self, left: &str, right: &str, key: usize, attrs: AttrMap) {
            let l = self.ensure_node(left);
            let r = if left == right {
                l
            } else {
                self.ensure_node(right)
            };
            let pair = (l.min(r), l.max(r));
            let bucket = self.edges.entry(pair).or_default();
            if !bucket.contains_key(&key) {
                self.edge_count += 1;
            }
            bucket.entry(key).or_default().extend(attrs);
            self.rows[l].entry(r).or_default().insert(key);
            if l != r {
                self.rows[r].entry(l).or_default().insert(key);
            }
        }

        /// Mirror of `MultiGraph::extend_fresh_int_prefix_keyed_edges_unrecorded`
        /// for the A/B: same node-name String table build (fairness — the name
        /// table survives the flip), then pure index-keyed edge inserts with no
        /// String clone/hash per edge.
        #[must_use]
        pub fn bulk_load_int_prefix<I>(node_count: usize, edges: I) -> Self
        where
            I: IntoIterator<Item = (usize, usize, usize)>,
        {
            let iterator = edges.into_iter();
            let (lower_bound, _) = iterator.size_hint();
            let mut proto = Self::new();
            proto.node_names.reserve(node_count);
            proto.node_index.reserve(node_count);
            proto.rows.reserve(node_count);
            proto.edges.reserve(lower_bound);
            for node in 0..node_count {
                let name = node.to_string();
                proto.node_names.push(name.clone());
                proto.node_index.insert(name, node);
                proto.rows.push(IndexMap::new());
            }
            for (left_idx, right_idx, key) in iterator {
                debug_assert!(left_idx < node_count);
                debug_assert!(right_idx < node_count);
                let pair = (left_idx.min(right_idx), left_idx.max(right_idx));
                proto
                    .edges
                    .entry(pair)
                    .or_default()
                    .insert(key, AttrMap::new());
                proto.rows[left_idx]
                    .entry(right_idx)
                    .or_default()
                    .insert(key);
                if left_idx != right_idx {
                    proto.rows[right_idx]
                        .entry(left_idx)
                        .or_default()
                        .insert(key);
                }
                proto.edge_count += 1;
            }
            proto
        }

        /// Distinct neighbors of node `i` as names, in row order.
        #[must_use]
        pub fn neighbor_names(&self, i: usize) -> Vec<&str> {
            self.rows[i]
                .keys()
                .map(|&j| self.node_names[j].as_str())
                .collect()
        }

        /// Parallel-edge key order for the (left, right) pair, `edge_keys_vec` analog.
        #[must_use]
        pub fn key_order(&self, left: &str, right: &str) -> Vec<usize> {
            let (Some(&l), Some(&r)) = (self.node_index.get(left), self.node_index.get(right))
            else {
                return Vec::new();
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(|bucket| bucket.keys().copied().collect())
                .unwrap_or_default()
        }

        /// br-r37-c1-thp6w S7: mirror of `MultiGraph::remove_edge` on the
        /// index layout — `key=None` picks the LAST bucket key (`next_back`),
        /// the surviving bucket keeps its key order (shift semantics), an
        /// emptied pair drops from the outer edges map (order unobservable)
        /// and shift-removes the neighbor cell from both rows.
        pub fn remove_edge(&mut self, left: &str, right: &str, key: Option<usize>) -> bool {
            let (Some(&l), Some(&r)) = (self.node_index.get(left), self.node_index.get(right))
            else {
                return false;
            };
            let pair = (l.min(r), l.max(r));
            let Some(bucket) = self.edges.get_mut(&pair) else {
                return false;
            };
            let Some(removal_key) = key.or_else(|| bucket.keys().next_back().copied()) else {
                return false;
            };
            if bucket.shift_remove(&removal_key).is_none() {
                return false;
            }
            self.edge_count -= 1;
            let pair_gone = bucket.is_empty();
            if pair_gone {
                self.edges.swap_remove(&pair);
            }
            let mut drop_cell = |u: usize, v: usize| {
                let mut cell_empty = false;
                if let Some(keys) = self.rows[u].get_mut(&v) {
                    keys.shift_remove(&removal_key);
                    cell_empty = keys.is_empty();
                }
                if cell_empty {
                    self.rows[u].shift_remove(&v);
                }
            };
            drop_cell(l, r);
            if l != r {
                drop_cell(r, l);
            }
            true
        }

        /// br-r37-c1-thp6w S7: mirror of `MultiGraph::remove_node` under the
        /// index layout — the d58s8-pattern fused renumber (Graph::remove_node
        /// template): drop the node's row, decrement every surviving index
        /// above it in one order-preserving pass per row, rebuild the edges
        /// map order-preserving with incident pairs skipped and both pair
        /// members decremented (order within the pair is preserved by a
        /// uniform decrement, so the index-canonical invariant survives).
        pub fn remove_node(&mut self, name: &str) -> bool {
            let Some(&idx) = self.node_index.get(name) else {
                return false;
            };
            self.node_names.remove(idx);
            self.node_index.shift_remove(name);
            for stored in self.node_index.values_mut() {
                if *stored > idx {
                    *stored -= 1;
                }
            }
            self.rows.remove(idx);
            for row in &mut self.rows {
                let old = std::mem::take(row);
                for (j, keys) in old {
                    if j == idx {
                        continue;
                    }
                    row.insert(if j > idx { j - 1 } else { j }, keys);
                }
            }
            let old_edges = std::mem::take(&mut self.edges);
            let mut removed_cells = 0usize;
            for ((a, b), bucket) in old_edges {
                if a == idx || b == idx {
                    removed_cells += bucket.len();
                    continue;
                }
                self.edges.insert(
                    (
                        if a > idx { a - 1 } else { a },
                        if b > idx { b - 1 } else { b },
                    ),
                    bucket,
                );
            }
            self.edge_count -= removed_cells;
            true
        }
    }

    /// br-r37-c1-thp6w S6: singleton-optimized parallel-key cell. The
    /// insertion-ordered set semantics of `IndexSet<usize>` are preserved
    /// exactly (dedup on insert, One -> Many promotion appends), but the
    /// singleton case — the overwhelmingly common one in real multigraphs —
    /// allocates NOTHING.
    #[derive(Debug, Clone)]
    pub enum CompactKeys {
        One(usize),
        Many(IndexSet<usize>),
    }

    impl CompactKeys {
        /// Set-insert preserving insertion order; returns true if newly added.
        pub fn insert(&mut self, key: usize) -> bool {
            match self {
                Self::One(existing) => {
                    if *existing == key {
                        return false;
                    }
                    let mut set = IndexSet::with_capacity(2);
                    set.insert(*existing);
                    set.insert(key);
                    *self = Self::Many(set);
                    true
                }
                Self::Many(set) => set.insert(key),
            }
        }

        #[cfg(test)]
        #[must_use]
        pub fn order(&self) -> Vec<usize> {
            match self {
                Self::One(key) => vec![*key],
                Self::Many(set) => set.iter().copied().collect(),
            }
        }

        /// br-r37-c1-thp6w S27: number of parallel keys (never zero — a cell is
        /// dropped wholesale when its last key is removed).
        #[must_use]
        pub fn len(&self) -> usize {
            match self {
                Self::One(_) => 1,
                Self::Many(set) => set.len(),
            }
        }

        /// br-r37-c1-thp6w S9: order-preserving key removal; returns
        /// (removed, cell_now_empty). A `Many` that shrinks to one entry stays
        /// `Many` — only iteration order is observable, not the variant.
        pub fn shift_remove(&mut self, key: usize) -> (bool, bool) {
            match self {
                Self::One(existing) => {
                    let removed = *existing == key;
                    (removed, removed)
                }
                Self::Many(set) => {
                    let removed = set.shift_remove(&key);
                    (removed, set.is_empty())
                }
            }
        }
    }

    /// br-r37-c1-thp6w S6: singleton-optimized (pair -> key -> attrs) bucket,
    /// insertion-key-ordered like `IndexMap<usize, AttrMap>`; the singleton
    /// case stores the key + attrs inline with no map allocation (an empty
    /// `AttrMap`/BTreeMap does not allocate).
    #[derive(Debug, Clone)]
    pub enum CompactBucket {
        One(usize, AttrMap),
        Many(IndexMap<usize, AttrMap>),
    }

    impl CompactBucket {
        /// `entry(key).or_default().extend(attrs)` analog; returns true if the
        /// (key) cell is new.
        pub fn merge(&mut self, key: usize, attrs: AttrMap) -> bool {
            match self {
                Self::One(existing, existing_attrs) => {
                    if *existing == key {
                        existing_attrs.extend(attrs);
                        return false;
                    }
                    let mut map = IndexMap::with_capacity(2);
                    map.insert(*existing, std::mem::take(existing_attrs));
                    map.insert(key, attrs);
                    *self = Self::Many(map);
                    true
                }
                Self::Many(map) => {
                    let is_new = !map.contains_key(&key);
                    map.entry(key).or_default().extend(attrs);
                    is_new
                }
            }
        }

        #[must_use]
        pub fn key_order(&self) -> Vec<usize> {
            match self {
                Self::One(key, _) => vec![*key],
                Self::Many(map) => map.keys().copied().collect(),
            }
        }

        #[must_use]
        pub fn attrs_for(&self, key: usize) -> Option<&AttrMap> {
            match self {
                Self::One(existing, attrs) => (*existing == key).then_some(attrs),
                Self::Many(map) => map.get(&key),
            }
        }

        #[must_use]
        pub fn contains_key(&self, key: usize) -> bool {
            self.attrs_for(key).is_some()
        }

        /// br-r37-c1-thp6w S22: OVERWRITE the attr map for an existing key
        /// (`merge` extends; this replaces). Returns true if the key was
        /// present. Mirror of one cell of `MultiGraph::replace_edge_attrs`.
        pub fn replace_attrs(&mut self, key: usize, attrs: AttrMap) -> bool {
            match self {
                Self::One(existing, existing_attrs) => {
                    if *existing == key {
                        *existing_attrs = attrs;
                        true
                    } else {
                        false
                    }
                }
                Self::Many(map) => {
                    if let Some(slot) = map.get_mut(&key) {
                        *slot = attrs;
                        true
                    } else {
                        false
                    }
                }
            }
        }

        /// br-r37-c1-thp6w S9: number of parallel keys in the bucket.
        #[must_use]
        pub fn len(&self) -> usize {
            match self {
                Self::One(..) => 1,
                Self::Many(map) => map.len(),
            }
        }

        #[must_use]
        pub fn is_empty(&self) -> bool {
            self.len() == 0
        }

        /// br-r37-c1-thp6w S9: the LAST key in insertion order (the real
        /// `remove_edge(key=None)` default via `next_back`).
        #[must_use]
        pub fn last_key(&self) -> Option<usize> {
            match self {
                Self::One(key, _) => Some(*key),
                Self::Many(map) => map.keys().next_back().copied(),
            }
        }

        /// br-r37-c1-thp6w S9: order-preserving key removal; returns
        /// (removed, bucket_now_empty).
        pub fn shift_remove(&mut self, key: usize) -> (bool, bool) {
            match self {
                Self::One(existing, _) => {
                    let removed = *existing == key;
                    (removed, removed)
                }
                Self::Many(map) => {
                    let removed = map.shift_remove(&key).is_some();
                    (removed, map.is_empty())
                }
            }
        }

        /// br-r37-c1-thp6w S12: key-ordered (key, attrs) iteration without a
        /// per-bucket allocation (read-path hot loop).
        pub fn iter(&self) -> CompactBucketIter<'_> {
            match self {
                Self::One(key, attrs) => CompactBucketIter::One(std::iter::once((*key, attrs))),
                Self::Many(map) => CompactBucketIter::Many(map.iter()),
            }
        }

        /// br-r37-c1-thp6w S33: zero-alloc parallel-key iterator yielding
        /// `&usize`, matching the String adjacency `IndexSet<usize>::iter` that
        /// backs `edge_keys_iter`.
        pub fn keys(&self) -> CompactBucketKeys<'_> {
            match self {
                Self::One(key, _) => CompactBucketKeys::One(Some(key)),
                Self::Many(map) => CompactBucketKeys::Many(map.keys()),
            }
        }

        pub fn values(&self) -> CompactBucketValues<'_> {
            match self {
                Self::One(_, attrs) => CompactBucketValues::One(Some(attrs)),
                Self::Many(map) => CompactBucketValues::Many(map.values()),
            }
        }
    }

    /// br-r37-c1-thp6w S12: enum iterator for `CompactBucket::iter` (no Box,
    /// no per-bucket allocation).
    pub enum CompactBucketIter<'a> {
        One(std::iter::Once<(usize, &'a AttrMap)>),
        Many(indexmap::map::Iter<'a, usize, AttrMap>),
    }

    impl<'a> Iterator for CompactBucketIter<'a> {
        type Item = (usize, &'a AttrMap);

        fn next(&mut self) -> Option<Self::Item> {
            match self {
                Self::One(it) => it.next(),
                Self::Many(it) => it.next().map(|(key, attrs)| (*key, attrs)),
            }
        }
    }

    /// br-r37-c1-thp6w S33: zero-alloc `&usize` parallel-key iterator over a
    /// `CompactBucket` (One = the single key once, Many = the map's keys),
    /// matching `IndexSet<usize>::Iter` so `edge_keys_iter` keeps `Item=&usize`.
    pub enum CompactBucketKeys<'a> {
        One(Option<&'a usize>),
        Many(indexmap::map::Keys<'a, usize, AttrMap>),
    }

    impl<'a> Iterator for CompactBucketKeys<'a> {
        type Item = &'a usize;

        fn next(&mut self) -> Option<Self::Item> {
            match self {
                Self::One(opt) => opt.take(),
                Self::Many(keys) => keys.next(),
            }
        }
    }

    pub enum CompactBucketValues<'a> {
        One(Option<&'a AttrMap>),
        Many(indexmap::map::Values<'a, usize, AttrMap>),
    }

    impl<'a> Iterator for CompactBucketValues<'a> {
        type Item = &'a AttrMap;

        fn next(&mut self) -> Option<Self::Item> {
            match self {
                Self::One(opt) => opt.take(),
                Self::Many(values) => values.next(),
            }
        }
    }

    /// br-r37-c1-thp6w S6: the compact-bucket variant of the index-keyed
    /// layout — identical structure to `MgIntStorageProto` except both nested
    /// bucket levels use the singleton-optimized enums, so a simple-graph-like
    /// multigraph (no parallel edges) performs ZERO per-pair bucket
    /// allocations.
    #[cfg(test)]
    #[derive(Debug, Default)]
    pub struct MgIntStorageProtoCompact {
        pub node_names: Vec<String>,
        pub node_index: IndexMap<String, usize, rustc_hash::FxBuildHasher>,
        pub rows: Vec<IndexMap<usize, CompactKeys>>,
        pub edges: IndexMap<(usize, usize), CompactBucket, rustc_hash::FxBuildHasher>,
        pub edge_count: usize,
    }

    #[cfg(test)]
    impl MgIntStorageProtoCompact {
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        fn ensure_node(&mut self, name: &str) -> usize {
            if let Some(&idx) = self.node_index.get(name) {
                return idx;
            }
            let idx = self.node_names.len();
            self.node_names.push(name.to_owned());
            self.node_index.insert(name.to_owned(), idx);
            self.rows.push(IndexMap::new());
            idx
        }

        /// Mirror of `MgIntStorageProto::add_keyed_edge` on compact buckets.
        pub fn add_keyed_edge(
            &mut self,
            left: &str,
            right: &str,
            key: usize,
            attrs: AttrMap,
        ) -> bool {
            let l = self.ensure_node(left);
            let r = if left == right {
                l
            } else {
                self.ensure_node(right)
            };
            let pair = (l.min(r), l.max(r));
            let is_new = match self.edges.entry(pair) {
                indexmap::map::Entry::Occupied(mut bucket) => bucket.get_mut().merge(key, attrs),
                indexmap::map::Entry::Vacant(slot) => {
                    slot.insert(CompactBucket::One(key, attrs));
                    true
                }
            };
            if is_new {
                self.edge_count += 1;
            }
            match self.rows[l].entry(r) {
                indexmap::map::Entry::Occupied(mut cell) => {
                    let _ = cell.get_mut().insert(key);
                }
                indexmap::map::Entry::Vacant(slot) => {
                    slot.insert(CompactKeys::One(key));
                }
            }
            if l != r {
                match self.rows[r].entry(l) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
            }
            is_new
        }

        /// Mirror of `MgIntStorageProto::bulk_load_int_prefix` on compact buckets.
        #[cfg(test)]
        #[must_use]
        pub fn bulk_load_int_prefix<I>(node_count: usize, edges: I) -> Self
        where
            I: IntoIterator<Item = (usize, usize, usize)>,
        {
            let iterator = edges.into_iter();
            let (lower_bound, _) = iterator.size_hint();
            let mut proto = Self::new();
            proto.node_names.reserve(node_count);
            proto.node_index.reserve(node_count);
            proto.rows.reserve(node_count);
            proto.edges.reserve(lower_bound);
            for node in 0..node_count {
                let name = node.to_string();
                proto.node_names.push(name.clone());
                proto.node_index.insert(name, node);
                proto.rows.push(IndexMap::new());
            }
            for (left_idx, right_idx, key) in iterator {
                debug_assert!(left_idx < node_count);
                debug_assert!(right_idx < node_count);
                let pair = (left_idx.min(right_idx), left_idx.max(right_idx));
                match proto.edges.entry(pair) {
                    indexmap::map::Entry::Occupied(mut bucket) => {
                        let _ = bucket.get_mut().merge(key, AttrMap::new());
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactBucket::One(key, AttrMap::new()));
                    }
                }
                match proto.rows[left_idx].entry(right_idx) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
                if left_idx != right_idx {
                    match proto.rows[right_idx].entry(left_idx) {
                        indexmap::map::Entry::Occupied(mut cell) => {
                            let _ = cell.get_mut().insert(key);
                        }
                        indexmap::map::Entry::Vacant(slot) => {
                            slot.insert(CompactKeys::One(key));
                        }
                    }
                }
                proto.edge_count += 1;
            }
            proto
        }

        /// Distinct neighbors of node `i` as names, in row order.
        #[must_use]
        pub fn neighbor_names(&self, i: usize) -> Vec<&str> {
            self.rows[i]
                .keys()
                .map(|&j| self.node_names[j].as_str())
                .collect()
        }

        /// Parallel-edge key order for the (left, right) pair.
        #[must_use]
        pub fn key_order(&self, left: &str, right: &str) -> Vec<usize> {
            let (Some(&l), Some(&r)) = (self.node_index.get(left), self.node_index.get(right))
            else {
                return Vec::new();
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(CompactBucket::key_order)
                .unwrap_or_default()
        }
    }

    /// br-r37-c1-thp6w S9: the slab/stable-slot layout MANDATED by the S8
    /// removal A/B (positional renumber measured 190-203x slower than the
    /// String store). Node identity = a STABLE SLOT that never renumbers;
    /// removal tombstones the slot (free-list reuse) and shift-removes only
    /// the order entry, so rows and edge pair-keys stay valid with ZERO
    /// rekeying. nx-observable insertion order lives entirely in `node_order`
    /// (name -> slot, insertion-ordered IndexMap — the same structure and
    /// O(V) shift_remove the production String store already pays). Buckets
    /// are the S6 compact enums (the winning construction layout).
    #[derive(Debug, Clone, Default)]
    pub struct MgSlabStorage {
        /// name -> stable slot, iteration = nx node insertion order.
        pub node_order: IndexMap<String, usize, rustc_hash::FxBuildHasher>,
        /// slot -> name (None = tombstone awaiting reuse/compaction).
        pub slot_names: Vec<Option<String>>,
        /// slot -> node attribute map (parallel to `slot_names`; empty for
        /// attr-less / edge-created nodes and for tombstoned slots).
        /// Slot-parallel node attributes. Empty for edge-created nodes and
        /// cleared when a slot is tombstoned.
        pub node_attrs: Vec<AttrMap>,
        /// LIFO free-list of tombstoned slots.
        pub free_slots: Vec<usize>,
        /// slot -> neighbor slot -> parallel-key cell (row insertion order).
        pub rows: Vec<IndexMap<usize, CompactKeys>>,
        /// slot-canonical (min, max) pair -> compact bucket. Slots are stable,
        /// so pair keys survive any removal without rekeying.
        pub edges: IndexMap<(usize, usize), CompactBucket, rustc_hash::FxBuildHasher>,
        pub edge_count: usize,
    }

    impl MgSlabStorage {
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        fn ensure_node(&mut self, name: &str) -> usize {
            if let Some(&slot) = self.node_order.get(name) {
                return slot;
            }
            let slot = if let Some(reused) = self.free_slots.pop() {
                debug_assert!(self.slot_names[reused].is_none());
                debug_assert!(self.rows[reused].is_empty());
                self.slot_names[reused] = Some(name.to_owned());
                self.node_attrs[reused] = AttrMap::new();
                reused
            } else {
                self.slot_names.push(Some(name.to_owned()));
                self.rows.push(IndexMap::new());
                self.node_attrs.push(AttrMap::new());
                self.slot_names.len() - 1
            };
            self.node_order.insert(name.to_owned(), slot);
            slot
        }

        /// Same insert semantics as the S5/S6 variants, slot-keyed.
        pub fn add_keyed_edge(
            &mut self,
            left: &str,
            right: &str,
            key: usize,
            attrs: AttrMap,
        ) -> bool {
            let l = self.ensure_node(left);
            let r = if left == right {
                l
            } else {
                self.ensure_node(right)
            };
            self.add_keyed_edge_by_pair(l, r, key, attrs)
        }

        /// br-r37-c1-4c29a: slot-keyed half of [`Self::add_keyed_edge`], for a
        /// caller that has already ensured both endpoints exist and knows their
        /// slots. Identical insert semantics — the only thing skipped is the
        /// `ensure_node` pair, which for such a caller is two redundant
        /// `String` hashes.
        pub fn add_keyed_edge_by_pair(
            &mut self,
            l: usize,
            r: usize,
            key: usize,
            attrs: AttrMap,
        ) -> bool {
            let pair = (l.min(r), l.max(r));
            let is_new = match self.edges.entry(pair) {
                indexmap::map::Entry::Occupied(mut bucket) => bucket.get_mut().merge(key, attrs),
                indexmap::map::Entry::Vacant(slot) => {
                    slot.insert(CompactBucket::One(key, attrs));
                    true
                }
            };
            if is_new {
                self.edge_count += 1;
            }
            match self.rows[l].entry(r) {
                indexmap::map::Entry::Occupied(mut cell) => {
                    let _ = cell.get_mut().insert(key);
                }
                indexmap::map::Entry::Vacant(slot) => {
                    slot.insert(CompactKeys::One(key));
                }
            }
            if l != r {
                match self.rows[r].entry(l) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
            }
            is_new
        }

        /// Bulk loader mirroring the S5/S6 int-prefix arms (fresh graph, slots
        /// == 0..n, no tombstones).
        #[cfg(test)]
        #[must_use]
        pub fn bulk_load_int_prefix<I>(node_count: usize, edges: I) -> Self
        where
            I: IntoIterator<Item = (usize, usize, usize)>,
        {
            let iterator = edges.into_iter();
            let (lower_bound, _) = iterator.size_hint();
            let mut proto = Self::new();
            proto.node_order.reserve(node_count);
            proto.slot_names.reserve(node_count);
            proto.rows.reserve(node_count);
            proto.edges.reserve(lower_bound);
            proto.node_attrs.reserve(node_count);
            for node in 0..node_count {
                let name = node.to_string();
                proto.node_order.insert(name.clone(), node);
                proto.slot_names.push(Some(name));
                proto.rows.push(IndexMap::new());
                proto.node_attrs.push(AttrMap::new());
            }
            for (left_slot, right_slot, key) in iterator {
                debug_assert!(left_slot < node_count);
                debug_assert!(right_slot < node_count);
                let pair = (left_slot.min(right_slot), left_slot.max(right_slot));
                match proto.edges.entry(pair) {
                    indexmap::map::Entry::Occupied(mut bucket) => {
                        let _ = bucket.get_mut().merge(key, AttrMap::new());
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactBucket::One(key, AttrMap::new()));
                    }
                }
                match proto.rows[left_slot].entry(right_slot) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
                if left_slot != right_slot {
                    match proto.rows[right_slot].entry(left_slot) {
                        indexmap::map::Entry::Occupied(mut cell) => {
                            let _ = cell.get_mut().insert(key);
                        }
                        indexmap::map::Entry::Vacant(slot) => {
                            slot.insert(CompactKeys::One(key));
                        }
                    }
                }
                proto.edge_count += 1;
            }
            proto
        }

        /// Mirror of `MultiGraph::remove_edge` (key=None -> LAST bucket key).
        pub fn remove_edge(&mut self, left: &str, right: &str, key: Option<usize>) -> bool {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return false;
            };
            let pair = (l.min(r), l.max(r));
            let Some(bucket) = self.edges.get_mut(&pair) else {
                return false;
            };
            let Some(removal_key) = key.or_else(|| bucket.last_key()) else {
                return false;
            };
            let (removed, bucket_empty) = bucket.shift_remove(removal_key);
            if !removed {
                return false;
            }
            self.edge_count -= 1;
            if bucket_empty {
                self.edges.swap_remove(&pair);
            }
            let mut drop_cell = |u: usize, v: usize| {
                let mut cell_empty = false;
                if let Some(keys) = self.rows[u].get_mut(&v) {
                    let (cell_removed, now_empty) = keys.shift_remove(removal_key);
                    debug_assert!(cell_removed);
                    cell_empty = now_empty;
                }
                if cell_empty {
                    self.rows[u].shift_remove(&v);
                }
            };
            drop_cell(l, r);
            if l != r {
                drop_cell(r, l);
            }
            true
        }

        /// Slab removal: O(V) order-entry shift + O(degree) row/bucket drops.
        /// NO renumber, NO edges rekey — the S8-mandated shape.
        pub fn remove_node(&mut self, name: &str) -> bool {
            let Some(&slot) = self.node_order.get(name) else {
                return false;
            };
            let neighbors: Vec<usize> = self.rows[slot].keys().copied().collect();
            for nbr in neighbors {
                if nbr != slot {
                    self.rows[nbr].shift_remove(&slot);
                }
                if let Some(bucket) = self.edges.swap_remove(&(slot.min(nbr), slot.max(nbr))) {
                    self.edge_count -= bucket.len();
                }
            }
            self.rows[slot] = IndexMap::new();
            self.node_order.shift_remove(name);
            self.slot_names[slot] = None;
            self.node_attrs[slot] = AttrMap::new();
            self.free_slots.push(slot);
            true
        }

        /// `MultiGraph::add_node_with_attrs` semantics: ensure the node exists,
        /// then extend its attribute map.
        pub fn set_node_attrs(&mut self, name: &str, attrs: AttrMap) -> (bool, bool, usize) {
            let existed = self.node_order.contains_key(name);
            let changed = !existed
                || attrs.iter().any(|(key, value)| {
                    self.node_attrs_for(name).and_then(|a| a.get(key)) != Some(value)
                });
            let slot = self.ensure_node(name);
            self.node_attrs[slot].extend(attrs);
            (existed, changed, self.node_attrs[slot].len())
        }

        /// Overwrite an existing node's attribute map. No-op if absent.
        pub fn replace_node_attrs(&mut self, name: &str, attrs: AttrMap) {
            if let Some(&slot) = self.node_order.get(name) {
                self.node_attrs[slot] = attrs;
            }
        }

        /// Distinct neighbors (names, row order) of the node at insertion-order
        /// position `pos`.
        #[cfg(test)]
        #[must_use]
        pub fn neighbor_names(&self, pos: usize) -> Vec<&str> {
            let Some((_, &slot)) = self.node_order.get_index(pos) else {
                return Vec::new();
            };
            self.rows[slot]
                .keys()
                .map(|&s| {
                    self.slot_names[s]
                        .as_deref()
                        .expect("row references a live slot")
                })
                .collect()
        }

        /// br-r37-c1-thp6w S26: name-keyed distinct neighbors in row order
        /// (mirror of `MultiGraph::neighbors`); `None` if the node is absent.
        #[must_use]
        pub fn neighbors_by_name(&self, name: &str) -> Option<Vec<&str>> {
            let &slot = self.node_order.get(name)?;
            Some(
                self.rows[slot]
                    .keys()
                    .map(|&s| {
                        self.slot_names[s]
                            .as_deref()
                            .expect("row references a live slot")
                    })
                    .collect(),
            )
        }

        /// br-r37-c1-thp6w S27: node degree (mirror of `MultiGraph::degree`) —
        /// sum of per-neighbor parallel-edge counts, self-loops counted twice
        /// (nx convention). 0 if the node is absent.
        #[must_use]
        pub fn degree(&self, name: &str) -> usize {
            let Some(&slot) = self.node_order.get(name) else {
                return 0;
            };
            let mut deg = 0;
            for (&nbr_slot, keys) in &self.rows[slot] {
                let count = keys.len();
                if nbr_slot == slot {
                    deg += count * 2;
                } else {
                    deg += count;
                }
            }
            deg
        }

        #[must_use]
        pub fn number_of_selfloops(&self) -> usize {
            self.edges
                .iter()
                .filter(|((left, right), _)| left == right)
                .map(|(_, bucket)| bucket.len())
                .sum()
        }

        /// br-r37-c1-thp6w S28: node membership (mirror of `MultiGraph::has_node`).
        #[must_use]
        pub fn has_node(&self, name: &str) -> bool {
            self.node_order.contains_key(name)
        }

        /// br-r37-c1-thp6w S28: edge membership (mirror of `MultiGraph::has_edge`)
        /// — true iff a non-empty (left, right) bucket exists.
        #[must_use]
        pub fn has_edge(&self, left: &str, right: &str) -> bool {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return false;
            };
            self.has_edge_by_pair(l, r)
        }

        /// br-r37-c1-4c29a: the slot-keyed half of [`Self::has_edge`].
        ///
        /// The callgrind profile of the MultiGraph build put
        /// `IndexMap<String, usize>::get_index_of` at 17.39% — the largest
        /// entry, ahead of the allocator — because `add_edge_impl` re-resolved
        /// both endpoint strings inside every one of six storage calls. These
        /// `_by_pair` variants let a caller that has already resolved its
        /// endpoints skip the lookup, and the `&str` methods keep working by
        /// resolving once and delegating here, so there is a single
        /// implementation of the logic.
        #[must_use]
        pub fn has_edge_by_pair(&self, l: usize, r: usize) -> bool {
            self.edges
                .get(&(l.min(r), l.max(r)))
                .is_some_and(|bucket| !bucket.is_empty())
        }

        /// Slot for a node name, or `None` when absent.
        #[must_use]
        pub fn node_slot(&self, name: &str) -> Option<usize> {
            self.node_order.get(name).copied()
        }

        /// br-r37-c1-2ndmw: the stable SLOT of the node at an insertion-order
        /// POSITION, in O(1) and without hashing a node key.
        ///
        /// This is the missing conversion between the two index spaces. Callers
        /// hold POSITIONS (`get_node_index`, and the cached exact-string index
        /// on the Python side); the edge map is keyed by SLOTS. Feeding one to
        /// the other reports a real edge as ABSENT once a node has been removed
        /// -- see `multigraph_node_slot_and_position_are_distinct_index_spaces`.
        /// `node_order` maps name to slot in insertion order, so the slot at a
        /// position is just that entry's value.
        #[must_use]
        pub fn slot_at_position(&self, position: usize) -> Option<usize> {
            self.node_order.get_index(position).map(|(_, slot)| *slot)
        }

        /// br-r37-c1-thp6w S30: node is isolated (mirror of
        /// `MultiGraph::is_isolate`) — present with an empty adjacency row.
        #[must_use]
        pub fn is_isolate(&self, name: &str) -> bool {
            self.node_order
                .get(name)
                .is_some_and(|&slot| self.rows[slot].is_empty())
        }

        #[must_use]
        pub fn isolates(&self) -> Vec<String> {
            self.node_order
                .iter()
                .filter(|(_, slot)| self.rows[**slot].is_empty())
                .map(|(name, _)| name.clone())
                .collect()
        }

        #[must_use]
        pub fn number_of_isolates(&self) -> usize {
            self.node_order
                .values()
                .filter(|&&slot| self.rows[slot].is_empty())
                .count()
        }

        /// br-r37-c1-thp6w S31: integer weighted size (mirror of
        /// `MultiGraph::weighted_size_int`) — sum of the `weight` attr over
        /// every edge cell (int -> value, missing -> 1); `None` on any non-int
        /// weight. Order-independent (commutative sum; `None` iff any non-int).
        #[must_use]
        pub fn weighted_size_int(&self, weight: &str) -> Option<i128> {
            let mut total: i128 = 0;
            for bucket in self.edges.values() {
                for (_key, attrs) in bucket.iter() {
                    let value = match attrs.get(weight) {
                        Some(fnx_runtime::CgseValue::Int(v)) => i128::from(*v),
                        Some(_) => return None,
                        None => 1,
                    };
                    total = total.checked_add(value)?;
                }
            }
            Some(total)
        }

        /// Parallel-edge key order for the (left, right) pair.
        #[must_use]
        pub fn key_order(&self, left: &str, right: &str) -> Vec<usize> {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return Vec::new();
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(CompactBucket::key_order)
                .unwrap_or_default()
        }

        #[must_use]
        pub fn edge_keys(&self, left: &str, right: &str) -> Option<Vec<usize>> {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return None;
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(CompactBucket::key_order)
        }

        pub fn edge_keys_iter(&self, left: &str, right: &str) -> Option<CompactBucketKeys<'_>> {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return None;
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(CompactBucket::keys)
        }

        pub fn edge_attr_values(&self, left: &str, right: &str) -> Option<CompactBucketValues<'_>> {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return None;
            };
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map(CompactBucket::values)
        }

        /// br-r37-c1-4c29a: slot-keyed edge-cell count. The `&str` wrapper this
        /// replaced had exactly one caller — `add_edge_impl`, which now holds
        /// the slots — so it was removed rather than left dead.
        #[must_use]
        pub fn edge_attr_count_by_pair(&self, l: usize, r: usize) -> usize {
            self.edges
                .get(&(l.min(r), l.max(r)))
                .map_or(0, CompactBucket::len)
        }

        /// br-r37-c1-4c29a: slot-keyed auto-key selection. As with
        /// `edge_attr_count_by_pair`, the `&str` wrapper had a single caller
        /// that now holds the slots, so it was removed rather than left dead.
        #[must_use]
        pub fn next_edge_key_by_pair(&self, l: usize, r: usize) -> usize {
            let Some(bucket) = self.edges.get(&(l.min(r), l.max(r))) else {
                return 0;
            };
            let mut key = bucket.len();
            while bucket.contains_key(key) {
                key += 1;
            }
            key
        }

        /// Overwrite the attribute map for one edge cell.
        pub fn replace_edge_attrs(
            &mut self,
            left: &str,
            right: &str,
            key: usize,
            attrs: AttrMap,
        ) -> bool {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return false;
            };
            self.edges
                .get_mut(&(l.min(r), l.max(r)))
                .is_some_and(|bucket| bucket.replace_attrs(key, attrs))
        }

        /// Attributes of one `(left, right, key)` edge cell.
        #[must_use]
        pub fn edge_attrs(&self, left: &str, right: &str, key: usize) -> Option<&AttrMap> {
            let (Some(&l), Some(&r)) = (self.node_order.get(left), self.node_order.get(right))
            else {
                return None;
            };
            self.edge_attrs_by_pair(l, r, key)
        }

        /// br-r37-c1-4c29a: slot-keyed half of [`Self::edge_attrs`].
        #[must_use]
        pub fn edge_attrs_by_pair(&self, l: usize, r: usize, key: usize) -> Option<&AttrMap> {
            self.edges
                .get(&(l.min(r), l.max(r)))
                .and_then(|bucket| bucket.attrs_for(key))
        }

        /// The node's attribute map, or `None` when the node is absent.
        #[must_use]
        pub fn node_attrs_for(&self, name: &str) -> Option<&AttrMap> {
            let &slot = self.node_order.get(name)?;
            Some(&self.node_attrs[slot])
        }

        #[must_use]
        pub fn get_node_index(&self, name: &str) -> Option<usize> {
            self.node_order.get_index_of(name)
        }

        #[must_use]
        pub fn get_node_name(&self, index: usize) -> Option<&str> {
            self.node_order
                .get_index(index)
                .map(|(name, _)| name.as_str())
        }

        #[must_use]
        pub fn node_index_matches_int(&self, index: usize) -> bool {
            self.node_order
                .get_index(index)
                .is_some_and(|(name, _)| name.parse::<usize>() == Ok(index))
        }

        #[must_use]
        pub fn build_int_adjacency(&self) -> Vec<Vec<usize>> {
            let slot_to_position = self.slot_positions();
            self.node_order
                .values()
                .map(|&slot| {
                    self.rows[slot]
                        .keys()
                        .map(|&neighbor_slot| slot_to_position[neighbor_slot])
                        .collect()
                })
                .collect()
        }

        /// br-r37-c1-thp6w S10: slot -> insertion-order position (usize::MAX
        /// for tombstones), rebuilt on demand in O(V).
        fn slot_positions(&self) -> Vec<usize> {
            let mut pos = vec![usize::MAX; self.slot_names.len()];
            for (p, (_, &slot)) in self.node_order.iter().enumerate() {
                pos[slot] = p;
            }
            pos
        }

        /// br-r37-c1-thp6w S12: full `edges_ordered_borrowed` analog with
        /// attrs — the production read candidate. Same walk contract as
        /// `edges_ordered_names` (node order x row order x bucket key order,
        /// first-touch dedup, String-lex canonical emission orientation) but
        /// hashing only usizes where the String store hashes `EdgeKeyRef`
        /// String pairs per cell and per seen-set probe.
        #[must_use]
        pub fn edges_ordered_borrowed(&self) -> Vec<(&str, &str, usize, &AttrMap)> {
            let mut ordered = Vec::with_capacity(self.edge_count);
            let mut seen: std::collections::HashSet<(usize, usize, usize)> =
                std::collections::HashSet::with_capacity(self.edge_count);
            for (u_name, &u_slot) in &self.node_order {
                for &v_slot in self.rows[u_slot].keys() {
                    let pair = (u_slot.min(v_slot), u_slot.max(v_slot));
                    let Some(bucket) = self.edges.get(&pair) else {
                        continue;
                    };
                    for (key, attrs) in bucket.iter() {
                        if !seen.insert((pair.0, pair.1, key)) {
                            continue;
                        }
                        let v_name = self.slot_names[v_slot]
                            .as_deref()
                            .expect("row references a live slot");
                        let (left, right) = if u_name.as_str() <= v_name {
                            (u_name.as_str(), v_name)
                        } else {
                            (v_name, u_name.as_str())
                        };
                        ordered.push((left, right, key, attrs));
                    }
                }
            }
            ordered
        }

        #[must_use]
        pub fn snapshot(&self, mode: CompatibilityMode) -> MultiGraphSnapshot {
            let node_attrs = self
                .node_order
                .iter()
                .filter_map(|(name, &slot)| {
                    let attrs = &self.node_attrs[slot];
                    (!attrs.is_empty()).then(|| (name.clone(), attrs.clone()))
                })
                .collect();
            let edges = self
                .edges_ordered_borrowed()
                .into_iter()
                .map(|(left, right, key, attrs)| MultiEdgeSnapshot {
                    left: left.to_owned(),
                    right: right.to_owned(),
                    key,
                    attrs: attrs.clone(),
                })
                .collect();
            MultiGraphSnapshot {
                mode,
                nodes: self.node_order.keys().cloned().collect(),
                node_attrs,
                edges,
            }
        }

        /// br-r37-c1-thp6w S13: index-space analog of `edges_ordered_borrowed`
        /// — the same walk/order/orientation, but each endpoint emitted as its
        /// POSITION (node_order iteration index = nx node position), not its
        /// name. A `slot -> position` array is built once up front (O(n),
        /// hash-free — positions come straight from `node_order` iteration, so
        /// this is correct under any slot recycling, where slot != position),
        /// then the walk resolves both endpoints by O(1) array index. The only
        /// per-edge string op is the lex compare for the canonical orientation
        /// (production `edges_ordered_indices_borrowed` pays a `get_index_of`
        /// String hash per endpoint plus an `EdgeKey` pair hash instead).
        #[must_use]
        pub fn edges_ordered_indices_borrowed(&self) -> Vec<(usize, usize, usize, &AttrMap)> {
            let mut slot_to_pos = vec![0usize; self.slot_names.len()];
            for (pos, (_name, &slot)) in self.node_order.iter().enumerate() {
                slot_to_pos[slot] = pos;
            }
            let mut ordered = Vec::with_capacity(self.edge_count);
            let mut seen: std::collections::HashSet<(usize, usize, usize)> =
                std::collections::HashSet::with_capacity(self.edge_count);
            for (u_name, &u_slot) in &self.node_order {
                for &v_slot in self.rows[u_slot].keys() {
                    let pair = (u_slot.min(v_slot), u_slot.max(v_slot));
                    let Some(bucket) = self.edges.get(&pair) else {
                        continue;
                    };
                    for (key, attrs) in bucket.iter() {
                        if !seen.insert((pair.0, pair.1, key)) {
                            continue;
                        }
                        let v_name = self.slot_names[v_slot]
                            .as_deref()
                            .expect("row references a live slot");
                        let (left_pos, right_pos) = if u_name.as_str() <= v_name {
                            (slot_to_pos[u_slot], slot_to_pos[v_slot])
                        } else {
                            (slot_to_pos[v_slot], slot_to_pos[u_slot])
                        };
                        ordered.push((left_pos, right_pos, key, attrs));
                    }
                }
            }
            ordered
        }

        /// br-r37-c1-thp6w S10: `edges_ordered_borrowed` analog — the ONLY
        /// observed edge order. Walk = node insertion order, row order, bucket
        /// key order; each (pair, key) emitted once (first touch); emitted
        /// orientation = STRING-LEX canonical (`EdgeKey` semantics), derived
        /// from the names at emission since the internal pair key is
        /// slot-canonical. This is the snapshot/pickle orientation gate.
        #[cfg(test)]
        #[must_use]
        pub fn edges_ordered_names(&self) -> Vec<(&str, &str, usize)> {
            let mut ordered = Vec::with_capacity(self.edge_count);
            let mut seen: std::collections::HashSet<(usize, usize, usize)> =
                std::collections::HashSet::with_capacity(self.edge_count);
            for (u_name, &u_slot) in &self.node_order {
                for &v_slot in self.rows[u_slot].keys() {
                    let pair = (u_slot.min(v_slot), u_slot.max(v_slot));
                    let Some(bucket) = self.edges.get(&pair) else {
                        continue;
                    };
                    for key in bucket.key_order() {
                        if !seen.insert((pair.0, pair.1, key)) {
                            continue;
                        }
                        let v_name = self.slot_names[v_slot]
                            .as_deref()
                            .expect("row references a live slot");
                        let (left, right) = if u_name.as_str() <= v_name {
                            (u_name.as_str(), v_name)
                        } else {
                            (v_name, u_name.as_str())
                        };
                        ordered.push((left, right, key));
                    }
                }
            }
            ordered
        }

        pub fn clear_edges(&mut self) {
            self.edges.clear();
            for row in &mut self.rows {
                row.clear();
            }
            self.edge_count = 0;
        }

        pub fn remove_nodes_from<'a, I>(&mut self, nodes: I) -> (usize, usize)
        where
            I: IntoIterator<Item = &'a str>,
        {
            let remove_slots: rustc_hash::FxHashSet<usize> = nodes
                .into_iter()
                .filter_map(|name| self.node_order.get(name).copied())
                .collect();
            if remove_slots.is_empty() {
                return (0, 0);
            }

            let old_edge_count = self.edge_count;
            self.edges.retain(|(left, right), _| {
                !remove_slots.contains(left) && !remove_slots.contains(right)
            });
            self.edge_count = self.edges.values().map(CompactBucket::len).sum();

            for (slot, row) in self.rows.iter_mut().enumerate() {
                if remove_slots.contains(&slot) {
                    row.clear();
                } else {
                    row.retain(|neighbor, _| !remove_slots.contains(neighbor));
                }
            }
            self.node_order
                .retain(|_, slot| !remove_slots.contains(slot));
            for &slot in &remove_slots {
                self.slot_names[slot] = None;
                self.node_attrs[slot].clear();
                self.free_slots.push(slot);
            }
            (
                remove_slots.len(),
                old_edge_count.saturating_sub(self.edge_count),
            )
        }

        /// br-r37-c1-thp6w S10: `MultiGraph::reorder_rows_for_nx_copy_walk`
        /// under slot storage. Two-phase exactly like the real one: ALL new
        /// row orders are computed against the PRE-reorder rows (early =
        /// earlier-position neighbors sorted by (pos(v), index of u within
        /// row v), then late in original order), then applied. Sort key
        /// (pos, idx, slot) is equivalent to the real (pos, idx, name)
        /// because pos is unique per neighbor.
        pub fn reorder_rows_for_nx_copy_walk(&mut self) {
            let pos = self.slot_positions();
            let order_slots: Vec<usize> = self.node_order.values().copied().collect();
            let mut new_orders: Vec<(usize, Vec<usize>)> = Vec::with_capacity(order_slots.len());
            for &u_slot in &order_slots {
                let pu = pos[u_slot];
                let mut early: Vec<(usize, usize, usize)> = Vec::new();
                let mut late: Vec<usize> = Vec::new();
                for &v_slot in self.rows[u_slot].keys() {
                    let pv = pos[v_slot];
                    if pv < pu {
                        let idx = self.rows[v_slot]
                            .get_index_of(&u_slot)
                            .unwrap_or(usize::MAX);
                        early.push((pv, idx, v_slot));
                    } else {
                        late.push(v_slot);
                    }
                }
                early.sort_unstable();
                let mut order: Vec<usize> = early.into_iter().map(|(_, _, v)| v).collect();
                order.extend(late);
                new_orders.push((u_slot, order));
            }
            for (u_slot, order) in new_orders {
                let mut old = std::mem::take(&mut self.rows[u_slot]);
                let mut rebuilt = IndexMap::with_capacity(old.len());
                for v_slot in order {
                    if let Some(cell) = old.shift_remove(&v_slot) {
                        rebuilt.insert(v_slot, cell);
                    }
                }
                debug_assert!(old.is_empty(), "copy-walk reorder dropped a cell");
                self.rows[u_slot] = rebuilt;
            }
        }

        /// Apply arbitrary name-keyed row orders to the slot-keyed rows, with
        /// requested neighbors first and untouched neighbors retaining order.
        pub fn apply_row_orders(&mut self, orders: &[(String, Vec<String>)]) {
            for (node, order) in orders {
                let Some(&slot) = self.node_order.get(node.as_str()) else {
                    continue;
                };
                let mut old = std::mem::take(&mut self.rows[slot]);
                let mut new_row = IndexMap::with_capacity(old.len());
                for v in order {
                    if let Some(&v_slot) = self.node_order.get(v.as_str())
                        && let Some((k, val)) = old.shift_remove_entry(&v_slot)
                    {
                        new_row.insert(k, val);
                    }
                }
                for (k, val) in old {
                    new_row.insert(k, val);
                }
                self.rows[slot] = new_row;
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct MultiGraph {
    mode: CompatibilityMode,
    revision: u64,
    storage: multigraph_storage::MgSlabStorage,
    runtime_policy: RuntimePolicy,
    edge_count: usize,
    /// br-r37-c1-thp6w slice 1: lazy revision-keyed integer adjacency (see `IntAdjCache`).
    int_adj_cache: IntAdjCache,
}

/// Neighbor-name iterator over a stable-slot integer row.
pub struct MgNeighborNames<'a> {
    rows: indexmap::map::Keys<'a, usize, multigraph_storage::CompactKeys>,
    slot_names: &'a [Option<String>],
}

impl<'a> Iterator for MgNeighborNames<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        self.rows.next().map(|&slot| {
            self.slot_names[slot]
                .as_deref()
                .expect("row references a live slot")
        })
    }
}

/// Zero-allocation parallel-key iterator over a stable-slot edge bucket.
pub struct MgEdgeKeys<'a>(multigraph_storage::CompactBucketKeys<'a>);

impl<'a> Iterator for MgEdgeKeys<'a> {
    type Item = &'a usize;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl MultiGraph {
    /// br-r37-c1-7dpyg: structural clone with a FRESH RuntimePolicy —
    /// see Graph::clone_with_fresh_policy.
    #[must_use]
    pub fn clone_with_fresh_policy(&self) -> Self {
        Self {
            mode: self.mode,
            revision: self.revision,
            storage: self.storage.clone(),
            runtime_policy: RuntimePolicy::new(self.mode),
            edge_count: self.edge_count,
            int_adj_cache: IntAdjCache::default(),
        }
    }

    /// br-r37-c1-s0d4x: reorder every adjacency row into NetworkX's
    /// `MultiGraph.copy()` walk order — the multigraph counterpart of
    /// Graph::reorder_rows_for_nx_copy_walk (cells move wholesale). A
    /// pair's cells enter both rows at the first u-major touch: row u =
    /// earlier-position neighbors sorted by (pos(v), index of u within
    /// row v), then the rest (self-loops included) in original order.
    pub fn reorder_rows_for_nx_copy_walk(&mut self) {
        self.storage.reorder_rows_for_nx_copy_walk();
        *self
            .int_adj_cache
            .0
            .get_mut()
            .expect("int_adj_cache poisoned") = None;
    }

    /// br-r37-c1-u3qyn: restore explicit adjacency row orders (pickle
    /// round-trip) — see Graph::apply_row_orders. Multigraph rows are
    /// keyed cells (neighbor -> key set); the cells move wholesale.
    pub fn apply_row_orders(&mut self, orders: &[(String, Vec<String>)]) {
        self.storage.apply_row_orders(orders);
        // br-r37-c1-thp6w slice 1: a pure ROW-ORDER change (MultiGraph.copy walk order,
        // pickle round-trip) does NOT bump `revision`, so the revision-keyed int-adjacency
        // memo would otherwise serve stale row order. Drop it explicitly here — this is the
        // only adjacency mutator that changes order without a content (revision) bump.
        *self
            .int_adj_cache
            .0
            .get_mut()
            .expect("int_adj_cache poisoned") = None;
    }

    #[must_use]
    pub fn new(mode: CompatibilityMode) -> Self {
        Self {
            mode,
            revision: 0,
            storage: multigraph_storage::MgSlabStorage::new(),
            runtime_policy: RuntimePolicy::new(mode),
            edge_count: 0,
            int_adj_cache: IntAdjCache::default(),
        }
    }

    #[must_use]
    pub fn with_runtime_policy(runtime_policy: RuntimePolicy) -> Self {
        let mode = runtime_policy.mode();
        Self {
            mode,
            revision: 0,
            storage: multigraph_storage::MgSlabStorage::new(),
            runtime_policy,
            edge_count: 0,
            int_adj_cache: IntAdjCache::default(),
        }
    }

    fn slab_store(&self) -> &multigraph_storage::MgSlabStorage {
        &self.storage
    }

    fn slab_store_mut(&mut self) -> &mut multigraph_storage::MgSlabStorage {
        &mut self.storage
    }

    #[must_use]
    pub fn strict() -> Self {
        Self::new(CompatibilityMode::Strict)
    }

    #[must_use]
    pub fn hardened() -> Self {
        Self::new(CompatibilityMode::Hardened)
    }

    #[must_use]
    pub fn mode(&self) -> CompatibilityMode {
        self.mode
    }

    #[must_use]
    pub fn node_count(&self) -> usize {
        self.slab_store().node_order.len()
    }

    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edge_count
    }

    #[must_use]
    pub fn number_of_selfloops(&self) -> usize {
        self.slab_store().number_of_selfloops()
    }

    /// Return edge keys as Vec (needed by Python bindings).
    #[must_use]
    pub fn edge_keys(&self, left: &str, right: &str) -> Option<Vec<usize>> {
        self.slab_store().edge_keys(left, right)
    }

    /// Return an iterator over keys for edges between left and right.
    pub fn edge_keys_iter(&self, left: &str, right: &str) -> Option<MgEdgeKeys<'_>> {
        self.slab_store()
            .edge_keys_iter(left, right)
            .map(MgEdgeKeys)
    }

    #[must_use]
    pub fn revision(&self) -> u64 {
        self.revision
    }

    #[must_use]
    pub fn has_node(&self, node: &str) -> bool {
        self.slab_store().has_node(node)
    }

    #[must_use]
    pub fn has_edge(&self, left: &str, right: &str) -> bool {
        self.slab_store().has_edge(left, right)
    }

    /// br-r37-c1-04z53 (cc): resolve `has_edge` straight from insertion-order
    /// indices, skipping the `i.to_string()` heap alloc the Python binding pays
    /// for int nodes. The names come from the node table by index (borrowed, no
    /// alloc); the caller (`PyMultiGraph::has_edge`) guards each index with
    /// `node_index_matches_int` so the identity `index == int-value` holds
    /// (any removal / remap that broke it fails the guard and falls through to
    /// the String path). Mirror of `Graph::has_edge_by_indices`.
    ///
    /// br-r37-c1-2ndmw: THIS TAKES A POSITION AND THE EDGE MAP IS KEYED BY SLOT,
    /// which is the whole subtlety. It used to bridge the two spaces by
    /// resolving both positions back to NAMES and calling the string
    /// `has_edge`, which re-hashes both node keys -- so this was O(node key
    /// length) while `Graph::has_edge_by_indices` was a genuine O(1)
    /// `contains_key`, and every caller taking the "index fast path"
    /// (`PyMultiGraph::has_edge`, the edge-view probe, the algorithms bulk
    /// paths) still paid for the key length it was trying to avoid.
    ///
    /// `slot_at_position` bridges the same gap in O(1) with no hashing, and
    /// substitutes an EQUAL value rather than changing behaviour:
    /// `MgSlabStorage::has_edge(l, r)` is itself defined as `node_order.get(l)`
    /// and `node_order.get(r)` followed by `has_edge_by_pair`, and the slot
    /// `get(name)` returns for an entry is the slot `get_index(position)`
    /// returns for that same entry.
    ///
    /// What must NEVER happen is passing the position straight to
    /// `has_edge_by_pair`: the spaces coincide only until a node is removed,
    /// after which that reports a real edge as absent. Pinned by
    /// `multigraph_node_slot_and_position_are_distinct_index_spaces`, and the
    /// equivalence pinned by
    /// `multigraph_has_edge_by_indices_matches_the_string_path_across_removals`.
    #[must_use]
    pub fn has_edge_by_indices(&self, li: usize, ri: usize) -> bool {
        let store = self.slab_store();
        match (store.slot_at_position(li), store.slot_at_position(ri)) {
            (Some(left), Some(right)) => store.has_edge_by_pair(left, right),
            _ => false,
        }
    }

    /// br-r37-c1-s8dj1: attributes of a KEYED edge, addressed by node POSITION.
    ///
    /// The keyed sibling of [`Self::has_edge_by_indices`], and it exists for the
    /// same reason: `PyMultiGraph::has_edge` had an O(1) path only while `key`
    /// was `None`, so `(u, v) in G.edges` -- which passes key 0 -- paid two
    /// canonicalisations and several node-key hashes and grew 3.6x from 2- to
    /// 2000-character keys while the keyless form stayed flat.
    ///
    /// Takes POSITIONS and converts them to SLOTS, exactly as the keyless
    /// sibling does. Passing a position straight to the slot-keyed store
    /// reports a real edge as absent after any node removal -- see
    /// `multigraph_node_slot_and_position_are_distinct_index_spaces`.
    #[must_use]
    pub fn edge_attrs_by_indices(&self, li: usize, ri: usize, key: usize) -> Option<&AttrMap> {
        let store = self.slab_store();
        match (store.slot_at_position(li), store.slot_at_position(ri)) {
            (Some(left), Some(right)) => store.edge_attrs_by_pair(left, right, key),
            _ => None,
        }
    }

    #[must_use]
    pub fn nodes_ordered(&self) -> Vec<&str> {
        self.slab_store()
            .node_order
            .keys()
            .map(String::as_str)
            .collect()
    }

    /// Resolve a node through the insertion-ordered node table without
    /// rebuilding a query-local name-to-index map.
    #[must_use]
    #[inline]
    pub fn get_node_index(&self, node: &str) -> Option<usize> {
        self.slab_store().get_node_index(node)
    }

    /// Resolve the current node name for an insertion-order index.
    #[must_use]
    #[inline]
    pub fn get_node_name(&self, index: usize) -> Option<&str> {
        self.slab_store().get_node_name(index)
    }

    /// br-cc-nbunchbulk: int membership fast path for `_nbunch_present` — see the
    /// simple-Graph accessor.
    #[must_use]
    pub fn node_index_matches_int(&self, idx: usize) -> bool {
        self.slab_store().node_index_matches_int(idx)
    }

    #[must_use]
    pub fn neighbors(&self, node: &str) -> Option<Vec<&str>> {
        self.slab_store().neighbors_by_name(node)
    }

    pub fn neighbors_iter(&self, node: &str) -> Option<MgNeighborNames<'_>> {
        let slab = self.slab_store();
        let &slot = slab.node_order.get(node)?;
        Some(MgNeighborNames {
            rows: slab.rows[slot].keys(),
            slot_names: &slab.slot_names,
        })
    }

    /// br-r37-c1-thp6w slice 1: build integer adjacency from the authoritative stable-slot
    /// rows. Row `i` (node at insertion-index `i`) lists the node indices of that node's
    /// neighbors in adjacency-row order — i.e. exactly
    /// `[get_node_index(v) for v in neighbors_iter(node_i)]`. Distinct neighbors only
    /// (parallel-edge multiplicity lives in `edges`).
    fn build_int_adjacency(&self) -> Vec<Vec<usize>> {
        self.slab_store().build_int_adjacency()
    }

    /// br-r37-c1-thp6w slice 1: run `f` with the integer adjacency (hash-free neighbor rows),
    /// built lazily from the stable-slot rows and memoized until the next mutation. The
    /// memo is keyed on `revision` (bumped by every content mutation) and cleared by
    /// `apply_row_orders` (the one order-only mutator), so the rows always match the current
    /// storage byte-for-byte. The closure form lets a whole traversal borrow the rows
    /// under one read lock without a per-node allocation. Foundation for the epoch's
    /// `neighbors_indices` traversal; no caller yet (infrastructure).
    pub fn with_int_adjacency<R>(&self, f: impl FnOnce(&[Vec<usize>]) -> R) -> R {
        {
            let guard = self.int_adj_cache.0.read().expect("int_adj_cache poisoned");
            if let Some((rev, adj)) = guard.as_ref()
                && *rev == self.revision
            {
                return f(adj);
            }
        }
        let adj = self.build_int_adjacency();
        let result = f(&adj);
        *self
            .int_adj_cache
            .0
            .write()
            .expect("int_adj_cache poisoned") = Some((self.revision, adj));
        result
    }

    /// br-r37-c1-thp6w S4: advance a warm integer-adjacency memo across one
    /// single-edge mutation instead of invalidating it. The memo must still be
    /// keyed at `prev_revision` (the revision on entry to the mutating call);
    /// the delta mirrors the String-row edit exactly (new distinct neighbors
    /// append, emptied pairs shift-remove, new nodes push fresh rows), then the
    /// memo re-keys to the post-mutation revision. Every mutation path that
    /// does NOT call this leaves the memo keyed at a stale revision, so
    /// `with_int_adjacency` lazily rebuilds — unhandled sites stay exactly as
    /// safe as the invalidate-only scheme.
    fn advance_int_adj_memo(&mut self, prev_revision: u64, delta: IntAdjEdgeDelta<'_>) {
        let needs_indices = matches!(
            delta,
            IntAdjEdgeDelta::Add { pair_new: true, .. }
                | IntAdjEdgeDelta::Remove {
                    pair_gone: true,
                    ..
                }
        );
        let indices = if needs_indices {
            let (left, right) = match &delta {
                IntAdjEdgeDelta::Add { left, right, .. }
                | IntAdjEdgeDelta::Remove { left, right, .. } => (*left, *right),
            };
            match (
                self.storage.get_node_index(left),
                self.storage.get_node_index(right),
            ) {
                (Some(u), Some(v)) => Some((u, v)),
                _ => None,
            }
        } else {
            None
        };
        let Ok(slot) = self.int_adj_cache.0.get_mut() else {
            return;
        };
        if needs_indices && indices.is_none() {
            // Endpoint missing from the node table (should be unreachable for a
            // live edge): the delta cannot be mirrored, so drop the memo.
            *slot = None;
            return;
        }
        let Some((rev, rows)) = slot.as_mut() else {
            return;
        };
        if *rev != prev_revision {
            return;
        }
        let mut advanced = true;
        match delta {
            IntAdjEdgeDelta::Add {
                left,
                right,
                left_new,
                right_new,
                pair_new,
            } => {
                if left_new {
                    rows.push(Vec::new());
                }
                if right_new && left != right {
                    rows.push(Vec::new());
                }
                if pair_new && let Some((u, v)) = indices {
                    rows[u].push(v);
                    if u != v {
                        rows[v].push(u);
                    }
                }
            }
            IntAdjEdgeDelta::Remove { pair_gone, .. } => {
                if pair_gone && let Some((u, v)) = indices {
                    // Mirror `IndexMap::shift_remove` on the String row:
                    // order-preserving removal of the emptied neighbor cell.
                    if let Some(pu) = rows[u].iter().position(|&x| x == v) {
                        rows[u].remove(pu);
                        if u != v {
                            if let Some(pv) = rows[v].iter().position(|&x| x == u) {
                                rows[v].remove(pv);
                            } else {
                                advanced = false;
                            }
                        }
                    } else {
                        advanced = false;
                    }
                }
            }
        }
        if advanced {
            *rev = self.revision;
        } else {
            *slot = None;
        }
    }

    #[must_use]
    pub fn edge_keys_vec(&self, left: &str, right: &str) -> Vec<usize> {
        self.slab_store().key_order(left, right)
    }

    #[must_use]
    pub fn node_attrs(&self, node: &str) -> Option<&AttrMap> {
        self.slab_store().node_attrs_for(node)
    }

    #[must_use]
    pub fn edge_attrs(&self, left: &str, right: &str, key: usize) -> Option<&AttrMap> {
        self.slab_store().edge_attrs(left, right, key)
    }

    /// Iterator over the `AttrMap`s of every parallel edge between `left` and
    /// `right` (undirected: the single canonical bucket), yielded in the SAME
    /// order as `edge_keys` / `edge_keys_iter`. The adjacency `IndexSet<usize>`
    /// and this `edges` `IndexMap<usize, AttrMap>` are appended together on add
    /// and both `shift_remove`d on per-key remove (whole bucket dropped on
    /// node/endpoint removal), so their key order stays identical — callers that
    /// need adjacency-order iteration (e.g. the order-sensitive Neumaier weighted
    /// degree) may consume this directly instead of re-looking-up each key.
    /// Undirected sibling of `MultiDiGraph::edge_attr_values`.
    pub fn edge_attr_values(
        &self,
        left: &str,
        right: &str,
    ) -> Option<impl Iterator<Item = &AttrMap> + '_> {
        self.slab_store().edge_attr_values(left, right)
    }

    #[must_use]
    pub fn evidence_ledger(&self) -> &EvidenceLedger {
        self.runtime_policy.decision_log()
    }

    pub fn drain_decision_records(&mut self) -> Vec<DecisionRecord> {
        self.runtime_policy.drain_decision_records()
    }

    #[must_use]
    pub fn runtime_policy(&self) -> &RuntimePolicy {
        &self.runtime_policy
    }

    pub fn set_runtime_policy(&mut self, runtime_policy: RuntimePolicy) {
        self.mode = runtime_policy.mode();
        self.runtime_policy = runtime_policy;
    }

    #[must_use]
    pub fn is_directed(&self) -> bool {
        false
    }

    #[must_use]
    pub fn is_multigraph(&self) -> bool {
        true
    }

    /// Return the degree of a node (total number of parallel edges incident).
    /// Self-loops contribute 2 to the degree each (NetworkX convention).
    #[must_use]
    pub fn degree(&self, node: &str) -> usize {
        self.slab_store().degree(node)
    }

    /// br-r37-c1-mgisol (cc): native isolate detection for MultiGraph. A node
    /// is isolated iff it has no incident edges (empty/absent adjacency row);
    /// a self-loop keeps a node non-isolated (the loop records the node in its
    /// own row, matching nx's degree-2 self-loop convention). Yields nodes in
    /// insertion order — identical to the `G.degree()`-driven nx generator and
    /// to the old `multigraph_to_simple_graph` projection path, but WITHOUT the
    /// per-call O(V+E) simple-graph rebuild that dominated the binding.
    #[must_use]
    pub fn isolates(&self) -> Vec<String> {
        self.slab_store().isolates()
    }

    /// br-r37-c1-mgisol (cc): isolate count without the simple-graph projection.
    #[must_use]
    pub fn number_of_isolates(&self) -> usize {
        self.slab_store().number_of_isolates()
    }

    /// br-r37-c1-mgisol (cc): O(1) isolate predicate. Absent node -> false
    /// (mirrors `is_isolate(&Graph)`); the binding validates presence first.
    #[must_use]
    pub fn is_isolate(&self, node: &str) -> bool {
        self.slab_store().is_isolate(node)
    }

    pub fn add_node(&mut self, node: impl AsRef<str>) -> bool {
        self.add_node_with_attrs(node, AttrMap::new())
    }

    /// br-r37-c1-wa1b9: the storage half of [`Self::add_node_with_attrs`],
    /// without its ledger record. See the undirected `Graph` sibling.
    /// br-r37-c1-jc9e4: no owned key at all on this path. `set_node_attrs`
    /// already takes `&str` and owns internally only when it inserts, so the
    /// `let node = node.into();` this used to open with was allocating a
    /// `String` purely to hand out a borrow of it — waste on every call, not
    /// just the occupied ones.
    fn add_node_with_attrs_unrecorded(
        &mut self,
        node: impl AsRef<str>,
        attrs: AttrMap,
    ) -> (bool, bool, usize) {
        let (existed, changed, attrs_count) = self.storage.set_node_attrs(node.as_ref(), attrs);
        if changed {
            self.revision = self.revision.saturating_add(1);
        }
        (changed, existed, attrs_count)
    }

    pub fn add_node_with_attrs(&mut self, node: impl AsRef<str>, attrs: AttrMap) -> bool {
        let (changed, existed, attrs_count) = self.add_node_with_attrs_unrecorded(node, attrs);
        self.record_decision(
            "add_node",
            0.0,
            false,
            vec![
                EvidenceTerm {
                    signal: "node_preexisting".into(),
                    observed_value: bool_evidence(existed),
                    log_likelihood_ratio: -3.0,
                },
                EvidenceTerm {
                    signal: "attrs_count".into(),
                    observed_value: count_evidence(attrs_count),
                    log_likelihood_ratio: -1.0,
                },
            ],
        );
        changed
    }

    pub fn add_edge(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
    ) -> Result<usize, GraphError> {
        self.add_edge_impl(left, right, None, AttrMap::new())
    }

    pub fn add_edge_with_attrs(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
        attrs: AttrMap,
    ) -> Result<usize, GraphError> {
        self.add_edge_impl(left, right, None, attrs)
    }

    pub fn add_edge_with_key_and_attrs(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
        key: usize,
        attrs: AttrMap,
    ) -> Result<usize, GraphError> {
        self.add_edge_impl(left, right, Some(key), attrs)
    }

    /// Insert one attribute-free edge for a pair known to have no existing
    /// parallel edge bucket. Returns `None` if the pair already exists.
    #[must_use]
    pub fn add_fresh_edge_unrecorded(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
    ) -> Option<usize> {
        self.add_fresh_edge_with_key_unrecorded(left, right, 0)
    }

    /// Insert one attribute-free edge with an explicit key for a pair known to
    /// have no existing parallel edge bucket. Returns `None` if the pair
    /// already exists.
    #[must_use]
    pub fn add_fresh_edge_with_key_unrecorded(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
        key: usize,
    ) -> Option<usize> {
        let left = left.into();
        let right = right.into();
        self.storage.set_node_attrs(&left, AttrMap::new());
        if left != right {
            self.storage.set_node_attrs(&right, AttrMap::new());
        }

        if self.storage.has_edge(&left, &right) {
            return None;
        }
        let inserted = self
            .storage
            .add_keyed_edge(&left, &right, key, AttrMap::new());
        debug_assert!(inserted, "fresh edge unexpectedly merged");
        self.edge_count += 1;
        self.revision = self.revision.saturating_add(1);
        Some(key)
    }

    /// br-r37-c1-l5ve7: bulk node insert WITH attrs, one ledger record —
    /// MultiGraph mirror of MultiDiGraph::extend_nodes_with_attrs_unrecorded.
    /// Existing nodes merge attrs (extend).
    pub fn extend_nodes_with_attrs_unrecorded<I>(&mut self, nodes: I) -> usize
    where
        I: IntoIterator<Item = (String, AttrMap)>,
    {
        let mut inserted = 0usize;
        for (node, attrs) in nodes {
            let (existed, _, _) = self.storage.set_node_attrs(&node, attrs);
            if !existed {
                inserted += 1;
            }
        }
        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            self.record_decision(
                "extend_nodes_with_attrs_unrecorded",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "batch_node_count".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: -1.0,
                }],
            );
        }
        inserted
    }

    /// br-r37-c1-l5ve7: bulk KEYED edge insert WITH attrs, one ledger
    /// record — MultiGraph mirror of
    /// MultiDiGraph::extend_keyed_edges_with_attrs_unrecorded
    /// (add_edge_impl pays TWO record_decision calls per edge). Endpoint
    /// nodes are created on demand; an existing (u, v, key) cell merges
    /// attrs (extend), matching add_edge_with_key_and_attrs.
    pub fn extend_keyed_edges_with_attrs_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (String, String, usize, AttrMap)>,
    {
        let mut inserted = 0usize;
        for (left, right, key, attrs) in edges {
            if self.storage.add_keyed_edge(&left, &right, key, attrs) {
                self.edge_count += 1;
                inserted += 1;
            }
        }
        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            self.record_decision(
                "extend_keyed_edges_with_attrs_unrecorded",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "batch_edge_count".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: -1.0,
                }],
            );
        }
        inserted
    }

    /// Bulk-load attribute-free keyed edges for a freshly-created integer
    /// prefix graph. The caller has already validated that node first-seen
    /// order is exactly `0..node_count` and that internal keys are sequential
    /// per undirected pair, so this builds the string-keyed MultiGraph state
    /// directly from indices instead of canonicalizing both endpoints for every
    /// edge in the Python boundary layer.
    #[must_use]
    pub fn extend_fresh_int_prefix_keyed_edges_unrecorded<I>(
        &mut self,
        node_count: usize,
        edges: I,
    ) -> usize
    where
        I: IntoIterator<Item = (usize, usize, usize)>,
    {
        debug_assert_eq!(self.node_count(), 0);
        debug_assert_eq!(self.edge_count(), 0);

        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();

        let node_names = (0..node_count)
            .map(|node| node.to_string())
            .collect::<Vec<_>>();
        let mut fresh_slab = {
            use multigraph_storage::MgSlabStorage;
            let mut slab = MgSlabStorage::new();
            slab.node_order.reserve(node_count);
            slab.slot_names.reserve(node_count);
            slab.node_attrs.reserve(node_count);
            slab.rows.reserve(node_count);
            slab.edges.reserve(lower_bound);
            for (slot, name) in node_names.iter().enumerate() {
                slab.node_order.insert(name.clone(), slot);
                slab.slot_names.push(Some(name.clone()));
                slab.node_attrs.push(AttrMap::new());
                slab.rows.push(IndexMap::new());
            }
            slab
        };

        let mut inserted = 0usize;
        for (left_idx, right_idx, key) in iterator {
            debug_assert!(left_idx < node_names.len());
            debug_assert!(right_idx < node_names.len());
            {
                use multigraph_storage::{CompactBucket, CompactKeys};
                let pair = (left_idx.min(right_idx), left_idx.max(right_idx));
                match fresh_slab.edges.entry(pair) {
                    indexmap::map::Entry::Occupied(mut bucket) => {
                        let _ = bucket.get_mut().merge(key, AttrMap::new());
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactBucket::One(key, AttrMap::new()));
                    }
                }
                match fresh_slab.rows[left_idx].entry(right_idx) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
                if left_idx != right_idx {
                    match fresh_slab.rows[right_idx].entry(left_idx) {
                        indexmap::map::Entry::Occupied(mut cell) => {
                            let _ = cell.get_mut().insert(key);
                        }
                        indexmap::map::Entry::Vacant(slot) => {
                            slot.insert(CompactKeys::One(key));
                        }
                    }
                }
                fresh_slab.edge_count += 1;
            }

            inserted += 1;
        }
        self.edge_count = fresh_slab.edge_count;
        if inserted > 0 || node_count > 0 {
            self.revision = self.revision.saturating_add(
                u64::try_from(inserted.saturating_add(node_count)).unwrap_or(u64::MAX),
            );
            self.record_decision(
                "extend_fresh_int_prefix_keyed_edges_unrecorded",
                0.0,
                false,
                vec![EvidenceTerm {
                    signal: "batch_edge_count".into(),
                    observed_value: count_evidence(inserted),
                    log_likelihood_ratio: -1.0,
                }],
            );
        }
        debug_assert_eq!(fresh_slab.edge_count, self.edge_count);
        self.storage = fresh_slab;
        inserted
    }

    /// Bulk-load attributed keyed edges for a freshly-created integer-indexed
    /// graph. The caller has already assigned NetworkX-compatible node labels
    /// and per-undirected-pair keys, so this avoids endpoint string hashing in
    /// the Python boundary layer while preserving the normal MultiGraph storage
    /// layout.
    #[must_use]
    pub fn extend_fresh_index_keyed_edges_with_attrs_unrecorded<I, N>(
        &mut self,
        nodes: N,
        edges: I,
    ) -> usize
    where
        I: IntoIterator<Item = (usize, usize, usize, AttrMap)>,
        N: IntoIterator<Item = String>,
    {
        if self.node_count() != 0 || self.edge_count() != 0 {
            return 0;
        }

        let node_labels: Vec<String> = nodes.into_iter().collect();
        let mut fresh_slab = {
            use multigraph_storage::MgSlabStorage;
            let mut slab = MgSlabStorage::new();
            slab.node_order.reserve(node_labels.len());
            slab.slot_names.reserve(node_labels.len());
            slab.node_attrs.reserve(node_labels.len());
            slab.rows.reserve(node_labels.len());
            for (slot, name) in node_labels.iter().enumerate() {
                slab.node_order.insert(name.clone(), slot);
                slab.slot_names.push(Some(name.clone()));
                slab.node_attrs.push(AttrMap::new());
                slab.rows.push(IndexMap::new());
            }
            slab
        };

        let node_count = node_labels.len();
        let mut inserted = 0usize;
        for (left_idx, right_idx, key, attrs) in edges {
            if node_labels.get(left_idx).is_none() {
                continue;
            }
            if node_labels.get(right_idx).is_none() {
                continue;
            }
            {
                use multigraph_storage::{CompactBucket, CompactKeys};
                let pair = (left_idx.min(right_idx), left_idx.max(right_idx));
                let is_new = match fresh_slab.edges.entry(pair) {
                    indexmap::map::Entry::Occupied(mut bucket) => {
                        bucket.get_mut().merge(key, attrs)
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactBucket::One(key, attrs));
                        true
                    }
                };
                if is_new {
                    fresh_slab.edge_count += 1;
                    inserted += 1;
                }
                match fresh_slab.rows[left_idx].entry(right_idx) {
                    indexmap::map::Entry::Occupied(mut cell) => {
                        let _ = cell.get_mut().insert(key);
                    }
                    indexmap::map::Entry::Vacant(slot) => {
                        slot.insert(CompactKeys::One(key));
                    }
                }
                if left_idx != right_idx {
                    match fresh_slab.rows[right_idx].entry(left_idx) {
                        indexmap::map::Entry::Occupied(mut cell) => {
                            let _ = cell.get_mut().insert(key);
                        }
                        indexmap::map::Entry::Vacant(slot) => {
                            slot.insert(CompactKeys::One(key));
                        }
                    }
                }
            }
        }

        self.edge_count = fresh_slab.edge_count;
        if node_count > 0 || inserted > 0 {
            self.revision = self.revision.saturating_add(
                u64::try_from(node_count.saturating_add(inserted)).unwrap_or(u64::MAX),
            );
            self.record_decision(
                "extend_fresh_index_keyed_edges_with_attrs_unrecorded",
                0.0,
                false,
                vec![
                    EvidenceTerm {
                        signal: "batch_node_count".into(),
                        observed_value: count_evidence(node_count),
                        log_likelihood_ratio: -1.0,
                    },
                    EvidenceTerm {
                        signal: "batch_edge_count".into(),
                        observed_value: count_evidence(inserted),
                        log_likelihood_ratio: -1.0,
                    },
                ],
            );
        }
        debug_assert_eq!(fresh_slab.edge_count, self.edge_count);
        self.storage = fresh_slab;
        inserted
    }

    fn add_edge_impl(
        &mut self,
        left: impl Into<String>,
        right: impl Into<String>,
        explicit_key: Option<usize>,
        attrs: AttrMap,
    ) -> Result<usize, GraphError> {
        let left = left.into();
        let right = right.into();
        // br-r37-c1-thp6w S4: revision on entry — a warm int-adjacency memo
        // keyed here is advanced across this mutation instead of invalidated.
        let prev_revision = self.revision;

        let unknown_feature = attrs
            .keys()
            .any(|key| key.starts_with("__fnx_incompatible"));
        let incompatibility_probability = if unknown_feature {
            1.0
        } else if left == right {
            0.22
        } else {
            0.08
        };

        // br-r37-c1-eo88t: the gate decision earns a ledger record only when it
        // REFUSES. A refusal returns from here, so the outcome record at the end
        // of this function never runs and the gate record is the whole audit
        // trail for the rejected mutation. On the allow path the outcome record
        // carries the same operation/mode/action/incompatibility_probability
        // plus strictly richer evidence, so recording the gate as well wrote two
        // near-identical records for every edge on the hottest mutation path.
        let action = self
            .runtime_policy
            .action_for(incompatibility_probability, unknown_feature);

        if action == DecisionAction::FailClosed || action == DecisionAction::FullValidate {
            self.record_decision(
                "add_edge",
                incompatibility_probability,
                unknown_feature,
                vec![EvidenceTerm {
                    signal: "unknown_incompatible_feature".into(),
                    observed_value: bool_evidence(unknown_feature),
                    log_likelihood_ratio: 12.0,
                }],
            );
            return Err(GraphError::FailClosed {
                operation: "add_edge",
                reason: "incompatible edge metadata".to_owned(),
            });
        }

        // br-r37-c1-wa1b9: internal autocreation files no record of its own —
        // see the undirected `Graph` sibling for the ruling.
        let mut left_autocreated = false;
        if !self.has_node(&left) {
            let _ = self.add_node_with_attrs_unrecorded(left.clone(), AttrMap::new());
            left_autocreated = true;
        }
        let mut right_autocreated = false;
        if left == right {
            right_autocreated = left_autocreated;
        } else if !self.has_node(&right) {
            let _ = self.add_node_with_attrs_unrecorded(right.clone(), AttrMap::new());
            right_autocreated = true;
        }

        // br-r37-c1-4c29a: resolve each endpoint to its slot ONCE. Both nodes
        // are guaranteed present by the autocreation above, and the six storage
        // calls below used to re-resolve BOTH endpoint strings independently —
        // `IndexMap<String, usize>::get_index_of` was 17.39% of the MultiGraph
        // build profile, the largest entry, ahead of the allocator. The
        // `_by_pair` variants take the slots and are otherwise identical.
        let left_slot = self
            .slab_store()
            .node_slot(&left)
            .expect("autocreated above");
        let right_slot = if left == right {
            left_slot
        } else {
            self.slab_store()
                .node_slot(&right)
                .expect("autocreated above")
        };

        let key = explicit_key.unwrap_or_else(|| {
            self.slab_store()
                .next_edge_key_by_pair(left_slot, right_slot)
        });
        let pair_was_present = self.slab_store().has_edge_by_pair(left_slot, right_slot);
        let changed = self
            .slab_store()
            .edge_attrs_by_pair(left_slot, right_slot, key)
            .is_none_or(|edge_attrs| {
                attrs
                    .iter()
                    .any(|(attr_key, value)| edge_attrs.get(attr_key) != Some(value))
            });
        let inserted = self
            .slab_store_mut()
            .add_keyed_edge_by_pair(left_slot, right_slot, key, attrs);
        if inserted {
            self.edge_count += 1;
        }
        let edge_attr_count = self
            .slab_store()
            .edge_attr_count_by_pair(left_slot, right_slot);
        if changed {
            self.revision = self.revision.saturating_add(1);
        }
        if self.revision != prev_revision {
            self.advance_int_adj_memo(
                prev_revision,
                IntAdjEdgeDelta::Add {
                    left: &left,
                    right: &right,
                    left_new: left_autocreated,
                    right_new: right_autocreated,
                    pair_new: !pair_was_present,
                },
            );
        }

        self.record_decision(
            "add_edge",
            incompatibility_probability,
            unknown_feature,
            vec![
                EvidenceTerm {
                    signal: "edge_key".into(),
                    observed_value: key.to_string().into(),
                    log_likelihood_ratio: -2.0,
                },
                EvidenceTerm {
                    signal: "edge_attr_count".into(),
                    observed_value: count_evidence(edge_attr_count),
                    log_likelihood_ratio: -2.0,
                },
                EvidenceTerm {
                    signal: "left_autocreated".into(),
                    observed_value: bool_evidence(left_autocreated),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "right_autocreated".into(),
                    observed_value: bool_evidence(right_autocreated),
                    log_likelihood_ratio: -1.25,
                },
            ],
        );

        Ok(key)
    }

    /// br-r37-c1-sjf4t: overwrite the attribute map for an existing
    /// (u, v, key) edge. Returns whether the edge existed.
    pub fn replace_edge_attrs(
        &mut self,
        left: &str,
        right: &str,
        key: usize,
        attrs: AttrMap,
    ) -> bool {
        let Some(existing) = self.slab_store().edge_attrs(left, right, key) else {
            return false;
        };
        let changed = *existing != attrs;
        if changed {
            let replaced = self
                .slab_store_mut()
                .replace_edge_attrs(left, right, key, attrs);
            debug_assert!(replaced, "slab edge disappeared during replacement");
            self.revision = self.revision.saturating_add(1);
        }
        true
    }

    /// br-r37-c1-sjf4t: overwrite the attribute map for an existing node.
    pub fn replace_node_attrs(&mut self, node: &str, attrs: AttrMap) -> bool {
        let Some(existing) = self.slab_store().node_attrs_for(node) else {
            return false;
        };
        let changed = *existing != attrs;
        if changed {
            self.slab_store_mut().replace_node_attrs(node, attrs);
            self.revision = self.revision.saturating_add(1);
        }
        true
    }

    pub fn remove_edge(&mut self, left: &str, right: &str, key: Option<usize>) -> bool {
        // br-r37-c1-thp6w S4: revision on entry — a warm int-adjacency memo
        // keyed here is advanced across this mutation instead of invalidated.
        let prev_revision = self.revision;
        let removal_key = key.or_else(|| {
            self.slab_store()
                .edge_keys_iter(left, right)
                .and_then(|keys| keys.last().copied())
        });

        let Some(removal_key) = removal_key else {
            return false;
        };

        if !self
            .slab_store_mut()
            .remove_edge(left, right, Some(removal_key))
        {
            return false;
        }
        self.edge_count -= 1;
        let pair_gone = !self.slab_store().has_edge(left, right);
        self.revision = self.revision.saturating_add(1);
        self.advance_int_adj_memo(
            prev_revision,
            IntAdjEdgeDelta::Remove {
                left,
                right,
                pair_gone,
            },
        );
        true
    }

    pub fn clear_edges(&mut self) {
        if self.edge_count == 0 {
            return;
        }

        self.slab_store_mut().clear_edges();
        self.edge_count = 0;
        self.revision = self.revision.saturating_add(1);
    }

    pub fn remove_node(&mut self, node: &str) -> bool {
        if !self.has_node(node) {
            return false;
        }

        let removed = self.slab_store_mut().remove_node(node);
        debug_assert!(removed, "node disappeared during remove_node");
        self.edge_count = self.slab_store().edge_count;
        self.revision = self.revision.saturating_add(1);
        true
    }

    /// br-r37-c1-mgrnf: batch node removal — the amortised analogue of
    /// `remove_node`. `MultiGraph::remove_node` pays two O(|V|) `shift_remove`s
    /// (the `adjacency` and `nodes` IndexMaps preserve insertion order), so a
    /// caller loop of `k` removals was O(k·|V|). This does each pass ONCE via
    /// `retain` — O(|V|+|E|) total, matching the simple-`Graph` batch
    /// (`Graph::remove_nodes_from`) that the directed types already carry.
    /// Returns `(removed_node_count, removed_edge_instance_count)`.
    pub fn remove_nodes_from<'a, I>(&mut self, nodes: I) -> (usize, usize)
    where
        I: IntoIterator<Item = &'a str>,
    {
        let (removed_nodes, removed_edges) = self.slab_store_mut().remove_nodes_from(nodes);
        if removed_nodes == 0 {
            return (0, 0);
        }
        self.edge_count = self.slab_store().edge_count;
        self.revision = self
            .revision
            .saturating_add(u64::try_from(removed_nodes).unwrap_or(u64::MAX));
        (removed_nodes, removed_edges)
    }

    #[must_use]
    pub fn edges_ordered(&self) -> Vec<MultiEdgeSnapshot> {
        self.slab_store()
            .edges_ordered_borrowed()
            .into_iter()
            .map(|(left, right, key, attrs)| MultiEdgeSnapshot {
                left: left.to_owned(),
                right: right.to_owned(),
                key,
                attrs: attrs.clone(),
            })
            .collect()
    }

    #[must_use]
    pub fn edges_ordered_borrowed(&self) -> Vec<(&str, &str, usize, &AttrMap)> {
        self.slab_store().edges_ordered_borrowed()
    }

    /// br-r37-c1-wsize (cc): integer `size(weight)` from the store — the
    /// multigraph twin of `Graph::weighted_size_int`. Each parallel edge is one
    /// bucket entry in `self.edges` and contributes its weight once (size halves
    /// degree's double count); a self-loop key is one stored edge counted once.
    /// Returns `None` on any non-integer weight (caller uses the exact
    /// float/PyObject degree path); missing weight defaults to nx's int `1`.
    #[must_use]
    pub fn weighted_size_int(&self, weight: &str) -> Option<i128> {
        self.slab_store().weighted_size_int(weight)
    }

    #[must_use]
    pub fn edges_ordered_indices_borrowed(&self) -> Vec<(usize, usize, usize, &AttrMap)> {
        self.slab_store().edges_ordered_indices_borrowed()
    }

    #[must_use]
    pub fn snapshot(&self) -> MultiGraphSnapshot {
        self.slab_store().snapshot(self.mode)
    }

    fn record_decision(
        &mut self,
        operation: &'static str,
        incompatibility_probability: f64,
        unknown_incompatible_feature: bool,
        evidence: Vec<EvidenceTerm>,
    ) -> DecisionAction {
        let action = self
            .runtime_policy
            .action_for(incompatibility_probability, unknown_incompatible_feature);
        self.runtime_policy.record(
            operation,
            action,
            incompatibility_probability,
            "argmin expected loss over {allow,full_validate,fail_closed}",
            evidence,
        );
        action
    }
}

#[cfg(test)]
mod tests {
    /// br-r37-c1-2ndmw: `has_edge_by_indices` must agree with the string path
    /// for EVERY pair, including after removals move the positions away from the
    /// slots.
    ///
    /// The implementation no longer resolves positions back to names; it
    /// converts position to slot and probes the slot-keyed edge map directly.
    /// That is only correct if the slot at a position is the slot the name at
    /// that position maps to, which is an IndexMap invariant rather than
    /// something this crate enforces — so it is asserted here exhaustively
    /// rather than assumed, against the string lookup as the oracle.
    #[test]
    fn multigraph_has_edge_by_indices_matches_the_string_path_across_removals() {
        let mut g = MultiGraph::new(CompatibilityMode::Strict);
        let names: Vec<String> = (0..8).map(|i| format!("n{i}")).collect();
        for name in &names {
            g.add_node(name.as_str());
        }
        for (a, b) in [(0, 1), (2, 3), (3, 5), (5, 7), (0, 7), (4, 4)] {
            g.add_edge(names[a].as_str(), names[b].as_str()).unwrap();
        }

        // Removals chosen to shift positions out from under the slots, plus a
        // re-add so a reused slot is exercised too.
        for step in 0..4 {
            if step == 1 {
                g.remove_node("n0");
            }
            if step == 2 {
                g.remove_node("n4");
            }
            if step == 3 {
                g.add_node("n8");
                g.add_edge("n8", "n3").unwrap();
            }
            let live: Vec<String> = g.nodes_ordered().iter().map(|s| (*s).to_string()).collect();
            for (li, left) in live.iter().enumerate() {
                for (ri, right) in live.iter().enumerate() {
                    let by_index = g.has_edge_by_indices(li, ri);
                    let by_name = g.has_edge(left.as_str(), right.as_str());
                    assert_eq!(
                        by_index, by_name,
                        "step {step}: has_edge_by_indices({li}, {ri}) disagreed with \
                         has_edge({left:?}, {right:?})"
                    );
                }
            }
            // Out-of-range positions must answer false, not panic.
            let n = live.len();
            assert!(!g.has_edge_by_indices(n, 0));
            assert!(!g.has_edge_by_indices(0, n + 50));
        }
    }

    /// br-r37-c1-2ndmw: THE SLOT AND THE POSITION ARE DIFFERENT INDEX SPACES,
    /// and confusing them is a silent wrong-answer bug rather than a type error.
    ///
    /// `MultiGraph::get_node_index` returns `node_order.get_index_of(name)` — a
    /// POSITION in the IndexMap. `MgSlabStorage::has_edge_by_pair` is keyed on
    /// `node_order.get(name)` — the stored SLOT. On a graph that has never had a
    /// node removed these are equal, which is precisely what makes the confusion
    /// dangerous: every fresh-graph test passes and the divergence only appears
    /// after a removal, as a `false` from an edge that exists.
    ///
    /// WHY THIS TEST EXISTS. `MultiGraph::has_edge_by_indices` reads like an
    /// O(1) index fast path — it is named like one and documented as a "Mirror
    /// of `Graph::has_edge_by_indices`", which genuinely is one
    /// (`edges.contains_key(&canon_pair)`). It is not. It resolves both indices
    /// back to NAMES and calls the string `has_edge`, so it is O(node key
    /// length). Anyone optimising the multigraph row probe will find the
    /// slot-keyed `has_edge_by_pair`, reach for a cached `get_node_index`, and
    /// ship a read that returns the wrong answer after any node removal. That
    /// was attempted on this pane and stopped by this test.
    ///
    /// The assertions below pin all three facts: the positions move, the
    /// position-keyed lookup is WRONG, and the slot-keyed lookup is RIGHT.
    #[test]
    fn multigraph_node_slot_and_position_are_distinct_index_spaces() {
        let mut g = MultiGraph::new(CompatibilityMode::Strict);
        for name in ["n0", "n1", "n2", "n3"] {
            g.add_node(name);
        }
        g.add_edge("n2", "n3").unwrap();
        assert!(g.has_edge("n2", "n3"));

        // Before any removal the two spaces agree, which is the trap.
        let pos_before = (g.get_node_index("n2"), g.get_node_index("n3"));
        let slot_before = (
            g.slab_store().node_slot("n2"),
            g.slab_store().node_slot("n3"),
        );
        assert_eq!(
            pos_before, slot_before,
            "on a graph with no removals the position and the slot coincide — \
             this is why confusing them survives fresh-graph testing"
        );

        g.remove_node("n0");

        let (Some(p2), Some(p3)) = (g.get_node_index("n2"), g.get_node_index("n3")) else {
            panic!("nodes vanished after removing an unrelated node");
        };
        let (Some(s2), Some(s3)) = (
            g.slab_store().node_slot("n2"),
            g.slab_store().node_slot("n3"),
        ) else {
            panic!("slots vanished after removing an unrelated node");
        };

        // The edge is untouched: only an unrelated node was removed.
        assert!(
            g.has_edge("n2", "n3"),
            "removing an unrelated node must not remove this edge"
        );

        // The positions MOVED and the slots did not follow them.
        assert_ne!(
            (p2, p3),
            (s2, s3),
            "after a removal the position and slot spaces must diverge; if this \
             ever holds, re-derive whether the fast path below is now safe"
        );

        // THE TRAP: position indices through the slot-keyed edge map are WRONG.
        assert!(
            !g.slab_store().has_edge_by_pair(p2, p3),
            "position indices happened to answer correctly here — that is luck, \
             not a contract; do not take it as licence to feed get_node_index() \
             into has_edge_by_pair()"
        );

        // THE CORRECT SPACE: slots answer correctly.
        assert!(
            g.slab_store().has_edge_by_pair(s2, s3),
            "slot indices must agree with the string lookup"
        );
    }

    /// br-r37-c1-f3i50: two helpers on the SAME struct use DIFFERENT index
    /// spaces, so you cannot infer the space from where a function lives.
    ///
    /// The test above pins that `MgSlabStorage::has_edge_by_pair` is SLOT-keyed.
    /// `MgSlabStorage::node_index_matches_int` sits in the same `impl`, is named
    /// in the same style, and is POSITION-keyed: it calls
    /// `node_order.get_index(index)`, which is the IndexMap POSITION, not the
    /// stored slot. So it composes correctly with `MultiGraph::get_node_index`
    /// and would be WRONG to pair with `has_edge_by_pair`.
    ///
    /// I got this backwards first: the helper delegates to `slab_store()`, which
    /// reads like slot territory, and I wrote the opposite assertion and watched
    /// it fail. Reading the body is the only way to know. That is exactly why
    /// this is pinned rather than left to the next reader's inference.
    ///
    /// SECOND FACT, and the one that bites: once a node is removed, name and
    /// position stop agreeing for EVERY surviving node, so this predicate goes
    /// uniformly false on a graph whose int nodes are all still present. A
    /// caller treating it as "is int N in the graph" would answer no for nodes
    /// that plainly exist.
    #[test]
    fn multigraph_node_index_matches_int_is_position_keyed_not_slot_keyed() {
        let mut g = MultiGraph::new(CompatibilityMode::Strict);
        for name in ["0", "1", "2", "3"] {
            g.add_node(name);
        }

        // Fresh graph: name, position and slot all coincide — the trap state.
        for idx in 0..4 {
            assert!(
                g.node_index_matches_int(idx),
                "on a fresh graph int {idx} sits at position {idx}"
            );
            assert_eq!(g.get_node_index(&idx.to_string()), Some(idx));
            assert_eq!(g.slab_store().node_slot(&idx.to_string()), Some(idx));
        }

        g.remove_node("0");

        // Node "3" survives; its SLOT is unchanged and its POSITION has moved.
        let slot_3 = g.slab_store().node_slot("3").expect("node 3 survives");
        let pos_3 = g.get_node_index("3").expect("node 3 survives");
        assert_eq!(slot_3, 3, "slots are stable across removals");
        assert_eq!(pos_3, 2, "positions compact after a removal");
        assert_ne!(slot_3, pos_3, "the two spaces have diverged");

        // POSITION-KEYED: asking with the out-of-range slot is simply absent,
        // which is what proves the argument is a position and not a slot — a
        // slot-keyed predicate would have answered for the live node 3.
        assert!(
            !g.node_index_matches_int(slot_3),
            "slot {slot_3} is past the end of a 3-node order, so a position-keyed              predicate reports absent; if this ever answers true the argument has              become slot-keyed and every caller must be re-derived"
        );

        // And the predicate is now uniformly false, because no surviving name
        // equals its position — even though all three nodes are present.
        for idx in 0..3 {
            assert!(
                !g.node_index_matches_int(idx),
                "after the removal no name equals its position, so int {idx} must                  not report as sitting at position {idx}"
            );
            assert!(
                g.has_node(&(idx + 1).to_string()),
                "...while the node itself is still very much present"
            );
        }
    }

    use super::{AttrMap, Graph, GraphError, MultiGraph};
    use fnx_runtime::{CgseValue, CompatibilityMode, DecisionAction, DecisionRecord};
    use proptest::prelude::*;
    use std::collections::BTreeSet;

    /// br-r37-c1-addedgenewedge parity: the new_edge-gated adjacency push must never create a
    /// duplicate adjacency entry, even under duplicate edges / self-loops / edges added in both
    /// orientations. (The old `!adj_indices[..].contains(..)` guard prevented dups; the O(1)
    /// `new_edge` flag must too, since adj-membership ⟺ edge existence.)
    #[test]
    fn add_edge_newedge_no_duplicate_adjacency() {
        let mut g = Graph::strict();
        let _ = g.add_edge("h", "a");
        let _ = g.add_edge("h", "b");
        let _ = g.add_edge("h", "a"); // exact duplicate
        let _ = g.add_edge("a", "h"); // reversed duplicate
        let _ = g.add_edge("s", "s"); // self-loop
        let _ = g.add_edge("s", "s"); // duplicate self-loop
        let n = g.node_count();
        for i in 0..n {
            if let Some(row) = g.neighbors_indices(i) {
                let uniq: BTreeSet<usize> = row.iter().copied().collect();
                assert_eq!(
                    uniq.len(),
                    row.len(),
                    "node {i} has duplicate adjacency entries"
                );
            }
        }
        // Unique edges: h-a, h-b, s-s.
        assert_eq!(
            g.edge_count(),
            3,
            "duplicate/reversed adds must not create new edges"
        );
    }

    /// br-r37-c1-addedgenewedge: paired-interleaved median A/B for the exact change — building a
    /// high-degree hub's adjacency row. The OLD code guarded each push with
    /// `adj_indices[hub].contains(&x)` (an O(row.len) linear rescan → O(n²) to build a star via
    /// add_edge); the NEW code pushes on the O(1) `new_edge` flag → O(n). This isolates the two
    /// changed lines; the rest of add_edge is O(1)/edge in both arms (so the full-function win is
    /// this, diluted by that per-edge overhead). `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib add_edge_newedge_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn add_edge_newedge_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        let n = 40000usize;
        let time = |use_new: bool| -> f64 {
            let t0 = Instant::now();
            let mut row: Vec<usize> = Vec::with_capacity(n);
            for i in 0..n {
                if use_new || !row.contains(&i) {
                    row.push(i);
                }
            }
            black_box(&row);
            t0.elapsed().as_secs_f64()
        };
        for _ in 0..2 {
            black_box(time(true));
            black_box(time(false));
        }
        let median = |v: &[f64]| {
            let mut s = v.to_vec();
            s.sort_by(|a, b| a.partial_cmp(b).unwrap());
            s[s.len() / 2]
        };
        let rounds = 41usize;
        let paired = |cand: bool, base: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for r in 0..rounds {
                let (tb, tc) = if r % 2 == 0 {
                    let b = time(base);
                    let c = time(cand);
                    (b, c)
                } else {
                    let c = time(cand);
                    let b = time(base);
                    (b, c)
                };
                v.push(tb / tc);
            }
            v
        };
        let report = |name: &str, ratios: &[f64]| {
            let wins = ratios.iter().filter(|&&r| r > 1.0).count();
            let mut sorted = ratios.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "ADDEDGE_AB {name}: median={:.4}x win_rate={wins}/{rounds} p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!("ADDEDGE_AB adj-row push n={n} rounds={rounds} (>1 = new_edge-flag faster)");
        report("NEWEDGE_vs_contains", &paired(true, false));
        report("NULL_new_vs_new", &paired(true, true));
    }

    /// br-r37-c1-degselfloopidx: parity + paired-interleaved A/B for `degree_by_index` — the O(1)
    /// `has_edge_by_indices(idx,idx)` self-loop check vs the pre-lever O(degree)
    /// `adj_indices[idx].contains(&idx)` rescan, over a degree histogram of a dense graph. Byte-exact
    /// parity (also vs the `&str` `degree`). `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib degree_by_index_selfloop_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn degree_by_index_selfloop_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        let n = 20000usize;
        let deg = 20usize;
        let mut g = Graph::strict();
        for i in 0..n {
            let _ = g.add_node(format!("n{i}"));
        }
        for i in 0..n {
            for step in 1..=deg {
                let _ = g.add_edge(format!("n{i}"), format!("n{}", (i + step) % n));
            }
        }
        for i in (0..n).step_by(1000) {
            let _ = g.add_edge(format!("n{i}"), format!("n{i}"));
        }

        // Byte-exact parity: new == old (row.contains) == the &str degree, incl. self-loop nodes.
        for idx in 0..g.node_count() {
            let new = g.degree_by_index(idx);
            let old = g.adj_indices[idx].len() + usize::from(g.adj_indices[idx].contains(&idx));
            assert_eq!(new, old, "degree_by_index parity vs row.contains at {idx}");
            assert_eq!(
                new,
                g.degree(&format!("n{idx}")),
                "degree_by_index parity vs &str degree at {idx}"
            );
        }

        let time = |use_new: bool| -> f64 {
            let t0 = Instant::now();
            let mut sum = 0usize;
            for idx in 0..g.node_count() {
                sum += if use_new {
                    g.degree_by_index(idx)
                } else {
                    g.adj_indices[idx].len() + usize::from(g.adj_indices[idx].contains(&idx))
                };
            }
            black_box(sum);
            t0.elapsed().as_secs_f64()
        };
        for _ in 0..3 {
            black_box(time(true));
            black_box(time(false));
        }
        let median = |v: &[f64]| {
            let mut s = v.to_vec();
            s.sort_by(|a, b| a.partial_cmp(b).unwrap());
            s[s.len() / 2]
        };
        let rounds = 41usize;
        let paired = |cand: bool, base: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for r in 0..rounds {
                let (tb, tc) = if r % 2 == 0 {
                    let b = time(base);
                    let c = time(cand);
                    (b, c)
                } else {
                    let c = time(cand);
                    let b = time(base);
                    (b, c)
                };
                v.push(tb / tc);
            }
            v
        };
        let report = |name: &str, ratios: &[f64]| {
            let wins = ratios.iter().filter(|&&r| r > 1.0).count();
            let mut sorted = ratios.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "DEGIDX_AB {name}: median={:.4}x win_rate={wins}/{rounds} p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!(
            "DEGIDX_AB degree histogram n={n} deg={deg} rounds={rounds} (>1 = O(1) has_edge faster)"
        );
        report("HASEDGE_vs_contains", &paired(true, false));
        report("NULL_new_vs_new", &paired(true, true));
    }

    /// br-r37-c1-isoedgecount: paired-interleaved A/B for the graph-isomorphism early-out edge
    /// count check. `undirected_isomorphism_mappings` / `directed_isomorphism_mappings` (fnx-python,
    /// reached by public `is_isomorphic`) compared edge COUNTS via `edges_ordered().len()`, which
    /// materialises a full `Vec<EdgeSnapshot>` (two owned Strings per edge) only to read its length;
    /// the O(1) `edge_count()` (== `self.edges.len()`) is byte-identical. This times the exact
    /// early-out compare on the non-isomorphic same-node / different-edge case (where the check is
    /// the dominant cost). Byte-exact parity asserted (`edge_count() == edges_ordered().len()`).
    /// `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib iso_edge_count_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn iso_edge_count_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        let n = 4000usize;
        let deg = 25usize;
        let build = |steps: usize| -> Graph {
            let mut g = Graph::strict();
            for i in 0..n {
                let _ = g.add_node(format!("n{i}"));
            }
            for i in 0..n {
                for step in 1..=steps {
                    let _ = g.add_edge(format!("n{i}"), format!("n{}", (i + step) % n));
                }
            }
            g
        };
        // Same node count, DIFFERENT edge count → the early-out returns at the edge-count compare.
        let g1 = build(deg);
        let g2 = build(deg - 1);

        // Byte-exact parity: edge_count() must equal edges_ordered().len() for both graphs.
        assert_eq!(
            g1.edge_count(),
            g1.edges_ordered().len(),
            "edge_count parity g1"
        );
        assert_eq!(
            g2.edge_count(),
            g2.edges_ordered().len(),
            "edge_count parity g2"
        );
        assert_ne!(
            g1.edge_count(),
            g2.edge_count(),
            "workload must exercise the differing-count early-out"
        );

        let time = |use_new: bool| -> f64 {
            let t0 = Instant::now();
            let mut acc = 0usize;
            for _ in 0..8 {
                let differ = if use_new {
                    g1.edge_count() != g2.edge_count()
                } else {
                    g1.edges_ordered().len() != g2.edges_ordered().len()
                };
                acc += usize::from(differ);
            }
            black_box(acc);
            t0.elapsed().as_secs_f64()
        };
        for _ in 0..3 {
            black_box(time(true));
            black_box(time(false));
        }
        let median = |v: &[f64]| {
            let mut s = v.to_vec();
            s.sort_by(|a, b| a.partial_cmp(b).unwrap());
            s[s.len() / 2]
        };
        let rounds = 41usize;
        let paired = |cand: bool, base: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for r in 0..rounds {
                let (tb, tc) = if r % 2 == 0 {
                    let b = time(base);
                    let c = time(cand);
                    (b, c)
                } else {
                    let c = time(cand);
                    let b = time(base);
                    (b, c)
                };
                v.push(tb / tc);
            }
            v
        };
        let report = |name: &str, ratios: &[f64]| {
            let wins = ratios.iter().filter(|&&r| r > 1.0).count();
            let mut sorted = ratios.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "ISOEDGE_AB {name}: median={:.4}x win_rate={wins}/{rounds} p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!(
            "ISOEDGE_AB same-node/different-edge early-out n={n} deg={deg} rounds={rounds} (>1 = edge_count faster)"
        );
        report("EDGECOUNT_vs_edgesordered", &paired(true, false));
        report("NULL_new_vs_new", &paired(true, true));
    }

    /// br-r37-c1-selfloopidx: paired-interleaved A/B for the `nodes_with_selfloops` per-node self-loop
    /// probe (feeds `number_of_selfloops` / `selfloop_edges` / `nodes_with_selfloops`, many callers).
    /// The kernel checked `has_edge(node, node)` — resolving BOTH `&str` endpoints via
    /// `edge_pair_key` (two String-hash lookups per node) — vs the index probe
    /// `has_edge_by_indices(i, i)` (a direct integer `canon_pair` + `contains_key`, no String
    /// resolution). Byte-exact parity asserted (same self-loop node set). `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib nodes_selfloop_idx_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn nodes_selfloop_idx_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        // 40k nodes, ring-of-chords, NO self-loops (the common case: every node is probed and misses).
        let n = 40_000usize;
        let deg = 10usize;
        let mut g = Graph::strict();
        for i in 0..n {
            let _ = g.add_node(i.to_string());
        }
        for i in 0..n {
            for step in 1..=deg {
                let _ = g.add_edge(i.to_string(), ((i + step) % n).to_string());
            }
        }

        let names = g.nodes_ordered();
        let old_scan =
            |g: &Graph| -> usize { names.iter().filter(|&&node| g.has_edge(node, node)).count() };
        let new_scan = |g: &Graph| -> usize {
            (0..names.len())
                .filter(|&i| g.has_edge_by_indices(i, i))
                .count()
        };
        assert_eq!(
            old_scan(&g),
            new_scan(&g),
            "nodes_with_selfloops parity (self-loop count)"
        );

        let time = |cand: bool| -> f64 {
            let t0 = Instant::now();
            let c = if cand { new_scan(&g) } else { old_scan(&g) };
            black_box(c);
            t0.elapsed().as_secs_f64()
        };
        for _ in 0..3 {
            black_box(time(true));
            black_box(time(false));
        }
        let median = |v: &[f64]| {
            let mut s = v.to_vec();
            s.sort_by(|a, b| a.partial_cmp(b).unwrap());
            s[s.len() / 2]
        };
        let rounds = 61usize;
        let paired = |cand: bool, base: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for r in 0..rounds {
                let (tb, tc) = if r % 2 == 0 {
                    let b = time(base);
                    let c = time(cand);
                    (b, c)
                } else {
                    let c = time(cand);
                    let b = time(base);
                    (b, c)
                };
                v.push(tb / tc);
            }
            v
        };
        let report = |name: &str, ratios: &[f64]| {
            let wins = ratios.iter().filter(|&&r| r > 1.0).count();
            let mut sorted = ratios.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "SELFLOOPIDX_AB {name}: median={:.4}x win_rate={wins}/{rounds} p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!(
            "SELFLOOPIDX_AB nodes_with_selfloops n={n} deg={deg} rounds={rounds} (>1 = index probe faster)"
        );
        report("HASEDGEIDX_vs_hasedge", &paired(true, false));
        report("NULL_new_vs_new", &paired(true, true));
    }

    /// br-r37-c1-numselfidx: paired-interleaved A/B for `number_of_selfloops` (feeds the is_planar
    /// dense-graph `planarity_euler_reject` fast path). The kernel counted self-loops with
    /// `edges_ordered().filter(|e| e.left == e.right).count()` — materialising a full
    /// `Vec<EdgeSnapshot>` (two owned Strings + an attr clone PER edge) — vs the integer per-node
    /// probe `(0..n).filter(|i| has_edge_by_indices(i, i)).count()` (no allocation). Byte-exact parity
    /// asserted (same self-loop count). `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib number_of_selfloops_idx_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn number_of_selfloops_idx_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        // Dense-ish ring-of-chords, ~20k nodes * 20 = ~200k edges, no self-loops (the count is 0 and
        // the old arm materialises the whole edge Vec anyway).
        let n = 20_000usize;
        let deg = 20usize;
        let mut g = Graph::strict();
        for i in 0..n {
            let _ = g.add_node(i.to_string());
        }
        for i in 0..n {
            for step in 1..=deg {
                let _ = g.add_edge(i.to_string(), ((i + step) % n).to_string());
            }
        }

        let old_count = |g: &Graph| -> usize {
            g.edges_ordered()
                .iter()
                .filter(|e| e.left == e.right)
                .count()
        };
        let new_count = |g: &Graph| -> usize {
            (0..g.node_count())
                .filter(|&i| g.has_edge_by_indices(i, i))
                .count()
        };
        assert_eq!(old_count(&g), new_count(&g), "number_of_selfloops parity");

        let time = |cand: bool| -> f64 {
            let t0 = Instant::now();
            let c = if cand { new_count(&g) } else { old_count(&g) };
            black_box(c);
            t0.elapsed().as_secs_f64()
        };
        for _ in 0..3 {
            black_box(time(true));
            black_box(time(false));
        }
        let median = |v: &[f64]| {
            let mut s = v.to_vec();
            s.sort_by(|a, b| a.partial_cmp(b).unwrap());
            s[s.len() / 2]
        };
        let rounds = 61usize;
        let paired = |cand: bool, base: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for r in 0..rounds {
                let (tb, tc) = if r % 2 == 0 {
                    let b = time(base);
                    let c = time(cand);
                    (b, c)
                } else {
                    let c = time(cand);
                    let b = time(base);
                    (b, c)
                };
                v.push(tb / tc);
            }
            v
        };
        let report = |name: &str, ratios: &[f64]| {
            let wins = ratios.iter().filter(|&&r| r > 1.0).count();
            let mut sorted = ratios.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!(
                "NUMSELFIDX_AB {name}: median={:.4}x win_rate={wins}/{rounds} p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!(
            "NUMSELFIDX_AB number_of_selfloops n={n} deg={deg} rounds={rounds} (>1 = index count faster)"
        );
        report("INDEXCOUNT_vs_edgesordered", &paired(true, false));
        report("NULL_new_vs_new", &paired(true, true));
    }

    /// br-r37-c1-kneserpush parity: removing the redundant `adj_indices.contains` guards under the
    /// `seen.insert(pair)` new-pair guard must keep the Kneser build byte-identical — correct
    /// node/edge counts and NO duplicate adjacency entries. (Same lever + adj_indices.push operation
    /// as br-r37-c1-addedgenewedge, whose A/B measured the O(degree)→O(1) win.)
    #[test]
    fn kneser_push_no_duplicate_adjacency() {
        // Kneser(10,3): C(10,3)=120 nodes, degree C(7,3)=35, edges = 120*35/2 = 2100.
        let g = Graph::kneser(CompatibilityMode::Strict, 10, 3);
        assert_eq!(g.node_count(), 120, "C(10,3) nodes");
        assert_eq!(g.edge_count(), 2100, "120*35/2 Kneser edges");
        let mut total_deg = 0usize;
        for (i, row) in g.adj_indices.iter().enumerate() {
            let uniq: BTreeSet<usize> = row.iter().copied().collect();
            assert_eq!(
                uniq.len(),
                row.len(),
                "node {i} has duplicate adjacency entries"
            );
            assert_eq!(row.len(), 35, "Kneser(10,3) is 35-regular");
            total_deg += row.len();
        }
        assert_eq!(total_deg, 2 * 2100, "handshake: sum of degrees == 2|E|");
    }

    fn node_name(id: u8) -> String {
        format!("n{}", id % 8)
    }

    fn canonical_edge(left: &str, right: &str) -> (String, String) {
        if left <= right {
            (left.to_owned(), right.to_owned())
        } else {
            (right.to_owned(), left.to_owned())
        }
    }

    /// br-r37-c1-thp6w slice 1 INVARIANT: the cached integer adjacency
    /// (`with_int_adjacency`) must equal, byte-for-byte, a fresh derivation from the
    /// authoritative stable-slot rows — row `i` == `[get_node_index(v) for v in
    /// neighbors_iter(node_i)]` — for the CURRENT graph state. Because the memo is keyed on
    /// `revision` + explicitly cleared by `apply_row_orders`, calling this after a mutation
    /// (with a prior populating read) catches any mutation path that fails to invalidate.
    fn assert_int_adjacency_matches(g: &MultiGraph) {
        let expected: Vec<Vec<usize>> = g
            .nodes_ordered()
            .iter()
            .map(|name| {
                g.neighbors_iter(name).map_or_else(Vec::new, |it| {
                    it.map(|v| g.get_node_index(v).unwrap()).collect()
                })
            })
            .collect();
        g.with_int_adjacency(|adj| {
            assert_eq!(
                adj,
                expected.as_slice(),
                "int adjacency must mirror the stable-slot rows exactly"
            );
        });
    }

    #[test]
    fn thp6w_int_adjacency_invariant_across_mutations() {
        let mut g = MultiGraph::strict();
        for i in 0..8 {
            g.add_node(format!("n{i}"));
        }
        // Edges incl. parallels and a self-loop.
        let _ = g.add_edge("n0", "n1");
        let _ = g.add_edge("n0", "n1"); // parallel
        let _ = g.add_edge("n1", "n2");
        let _ = g.add_edge("n2", "n3");
        let _ = g.add_edge("n3", "n0");
        let _ = g.add_edge("n4", "n4"); // self-loop
        let _ = g.add_edge("n5", "n6");
        // Populate the memo, then verify.
        assert_int_adjacency_matches(&g);

        // read-mutate-read for EACH mutation kind: a stale memo would fail the re-check.
        // add_node
        assert_int_adjacency_matches(&g);
        g.add_node("n9");
        assert_int_adjacency_matches(&g);
        // add_edge (new neighbor -> row grows)
        assert_int_adjacency_matches(&g);
        let _ = g.add_edge("n9", "n0");
        assert_int_adjacency_matches(&g);
        // parallel add_edge (row unchanged, content bumps revision)
        assert_int_adjacency_matches(&g);
        let _ = g.add_edge("n9", "n0");
        assert_int_adjacency_matches(&g);
        // remove one parallel edge (row must stay; neighbor still present)
        assert_int_adjacency_matches(&g);
        assert!(g.remove_edge("n0", "n1", None));
        assert_int_adjacency_matches(&g);
        // remove last edge of a pair (neighbor drops from both rows)
        assert_int_adjacency_matches(&g);
        assert!(g.remove_edge("n5", "n6", None));
        assert_int_adjacency_matches(&g);
        // remove_node (renumber: indices shift down)
        assert_int_adjacency_matches(&g);
        assert!(g.remove_node("n2"));
        assert_int_adjacency_matches(&g);
        // ORDER-ONLY change via the copy walk reorder (does NOT bump revision — the
        // apply_row_orders cache-clear is what keeps this correct).
        assert_int_adjacency_matches(&g);
        g.reorder_rows_for_nx_copy_walk();
        assert_int_adjacency_matches(&g);
        // clear_edges
        assert_int_adjacency_matches(&g);
        g.clear_edges();
        assert_int_adjacency_matches(&g);
    }

    /// br-r37-c1-thp6w S4: the memo is keyed at the CURRENT revision without any
    /// intervening read — i.e. the mutation advanced it in place rather than
    /// leaving it stale for the next `with_int_adjacency` rebuild.
    fn int_adj_memo_is_warm(g: &MultiGraph) -> bool {
        g.int_adj_cache
            .0
            .read()
            .expect("int_adj_cache poisoned")
            .as_ref()
            .is_some_and(|(rev, _)| *rev == g.revision)
    }

    /// br-r37-c1-thp6w S4 INVARIANT: single-edge `add_edge`/`remove_edge` must
    /// ADVANCE a warm integer-adjacency memo across the mutation (no rebuild),
    /// and the advanced rows must equal a fresh derivation from the String
    /// adjacency after every step. Unhandled mutation kinds (`remove_node`)
    /// must still leave the memo stale so the lazy rebuild path takes over.
    #[test]
    fn thp6w_s4_single_edge_mutations_advance_warm_memo() {
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        assert_int_adjacency_matches(&g); // populate the memo

        // new neighbor with an auto-created right endpoint
        let _ = g.add_edge("b", "c");
        assert!(
            int_adj_memo_is_warm(&g),
            "add_edge must advance, not invalidate"
        );
        assert_int_adjacency_matches(&g);
        // both endpoints auto-created
        let _ = g.add_edge("d", "e");
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // self-loop on an auto-created node
        let _ = g.add_edge("f", "f");
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // parallel edge: rows unchanged, revision bumps -> re-key only
        let _ = g.add_edge("a", "b");
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // attr-only change on an existing key: rows unchanged, revision bumps
        let mut attrs = AttrMap::new();
        attrs.insert("w".to_owned(), fnx_runtime::CgseValue::Int(2));
        let _ = g.add_edge_with_key_and_attrs("a", "b", 0, attrs);
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // remove one parallel key (pair survives -> rows unchanged)
        assert!(g.remove_edge("a", "b", None));
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // remove the last key (pair gone -> shift-remove mirrored in the rows)
        assert!(g.remove_edge("a", "b", None));
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // order-sensitive middle-of-row removal: row b = [a-gone..., c, ...]; build
        // b->x, b->y then drop (b,c) so the survivors must keep String-row order.
        let _ = g.add_edge("b", "x");
        let _ = g.add_edge("b", "y");
        assert!(g.remove_edge("b", "c", None));
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // self-loop removal
        assert!(g.remove_edge("f", "f", None));
        assert!(int_adj_memo_is_warm(&g));
        assert_int_adjacency_matches(&g);
        // unhandled mutation kind: remove_node renumbers -> memo must go stale
        assert!(g.remove_node("x"));
        assert!(
            !int_adj_memo_is_warm(&g),
            "remove_node stays invalidate-only; a warm memo here would serve stale indices"
        );
        assert_int_adjacency_matches(&g);
    }

    /// br-r37-c1-thp6w S5 PARITY GATES: the index-keyed prototype must derive
    /// byte-identical observable orderings (node order, per-row distinct-
    /// neighbor order, per-pair parallel-key order) and identical edge count +
    /// merged attrs from the same insert stream as the real String-keyed
    /// MultiGraph batch path. The stream deliberately includes names where
    /// String-lex and index canonicalization DIVERGE ("10" < "2" lex, 2 < 10
    /// numeric), reversed re-adds, self-loops, sparse explicit keys, dup
    /// (pair, key) attr merges, and late out-of-order node introduction.
    #[test]
    fn thp6w_s5_int_storage_proto_parity_gates() {
        use super::multigraph_storage::MgIntStorageProto;

        let stream: Vec<(&str, &str, usize)> = vec![
            ("2", "10", 0),
            ("10", "2", 1), // reversed orientation, same pair, next key
            ("1", "1", 0),  // self-loop on a fresh node
            ("2", "3", 0),
            ("3", "2", 0), // dup (pair, key) from the reverse orientation -> attr merge
            ("10", "1", 5), // sparse explicit key
            ("0", "2", 0), // node "0" introduced late (insertion order != numeric)
            ("2", "10", 1), // dup (pair, key) again -> attr merge
            ("4", "5", 2),
            ("5", "4", 0), // parallel keys, both orientations
            ("1", "1", 1), // parallel self-loop key
        ];
        let attrs_for = |i: usize| {
            let mut attrs = AttrMap::new();
            attrs.insert(
                format!("a{}", i % 3),
                fnx_runtime::CgseValue::Int(i64::try_from(i).unwrap()),
            );
            attrs
        };

        let mut mg = MultiGraph::strict();
        let _ = mg.extend_keyed_edges_with_attrs_unrecorded(
            stream
                .iter()
                .enumerate()
                .map(|(i, (l, r, k))| ((*l).to_owned(), (*r).to_owned(), *k, attrs_for(i))),
        );
        let mut proto = MgIntStorageProto::new();
        for (i, (l, r, k)) in stream.iter().enumerate() {
            proto.add_keyed_edge(l, r, *k, attrs_for(i));
        }
        // br-r37-c1-thp6w S6: the compact-bucket variant must pass the same gates.
        let mut compact = super::multigraph_storage::MgIntStorageProtoCompact::new();
        for (i, (l, r, k)) in stream.iter().enumerate() {
            compact.add_keyed_edge(l, r, *k, attrs_for(i));
        }

        // Gate 1: node insertion order.
        assert_eq!(
            proto
                .node_names
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            mg.nodes_ordered(),
            "node order must match"
        );
        assert_eq!(
            compact
                .node_names
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            mg.nodes_ordered(),
            "compact node order must match"
        );
        // Gate 2 + 3: per-row distinct-neighbor order and per-pair key order.
        for (i, name) in mg.nodes_ordered().iter().enumerate() {
            let mg_row: Vec<&str> = mg
                .neighbors_iter(name)
                .map_or_else(Vec::new, Iterator::collect);
            assert_eq!(proto.neighbor_names(i), mg_row, "row order for node {name}");
            assert_eq!(
                compact.neighbor_names(i),
                mg_row,
                "compact row order for node {name}"
            );
            for v in &mg_row {
                assert_eq!(
                    proto.key_order(name, v),
                    mg.edge_keys_vec(name, v),
                    "key order for pair ({name}, {v})"
                );
                assert_eq!(
                    compact.key_order(name, v),
                    mg.edge_keys_vec(name, v),
                    "compact key order for pair ({name}, {v})"
                );
            }
        }
        // Gate 4: edge count.
        assert_eq!(proto.edge_count, mg.edge_count(), "edge_count must match");
        assert_eq!(
            compact.edge_count,
            mg.edge_count(),
            "compact edge_count must match"
        );
        // Gate 5: merged attrs on a dup-inserted cell ((2,10) key 1 saw inserts
        // at stream positions 1 and 7 -> extend semantics on both sides).
        let l = *proto.node_index.get("2").expect("proto must retain node 2");
        let r = *proto
            .node_index
            .get("10")
            .expect("proto must retain node 10");
        let proto_attrs = proto.edges[&(l.min(r), l.max(r))]
            .get(&1)
            .expect("proto (2,10,1) cell");
        assert_eq!(
            Some(proto_attrs),
            mg.edge_attrs("2", "10", 1),
            "merged attrs on the dup (pair, key) cell must match"
        );
        assert_eq!(
            compact.edges[&(l.min(r), l.max(r))].attrs_for(1),
            mg.edge_attrs("2", "10", 1),
            "compact merged attrs on the dup (pair, key) cell must match"
        );
    }

    /// br-r37-c1-thp6w S7 helper: full observable-order parity between the
    /// real MultiGraph and the index-keyed prototype, plus the prototype's own
    /// name->index consistency (the renumber invariant).
    fn assert_proto_matches_mg(
        mg: &MultiGraph,
        proto: &super::multigraph_storage::MgIntStorageProto,
    ) {
        assert_eq!(
            proto
                .node_names
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            mg.nodes_ordered(),
            "node order"
        );
        for (i, name) in proto.node_names.iter().enumerate() {
            assert_eq!(
                proto.node_index.get(name),
                Some(&i),
                "node_index desync for {name}"
            );
        }
        for (i, name) in mg.nodes_ordered().iter().enumerate() {
            let mg_row: Vec<&str> = mg
                .neighbors_iter(name)
                .map_or_else(Vec::new, Iterator::collect);
            assert_eq!(proto.neighbor_names(i), mg_row, "row order for {name}");
            for v in &mg_row {
                assert_eq!(
                    proto.key_order(name, v),
                    mg.edge_keys_vec(name, v),
                    "key order for ({name}, {v})"
                );
            }
        }
        assert_eq!(proto.edge_count, mg.edge_count(), "edge_count");
    }

    /// br-r37-c1-thp6w S7 PARITY GAUNTLET (removal + renumber): the epoch's
    /// riskiest semantics — `remove_edge` shift/`next_back` behavior and the
    /// `remove_node` index renumber — must keep every observable ordering
    /// byte-identical to the real String-keyed MultiGraph after EVERY step,
    /// including re-adds AFTER a renumber (stale-index detection).
    #[test]
    fn thp6w_s7_removal_renumber_parity_gauntlet() {
        use super::multigraph_storage::MgIntStorageProto;

        let stream: Vec<(&str, &str, usize)> = vec![
            ("2", "10", 0),
            ("10", "2", 1),
            ("1", "1", 0),
            ("2", "3", 0),
            ("3", "2", 0),
            ("10", "1", 5),
            ("0", "2", 0),
            ("2", "10", 1),
            ("4", "5", 2),
            ("5", "4", 0),
            ("1", "1", 1),
        ];
        let mut mg = MultiGraph::strict();
        let _ = mg.extend_keyed_edges_with_attrs_unrecorded(
            stream
                .iter()
                .map(|(l, r, k)| ((*l).to_owned(), (*r).to_owned(), *k, AttrMap::new())),
        );
        let mut proto = MgIntStorageProto::new();
        for (l, r, k) in &stream {
            proto.add_keyed_edge(l, r, *k, AttrMap::new());
        }
        assert_proto_matches_mg(&mg, &proto);

        // key=None must pick the LAST bucket key (next_back): (4,5) keys are
        // [2, 0] in insertion order -> removes 0, survivor [2].
        assert_eq!(
            mg.remove_edge("4", "5", None),
            proto.remove_edge("4", "5", None)
        );
        assert_proto_matches_mg(&mg, &proto);
        // Partial removal of a parallel bundle: survivor key order preserved.
        assert_eq!(
            mg.remove_edge("2", "10", Some(0)),
            proto.remove_edge("2", "10", Some(0))
        );
        assert_proto_matches_mg(&mg, &proto);
        // Last key of the pair -> neighbor cell drops from both rows.
        assert_eq!(
            mg.remove_edge("2", "10", None),
            proto.remove_edge("2", "10", None)
        );
        assert_proto_matches_mg(&mg, &proto);
        // Self-loop partial removal.
        assert_eq!(
            mg.remove_edge("1", "1", Some(0)),
            proto.remove_edge("1", "1", Some(0))
        );
        assert_proto_matches_mg(&mg, &proto);
        // Missing pair / missing key: both sides must refuse identically.
        assert_eq!(
            mg.remove_edge("0", "10", None),
            proto.remove_edge("0", "10", None)
        );
        assert_eq!(
            mg.remove_edge("2", "3", Some(9)),
            proto.remove_edge("2", "3", Some(9))
        );
        assert_proto_matches_mg(&mg, &proto);

        // THE renumber: remove a mid-order node with live edges.
        assert_eq!(mg.remove_node("2"), proto.remove_node("2"));
        assert_proto_matches_mg(&mg, &proto);
        // Re-adds AFTER the renumber: fresh node + edges into shifted indices.
        mg.extend_keyed_edges_with_attrs_unrecorded(vec![
            ("3".to_owned(), "99".to_owned(), 0, AttrMap::new()),
            ("0".to_owned(), "3".to_owned(), 0, AttrMap::new()),
        ]);
        proto.add_keyed_edge("3", "99", 0, AttrMap::new());
        proto.add_keyed_edge("0", "3", 0, AttrMap::new());
        assert_proto_matches_mg(&mg, &proto);
        // Renumber again from the other end, then the self-loop node.
        assert_eq!(mg.remove_node("10"), proto.remove_node("10"));
        assert_proto_matches_mg(&mg, &proto);
        assert_eq!(mg.remove_node("1"), proto.remove_node("1"));
        assert_proto_matches_mg(&mg, &proto);
        // Removing a missing node refuses identically.
        assert_eq!(mg.remove_node("2"), proto.remove_node("2"));
        assert_proto_matches_mg(&mg, &proto);
    }

    /// br-r37-c1-thp6w S8 A/B: the flip's COST side — `remove_node` under the
    /// index layout pays the d58s8 positional renumber (O(V+E) per removal:
    /// row drop+decrement passes + full edges-map rebuild) where the current
    /// String store pays only O(V + degree) (shift_remove memmoves, no edge
    /// rekey). Same build stream, same 200-name removal sequence, removal
    /// phase timed alone, paired-interleaved with a null arm. This number
    /// decides whether the real flip needs the slab/stable-slot + tombstone
    /// node store (see the bead's S8 design note) instead of positional
    /// renumber.
    /// `cargo test --release -p fnx-classes --lib thp6w_s8_removal_cost_ab -- --ignored --nocapture`
    #[test]
    #[ignore = "paired A/B benchmark; run --release with --ignored --nocapture"]
    fn thp6w_s8_removal_cost_ab() {
        use super::multigraph_storage::MgIntStorageProto;
        use std::collections::HashMap;
        use std::hint::black_box;
        use std::time::Instant;

        fn push_edge(
            stream: &mut Vec<(usize, usize, usize)>,
            key_counter: &mut HashMap<(usize, usize), usize>,
            u: usize,
            v: usize,
        ) {
            let entry = key_counter.entry((u.min(v), u.max(v))).or_insert(0);
            stream.push((u, v, *entry));
            *entry += 1;
        }

        let n = 20000usize;
        let mut stream = Vec::new();
        let mut key_counter = HashMap::new();
        for i in 0..n {
            push_edge(&mut stream, &mut key_counter, i, (i + 1) % n);
        }
        let mut state = 0x2545_F491_4F6C_DD1D_u64;
        let draw = |state: &mut u64| -> usize {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(*state >> 33).unwrap() % n
        };
        for _ in 0..3 * n {
            let u = draw(&mut state);
            let v = draw(&mut state);
            push_edge(&mut stream, &mut key_counter, u, v);
        }
        let victims: Vec<String> = (0..n).step_by(100).map(|i| i.to_string()).collect();

        let time_current_removals = |stream: &[(usize, usize, usize)]| -> f64 {
            let mut g = MultiGraph::strict();
            let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
            let t0 = Instant::now();
            for name in &victims {
                assert!(g.remove_node(name));
            }
            let dt = t0.elapsed().as_secs_f64();
            black_box(g.edge_count());
            dt
        };
        let time_proto_removals = |stream: &[(usize, usize, usize)]| -> f64 {
            let mut proto = MgIntStorageProto::bulk_load_int_prefix(n, stream.iter().copied());
            let t0 = Instant::now();
            for name in &victims {
                assert!(proto.remove_node(name));
            }
            let dt = t0.elapsed().as_secs_f64();
            black_box(proto.edge_count);
            dt
        };

        // Post-removal structural agreement (once, outside timing).
        let mut g = MultiGraph::strict();
        let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
        let mut proto = MgIntStorageProto::bulk_load_int_prefix(n, stream.iter().copied());
        for name in &victims {
            assert!(g.remove_node(name));
            assert!(proto.remove_node(name));
        }
        assert_eq!(
            proto.edge_count,
            g.edge_count(),
            "removal arms diverged in edge_count"
        );
        assert_eq!(
            proto
                .node_names
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            g.nodes_ordered(),
            "removal arms diverged in node order"
        );

        let median = |samples: &mut Vec<f64>| -> f64 {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let (mut cur, mut pro, mut nul) = (Vec::new(), Vec::new(), Vec::new());
        for _ in 0..7 {
            cur.push(time_current_removals(&stream));
            pro.push(time_proto_removals(&stream));
            nul.push(time_current_removals(&stream));
        }
        // br-r37-c1-thp6w S9: slab arm — must be ~parity with the String store.
        let time_slab_removals = |stream: &[(usize, usize, usize)]| -> f64 {
            let mut slab = super::multigraph_storage::MgSlabStorage::bulk_load_int_prefix(
                n,
                stream.iter().copied(),
            );
            let t0 = Instant::now();
            for name in &victims {
                assert!(slab.remove_node(name));
            }
            let dt = t0.elapsed().as_secs_f64();
            black_box(slab.edge_count);
            dt
        };
        let mut g2 = MultiGraph::strict();
        let _ = g2.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
        let mut slab = super::multigraph_storage::MgSlabStorage::bulk_load_int_prefix(
            n,
            stream.iter().copied(),
        );
        for name in &victims {
            assert!(g2.remove_node(name));
            assert!(slab.remove_node(name));
        }
        assert_eq!(
            slab.edge_count,
            g2.edge_count(),
            "slab removal arm diverged in edge_count"
        );
        assert_eq!(
            slab.node_order
                .keys()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            g2.nodes_ordered(),
            "slab removal arm diverged in node order"
        );
        let mut sla = Vec::new();
        for _ in 0..7 {
            sla.push(time_slab_removals(&stream));
        }
        let msl = median(&mut sla);

        let (mc, mp, mn) = (median(&mut cur), median(&mut pro), median(&mut nul));
        println!(
            "THP6W_S8_REMOVAL_AB n={n} m={} removals={} current={mc:.6}s proto_renumber={mp:.6}s slab={msl:.6}s ratio_proto_over_current={:.3} ratio_slab_over_current={:.3} null={:.3}",
            stream.len(),
            victims.len(),
            mp / mc,
            msl / mc,
            mc / mn,
        );
    }

    /// br-r37-c1-thp6w S9 helper: full observable-order parity between the
    /// real MultiGraph and the slab prototype (order from `node_order`, rows
    /// resolved slot -> name), plus slab self-consistency (live slots named,
    /// free slots tombstoned).
    fn assert_slab_matches_mg(mg: &MultiGraph, slab: &super::multigraph_storage::MgSlabStorage) {
        let mg_node_order = mg.nodes_ordered();
        assert_eq!(
            slab.node_order
                .keys()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            mg_node_order,
            "slab node order"
        );
        for (name, &slot) in &slab.node_order {
            assert_eq!(
                slab.slot_names[slot].as_deref(),
                Some(name.as_str()),
                "slot_names desync for {name}"
            );
        }
        for &free in &slab.free_slots {
            assert!(
                slab.slot_names[free].is_none(),
                "free slot {free} still named"
            );
            assert!(slab.rows[free].is_empty(), "free slot {free} has row cells");
            assert!(
                slab.node_attrs[free].is_empty(),
                "free slot {free} still has node attrs"
            );
        }
        for &name in &mg_node_order {
            assert_eq!(
                slab.node_attrs_for(name),
                mg.node_attrs(name),
                "slab node attrs for {name}"
            );
        }
        for (pos, &name) in mg_node_order.iter().enumerate() {
            let mg_row = mg.neighbors(name).unwrap_or_default();
            assert_eq!(
                slab.neighbor_names(pos),
                mg_row,
                "slab row order for {name}"
            );
            for &v in &mg_row {
                let mg_keys = mg.edge_keys_vec(name, v);
                assert_eq!(
                    slab.key_order(name, v),
                    mg_keys,
                    "slab key order for ({name}, {v})"
                );
            }
        }
        assert_eq!(slab.edge_count, mg.edge_count, "slab edge_count");
    }

    /// br-r37-c1-thp6w S9 PARITY GAUNTLET (slab + slot recycling): the
    /// S8-mandated layout must stay byte-identical to the real MultiGraph
    /// through the S7 removal shapes AND the slab-specific hazards — slot
    /// reuse after removal (fresh name AND the removed name re-added must
    /// append at the END of node order with no phantom edges from the slot's
    /// previous occupant).
    #[test]
    fn thp6w_s9_slab_recycling_parity_gauntlet() {
        use super::multigraph_storage::MgSlabStorage;

        let stream: Vec<(&str, &str, usize)> = vec![
            ("2", "10", 0),
            ("10", "2", 1),
            ("1", "1", 0),
            ("2", "3", 0),
            ("3", "2", 0),
            ("10", "1", 5),
            ("0", "2", 0),
            ("2", "10", 1),
            ("4", "5", 2),
            ("5", "4", 0),
            ("1", "1", 1),
        ];
        let mut mg = MultiGraph::strict();
        let _ = mg.extend_keyed_edges_with_attrs_unrecorded(
            stream
                .iter()
                .map(|(l, r, k)| ((*l).to_owned(), (*r).to_owned(), *k, AttrMap::new())),
        );
        let mut slab = MgSlabStorage::new();
        for (l, r, k) in &stream {
            slab.add_keyed_edge(l, r, *k, AttrMap::new());
        }
        assert_slab_matches_mg(&mg, &slab);

        // S7 removal shapes.
        assert_eq!(
            mg.remove_edge("4", "5", None),
            slab.remove_edge("4", "5", None)
        );
        assert_slab_matches_mg(&mg, &slab);
        assert_eq!(
            mg.remove_edge("2", "10", Some(0)),
            slab.remove_edge("2", "10", Some(0))
        );
        assert_slab_matches_mg(&mg, &slab);
        assert_eq!(
            mg.remove_edge("2", "10", None),
            slab.remove_edge("2", "10", None)
        );
        assert_slab_matches_mg(&mg, &slab);
        assert_eq!(
            mg.remove_edge("1", "1", Some(0)),
            slab.remove_edge("1", "1", Some(0))
        );
        assert_slab_matches_mg(&mg, &slab);
        assert_eq!(
            mg.remove_edge("0", "10", None),
            slab.remove_edge("0", "10", None)
        );
        assert_eq!(
            mg.remove_edge("2", "3", Some(9)),
            slab.remove_edge("2", "3", Some(9))
        );
        assert_slab_matches_mg(&mg, &slab);

        // Tombstone a mid-order node with live parallel edges...
        assert_eq!(mg.remove_node("2"), slab.remove_node("2"));
        assert_slab_matches_mg(&mg, &slab);
        // ...then RECYCLE its slot with a FRESH name: must append at the END
        // of node order and carry no phantom adjacency from the old occupant.
        mg.extend_keyed_edges_with_attrs_unrecorded(vec![(
            "fresh".to_owned(),
            "3".to_owned(),
            0,
            AttrMap::new(),
        )]);
        slab.add_keyed_edge("fresh", "3", 0, AttrMap::new());
        assert_slab_matches_mg(&mg, &slab);
        // ...and re-add the REMOVED name too (recycles another slot or a fresh
        // one; order must be append-at-end either way).
        mg.extend_keyed_edges_with_attrs_unrecorded(vec![(
            "2".to_owned(),
            "fresh".to_owned(),
            7,
            AttrMap::new(),
        )]);
        slab.add_keyed_edge("2", "fresh", 7, AttrMap::new());
        assert_slab_matches_mg(&mg, &slab);
        // Remove the recycled node again (double-recycle path).
        assert_eq!(mg.remove_node("fresh"), slab.remove_node("fresh"));
        assert_slab_matches_mg(&mg, &slab);
        // Self-loop node and end nodes.
        assert_eq!(mg.remove_node("1"), slab.remove_node("1"));
        assert_slab_matches_mg(&mg, &slab);
        assert_eq!(mg.remove_node("10"), slab.remove_node("10"));
        assert_slab_matches_mg(&mg, &slab);
        // Missing-node refusal parity.
        assert_eq!(mg.remove_node("gone"), slab.remove_node("gone"));
        assert_slab_matches_mg(&mg, &slab);
    }

    /// br-r37-c1-thp6w S10 helper: the ONLY observed edge order — walk-order
    /// emission with String-lex canonical orientation — must be byte-identical
    /// between the real MultiGraph and the slab layout.
    fn assert_slab_edges_ordered_matches_mg(
        mg: &MultiGraph,
        slab: &super::multigraph_storage::MgSlabStorage,
    ) {
        let mg_ordered: Vec<(&str, &str, usize)> = mg
            .edges_ordered_borrowed()
            .into_iter()
            .map(|(l, r, k, _)| (l, r, k))
            .collect();
        assert_eq!(
            slab.edges_ordered_names(),
            mg_ordered,
            "edges_ordered walk emission must match"
        );
        // br-r37-c1-thp6w S12: the attrs-carrying walk must match in FULL,
        // including per-cell attr payloads.
        assert_eq!(
            slab.edges_ordered_borrowed(),
            mg.edges_ordered_borrowed(),
            "attrs-carrying edges_ordered walk must match"
        );
    }

    /// br-r37-c1-thp6w S10 PARITY GAUNTLET (copy-walk reorder + snapshot
    /// orientation): the two remaining tie-break axes for the real flip.
    /// `edges_ordered` (walk emission with lex-canonical orientation) and
    /// `reorder_rows_for_nx_copy_walk` (the MultiGraph.copy row-order
    /// contract) must stay byte-identical through reorders, post-reorder
    /// mutations, removals, and slot recycling.
    #[test]
    fn thp6w_s10_copy_walk_and_snapshot_orientation_gauntlet() {
        use super::multigraph_storage::MgSlabStorage;

        let stream: Vec<(&str, &str, usize)> = vec![
            ("2", "10", 0),
            ("10", "2", 1),
            ("1", "1", 0),
            ("2", "3", 0),
            ("10", "1", 5),
            ("0", "2", 0),
            ("4", "5", 2),
            ("5", "4", 0),
            ("3", "0", 0),
            ("1", "1", 1),
            ("5", "0", 3),
        ];
        let mut mg = MultiGraph::strict();
        let _ = mg.extend_keyed_edges_with_attrs_unrecorded(
            stream
                .iter()
                .map(|(l, r, k)| ((*l).to_owned(), (*r).to_owned(), *k, AttrMap::new())),
        );
        let mut slab = MgSlabStorage::new();
        for (l, r, k) in &stream {
            slab.add_keyed_edge(l, r, *k, AttrMap::new());
        }
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);

        // THE copy-walk reorder (MultiGraph.copy row-order contract).
        mg.reorder_rows_for_nx_copy_walk();
        slab.reorder_rows_for_nx_copy_walk();
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);

        // Reorder must be idempotent on both sides.
        mg.reorder_rows_for_nx_copy_walk();
        slab.reorder_rows_for_nx_copy_walk();
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);

        // Post-reorder mutations: new edges append after the reordered cells.
        mg.extend_keyed_edges_with_attrs_unrecorded(vec![
            ("0".to_owned(), "9".to_owned(), 0, AttrMap::new()),
            ("9".to_owned(), "2".to_owned(), 0, AttrMap::new()),
        ]);
        slab.add_keyed_edge("0", "9", 0, AttrMap::new());
        slab.add_keyed_edge("9", "2", 0, AttrMap::new());
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);

        // Removal + slot recycling, then reorder AGAIN on the recycled state.
        assert_eq!(mg.remove_node("2"), slab.remove_node("2"));
        mg.extend_keyed_edges_with_attrs_unrecorded(vec![(
            "fresh".to_owned(),
            "9".to_owned(),
            0,
            AttrMap::new(),
        )]);
        slab.add_keyed_edge("fresh", "9", 0, AttrMap::new());
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);
        mg.reorder_rows_for_nx_copy_walk();
        slab.reorder_rows_for_nx_copy_walk();
        assert_slab_matches_mg(&mg, &slab);
        assert_slab_edges_ordered_matches_mg(&mg, &slab);
    }

    /// br-r37-c1-thp6w S12 A/B: the `edges_ordered_borrowed` read on the
    /// String store (per-cell `EdgeKeyRef` String-pair hashing + String-pair
    /// seen-set probes) vs the slab walk (usize hashing throughout). Same
    /// graph state on both sides (slab via `from_string_state`), full-output
    /// equality asserted outside timing, paired-interleaved with a null arm.
    /// `cargo test --release -p fnx-classes --lib thp6w_s12_edges_ordered_read_ab -- --ignored --nocapture`
    #[test]
    #[ignore = "paired A/B benchmark; run --release with --ignored --nocapture"]
    fn thp6w_s12_edges_ordered_read_ab() {
        use std::collections::HashMap;
        use std::hint::black_box;
        use std::time::Instant;

        fn push_edge(
            stream: &mut Vec<(usize, usize, usize)>,
            key_counter: &mut HashMap<(usize, usize), usize>,
            u: usize,
            v: usize,
        ) {
            let entry = key_counter.entry((u.min(v), u.max(v))).or_insert(0);
            stream.push((u, v, *entry));
            *entry += 1;
        }

        let n = 20000usize;
        let mut stream = Vec::new();
        let mut key_counter = HashMap::new();
        for i in 0..n {
            push_edge(&mut stream, &mut key_counter, i, (i + 1) % n);
        }
        let mut state = 0x2545_F491_4F6C_DD1D_u64;
        let draw = |state: &mut u64| -> usize {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(*state >> 33).unwrap() % n
        };
        for _ in 0..3 * n {
            let u = draw(&mut state);
            let v = draw(&mut state);
            push_edge(&mut stream, &mut key_counter, u, v);
        }

        let mut g = MultiGraph::strict();
        let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
        let slab = g.storage.clone();
        assert_eq!(
            slab.edges_ordered_borrowed(),
            g.edges_ordered_borrowed(),
            "arms must emit identical sequences"
        );

        let time_string = || -> f64 {
            let t0 = Instant::now();
            let out = g.edges_ordered_borrowed();
            let dt = t0.elapsed().as_secs_f64();
            black_box(out.len());
            dt
        };
        let time_slab = || -> f64 {
            let t0 = Instant::now();
            let out = slab.edges_ordered_borrowed();
            let dt = t0.elapsed().as_secs_f64();
            black_box(out.len());
            dt
        };
        let median = |samples: &mut Vec<f64>| -> f64 {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let (mut cur, mut sla, mut nul) = (Vec::new(), Vec::new(), Vec::new());
        for _ in 0..9 {
            cur.push(time_string());
            sla.push(time_slab());
            nul.push(time_string());
        }
        let (mc, ms, mn) = (median(&mut cur), median(&mut sla), median(&mut nul));
        println!(
            "THP6W_S12_EDGES_ORDERED_AB n={n} m={} string={mc:.6}s slab={ms:.6}s ratio_string_over_slab={:.3} null={:.3}",
            stream.len(),
            mc / ms,
            mc / mn,
        );
    }

    /// br-r37-c1-thp6w S13 A/B: the INDEX-space `edges_ordered_indices_borrowed`
    /// read — String store (per-edge `nodes.get_index_of` String hash + `EdgeKey`
    /// pair hash) vs the slab (hash-free `slot->position` array + usize walk).
    /// Same graph state, output equality asserted outside timing, paired-
    /// interleaved with a null arm.
    /// `cargo test --release -p fnx-classes --lib thp6w_s13_edges_ordered_indices_ab -- --ignored --nocapture`
    #[test]
    #[ignore = "paired A/B benchmark; run --release with --ignored --nocapture"]
    fn thp6w_s13_edges_ordered_indices_ab() {
        use std::collections::HashMap;
        use std::hint::black_box;
        use std::time::Instant;

        fn push_edge(
            stream: &mut Vec<(usize, usize, usize)>,
            key_counter: &mut HashMap<(usize, usize), usize>,
            u: usize,
            v: usize,
        ) {
            let entry = key_counter.entry((u.min(v), u.max(v))).or_insert(0);
            stream.push((u, v, *entry));
            *entry += 1;
        }

        let n = 20000usize;
        let mut stream = Vec::new();
        let mut key_counter = HashMap::new();
        for i in 0..n {
            push_edge(&mut stream, &mut key_counter, i, (i + 1) % n);
        }
        let mut state = 0x2545_F491_4F6C_DD1D_u64;
        let draw = |state: &mut u64| -> usize {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(*state >> 33).unwrap() % n
        };
        for _ in 0..3 * n {
            let u = draw(&mut state);
            let v = draw(&mut state);
            push_edge(&mut stream, &mut key_counter, u, v);
        }

        let mut g = MultiGraph::strict();
        let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
        let slab = g.storage.clone();
        assert_eq!(
            slab.edges_ordered_indices_borrowed(),
            g.edges_ordered_indices_borrowed(),
            "arms must emit identical index sequences"
        );

        let time_string = || -> f64 {
            let t0 = Instant::now();
            let out = g.edges_ordered_indices_borrowed();
            let dt = t0.elapsed().as_secs_f64();
            black_box(out.len());
            dt
        };
        let time_slab = || -> f64 {
            let t0 = Instant::now();
            let out = slab.edges_ordered_indices_borrowed();
            let dt = t0.elapsed().as_secs_f64();
            black_box(out.len());
            dt
        };
        let median = |samples: &mut Vec<f64>| -> f64 {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let (mut cur, mut sla, mut nul) = (Vec::new(), Vec::new(), Vec::new());
        for _ in 0..9 {
            cur.push(time_string());
            sla.push(time_slab());
            nul.push(time_string());
        }
        let (mc, ms, mn) = (median(&mut cur), median(&mut sla), median(&mut nul));
        println!(
            "THP6W_S13_EDGES_ORDERED_INDICES_AB n={n} m={} string={mc:.6}s slab={ms:.6}s ratio_string_over_slab={:.3} null={:.3}",
            stream.len(),
            mc / ms,
            mc / mn,
        );
    }

    fn assert_multigraph_storage_invariants(graph: &MultiGraph) {
        let storage = &graph.storage;
        assert_eq!(storage.slot_names.len(), storage.node_attrs.len());
        assert_eq!(storage.slot_names.len(), storage.rows.len());
        assert_eq!(graph.edge_count, storage.edge_count);
        assert_eq!(
            storage.edge_count,
            storage
                .edges
                .values()
                .map(super::multigraph_storage::CompactBucket::len)
                .sum::<usize>()
        );

        let mut live_slots = vec![false; storage.slot_names.len()];
        for (name, &slot) in &storage.node_order {
            assert!(!live_slots[slot], "slot {slot} is assigned twice");
            live_slots[slot] = true;
            assert_eq!(storage.slot_names[slot].as_deref(), Some(name.as_str()));
        }
        assert_eq!(
            live_slots.iter().filter(|&&live| live).count(),
            graph.node_count()
        );

        let mut free_slots = BTreeSet::new();
        for &slot in &storage.free_slots {
            assert!(free_slots.insert(slot), "free slot {slot} listed twice");
            assert!(!live_slots[slot], "live slot {slot} is also free");
            assert!(storage.slot_names[slot].is_none());
            assert!(storage.node_attrs[slot].is_empty());
            assert!(storage.rows[slot].is_empty());
        }

        for (left, row) in storage.rows.iter().enumerate() {
            if !live_slots[left] {
                assert!(row.is_empty(), "tombstoned slot {left} has neighbors");
                continue;
            }
            for (&right, keys) in row {
                assert!(live_slots[right], "row points to tombstoned slot {right}");
                let pair = (left.min(right), left.max(right));
                let bucket = storage
                    .edges
                    .get(&pair)
                    .expect("every row cell must have an edge bucket");
                assert_eq!(keys.order(), bucket.key_order());
                if left != right {
                    assert_eq!(
                        storage.rows[right]
                            .get(&left)
                            .expect("undirected reverse row is missing")
                            .order(),
                        keys.order()
                    );
                }
            }
        }
        for (&(left, right), bucket) in &storage.edges {
            assert!(live_slots[left] && live_slots[right]);
            assert_eq!(
                storage.rows[left]
                    .get(&right)
                    .expect("edge bucket missing left row")
                    .order(),
                bucket.key_order()
            );
            if left != right {
                assert_eq!(
                    storage.rows[right]
                        .get(&left)
                        .expect("edge bucket missing right row")
                        .order(),
                    bucket.key_order()
                );
            }
        }
    }

    #[test]
    fn thp6w_s35_slab_is_sole_store_mutation_gauntlet() {
        let attr = |key: &str, value: i64| {
            let mut attrs = AttrMap::new();
            attrs.insert(key.to_owned(), fnx_runtime::CgseValue::Int(value));
            attrs
        };

        let mut graph = MultiGraph::strict();
        assert!(graph.add_node_with_attrs("iso", attr("kind", 1)));
        assert_eq!(
            graph.add_edge_with_key_and_attrs("b", "a", 3, attr("weight", 2)),
            Ok(3)
        );
        assert_eq!(
            graph.add_edge_with_key_and_attrs("a", "b", 3, attr("color", 7)),
            Ok(3)
        );
        assert_eq!(
            graph.add_edge_with_key_and_attrs("a", "b", 0, AttrMap::new()),
            Ok(0)
        );
        assert_eq!(
            graph.add_edge_with_key_and_attrs("c", "c", 5, attr("weight", 11)),
            Ok(5)
        );
        assert_eq!(graph.nodes_ordered(), vec!["iso", "b", "a", "c"]);
        assert_eq!(graph.edge_keys_vec("a", "b"), vec![3, 0]);
        assert_eq!(
            graph.edge_attrs("a", "b", 3),
            Some(&{
                let mut attrs = attr("weight", 2);
                attrs.extend(attr("color", 7));
                attrs
            })
        );
        assert_eq!(graph.number_of_selfloops(), 1);
        assert_eq!(graph.degree("c"), 2);
        assert_eq!(graph.isolates(), vec!["iso"]);
        assert_multigraph_storage_invariants(&graph);
        assert_int_adjacency_matches(&graph);

        let baseline = graph.snapshot();
        let cloned = graph.clone_with_fresh_policy();
        assert_eq!(cloned.snapshot(), baseline);
        assert_multigraph_storage_invariants(&cloned);

        let revision = graph.revision();
        assert!(graph.replace_edge_attrs("a", "b", 3, attr("replacement", 9)));
        assert_eq!(graph.revision(), revision + 1);
        let revision = graph.revision();
        assert!(graph.replace_edge_attrs("a", "b", 3, attr("replacement", 9)));
        assert_eq!(
            graph.revision(),
            revision,
            "no-op edge replace bumped revision"
        );
        assert!(graph.replace_node_attrs("iso", attr("kind", 4)));
        assert!(graph.remove_edge("b", "a", Some(3)));
        assert_eq!(graph.edge_keys_vec("a", "b"), vec![0]);
        assert!(graph.remove_node("b"));
        assert!(!graph.has_edge("a", "b"));
        assert_eq!(graph.nodes_ordered(), vec!["iso", "a", "c"]);
        assert_eq!(graph.add_edge("d", "a"), Ok(0));
        assert_eq!(graph.nodes_ordered(), vec!["iso", "a", "c", "d"]);
        assert_multigraph_storage_invariants(&graph);

        let (removed_nodes, removed_edges) = graph.remove_nodes_from(["iso", "c", "missing"]);
        assert_eq!((removed_nodes, removed_edges), (2, 1));
        assert_eq!(graph.nodes_ordered(), vec!["a", "d"]);
        assert_eq!(graph.edge_count(), 1);
        assert_multigraph_storage_invariants(&graph);
        graph.clear_edges();
        assert_eq!(graph.edge_count(), 0);
        assert_eq!(graph.isolates(), vec!["a", "d"]);
        assert_multigraph_storage_invariants(&graph);
    }

    #[test]
    fn thp6w_s35_fresh_loaders_populate_sole_store() {
        let mut integer = MultiGraph::strict();
        assert_eq!(
            integer.extend_fresh_int_prefix_keyed_edges_unrecorded(
                4,
                [(0, 1, 0), (1, 0, 1), (2, 2, 0), (3, 0, 0)]
            ),
            4
        );
        assert_eq!(integer.nodes_ordered(), vec!["0", "1", "2", "3"]);
        assert_eq!(integer.edge_keys_vec("0", "1"), vec![0, 1]);
        assert_eq!(integer.number_of_selfloops(), 1);
        assert_multigraph_storage_invariants(&integer);
        assert_int_adjacency_matches(&integer);

        let mut weight = AttrMap::new();
        weight.insert("weight".to_owned(), fnx_runtime::CgseValue::Int(2));
        let mut color = AttrMap::new();
        color.insert("color".to_owned(), fnx_runtime::CgseValue::Int(7));
        let mut attributed = MultiGraph::strict();
        assert_eq!(
            attributed.extend_fresh_index_keyed_edges_with_attrs_unrecorded(
                ["b", "a", "c"].into_iter().map(str::to_owned),
                [
                    (0, 1, 4, weight),
                    (1, 0, 4, color),
                    (2, 2, 0, AttrMap::new()),
                    (0, 9, 0, AttrMap::new()),
                ]
            ),
            2
        );
        assert_eq!(attributed.nodes_ordered(), vec!["b", "a", "c"]);
        assert_eq!(attributed.edge_count(), 2);
        assert_eq!(attributed.edge_keys_vec("a", "b"), vec![4]);
        let attrs = attributed
            .edge_attrs("a", "b", 4)
            .expect("merged attributed edge");
        assert_eq!(attrs.len(), 2);
        assert!(attrs.contains_key("weight"));
        assert!(attrs.contains_key("color"));
        assert_multigraph_storage_invariants(&attributed);
    }

    /// br-r37-c1-thp6w S14: a fresh bulk-built graph must be WARM from birth
    /// (the slab co-built during construction), byte-identical, and stay warm
    /// through instrumented mutations. NOTE: `edges_ordered_borrowed` is a
    /// ROUTED read (S13) — comparing it against the shadow would be circular
    /// with a warm shadow, so this gauntlet uses only unrouted ground-truth
    /// accessors (`nodes_ordered`, `neighbors_iter`, `edge_keys_vec`); the
    /// walk itself is gated non-circularly by the S13 route gate.
    #[cfg(any())]
    #[test]
    fn thp6w_s14_fresh_bulk_graph_is_warm_from_birth() {
        let mut g = MultiGraph::strict();
        let stream = vec![
            (0usize, 1usize, 0usize),
            (1, 2, 0),
            (0, 1, 1), // parallel
            (2, 2, 0), // self-loop
            (3, 0, 0),
        ];
        let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(5, stream.into_iter());
        assert!(
            g.slab_shadow_is_warm(),
            "fresh bulk graph must be born warm"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
        }
        // Instrumented mutations keep the born-warm shadow warm.
        let _ = g.add_edge("2", "4");
        assert!(g.slab_shadow_is_warm());
        assert!(g.remove_edge("0", "1", None));
        assert!(g.slab_shadow_is_warm());
        assert!(g.remove_node("1"));
        assert!(g.slab_shadow_is_warm());
        let shadow = g.slab_shadow.as_deref().expect("shadow present");
        assert_slab_matches_mg(&g, &shadow.1);

        // br-r37-c1-thp6w S17: a node-attr set now ADVANCES the warm shadow in
        // place (was stale->rebuild in S16). Existing node "2":
        let mut nattrs = AttrMap::new();
        nattrs.insert("color".to_owned(), fnx_runtime::CgseValue::Int(7));
        let _ = g.add_node_with_attrs("2", nattrs);
        assert!(
            g.slab_shadow_is_warm(),
            "node-attr set must advance (not stale) the warm shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
            assert_eq!(
                shadow.1.node_attrs_for("2"),
                g.nodes.get("2"),
                "advanced shadow must carry the set node attr for node 2"
            );
        }
        // A node-attr set that CREATES a new node advances the shadow too.
        let mut nattrs2 = AttrMap::new();
        nattrs2.insert("w".to_owned(), fnx_runtime::CgseValue::Int(9));
        let _ = g.add_node_with_attrs("attr_only", nattrs2);
        assert!(g.slab_shadow_is_warm());
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
            assert_eq!(
                shadow.1.node_attrs_for("attr_only"),
                g.nodes.get("attr_only"),
                "advanced shadow must carry a new attr-only node"
            );
        }
        // A full rebuild still reproduces the same node attrs (from_string_state).
        g.sync_slab_shadow();
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
        }

        // br-r37-c1-thp6w S15: the ATTRIBUTED fresh path is born warm too —
        // arbitrary labels, dup-(pair,key) attr merge, out-of-bounds skip.
        let mut h = MultiGraph::strict();
        let mut w1 = AttrMap::new();
        w1.insert("w".to_owned(), fnx_runtime::CgseValue::Int(1));
        let mut w2 = AttrMap::new();
        w2.insert("x".to_owned(), fnx_runtime::CgseValue::Int(2));
        let _ = h.extend_fresh_index_keyed_edges_with_attrs_unrecorded(
            vec!["b".to_owned(), "a".to_owned(), "c".to_owned()],
            vec![
                (0, 1, 0, w1.clone()),
                (1, 0, 0, w2),             // dup (pair, key) reversed -> attr merge
                (2, 2, 0, w1),             // self-loop
                (0, 9, 0, AttrMap::new()), // out-of-bounds -> skipped by BOTH sides
                (1, 2, 3, AttrMap::new()), // sparse key
            ],
        );
        assert!(h.slab_shadow_is_warm(), "attributed fresh graph born warm");
        let shadow = h.slab_shadow.as_deref().expect("shadow present");
        assert_slab_matches_mg(&h, &shadow.1);
        assert_eq!(
            shadow.1.edges[&(0, 1)].attrs_for(0),
            h.edges
                .get(&super::EdgeKeyRef::new("b", "a"))
                .and_then(|kb| kb.get(&0)),
            "merged attrs on the dup cell must match"
        );
    }

    /// br-r37-c1-thp6w S19: batch `remove_nodes_from` advances the warm shadow
    /// (per-node slab remove, stable slots) on BOTH its exit paths — the
    /// small-fraction incident fast path and the large-fraction whole-graph
    /// retain — and never spuriously warms a stale shadow.
    #[cfg(any())]
    #[test]
    fn thp6w_s19_remove_nodes_from_advances_shadow() {
        let mut g = MultiGraph::strict();
        for i in 0..12u32 {
            let _ = g.add_edge(&i.to_string(), &((i + 1) % 12).to_string());
        }
        let _ = g.add_edge("0", "6"); // a chord
        let _ = g.add_edge("3", "3"); // a self-loop
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());

        // Fast path: small fraction (2*4 <= 12 nodes).
        let (rn, _) = g.remove_nodes_from(["3", "9"].into_iter());
        assert_eq!(rn, 2);
        assert!(
            g.slab_shadow_is_warm(),
            "remove_nodes_from fast path must advance the shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
        }

        // Fall-through path: large fraction (5*4 > 10 remaining nodes).
        let (rn2, _) = g.remove_nodes_from(["0", "1", "2", "4", "5"].into_iter());
        assert_eq!(rn2, 5);
        assert!(
            g.slab_shadow_is_warm(),
            "remove_nodes_from fall-through must advance the shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
        }

        // A STALE shadow must not be spuriously warmed by the removal.
        g.add_node("island"); // structural (empty attrs) -> stales
        assert!(!g.slab_shadow_is_warm());
        let _ = g.remove_nodes_from(["island"].into_iter());
        assert!(
            !g.slab_shadow_is_warm(),
            "remove_nodes_from must not warm a stale shadow"
        );
        g.sync_slab_shadow();
        let shadow = g.slab_shadow.as_deref().expect("shadow present");
        assert_slab_matches_mg(&g, &shadow.1);
    }

    /// br-r37-c1-thp6w S20: batch `extend_nodes_with_attrs_unrecorded` advances
    /// the warm shadow — including the latent attr-only case (no NEW nodes, so
    /// no revision bump) where a warm shadow would otherwise carry stale attrs.
    #[cfg(any())]
    #[test]
    fn thp6w_s20_extend_nodes_with_attrs_advances_shadow() {
        let mut g = MultiGraph::strict();
        for i in 0..6u32 {
            let _ = g.add_edge(&i.to_string(), &((i + 1) % 6).to_string());
        }
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());

        let attr = |k: &str, v: i64| {
            let mut a = AttrMap::new();
            a.insert(k.to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        // Batch: 2 new attr-only nodes + an attr update on existing node "0".
        let ins = g.extend_nodes_with_attrs_unrecorded(vec![
            ("new_a".to_owned(), attr("c", 1)),
            ("new_b".to_owned(), attr("c", 2)),
            ("0".to_owned(), attr("k", 3)),
        ]);
        assert_eq!(ins, 2, "two new nodes");
        assert!(
            g.slab_shadow_is_warm(),
            "node-attr batch must advance the shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
            assert_eq!(shadow.1.node_attrs_for("new_a"), g.nodes.get("new_a"));
            assert_eq!(shadow.1.node_attrs_for("0"), g.nodes.get("0"));
        }

        // ATTR-ONLY batch (no new nodes -> no revision bump): the shadow must
        // still carry the updated attr, not stay warm-but-stale.
        let ins2 = g.extend_nodes_with_attrs_unrecorded(vec![("new_a".to_owned(), attr("c", 99))]);
        assert_eq!(ins2, 0, "no new nodes");
        assert!(
            g.slab_shadow_is_warm(),
            "attr-only batch keeps the shadow warm"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_eq!(
                shadow.1.node_attrs_for("new_a"),
                g.nodes.get("new_a"),
                "attr-only update must be reflected in the (still-warm) shadow"
            );
        }
    }

    /// br-r37-c1-thp6w S21: `replace_node_attrs` (node attr OVERWRITE) advances
    /// the warm shadow; a no-op replace (no revision bump) and a missing-node
    /// replace leave it warm and uncorrupted.
    #[cfg(any())]
    #[test]
    fn thp6w_s21_replace_node_attrs_advances_shadow() {
        let attr = |k: &str, v: i64| {
            let mut a = AttrMap::new();
            a.insert(k.to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_node_with_attrs("x", attr("c", 1));
        let _ = g.add_edge("x", "y");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());

        // Overwrite x's attrs -> advances the warm shadow.
        assert!(g.replace_node_attrs("x", attr("d", 2)));
        assert!(
            g.slab_shadow_is_warm(),
            "replace_node_attrs must advance the shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
            assert_eq!(
                shadow.1.node_attrs_for("x"),
                g.nodes.get("x"),
                "shadow must reflect the overwrite"
            );
        }

        // No-op replace (same attrs) does not bump revision; shadow stays warm.
        let same = g.nodes.get("x").cloned().unwrap_or_default();
        assert!(g.replace_node_attrs("x", same));
        assert!(g.slab_shadow_is_warm());

        // Replace on a missing node returns false and leaves the shadow warm.
        assert!(!g.replace_node_attrs("missing", attr("z", 9)));
        assert!(g.slab_shadow_is_warm());
        let shadow = g.slab_shadow.as_deref().expect("shadow present");
        assert_slab_matches_mg(&g, &shadow.1);
    }

    /// br-r37-c1-thp6w S22: `replace_edge_attrs` (edge-cell attr OVERWRITE)
    /// advances the warm shadow, leaves parallel cells untouched, and a no-op
    /// or missing-edge replace leaves the shadow warm/uncorrupted.
    #[cfg(any())]
    #[test]
    fn thp6w_s22_replace_edge_attrs_advances_shadow() {
        let attr = |k: &str, v: i64| {
            let mut a = AttrMap::new();
            a.insert(k.to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge_with_key_and_attrs("a", "b", 0, attr("w", 1));
        let _ = g.add_edge_with_key_and_attrs("a", "b", 1, attr("w", 2)); // parallel
        let _ = g.add_edge("b", "c");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());

        // Overwrite the (a,b,0) cell attrs -> advances the warm shadow.
        assert!(g.replace_edge_attrs("a", "b", 0, attr("x", 5)));
        assert!(
            g.slab_shadow_is_warm(),
            "replace_edge_attrs must advance the shadow"
        );
        {
            let shadow = g.slab_shadow.as_deref().expect("shadow present");
            assert_slab_matches_mg(&g, &shadow.1);
            // a=slot0, b=slot1 (fresh graph) -> the a,b bucket is (0,1).
            assert_eq!(
                shadow.1.edges[&(0, 1)].attrs_for(0),
                g.edges
                    .get(&super::EdgeKeyRef::new("a", "b"))
                    .and_then(|kb| kb.get(&0)),
                "advanced shadow must carry the overwritten cell attrs"
            );
            assert_eq!(
                shadow.1.edges[&(0, 1)].attrs_for(1),
                g.edges
                    .get(&super::EdgeKeyRef::new("a", "b"))
                    .and_then(|kb| kb.get(&1)),
                "the parallel cell (key 1) must be untouched"
            );
        }

        // No-op replace (same attrs): no revision bump, shadow stays warm.
        let same = g.edge_attrs("a", "b", 0).cloned().unwrap_or_default();
        assert!(g.replace_edge_attrs("a", "b", 0, same));
        assert!(g.slab_shadow_is_warm());

        // Missing edge -> false, shadow left warm/uncorrupted.
        assert!(!g.replace_edge_attrs("a", "z", 0, attr("q", 1)));
        assert!(g.slab_shadow_is_warm());
        let shadow = g.slab_shadow.as_deref().expect("shadow present");
        assert_slab_matches_mg(&g, &shadow.1);
    }

    /// br-r37-c1-thp6w S23: feature-on `node_attrs` READS route through the
    /// always-warm slab. Verified against the unrouted String ground truth
    /// (`g.nodes` direct field access) — non-circular — across present (with
    /// and without attrs) and missing nodes, and after a mutation keeps the
    /// shadow warm so the routed read stays correct.
    #[cfg(any())]
    #[test]
    fn thp6w_s23_node_attrs_reads_route_to_slab() {
        let attr = |k: &str, v: i64| {
            let mut a = AttrMap::new();
            a.insert(k.to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_node_with_attrs("x", attr("c", 1));
        let _ = g.add_edge("x", "y"); // y born attr-less
        // A fresh graph built by individual adds has no shadow yet; sync it warm
        // (individual adds only ADVANCE an existing warm shadow, never create one).
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        // Routed read (-> slab) == String field ground truth.
        assert_eq!(
            g.node_attrs("x"),
            g.nodes.get("x"),
            "attr node routes to slab"
        );
        assert_eq!(g.node_attrs("y"), g.nodes.get("y"), "attr-less node routes");
        assert_eq!(g.node_attrs("missing"), g.nodes.get("missing"), "both None");
        assert!(g.node_attrs("x").is_some_and(|a| a.get("c").is_some()));
        // After an overwrite the shadow stays warm; the routed read reflects it.
        assert!(g.replace_node_attrs("x", attr("d", 9)));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(
            g.node_attrs("x"),
            g.nodes.get("x"),
            "routed read tracks overwrite"
        );
        // With a STALE/absent shadow the read falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_node_with_attrs("p", attr("c", 3));
        assert!(
            !h.slab_shadow_is_warm(),
            "fresh individual-add graph has no shadow"
        );
        assert_eq!(
            h.node_attrs("p"),
            h.nodes.get("p"),
            "unrouted fallback still correct"
        );
    }

    /// br-r37-c1-thp6w S24: feature-on `edge_attrs` READS route through the
    /// always-warm slab. Verified against the unrouted String field ground
    /// truth (`g.edges` direct access) across present cells (incl. a parallel
    /// key), a missing key, and a missing edge, plus the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s24_edge_attrs_reads_route_to_slab() {
        let attr = |k: &str, v: i64| {
            let mut a = AttrMap::new();
            a.insert(k.to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        let gt = |g: &MultiGraph, l: &str, r: &str, k: usize| {
            g.edges
                .get(&super::EdgeKeyRef::new(l, r))
                .and_then(|kb| kb.get(&k))
                .cloned()
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge_with_key_and_attrs("a", "b", 0, attr("w", 1));
        let _ = g.add_edge_with_key_and_attrs("a", "b", 1, attr("w", 2)); // parallel
        let _ = g.add_edge("b", "c");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        // Routed read (-> slab) == String field ground truth.
        assert_eq!(g.edge_attrs("a", "b", 0).cloned(), gt(&g, "a", "b", 0));
        assert_eq!(g.edge_attrs("a", "b", 1).cloned(), gt(&g, "a", "b", 1));
        assert_eq!(g.edge_attrs("a", "b", 9), None, "missing key");
        assert_eq!(g.edge_attrs("a", "z", 0), None, "missing edge");
        // Overwrite advances the shadow; the routed read reflects it.
        assert!(g.replace_edge_attrs("a", "b", 0, attr("x", 8)));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.edge_attrs("a", "b", 0).cloned(), gt(&g, "a", "b", 0));
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge_with_key_and_attrs("p", "q", 0, attr("z", 5));
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.edge_attrs("p", "q", 0).cloned(), gt(&h, "p", "q", 0));
    }

    /// br-r37-c1-thp6w S25: feature-on `edge_keys_vec` READS route through the
    /// always-warm slab (`key_order`). Verified against the unrouted String
    /// field ground truth (`g.edges` bucket keys), incl. parallel keys, a
    /// removal advance, missing edge, and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s25_edge_keys_vec_reads_route_to_slab() {
        let gt = |g: &MultiGraph, l: &str, r: &str| -> Vec<usize> {
            g.edges
                .get(&super::EdgeKeyRef::new(l, r))
                .map(|b| b.keys().copied().collect())
                .unwrap_or_default()
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b"); // auto key 0
        let _ = g.add_edge("a", "b"); // auto key 1
        let _ = g.add_edge("a", "b"); // auto key 2
        let _ = g.add_edge("b", "c");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(
            g.edge_keys_vec("a", "b"),
            gt(&g, "a", "b"),
            "routed key order"
        );
        assert_eq!(g.edge_keys_vec("b", "c"), gt(&g, "b", "c"));
        assert_eq!(
            g.edge_keys_vec("a", "z"),
            Vec::<usize>::new(),
            "missing edge"
        );
        // A per-key removal advances the shadow; the routed read reflects it.
        assert!(g.remove_edge("a", "b", Some(1)));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.edge_keys_vec("a", "b"), gt(&g, "a", "b"), "after removal");
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.edge_keys_vec("p", "q"), gt(&h, "p", "q"));
    }

    /// br-r37-c1-thp6w S26: feature-on `neighbors` READS route through the
    /// always-warm slab. Verified against the unrouted String field ground
    /// truth (`g.adjacency` row keys) incl. row order, a removal advance, a
    /// missing node (None), and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s26_neighbors_reads_route_to_slab() {
        fn gt<'a>(g: &'a MultiGraph, n: &str) -> Option<Vec<&'a str>> {
            g.adjacency
                .get(n)
                .map(|row| row.keys().map(String::as_str).collect())
        }
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        let _ = g.add_edge("a", "c");
        let _ = g.add_edge("a", "b"); // parallel — distinct neighbor unchanged
        let _ = g.add_edge("c", "d");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(
            g.neighbors("a"),
            gt(&g, "a"),
            "routed distinct neighbors, row order"
        );
        assert_eq!(g.neighbors("c"), gt(&g, "c"));
        assert_eq!(g.neighbors("missing"), None, "absent node -> None");
        assert_eq!(g.neighbors("missing"), gt(&g, "missing"));
        // A removal advances the shadow; the routed read reflects it.
        assert!(g.remove_edge("a", "c", None));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.neighbors("a"), gt(&g, "a"), "after removal");
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.neighbors("p"), gt(&h, "p"));
    }

    /// br-r37-c1-thp6w S27: feature-on `degree` READS route through the
    /// always-warm slab. Verified against the unrouted String field ground
    /// truth (same self-loop-double + parallel-count formula over
    /// `g.adjacency`) incl. a removal advance, a missing node (0), and the
    /// no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s27_degree_reads_route_to_slab() {
        let gt = |g: &MultiGraph, n: &str| -> usize {
            g.adjacency.get(n).map_or(0, |row| {
                let mut d = 0;
                for (nbr, keys) in row {
                    let c = keys.len();
                    if nbr.as_str() == n {
                        d += c * 2;
                    } else {
                        d += c;
                    }
                }
                d
            })
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        let _ = g.add_edge("a", "b"); // parallel
        let _ = g.add_edge("a", "c");
        let _ = g.add_edge("a", "a"); // self-loop -> +2 to a
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.degree("a"), gt(&g, "a"), "self-loop double + parallel");
        assert_eq!(g.degree("b"), gt(&g, "b"));
        assert_eq!(g.degree("missing"), 0, "absent node -> 0");
        assert_eq!(g.degree("missing"), gt(&g, "missing"));
        // A removal advances the shadow; the routed read reflects it.
        assert!(g.remove_edge("a", "b", None));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.degree("a"), gt(&g, "a"), "after removal");
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.degree("p"), gt(&h, "p"));
    }

    /// br-r37-c1-thp6w S28: feature-on `has_node` / `has_edge` membership READS
    /// route through the always-warm slab. Verified against the unrouted String
    /// field ground truth incl. isolated node, undirected symmetry, a removal
    /// advance, missing node/edge, and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s28_membership_reads_route_to_slab() {
        let he = |g: &MultiGraph, l: &str, r: &str| {
            g.edges
                .get(&super::EdgeKeyRef::new(l, r))
                .is_some_and(|b| !b.is_empty())
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        let _ = g.add_edge("b", "c");
        let _ = g.add_node("iso"); // isolated node
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        // has_node
        assert_eq!(g.has_node("a"), g.nodes.contains_key("a"));
        assert_eq!(g.has_node("iso"), g.nodes.contains_key("iso"));
        assert_eq!(g.has_node("missing"), g.nodes.contains_key("missing"));
        assert!(g.has_node("iso") && !g.has_node("missing"));
        // has_edge (undirected: symmetric; missing nodes -> false)
        assert_eq!(g.has_edge("a", "b"), he(&g, "a", "b"));
        assert_eq!(g.has_edge("b", "a"), he(&g, "b", "a"));
        assert_eq!(g.has_edge("a", "c"), he(&g, "a", "c"));
        assert_eq!(g.has_edge("x", "y"), he(&g, "x", "y"));
        assert!(g.has_edge("a", "b") && g.has_edge("b", "a") && !g.has_edge("a", "c"));
        // A removal advances the shadow; membership reflects it.
        assert!(g.remove_edge("a", "b", None));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.has_edge("a", "b"), he(&g, "a", "b"));
        assert!(!g.has_edge("a", "b"));
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.has_edge("p", "q"), he(&h, "p", "q"));
        assert_eq!(h.has_node("p"), h.nodes.contains_key("p"));
    }

    /// br-r37-c1-thp6w S29: feature-on `nodes_ordered` READS route through the
    /// always-warm slab. Verified against the unrouted String field ground
    /// truth (`g.nodes.keys()`) + exact insertion order, a node-removal advance
    /// (order compaction), and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s29_nodes_ordered_reads_route_to_slab() {
        fn gt<'a>(g: &'a MultiGraph) -> Vec<&'a str> {
            g.nodes.keys().map(String::as_str).collect()
        }
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("c", "a"); // insertion: c, a
        let _ = g.add_edge("a", "b"); // b
        let _ = g.add_node("z"); // z
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.nodes_ordered(), gt(&g), "routed node order == String");
        assert_eq!(
            g.nodes_ordered(),
            vec!["c", "a", "b", "z"],
            "insertion order"
        );
        // A node removal advances the shadow; order compacts.
        assert!(g.remove_node("a"));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.nodes_ordered(), gt(&g), "after removal");
        assert_eq!(g.nodes_ordered(), vec!["c", "b", "z"]);
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.nodes_ordered(), gt(&h));
    }

    /// br-r37-c1-thp6w S30: feature-on `is_isolate` READS route through the
    /// always-warm slab. Verified against the unrouted String field ground
    /// truth incl. an isolated node, a self-loop node (NOT isolated), a node
    /// with edges, a missing node, a removal that isolates, and the no-shadow
    /// fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s30_is_isolate_reads_route_to_slab() {
        let gt = |g: &MultiGraph, n: &str| -> bool {
            g.nodes.contains_key(n) && g.adjacency.get(n).is_none_or(|row| row.is_empty())
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        let _ = g.add_node("iso"); // isolated
        let _ = g.add_edge("s", "s"); // self-loop -> NOT isolated
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.is_isolate("iso"), gt(&g, "iso"));
        assert!(g.is_isolate("iso"));
        assert_eq!(g.is_isolate("a"), gt(&g, "a"));
        assert!(!g.is_isolate("a"));
        assert_eq!(g.is_isolate("s"), gt(&g, "s"));
        assert!(!g.is_isolate("s"), "self-loop node is not isolated");
        assert_eq!(g.is_isolate("missing"), gt(&g, "missing"));
        assert!(!g.is_isolate("missing"));
        // A removal isolates node "a"; the routed read reflects it.
        assert!(g.remove_edge("a", "b", None));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.is_isolate("a"), gt(&g, "a"));
        assert!(g.is_isolate("a"));
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_node("lonely");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.is_isolate("lonely"), gt(&h, "lonely"));
    }

    /// br-r37-c1-thp6w S31: feature-on `weighted_size_int` READS route through
    /// the always-warm slab. Verified against the unrouted String field ground
    /// truth (same int-sum/missing=1/non-int=None formula over `g.edges`) incl.
    /// parallel + self-loop weights, a removal advance, a non-int (Float) weight
    /// -> None, and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s31_weighted_size_int_routes_to_slab() {
        fn gt(g: &MultiGraph, w: &str) -> Option<i128> {
            let mut total = 0i128;
            for bucket in g.edges.values() {
                for attrs in bucket.values() {
                    let v = match attrs.get(w) {
                        Some(fnx_runtime::CgseValue::Int(x)) => i128::from(*x),
                        Some(_) => return None,
                        None => 1,
                    };
                    total = total.checked_add(v)?;
                }
            }
            Some(total)
        }
        let w = |v: i64| -> AttrMap {
            let mut a = AttrMap::new();
            a.insert("weight".to_owned(), fnx_runtime::CgseValue::Int(v));
            a
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge_with_key_and_attrs("a", "b", 0, w(5));
        let _ = g.add_edge_with_key_and_attrs("a", "b", 1, w(3)); // parallel
        let _ = g.add_edge("b", "c"); // no weight -> counts as 1
        let _ = g.add_edge_with_key_and_attrs("c", "c", 0, w(2)); // self-loop
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(
            g.weighted_size_int("weight"),
            gt(&g, "weight"),
            "routed == String"
        );
        assert_eq!(g.weighted_size_int("weight"), Some(11), "5+3+1+2");
        // A removal advances the shadow; the routed sum reflects it.
        assert!(g.remove_edge("a", "b", Some(0)));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.weighted_size_int("weight"), gt(&g, "weight"));
        assert_eq!(g.weighted_size_int("weight"), Some(6), "3+1+2");
        // A non-int (Float) weight makes it None on both arms.
        let mut fattr = AttrMap::new();
        fattr.insert("weight".to_owned(), fnx_runtime::CgseValue::Float(1.5));
        let _ = g.add_edge_with_key_and_attrs("d", "e", 0, fattr);
        assert!(g.slab_shadow_is_warm());
        assert_eq!(g.weighted_size_int("weight"), gt(&g, "weight"));
        assert!(
            g.weighted_size_int("weight").is_none(),
            "non-int weight -> None"
        );
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge_with_key_and_attrs("p", "q", 0, w(7));
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(h.weighted_size_int("weight"), gt(&h, "weight"));
        assert_eq!(h.weighted_size_int("weight"), Some(7));
    }

    /// br-r37-c1-thp6w S32: feature-on `neighbors_iter` READS route through the
    /// always-warm slab via the `MgNeighborNames` enum iterator. Collected
    /// output verified against the unrouted String field ground truth
    /// (`g.adjacency` row keys) incl. row order, a removal advance, a missing
    /// node (None), and the no-shadow fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s32_neighbors_iter_reads_route_to_slab() {
        fn gt<'a>(g: &'a MultiGraph, n: &str) -> Option<Vec<&'a str>> {
            g.adjacency
                .get(n)
                .map(|row| row.keys().map(String::as_str).collect())
        }
        let collect = |g: &MultiGraph, n: &str| -> Option<Vec<String>> {
            g.neighbors_iter(n)
                .map(|it| it.map(str::to_owned).collect())
        };
        let want = |g: &MultiGraph, n: &str| -> Option<Vec<String>> {
            gt(g, n).map(|v| v.into_iter().map(str::to_owned).collect())
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        let _ = g.add_edge("a", "c");
        let _ = g.add_edge("a", "b"); // parallel — distinct neighbor unchanged
        let _ = g.add_edge("c", "d");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(
            collect(&g, "a"),
            want(&g, "a"),
            "routed iter == String, row order"
        );
        assert_eq!(collect(&g, "c"), want(&g, "c"));
        assert!(g.neighbors_iter("missing").is_none(), "absent node -> None");
        // A removal advances the shadow; the routed iteration reflects it.
        assert!(g.remove_edge("a", "c", None));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(collect(&g, "a"), want(&g, "a"), "after removal");
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(collect(&h, "p"), want(&h, "p"));
    }

    /// br-r37-c1-thp6w S33: feature-on `edge_keys_iter` READS route through the
    /// always-warm slab via the `MgEdgeKeys` enum iterator. Collected output
    /// verified against the unrouted String field ground truth (`g.adjacency`
    /// key set) incl. the Many bucket (parallel keys), the One bucket (single
    /// key), a per-key removal advance, a missing edge (None), and the no-shadow
    /// fallback.
    #[cfg(any())]
    #[test]
    fn thp6w_s33_edge_keys_iter_reads_route_to_slab() {
        fn gt(g: &MultiGraph, l: &str, r: &str) -> Option<Vec<usize>> {
            g.adjacency
                .get(l)?
                .get(r)
                .map(|keys| keys.iter().copied().collect())
        }
        let collect = |g: &MultiGraph, l: &str, r: &str| -> Option<Vec<usize>> {
            g.edge_keys_iter(l, r).map(|it| it.copied().collect())
        };
        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b"); // key 0
        let _ = g.add_edge("a", "b"); // key 1
        let _ = g.add_edge("a", "b"); // key 2 (Many bucket)
        let _ = g.add_edge("b", "c"); // single key (One bucket)
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        assert_eq!(collect(&g, "a", "b"), gt(&g, "a", "b"), "Many == String");
        assert_eq!(collect(&g, "a", "b"), Some(vec![0, 1, 2]));
        assert_eq!(collect(&g, "b", "c"), gt(&g, "b", "c"), "One == String");
        assert_eq!(collect(&g, "b", "c"), Some(vec![0]));
        assert!(g.edge_keys_iter("a", "z").is_none(), "missing edge -> None");
        // A per-key removal advances the shadow; iteration reflects it.
        assert!(g.remove_edge("a", "b", Some(1)));
        assert!(g.slab_shadow_is_warm());
        assert_eq!(collect(&g, "a", "b"), gt(&g, "a", "b"), "after removal");
        assert_eq!(collect(&g, "a", "b"), Some(vec![0, 2]));
        // No-shadow graph falls through to the String store.
        let mut h = MultiGraph::strict();
        let _ = h.add_edge("p", "q");
        assert!(!h.slab_shadow_is_warm());
        assert_eq!(collect(&h, "p", "q"), gt(&h, "p", "q"));
    }

    /// br-r37-c1-thp6w S11 GAUNTLET (production dual-write shadow): with the
    /// `mg-int-storage` feature on, every instrumented mutation (single-edge
    /// add incl. autocreate/parallel/self-loop/attr-merge, keyed batch,
    /// edge/node removal with slot recycling, node-attr set (S17), copy-walk
    /// row reorder (S18)) must ADVANCE the shadow in place (warm +
    /// byte-identical), and every UNINSTRUMENTED mutation must leave it stale
    /// (revision key) — never silently wrong.
    #[cfg(any())]
    #[test]
    fn thp6w_s11_slab_shadow_dual_write_gauntlet() {
        let shadow_parity = |g: &MultiGraph| {
            let shadow = g.slab_shadow.as_deref().expect("shadow must be present");
            assert_eq!(shadow.0, g.revision, "shadow must be warm (advanced)");
            assert_slab_matches_mg(g, &shadow.1);
        };

        let mut g = MultiGraph::strict();
        let _ = g.add_edge("a", "b");
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        shadow_parity(&g);

        // Instrumented single-edge adds.
        let _ = g.add_edge("b", "c"); // autocreated endpoint
        shadow_parity(&g);
        let _ = g.add_edge("a", "b"); // parallel key
        shadow_parity(&g);
        let _ = g.add_edge("d", "d"); // self-loop, fresh node
        shadow_parity(&g);
        let mut attrs = AttrMap::new();
        attrs.insert("w".to_owned(), fnx_runtime::CgseValue::Int(3));
        let _ = g.add_edge_with_key_and_attrs("a", "b", 0, attrs); // attr merge
        shadow_parity(&g);

        // Instrumented keyed batch (write-through).
        let _ = g.extend_keyed_edges_with_attrs_unrecorded(vec![
            ("x".to_owned(), "y".to_owned(), 0, AttrMap::new()),
            ("y".to_owned(), "x".to_owned(), 1, AttrMap::new()),
            ("a".to_owned(), "x".to_owned(), 0, AttrMap::new()),
        ]);
        shadow_parity(&g);

        // Instrumented removals: parallel key (next_back), last key, node
        // removal, then slot recycling via a fresh name.
        assert!(g.remove_edge("a", "b", None));
        shadow_parity(&g);
        assert!(g.remove_edge("a", "b", None));
        shadow_parity(&g);
        assert!(g.remove_node("b"));
        shadow_parity(&g);
        let _ = g.add_edge("recycled", "c");
        shadow_parity(&g);

        // br-r37-c1-thp6w S18: an order-only mutation (copy-walk reorder) now
        // ADVANCES the warm shadow in place — rows reordered on the slab,
        // revision unchanged so it stays warm and byte-identical.
        g.reorder_rows_for_nx_copy_walk();
        assert!(
            g.slab_shadow_is_warm(),
            "apply_row_orders must advance (not drop) the warm shadow"
        );
        shadow_parity(&g);
        // A full rebuild still reproduces the same post-reorder row orders.
        g.sync_slab_shadow();
        shadow_parity(&g);

        // Uninstrumented content mutations leave the shadow STALE, never wrong.
        g.add_node("island");
        assert!(
            !g.slab_shadow_is_warm(),
            "uninstrumented mutation must stale the shadow"
        );
        g.sync_slab_shadow();
        shadow_parity(&g);
        g.clear_edges();
        assert!(!g.slab_shadow_is_warm());
        g.sync_slab_shadow();
        shadow_parity(&g);

        // br-r37-c1-thp6w S13 ROUTE GATE: with a warm shadow the production
        // `edges_ordered_borrowed` serves from the slab; the sequence must be
        // byte-identical to what the String walk produced while the shadow
        // was STALE (owned snapshot so it survives the sync).
        let _ = g.add_edge("r1", "r2"); // stales nothing — shadow advances...
        g.add_node("stale_maker"); // ...so force staleness via an uninstrumented op
        assert!(!g.slab_shadow_is_warm());
        let _ = g.add_edge("r2", "r1"); // parallel via reverse orientation (shadow stays stale)
        let _ = g.add_edge("r3", "r3");
        let expected: Vec<(String, String, usize, AttrMap)> = g
            .edges_ordered_borrowed() // stale shadow -> String walk
            .into_iter()
            .map(|(l, r, k, a)| (l.to_owned(), r.to_owned(), k, a.clone()))
            .collect();
        // Same gate for the OWNED `edges_ordered` route (captured stale first).
        let expected_owned: Vec<(String, String, usize, AttrMap)> = g
            .edges_ordered() // stale shadow -> String walk (owned)
            .into_iter()
            .map(|e| (e.left, e.right, e.key, e.attrs))
            .collect();
        g.sync_slab_shadow();
        assert!(g.slab_shadow_is_warm());
        let served: Vec<(String, String, usize, AttrMap)> = g
            .edges_ordered_borrowed() // warm shadow -> slab walk
            .into_iter()
            .map(|(l, r, k, a)| (l.to_owned(), r.to_owned(), k, a.clone()))
            .collect();
        assert_eq!(
            served, expected,
            "shadow-served edges_ordered must equal the String walk"
        );
        let served_owned: Vec<(String, String, usize, AttrMap)> = g
            .edges_ordered() // warm shadow -> slab walk (owned)
            .into_iter()
            .map(|e| (e.left, e.right, e.key, e.attrs))
            .collect();
        assert_eq!(
            served_owned, expected_owned,
            "shadow-served owned edges_ordered must equal the String walk"
        );
    }

    /// br-r37-c1-thp6w S5 A/B: pure storage-representation tax of the String-
    /// keyed MultiGraph core vs the index-keyed prototype layout, on the SAME
    /// pre-resolved (u_idx, v_idx, key) stream via the SAME-shape bulk loaders
    /// (`extend_fresh_int_prefix_keyed_edges_unrecorded` vs
    /// `bulk_load_int_prefix`) — no canonicalization, no Python boundary, no
    /// per-edge ledger in either arm. Paired-interleaved (current, proto,
    /// current-null per round), medians over 9 rounds.
    /// `cargo test --release -p fnx-classes --lib thp6w_s5_int_storage_construction_ab -- --ignored --nocapture`
    #[test]
    #[ignore = "paired A/B benchmark; run --release with --ignored --nocapture"]
    fn thp6w_s5_int_storage_construction_ab() {
        use super::multigraph_storage::MgIntStorageProto;
        use std::collections::HashMap;
        use std::hint::black_box;
        use std::time::Instant;

        fn push_edge(
            stream: &mut Vec<(usize, usize, usize)>,
            key_counter: &mut HashMap<(usize, usize), usize>,
            u: usize,
            v: usize,
        ) {
            let entry = key_counter.entry((u.min(v), u.max(v))).or_insert(0);
            stream.push((u, v, *entry));
            *entry += 1;
        }

        let n = 20000usize;
        let mut stream = Vec::new();
        let mut key_counter = HashMap::new();
        for i in 0..n {
            push_edge(&mut stream, &mut key_counter, i, (i + 1) % n);
        }
        // Deterministic LCG chords (incl. incidental self-loops) + explicit parallels.
        let mut state = 0x2545_F491_4F6C_DD1D_u64;
        let draw = |state: &mut u64| -> usize {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            usize::try_from(*state >> 33).unwrap() % n
        };
        for _ in 0..3 * n {
            let u = draw(&mut state);
            let v = draw(&mut state);
            push_edge(&mut stream, &mut key_counter, u, v);
        }
        for i in (0..2000).step_by(2) {
            push_edge(&mut stream, &mut key_counter, i, i + 1);
        }

        let time_current = |stream: &[(usize, usize, usize)]| -> f64 {
            let t0 = Instant::now();
            let mut g = MultiGraph::strict();
            let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
            let dt = t0.elapsed().as_secs_f64();
            black_box(&g);
            dt
        };
        let time_proto = |stream: &[(usize, usize, usize)]| -> f64 {
            let t0 = Instant::now();
            let proto = MgIntStorageProto::bulk_load_int_prefix(n, stream.iter().copied());
            let dt = t0.elapsed().as_secs_f64();
            black_box(&proto);
            dt
        };
        // br-r37-c1-thp6w S6: compact One/Many bucket arm.
        let time_compact = |stream: &[(usize, usize, usize)]| -> f64 {
            let t0 = Instant::now();
            let compact = super::multigraph_storage::MgIntStorageProtoCompact::bulk_load_int_prefix(
                n,
                stream.iter().copied(),
            );
            let dt = t0.elapsed().as_secs_f64();
            black_box(&compact);
            dt
        };

        // Structural agreement between the arms (once, outside timing):
        // the real store's derived integer rows must equal both proto rows.
        let mut g = MultiGraph::strict();
        let _ = g.extend_fresh_int_prefix_keyed_edges_unrecorded(n, stream.iter().copied());
        let proto = MgIntStorageProto::bulk_load_int_prefix(n, stream.iter().copied());
        let compact = super::multigraph_storage::MgIntStorageProtoCompact::bulk_load_int_prefix(
            n,
            stream.iter().copied(),
        );
        g.with_int_adjacency(|adj| {
            for (i, row) in adj.iter().enumerate() {
                let proto_row: Vec<usize> = proto.rows[i].keys().copied().collect();
                assert_eq!(row, &proto_row, "derived integer row {i} must agree");
                let compact_row: Vec<usize> = compact.rows[i].keys().copied().collect();
                assert_eq!(row, &compact_row, "compact integer row {i} must agree");
            }
        });
        assert_eq!(
            proto.edge_count,
            g.edge_count(),
            "A/B arms built different graphs"
        );
        assert_eq!(
            compact.edge_count,
            g.edge_count(),
            "compact arm built a different graph"
        );
        // br-r37-c1-thp6w S9: slab arm — must hold the compact win.
        let time_slab = |stream: &[(usize, usize, usize)]| -> f64 {
            let t0 = Instant::now();
            let slab = super::multigraph_storage::MgSlabStorage::bulk_load_int_prefix(
                n,
                stream.iter().copied(),
            );
            let dt = t0.elapsed().as_secs_f64();
            black_box(&slab);
            dt
        };
        let slab = super::multigraph_storage::MgSlabStorage::bulk_load_int_prefix(
            n,
            stream.iter().copied(),
        );
        g.with_int_adjacency(|adj| {
            for (i, row) in adj.iter().enumerate() {
                let slab_row: Vec<usize> = slab.rows[i].keys().copied().collect();
                assert_eq!(row, &slab_row, "slab integer row {i} must agree");
            }
        });
        assert_eq!(
            slab.edge_count,
            g.edge_count(),
            "slab arm built a different graph"
        );

        let median = |samples: &mut Vec<f64>| -> f64 {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let (mut cur, mut pro, mut com, mut sla, mut nul) =
            (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
        for _ in 0..9 {
            cur.push(time_current(&stream));
            pro.push(time_proto(&stream));
            com.push(time_compact(&stream));
            sla.push(time_slab(&stream));
            nul.push(time_current(&stream));
        }
        let (mc, mp, mk, ms, mn) = (
            median(&mut cur),
            median(&mut pro),
            median(&mut com),
            median(&mut sla),
            median(&mut nul),
        );
        println!(
            "THP6W_S5_AB n={n} m={} current={mc:.6}s proto={mp:.6}s compact={mk:.6}s slab={ms:.6}s ratio_current_over_proto={:.3} ratio_current_over_compact={:.3} ratio_current_over_slab={:.3} ratio_compact_over_slab={:.3} null_current_over_current={:.3}",
            stream.len(),
            mc / mp,
            mc / mk,
            mc / ms,
            mk / ms,
            mc / mn,
        );
    }

    #[test]
    fn thp6w_int_adjacency_cache_is_fresh_per_clone() {
        let mut g = MultiGraph::strict();
        for i in 0..4 {
            g.add_node(format!("n{i}"));
        }
        let _ = g.add_edge("n0", "n1");
        // Populate g's memo.
        assert_int_adjacency_matches(&g);
        // Clone, then mutate the CLONE differently. The clone must NOT serve g's rows
        // (fresh-per-clone memo), and g must keep its own.
        let mut clone = g.clone();
        let _ = clone.add_edge("n2", "n3");
        assert_int_adjacency_matches(&clone);
        assert_int_adjacency_matches(&g);
        // And mutate g after the clone; both stay self-consistent.
        let _ = g.add_edge("n0", "n2");
        assert_int_adjacency_matches(&g);
        assert_int_adjacency_matches(&clone);
    }

    fn single_attr(key: &str, value: &str) -> AttrMap {
        let mut attrs = AttrMap::new();
        attrs.insert(key.to_owned(), CgseValue::from(value));
        attrs
    }

    #[test]
    fn edge_slot_rows_follow_adj_order_and_refresh_after_mutation() {
        let mut graph = Graph::strict();
        let weighted = |value| {
            let mut attrs = AttrMap::new();
            attrs.insert("weight".to_owned(), CgseValue::Int(value));
            attrs
        };
        graph
            .add_edge_with_attrs("a", "b", weighted(1))
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("a", "c", weighted(2))
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("b", "c", weighted(3))
            .expect("edge add should succeed");

        let a = graph.get_node_index("a").expect("a exists");
        graph.with_edge_slots_by_neighbor(|rows| {
            let weights = rows[a]
                .iter()
                .map(|&slot| {
                    graph
                        .edge_attrs_by_slot(slot)
                        .and_then(|attrs| attrs.get("weight"))
                })
                .collect::<Vec<_>>();
            assert_eq!(
                weights,
                vec![Some(&CgseValue::Int(1)), Some(&CgseValue::Int(2))]
            );
        });

        graph.apply_row_orders(&[("a".to_owned(), vec!["c".to_owned(), "b".to_owned()])]);
        graph.with_edge_slots_by_neighbor(|rows| {
            let weights = rows[a]
                .iter()
                .map(|&slot| {
                    graph
                        .edge_attrs_by_slot(slot)
                        .and_then(|attrs| attrs.get("weight"))
                })
                .collect::<Vec<_>>();
            assert_eq!(
                weights,
                vec![Some(&CgseValue::Int(2)), Some(&CgseValue::Int(1))]
            );
        });

        assert!(graph.remove_edge("a", "c"));
        graph.with_edge_slots_by_neighbor(|rows| {
            assert_eq!(rows[a].len(), 1);
            assert_eq!(
                graph
                    .edge_attrs_by_slot(rows[a][0])
                    .and_then(|attrs| attrs.get("weight")),
                Some(&CgseValue::Int(1))
            );
        });
    }

    #[test]
    fn edges_ordered_tracks_node_and_neighbor_iteration_order() {
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("b", "c", AttrMap::new())
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("a", "c", AttrMap::new())
            .expect("edge add should succeed");

        let pairs = graph
            .edges_ordered()
            .into_iter()
            .map(|edge| (edge.left, edge.right))
            .collect::<Vec<(String, String)>>();
        assert_eq!(
            pairs,
            vec![
                ("a".to_owned(), "b".to_owned()),
                ("a".to_owned(), "c".to_owned()),
                ("b".to_owned(), "c".to_owned()),
            ]
        );
    }

    #[test]
    fn edges_ordered_preserves_traversed_endpoint_orientation() {
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("2", "1", AttrMap::new())
            .expect("edge add should succeed");

        let pairs = graph
            .edges_ordered()
            .into_iter()
            .map(|edge| (edge.left, edge.right))
            .collect::<Vec<(String, String)>>();
        assert_eq!(pairs, vec![("2".to_owned(), "1".to_owned())]);

        let borrowed_pairs = graph
            .edges_ordered_borrowed()
            .into_iter()
            .map(|(left, right, _)| (left.to_owned(), right.to_owned()))
            .collect::<Vec<(String, String)>>();
        assert_eq!(borrowed_pairs, vec![("2".to_owned(), "1".to_owned())]);
    }

    #[test]
    fn edges_ordered_uses_node_order_for_preexisting_nodes() {
        let mut graph = Graph::strict();
        graph.add_node("1".to_owned());
        graph.add_node("2".to_owned());
        graph
            .add_edge_with_attrs("2", "1", AttrMap::new())
            .expect("edge add should succeed");

        let pairs = graph
            .edges_ordered()
            .into_iter()
            .map(|edge| (edge.left, edge.right))
            .collect::<Vec<(String, String)>>();
        assert_eq!(pairs, vec![("1".to_owned(), "2".to_owned())]);
    }

    #[test]
    fn edge_storage_order_index_iter_tracks_mutations() {
        let mut graph = Graph::strict();
        graph.add_node("c");
        graph.add_node("a");
        graph.add_node("b");
        graph
            .add_edge_with_attrs("c", "a", single_attr("weight", "1"))
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("b", "c", single_attr("weight", "2"))
            .expect("edge add should succeed");
        graph
            .add_edge_with_attrs("a", "c", single_attr("color", "red"))
            .expect("duplicate edge update should succeed");

        let indexed_edges = |graph: &Graph| {
            graph
                .edges_storage_order_index_iter()
                .map(|(left, right, attrs)| {
                    (
                        graph
                            .get_node_name(left)
                            .expect("left endpoint index should resolve")
                            .to_owned(),
                        graph
                            .get_node_name(right)
                            .expect("right endpoint index should resolve")
                            .to_owned(),
                        attrs.get("weight").cloned(),
                    )
                })
                .collect::<Vec<_>>()
        };

        assert_eq!(
            indexed_edges(&graph),
            vec![
                (
                    "a".to_owned(),
                    "c".to_owned(),
                    Some(CgseValue::String("1".to_owned())),
                ),
                (
                    "b".to_owned(),
                    "c".to_owned(),
                    Some(CgseValue::String("2".to_owned())),
                ),
            ]
        );

        assert!(graph.remove_edge("a", "c"));
        assert_eq!(
            indexed_edges(&graph),
            vec![(
                "b".to_owned(),
                "c".to_owned(),
                Some(CgseValue::String("2".to_owned())),
            )]
        );

        assert!(graph.remove_node("b"));
        assert!(indexed_edges(&graph).is_empty());
    }

    fn assert_graph_core_invariants(graph: &Graph) {
        let mut unique_edges = BTreeSet::new();
        for node in graph.nodes_ordered() {
            let neighbors = graph
                .neighbors(node)
                .expect("graph nodes should always have adjacency buckets");
            for neighbor in neighbors {
                assert!(graph.has_node(neighbor));
                assert!(graph.has_edge(node, neighbor));
                let reverse_neighbors = graph
                    .neighbors(neighbor)
                    .expect("neighbor should always have adjacency bucket");
                assert!(reverse_neighbors.contains(&node));
                unique_edges.insert(canonical_edge(node, neighbor));
            }
        }
        assert_eq!(graph.edge_count(), unique_edges.len());
    }

    fn assert_multigraph_core_invariants(graph: &MultiGraph) {
        let mut edge_instances = BTreeSet::new();
        for node in graph.nodes_ordered() {
            let neighbors = graph
                .neighbors(node)
                .expect("multigraph nodes should always have adjacency buckets");
            for neighbor in neighbors {
                assert!(graph.has_node(neighbor));
                assert!(graph.has_edge(node, neighbor));
                let reverse_neighbors = graph
                    .neighbors(neighbor)
                    .expect("neighbor should always have adjacency bucket");
                assert!(reverse_neighbors.contains(&node));
                let keys = graph
                    .edge_keys(node, neighbor)
                    .expect("parallel edge bucket should exist");
                for key in keys {
                    let canonical = canonical_edge(node, neighbor);
                    edge_instances.insert((canonical.0, canonical.1, key));
                }
            }
        }
        assert_eq!(graph.edge_count(), edge_instances.len());
    }

    fn assert_decision_record_schema(record: &DecisionRecord, expected_mode: CompatibilityMode) {
        assert!(record.ts_unix_ms > 0);
        assert!(!record.operation.trim().is_empty());
        assert_eq!(record.mode, expected_mode);
        assert!((0.0..=1.0).contains(&record.incompatibility_probability));
        assert!(!record.rationale.trim().is_empty());
        assert!(!record.evidence.is_empty());
        for term in &record.evidence {
            assert!(!term.signal.trim().is_empty());
            assert!(!term.observed_value.trim().is_empty());
        }
    }

    #[test]
    fn add_edge_autocreates_nodes_and_preserves_order() {
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("edge insert should succeed");
        graph
            .add_edge_with_attrs("a", "c", AttrMap::new())
            .expect("edge insert should succeed");

        assert_eq!(graph.node_count(), 3);
        assert_eq!(graph.edge_count(), 2);
        assert_eq!(graph.nodes_ordered(), vec!["a", "b", "c"]);
        assert_eq!(graph.neighbors("a"), Some(vec!["b", "c"]));
    }

    #[test]
    fn add_edge_empty_endpoint_resolution_preserves_autocreation_effects() {
        let mut graph = Graph::strict();
        let before = graph.revision();

        graph
            .add_edge("c", "a")
            .expect("fresh endpoints should be autocreated");

        // The single-probe endpoint resolver keeps the public storage effects
        // of two empty add_node calls plus the new edge mutation: first-seen
        // node order, one adjacency bucket per node, and three revision bumps.
        assert_eq!(graph.nodes_ordered(), vec!["c", "a"]);
        assert_eq!(graph.neighbors("c"), Some(vec!["a"]));
        assert_eq!(graph.neighbors("a"), Some(vec!["c"]));
        assert_eq!(graph.revision(), before + 3);

        graph
            .add_edge("a", "c")
            .expect("an existing empty edge is a no-op");
        assert_eq!(graph.nodes_ordered(), vec!["c", "a"]);
        assert_eq!(graph.revision(), before + 3);
    }

    #[test]
    fn extend_edges_unrecorded_preserves_adjacency_and_records_once() {
        let mut graph = Graph::strict();
        graph.add_node("a");
        graph.add_node("b");
        graph.add_node("c");
        let before = graph.evidence_ledger().records().len();

        let inserted = graph.extend_edges_unrecorded([("a", "b"), ("a", "c"), ("b", "a")]);

        assert_eq!(inserted, 2);
        assert_eq!(graph.edge_count(), 2);
        assert_eq!(graph.neighbors("a"), Some(vec!["b", "c"]));
        let records = graph.evidence_ledger().records();
        assert_eq!(records.len(), before + 1);
        assert_eq!(
            records.last().map(|record| record.operation.as_ref()),
            Some("extend_edges_unrecorded")
        );
    }

    #[test]
    fn extend_existing_index_edges_unrecorded_matches_string_batch_on_int_prefix() {
        let nodes = (0..12).map(|node| node.to_string()).collect::<Vec<_>>();
        let edge_indices = vec![(10usize, 2usize), (2, 10), (3, 3), (1, 11), (11, 1)];
        let edge_strings = edge_indices
            .iter()
            .map(|(left, right)| (left.to_string(), right.to_string()))
            .collect::<Vec<_>>();

        let mut by_string = Graph::strict();
        let mut by_index = Graph::strict();
        let _ = by_string.extend_nodes_unrecorded(nodes.clone());
        let _ = by_index.extend_nodes_unrecorded(nodes);

        assert!(by_index.nodes_are_contiguous_int_prefix());
        assert_eq!(by_string.extend_edges_unrecorded(edge_strings), 3);
        assert_eq!(
            by_index.extend_existing_index_edges_unrecorded(edge_indices),
            3
        );

        assert_eq!(by_index.snapshot(), by_string.snapshot());
        assert_graph_core_invariants(&by_index);
    }

    #[test]
    fn extend_edges_with_attrs_unrecorded_matches_add_edge_with_attrs() {
        // br-r37-c1-pr8q6: bulk attributed insertion must be observationally
        // identical to a sequence of add_edge_with_attrs calls (node order,
        // adjacency order, attr merge on duplicates) minus the per-edge
        // ledger records.
        let mut attrs1 = AttrMap::new();
        attrs1.insert("w".to_owned(), CgseValue::Int(1));
        let mut attrs2 = AttrMap::new();
        attrs2.insert("w".to_owned(), CgseValue::Int(7));
        attrs2.insert("c".to_owned(), CgseValue::String("x".to_owned()));

        let mut reference = Graph::strict();
        reference
            .add_edge_with_attrs("a", "b", attrs1.clone())
            .unwrap();
        reference
            .add_edge_with_attrs("b", "c", AttrMap::new())
            .unwrap();
        // duplicate edge: attrs merge
        reference
            .add_edge_with_attrs("b", "a", attrs2.clone())
            .unwrap();
        // self-loop
        reference
            .add_edge_with_attrs("d", "d", attrs1.clone())
            .unwrap();

        let mut bulk = Graph::strict();
        let before = bulk.evidence_ledger().records().len();
        let inserted = bulk.extend_edges_with_attrs_unrecorded([
            ("a".to_owned(), "b".to_owned(), attrs1.clone()),
            ("b".to_owned(), "c".to_owned(), AttrMap::new()),
            ("b".to_owned(), "a".to_owned(), attrs2.clone()),
            ("d".to_owned(), "d".to_owned(), attrs1.clone()),
        ]);

        assert_eq!(inserted, 3);
        assert_eq!(bulk.edge_count(), reference.edge_count());
        assert_eq!(bulk.nodes_ordered(), reference.nodes_ordered());
        for node in bulk.nodes_ordered() {
            assert_eq!(bulk.neighbors(node), reference.neighbors(node));
        }
        assert_eq!(bulk.edge_attrs("a", "b"), reference.edge_attrs("a", "b"));
        assert_eq!(bulk.edge_attrs("d", "d"), reference.edge_attrs("d", "d"));
        // one summary record, not one per edge
        assert_eq!(bulk.evidence_ledger().records().len(), before + 1);
    }

    #[test]
    fn multigraph_int_prefix_keyed_edges_match_string_batch() {
        let indexed_edges = vec![
            (0usize, 1usize, 0usize),
            (1, 2, 0),
            (2, 0, 0),
            (0, 1, 1),
            (2, 2, 0),
        ];
        let string_edges = indexed_edges
            .iter()
            .map(|(left, right, key)| (left.to_string(), right.to_string(), *key, AttrMap::new()))
            .collect::<Vec<_>>();

        let mut by_string = MultiGraph::strict();
        let mut by_index = MultiGraph::strict();

        assert_eq!(
            by_string.extend_keyed_edges_with_attrs_unrecorded(string_edges),
            indexed_edges.len()
        );
        assert_eq!(
            by_index.extend_fresh_int_prefix_keyed_edges_unrecorded(3, indexed_edges),
            5
        );

        assert_eq!(by_index.snapshot(), by_string.snapshot());
        assert_multigraph_core_invariants(&by_index);
    }

    #[test]
    fn extend_nodes_unrecorded_preserves_order_and_records_once() {
        let mut graph = Graph::strict();
        graph.add_node("1");
        let before = graph.evidence_ledger().records().len();

        let inserted =
            graph.extend_nodes_unrecorded(["0".to_owned(), "1".to_owned(), "2".to_owned()]);

        assert_eq!(inserted, 2);
        assert_eq!(graph.node_count(), 3);
        assert_eq!(graph.nodes_ordered(), vec!["1", "0", "2"]);
        assert_eq!(graph.neighbor_count("0"), 0);
        assert_eq!(graph.neighbor_count("2"), 0);
        let records = graph.evidence_ledger().records();
        assert_eq!(records.len(), before + 1);
        assert_eq!(
            records.last().map(|record| record.operation.as_ref()),
            Some("extend_nodes_unrecorded")
        );
    }

    #[test]
    fn neighbors_iter_preserves_deterministic_order() {
        let mut graph = Graph::strict();
        graph.add_edge("a", "b").expect("edge add should succeed");
        graph.add_edge("a", "c").expect("edge add should succeed");
        graph.add_edge("a", "d").expect("edge add should succeed");

        let neighbors = graph
            .neighbors_iter("a")
            .expect("neighbors should exist")
            .collect::<Vec<&str>>();
        assert_eq!(neighbors, vec!["b", "c", "d"]);
    }

    #[test]
    fn neighbor_count_matches_neighbors_len() {
        let mut graph = Graph::strict();
        graph.add_edge("a", "b").expect("edge add should succeed");
        graph.add_edge("a", "c").expect("edge add should succeed");
        assert_eq!(graph.neighbor_count("a"), 2);
        assert_eq!(graph.neighbor_count("missing"), 0);
    }

    #[test]
    fn repeated_edge_updates_attrs_in_place() {
        let mut graph = Graph::strict();
        let mut first = AttrMap::new();
        first.insert("weight".to_owned(), "1".into());
        graph
            .add_edge_with_attrs("a", "b", first)
            .expect("edge insert should succeed");

        let mut second = AttrMap::new();
        second.insert("color".to_owned(), "blue".into());
        graph
            .add_edge_with_attrs("b", "a", second)
            .expect("edge update should succeed");

        let attrs = graph
            .edge_attrs("a", "b")
            .expect("edge attrs should be present");
        assert_eq!(
            attrs.get("weight"),
            Some(&CgseValue::String("1".to_owned()))
        );
        assert_eq!(
            attrs.get("color"),
            Some(&CgseValue::String("blue".to_owned()))
        );
        assert_eq!(graph.edge_count(), 1);
    }

    #[test]
    fn complete_graph_bulk_constructor_preserves_ordered_contract() {
        let graph = Graph::complete_graph(CompatibilityMode::Strict, 5);

        assert_eq!(graph.node_count(), 5);
        assert_eq!(graph.edge_count(), 10);
        assert_eq!(graph.nodes_ordered(), vec!["0", "1", "2", "3", "4"]);
        assert_eq!(
            graph.neighbors("0").expect("node 0 should exist"),
            vec!["1", "2", "3", "4"]
        );
        assert_eq!(
            graph.neighbors("4").expect("node 4 should exist"),
            vec!["0", "1", "2", "3"]
        );
        assert_eq!(
            graph
                .edges_ordered()
                .into_iter()
                .map(|edge| (edge.left, edge.right))
                .collect::<Vec<_>>(),
            vec![
                ("0".to_owned(), "1".to_owned()),
                ("0".to_owned(), "2".to_owned()),
                ("0".to_owned(), "3".to_owned()),
                ("0".to_owned(), "4".to_owned()),
                ("1".to_owned(), "2".to_owned()),
                ("1".to_owned(), "3".to_owned()),
                ("1".to_owned(), "4".to_owned()),
                ("2".to_owned(), "3".to_owned()),
                ("2".to_owned(), "4".to_owned()),
                ("3".to_owned(), "4".to_owned()),
            ]
        );

        let operations = graph
            .evidence_ledger()
            .records()
            .iter()
            .map(|record| record.operation.as_ref())
            .collect::<Vec<_>>();
        assert_eq!(operations, vec!["complete_graph_bulk"]);
    }

    #[test]
    fn remove_node_removes_incident_edges() {
        let mut graph = Graph::strict();
        graph.add_edge("a", "b").expect("edge add should succeed");
        graph.add_edge("b", "c").expect("edge add should succeed");
        assert!(graph.remove_node("b"));
        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 0);
    }

    /// br-r37-c1-8n3j3: attribution bench for the per-mutation CGSE decision
    /// record. `Graph::add_edge_with_attrs` calls `record_decision` twice per
    /// edge (5 `EvidenceTerm`s total), and every field of a `DecisionRecord`
    /// that comes from a `&'static str` is materialised as an owned `String`.
    /// This measures, in one invocation and interleaved, how much of a single
    /// `add_edge_with_attrs` is the ledger: arm A records the exact terms
    /// `add_edge_with_attrs` builds, arm B builds the identical terms and
    /// discards them. `add_edge_full` is the denominator the ratio is against.
    /// `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib ledger_record_cost_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn ledger_record_cost_ab() {
        use fnx_runtime::{EvidenceTerm, RuntimePolicy, bool_evidence, count_evidence};
        use std::hint::black_box;
        use std::time::Instant;

        const EDGES: usize = 20_000;
        const ROUNDS: usize = 21;
        const RATIONALE: &str = "argmin expected loss over {allow,full_validate,fail_closed}";

        // The exact evidence `add_edge_with_attrs` builds for a fresh
        // non-self-loop edge between two autocreated nodes.
        fn gate_terms() -> Vec<EvidenceTerm> {
            vec![EvidenceTerm {
                signal: "unknown_incompatible_feature".into(),
                observed_value: bool_evidence(false),
                log_likelihood_ratio: 12.0,
            }]
        }
        fn outcome_terms(edge_attr_count: usize) -> Vec<EvidenceTerm> {
            vec![
                EvidenceTerm {
                    signal: "self_loop".into(),
                    observed_value: bool_evidence(false),
                    log_likelihood_ratio: -0.5,
                },
                EvidenceTerm {
                    signal: "edge_attr_count".into(),
                    observed_value: count_evidence(edge_attr_count),
                    log_likelihood_ratio: -2.0,
                },
                EvidenceTerm {
                    signal: "left_autocreated".into(),
                    observed_value: bool_evidence(true),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "right_autocreated".into(),
                    observed_value: bool_evidence(true),
                    log_likelihood_ratio: -1.25,
                },
            ]
        }

        // br-r37-c1-jc9e4: the record the AUTOCREATED ENDPOINT files.
        // `add_edge_with_attrs` creates a missing endpoint via `add_node` ->
        // `add_node_with_attrs`, which calls `record_decision` UNCONDITIONALLY,
        // so an edge-BUILDING workload files this record in addition to the
        // outcome record. Two evidence terms, against the outcome record's four.
        fn node_terms() -> Vec<EvidenceTerm> {
            vec![
                EvidenceTerm {
                    signal: "node_preexisting".into(),
                    observed_value: bool_evidence(false),
                    log_likelihood_ratio: -3.0,
                },
                EvidenceTerm {
                    signal: "attrs_count".into(),
                    observed_value: count_evidence(0),
                    log_likelihood_ratio: -1.0,
                },
            ]
        }

        // Arm A: build the terms AND record them (the shipped behaviour).
        let recorded = || {
            let mut policy = RuntimePolicy::strict();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                policy.record("add_edge", action, 0.08, RATIONALE, gate_terms());
                policy.record(
                    "add_edge",
                    action,
                    0.08,
                    RATIONALE,
                    outcome_terms(index & 3),
                );
            }
            let elapsed = start.elapsed();
            assert_eq!(policy.decision_log().total_recorded(), (EDGES * 2) as u64);
            elapsed
        };

        // Arm A1: the shipped path after br-r37-c1-eo88t — the gate decision is
        // taken without a record, so an allowed edge writes only the outcome
        // record. Same bounded ledger as arm A, half the traffic.
        let recorded_single = || {
            let mut policy = RuntimePolicy::strict();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                policy.record(
                    "add_edge",
                    action,
                    0.08,
                    RATIONALE,
                    outcome_terms(index & 3),
                );
            }
            let elapsed = start.elapsed();
            assert_eq!(policy.decision_log().total_recorded(), EDGES as u64);
            elapsed
        };

        // Arm A2: two records per edge — the autocreated endpoint's `add_node`
        // record PLUS the `add_edge` outcome record. This was the shipped
        // behaviour until br-r37-c1-wa1b9 stopped the internal autocreation
        // filing its own record; it is now the COUNTERFACTUAL that prices what
        // that change removed, and A1 is the shipped path. Keep it: it is the
        // only arm that shows what a per-call (rather than per-operation)
        // ledger contract would cost on the hottest mutation path.
        let recorded_edge_build = || {
            let mut policy = RuntimePolicy::strict();
            let start = Instant::now();
            for index in 0..EDGES {
                let node_action = policy.action_for(0.0, false);
                policy.record("add_node", node_action, 0.0, RATIONALE, node_terms());
                let action = policy.action_for(0.08, false);
                policy.record(
                    "add_edge",
                    action,
                    0.08,
                    RATIONALE,
                    outcome_terms(index & 3),
                );
            }
            let elapsed = start.elapsed();
            assert_eq!(policy.decision_log().total_recorded(), (EDGES * 2) as u64);
            elapsed
        };

        // Arm A0: the pre-br-r37-c1-8n3j3 ledger — the identical records pushed
        // into an unbounded `Vec` that is never retired. This is the incumbent
        // arm for the bound, run in the SAME invocation as arm A.
        let unbounded = || {
            let policy = RuntimePolicy::strict();
            let mode = policy.mode();
            let mut records: Vec<DecisionRecord> = Vec::new();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                records.push(DecisionRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: "add_edge".into(),
                    mode,
                    action,
                    incompatibility_probability: 0.08,
                    rationale: RATIONALE.into(),
                    evidence: gate_terms(),
                });
                records.push(DecisionRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: "add_edge".into(),
                    mode,
                    action,
                    incompatibility_probability: 0.08,
                    rationale: RATIONALE.into(),
                    evidence: outcome_terms(index & 3),
                });
            }
            let elapsed = start.elapsed();
            assert_eq!(records.len(), EDGES * 2);
            elapsed
        };

        // Arm B: build the identical terms, skip only the recording.
        let discarded = || {
            let policy = RuntimePolicy::strict();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                black_box((action, "add_edge", 0.08, RATIONALE, gate_terms()));
                black_box((
                    action,
                    "add_edge",
                    0.08,
                    RATIONALE,
                    outcome_terms(index & 3),
                ));
            }
            let elapsed = start.elapsed();
            assert!(policy.decision_log().records().is_empty());
            elapsed
        };

        // Arm C: terms + the clock read, discarded. Isolates `unix_time_ms`.
        let clocked = || {
            let policy = RuntimePolicy::strict();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                black_box((action, fnx_runtime::unix_time_ms(), gate_terms()));
                black_box((
                    action,
                    fnx_runtime::unix_time_ms(),
                    outcome_terms(index & 3),
                ));
            }
            start.elapsed()
        };

        // Arm D: terms + clock + the two owned `&'static str` clones + the whole
        // `DecisionRecord`, discarded instead of pushed. Isolates the ledger Vec
        // push and its growth memcpy from the per-record materialisation cost.
        let materialized = || {
            let policy = RuntimePolicy::strict();
            let mode = policy.mode();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                black_box(DecisionRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: "add_edge".into(),
                    mode,
                    action,
                    incompatibility_probability: 0.08,
                    rationale: RATIONALE.into(),
                    evidence: gate_terms(),
                });
                black_box(DecisionRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: "add_edge".into(),
                    mode,
                    action,
                    incompatibility_probability: 0.08,
                    rationale: RATIONALE.into(),
                    evidence: outcome_terms(index & 3),
                });
            }
            start.elapsed()
        };

        // Denominator: the whole shipped add_edge_with_attrs path.
        let add_edge_full = || {
            let mut graph = Graph::strict();
            let keys = (0..=EDGES).map(|n| n.to_string()).collect::<Vec<_>>();
            let start = Instant::now();
            for index in 0..EDGES {
                graph
                    .add_edge_with_attrs(
                        keys[index].clone(),
                        keys[index + 1].clone(),
                        AttrMap::new(),
                    )
                    .expect("edge add should succeed");
            }
            let elapsed = start.elapsed();
            assert_eq!(graph.edge_count(), EDGES);
            elapsed
        };

        let mut record_ns = Vec::with_capacity(ROUNDS);
        let mut single_ns = Vec::with_capacity(ROUNDS);
        let mut edge_build_ns = Vec::with_capacity(ROUNDS);
        let mut unbounded_ns = Vec::with_capacity(ROUNDS);
        let mut discard_ns = Vec::with_capacity(ROUNDS);
        let mut clock_ns = Vec::with_capacity(ROUNDS);
        let mut material_ns = Vec::with_capacity(ROUNDS);
        let mut full_ns = Vec::with_capacity(ROUNDS);
        for _ in 0..ROUNDS {
            record_ns.push(recorded().as_nanos() as f64 / EDGES as f64);
            single_ns.push(recorded_single().as_nanos() as f64 / EDGES as f64);
            edge_build_ns.push(recorded_edge_build().as_nanos() as f64 / EDGES as f64);
            unbounded_ns.push(unbounded().as_nanos() as f64 / EDGES as f64);
            discard_ns.push(discarded().as_nanos() as f64 / EDGES as f64);
            clock_ns.push(clocked().as_nanos() as f64 / EDGES as f64);
            material_ns.push(materialized().as_nanos() as f64 / EDGES as f64);
            full_ns.push(add_edge_full().as_nanos() as f64 / EDGES as f64);
        }
        let median = |samples: &mut Vec<f64>| {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let recorded_ns = median(&mut record_ns);
        let single_median_ns = median(&mut single_ns);
        let edge_build_median_ns = median(&mut edge_build_ns);
        let unbounded_median_ns = median(&mut unbounded_ns);
        let discarded_ns = median(&mut discard_ns);
        let clocked_ns = median(&mut clock_ns);
        let materialized_ns = median(&mut material_ns);
        let full = median(&mut full_ns);
        println!("ledger_record_cost_ab n={EDGES} rounds={ROUNDS} (2 records/edge)");
        println!("  A  bounded ledger, 2 records: {recorded_ns:8.1} ns/edge");
        println!("  A1 bounded ledger, 1 record : {single_median_ns:8.1} ns/edge  (SHIPPED)");
        println!(
            "  A2 two records per edge      : {edge_build_median_ns:8.1} ns/edge  (pre-wa1b9 counterfactual)"
        );
        println!("  A0 unbounded Vec (incumbent): {unbounded_median_ns:8.1} ns/edge");
        println!("  B  build terms only         : {discarded_ns:8.1} ns/edge");
        println!("  C  terms + clock            : {clocked_ns:8.1} ns/edge");
        println!("  D  terms + clock + record   : {materialized_ns:8.1} ns/edge");
        println!("  add_edge_with_attrs (total) : {full:8.1} ns/edge");
        println!(
            "  -> clock (C-B)              : {:8.1} ns/edge",
            clocked_ns - discarded_ns
        );
        println!(
            "  -> static str clones (D-C)  : {:8.1} ns/edge",
            materialized_ns - clocked_ns
        );
        println!(
            "  -> unbounded retention (A0-D): {:8.1} ns/edge",
            unbounded_median_ns - materialized_ns
        );
        println!(
            "  -> bounded retention (A-D)  : {:8.1} ns/edge",
            recorded_ns - materialized_ns
        );
        println!(
            "  -> bound speedup (A0/A)     : {:8.4}x",
            unbounded_median_ns / recorded_ns
        );
        println!(
            "  -> single-record (A/A1)     : {:8.4}x",
            recorded_ns / single_median_ns
        );
        println!(
            "  -> both levers (A0/A1)      : {:8.4}x",
            unbounded_median_ns / single_median_ns
        );
        println!(
            "  -> ledger share, SHIPPED    : {:6.1}%  (A1/full — one record per add_edge)",
            single_median_ns / full * 100.0
        );
        println!(
            "  -> ledger share, pre-wa1b9  : {:6.1}%  (A2/full — when autocreation also recorded)",
            edge_build_median_ns / full * 100.0
        );
    }

    /// br-r37-c1-g2nev: is the `Cow<'static, str>` field migration worth 110
    /// hand-edited construction sites?
    ///
    /// The bead proposes changing `DecisionRecord.operation`/`.rationale` and
    /// `EvidenceTerm.signal`/`.observed_value` from `String` to
    /// `Cow<'static, str>`, because 13 of the 14 owned strings a shipped
    /// `add_edge` materialises are compile-time constants. It has been REJECTed
    /// twice — not on the merits, but because it is an all-surface mechanical
    /// conversion across seven crates that `AGENTS.md` forbids scripting, and
    /// nobody had a number saying whether the payoff justifies it.
    ///
    /// This produces that number WITHOUT doing the migration first. Both arms
    /// run in ONE invocation and differ in exactly one thing: the field type.
    ///
    /// WHAT IS SIMULATED, AND WHY THE DELTA STILL TRANSFERS. The real ledger
    /// retires selectively (oldest `Allow` only) inside `RuntimePolicy`, which
    /// a local type cannot reuse. Both arms here therefore use the same plain
    /// capped `Vec` instead. That shifts the ABSOLUTE ns/edge away from the
    /// shipped path — so these are not ledger-share numbers and must not be
    /// quoted as such — but it shifts BOTH arms identically, and the quantity
    /// this bead turns on is the DIFFERENCE between them. `ledger_record_cost_ab`
    /// above remains the authority on the shipped path's absolute cost.
    ///
    /// A `Cow` record is also WIDER than a `String` one (a `Cow<str>` carries a
    /// discriminant), so a migration trades N allocations for a larger memcpy on
    /// every push and retire. That trade is exactly what is being measured, and
    /// it is why the answer was not obvious enough to skip measuring.
    ///
    /// `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib ledger_cow_field_cost_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn ledger_cow_field_cost_ab() {
        use fnx_runtime::{
            DecisionAction, EvidenceTerm, RuntimePolicy, bool_evidence, count_evidence,
        };
        use std::borrow::Cow;
        use std::hint::black_box;
        use std::time::{Duration, Instant};

        const EDGES: usize = 20_000;
        const ROUNDS: usize = 21;
        const CAP: usize = fnx_runtime::DECISION_LEDGER_RETAINED_RECORDS;
        const RATIONALE: &str = "argmin expected loss over {allow,full_validate,fail_closed}";

        /// Shape-for-shape mirror of `DecisionRecord` with borrowed fields.
        struct CowRecord {
            ts_unix_ms: u128,
            operation: Cow<'static, str>,
            action: DecisionAction,
            incompatibility_probability: f64,
            rationale: Cow<'static, str>,
            evidence: Vec<CowTerm>,
        }
        struct CowTerm {
            signal: Cow<'static, str>,
            observed_value: Cow<'static, str>,
            log_likelihood_ratio: f64,
        }

        // The exact four terms a shipped allowed edge records, in both forms.
        // Only `edge_attr_count` is genuinely dynamic; the other nine strings
        // are constants, which is the whole premise of the bead.
        fn owned_terms(edge_attr_count: usize) -> Vec<EvidenceTerm> {
            vec![
                EvidenceTerm {
                    signal: "self_loop".into(),
                    observed_value: bool_evidence(false),
                    log_likelihood_ratio: -0.5,
                },
                EvidenceTerm {
                    signal: "edge_attr_count".into(),
                    observed_value: count_evidence(edge_attr_count),
                    log_likelihood_ratio: -2.0,
                },
                EvidenceTerm {
                    signal: "left_autocreated".into(),
                    observed_value: bool_evidence(true),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "right_autocreated".into(),
                    observed_value: bool_evidence(true),
                    log_likelihood_ratio: -1.25,
                },
            ]
        }
        fn borrowed_terms(edge_attr_count: usize) -> Vec<CowTerm> {
            vec![
                CowTerm {
                    signal: Cow::Borrowed("self_loop"),
                    observed_value: Cow::Borrowed("false"),
                    log_likelihood_ratio: -0.5,
                },
                CowTerm {
                    signal: Cow::Borrowed("edge_attr_count"),
                    // The one field a migration cannot borrow.
                    observed_value: Cow::Owned(edge_attr_count.to_string()),
                    log_likelihood_ratio: -2.0,
                },
                CowTerm {
                    signal: Cow::Borrowed("left_autocreated"),
                    observed_value: Cow::Borrowed("true"),
                    log_likelihood_ratio: -1.25,
                },
                CowTerm {
                    signal: Cow::Borrowed("right_autocreated"),
                    observed_value: Cow::Borrowed("true"),
                    log_likelihood_ratio: -1.25,
                },
            ]
        }

        let owned_arm = || -> Duration {
            let policy = RuntimePolicy::strict();
            let mode = policy.mode();
            let mut log: Vec<DecisionRecord> = Vec::new();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                if log.len() == CAP {
                    log.clear();
                }
                log.push(DecisionRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: "add_edge".into(),
                    mode,
                    action,
                    incompatibility_probability: 0.08,
                    rationale: RATIONALE.into(),
                    evidence: owned_terms(index & 3),
                });
            }
            let elapsed = start.elapsed();
            // Consume every field AFTER timing. Both arms do this, symmetrically:
            // it keeps the record contents observable so neither arm can have
            // its construction elided as dead, which would compare a real build
            // against an optimised-away one.
            let mut sink = 0usize;
            for record in &log {
                sink ^= record.operation.len()
                    ^ record.rationale.len()
                    ^ (record.ts_unix_ms as usize)
                    ^ (record.incompatibility_probability.to_bits() as usize)
                    ^ usize::from(matches!(record.action, DecisionAction::Allow));
                for term in &record.evidence {
                    sink ^= term.signal.len()
                        ^ term.observed_value.len()
                        ^ (term.log_likelihood_ratio.to_bits() as usize);
                }
            }
            black_box(sink);
            elapsed
        };

        let borrowed_arm = || -> Duration {
            let policy = RuntimePolicy::strict();
            let mut log: Vec<CowRecord> = Vec::new();
            let start = Instant::now();
            for index in 0..EDGES {
                let action = policy.action_for(0.08, false);
                if log.len() == CAP {
                    log.clear();
                }
                log.push(CowRecord {
                    ts_unix_ms: fnx_runtime::unix_time_ms(),
                    operation: Cow::Borrowed("add_edge"),
                    action,
                    incompatibility_probability: 0.08,
                    rationale: Cow::Borrowed(RATIONALE),
                    evidence: borrowed_terms(index & 3),
                });
            }
            let elapsed = start.elapsed();
            let mut sink = 0usize;
            for record in &log {
                sink ^= record.operation.len()
                    ^ record.rationale.len()
                    ^ (record.ts_unix_ms as usize)
                    ^ (record.incompatibility_probability.to_bits() as usize)
                    ^ usize::from(matches!(record.action, DecisionAction::Allow));
                for term in &record.evidence {
                    sink ^= term.signal.len()
                        ^ term.observed_value.len()
                        ^ (term.log_likelihood_ratio.to_bits() as usize);
                }
            }
            black_box(sink);
            elapsed
        };

        // Order-balanced ABBA, and an A/A null measured through the identical
        // scheme. br-r37-c1-vz4v9 found a fixed-order sibling bench reporting a
        // 12% "effect" that was purely which arm ran first; the null is what
        // makes this readable.
        let balanced =
            |first: &dyn Fn() -> Duration, second: &dyn Fn() -> Duration| -> (f64, f64) {
                let a1 = first();
                let b1 = second();
                let b2 = second();
                let a2 = first();
                let scale = (2 * EDGES) as f64;
                (
                    (a1 + a2).as_nanos() as f64 / scale,
                    (b1 + b2).as_nanos() as f64 / scale,
                )
            };

        owned_arm();
        borrowed_arm();

        let mut owned_ns = Vec::with_capacity(ROUNDS);
        let mut cow_ns = Vec::with_capacity(ROUNDS);
        let mut null_a_ns = Vec::with_capacity(ROUNDS);
        let mut null_b_ns = Vec::with_capacity(ROUNDS);
        for _ in 0..ROUNDS {
            let (na, nb) = balanced(&owned_arm, &owned_arm);
            let (owned, cow) = balanced(&owned_arm, &borrowed_arm);
            null_a_ns.push(na);
            null_b_ns.push(nb);
            owned_ns.push(owned);
            cow_ns.push(cow);
        }

        let median = |samples: &mut Vec<f64>| {
            samples.sort_by(f64::total_cmp);
            samples[samples.len() / 2]
        };
        let owned = median(&mut owned_ns);
        let cow = median(&mut cow_ns);
        let null_a = median(&mut null_a_ns);
        let null_b = median(&mut null_b_ns);

        println!("ledger_cow_field_cost_ab n={EDGES} rounds={ROUNDS} cap={CAP}");
        println!("  S  String fields   : {owned:8.1} ns/edge  (incumbent)");
        println!("  C  Cow fields      : {cow:8.1} ns/edge  (proposed)");
        println!("  N1 String, null A  : {null_a:8.1} ns/edge");
        println!("  N2 String, null B  : {null_b:8.1} ns/edge");
        println!("  -> A/A null (N2/N1): {:8.4}x", null_b / null_a);
        println!("  -> Cow gain (S/C)  : {:8.4}x", owned / cow);
        println!("  -> saving          : {:8.1} ns/edge", owned - cow);
    }

    // br-r37-c1-p6bxu: A/B substrate bench for MultiGraph::remove_node
    // (O(degree) swap_remove vs the old O(|E|) retain). Ignored by default;
    // run with `cargo test -p fnx-classes --release ab_bench_multigraph_remove_node
    // -- --ignored --nocapture`. Also asserts byte-exact parity (node_count,
    // edge_count, edges_ordered) between the two paths.
    #[test]
    #[ignore]
    fn ab_bench_multigraph_remove_node() {
        use std::time::Instant;
        const N: usize = 1000;
        const M: usize = 8000;
        const ITERS: usize = 500;
        let build = || {
            let mut g = MultiGraph::new(CompatibilityMode::Strict);
            for i in 0..N {
                let _ = g.add_node(i.to_string());
            }
            let mut s: u64 = 0x9E3779B97F4A7C15;
            let mut next = || {
                s = s
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                (s >> 33) as usize % N
            };
            for _ in 0..M {
                let a = next();
                let b = next();
                let _ = g.add_edge(a.to_string(), b.to_string());
            }
            g
        };

        let mut gnew = build();
        let victims: Vec<String> = gnew
            .nodes_ordered()
            .into_iter()
            .take(ITERS)
            .map(str::to_owned)
            .collect();
        let t = Instant::now();
        for node in &victims {
            gnew.remove_node(node);
        }
        let new_t = t.elapsed();

        // A/A null path: the sole store must produce the same state under the
        // same removal sequence.
        let mut gold = build();
        let t = Instant::now();
        for node in &victims {
            gold.remove_node(node);
        }
        let null_t = t.elapsed();

        assert_eq!(gnew.node_count(), gold.node_count());
        assert_eq!(gnew.edge_count(), gold.edge_count());
        assert_eq!(gnew.edges_ordered(), gold.edges_ordered());
        eprintln!(
            "MultiGraph remove_node A/A x{ITERS}: candidate {new_t:?}, null {null_t:?}, ratio={:.3}",
            null_t.as_secs_f64() / new_t.as_secs_f64()
        );
    }

    #[test]
    fn remove_nodes_from_matches_repeated_removal_and_rebuilds_indices() {
        let edges = [
            ("0", "1"),
            ("1", "2"),
            ("2", "3"),
            ("3", "4"),
            ("4", "5"),
            ("0", "5"),
            ("1", "4"),
            ("2", "5"),
        ];
        let mut batch = Graph::strict();
        let mut repeated = Graph::strict();
        for (left, right) in edges {
            batch.add_edge(left, right).expect("batch edge add");
            repeated.add_edge(left, right).expect("repeated edge add");
        }

        let victims = ["1", "3", "99", "1"];
        let removed = batch.remove_nodes_from(victims);
        for victim in victims {
            let _ = repeated.remove_node(victim);
        }

        assert_eq!(removed, (2, 5));
        assert_eq!(batch.snapshot(), repeated.snapshot());
        let ordered_nodes = batch
            .nodes_ordered()
            .into_iter()
            .map(str::to_owned)
            .collect::<Vec<_>>();
        for (node_index, node) in ordered_nodes.iter().enumerate() {
            let names_from_strings = batch.neighbors(node).expect("node should exist");
            let names_from_indices = batch
                .neighbors_indices(node_index)
                .expect("index should exist")
                .iter()
                .map(|index| batch.get_node_name(*index).expect("index should resolve"))
                .collect::<Vec<_>>();
            assert_eq!(names_from_indices, names_from_strings);
        }
        let names_from_edge_indices = batch
            .edges_storage_order_index_iter()
            .map(|(left, right, _)| {
                (
                    batch
                        .get_node_name(left)
                        .expect("left endpoint should resolve")
                        .to_owned(),
                    batch
                        .get_node_name(right)
                        .expect("right endpoint should resolve")
                        .to_owned(),
                )
            })
            .collect::<Vec<_>>();
        let names_from_edge_storage = batch
            .edges_storage_order_iter()
            .map(|(left, right, _)| (left.to_owned(), right.to_owned()))
            .collect::<Vec<_>>();
        assert_eq!(names_from_edge_indices, names_from_edge_storage);
    }

    #[test]
    fn multigraph_ordered_indices_match_borrowed_edges() {
        let mut graph = MultiGraph::strict();
        graph
            .add_edge_with_key_and_attrs("b", "a", 2, single_attr("w", "left"))
            .expect("first keyed edge should be added");
        graph
            .add_edge_with_key_and_attrs("a", "b", 0, single_attr("w", "right"))
            .expect("parallel keyed edge should be added");
        graph
            .add_edge_with_key_and_attrs("a", "c", 3, AttrMap::new())
            .expect("third edge should be added");
        graph
            .add_edge_with_key_and_attrs("c", "c", 1, single_attr("w", "loop"))
            .expect("self-loop should be added");

        let nodes = graph.nodes_ordered();
        let from_indices = graph
            .edges_ordered_indices_borrowed()
            .into_iter()
            .map(|(left, right, key, attrs)| {
                (
                    nodes[left].to_owned(),
                    nodes[right].to_owned(),
                    key,
                    attrs.clone(),
                )
            })
            .collect::<Vec<_>>();
        let from_borrowed = graph
            .edges_ordered_borrowed()
            .into_iter()
            .map(|(left, right, key, attrs)| {
                (left.to_owned(), right.to_owned(), key, attrs.clone())
            })
            .collect::<Vec<_>>();

        assert_eq!(from_indices, from_borrowed);
    }

    #[test]
    fn multigraph_node_index_accessors_follow_remove_readd() {
        let mut graph = MultiGraph::strict();
        for node in ["prefix", "s", "a", "b", "t"] {
            let _ = graph.add_node(node);
        }

        for (expected_index, node) in ["prefix", "s", "a", "b", "t"].into_iter().enumerate() {
            assert_eq!(graph.get_node_index(node), Some(expected_index));
            assert_eq!(graph.get_node_name(expected_index), Some(node));
        }

        assert!(graph.remove_node("prefix"));
        assert!(graph.remove_node("a"));
        let _ = graph.add_node("a");

        for (expected_index, node) in ["s", "b", "t", "a"].into_iter().enumerate() {
            assert_eq!(graph.get_node_index(node), Some(expected_index));
            assert_eq!(graph.get_node_name(expected_index), Some(node));
        }
        assert_eq!(graph.get_node_index("prefix"), None);
        assert_eq!(graph.get_node_name(graph.node_count()), None);
    }

    #[test]
    fn strict_mode_fails_closed_for_unknown_incompatible_feature() {
        let mut graph = Graph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("__fnx_incompatible_decoder".to_owned(), "v2".into());
        let err = graph
            .add_edge_with_attrs("a", "b", attrs)
            .expect_err("strict mode should fail closed");

        assert_eq!(
            err,
            GraphError::FailClosed {
                operation: "add_edge",
                reason: "incompatible edge metadata".to_owned(),
            }
        );

        let last_record = graph
            .evidence_ledger()
            .records()
            .last()
            .expect("strict fail-closed path should emit a ledger row");
        assert_decision_record_schema(last_record, CompatibilityMode::Strict);
        assert_eq!(last_record.operation, "add_edge");
        assert_eq!(last_record.action, DecisionAction::FailClosed);
        assert!(
            last_record
                .evidence
                .iter()
                .any(|term| term.signal == "unknown_incompatible_feature")
        );
    }

    /// br-r37-c1-eo88t: an ALLOWED edge add writes exactly one `add_edge`
    /// ledger record, and it is the outcome record. Asserting the surviving
    /// record's evidence is the point: an implementation that kept the gate
    /// record instead of the outcome one would still pass a bare count check
    /// but would have thrown away the richer decision.
    fn add_edge_records(graph_records: &[DecisionRecord]) -> Vec<Vec<&str>> {
        graph_records
            .iter()
            .filter(|record| record.operation == "add_edge")
            .map(|record| {
                record
                    .evidence
                    .iter()
                    .map(|term| term.signal.as_ref())
                    .collect()
            })
            .collect()
    }

    #[test]
    fn allowed_add_edge_records_only_the_outcome_decision() {
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("edge add should succeed");

        assert_eq!(
            add_edge_records(graph.evidence_ledger().records()),
            vec![vec![
                "self_loop",
                "edge_attr_count",
                "left_autocreated",
                "right_autocreated",
            ]]
        );
        assert_eq!(
            graph
                .evidence_ledger()
                .records()
                .iter()
                .filter(|record| record.operation == "add_edge")
                .map(|record| record.action)
                .collect::<Vec<_>>(),
            vec![DecisionAction::Allow]
        );
    }

    #[test]
    fn add_edge_autocreation_files_no_add_node_record() {
        // br-r37-c1-wa1b9: autocreating an endpoint is an internal STEP of
        // add_edge, so the ledger's per-OPERATION contract means add_edge files
        // exactly ONE record however many endpoints it had to create. The
        // information is not lost — it is in that record's autocreated terms.
        // A caller-visible add_node still records, which the second half pins.
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("edge add should succeed");

        let records = graph.evidence_ledger().records();
        assert_eq!(
            records.len(),
            1,
            "add_edge creating two nodes must file one record, got {:?}",
            records
                .iter()
                .map(|record| record.operation.as_ref())
                .collect::<Vec<_>>()
        );
        let record = &records[0];
        assert_eq!(record.operation, "add_edge");
        assert_eq!(
            record
                .evidence
                .iter()
                .filter(
                    |term| term.signal == "left_autocreated" || term.signal == "right_autocreated"
                )
                .map(|term| term.observed_value.as_ref())
                .collect::<Vec<_>>(),
            vec!["true", "true"],
            "the autocreation event must still be auditable from the outcome record"
        );

        // A user-visible add_node keeps its own record.
        let before = graph.evidence_ledger().records().len();
        graph.add_node("c");
        let records = graph.evidence_ledger().records();
        assert_eq!(records.len(), before + 1);
        assert_eq!(
            records.last().map(|record| record.operation.as_ref()),
            Some("add_node")
        );
    }

    /// br-r37-c1-4c29a: `MultiGraph::add_edge_impl` now resolves each endpoint
    /// to a storage slot ONCE and calls the `_by_pair` variants, instead of
    /// re-resolving both endpoint strings inside six separate storage calls.
    /// The behaviour that could break is key assignment and the self-loop
    /// shortcut (`left == right` reuses the source slot rather than probing),
    /// so both are pinned here against the observable key sequence.
    #[test]
    fn multigraph_slot_resolution_preserves_key_assignment() {
        let mut graph = MultiGraph::strict();

        // Parallel edges take successive keys, and the pair is order-insensitive.
        assert_eq!(
            graph
                .add_edge_with_attrs("a", "b", AttrMap::new())
                .expect("edge is allowed"),
            0
        );
        assert_eq!(
            graph
                .add_edge_with_attrs("a", "b", AttrMap::new())
                .expect("edge is allowed"),
            1
        );
        assert_eq!(
            graph
                .add_edge_with_attrs("b", "a", AttrMap::new())
                .expect("reversed endpoints are the same undirected pair"),
            2
        );

        // Self-loop takes the shortcut branch and must key independently.
        assert_eq!(
            graph
                .add_edge_with_attrs("a", "a", AttrMap::new())
                .expect("self-loop is allowed"),
            0
        );
        assert_eq!(
            graph
                .add_edge_with_attrs("a", "a", AttrMap::new())
                .expect("parallel self-loop is allowed"),
            1
        );

        // An explicit key still lands where asked, on both branches.
        assert_eq!(
            graph
                .add_edge_with_key_and_attrs("a", "b", 9, AttrMap::new())
                .expect("explicit key is allowed"),
            9
        );
        assert_eq!(
            graph
                .add_edge_with_key_and_attrs("a", "a", 9, AttrMap::new())
                .expect("explicit key is allowed"),
            9
        );

        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 7);
    }

    /// br-r37-c1-jc9e4: `add_edge_with_attrs` now TAKES the caller's attribute
    /// map when the edge bucket is empty instead of extending entry by entry.
    /// That is a new branch on a CGSE-critical path, so this pins the four
    /// bucket-state / incoming-attrs combinations it splits, including the
    /// non-obvious one: an edge that already exists but carries NO attributes
    /// still takes the empty-bucket branch on a later attributed add.
    #[test]
    fn add_edge_fresh_bucket_take_matches_merge_semantics() {
        fn weight(value: i64) -> AttrMap {
            let mut attrs = AttrMap::new();
            attrs.insert("w".to_owned(), CgseValue::Int(value));
            attrs
        }
        fn stored(graph: &Graph, left: &str, right: &str) -> Vec<(String, CgseValue)> {
            graph
                .edge_attrs(left, right)
                .expect("edge exists")
                .iter()
                .map(|(key, value)| (key.clone(), value.clone()))
                .collect()
        }

        // New edge WITH attrs: the taken map is the stored map.
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", weight(1))
            .expect("edge is allowed");
        assert_eq!(
            stored(&graph, "a", "b"),
            vec![("w".to_owned(), CgseValue::Int(1))]
        );

        // New edge with EMPTY attrs: bucket stays empty, edge still exists.
        graph
            .add_edge_with_attrs("c", "d", AttrMap::new())
            .expect("edge is allowed");
        assert!(stored(&graph, "c", "d").is_empty());

        // EXISTING edge whose bucket is still empty — takes the same branch a
        // brand-new edge does, and must land the attrs just the same.
        graph
            .add_edge_with_attrs("c", "d", weight(7))
            .expect("edge is allowed");
        assert_eq!(
            stored(&graph, "c", "d"),
            vec![("w".to_owned(), CgseValue::Int(7))]
        );

        // EXISTING edge with a NON-empty bucket still merges, and a differing
        // value overwrites rather than being dropped by the take.
        graph
            .add_edge_with_attrs("a", "b", weight(9))
            .expect("edge is allowed");
        let mut extra = AttrMap::new();
        extra.insert("k".to_owned(), CgseValue::Int(2));
        graph
            .add_edge_with_attrs("a", "b", extra)
            .expect("edge is allowed");
        assert_eq!(
            stored(&graph, "a", "b"),
            vec![
                ("k".to_owned(), CgseValue::Int(2)),
                ("w".to_owned(), CgseValue::Int(9)),
            ]
        );
    }

    #[test]
    fn add_edge_entry_probe_keeps_existing_empty_edge_structurally_unchanged() {
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("initial edge is allowed");
        let revision_before = graph.revision;

        graph
            .add_edge_with_attrs("b", "a", AttrMap::new())
            .expect("duplicate edge is allowed");

        assert_eq!(graph.edge_count(), 1);
        assert_eq!(graph.neighbors("a"), Some(vec!["b"]));
        assert_eq!(graph.neighbors("b"), Some(vec!["a"]));
        assert_eq!(graph.revision, revision_before);
    }

    /// br-r37-c1-jc9e4: locks the endpoint-resolution cases that collapsing the
    /// per-endpoint `contains_key` + `get_index_of` pair restructured.
    ///
    /// The self-loop branch is the delicate one: it now returns the left index
    /// directly instead of probing the map for the right endpoint, and it
    /// still has to report `right_autocreated` as a COPY of `left_autocreated`
    /// — true when the loop created its node, false when the node was already
    /// there. Node insertion order after autocreation is asserted alongside,
    /// because the left endpoint is resolved before the right one and an
    /// `IndexMap` append is what keeps the left index valid across the right
    /// endpoint's insertion.
    #[test]
    fn add_edge_endpoint_resolution_preserves_autocreation_and_order() {
        fn autocreated(graph: &Graph) -> (String, String) {
            let record = graph
                .evidence_ledger()
                .records()
                .last()
                .expect("add_edge files an outcome record");
            let read = |signal: &str| {
                record
                    .evidence
                    .iter()
                    .find(|term| term.signal == signal)
                    .map(|term| term.observed_value.to_string())
                    .unwrap_or_else(|| panic!("{signal} must be present"))
            };
            (read("left_autocreated"), read("right_autocreated"))
        }

        // Self-loop that CREATES its node: both flags true, one node added.
        let mut graph = Graph::strict();
        graph
            .add_edge_with_attrs("s", "s", AttrMap::new())
            .expect("self-loop is allowed");
        assert_eq!(autocreated(&graph), ("true".to_owned(), "true".to_owned()));
        assert_eq!(graph.node_count(), 1);

        // Self-loop on an EXISTING node: both flags false, nothing added.
        graph
            .add_edge_with_attrs("s", "s", AttrMap::new())
            .expect("re-adding a self-loop is allowed");
        assert_eq!(
            autocreated(&graph),
            ("false".to_owned(), "false".to_owned())
        );
        assert_eq!(graph.node_count(), 1);

        // Left exists, right is new — the asymmetric case.
        graph
            .add_edge_with_attrs("s", "t", AttrMap::new())
            .expect("edge is allowed");
        assert_eq!(autocreated(&graph), ("false".to_owned(), "true".to_owned()));

        // Both new: left is resolved and inserted BEFORE right, so insertion
        // order is left-then-right and the earlier indices are unmoved.
        graph
            .add_edge_with_attrs("z", "a", AttrMap::new())
            .expect("edge is allowed");
        assert_eq!(autocreated(&graph), ("true".to_owned(), "true".to_owned()));
        assert_eq!(graph.get_node_index("s"), Some(0));
        assert_eq!(graph.get_node_index("t"), Some(1));
        assert_eq!(graph.get_node_index("z"), Some(2));
        assert_eq!(graph.get_node_index("a"), Some(3));
    }

    /// br-r37-c1-g2nev: the ledger's compile-time-constant strings must reach
    /// the record as BORROWED `Cow`s. That is the whole lever — every one of
    /// them used to be a per-mutation heap allocation — so this pins it on the
    /// shipped `add_edge`/`add_node` path rather than on a bench mirror. The
    /// value assertions pin the other half: the bytes are unchanged, so the
    /// CGSE audit trail is untouched.
    #[test]
    fn mutation_ledger_constants_are_borrowed_not_allocated() {
        use std::borrow::Cow;
        use std::collections::BTreeMap;

        let mut graph = Graph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("weight".to_owned(), CgseValue::Int(3));
        graph
            .add_edge_with_attrs("a", "b", attrs)
            .expect("strict add_edge with an int attribute is allowed");
        graph.add_node("c");

        let records = graph.evidence_ledger().records();
        assert_eq!(
            records
                .iter()
                .map(|record| record.operation.as_ref())
                .collect::<Vec<_>>(),
            vec!["add_edge", "add_node"],
            "ledger shape must be unchanged by the Cow migration"
        );

        // Constant `observed_value`s, by signal, exactly as `bool::to_string()`
        // rendered them before the migration.
        let expected_borrowed: BTreeMap<&str, &str> = [
            ("self_loop", "false"),
            ("left_autocreated", "true"),
            ("right_autocreated", "true"),
            ("node_preexisting", "false"),
        ]
        .into_iter()
        .collect();

        for record in records {
            assert!(
                matches!(record.operation, Cow::Borrowed(_)),
                "operation `{}` must be borrowed",
                record.operation
            );
            assert!(
                matches!(record.rationale, Cow::Borrowed(_)),
                "rationale `{}` must be borrowed",
                record.rationale
            );
            for term in &record.evidence {
                assert!(
                    matches!(term.signal, Cow::Borrowed(_)),
                    "signal `{}` must be borrowed",
                    term.signal
                );
                if let Some(expected) = expected_borrowed.get(term.signal.as_ref()) {
                    assert_eq!(&term.observed_value, expected);
                    assert!(
                        matches!(term.observed_value, Cow::Borrowed(_)),
                        "boolean observed_value for `{}` must be borrowed",
                        term.signal
                    );
                }
            }
        }

        // The genuinely dynamic counts still allocate, and still read the same.
        let edge_record = &records[0];
        assert_eq!(
            edge_record
                .evidence
                .iter()
                .find(|term| term.signal == "edge_attr_count")
                .map(|term| term.observed_value.as_ref()),
            Some("1")
        );
    }

    #[test]
    fn allowed_multigraph_add_edge_records_only_the_outcome_decision() {
        let mut graph = MultiGraph::strict();
        let _ = graph
            .add_edge_with_attrs("a", "b", AttrMap::new())
            .expect("edge add should succeed");

        assert_eq!(
            add_edge_records(graph.evidence_ledger().records()),
            vec![vec![
                "edge_key",
                "edge_attr_count",
                "left_autocreated",
                "right_autocreated",
            ]]
        );
    }

    #[test]
    fn refused_multigraph_add_edge_still_records_its_gate_decision() {
        // The negative case for the pairing above: a refusal returns before the
        // outcome record runs, so dropping the gate record unconditionally would
        // leave a rejected mutation with no audit trail at all.
        let mut graph = MultiGraph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("__fnx_incompatible_decoder".to_owned(), "v2".into());
        let err = graph
            .add_edge_with_attrs("a", "b", attrs)
            .expect_err("strict mode should fail closed");
        assert_eq!(
            err,
            GraphError::FailClosed {
                operation: "add_edge",
                reason: "incompatible edge metadata".to_owned(),
            }
        );

        assert_eq!(
            add_edge_records(graph.evidence_ledger().records()),
            vec![vec!["unknown_incompatible_feature"]]
        );
        assert_eq!(
            graph
                .evidence_ledger()
                .records()
                .last()
                .map(|record| record.action),
            Some(DecisionAction::FailClosed)
        );
    }

    #[test]
    fn revision_increments_on_mutating_operations() {
        let mut graph = Graph::strict();
        let r0 = graph.revision();
        let _ = graph.add_node("a");
        let r1 = graph.revision();
        assert!(r1 > r0);

        graph.add_edge("a", "b").expect("edge add should succeed");
        let r2 = graph.revision();
        assert!(r2 > r1);

        let _ = graph.remove_edge("a", "b");
        let r3 = graph.revision();
        assert!(r3 > r2);
    }

    #[test]
    fn add_node_with_attrs_reports_change_on_existing_node() {
        let mut graph = Graph::strict();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "red")));
        let r1 = graph.revision();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "blue")));
        let r2 = graph.revision();
        assert!(r2 > r1);
        let expected = CgseValue::from("blue");
        assert_eq!(graph.node_attrs("a").unwrap().get("color"), Some(&expected));
    }

    #[test]
    fn add_node_with_identical_attrs_keeps_order_and_revision() {
        let mut graph = Graph::strict();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "red")));
        assert!(graph.add_node("b"));
        let revision_before = graph.revision();

        assert!(!graph.add_node_with_attrs("a", single_attr("color", "red")));

        assert_eq!(graph.nodes_ordered(), vec!["a", "b"]);
        assert_eq!(graph.revision(), revision_before);
        assert_eq!(
            graph.node_attrs("a").and_then(|attrs| attrs.get("color")),
            Some(&CgseValue::from("red"))
        );
    }

    #[test]
    fn add_node_with_attrs_keeps_fresh_node_order_and_attrs() {
        let mut graph = Graph::strict();
        assert!(graph.add_node("before"));
        assert!(graph.add_node_with_attrs("fresh", single_attr("color", "red")));
        assert!(graph.add_node("after"));

        assert_eq!(graph.nodes_ordered(), vec!["before", "fresh", "after"]);
        assert_eq!(
            graph
                .node_attrs("fresh")
                .and_then(|attrs| attrs.get("color")),
            Some(&CgseValue::from("red"))
        );
    }

    #[test]
    fn multigraph_add_node_with_attrs_reports_change_on_existing_node() {
        let mut graph = MultiGraph::strict();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "red")));
        let r1 = graph.revision();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "blue")));
        let r2 = graph.revision();
        assert!(r2 > r1);
        let expected = CgseValue::from("blue");
        assert_eq!(graph.node_attrs("a").unwrap().get("color"), Some(&expected));
    }

    #[test]
    fn hardened_self_loop_records_allow_decision() {
        let mut graph = Graph::hardened();
        graph
            .add_edge("loop", "loop")
            .expect("hardened self-loop edge should be accepted");

        let add_edge_record = graph
            .evidence_ledger()
            .records()
            .iter()
            .rev()
            .find(|record| record.operation == "add_edge")
            .expect("add_edge operation should emit ledger row");
        assert_decision_record_schema(add_edge_record, CompatibilityMode::Hardened);
        assert_eq!(add_edge_record.action, DecisionAction::Allow);
        assert!(
            add_edge_record
                .evidence
                .iter()
                .any(|term| term.signal == "self_loop" && term.observed_value == "true")
        );
    }

    #[test]
    fn runtime_policy_tracks_hardened_graph_recovery() {
        let mut graph = Graph::hardened();
        graph
            .add_edge("a", "b")
            .expect("hardened graph edge add should succeed");

        assert_eq!(graph.runtime_policy().mode(), CompatibilityMode::Hardened);
        assert!(!graph.runtime_policy().decision_log().records().is_empty());
        assert!(graph.runtime_policy().posterior().observation_count >= 1);
    }

    #[test]
    fn snapshot_roundtrip_replays_to_identical_state() {
        let mut graph = Graph::strict();

        let mut first_attrs = AttrMap::new();
        first_attrs.insert("weight".to_owned(), "7".into());
        graph
            .add_edge_with_attrs("a", "b", first_attrs)
            .expect("edge insert should succeed");

        let mut second_attrs = AttrMap::new();
        second_attrs.insert("color".to_owned(), "green".into());
        graph
            .add_edge_with_attrs("b", "c", second_attrs)
            .expect("edge insert should succeed");

        let snapshot = graph.snapshot();
        let mut replayed = Graph::new(snapshot.mode);
        for node in &snapshot.nodes {
            let _ = replayed.add_node(node.clone());
        }
        for edge in &snapshot.edges {
            replayed
                .add_edge_with_attrs(edge.left.clone(), edge.right.clone(), edge.attrs.clone())
                .expect("snapshot replay should be valid");
        }

        assert_eq!(replayed.snapshot(), snapshot);
        assert_graph_core_invariants(&replayed);
    }

    #[test]
    fn multigraph_tracks_parallel_edges_with_distinct_keys() {
        let mut graph = MultiGraph::strict();
        let first = graph.add_edge("a", "b").expect("edge add should succeed");
        let second = graph.add_edge("a", "b").expect("edge add should succeed");

        assert_ne!(first, second);
        assert_eq!(graph.edge_count(), 2);
        assert_eq!(graph.edge_keys("a", "b"), Some(vec![0, 1]));
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_counts_parallel_selfloops_only() {
        let mut graph = MultiGraph::strict();
        let _ = graph
            .add_edge("a", "a")
            .expect("self-loop add should succeed");
        let _ = graph
            .add_edge("a", "a")
            .expect("self-loop add should succeed");
        let _ = graph
            .add_edge("b", "b")
            .expect("self-loop add should succeed");
        let _ = graph.add_edge("a", "b").expect("edge add should succeed");
        let _ = graph.add_edge("a", "b").expect("edge add should succeed");

        assert_eq!(graph.number_of_selfloops(), 3);
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_add_fresh_edge_unrecorded_rejects_occupied_bucket() {
        let mut graph = MultiGraph::strict();
        assert_eq!(graph.add_fresh_edge_unrecorded("a", "b"), Some(0));
        let revision = graph.revision();
        let edge_count = graph.edge_count();

        assert_eq!(graph.add_fresh_edge_unrecorded("b", "a"), None);

        assert_eq!(graph.revision(), revision);
        assert_eq!(graph.edge_count(), edge_count);
        assert_eq!(graph.edge_keys("a", "b"), Some(vec![0]));
        assert_eq!(graph.nodes_ordered(), vec!["a", "b"]);
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_add_fresh_edge_with_key_unrecorded_preserves_key() {
        let mut graph = MultiGraph::strict();

        assert_eq!(
            graph.add_fresh_edge_with_key_unrecorded("a", "b", 42),
            Some(42)
        );

        assert_eq!(graph.edge_count(), 1);
        assert_eq!(graph.edge_keys("a", "b"), Some(vec![42]));
        assert_eq!(graph.nodes_ordered(), vec!["a", "b"]);
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_remove_edge_without_key_removes_latest_instance() {
        let mut graph = MultiGraph::strict();
        let first = graph.add_edge("a", "b").expect("edge add should succeed");
        let second = graph.add_edge("a", "b").expect("edge add should succeed");

        assert!(graph.remove_edge("a", "b", None));
        assert_eq!(graph.edge_count(), 1);
        assert_eq!(graph.edge_keys("a", "b"), Some(vec![first]));
        assert_ne!(first, second);
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_remove_node_clears_parallel_incident_edges() {
        let mut graph = MultiGraph::strict();
        let _ = graph.add_edge("a", "b").expect("edge add should succeed");
        let _ = graph.add_edge("a", "b").expect("edge add should succeed");
        let _ = graph.add_edge("b", "c").expect("edge add should succeed");

        assert!(graph.remove_node("b"));
        assert_eq!(graph.edge_count(), 0);
        assert!(!graph.has_node("b"));
        assert_eq!(graph.neighbors("a"), Some(vec![]));
        assert_eq!(graph.neighbors("c"), Some(vec![]));
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn multigraph_clear_edges_preserves_nodes_attrs_and_rows() {
        let mut graph = MultiGraph::strict();
        assert!(graph.add_node_with_attrs("a", single_attr("color", "red")));
        assert!(graph.add_node_with_attrs("b", single_attr("color", "blue")));
        let _ = graph
            .add_edge_with_key_and_attrs("a", "b", 7, single_attr("weight", "3"))
            .expect("edge add should succeed");
        let _ = graph
            .add_edge_with_key_and_attrs("b", "a", 2, single_attr("weight", "5"))
            .expect("edge add should succeed");
        let before_revision = graph.revision();

        graph.clear_edges();

        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.nodes_ordered(), vec!["a", "b"]);
        assert_eq!(graph.edge_count(), 0);
        assert!(graph.edges_ordered().is_empty());
        assert_eq!(graph.neighbors("a"), Some(vec![]));
        assert_eq!(graph.neighbors("b"), Some(vec![]));
        assert_eq!(
            graph.node_attrs("a").unwrap().get("color"),
            Some(&CgseValue::from("red"))
        );
        assert!(graph.revision() > before_revision);
        assert_multigraph_core_invariants(&graph);
    }

    #[test]
    fn runtime_policy_tracks_hardened_multigraph_recovery() {
        let mut graph = MultiGraph::hardened();
        graph
            .add_edge("a", "b")
            .expect("hardened multigraph edge add should succeed");

        assert_eq!(graph.runtime_policy().mode(), CompatibilityMode::Hardened);
        assert!(!graph.runtime_policy().decision_log().records().is_empty());
        assert!(graph.runtime_policy().posterior().observation_count >= 1);
    }

    #[test]
    fn multigraph_roundtrips_sparse_snapshot_keys() {
        let mut graph = MultiGraph::strict();
        assert_eq!(
            graph.add_edge("a", "b").expect("edge add should succeed"),
            0
        );
        assert_eq!(
            graph.add_edge("a", "b").expect("edge add should succeed"),
            1
        );
        assert_eq!(
            graph.add_edge("a", "b").expect("edge add should succeed"),
            2
        );
        assert!(graph.remove_edge("a", "b", Some(1)));
        assert_eq!(
            graph.add_edge("a", "b").expect("edge add should succeed"),
            3
        );

        let snapshot = graph.snapshot();
        assert_eq!(
            snapshot
                .edges
                .iter()
                .map(|edge| edge.key)
                .collect::<Vec<_>>(),
            vec![0, 2, 3]
        );

        let mut replayed = MultiGraph::new(snapshot.mode);
        for node in &snapshot.nodes {
            let _ = replayed.add_node(node.clone());
        }
        for edge in &snapshot.edges {
            replayed
                .add_edge_with_key_and_attrs(
                    edge.left.clone(),
                    edge.right.clone(),
                    edge.key,
                    edge.attrs.clone(),
                )
                .expect("snapshot replay should preserve explicit keys");
        }

        assert_eq!(replayed.snapshot(), snapshot);
        assert_multigraph_core_invariants(&replayed);
    }

    proptest! {
        #[test]
        fn prop_core_invariants_hold_for_mixed_edge_mutations(
            ops in prop::collection::vec((0_u8..8, 0_u8..8, any::<bool>()), 1..80),
        ) {
            let mut graph = Graph::strict();
            let mut last_revision = graph.revision();

            for (left_id, right_id, is_add) in ops {
                let left = node_name(left_id);
                let right = node_name(right_id);
                if is_add {
                    prop_assert!(graph.add_edge(left.clone(), right.clone()).is_ok());
                } else {
                    let _ = graph.remove_edge(&left, &right);
                }
                let revision = graph.revision();
                prop_assert!(revision >= last_revision);
                last_revision = revision;
                assert_graph_core_invariants(&graph);
            }
        }

        #[test]
        fn prop_snapshot_is_deterministic_for_same_operation_stream(
            ops in prop::collection::vec((0_u8..8, 0_u8..8, 0_u8..3), 0..64),
        ) {
            let mut graph_left = Graph::hardened();
            let mut graph_right = Graph::hardened();

            for (left_id, right_id, attrs_variant) in ops {
                let left = node_name(left_id);
                let right = node_name(right_id);
                let mut attrs = AttrMap::new();
                if attrs_variant == 1 {
                    attrs.insert("weight".to_owned(), (left_id % 5).to_string().into());
                } else if attrs_variant == 2 {
                    attrs.insert("tag".to_owned(), format!("k{}", right_id % 4).into());
                }
                prop_assert!(
                    graph_left
                        .add_edge_with_attrs(left.clone(), right.clone(), attrs.clone())
                        .is_ok()
                );
                prop_assert!(
                    graph_right
                        .add_edge_with_attrs(left, right, attrs)
                        .is_ok()
                );
            }

            prop_assert_eq!(graph_left.snapshot(), graph_right.snapshot());
            prop_assert_eq!(graph_left.snapshot(), graph_left.snapshot());
        }

        #[test]
        fn prop_reapplying_identical_edge_attrs_is_revision_stable(
            left_id in 0_u8..8,
            right_id in 0_u8..8,
            weight in 0_u16..5000,
        ) {
            let mut graph = Graph::strict();
            let left = node_name(left_id);
            let right = node_name(right_id);
            let mut attrs = AttrMap::new();
            attrs.insert("weight".to_owned(), weight.to_string().into());

            prop_assert!(
                graph
                    .add_edge_with_attrs(left.clone(), right.clone(), attrs.clone())
                    .is_ok()
            );
            let revision_after_first = graph.revision();
            prop_assert!(
                graph
                    .add_edge_with_attrs(left, right, attrs)
                    .is_ok()
            );
            prop_assert_eq!(graph.revision(), revision_after_first);
        }

        #[test]
        fn prop_remove_node_clears_incident_edges(
            ops in prop::collection::vec((0_u8..8, 0_u8..8), 1..64),
            target_id in 0_u8..8,
        ) {
            let mut graph = Graph::strict();
            for (left_id, right_id) in ops {
                let left = node_name(left_id);
                let right = node_name(right_id);
                prop_assert!(graph.add_edge(left, right).is_ok());
            }

            let target = node_name(target_id);
            let removed = graph.remove_node(&target);
            if removed {
                prop_assert!(!graph.has_node(&target));
                for node in graph.nodes_ordered() {
                    let neighbors = graph
                        .neighbors(node)
                        .expect("graph nodes should always have adjacency buckets");
                    prop_assert!(!neighbors.contains(&target.as_str()));
                    prop_assert!(!graph.has_edge(node, &target));
                }
            }
            assert_graph_core_invariants(&graph);
        }

        #[test]
        fn prop_decision_ledger_records_follow_schema(
            ops in prop::collection::vec((0_u8..8, 0_u8..8, 0_u8..4), 1..72),
        ) {
            let mut graph = Graph::strict();
            for (left_id, right_id, attrs_kind) in ops {
                let left = node_name(left_id);
                let right = node_name(right_id);
                let mut attrs = AttrMap::new();
                match attrs_kind {
                    0 => {}
                    1 => {
                        attrs.insert("weight".to_owned(), (left_id % 9).to_string().into());
                    }
                    2 => {
                        attrs.insert("color".to_owned(), format!("c{}", right_id % 6).into());
                    }
                    _ => {
                        attrs.insert("__fnx_incompatible_decoder".to_owned(), "v2".into());
                    }
                }
                let _ = graph.add_edge_with_attrs(left, right, attrs);
            }

            let records = graph.evidence_ledger().records();
            prop_assert!(!records.is_empty());
            for record in records {
                assert_decision_record_schema(record, CompatibilityMode::Strict);
                if record.operation == "add_node" {
                    prop_assert_eq!(record.action, DecisionAction::Allow);
                    prop_assert!(record.evidence.iter().any(|term| term.signal == "node_preexisting"));
                    prop_assert!(record.evidence.iter().any(|term| term.signal == "attrs_count"));
                } else {
                    prop_assert_eq!(&record.operation, "add_edge");
                    if record.action == DecisionAction::FailClosed {
                        prop_assert!(
                            record
                                .evidence
                                .iter()
                                .any(|term| term.signal == "unknown_incompatible_feature")
                        );
                    } else {
                        prop_assert_eq!(record.action, DecisionAction::Allow);
                        // add_edge records two decisions: a pre-check (only
                        // unknown_incompatible_feature) and a post-check (with
                        // self_loop, edge_attr_count, etc.). Both are valid.
                        let is_precheck = record
                            .evidence
                            .iter()
                            .any(|term| term.signal == "unknown_incompatible_feature")
                            && !record
                                .evidence
                                .iter()
                                .any(|term| term.signal == "edge_attr_count");
                        if !is_precheck {
                            prop_assert!(record.evidence.iter().any(|term| term.signal == "edge_attr_count"));
                            prop_assert!(record.evidence.iter().any(|term| term.signal == "self_loop"));
                        }
                    }
                }
            }
        }
    }
}

/// br-r37-c1-jc9e4: how much of a no-op `add_node` is the DECISION LEDGER?
///
/// The closed self-time ladder in `fnx-python` puts `Graph::add_node_with_attrs` at
/// `+128` ns of a `~243` ns no-op call — the single largest term inside the body. That
/// call is exactly two things: `add_node_with_attrs_unrecorded`, which does the store
/// work, and `record_decision`, which builds a `Vec<EvidenceTerm>`, reads the clock via
/// `unix_time_ms`, updates the posterior and pushes into the decision log. Which of the
/// two carries the 128 ns has never been measured, and the answer decides whether there
/// is anything worth trading against the audit doctrine at all.
///
/// This lives in `fnx-classes` because `add_node_with_attrs_unrecorded` is private to
/// this crate; measuring it from the binding would have meant widening its visibility
/// for a benchmark, which is a worse trade than putting the probe where the code is.
///
/// It changes NO shipped behaviour — both arms are existing functions, and the node is
/// already present so neither mutates anything.
///
/// CONTROLS: `recorded/recorded` is an A/A null through the identical ABBA scheme; if it
/// is not ~1.0 the instrument is measuring slot position, not the arms.
///
/// `#[ignore]`; run with
/// `rch exec -- cargo test --release -j 2 -p fnx-classes --lib
///  node_decision_ledger_self_time_ab -- --ignored --nocapture`.
#[test]
#[ignore = "measurement; run with --release --ignored --nocapture"]
fn node_decision_ledger_self_time_ab() {
    use std::hint::black_box;
    use std::time::{Duration, Instant};

    const NODES: usize = 2000;
    const REPS: usize = 200;
    const ROUNDS: usize = 41;

    let keys: Vec<String> = (0..NODES).map(|n| format!("n{n}")).collect();
    let mut graph = Graph::strict();
    for key in &keys {
        let _ = graph.add_node_with_attrs(key.clone(), AttrMap::new());
    }
    let before = graph.node_count();

    // Both arms re-add nodes that are ALREADY PRESENT, so neither changes the store and
    // repeating them is idempotent — the property that makes a no-op control timeable.
    let recorded = |g: &mut Graph| -> Duration {
        let start = Instant::now();
        for _ in 0..REPS {
            for key in &keys {
                black_box(g.add_node_with_attrs(key.as_str(), AttrMap::new()));
            }
        }
        start.elapsed()
    };
    let unrecorded = |g: &mut Graph| -> Duration {
        let start = Instant::now();
        for _ in 0..REPS {
            for key in &keys {
                black_box(g.add_node_with_attrs_unrecorded(key.as_str(), AttrMap::new()));
            }
        }
        start.elapsed()
    };

    // ABBA: each arm runs at both ends of a four-slot block, so any cost that depends on
    // slot rather than work cancels.
    let balanced = |first: &dyn Fn(&mut Graph) -> Duration,
                    second: &dyn Fn(&mut Graph) -> Duration,
                    g: &mut Graph|
     -> (f64, f64) {
        let a1 = first(g);
        let b1 = second(g);
        let b2 = second(g);
        let a2 = first(g);
        let scale = (2 * NODES * REPS) as f64;
        (
            (a1 + a2).as_nanos() as f64 / scale,
            (b1 + b2).as_nanos() as f64 / scale,
        )
    };

    for _ in 0..3 {
        recorded(&mut graph);
        unrecorded(&mut graph);
    }

    let mut rec_ns = Vec::with_capacity(ROUNDS);
    let mut unrec_ns = Vec::with_capacity(ROUNDS);
    let mut null_a = Vec::with_capacity(ROUNDS);
    let mut null_b = Vec::with_capacity(ROUNDS);
    for _ in 0..ROUNDS {
        let (na, nb) = balanced(&recorded, &recorded, &mut graph);
        null_a.push(na);
        null_b.push(nb);
        let (r, u) = balanced(&recorded, &unrecorded, &mut graph);
        rec_ns.push(r);
        unrec_ns.push(u);
    }

    assert_eq!(
        graph.node_count(),
        before,
        "a no-op control that changed the node count measured a real insert"
    );

    let median = |v: &mut Vec<f64>| -> f64 {
        v.sort_by(f64::total_cmp);
        v[(v.len() - 1) / 2]
    };
    let rec = median(&mut rec_ns);
    let unrec = median(&mut unrec_ns);
    let na = median(&mut null_a);
    let nb = median(&mut null_b);

    println!("node_decision_ledger_self_time_ab nodes={NODES} reps={REPS} rounds={ROUNDS}");
    println!("  A/A null (recorded/recorded) : {:8.4}x", nb / na);
    println!("  A  add_node_with_attrs       : {rec:8.1} ns/call  (store + ledger)");
    println!("  B  ..._unrecorded            : {unrec:8.1} ns/call  (store only)");
    println!(
        "  -> decision ledger costs     : {:8.1} ns/call",
        rec - unrec
    );
    println!(
        "  -> ledger share of the pair  : {:8.1}%",
        100.0 * (rec - unrec) / rec
    );
}