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
//! Directed graph (DiGraph) storage.
//!
//! Mirrors the undirected [`Graph`] API with directed semantics:
//! - Edge `(u, v)` is distinct from `(v, u)`.
//! - Adjacency is split into **successors** (outgoing) and **predecessors** (incoming).
//! - `neighbors(n)` returns successors (matching NetworkX convention).

use crate::{AttrMap, EdgeSnapshot, GraphError};
use fnx_runtime::{
    CgseValue, CompatibilityMode, DecisionAction, DecisionRecord, EvidenceLedger, EvidenceTerm,
    RuntimePolicy, bool_evidence, count_evidence,
};
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// DirectedEdgeKey — order-preserving (NOT canonicalized)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DirectedEdgeKey {
    source: String,
    target: String,
}

impl DirectedEdgeKey {
    fn new(source: &str, target: &str) -> Self {
        Self {
            source: source.to_owned(),
            target: target.to_owned(),
        }
    }
}

#[derive(Hash, PartialEq, Eq, Clone, Copy)]
struct DirectedEdgeKeyRef<'a> {
    source: &'a str,
    target: &'a str,
}

impl<'a> DirectedEdgeKeyRef<'a> {
    fn new(source: &'a str, target: &'a str) -> Self {
        Self { source, target }
    }
}

impl<'a> indexmap::Equivalent<DirectedEdgeKey> for DirectedEdgeKeyRef<'a> {
    fn equivalent(&self, key: &DirectedEdgeKey) -> bool {
        self.source == key.source && self.target == key.target
    }
}

// ---------------------------------------------------------------------------
// DiGraphSnapshot
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiGraphSnapshot {
    pub mode: CompatibilityMode,
    pub nodes: Vec<String>,
    /// br-snapnodeattrs: per-node attributes preserved across snapshot
    /// round-trip. Defaults to empty for backward compatibility.
    #[serde(default)]
    pub node_attrs: std::collections::BTreeMap<String, AttrMap>,
    /// Edges in source→target order. `left` = source, `right` = target.
    pub edges: Vec<EdgeSnapshot>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiDiEdgeSnapshot {
    pub source: String,
    pub target: String,
    pub key: usize,
    pub attrs: AttrMap,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiDiGraphSnapshot {
    pub mode: CompatibilityMode,
    pub nodes: Vec<String>,
    /// See DiGraphSnapshot::node_attrs.
    #[serde(default)]
    pub node_attrs: std::collections::BTreeMap<String, AttrMap>,
    pub edges: Vec<MultiDiEdgeSnapshot>,
}

// ---------------------------------------------------------------------------
// DiGraph
// ---------------------------------------------------------------------------

/// br-r37-c1-d58s8 P1: integer CSR view of a DiGraph's adjacency —
/// succ/pred targets are node INDICES (IndexMap insertion order) with
/// per-row slices in ROW order, so index walks reproduce the String
/// walks exactly. Built once per revision via `DiGraph::csr()`.
#[derive(Debug)]
pub struct DiCsr {
    pub succ_offsets: Vec<usize>,
    pub succ_targets: Vec<u32>,
    pub pred_offsets: Vec<usize>,
    pub pred_targets: Vec<u32>,
}

impl DiCsr {
    #[must_use]
    pub fn successors(&self, idx: usize) -> &[u32] {
        &self.succ_targets[self.succ_offsets[idx]..self.succ_offsets[idx + 1]]
    }

    #[must_use]
    pub fn predecessors(&self, idx: usize) -> &[u32] {
        &self.pred_targets[self.pred_offsets[idx]..self.pred_offsets[idx + 1]]
    }
}

type DiCsrCache = std::sync::Arc<std::sync::RwLock<Option<(u64, std::sync::Arc<DiCsr>)>>>;
type DiAllIntCache = std::sync::Arc<std::sync::RwLock<Option<(u64, String, bool)>>>;

/// Revision-keyed integer CSR view of a MultiDiGraph's distinct successor and
/// predecessor rows. Parallel-edge keys are intentionally collapsed because this
/// view is for multiplicity-insensitive structural algorithms.
#[derive(Debug)]
pub struct MultiDiCsr {
    pub succ_offsets: Vec<usize>,
    pub succ_targets: Vec<u32>,
    pub pred_offsets: Vec<usize>,
    pub pred_targets: Vec<u32>,
}

impl MultiDiCsr {
    #[must_use]
    pub fn successors(&self, idx: usize) -> &[u32] {
        &self.succ_targets[self.succ_offsets[idx]..self.succ_offsets[idx + 1]]
    }

    #[must_use]
    pub fn predecessors(&self, idx: usize) -> &[u32] {
        &self.pred_targets[self.pred_offsets[idx]..self.pred_offsets[idx + 1]]
    }
}

type MultiDiCsrCache = std::sync::Arc<std::sync::RwLock<Option<(u64, std::sync::Arc<MultiDiCsr>)>>>;

/// br-r37-c1-s8dj1: node POSITION pair -> position in `edges`.
type EdgePairMap = std::collections::HashMap<(usize, usize), usize, rustc_hash::FxBuildHasher>;

/// br-r37-c1-s8dj1: the pair lookaside, stamped with the graph revision.
///
/// CLONES COLD, AND IS NEVER SHARED. `MultiDiGraph` derives `Clone`, which would
/// otherwise hand both copies the same cache. The stamp does not rescue an
/// INCREMENTALLY maintained map from that: the two graphs' revisions advance
/// independently and can COINCIDE, so the clone updates the shared map and
/// stamps its own revision, and the original then reads a map describing a
/// different graph. A cold clone costs one rebuild and removes the class.
#[derive(Debug, Default)]
pub(crate) struct EdgePairIndex {
    map: std::sync::RwLock<Option<(u64, EdgePairMap)>>,
    /// br-r37-c1-s8dj1: the revision the warm-up counter belongs to.
    probed_revision: std::sync::atomic::AtomicU64,
    /// Probes seen at that revision without an index. See `PAIR_INDEX_WARMUP`.
    probes_since_build: std::sync::atomic::AtomicUsize,
}

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

/// br-r37-c1-s8dj1: probes at one revision before the O(E) map is built.
///
/// THE GUARD EXISTS BECAUSE THE BUILD IS NOT FREE. Building costs a hash per
/// endpoint of every edge, so a caller that probes a large graph a HANDFUL of
/// times would pay O(E) to save O(node key length) — measured at E=8000 as
/// 6308 ns/probe against 592 ns for the undirected class, a loss on exactly the
/// sparse-probing shape that never benefits.
///
/// SO THE THRESHOLD SCALES WITH THE BUILD IT AMORTISES, and a constant will not
/// do: 64 probes justify a build at E=100 and are nowhere near justifying one at
/// E=8000. Waiting until the caller has made roughly half as many probes as the
/// build costs entries bounds the waste at a small constant factor of the work
/// already spent, which is the ordinary amortisation rule. Below the threshold
/// the string path answers, exactly as the class did before this index existed.
const PAIR_INDEX_WARMUP_FLOOR: usize = 64;

#[inline]
fn pair_index_warmup(edge_pairs: usize) -> usize {
    PAIR_INDEX_WARMUP_FLOOR.max(edge_pairs / 2)
}

#[derive(Debug, Clone)]
pub struct DiGraph {
    mode: CompatibilityMode,
    revision: u64,
    nodes: crate::FxIndexMap<String, AttrMap>,
    // br-r37-c1-d58s8 DiGraph flip P3: String rows GONE — the eager
    // index rows below are the single row store; String views derive
    // through the nodes name table.
    /// br-r37-c1-d58s8 DiGraph row flip phase 1: EAGER integer row
    /// mirrors (insertion-order-faithful, maintained by every writer
    /// with the I5 repair pattern on removal). Phase 2 re-points
    /// readers here; phase 3 deletes the String rows above.
    succ_indices: Vec<Vec<usize>>,
    pred_indices: Vec<Vec<usize>>,
    // br-r37-c1-d58s8 edges-map flip (directed twin): keyed by the
    // ORIENTED (source_idx, target_idx) pair — NOT canonicalized
    // (direction IS identity for directed edges). Zero String
    // allocs/hashes per insert; node removal REKEYS via the remap.
    edges: crate::FxIndexMap<(usize, usize), AttrMap>,
    runtime_policy: RuntimePolicy,
    /// br-r37-c1-d58s8 P1: revision-keyed CSR cache. Derived from the
    /// String maps on demand (never eagerly maintained — the I5
    /// renumbering hazard cannot apply); shared across clones safely
    /// because entries are revision-checked before use. Mutations
    /// invalidate implicitly by bumping `revision`.
    csr_cache: DiCsrCache,
    /// br-r37-c1-d58s8: revision-keyed all-int weights memo (the
    /// shortest-path int-coercion pre-scan walked every edge attr per
    /// call). Single entry keyed by (revision, attr).
    all_int_cache: DiAllIntCache,
}

impl DiGraph {
    /// br-r37-c1-clearedgesinplace (cc): drop all edges in place, keeping nodes (index,
    /// order, attrs). O(E)+O(V): clear the edges map + every succ/pred index row; the
    /// revision bump invalidates the CSR + all-int caches. Sibling of Graph::clear_edges
    /// and MultiDiGraph::clear_edges. The binding's prior path collected the mirror keys
    /// and called remove_edge per edge (each an O(degree) row retain -> O(E*degree),
    /// measured ~0.003-0.011x vs nx); this is the in-place fix.
    pub fn clear_edges(&mut self) {
        if self.edges.is_empty() {
            return;
        }
        self.edges.clear();
        for row in &mut self.succ_indices {
            row.clear();
        }
        for row in &mut self.pred_indices {
            row.clear();
        }
        self.revision = self.revision.saturating_add(1);
    }

    /// 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,
            nodes: self.nodes.clone(),
            succ_indices: self.succ_indices.clone(),
            pred_indices: self.pred_indices.clone(),
            edges: self.edges.clone(),
            runtime_policy: RuntimePolicy::new(self.mode),
            csr_cache: self.csr_cache.clone(),
            all_int_cache: self.all_int_cache.clone(),
        }
    }

    // -----------------------------------------------------------------------
    // Constructors
    // -----------------------------------------------------------------------

    #[must_use]
    pub fn new(mode: CompatibilityMode) -> Self {
        Self {
            mode,
            revision: 0,
            nodes: crate::FxIndexMap::default(),
            succ_indices: Vec::new(),
            pred_indices: Vec::new(),
            edges: crate::FxIndexMap::default(),
            runtime_policy: RuntimePolicy::new(mode),
            csr_cache: std::sync::Arc::default(),
            all_int_cache: std::sync::Arc::default(),
        }
    }

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

    /// br-r37-c1-indsub: directed twin of `Graph::induced_subgraph_ordered` —
    /// build the induced subgraph over `order` (parent node indices, already in
    /// the caller's output order) with no node-name hashing.
    ///
    /// `add_edge_with_attrs` costs two `String` allocations, four name hashes
    /// and TWO `record_decision` ledger entries per arc (the second carrying
    /// four `EvidenceTerm`s, eight more String allocations). Everything it
    /// re-derives is already known here. Invariants reproduced directly:
    /// `edges` keyed by the ORIENTED new-index pair (direction is identity for
    /// a directed edge, so no canonicalization), and a succ/pred row records
    /// its endpoint when the arc is emitted, so both row orders are the walk
    /// order — matching nx's `add_edges_from` over the induced walk.
    ///
    /// `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 = crate::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 succ_indices = vec![Vec::new(); order.len()];
        let mut pred_indices = vec![Vec::new(); order.len()];
        let mut edges = crate::FxIndexMap::default();
        for (slot, &parent_idx) in order.iter().enumerate() {
            for &parent_target in &self.succ_indices[parent_idx] {
                let other = position[parent_target];
                if other == usize::MAX {
                    continue;
                }
                let attrs = self
                    .edges
                    .get(&(parent_idx, parent_target))
                    .cloned()
                    .unwrap_or_default();
                edges.insert((slot, other), attrs);
                succ_indices[slot].push(other);
                pred_indices[other].push(slot);
            }
        }

        Self {
            mode: runtime_policy.mode(),
            revision: 0,
            nodes,
            succ_indices,
            pred_indices,
            edges,
            runtime_policy,
            csr_cache: std::sync::Arc::default(),
            all_int_cache: std::sync::Arc::default(),
        }
    }

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

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

    // -----------------------------------------------------------------------
    // Read-only queries
    // -----------------------------------------------------------------------

    #[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
    }

    /// br-r37-c1-d58s8 P1: revision-keyed integer CSR of both row
    /// families. O(V+E) rebuild only when the graph changed since the
    /// cached build; kernels get index walks identical to the String
    /// walks (per-row order preserved).
    #[must_use]
    pub fn csr(&self) -> std::sync::Arc<DiCsr> {
        if let Ok(guard) = self.csr_cache.read()
            && let Some((rev, csr)) = guard.as_ref()
            && *rev == self.revision
        {
            return csr.clone();
        }
        let built = std::sync::Arc::new(self.build_csr());
        if let Ok(mut guard) = self.csr_cache.write() {
            *guard = Some((self.revision, built.clone()));
        }
        built
    }

    /// 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
    }

    fn build_csr(&self) -> DiCsr {
        // br-r37-c1-d58s8 DiGraph flip P1: build from the EAGER index rows
        // — zero String hashing (was a get_index_of per neighbor).
        let n = self.nodes.len();
        let mut succ_offsets = Vec::with_capacity(n + 1);
        let mut pred_offsets = Vec::with_capacity(n + 1);
        let mut succ_targets = Vec::new();
        let mut pred_targets = Vec::new();
        succ_offsets.push(0);
        pred_offsets.push(0);
        for i in 0..n {
            succ_targets.extend(
                self.succ_indices[i]
                    .iter()
                    .map(|&v| u32::try_from(v).unwrap_or(u32::MAX)),
            );
            succ_offsets.push(succ_targets.len());
            pred_targets.extend(
                self.pred_indices[i]
                    .iter()
                    .map(|&v| u32::try_from(v).unwrap_or(u32::MAX)),
            );
            pred_offsets.push(pred_targets.len());
        }
        DiCsr {
            succ_offsets,
            succ_targets,
            pred_offsets,
            pred_targets,
        }
    }

    /// br-r37-c1-d58s8: consistency oracle — eager index rows must mirror
    /// the String rows exactly (order included). Test-only.
    #[doc(hidden)]
    #[must_use]
    pub fn debug_index_rows_consistent(&self) -> bool {
        // br-r37-c1-d58s8 P3: the String rows this oracle compared
        // against are GONE; the index rows are the single store. Length
        // sanity only (parity batteries cover content).
        self.succ_indices.len() == self.nodes.len() && self.pred_indices.len() == self.nodes.len()
    }

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

    /// Check for directed edge source→target.
    #[must_use]
    /// br-r37-c1-d58s8: resolve a String pair to the ORIENTED index key.
    #[inline]
    fn edge_pair_key(&self, source: &str, target: &str) -> Option<(usize, usize)> {
        Some((
            self.nodes.get_index_of(source)?,
            self.nodes.get_index_of(target)?,
        ))
    }

    /// br-r37-c1-1l8s0: direct slice access to the eager succ index row.
    #[must_use]
    #[inline]
    pub fn successors_indices(&self, idx: usize) -> Option<&[usize]> {
        self.succ_indices.get(idx).map(Vec::as_slice)
    }

    /// Direct slice access to the eager pred index row.
    #[must_use]
    #[inline]
    pub fn predecessors_indices(&self, idx: usize) -> Option<&[usize]> {
        self.pred_indices.get(idx).map(Vec::as_slice)
    }

    pub fn has_edge(&self, source: &str, target: &str) -> bool {
        self.edge_pair_key(source, target)
            .is_some_and(|k| self.edges.contains_key(&k))
    }

    /// br-r37-c1-04z53 (cc): directed `has_edge` straight from insertion-order
    /// indices (source-major), skipping the `i.to_string()` heap alloc for int
    /// nodes. Names come from the node table by index (borrowed); the caller
    /// guards each index with `node_index_matches_int`. Mirror of
    /// `Graph::has_edge_by_indices`.
    ///
    /// br-r37-c1-p1tvg: this used to resolve both indices back to NAMES and
    /// call `has_edge`, which hashes two Strings to rediscover the very
    /// indices it was handed — exactly the cost a caller pays an index route
    /// to avoid. The edges map has been keyed by the ORIENTED
    /// `(source_idx, target_idx)` pair since the d58s8 flip, so the pair IS
    /// the key. An out-of-range index still answers `false`: every key in the
    /// map names two live nodes, so no key can carry one.
    #[must_use]
    pub fn has_edge_by_indices(&self, source_idx: usize, target_idx: usize) -> bool {
        self.edges.contains_key(&(source_idx, target_idx))
    }

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

    /// br-cc-nbunchbulk: does the node at contiguous index `idx` have the exact int
    /// name `idx`? O(1) index probe + no-alloc parse — the int membership fast path
    /// for `_nbunch_present` (sibling of the undirected Graph accessor).
    #[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))
    }

    #[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())
    }

    // -- Directed adjacency queries ----------------------------------------

    /// Successors of `node` (outgoing neighbors). Returns `None` if node absent.
    #[must_use]
    pub fn successors(&self, node: &str) -> Option<Vec<&str>> {
        // br-r37-c1-d58s8 DiGraph flip P2: serve from the eager index
        // rows + name table (order-faithful; oracle-validated in P1).
        let idx = self.nodes.get_index_of(node)?;
        Some(
            self.succ_indices[idx]
                .iter()
                .map(|&i| {
                    self.nodes
                        .get_index(i)
                        .expect("index rows hold valid node indices")
                        .0
                        .as_str()
                })
                .collect(),
        )
    }

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

    /// Predecessors of `node` (incoming neighbors). Returns `None` if node absent.
    #[must_use]
    pub fn predecessors(&self, node: &str) -> Option<Vec<&str>> {
        // br-r37-c1-d58s8 DiGraph flip P2: index-backed.
        let idx = self.nodes.get_index_of(node)?;
        Some(
            self.pred_indices[idx]
                .iter()
                .map(|&i| {
                    self.nodes
                        .get_index(i)
                        .expect("index rows hold valid node indices")
                        .0
                        .as_str()
                })
                .collect(),
        )
    }

    /// br-r37-c1-u3qyn: restore explicit succ/pred row orders (pickle
    /// round-trip) — see Graph::apply_row_orders. `which` selects the
    /// adjacency side.
    pub fn apply_row_orders(&mut self, orders: &[(String, Vec<String>)], pred: bool) {
        // br-r37-c1-d58s8 P3: pure integer-row reorder per family.
        for (node, order) in orders {
            let Some(idx) = self.nodes.get_index_of(node.as_str()) else {
                continue;
            };
            let rows = if pred {
                &mut self.pred_indices
            } else {
                &mut self.succ_indices
            };
            let row = &rows[idx];
            let row_set: std::collections::HashSet<usize> = row.iter().copied().collect();
            let mut placed: std::collections::HashSet<usize> = std::collections::HashSet::new();
            let mut new_row: Vec<usize> = Vec::with_capacity(row.len());
            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);
                }
            }
            rows[idx] = new_row;
        }
    }

    /// br-r37-c1-0ek49: reorder every PRED row into NetworkX's
    /// `DiGraph.copy()` walk order. nx copy rebuilds via the u-major
    /// succ walk (`(u, v, d) for u in _adj for v in _adj[u]`), which
    /// recreates succ rows in their original order but fills each pred
    /// row in walk order: `(pos(u), index of v within succ[u])`. Call on
    /// a fresh clone inside copy-shaped constructors; graph content is
    /// unchanged, only pred row order moves.
    pub fn reorder_pred_rows_for_nx_copy_walk(&mut self) {
        // br-r37-c1-predrebuild: rebuild pred rows in nx's u-major copy-walk order
        // DIRECTLY from succ rows in O(E), replacing the prior per-pred-entry
        // linear search `succ_indices[u].position(|w| w == v)` (O(E * degree) —
        // quadratic on dense graphs). Iterating succ in (u, succ-index) order and
        // appending u to pred[v] reproduces exactly the
        // (pos(u), index-of-v-within-succ[u]) ordering the old sort produced,
        // including parallel-edge multiplicity — byte-identical pred row order.
        let mut new_rows: Vec<Vec<usize>> = self
            .pred_indices
            .iter()
            .map(|row| Vec::with_capacity(row.len()))
            .collect();
        for (u, succ_row) in self.succ_indices.iter().enumerate() {
            for &v in succ_row {
                new_rows[v].push(u);
            }
        }
        self.pred_indices = new_rows;
    }

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

    /// Neighbors = successors (matches NetworkX `DiGraph.neighbors()` convention).
    #[must_use]
    pub fn neighbors(&self, node: &str) -> Option<Vec<&str>> {
        self.successors(node)
    }

    #[must_use]
    pub fn neighbors_iter(&self, node: &str) -> Option<impl Iterator<Item = &str> + '_> {
        self.successors_iter(node)
    }

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

    /// Out-degree: number of successors.
    #[must_use]
    pub fn out_degree(&self, node: &str) -> usize {
        self.nodes
            .get_index_of(node)
            .map_or(0, |i| self.succ_indices[i].len())
    }

    /// In-degree: number of predecessors.
    #[must_use]
    pub fn in_degree(&self, node: &str) -> usize {
        self.nodes
            .get_index_of(node)
            .map_or(0, |i| self.pred_indices[i].len())
    }

    /// Total degree: in_degree + out_degree.
    #[must_use]
    pub fn degree(&self, node: &str) -> usize {
        // br-r37-c1-3gt4y: both rows share the same contiguous node index.
        // Resolve the name once instead of paying the IndexMap lookup in both
        // in_degree() and out_degree(). Missing nodes still report degree zero.
        self.nodes.get_index_of(node).map_or(0, |idx| {
            self.pred_indices[idx].len() + self.succ_indices[idx].len()
        })
    }

    /// br-r37-c1-degidx: index-based degree accessors — O(1), zero
    /// String hashing (the &str path costs get_index_of per call;
    /// degree pays it twice). Used by the directed DegreeView iterator
    /// which walks nodes in index order.
    #[must_use]
    pub fn out_degree_by_index(&self, idx: usize) -> usize {
        self.succ_indices[idx].len()
    }

    #[must_use]
    pub fn in_degree_by_index(&self, idx: usize) -> usize {
        self.pred_indices[idx].len()
    }

    #[must_use]
    pub fn degree_by_index(&self, idx: usize) -> usize {
        self.succ_indices[idx].len() + self.pred_indices[idx].len()
    }

    /// Outgoing edges from `node` as (source, target) pairs.
    #[must_use]
    pub fn out_edges<'a>(&'a self, node: &'a str) -> Vec<(&'a str, &'a str)> {
        // br-r37-c1-d58s8 DiGraph flip P2: index-backed.
        self.nodes.get_index_of(node).map_or_else(Vec::new, |idx| {
            self.succ_indices[idx]
                .iter()
                .map(|&i| {
                    (
                        node,
                        self.nodes
                            .get_index(i)
                            .expect("index rows hold valid node indices")
                            .0
                            .as_str(),
                    )
                })
                .collect()
        })
    }

    /// Incoming edges to `node` as (source, target) pairs.
    #[must_use]
    pub fn in_edges<'a>(&'a self, node: &'a str) -> Vec<(&'a str, &'a str)> {
        // br-r37-c1-d58s8 DiGraph flip P2: index-backed.
        self.nodes.get_index_of(node).map_or_else(Vec::new, |idx| {
            self.pred_indices[idx]
                .iter()
                .map(|&i| {
                    (
                        self.nodes
                            .get_index(i)
                            .expect("index rows hold valid node indices")
                            .0
                            .as_str(),
                        node,
                    )
                })
                .collect()
        })
    }

    // -- Attribute queries -------------------------------------------------

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

    /// Attributes of directed edge source→target.
    #[must_use]
    pub fn edge_attrs(&self, source: &str, target: &str) -> Option<&AttrMap> {
        self.edges.get(&self.edge_pair_key(source, target)?)
    }

    /// br-r37-c1-d58s8: index-keyed attr access (oriented). Zero
    /// node-map probes for callers already holding indices.
    #[must_use]
    #[inline]
    pub fn edge_attrs_by_indices(&self, source_idx: usize, target_idx: usize) -> Option<&AttrMap> {
        self.edges.get(&(source_idx, target_idx))
    }

    /// br-r37-c1-hasattrlazyfix: does ANY directed edge carry the attribute `key` in the
    /// authoritative Rust storage (the inner `edges` AttrMaps), regardless of whether the
    /// lazy `edge_py_attrs` Python mirror has been materialized? ~O(E) key checks.
    #[must_use]
    pub fn any_edge_has_attr(&self, key: &str) -> bool {
        self.edges.values().any(|attrs| attrs.contains_key(key))
    }

    /// Directed twin of `Graph::all_edge_attr_values_scalar`: true if EVERY inner
    /// edge attr value is a faithful scalar (Int/Float/Bool). No-alloc scan over
    /// the edge store values — contrast `edges_ordered_borrowed`, which allocates
    /// an O(E) Vec and resolves node names per edge. Used by the reverse 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: any node / any edge carries a Python-visible attr per
    /// the authoritative inner storage (not the lazy `*_py_attrs` mirrors).
    #[must_use]
    pub fn any_node_has_attrs(&self) -> bool {
        self.nodes.values().any(|attrs| !attrs.is_empty())
    }

    #[must_use]
    pub fn any_edge_has_attrs(&self) -> bool {
        self.edges.values().any(|attrs| !attrs.is_empty())
    }

    /// br-r37-c1-prdir: iterate every directed edge as
    /// `((source_idx, target_idx), &AttrMap)` straight from the index-keyed edge
    /// store, in insertion order. Lets COO/CSR exporters read each edge's weight
    /// with ONE attr lookup instead of the per-edge `edges.get(&(u,v))` hash that
    /// the successors-then-`edge_attrs_by_indices` path pays.
    pub fn edges_indexed(&self) -> impl Iterator<Item = ((usize, usize), &AttrMap)> + '_ {
        self.edges.iter().map(|(&pair, attrs)| (pair, attrs))
    }

    #[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 `true` for DiGraph.
    #[must_use]
    pub fn is_directed(&self) -> bool {
        true
    }

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

    // -----------------------------------------------------------------------
    // Mutations
    // -----------------------------------------------------------------------

    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: the storage half of [`Self::add_node_with_attrs`],
    /// without its ledger record. See the undirected `Graph` sibling.
    /// br-r37-c1-jc9e4: the key is materialised only on the VACANT path, the
    /// directed mirror of the `Graph` sibling. 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`. The allocation census
    /// measured the directed pair at the undirected pair's pre-lever numbers,
    /// so the fix did not transfer on its own and had to be applied here too.
    ///
    /// Occupied-branch semantics are unchanged: `IndexMap::entry(..).or_default()`
    /// on a present key returns the existing value without reordering, which is
    /// exactly what `get_mut` returns.
    fn add_node_with_attrs_unrecorded(
        &mut self,
        node: impl AsRef<str> + Into<String>,
        attrs: AttrMap,
    ) -> (bool, bool, usize) {
        let existed = self.nodes.contains_key(node.as_ref());
        let mut changed = !existed;
        let attrs_count = {
            let bucket = if existed {
                self.nodes
                    .get_mut(node.as_ref())
                    .expect("contains_key reported this node present")
            } else {
                self.nodes.entry(node.into()).or_default()
            };
            if !attrs.is_empty()
                && attrs
                    .iter()
                    .any(|(key, value)| bucket.get(key) != Some(value))
            {
                changed = true;
            }
            bucket.extend(attrs);
            bucket.len()
        };
        if self.succ_indices.len() < self.nodes.len() {
            self.succ_indices.push(Vec::new());
            self.pred_indices.push(Vec::new());
        }
        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> + 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
    }

    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,
        source: impl AsRef<str>,
        target: impl AsRef<str>,
    ) -> Result<(), GraphError> {
        self.add_edge_with_attrs(source, target, AttrMap::new())
    }

    /// br-r37-c1-jc9e4: the directed mirror of the `Graph` sibling — the
    /// endpoint keys are never owned here, and each is resolved with ONE map
    /// probe. This used to own both keys, clone each again for autocreation,
    /// and then hash each up to three times (`contains_key`, `get_index_of`
    /// for the edge key, `get_index_of` again for the successor/predecessor
    /// rows). The census measured the directed pair at the undirected pair's
    /// pre-lever numbers, so none of that transferred on its own.
    pub fn add_edge_with_attrs(
        &mut self,
        source: impl AsRef<str>,
        target: impl AsRef<str>,
        attrs: AttrMap,
    ) -> Result<(), GraphError> {
        let source = source.as_ref();
        let target = target.as_ref();

        let unknown_feature = attrs
            .keys()
            .any(|key| key.starts_with("__fnx_incompatible"));
        let self_loop = source == target;
        let incompatibility_probability = if unknown_feature {
            1.0
        } else if self_loop {
            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(),
            });
        }

        // Auto-create nodes. br-r37-c1-wa1b9: no record of their own — the
        // outcome record below reports them via source/target_autocreated. See
        // the undirected `Graph` sibling for the ruling.
        // Resolve each endpoint with ONE probe: `get_index_of` answers both
        // "does it exist" and "what is its index", so the old `contains_key`
        // that preceded it was a second hash of the same key. A self-loop does
        // not probe the target at all — `self_loop` makes the indices equal by
        // construction. Order is untouched: the source is still resolved and
        // autocreated before the target, and `IndexMap` appends, so
        // autocreating the target cannot move the source's index.
        let mut source_autocreated = false;
        let source_idx = match self.nodes.get_index_of(source) {
            Some(index) => index,
            None => {
                let _ = self.add_node_with_attrs_unrecorded(source, AttrMap::new());
                source_autocreated = true;
                self.nodes.get_index_of(source).expect("autocreated above")
            }
        };
        let mut target_autocreated = false;
        let target_idx = if self_loop {
            target_autocreated = source_autocreated;
            source_idx
        } else {
            match self.nodes.get_index_of(target) {
                Some(index) => index,
                None => {
                    let _ = self.add_node_with_attrs_unrecorded(target, AttrMap::new());
                    target_autocreated = true;
                    self.nodes.get_index_of(target).expect("autocreated above")
                }
            }
        };

        let edge_key = (source_idx, target_idx);
        let new_edge = !self.edges.contains_key(&edge_key);
        let mut changed = new_edge;
        let edge_attr_count = {
            let edge_attrs = self.edges.entry(edge_key).or_default();
            if edge_attrs.is_empty() {
                // br-r37-c1-jc9e4: a fresh bucket TAKES the caller's map whole.
                // Directed mirror of the `Graph` sibling — see it for why, and
                // for the byte-identity argument.
                if !attrs.is_empty() {
                    changed = true;
                }
                *edge_attrs = attrs;
            } else {
                if !attrs.is_empty()
                    && attrs
                        .iter()
                        .any(|(key, value)| edge_attrs.get(key) != Some(value))
                {
                    changed = true;
                }
                edge_attrs.extend(attrs);
            }
            edge_attrs.len()
        };
        // br-r37-c1-d58s8 DiGraph flip P1: eager index rows (dup-guarded
        // by edge newness; the IndexSet inserts above are idempotent).
        if new_edge {
            // br-r37-c1-jc9e4: reuse the indices resolved above rather than
            // hashing both keys a third time. Nothing between the resolution
            // and here touches `self.nodes` — the intervening work is the
            // `self.edges` entry and the attr extend — so these are the same
            // two indices the lookups produced.
            self.succ_indices[source_idx].push(target_idx);
            self.pred_indices[target_idx].push(source_idx);
        }

        if changed {
            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: "source_autocreated".into(),
                    observed_value: bool_evidence(source_autocreated),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "target_autocreated".into(),
                    observed_value: bool_evidence(target_autocreated),
                    log_likelihood_ratio: -1.25,
                },
            ],
        );

        Ok(())
    }

    /// Bulk-add a sequence of attribute-free directed 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 where per-edge compatibility
    /// accounting would add constant-factor overhead without adding
    /// useful policy evidence. Nodes referenced by edges are
    /// auto-created if absent, matching `add_edge` semantics.
    #[must_use]
    pub fn extend_edges_unrecorded<I, S, T>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (S, T)>,
        S: Into<String>,
        T: Into<String>,
    {
        // br-r37-c1-digbatch: compute each endpoint's index ONCE via match-insert
        // (mirroring Graph::extend_edges_unrecorded) instead of contains_key + TWO
        // get_index_of per endpoint. The old form did ~6 IndexMap hashes/edge, so
        // DiGraph.add_edges_from ran 4x slower than Graph's (taxing every DiGraph-
        // returning constructor). Reserve the collections up front as well.
        let iterator = edges.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.nodes.reserve(lower_bound);
        self.succ_indices.reserve(lower_bound);
        self.pred_indices.reserve(lower_bound);
        self.edges.reserve(lower_bound);

        let mut inserted = 0usize;
        for (source, target) in iterator {
            let source = source.into();
            let target = target.into();
            let s_idx = match self.nodes.get_index_of(&source) {
                Some(index) => index,
                None => {
                    let index = self.nodes.len();
                    self.nodes.insert(source.clone(), AttrMap::new());
                    self.succ_indices.push(Vec::new());
                    self.pred_indices.push(Vec::new());
                    index
                }
            };
            let t_idx = if source == target {
                s_idx
            } else {
                match self.nodes.get_index_of(&target) {
                    Some(index) => index,
                    None => {
                        let index = self.nodes.len();
                        self.nodes.insert(target.clone(), AttrMap::new());
                        self.succ_indices.push(Vec::new());
                        self.pred_indices.push(Vec::new());
                        index
                    }
                }
            };
            let edge_key = (s_idx, t_idx);
            if self.edges.contains_key(&edge_key) {
                continue;
            }
            self.edges.insert(edge_key, AttrMap::new());
            self.succ_indices[s_idx].push(t_idx);
            self.pred_indices[t_idx].push(s_idx);
            inserted += 1;
        }

        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            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,
                }],
            );
        }

        inserted
    }

    /// br-r37-c1-tcidx: bulk-add directed edges by EXISTING node index — the directed sibling of
    /// `Graph::extend_existing_index_edges_unrecorded`. All endpoints MUST already exist (callers
    /// gate on all nodes being pre-added). A new edge takes an empty AttrMap; a duplicate
    /// `(source_idx, target_idx)` pair is skipped. Emits the IDENTICAL succ/pred adjacency,
    /// revision bump, and batch ledger summary as `extend_edges_unrecorded` given the same
    /// resolved index sequence — but with ZERO String hashing (endpoints arrive as integer
    /// indices). Unblocks the O(|V|²)-closure `transitive_closure` from paying a per-edge
    /// `get_index_of` on both endpoints.
    pub fn extend_existing_index_edges_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (usize, usize)>,
    {
        let iterator = edges.into_iter();
        self.edges.reserve(iterator.size_hint().0);

        let mut inserted = 0usize;
        for (s_idx, t_idx) in iterator {
            debug_assert!(s_idx < self.nodes.len());
            debug_assert!(t_idx < self.nodes.len());
            let edge_key = (s_idx, t_idx);
            if self.edges.contains_key(&edge_key) {
                continue;
            }
            self.edges.insert(edge_key, AttrMap::new());
            self.succ_indices[s_idx].push(t_idx);
            self.pred_indices[t_idx].push(s_idx);
            inserted += 1;
        }

        if inserted > 0 {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
            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,
                }],
            );
        }

        inserted
    }

    /// br-r37-c1-digbatch: bulk-add plain nodes (no attrs), one summary ledger
    /// record — the directed sibling of `Graph::extend_nodes_unrecorded`, backing
    /// PyDiGraph's fast integer-node path (`add_nodes_from(range)` / int list).
    /// First insertion wins order; existing nodes are skipped.
    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.succ_indices.reserve(lower_bound);
        self.pred_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.succ_indices.push(Vec::new());
            self.pred_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-dgctor: bulk-add nodes WITH attrs, one summary ledger
    /// record — the directed sibling of `Graph::extend_nodes_unrecorded`
    /// extended with per-node AttrMaps. First insertion wins the order;
    /// re-inserting an existing node merges attrs (matching
    /// `add_node_with_attrs`).
    #[must_use]
    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 {
            if let Some(existing) = self.nodes.get_mut(&node) {
                existing.extend(attrs);
                continue;
            }
            self.nodes.insert(node.clone(), attrs);
            self.succ_indices.push(Vec::new());
            self.pred_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-dgctor: bulk-add ATTRIBUTED directed edges without
    /// per-edge ledger records — the directed sibling of
    /// `Graph::extend_edges_with_attrs_unrecorded`. Insert-or-MERGE
    /// (duplicate (source, target) extends the existing AttrMap, matching
    /// `add_edge_with_attrs`); nodes auto-created in first-appearance
    /// order. Callers must pre-screen "__fnx_incompatible" attr keys.
    #[must_use]
    pub fn extend_edges_with_attrs_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (String, String, AttrMap)>,
    {
        let mut inserted = 0usize;
        let mut merged_changed = false;
        for (source, target, attrs) in edges {
            if !self.nodes.contains_key(&source) {
                self.nodes.insert(source.clone(), AttrMap::new());
                self.succ_indices.push(Vec::new());
                self.pred_indices.push(Vec::new());
            }
            if source != target && !self.nodes.contains_key(&target) {
                self.nodes.insert(target.clone(), AttrMap::new());
                self.succ_indices.push(Vec::new());
                self.pred_indices.push(Vec::new());
            }
            let edge_key = (
                self.nodes.get_index_of(&source).expect("created above"),
                self.nodes.get_index_of(&target).expect("created above"),
            );
            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;
            }
            self.edges.insert(edge_key, attrs);
            let s_idx = self
                .nodes
                .get_index_of(&source)
                .expect("source node exists");
            let t_idx = self
                .nodes
                .get_index_of(&target)
                .expect("target node exists");
            self.succ_indices[s_idx].push(t_idx);
            self.pred_indices[t_idx].push(s_idx);
            inserted += 1;
        }
        if inserted > 0 || merged_changed {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted.max(1)).unwrap_or(u64::MAX));
            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,
                }],
            );
        }
        inserted
    }

    /// Bulk-add ATTRIBUTED directed edges when the caller has already
    /// identified newly-created nodes. This keeps edge-map insertion in global
    /// input order, then stages successor and predecessor row commits by row so
    /// adjacency maps are probed once per touched row rather than once per edge.
    #[must_use]
    pub fn extend_prepared_edges_with_attrs_row_staged_unrecorded<I, N>(
        &mut self,
        new_nodes: N,
        edges: I,
    ) -> usize
    where
        I: IntoIterator<Item = (String, String, AttrMap)>,
        N: IntoIterator<Item = String>,
    {
        for node in new_nodes {
            if self.nodes.contains_key(&node) {
                continue;
            }
            self.nodes.insert(node.clone(), AttrMap::new());
            self.succ_indices.push(Vec::new());
            self.pred_indices.push(Vec::new());
        }

        let mut inserted = 0usize;
        let mut merged_changed = false;
        let mut successor_rows: IndexMap<String, Vec<String>> = IndexMap::new();
        let mut predecessor_rows: IndexMap<String, Vec<String>> = IndexMap::new();

        for (source, target, attrs) in edges {
            let edge_key = (
                self.nodes.get_index_of(&source).expect("created above"),
                self.nodes.get_index_of(&target).expect("created above"),
            );
            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;
            }

            successor_rows
                .entry(source.clone())
                .or_default()
                .push(target.clone());
            predecessor_rows
                .entry(target.clone())
                .or_default()
                .push(source.clone());
            let s_idx = self
                .nodes
                .get_index_of(&source)
                .expect("source node exists");
            let t_idx = self
                .nodes
                .get_index_of(&target)
                .expect("target node exists");
            self.succ_indices[s_idx].push(t_idx);
            self.pred_indices[t_idx].push(s_idx);
            self.edges.insert(edge_key, attrs);
            inserted += 1;
        }

        if inserted > 0 || merged_changed {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted.max(1)).unwrap_or(u64::MAX));
            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,
                }],
            );
        }

        inserted
    }

    /// Bulk-add attributed directed edges into a fresh graph when the caller has
    /// already assigned NetworkX-compatible node indices in first-seen order.
    ///
    /// This bypasses the string-key lookup path in
    /// [`extend_prepared_edges_with_attrs_row_staged_unrecorded`]: node labels
    /// are installed once, then edges are committed directly by `(source_idx,
    /// target_idx)`. Duplicate directed edges merge attributes without appending
    /// another successor/predecessor entry, matching `DiGraph.add_edges_from`.
    #[must_use]
    /// br-r37-c1-dodattrbatch: bulk-add ATTRIBUTED directed edges by EXISTING
    /// node index. All endpoints MUST already exist (callers gate on int-labeled
    /// nodes). A new edge takes the AttrMap; a duplicate (source, target) MERGES
    /// last-wins like add_edge_with_attrs. Sibling of the fresh-index attr extend
    /// minus node creation; integer index rows only (no String hashing).
    pub fn extend_existing_index_edges_with_attrs_unrecorded<I>(&mut self, edges: I) -> usize
    where
        I: IntoIterator<Item = (usize, usize, AttrMap)>,
    {
        let node_count = self.nodes.len();
        let edges = edges.into_iter();
        self.edges.reserve(edges.size_hint().0);
        let mut inserted = 0usize;
        let mut merged_changed = false;
        for (source_idx, target_idx, attrs) in edges {
            debug_assert!(source_idx < node_count && target_idx < node_count);
            let edge_key = (source_idx, target_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;
            }
            self.edges.insert(edge_key, attrs);
            self.succ_indices[source_idx].push(target_idx);
            self.pred_indices[target_idx].push(source_idx);
            inserted += 1;
        }
        if inserted > 0 || merged_changed {
            self.revision = self
                .revision
                .saturating_add(u64::try_from(inserted).unwrap_or(u64::MAX));
        }
        inserted
    }

    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.succ_indices.is_empty()
            || !self.pred_indices.is_empty()
            || !self.edges.is_empty()
        {
            return 0;
        }

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

        let mut inserted = 0usize;
        let mut merged_changed = false;
        let edges = edges.into_iter();
        self.edges.reserve(edges.size_hint().0);
        for (source_idx, target_idx, attrs) in edges {
            if source_idx >= node_count || target_idx >= node_count {
                continue;
            }
            let edge_key = (source_idx, target_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;
            }
            self.edges.insert(edge_key, attrs);
            self.succ_indices[source_idx].push(target_idx);
            self.pred_indices[target_idx].push(source_idx);
            inserted += 1;
        }

        if node_count > 0 || inserted > 0 || merged_changed {
            self.revision = self.revision.saturating_add(
                u64::try_from(node_count.saturating_add(inserted)).unwrap_or(u64::MAX),
            );
            self.record_decision(
                "extend_fresh_index_edges_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,
                    },
                ],
            );
        }

        inserted
    }

    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.
    pub fn replace_edge_attrs(&mut self, source: &str, target: &str, attrs: AttrMap) -> bool {
        let Some(edge_key) = self.edge_pair_key(source, target) 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
        }
    }

    /// Remove directed edge source→target. Returns `true` if it existed.
    pub fn remove_edge(&mut self, source: &str, target: &str) -> bool {
        let Some(pair) = self.edge_pair_key(source, target) else {
            return false;
        };
        // br-r37-c1-vbwpl (cc, ported from PyGraph::remove_edge): swap_remove
        // (O(1)) instead of shift_remove (O(|E|)) — turns remove-heavy work
        // (remove_edges_from, double_edge_swap) from O(k*|E|) into O(k). The
        // `edges` map's STORAGE order is never observed externally: `edges_ordered`
        // /`edges_ordered_borrowed` walk `succ_indices` and look edges up by key;
        // COO/CSR exporters (`edges_indexed`) are triple-order-irrelevant (scipy
        // CSR canonicalises); `weighted_size_int`/attr scans are order-insensitive
        // sums/`any`. `remove_node` already swap_removes this same map (see below),
        // so the "unobserved" invariant is already committed. DiGraph has no
        // edge_index_endpoints parallel vector (that is PyGraph-only), so no
        // parallel structure needs the matching swap.
        let removed = self.edges.swap_remove(&pair).is_some();
        if removed {
            if let (Some(s_idx), Some(t_idx)) = (
                self.nodes.get_index_of(source),
                self.nodes.get_index_of(target),
            ) {
                self.succ_indices[s_idx].retain(|&i| i != t_idx);
                self.pred_indices[t_idx].retain(|&i| i != s_idx);
            }
            self.revision = self.revision.saturating_add(1);
        }
        removed
    }

    /// Remove node and all incident edges (both incoming and outgoing).
    pub fn remove_node(&mut self, node: &str) -> bool {
        if !self.nodes.contains_key(node) {
            return false;
        }

        // br-r37-c1-rmnode-di2: drop each incident edge with O(1) `swap_remove`
        // (the `edges` map order is never observed externally — `edges_ordered`,
        // used by every public consumer, walks node->successor order, and the one
        // internal map-order use, `to_undirected`, was canonicalised). The
        // incident edges are known exactly from successors/predecessors, so the
        // whole removal is O(degree) instead of the O(|E|) `retain` scan (let
        // alone the original O(degree*|E|) per-edge shift_remove). Matches nx's
        // O(degree) remove_node.
        // br-r37-c1-d58s8 P3: incident-edge walk from the index rows;
        // the per-neighbor String-row maintenance vanished with the rows
        // (the index repair below handles the integer side).
        let node_idx = self
            .nodes
            .get_index_of(node)
            .expect("node existence checked above");

        // br-r37-c1-qxtlj: undirected sibling's fast path, same reasoning. The
        // incident-edge removal above is already O(degree) here, so what is left
        // to skip is the succ/pred index repair, which walks EVERY row to drop
        // references to `idx` and decrement the indices that shifted down. When
        // `idx` is the last position nothing shifts, and when both rows are
        // empty no row references it, so that repair is a no-op over its whole
        // input. Measured before this: one isolated node off a 12800-node
        // DiGraph cost 178.22us against networkx's 0.71us (0.0040x), the same
        // whether the node sat first or last.
        if node_idx + 1 == self.nodes.len()
            && self.succ_indices[node_idx].is_empty()
            && self.pred_indices[node_idx].is_empty()
        {
            self.nodes.shift_remove(node);
            self.succ_indices.remove(node_idx);
            self.pred_indices.remove(node_idx);
            self.revision = self.revision.saturating_add(1);
            return true;
        }

        let targets: Vec<usize> = self.succ_indices[node_idx].clone();
        for t in targets {
            self.edges.swap_remove(&(node_idx, t));
        }
        let sources: Vec<usize> = self.pred_indices[node_idx].clone();
        for s in sources {
            self.edges.swap_remove(&(s, node_idx));
        }

        // br-r37-c1-d58s8 DiGraph flip P1: I5 repair on both index
        // families — drop the removed index's rows, purge refs, decrement
        // indices that shift down.
        let idx = self
            .nodes
            .get_index_of(node)
            .expect("node existence checked above");
        self.nodes.shift_remove(node);
        self.succ_indices.remove(idx);
        self.pred_indices.remove(idx);
        // br-cc-rmnode-fuse: one pass per row (was retain THEN decrement) —
        // drop refs to the removed index and decrement shifted indices in a
        // single traversal. Order preserved.
        for rows in [&mut self.succ_indices, &mut self.pred_indices] {
            for row in rows.iter_mut() {
                let mut w = 0usize;
                for read in 0..row.len() {
                    let e = row[read];
                    if e == idx {
                        continue;
                    }
                    row[w] = if e > idx { e - 1 } else { e };
                    w += 1;
                }
                row.truncate(w);
            }
        }
        // br-r37-c1-d58s8 edges-map flip: REKEY surviving edges past the
        // removed index (integer rehash, order preserved).
        self.edges = std::mem::take(&mut self.edges)
            .into_iter()
            .map(|((s, t), attrs)| {
                (
                    (
                        if s > idx { s - 1 } else { s },
                        if t > idx { t - 1 } else { t },
                    ),
                    attrs,
                )
            })
            .collect();
        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: std::collections::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 DiGraph flip P1: removed-mask + old->new remap
        // BEFORE the map shifts; index rows filtered + remapped from the
        // OLD rows (the slice-1 recipe).
        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;
            }
        }
        for rows in [&mut self.succ_indices, &mut self.pred_indices] {
            let old_rows = std::mem::take(rows);
            *rows = 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();
        }
        self.nodes
            .retain(|node, _| !remove_set.contains(node.as_str()));
        self.edges
            .retain(|&(s, t), _| !removed_mask[s] && !removed_mask[t]);
        // br-r37-c1-d58s8 edges-map flip: rekey survivors through the remap.
        self.edges = std::mem::take(&mut self.edges)
            .into_iter()
            .map(|((s, t), attrs)| ((remap[s], remap[t]), attrs))
            .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)
    }

    // -----------------------------------------------------------------------
    // Snapshot / ordered iteration
    // -----------------------------------------------------------------------

    /// Edges in deterministic order: iterate nodes in insertion order, then
    /// each node's successors in insertion order.
    #[must_use]
    pub fn edges_ordered(&self) -> Vec<EdgeSnapshot> {
        let mut ordered = Vec::with_capacity(self.edges.len());

        for (u, row) in self.succ_indices.iter().enumerate() {
            let node = self.nodes.get_index(u).expect("valid index").0;
            for &t in row {
                let target = self.nodes.get_index(t).expect("valid index").0;
                if let Some(attrs) = self.edges.get(&(u, t)) {
                    ordered.push(EdgeSnapshot {
                        left: node.clone(),
                        right: target.clone(),
                        attrs: attrs.clone(),
                    });
                }
            }
        }

        ordered
    }

    #[must_use]
    pub fn edges_ordered_borrowed(&self) -> Vec<(&str, &str, &AttrMap)> {
        let mut ordered = Vec::with_capacity(self.edges.len());

        for (u, row) in self.succ_indices.iter().enumerate() {
            let node = self.nodes.get_index(u).expect("valid index").0;
            for &t in row {
                let target = self.nodes.get_index(t).expect("valid index").0;
                if let Some(attrs) = self.edges.get(&(u, t)) {
                    ordered.push((node.as_str(), target.as_str(), attrs));
                }
            }
        }

        ordered
    }

    /// br-r37-c1-wsize (cc): integer `size(weight)` from the store — directed
    /// twin of `Graph::weighted_size_int`. A directed edge `(u,v,w)` adds `w` to
    /// `out_degree(u)` and `in_degree(v)`, so `sum(degree)/2` halves back to each
    /// edge's weight once; a self-loop adds `w` to both in and out of one node →
    /// `2w` → halves to `w`, again one stored edge counted once. Returns `None` on
    /// any non-integer weight (caller uses the exact degree path); missing weight
    /// defaults to nx's int `1`.
    #[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-revborrow: O(V+E) directed transpose. The reverse of a
    /// `DiGraph` keeps the SAME node table (identical insertion order, identical
    /// indices), so reversing is a pure topology flip — no String hashing, no
    /// per-edge node-index lookups, no re-insertion through the name table (the
    /// edge-iterate + `edges_ordered()` clone + `extend_edges_with_attrs_*`
    /// re-hash path is O(E) String/hash work this avoids entirely).
    ///
    /// Successor rows are rebuilt by walking the ORIGINAL successor rows in
    /// node-major (ascending source index) order and appending the reversed
    /// endpoint, so the reversed graph's `edges_ordered()` stream is
    /// byte-identical to NetworkX's `reverse()`, which walks `self.edges()`
    /// (u-major successor order) and adds each `(v, u)`. `pred_indices[u]` ends
    /// up equal to the original `succ_indices[u]`, matching NetworkX's reversed
    /// `pred` order as well. Node + edge attribute maps are cloned verbatim.
    #[must_use]
    pub fn reversed(&self) -> Self {
        let n = self.nodes.len();
        let mut succ_indices: Vec<Vec<usize>> = vec![Vec::new(); n];
        let mut pred_indices: Vec<Vec<usize>> = vec![Vec::new(); n];
        for (i, (succ_row, pred_row)) in succ_indices
            .iter_mut()
            .zip(pred_indices.iter_mut())
            .enumerate()
        {
            // reversed succ row = original pred row; reversed pred row = original
            // succ row — pre-size so neither row reallocates.
            succ_row.reserve(self.pred_indices[i].len());
            pred_row.reserve(self.succ_indices[i].len());
        }
        let mut edges: crate::FxIndexMap<(usize, usize), AttrMap> =
            crate::FxIndexMap::with_capacity_and_hasher(
                self.edges.len(),
                rustc_hash::FxBuildHasher,
            );
        for (u, (source_succs, reversed_preds)) in self
            .succ_indices
            .iter()
            .zip(pred_indices.iter_mut())
            .enumerate()
        {
            for &t in source_succs {
                // original edge u -> t becomes t -> u in the reverse
                succ_indices[t].push(u);
                reversed_preds.push(t);
                if let Some(attrs) = self.edges.get(&(u, t)) {
                    edges.insert((t, u), attrs.clone());
                }
            }
        }
        Self {
            mode: self.mode,
            revision: 0,
            nodes: self.nodes.clone(),
            succ_indices,
            pred_indices,
            edges,
            runtime_policy: self.runtime_policy.clone(),
            csr_cache: std::sync::Arc::default(),
            all_int_cache: std::sync::Arc::default(),
        }
    }

    /// Directed edge endpoints in the same order as `edges_ordered_borrowed`.
    #[must_use]
    pub fn edges_ordered_indices(&self) -> Vec<(usize, usize)> {
        let mut ordered = Vec::with_capacity(self.edges.len());

        for (u, row) in self.succ_indices.iter().enumerate() {
            for &t in row {
                if self.edges.contains_key(&(u, t)) {
                    ordered.push((u, t));
                }
            }
        }

        ordered
    }

    #[must_use]
    pub fn snapshot(&self) -> DiGraphSnapshot {
        let node_attrs: std::collections::BTreeMap<String, AttrMap> = self
            .nodes
            .iter()
            .filter(|(_, attrs)| !attrs.is_empty())
            .map(|(name, attrs)| (name.clone(), attrs.clone()))
            .collect();
        DiGraphSnapshot {
            mode: self.mode,
            nodes: self.nodes.keys().cloned().collect(),
            node_attrs,
            edges: self.edges_ordered(),
        }
    }

    /// Convert to an undirected Graph by dropping directionality.
    /// Both (u→v) and (v→u) merge into a single undirected edge.
    /// When both exist, the latter's attributes overwrite the former's.
    #[must_use]
    pub fn to_undirected(&self) -> crate::Graph {
        let mut g = crate::Graph::with_runtime_policy(self.runtime_policy.clone());
        for (node, attrs) in &self.nodes {
            g.add_node_with_attrs(node.clone(), attrs.clone());
        }
        // Iterate in canonical node->successor order (`edges_ordered`) rather
        // than the private `edges` IndexMap order: this matches networkx's
        // reciprocal-edge merge order (for a<->b the later-processed direction's
        // attrs win) AND keeps the `edges` map order unobservable, so
        // `remove_node` can drop incident edges with O(1) swap_remove.
        //
        // br-r37-c1-toundirbatch (cc): collect the directed edges (same
        // edges_ordered order) + one extend_edges_with_attrs_unrecorded instead
        // of per-edge add_edge_with_attrs (a policy record EACH — and for a<->b
        // reciprocal digraphs HALF the calls are merge-dups). The batch helper
        // dedups on the canonical endpoint pair and merges attrs via the same
        // `extend` (later direction wins), in the identical order; all nodes are
        // pre-added so endpoints resolve to existing indices → byte-identical.
        let edges: Vec<(String, String, AttrMap)> = self
            .edges_ordered()
            .into_iter()
            .map(|snap| (snap.left, snap.right, snap.attrs))
            .collect();
        let _ = g.extend_edges_with_attrs_unrecorded(edges);
        g
    }

    // -----------------------------------------------------------------------
    // Internal
    // -----------------------------------------------------------------------

    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
    }
}

#[derive(Debug, Clone)]
pub struct MultiDiGraph {
    mode: CompatibilityMode,
    revision: u64,
    nodes: crate::FxIndexMap<String, AttrMap>,
    successors: crate::FxIndexMap<String, crate::FxIndexMap<String, crate::FxIndexSet<usize>>>,
    predecessors: crate::FxIndexMap<String, crate::FxIndexMap<String, crate::FxIndexSet<usize>>>,
    edges: crate::FxIndexMap<DirectedEdgeKey, IndexMap<usize, AttrMap>>,
    runtime_policy: RuntimePolicy,
    edge_count: usize,
    csr_cache: MultiDiCsrCache,
    /// br-r37-c1-s8dj1: (source position, target position) -> position in
    /// `edges`, so an edge can be reached without hashing the node keys.
    ///
    /// Every level of this graph's storage is keyed by `String`, so resolving an
    /// edge cost a hash of the whole node key however the caller arrived — which
    /// is why `has_edge_by_indices` could only convert its indices BACK to names,
    /// and the directed class kept a 3.7x key-length slope on `has_edge(u, v)`
    /// and 4.4x on the keyed form while the slot-addressed undirected twin sat at
    /// networkx's own 1.9x.
    ///
    /// BUILT LAZILY AND MAINTAINED INCREMENTALLY. A first attempt rebuilt it on
    /// every revision change, which made an add-then-check loop O(E) per probe
    /// and measured 137x slower than networkx at E=8000 — the rebuild was worse
    /// than the hashing it removed. Adds now patch the map in O(1), because
    /// inserting into `edges` APPENDS and adding a node APPENDS, so no existing
    /// position moves.
    ///
    /// THE STAMP IS THE SAFETY NET, not merely an optimisation. Removals do move
    /// both index spaces (`remove_node` shift-removes from `nodes`,
    /// `remove_edge` swap-removes from `edges`) and are deliberately NOT patched
    /// here: they bump `revision` without re-stamping, so the next read finds a
    /// stale stamp and rebuilds. Any mutation path not handled explicitly
    /// therefore degrades to a correct rebuild rather than a wrong answer.
    edge_pair_index: EdgePairIndex,
}

impl MultiDiGraph {
    /// br-r37-c1-7qqr8: positional index of a node, matching
    /// `DiGraph::get_node_index`. MultiDiGraph carried the
    /// `NodeIndexLookupCache` (br-r37-c1-ic4cv) but only ever used its
    /// present-set half, so there was no accessor to populate the index half
    /// from — which is what the edge-attr index lookaside needs.
    #[must_use]
    pub fn get_node_index(&self, node: &str) -> Option<usize> {
        self.nodes.get_index_of(node)
    }

    /// 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,
            nodes: self.nodes.clone(),
            successors: self.successors.clone(),
            predecessors: self.predecessors.clone(),
            edges: self.edges.clone(),
            runtime_policy: RuntimePolicy::new(self.mode),
            edge_count: self.edge_count,
            csr_cache: self.csr_cache.clone(),
            edge_pair_index: EdgePairIndex::default(),
        }
    }

    /// br-r37-c1-s0d4x: reorder every PRED row into NetworkX's
    /// `MultiDiGraph.copy()` walk order — the multigraph counterpart of
    /// DiGraph::reorder_pred_rows_for_nx_copy_walk: each pred row's cells
    /// sort by `(pos(u), index of v within succ[u])`; succ rows are
    /// recreated in their original order by the u-major walk.
    pub fn reorder_pred_rows_for_nx_copy_walk(&mut self) {
        // br-r37-c1-predrebuild: build each pred row's u-major copy-walk order
        // DIRECTLY by walking succ in pos(u) order, replacing the prior
        // per-pred-entry double `get_index_of` lookup + per-row sort. Each pred
        // row holds DISTINCT predecessors u, so pos(u) is the sole ordering key
        // (the succ-index tiebreak never fires), and appending u to pred[v] while
        // iterating succ in insertion (= position) order yields the exact same
        // ordering — byte-identical pred row order, no sort, no index lookups.
        let mut order_map: IndexMap<String, Vec<String>> =
            IndexMap::with_capacity(self.predecessors.len());
        for (u, succ_row) in &self.successors {
            for v in succ_row.keys() {
                order_map.entry(v.clone()).or_default().push(u.clone());
            }
        }
        let orders: Vec<(String, Vec<String>)> = order_map.into_iter().collect();
        self.apply_row_orders(&orders, true);
    }

    /// br-r37-c1-u3qyn: restore explicit succ/pred row orders (pickle
    /// round-trip) — see Graph::apply_row_orders. Keyed cells move
    /// wholesale; `pred` selects the adjacency side.
    pub fn apply_row_orders(&mut self, orders: &[(String, Vec<String>)], pred: bool) {
        let map = if pred {
            &mut self.predecessors
        } else {
            &mut self.successors
        };
        for (node, order) in orders {
            let Some(row) = map.get_mut(node.as_str()) else {
                continue;
            };
            let mut old = std::mem::take(row);
            let mut new_row =
                crate::FxIndexMap::with_capacity_and_hasher(old.len(), rustc_hash::FxBuildHasher);
            for v in order {
                if let Some((k, val)) = old.shift_remove_entry(v.as_str()) {
                    new_row.insert(k, val);
                }
            }
            for (k, val) in old {
                new_row.insert(k, val);
            }
            *row = new_row;
        }
    }

    #[must_use]
    pub fn new(mode: CompatibilityMode) -> Self {
        Self {
            mode,
            revision: 0,
            nodes: crate::FxIndexMap::default(),
            successors: crate::FxIndexMap::default(),
            predecessors: crate::FxIndexMap::default(),
            edges: crate::FxIndexMap::default(),
            runtime_policy: RuntimePolicy::new(mode),
            edge_count: 0,
            csr_cache: std::sync::Arc::default(),
            edge_pair_index: EdgePairIndex::default(),
        }
    }

    #[must_use]
    pub fn with_runtime_policy(runtime_policy: RuntimePolicy) -> Self {
        let mode = runtime_policy.mode();
        Self {
            mode,
            revision: 0,
            nodes: crate::FxIndexMap::default(),
            successors: crate::FxIndexMap::default(),
            predecessors: crate::FxIndexMap::default(),
            edges: crate::FxIndexMap::default(),
            runtime_policy,
            edge_count: 0,
            csr_cache: std::sync::Arc::default(),
            edge_pair_index: EdgePairIndex::default(),
        }
    }

    #[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.nodes.len()
    }

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

    #[must_use]
    pub fn number_of_selfloops(&self) -> usize {
        self.edges
            .iter()
            .filter(|(edge_key, _)| edge_key.source == edge_key.target)
            .map(|(_, edge_bucket)| edge_bucket.len())
            .sum()
    }

    /// Return an iterator over keys for edges from source to target.
    /// Edge keys as Vec.
    #[must_use]
    pub fn edge_keys(&self, source: &str, target: &str) -> Option<Vec<usize>> {
        self.successors
            .get(source)?
            .get(target)
            .map(|keys| keys.iter().copied().collect())
    }

    /// Edge keys as iterator.
    pub fn edge_keys_iter(
        &self,
        source: &str,
        target: &str,
    ) -> Option<impl Iterator<Item = &usize>> {
        self.successors
            .get(source)?
            .get(target)
            .map(|keys| keys.iter())
    }

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

    /// Revision-keyed integer CSR of distinct successor and predecessor rows.
    /// Row order follows the existing map-backed rows exactly, so consumers can
    /// replace string-key walks without changing observable traversal order.
    #[must_use]
    pub fn csr(&self) -> std::sync::Arc<MultiDiCsr> {
        if let Ok(guard) = self.csr_cache.read()
            && let Some((rev, csr)) = guard.as_ref()
            && *rev == self.revision
        {
            return csr.clone();
        }
        let built = std::sync::Arc::new(self.build_csr());
        if let Ok(mut guard) = self.csr_cache.write() {
            *guard = Some((self.revision, built.clone()));
        }
        built
    }

    fn build_csr(&self) -> MultiDiCsr {
        let n = self.nodes.len();
        let distinct_succ_edges: usize = self.successors.values().map(IndexMap::len).sum();
        let distinct_pred_edges: usize = self.predecessors.values().map(IndexMap::len).sum();
        let mut succ_offsets = Vec::with_capacity(n + 1);
        let mut pred_offsets = Vec::with_capacity(n + 1);
        let mut succ_targets = Vec::with_capacity(distinct_succ_edges);
        let mut pred_targets = Vec::with_capacity(distinct_pred_edges);
        succ_offsets.push(0);
        pred_offsets.push(0);
        for node in self.nodes.keys() {
            if let Some(row) = self.successors.get(node.as_str()) {
                succ_targets.extend(row.keys().filter_map(|target| {
                    self.nodes
                        .get_index_of(target.as_str())
                        .map(|idx| u32::try_from(idx).unwrap_or(u32::MAX))
                }));
            }
            succ_offsets.push(succ_targets.len());

            if let Some(row) = self.predecessors.get(node.as_str()) {
                pred_targets.extend(row.keys().filter_map(|source| {
                    self.nodes
                        .get_index_of(source.as_str())
                        .map(|idx| u32::try_from(idx).unwrap_or(u32::MAX))
                }));
            }
            pred_offsets.push(pred_targets.len());
        }
        MultiDiCsr {
            succ_offsets,
            succ_targets,
            pred_offsets,
            pred_targets,
        }
    }

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

    #[must_use]
    pub fn has_edge(&self, source: &str, target: &str) -> bool {
        self.edges
            .get(&DirectedEdgeKeyRef::new(source, target))
            .is_some_and(|edge_bucket| !edge_bucket.is_empty())
    }

    /// br-r37-c1-04z53 (cc): directed `has_edge` straight from insertion-order
    /// indices (source-major), skipping the `i.to_string()` heap alloc for int
    /// nodes. Names come from the node table by index (borrowed); the caller
    /// guards each index with `node_index_matches_int`. Mirror of
    /// `Graph::has_edge_by_indices`.
    /// br-r37-c1-s8dj1: O(E) rebuild of the pair lookaside. Paid on the first
    /// probe, and again after any mutation that did not patch it.
    fn build_edge_pair_index(&self) -> EdgePairMap {
        let mut built =
            EdgePairMap::with_capacity_and_hasher(self.edges.len(), rustc_hash::FxBuildHasher);
        for (position, edge_key) in self.edges.keys().enumerate() {
            if let Some(source_idx) = self.nodes.get_index_of(edge_key.source.as_str())
                && let Some(target_idx) = self.nodes.get_index_of(edge_key.target.as_str())
            {
                built.insert((source_idx, target_idx), position);
            }
        }
        built
    }

    /// br-r37-c1-s8dj1: position of the (source, target) bucket in `edges`,
    /// addressed by node POSITION and never by name.
    /// TRI-STATE: `None` means "no index available, use the name path" -- which
    /// is what the warm-up guard returns until a caller has proved it will probe
    /// enough to amortise the build. `Some(inner)` is an authoritative answer,
    /// `inner` being the bucket position or `None` for absent.
    fn edge_pair_position(&self, source_idx: usize, target_idx: usize) -> Option<Option<usize>> {
        use std::sync::atomic::Ordering;
        if let Ok(guard) = self.edge_pair_index.map.read()
            && let Some((stamp, map)) = guard.as_ref()
            && *stamp == self.revision
        {
            return Some(map.get(&(source_idx, target_idx)).copied());
        }
        let revision = self.revision;
        if self.edge_pair_index.probed_revision.load(Ordering::Relaxed) != revision {
            self.edge_pair_index
                .probed_revision
                .store(revision, Ordering::Relaxed);
            self.edge_pair_index
                .probes_since_build
                .store(1, Ordering::Relaxed);
            return None;
        }
        let seen = self
            .edge_pair_index
            .probes_since_build
            .fetch_add(1, Ordering::Relaxed)
            + 1;
        if seen < pair_index_warmup(self.edges.len()) {
            return None;
        }
        let built = self.build_edge_pair_index();
        let found = built.get(&(source_idx, target_idx)).copied();
        if let Ok(mut guard) = self.edge_pair_index.map.write() {
            *guard = Some((revision, built));
        }
        Some(found)
    }

    /// br-r37-c1-s8dj1: patch the lookaside through an edge ADD rather than
    /// letting the stamp drop it, which is what made the rebuild version a loss
    /// on add-then-check loops.
    ///
    /// Sound because an add MOVES NOTHING: `IndexMap::insert` appends, so a new
    /// pair takes the last position and every existing position stands, and a
    /// node added by this same call appends to `nodes` so every existing node
    /// position stands too.
    ///
    /// Costs nothing on a graph nobody has probed: the liveness check comes
    /// first, and a cold cache returns before any node-key hash is paid.
    fn pair_index_note_edge_added(
        &mut self,
        previous_revision: u64,
        source: &str,
        target: &str,
        new_pair_position: Option<usize>,
    ) {
        match self.edge_pair_index.map.get_mut() {
            Ok(Some((stamp, _))) if *stamp == previous_revision => {}
            _ => return,
        }
        let resolved = match new_pair_position {
            Some(position) => match (
                self.nodes.get_index_of(source),
                self.nodes.get_index_of(target),
            ) {
                (Some(source_idx), Some(target_idx)) => Some(((source_idx, target_idx), position)),
                // Cannot describe the new edge: drop rather than half-patch.
                _ => {
                    if let Ok(slot) = self.edge_pair_index.map.get_mut() {
                        *slot = None;
                    }
                    return;
                }
            },
            None => None,
        };
        let current = self.revision;
        if let Ok(Some((stamp, map))) = self.edge_pair_index.map.get_mut() {
            if let Some((pair, position)) = resolved {
                map.insert(pair, position);
            }
            *stamp = current;
        }
    }

    /// br-r37-c1-s8dj1: is the pair index worth maintaining right now? A graph
    /// nobody has probed carries no map, and must pay nothing for one.
    fn edge_pair_index_is_live(&self, at_revision: u64) -> bool {
        matches!(
            self.edge_pair_index.map.read().as_deref(),
            Ok(Some((stamp, _))) if *stamp == at_revision
        )
    }

    /// br-r37-c1-s8dj1: patch the lookaside through an edge REMOVAL.
    ///
    /// `remove_edge` SWAP-removes the bucket when its last key goes, which moves
    /// exactly ONE entry: whatever sat last now sits in the freed slot. That is a
    /// bounded repair, unlike `remove_node`, which shift-removes from `nodes` and
    /// renumbers every later node — that one still drops the map and rebuilds,
    /// which is proportionate because the removal itself is already O(V+E).
    ///
    /// `dropped_position` is `None` when the bucket survived (a parallel key went
    /// but the pair remains), in which case nothing moved and only the stamp
    /// needs carrying forward.
    fn pair_index_note_edge_removed(
        &mut self,
        previous_revision: u64,
        source: &str,
        target: &str,
        dropped_position: Option<usize>,
    ) {
        match self.edge_pair_index.map.get_mut() {
            Ok(Some((stamp, _))) if *stamp == previous_revision => {}
            _ => return,
        }
        let removed_pair = match dropped_position {
            Some(_) => match (
                self.nodes.get_index_of(source),
                self.nodes.get_index_of(target),
            ) {
                (Some(source_idx), Some(target_idx)) => Some((source_idx, target_idx)),
                _ => {
                    if let Ok(slot) = self.edge_pair_index.map.get_mut() {
                        *slot = None;
                    }
                    return;
                }
            },
            None => None,
        };
        // The entry that swap_remove relocated into the freed slot, if any.
        let relocated = match dropped_position {
            Some(position) if position < self.edges.len() => match self.edges.get_index(position) {
                Some((moved_key, _)) => {
                    let moved_source = moved_key.source.clone();
                    let moved_target = moved_key.target.clone();
                    match (
                        self.nodes.get_index_of(moved_source.as_str()),
                        self.nodes.get_index_of(moved_target.as_str()),
                    ) {
                        (Some(source_idx), Some(target_idx)) => {
                            Some(((source_idx, target_idx), position))
                        }
                        _ => {
                            if let Ok(slot) = self.edge_pair_index.map.get_mut() {
                                *slot = None;
                            }
                            return;
                        }
                    }
                }
                None => None,
            },
            _ => None,
        };
        let current = self.revision;
        if let Ok(Some((stamp, map))) = self.edge_pair_index.map.get_mut() {
            if let Some(pair) = removed_pair {
                map.remove(&pair);
            }
            if let Some((pair, position)) = relocated {
                map.insert(pair, position);
            }
            *stamp = current;
        }
    }

    /// br-r37-c1-s8dj1: now a REAL index path.
    ///
    /// It used to resolve both indices back to names and call `has_edge(&str,
    /// &str)`, which hashes the full-length keys again — so a caller's O(1)
    /// index resolution bought nothing, and `PyMultiDiGraph`'s exact-string
    /// branch (br-r37-c1-ptiz2) inherited the slope it was written to remove.
    ///
    /// An `edges` bucket is dropped as soon as its last key goes (see
    /// `remove_edge`), so membership of the pair map is exactly `has_edge`.
    #[must_use]
    pub fn has_edge_by_indices(&self, source_idx: usize, target_idx: usize) -> bool {
        if let Some(position) = self.edge_pair_position(source_idx, target_idx) {
            return position.is_some();
        }
        match (
            self.get_node_name(source_idx),
            self.get_node_name(target_idx),
        ) {
            (Some(source), Some(target)) => self.has_edge(source, target),
            _ => false,
        }
    }

    /// br-r37-c1-s8dj1: how many PARALLEL edges a pair carries, addressed by
    /// node POSITION. `number_of_edges(u, v)` built two owned canonicals and
    /// hashed the pair to answer what is a bucket length, and measured 0.272x
    /// of networkx at 2000-character keys — the worst surviving row on this
    /// class after the keyed `has_edge` path landed.
    ///
    /// Falls back to the name path while the lookaside is still warming up, so
    /// it inherits the same amortisation guard rather than forcing a build.
    #[must_use]
    pub fn edge_key_count_by_indices(&self, source_idx: usize, target_idx: usize) -> usize {
        if let Some(position) = self.edge_pair_position(source_idx, target_idx) {
            return position
                .and_then(|found| self.edges.get_index(found))
                .map_or(0, |(_, keyed)| keyed.len());
        }
        match (
            self.get_node_name(source_idx),
            self.get_node_name(target_idx),
        ) {
            (Some(source), Some(target)) => self
                .edges
                .get(&DirectedEdgeKeyRef::new(source, target))
                .map_or(0, IndexMap::len),
            _ => 0,
        }
    }

    /// br-r37-c1-s8dj1: attributes of a KEYED directed edge, addressed by node
    /// POSITION — the directed twin of `MultiGraph::edge_attrs_by_indices`, and
    /// the primitive whose absence is why `PyMultiDiGraph::has_edge` left its
    /// keyed form on the string path.
    #[must_use]
    pub fn edge_attrs_by_indices(
        &self,
        source_idx: usize,
        target_idx: usize,
        key: usize,
    ) -> Option<&AttrMap> {
        if let Some(position) = self.edge_pair_position(source_idx, target_idx) {
            let (_, keyed) = self.edges.get_index(position?)?;
            return keyed.get(&key);
        }
        let source = self.get_node_name(source_idx)?;
        let target = self.get_node_name(target_idx)?;
        self.edges
            .get(&DirectedEdgeKeyRef::new(source, target))
            .and_then(|bucket| bucket.get(&key))
    }

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

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

    /// br-cc-nbunchbulk: int membership fast path for `_nbunch_present` — see the
    /// DiGraph accessor.
    #[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))
    }

    #[must_use]
    pub fn successors(&self, node: &str) -> Option<Vec<&str>> {
        self.successors
            .get(node)
            .map(|neighbors| neighbors.keys().map(String::as_str).collect::<Vec<&str>>())
    }

    #[must_use]
    pub fn successors_iter(&self, node: &str) -> Option<impl Iterator<Item = &str> + '_> {
        self.successors
            .get(node)
            .map(|neighbors| neighbors.keys().map(String::as_str))
    }

    #[must_use]
    pub fn predecessors(&self, node: &str) -> Option<Vec<&str>> {
        self.predecessors
            .get(node)
            .map(|neighbors| neighbors.keys().map(String::as_str).collect::<Vec<&str>>())
    }

    #[must_use]
    pub fn predecessors_iter(&self, node: &str) -> Option<impl Iterator<Item = &str> + '_> {
        self.predecessors
            .get(node)
            .map(|neighbors| neighbors.keys().map(String::as_str))
    }

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

    #[must_use]
    pub fn neighbors_iter(&self, node: &str) -> Option<impl Iterator<Item = &str> + '_> {
        self.successors_iter(node)
    }

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

    #[must_use]
    pub fn edge_attrs(&self, source: &str, target: &str, key: usize) -> Option<&AttrMap> {
        self.edges
            .get(&DirectedEdgeKeyRef::new(source, target))
            .and_then(|edge_bucket| edge_bucket.get(&key))
    }

    #[must_use]
    pub fn edge_attr_values(
        &self,
        source: &str,
        target: &str,
    ) -> Option<impl Iterator<Item = &AttrMap> + '_> {
        self.edges
            .get(&DirectedEdgeKeyRef::new(source, target))
            .map(|edge_bucket| edge_bucket.values())
    }

    #[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 {
        true
    }

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

    /// Return the out-degree of a node (number of outgoing parallel edges).
    #[must_use]
    pub fn out_degree(&self, node: &str) -> usize {
        self.successors
            .get(node)
            .map_or(0, |succs| succs.values().map(IndexSet::len).sum())
    }

    /// Return the in-degree of a node (number of incoming parallel edges).
    #[must_use]
    pub fn in_degree(&self, node: &str) -> usize {
        self.predecessors
            .get(node)
            .map_or(0, |preds| preds.values().map(IndexSet::len).sum())
    }

    /// Return the degree of a node (in-degree + out-degree).
    #[must_use]
    pub fn degree(&self, node: &str) -> usize {
        self.in_degree(node) + self.out_degree(node)
    }

    /// br-r37-c1-mgisol (cc): native isolate detection for MultiDiGraph. A node
    /// is isolated iff it has no incident edges in either direction (empty/absent
    /// successor AND predecessor rows). A self-loop records the node in both its
    /// own successor and predecessor rows, keeping it non-isolated (matches nx's
    /// degree-2 self-loop convention). Yields nodes in insertion order, identical
    /// to the old `multidigraph_to_simple_digraph` projection path but without the
    /// per-call O(V+E) simple-graph rebuild.
    #[must_use]
    pub fn isolates(&self) -> Vec<String> {
        self.nodes
            .keys()
            .filter(|node| self.is_isolate(node.as_str()))
            .cloned()
            .collect()
    }

    /// br-r37-c1-mgisol (cc): isolate count without the simple-digraph projection.
    #[must_use]
    pub fn number_of_isolates(&self) -> usize {
        self.nodes
            .keys()
            .filter(|node| self.is_isolate(node.as_str()))
            .count()
    }

    /// br-r37-c1-mgisol (cc): O(1) isolate predicate. Absent node -> false
    /// (mirrors `is_isolate_directed(&DiGraph)`); the binding validates presence.
    #[must_use]
    pub fn is_isolate(&self, node: &str) -> bool {
        self.nodes.contains_key(node)
            && self.successors.get(node).is_none_or(IndexMap::is_empty)
            && self.predecessors.get(node).is_none_or(IndexMap::is_empty)
    }

    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: the storage half of [`Self::add_node_with_attrs`],
    /// without its ledger record. See the undirected `Graph` sibling.
    ///
    /// br-r37-c1-jc9e4: this key used to be materialised THREE times per call —
    /// `node.into()` plus a `clone()` for the `nodes` entry and another for the
    /// `successors` entry — because `entry()` allocates its key eagerly whether
    /// or not the slot is vacant. On a node that already exists all three were
    /// built only to be dropped. The allocation census measured this pair at
    /// 4.000 allocations per call against 1.000 for every other graph type,
    /// which is how the outlier was found. Each map is now probed borrowed and
    /// the key owned only where a slot is genuinely created.
    ///
    /// The `successors` / `predecessors` rows are still created unconditionally
    /// when missing rather than being skipped whenever the node exists: nothing
    /// here may assume that every path which inserts into `nodes` also created
    /// those rows, and `contains_key` + `insert`-when-absent is exactly what
    /// `entry(..).or_default()` did, including appending at the end when vacant.
    fn add_node_with_attrs_unrecorded(
        &mut self,
        node: impl AsRef<str> + Into<String>,
        attrs: AttrMap,
    ) -> (bool, bool, usize) {
        let existed = self.nodes.contains_key(node.as_ref());
        let mut changed = !existed;
        let attrs_count = {
            let bucket = if existed {
                self.nodes
                    .get_mut(node.as_ref())
                    .expect("contains_key reported this node present")
            } else {
                self.nodes.entry(node.as_ref().to_owned()).or_default()
            };
            if !attrs.is_empty()
                && attrs
                    .iter()
                    .any(|(key, value)| bucket.get(key) != Some(value))
            {
                changed = true;
            }
            bucket.extend(attrs);
            bucket.len()
        };
        if !self.successors.contains_key(node.as_ref()) {
            self.successors
                .insert(node.as_ref().to_owned(), IndexMap::default());
        }
        if !self.predecessors.contains_key(node.as_ref()) {
            self.predecessors.insert(node.into(), IndexMap::default());
        }
        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> + 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
    }

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

    /// br-r37-c1-l5ve7: bulk node insert WITH attrs, one ledger record —
    /// MultiDiGraph mirror of DiGraph::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 {
            if let Some(existing) = self.nodes.get_mut(&node) {
                existing.extend(attrs);
                continue;
            }
            self.nodes.insert(node.clone(), attrs);
            self.successors.entry(node.clone()).or_default();
            self.predecessors.entry(node).or_default();
            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 — for native copy/convert paths that replicate a source
    /// multigraph's exact internal keys (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 (source, target, key, attrs) in edges {
            if !self.nodes.contains_key(&source) {
                self.nodes.insert(source.clone(), AttrMap::new());
                self.successors.entry(source.clone()).or_default();
                self.predecessors.entry(source.clone()).or_default();
            }
            if source != target && !self.nodes.contains_key(&target) {
                self.nodes.insert(target.clone(), AttrMap::new());
                self.successors.entry(target.clone()).or_default();
                self.predecessors.entry(target.clone()).or_default();
            }
            let edge_key = DirectedEdgeKey::new(&source, &target);
            let bucket = self.edges.entry(edge_key).or_default();
            if !bucket.contains_key(&key) {
                self.edge_count += 1;
                inserted += 1;
            }
            bucket.entry(key).or_default().extend(attrs);
            self.successors
                .entry(source.clone())
                .or_default()
                .entry(target.clone())
                .or_default()
                .insert(key);
            self.predecessors
                .entry(target)
                .or_default()
                .entry(source)
                .or_default()
                .insert(key);
        }
        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-add keyed attributed directed multiedges into a fresh graph when the
    /// caller has already assigned NetworkX-compatible node indices and per-pair
    /// keys. This avoids hashing/copying canonical endpoint strings for every
    /// edge in fresh `MultiDiGraph.add_edges_from` batches.
    #[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.nodes.is_empty()
            || !self.successors.is_empty()
            || !self.predecessors.is_empty()
            || !self.edges.is_empty()
        {
            return 0;
        }

        let node_labels: Vec<String> = nodes.into_iter().collect();
        for node in &node_labels {
            self.nodes.insert(node.clone(), AttrMap::new());
            self.successors
                .insert(node.clone(), crate::FxIndexMap::default());
            self.predecessors
                .insert(node.clone(), crate::FxIndexMap::default());
        }

        let node_count = node_labels.len();
        let mut inserted = 0usize;
        let mut merged_changed = false;
        for (source_idx, target_idx, key, attrs) in edges {
            let Some(source) = node_labels.get(source_idx) else {
                continue;
            };
            let Some(target) = node_labels.get(target_idx) else {
                continue;
            };
            let edge_key = DirectedEdgeKey::new(source, target);
            let bucket = self.edges.entry(edge_key).or_default();
            if !bucket.contains_key(&key) {
                self.edge_count += 1;
                inserted += 1;
            }
            let edge_attrs = bucket.entry(key).or_default();
            if !attrs.is_empty()
                && attrs
                    .iter()
                    .any(|(attr_key, value)| edge_attrs.get(attr_key) != Some(value))
            {
                merged_changed = true;
            }
            edge_attrs.extend(attrs);
            self.successors
                .get_mut(source.as_str())
                .expect("fresh node row exists")
                .entry(target.clone())
                .or_default()
                .insert(key);
            self.predecessors
                .get_mut(target.as_str())
                .expect("fresh node row exists")
                .entry(source.clone())
                .or_default()
                .insert(key);
        }

        if node_count > 0 || inserted > 0 || merged_changed {
            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,
                    },
                ],
            );
        }

        inserted
    }

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

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

    fn add_edge_impl(
        &mut self,
        source: impl Into<String>,
        target: impl Into<String>,
        explicit_key: Option<usize>,
        attrs: AttrMap,
    ) -> Result<usize, GraphError> {
        let source = source.into();
        let target = target.into();
        // br-r37-c1-s8dj1: the revision AT ENTRY, before the node inserts below.
        // Those call `add_node_with_attrs_unrecorded`, which bumps the revision
        // too -- capturing after them left the pair index stale-looking and the
        // patch never fired, so every add still forced an O(E) rebuild.
        // Everything this function does to either index space is an APPEND, so a
        // map valid at entry is still valid to patch here.
        let previous_revision = self.revision;

        let unknown_feature = attrs
            .keys()
            .any(|key| key.starts_with("__fnx_incompatible"));
        let self_loop = source == target;
        let incompatibility_probability = if unknown_feature {
            1.0
        } else if self_loop {
            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 source_autocreated = false;
        if !self.nodes.contains_key(&source) {
            let _ = self.add_node_with_attrs_unrecorded(source.clone(), AttrMap::new());
            source_autocreated = true;
        }
        let mut target_autocreated = false;
        if self_loop {
            target_autocreated = source_autocreated;
        } else if !self.nodes.contains_key(&target) {
            let _ = self.add_node_with_attrs_unrecorded(target.clone(), AttrMap::new());
            target_autocreated = true;
        }

        let edge_key = DirectedEdgeKey::new(&source, &target);
        let key = explicit_key.unwrap_or_else(|| {
            let edge_bucket = self.edges.get(&edge_key);
            let mut k = edge_bucket.map_or(0, |b| b.len());
            if let Some(b) = edge_bucket {
                while b.contains_key(&k) {
                    k += 1;
                }
            }
            k
        });
        // br-r37-c1-s8dj1: captured BEFORE the insert, so the pair-index patch
        // below can tell a new bucket from an added parallel key without paying
        // a second hash of the pair.
        let edges_len_before = self.edges.len();
        let mut changed;
        let edge_attr_count = {
            let edge_bucket = self.edges.entry(edge_key.clone()).or_default();
            let is_new = !edge_bucket.contains_key(&key);
            if is_new {
                self.edge_count += 1;
            }
            changed = is_new;
            let edge_attrs = edge_bucket.entry(key).or_default();
            if edge_attrs.is_empty() {
                // br-r37-c1-jc9e4: a fresh keyed bucket TAKES the caller's map
                // whole. Same lever and same byte-identity argument as the
                // `Graph` sibling; `attrs` here is the function's own owned
                // parameter, so the move is unambiguous.
                if !attrs.is_empty() {
                    changed = true;
                }
                *edge_attrs = attrs;
            } else {
                if !attrs.is_empty()
                    && attrs
                        .iter()
                        .any(|(attr_key, value)| edge_attrs.get(attr_key) != Some(value))
                {
                    changed = true;
                }
                edge_attrs.extend(attrs);
            }
            edge_bucket.len()
        };

        self.successors
            .entry(source.clone())
            .or_default()
            .entry(target.clone())
            .or_default()
            .insert(key);
        self.predecessors
            .entry(target.clone())
            .or_default()
            .entry(source.clone())
            .or_default()
            .insert(key);
        if changed {
            self.revision = self.revision.saturating_add(1);
        }
        // br-r37-c1-s8dj1: `insert` APPENDS, so a bucket created by this call
        // sits at the LAST position and no existing position moved.
        let new_pair_position = if self.edges.len() > edges_len_before {
            Some(self.edges.len() - 1)
        } else {
            None
        };
        self.pair_index_note_edge_added(previous_revision, &source, &target, new_pair_position);

        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: "source_autocreated".into(),
                    observed_value: bool_evidence(source_autocreated),
                    log_likelihood_ratio: -1.25,
                },
                EvidenceTerm {
                    signal: "target_autocreated".into(),
                    observed_value: bool_evidence(target_autocreated),
                    log_likelihood_ratio: -1.25,
                },
            ],
        );

        Ok(key)
    }

    /// br-r37-c1-sjf4t: overwrite the attribute map for an existing
    /// (source, target, key) edge. Returns whether the edge existed.
    pub fn replace_edge_attrs(
        &mut self,
        source: &str,
        target: &str,
        key: usize,
        attrs: AttrMap,
    ) -> bool {
        let edge_key = DirectedEdgeKey::new(source, target);
        if let Some(bucket) = self.edges.get_mut(&edge_key)
            && let Some(slot) = bucket.get_mut(&key)
        {
            if *slot != attrs {
                *slot = attrs;
                self.revision = self.revision.saturating_add(1);
            }
            return true;
        }
        false
    }

    /// Overwrite one attribute value on an existing keyed edge. This is the
    /// hot path for algorithms that clone graph topology and patch one derived
    /// edge field without rebuilding every edge's full attribute map.
    pub fn set_edge_attr_value(
        &mut self,
        source: &str,
        target: &str,
        key: usize,
        attr_key: &str,
        value: CgseValue,
    ) -> bool {
        let edge_key = DirectedEdgeKey::new(source, target);
        if let Some(bucket) = self.edges.get_mut(&edge_key)
            && let Some(attrs) = bucket.get_mut(&key)
        {
            if attrs.get(attr_key) != Some(&value) {
                attrs.insert(attr_key.to_owned(), value);
                self.revision = self.revision.saturating_add(1);
            }
            return true;
        }
        false
    }

    /// Overwrite one attribute on all keyed edges in `edges_ordered_borrowed`
    /// order. Returns false if the caller supplied the wrong value count.
    pub fn set_ordered_edge_attr_values<I>(&mut self, attr_key: &str, values: I) -> bool
    where
        I: IntoIterator<Item = CgseValue>,
    {
        let mut values = values.into_iter();
        let mut changed = false;
        let mut visited = 0usize;

        for node in self.nodes.keys() {
            if let Some(neighbors) = self.successors.get(node) {
                for target in neighbors.keys() {
                    let pair = DirectedEdgeKeyRef::new(node, target);
                    if let Some(edge_bucket) = self.edges.get_mut(&pair) {
                        for attrs in edge_bucket.values_mut() {
                            let Some(value) = values.next() else {
                                return false;
                            };
                            if attrs.get(attr_key) != Some(&value) {
                                attrs.insert(attr_key.to_owned(), value);
                                changed = true;
                            }
                            visited = visited.saturating_add(1);
                        }
                    }
                }
            }
        }

        if values.next().is_some() || visited != self.edge_count {
            return false;
        }
        if changed {
            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 {
        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, source: &str, target: &str, key: Option<usize>) -> bool {
        // br-r37-c1-s8dj1: revision at entry, for the pair-index patch below.
        let previous_revision = self.revision;
        let edge_key = DirectedEdgeKeyRef::new(source, target);
        let removal_key = key.or_else(|| {
            self.edges
                .get(&edge_key)
                .and_then(|edge_bucket| edge_bucket.keys().next_back().copied())
        });

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

        let removed = self
            .edges
            .get_mut(&edge_key)
            .is_some_and(|edge_bucket| edge_bucket.shift_remove(&removal_key).is_some());
        if !removed {
            return false;
        }

        self.edge_count -= 1;

        let should_drop_bucket = self.edges.get(&edge_key).is_some_and(IndexMap::is_empty);
        // br-r37-c1-s8dj1: the position the bucket occupies BEFORE swap_remove
        // frees it. Resolved only when a live pair index will actually use it.
        let dropped_position =
            if should_drop_bucket && self.edge_pair_index_is_live(previous_revision) {
                self.edges.get_index_of(&edge_key)
            } else {
                None
            };
        if should_drop_bucket {
            // br-r37-c1-vbwpl (cc): swap_remove (O(1)) on the OUTER node-pair map
            // — its storage order is never observed (edges_ordered walks
            // successors and looks pairs up by key; remove_node already
            // swap_removes this same map). The inner bucket above keeps
            // shift_remove because per-pair key order IS observed. Turns
            // remove_edges_from from O(k*pairs) into O(k).
            self.edges.swap_remove(&edge_key);
        }

        self.remove_successor_key(source, target, removal_key);
        self.remove_predecessor_key(target, source, removal_key);
        self.revision = self.revision.saturating_add(1);
        self.pair_index_note_edge_removed(previous_revision, source, target, dropped_position);
        true
    }

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

        self.edges.clear();
        for row in self.successors.values_mut() {
            row.clear();
        }
        for row in self.predecessors.values_mut() {
            row.clear();
        }
        self.edge_count = 0;
        self.revision = self.revision.saturating_add(1);
    }

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

        // br-r37-c1-p6bxu: drop each incident edge bucket with O(1) `swap_remove`
        // (the `edges` IndexMap order is never observed externally — every public
        // consumer reads via `edges_ordered`, which walks node->successor order;
        // no internal consumer iterates the map order). Out-edges are known from
        // `successors`, in-edges from `predecessors`; a self-loop's (node,node)
        // bucket appears in both but `swap_remove` returns it only once, so it is
        // counted exactly once. Removal is O(degree) instead of the
        // O(|distinct pairs|) `retain` scan — matching nx.
        let mut removed_count = 0usize;
        if let Some(succs) = self.successors.get(node) {
            let targets: Vec<String> = succs.keys().cloned().collect();
            for target in targets {
                if target != node
                    && let Some(preds) = self.predecessors.get_mut(&target)
                {
                    preds.shift_remove(node);
                }
                if let Some(bucket) = self
                    .edges
                    .swap_remove(&DirectedEdgeKeyRef::new(node, &target))
                {
                    removed_count += bucket.len();
                }
            }
        }
        if let Some(preds) = self.predecessors.get(node) {
            let sources: Vec<String> = preds.keys().cloned().collect();
            for source in sources {
                if source != node
                    && let Some(succs) = self.successors.get_mut(&source)
                {
                    succs.shift_remove(node);
                }
                if let Some(bucket) = self
                    .edges
                    .swap_remove(&DirectedEdgeKeyRef::new(&source, node))
                {
                    removed_count += bucket.len();
                }
            }
        }
        self.edge_count -= removed_count;

        self.successors.shift_remove(node);
        self.predecessors.shift_remove(node);
        self.nodes.shift_remove(node);
        self.revision = self.revision.saturating_add(1);
        true
    }

    /// br-r37-c1-mgrnf: batch node removal — amortised analogue of `remove_node`.
    /// `MultiDiGraph::remove_node` pays THREE O(|V|) `shift_remove`s (successors,
    /// predecessors, nodes) per call, 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 `DiGraph::remove_nodes_from` batch. Returns
    /// `(removed_node_count, removed_edge_instance_count)`. The `revision` bump
    /// invalidates `csr_cache` exactly as repeated `remove_node` would.
    pub fn remove_nodes_from<'a, I>(&mut self, nodes: I) -> (usize, usize)
    where
        I: IntoIterator<Item = &'a str>,
    {
        let remove_set: rustc_hash::FxHashSet<&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.edge_count;

        // br-r37-c1-mgrnf-incident: SMALL-fraction fast path — walk only the removed
        // nodes' out/in adjacency (like `remove_node`), pruning the removed node from
        // each surviving neighbour's opposite row and dropping incident edge buckets
        // O(1), then compact the three outer maps ONCE. O(|V| + sum_removed_degrees)
        // vs the whole-graph O(|V|+|E|) retain (removing 10 nodes from a 2000/10000
        // graph was ~100x nx). Large removals fall through (repeated hub shift_remove).
        let mut removed_instances = 0usize;
        if remove_set.len().saturating_mul(4) <= old_node_count {
            for &rn in &remove_set {
                // Out-edges: rn -> target. Drop rn from a surviving target's preds.
                let targets: Vec<String> = match self.successors.get(rn) {
                    Some(row) => row.keys().cloned().collect(),
                    None => Vec::new(),
                };
                for t in &targets {
                    if t.as_str() != rn
                        && !remove_set.contains(t.as_str())
                        && let Some(preds) = self.predecessors.get_mut(t)
                    {
                        preds.shift_remove(rn);
                    }
                    if let Some(bucket) = self.edges.swap_remove(&DirectedEdgeKeyRef::new(rn, t)) {
                        removed_instances += bucket.len();
                    }
                }
                // In-edges: source -> rn. Drop rn from a surviving source's succs.
                let sources: Vec<String> = match self.predecessors.get(rn) {
                    Some(row) => row.keys().cloned().collect(),
                    None => Vec::new(),
                };
                for s in &sources {
                    if s.as_str() != rn
                        && !remove_set.contains(s.as_str())
                        && let Some(succs) = self.successors.get_mut(s)
                    {
                        succs.shift_remove(rn);
                    }
                    // Self-loop (rn,rn) already dropped in the out-edges pass, so
                    // swap_remove returns None here — no double count.
                    if let Some(bucket) = self.edges.swap_remove(&DirectedEdgeKeyRef::new(s, rn)) {
                        removed_instances += bucket.len();
                    }
                }
            }
            self.edge_count -= removed_instances;
            self.successors
                .retain(|node, _| !remove_set.contains(node.as_str()));
            self.predecessors
                .retain(|node, _| !remove_set.contains(node.as_str()));
            self.nodes
                .retain(|node, _| !remove_set.contains(node.as_str()));
            let removed_nodes = old_node_count - self.nodes.len();
            let removed_edges = old_edge_count - self.edge_count;
            self.revision = self
                .revision
                .saturating_add(u64::try_from(removed_nodes).unwrap_or(u64::MAX));
            return (removed_nodes, removed_edges);
        }

        // Drop every edge bucket incident to a removed node (source OR target) in
        // one pass, tallying parallel-edge instances so `edge_count` stays exact.
        // `edges` map order is unobserved externally (consumers walk `edges_ordered`
        // = successor order), so `retain` is order-safe — same rationale as
        // `remove_node`.
        self.edges.retain(|key, bucket| {
            let keep = !remove_set.contains(key.source.as_str())
                && !remove_set.contains(key.target.as_str());
            if !keep {
                removed_instances += bucket.len();
            }
            keep
        });
        self.edge_count -= removed_instances;

        // successors + predecessors: drop the removed nodes' own rows, then prune
        // references to removed nodes from every surviving row. Order-preserving
        // `retain`, so byte-identical to repeated `remove_node`.
        self.successors
            .retain(|node, _| !remove_set.contains(node.as_str()));
        for row in self.successors.values_mut() {
            row.retain(|target, _| !remove_set.contains(target.as_str()));
        }
        self.predecessors
            .retain(|node, _| !remove_set.contains(node.as_str()));
        for row in self.predecessors.values_mut() {
            row.retain(|source, _| !remove_set.contains(source.as_str()));
        }
        self.nodes
            .retain(|node, _| !remove_set.contains(node.as_str()));

        let removed_nodes = old_node_count - self.nodes.len();
        let removed_edges = old_edge_count - self.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<MultiDiEdgeSnapshot> {
        let mut ordered = Vec::with_capacity(self.edge_count());

        for node in self.nodes.keys() {
            if let Some(neighbors) = self.successors.get(node) {
                for target in neighbors.keys() {
                    let pair = DirectedEdgeKey::new(node, target);
                    if let Some(edge_bucket) = self.edges.get(&pair) {
                        for (key, attrs) in edge_bucket {
                            ordered.push(MultiDiEdgeSnapshot {
                                source: node.clone(),
                                target: target.clone(),
                                key: *key,
                                attrs: attrs.clone(),
                            });
                        }
                    }
                }
            }
        }

        ordered
    }

    #[must_use]
    pub fn edges_ordered_borrowed(&self) -> Vec<(&str, &str, usize, &AttrMap)> {
        let mut ordered = Vec::with_capacity(self.edge_count());

        for node in self.nodes.keys() {
            if let Some(neighbors) = self.successors.get(node) {
                for target in neighbors.keys() {
                    let pair = DirectedEdgeKeyRef::new(node, target);
                    if let Some(edge_bucket) = self.edges.get(&pair) {
                        for (key, attrs) in edge_bucket {
                            ordered.push((node.as_str(), target.as_str(), *key, attrs));
                        }
                    }
                }
            }
        }

        ordered
    }

    /// br-r37-c1-wsize (cc): integer `size(weight)` from the store — directed
    /// multigraph twin of `Graph::weighted_size_int`. Each parallel directed edge
    /// is one bucket entry contributing its weight once (size halves degree's
    /// in+out double count). Returns `None` on any non-integer weight (caller uses
    /// the exact degree path); missing weight defaults to nx's int `1`.
    #[must_use]
    pub fn weighted_size_int(&self, weight: &str) -> Option<i128> {
        let mut total: i128 = 0;
        for bucket in self.edges.values() {
            for attrs in bucket.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)
    }

    pub fn try_for_each_edge_ordered_borrowed<E>(
        &self,
        mut visit: impl FnMut(&str, &str, usize, &AttrMap) -> Result<(), E>,
    ) -> Result<(), E> {
        for node in self.nodes.keys() {
            if let Some(neighbors) = self.successors.get(node) {
                for target in neighbors.keys() {
                    let pair = DirectedEdgeKeyRef::new(node, target);
                    if let Some(edge_bucket) = self.edges.get(&pair) {
                        for (key, attrs) in edge_bucket {
                            visit(node.as_str(), target.as_str(), *key, attrs)?;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    pub fn try_for_each_indexed_edge_ordered_borrowed<E>(
        &self,
        mut visit: impl FnMut(usize, usize, &str, &str, usize, &AttrMap) -> Result<(), E>,
    ) -> Result<(), E> {
        for (source_index, node) in self.nodes.keys().enumerate() {
            if let Some(neighbors) = self.successors.get(node) {
                for target in neighbors.keys() {
                    let Some(target_index) = self.nodes.get_index_of(target.as_str()) else {
                        continue;
                    };
                    let pair = DirectedEdgeKeyRef::new(node, target);
                    if let Some(edge_bucket) = self.edges.get(&pair) {
                        for (key, attrs) in edge_bucket {
                            visit(
                                source_index,
                                target_index,
                                node.as_str(),
                                target.as_str(),
                                *key,
                                attrs,
                            )?;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Return a reversed copy with NetworkX-compatible node/edge row order.
    ///
    /// This is the directed-multigraph sibling of `DiGraph::reversed`, but it
    /// cannot simply swap `successors` and `predecessors`: NetworkX materializes
    /// `MultiDiGraph.reverse(copy=True)` by walking `G.edges(keys=True, data=True)`
    /// in source-node order and adding `(v, u, key)` to the result. Predecessor
    /// rows may have been formed by historical edge insertion order, which is not
    /// always the same as that source-major edge stream. Rebuild the two row maps
    /// from the observed edge stream while avoiding the expensive per-edge
    /// `add_edge` policy path.
    #[must_use]
    pub fn reversed(&self) -> Self {
        let mut successors: crate::FxIndexMap<
            String,
            crate::FxIndexMap<String, crate::FxIndexSet<usize>>,
        > = crate::FxIndexMap::with_capacity_and_hasher(
            self.nodes.len(),
            rustc_hash::FxBuildHasher,
        );
        let mut predecessors: crate::FxIndexMap<
            String,
            crate::FxIndexMap<String, crate::FxIndexSet<usize>>,
        > = crate::FxIndexMap::with_capacity_and_hasher(
            self.nodes.len(),
            rustc_hash::FxBuildHasher,
        );
        for node in self.nodes.keys() {
            successors.insert(node.clone(), crate::FxIndexMap::default());
            predecessors.insert(node.clone(), crate::FxIndexMap::default());
        }

        let mut edges: crate::FxIndexMap<DirectedEdgeKey, IndexMap<usize, AttrMap>> =
            crate::FxIndexMap::with_capacity_and_hasher(
                self.edges.len(),
                rustc_hash::FxBuildHasher,
            );
        let mut edge_count = 0usize;
        for source in self.nodes.keys() {
            let Some(neighbors) = self.successors.get(source) else {
                continue;
            };
            for target in neighbors.keys() {
                let pair = DirectedEdgeKeyRef::new(source, target);
                let Some(edge_bucket) = self.edges.get(&pair) else {
                    continue;
                };
                let reversed_pair = DirectedEdgeKey::new(target, source);
                let reversed_bucket = edges.entry(reversed_pair).or_default();
                let reversed_succ_keys = successors
                    .get_mut(target.as_str())
                    .expect("target row exists")
                    .entry(source.clone())
                    .or_default();
                let reversed_pred_keys = predecessors
                    .get_mut(source.as_str())
                    .expect("source row exists")
                    .entry(target.clone())
                    .or_default();
                for (key, attrs) in edge_bucket {
                    reversed_bucket.insert(*key, attrs.clone());
                    reversed_succ_keys.insert(*key);
                    reversed_pred_keys.insert(*key);
                    edge_count += 1;
                }
            }
        }

        Self {
            mode: self.mode,
            revision: 0,
            nodes: self.nodes.clone(),
            successors,
            predecessors,
            edges,
            runtime_policy: self.runtime_policy.clone(),
            edge_count,
            csr_cache: std::sync::Arc::default(),
            edge_pair_index: EdgePairIndex::default(),
        }
    }

    /// Out-edges of a single source node in nx adjacency order
    /// (successors[node].keys() then key-bucket order), borrowing attrs.
    ///
    /// Equivalent to ``edges_ordered_borrowed()`` filtered to one source,
    /// but O(out-deg(node)) instead of O(E) — and it clones nothing. Used
    /// by ``MultiDiGraph.edges(nbunch)`` to avoid scanning/cloning every
    /// edge when only a handful of sources are requested.
    #[must_use]
    pub fn out_edges_ordered_borrowed<'a>(
        &'a self,
        node: &str,
    ) -> Vec<(&'a str, &'a str, usize, &'a AttrMap)> {
        let mut ordered = Vec::new();
        if let Some((src, neighbors)) = self.successors.get_key_value(node) {
            for target in neighbors.keys() {
                let pair = DirectedEdgeKeyRef::new(src, target);
                if let Some(edge_bucket) = self.edges.get(&pair) {
                    for (key, attrs) in edge_bucket {
                        ordered.push((src.as_str(), target.as_str(), *key, attrs));
                    }
                }
            }
        }
        ordered
    }

    #[must_use]
    pub fn snapshot(&self) -> MultiDiGraphSnapshot {
        let node_attrs: std::collections::BTreeMap<String, AttrMap> = self
            .nodes
            .iter()
            .filter(|(_, attrs)| !attrs.is_empty())
            .map(|(name, attrs)| (name.clone(), attrs.clone()))
            .collect();
        MultiDiGraphSnapshot {
            mode: self.mode,
            nodes: self.nodes.keys().cloned().collect(),
            node_attrs,
            edges: self.edges_ordered(),
        }
    }

    fn remove_successor_key(&mut self, source: &str, target: &str, key: usize) {
        let mut drop_neighbor = false;
        if let Some(neighbors) = self.successors.get_mut(source)
            && let Some(keys) = neighbors.get_mut(target)
        {
            keys.shift_remove(&key);
            drop_neighbor = keys.is_empty();
        }
        if drop_neighbor && let Some(neighbors) = self.successors.get_mut(source) {
            neighbors.shift_remove(target);
        }
    }

    fn remove_predecessor_key(&mut self, target: &str, source: &str, key: usize) {
        let mut drop_neighbor = false;
        if let Some(neighbors) = self.predecessors.get_mut(target)
            && let Some(keys) = neighbors.get_mut(source)
        {
            keys.shift_remove(&key);
            drop_neighbor = keys.is_empty();
        }
        if drop_neighbor && let Some(neighbors) = self.predecessors.get_mut(target) {
            neighbors.shift_remove(source);
        }
    }

    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
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use fnx_runtime::{
        CgseValue, CompatibilityMode, DecisionAction, DecisionRecord, RuntimePolicy,
    };
    use proptest::prelude::*;

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

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

    fn assert_runtime_policy_preserved(source: &RuntimePolicy, result: &RuntimePolicy) {
        assert_eq!(result.mode(), source.mode());
        assert_eq!(result.allowlist(), source.allowlist());
        assert_eq!(result.loss_matrix(), source.loss_matrix());
        assert!(result.posterior().observation_count >= source.posterior().observation_count);
        assert!(
            result
                .decision_log()
                .records()
                .starts_with(source.decision_log().records())
        );
    }

    // -- Invariant checker --------------------------------------------------

    fn assert_digraph_core_invariants(g: &DiGraph) {
        // Every edge in the edge map must be reflected in successors/predecessors.
        for (&(source_idx, target_idx), _attrs) in &g.edges {
            let source = g
                .nodes
                .get_index(source_idx)
                .map(|(name, _)| name.as_str())
                .expect("edge source index should be a node");
            let target = g
                .nodes
                .get_index(target_idx)
                .map(|(name, _)| name.as_str())
                .expect("edge target index should be a node");
            assert!(
                g.has_node(source),
                "edge source {} should be a node",
                source
            );
            assert!(
                g.has_node(target),
                "edge target {} should be a node",
                target
            );
            let succs = g
                .successors(source)
                .expect("source should have successors bucket");
            assert!(
                succs.contains(&target),
                "{} should be in successors of {}",
                target,
                source
            );
            let preds = g
                .predecessors(target)
                .expect("target should have predecessors bucket");
            assert!(
                preds.contains(&source),
                "{} should be in predecessors of {}",
                source,
                target
            );
        }

        // Every successor entry should have a corresponding edge.
        let mut edge_count_from_adj = 0usize;
        for node in g.nodes_ordered() {
            let succs = g
                .successors(node)
                .expect("node should have successors bucket");
            for s in &succs {
                assert!(
                    g.has_edge(node, s),
                    "successor {} of {} should have directed edge",
                    s,
                    node
                );
                edge_count_from_adj += 1;
            }
            // Every predecessor entry should have a corresponding edge.
            let preds = g
                .predecessors(node)
                .expect("node should have predecessors bucket");
            for p in &preds {
                assert!(
                    g.has_edge(p, node),
                    "predecessor {} of {} should have directed edge",
                    p,
                    node
                );
            }
        }
        assert_eq!(g.edge_count(), edge_count_from_adj);
    }

    #[test]
    fn add_node_with_attrs_reports_change_on_existing_node() {
        let mut graph = DiGraph::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 multidigraph_add_node_with_attrs_reports_change_on_existing_node() {
        let mut graph = MultiDiGraph::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));
    }

    fn assert_multidigraph_core_invariants(g: &MultiDiGraph) {
        let mut edge_instances = std::collections::BTreeSet::new();
        for node in g.nodes_ordered() {
            let successors = g
                .successors(node)
                .expect("multidigraph nodes should always have successor buckets");
            for target in successors {
                assert!(g.has_node(target));
                assert!(g.has_edge(node, target));
                let preds = g
                    .predecessors(target)
                    .expect("target should always have predecessor buckets");
                assert!(preds.contains(&node));
                let keys = g
                    .edge_keys(node, target)
                    .expect("parallel directed edge bucket should exist");
                for key in keys {
                    edge_instances.insert((node.to_owned(), target.to_owned(), key));
                }
            }
        }
        assert_eq!(g.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());
        }
    }

    // -- Basic operations ---------------------------------------------------

    #[test]
    fn add_directed_edge_autocreates_nodes() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();

        assert_eq!(g.node_count(), 2);
        assert_eq!(g.edge_count(), 1);
        assert!(g.has_edge("a", "b"));
        assert!(!g.has_edge("b", "a")); // directed: reverse does NOT exist
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn directed_edge_asymmetry() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("b", "a").unwrap();

        assert_eq!(g.edge_count(), 2);
        assert!(g.has_edge("a", "b"));
        assert!(g.has_edge("b", "a"));
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn successors_and_predecessors() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("a", "c").unwrap();
        g.add_edge("d", "a").unwrap();

        assert_eq!(g.successors("a"), Some(vec!["b", "c"]));
        assert_eq!(g.predecessors("a"), Some(vec!["d"]));
        assert_eq!(g.out_degree("a"), 2);
        assert_eq!(g.in_degree("a"), 1);
        assert_eq!(g.degree("a"), 3);
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn degree_single_lookup_preserves_missing_and_self_loop_semantics() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "a").expect("self-loop add should succeed");
        g.add_edge("a", "b").expect("edge add should succeed");
        g.add_edge("c", "a").expect("edge add should succeed");

        for node in ["a", "b", "c", "missing"] {
            assert_eq!(g.degree(node), g.in_degree(node) + g.out_degree(node));
        }
        assert_eq!(g.degree("a"), 4);
        assert_eq!(g.degree("missing"), 0);
    }

    #[test]
    fn neighbors_returns_successors() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("c", "a").unwrap();

        // neighbors() = successors() per NetworkX convention
        assert_eq!(g.neighbors("a"), Some(vec!["b"]));
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn in_edges_and_out_edges() {
        let mut g = DiGraph::strict();
        g.add_edge("x", "y").unwrap();
        g.add_edge("z", "y").unwrap();
        g.add_edge("y", "w").unwrap();

        assert_eq!(g.out_edges("y"), vec![("y", "w")]);
        assert_eq!(g.in_edges("y"), vec![("x", "y"), ("z", "y")]);
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn remove_directed_edge() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("b", "a").unwrap();

        assert!(g.remove_edge("a", "b"));
        assert!(!g.has_edge("a", "b"));
        assert!(g.has_edge("b", "a")); // reverse still exists
        assert_eq!(g.edge_count(), 1);
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn remove_node_removes_all_incident_directed_edges() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("b", "c").unwrap();
        g.add_edge("c", "a").unwrap();
        g.add_edge("d", "b").unwrap();

        assert!(g.remove_node("b"));
        assert_eq!(g.node_count(), 3);
        assert!(!g.has_edge("a", "b"));
        assert!(!g.has_edge("b", "c"));
        assert!(!g.has_edge("d", "b"));
        assert!(g.has_edge("c", "a")); // not incident to b
        assert_digraph_core_invariants(&g);
    }

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

        assert_eq!(g.number_of_selfloops(), 3);
        assert_multidigraph_core_invariants(&g);
    }

    // br-r37-c1-p6bxu: A/B substrate bench for MultiDiGraph::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_multidigraph_remove_node
    // -- --ignored --nocapture`. Also asserts byte-exact parity (node_count,
    // edge_count, edges_ordered, incl. self-loops) between the two paths.
    #[test]
    #[ignore]
    fn ab_bench_multidigraph_remove_node() {
        use std::time::Instant;
        const N: usize = 1000;
        const M: usize = 8000;
        const ITERS: usize = 500;
        let build = || {
            let mut g = MultiDiGraph::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.keys().take(ITERS).cloned().collect();
        let t = Instant::now();
        for node in &victims {
            gnew.remove_node(node);
        }
        let new_t = t.elapsed();

        // OLD path: full O(|E|) retain per removal.
        let mut gold = build();
        let t = Instant::now();
        for node in &victims {
            if !gold.nodes.contains_key(node) {
                continue;
            }
            if let Some(succs) = gold.successors.get(node) {
                let targets: Vec<String> = succs.keys().cloned().collect();
                for target in targets {
                    if target != *node
                        && let Some(preds) = gold.predecessors.get_mut(&target)
                    {
                        preds.shift_remove(node.as_str());
                    }
                }
            }
            if let Some(preds) = gold.predecessors.get(node) {
                let sources: Vec<String> = preds.keys().cloned().collect();
                for source in sources {
                    if source != *node
                        && let Some(succs) = gold.successors.get_mut(&source)
                    {
                        succs.shift_remove(node.as_str());
                    }
                }
            }
            let mut rc = 0usize;
            let nd = node.clone();
            gold.edges.retain(|k, bucket| {
                let keep = k.source != nd && k.target != nd;
                if !keep {
                    rc += bucket.len();
                }
                keep
            });
            gold.edge_count -= rc;
            gold.successors.shift_remove(node);
            gold.predecessors.shift_remove(node);
            gold.nodes.shift_remove(node);
        }
        let old_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!(
            "MultiDiGraph remove_node x{ITERS}: retain {old_t:?} -> swap_remove {new_t:?} = {:.2}x",
            old_t.as_secs_f64() / new_t.as_secs_f64()
        );
    }

    #[test]
    fn self_loop_directed() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "a").unwrap();

        assert_eq!(g.edge_count(), 1);
        assert!(g.has_edge("a", "a"));
        assert_eq!(g.out_degree("a"), 1);
        assert_eq!(g.in_degree("a"), 1);
        assert_digraph_core_invariants(&g);
    }

    #[test]
    fn edge_attrs_directed() {
        let mut g = DiGraph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("weight".to_owned(), "5".into());
        g.add_edge_with_attrs("a", "b", attrs).unwrap();

        assert_eq!(
            g.edge_attrs("a", "b").unwrap().get("weight"),
            Some(&CgseValue::String("5".to_owned()))
        );
        assert!(g.edge_attrs("b", "a").is_none()); // reverse has no attrs
    }

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

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

        assert_eq!(inserted, 2);
        assert_eq!(g.edge_count(), 2);
        assert!(g.has_edge("a", "b"));
        assert!(g.has_edge("b", "a"));
        assert!(!g.has_edge("a", "c"));
        let records = g.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 row_staged_attr_edges_preserve_orders_and_duplicate_merges() {
        let mut g = DiGraph::strict();
        let before = g.evidence_ledger().records().len();

        let inserted = g.extend_prepared_edges_with_attrs_row_staged_unrecorded(
            ["b", "x", "a", "t"]
                .into_iter()
                .map(std::borrow::ToOwned::to_owned),
            vec![
                ("b".to_owned(), "x".to_owned(), single_attr("first", "bx")),
                ("a".to_owned(), "t".to_owned(), single_attr("first", "at")),
                ("b".to_owned(), "t".to_owned(), single_attr("first", "bt")),
                (
                    "a".to_owned(),
                    "t".to_owned(),
                    single_attr("second", "merge"),
                ),
                ("t".to_owned(), "t".to_owned(), single_attr("loop", "yes")),
            ],
        );

        assert_eq!(inserted, 4);
        assert_eq!(g.nodes_ordered(), vec!["b", "x", "a", "t"]);
        assert_eq!(
            g.edges_ordered_borrowed()
                .into_iter()
                .map(|(u, v, _)| (u, v))
                .collect::<Vec<_>>(),
            vec![("b", "x"), ("b", "t"), ("a", "t"), ("t", "t")]
        );
        assert_eq!(
            g.edges_ordered_indices(),
            vec![(0, 1), (0, 3), (2, 3), (3, 3)]
        );
        assert_eq!(g.successors("b"), Some(vec!["x", "t"]));
        assert_eq!(g.predecessors("t"), Some(vec!["a", "b", "t"]));
        let merged = g.edge_attrs("a", "t").expect("merged edge should exist");
        assert_eq!(merged.get("first"), Some(&CgseValue::from("at")));
        assert_eq!(merged.get("second"), Some(&CgseValue::from("merge")));
        assert_digraph_core_invariants(&g);
        let records = g.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 repeated_edge_merges_attrs() {
        let mut g = DiGraph::strict();
        let mut first = AttrMap::new();
        first.insert("weight".to_owned(), "1".into());
        g.add_edge_with_attrs("a", "b", first).unwrap();

        let mut second = AttrMap::new();
        second.insert("color".to_owned(), "red".into());
        g.add_edge_with_attrs("a", "b", second).unwrap();

        assert_eq!(g.edge_count(), 1);
        let attrs = g.edge_attrs("a", "b").unwrap();
        assert_eq!(
            attrs.get("weight"),
            Some(&CgseValue::String("1".to_owned()))
        );
        assert_eq!(
            attrs.get("color"),
            Some(&CgseValue::String("red".to_owned()))
        );
    }

    #[test]
    fn edges_ordered_preserves_direction() {
        let mut g = DiGraph::strict();
        g.add_edge("b", "a").unwrap();
        g.add_edge("a", "c").unwrap();

        let pairs: Vec<(String, String)> = g
            .edges_ordered()
            .into_iter()
            .map(|e| (e.left, e.right))
            .collect();
        // b was added first as source, so b→a first, then a→c
        assert_eq!(
            pairs,
            vec![
                ("b".to_owned(), "a".to_owned()),
                ("a".to_owned(), "c".to_owned()),
            ]
        );
    }

    #[test]
    fn type_identity() {
        let g = DiGraph::strict();
        assert!(g.is_directed());
        assert!(!g.is_multigraph());
    }

    #[test]
    fn to_undirected_merges_edges() {
        let mut g = DiGraph::strict();
        g.add_edge("a", "b").unwrap();
        g.add_edge("b", "a").unwrap();
        g.add_edge("b", "c").unwrap();

        let ug = g.to_undirected();
        assert_eq!(ug.node_count(), 3);
        assert_eq!(ug.edge_count(), 2); // (a,b) merged, plus (b,c)
        assert!(ug.has_edge("a", "b"));
        assert!(ug.has_edge("b", "a")); // undirected: same edge
        assert!(ug.has_edge("b", "c"));
    }

    #[test]
    fn to_undirected_preserves_runtime_policy() {
        let mut g = DiGraph::hardened();
        g.add_edge("a", "b").unwrap();
        g.add_edge("b", "a").unwrap();
        let expected_policy = g.runtime_policy().clone();

        let ug = g.to_undirected();

        assert_runtime_policy_preserved(&expected_policy, ug.runtime_policy());
    }

    /// br-r37-c1-toundirbatch: paired-interleaved median A/B for DiGraph::to_undirected —
    /// inline per-edge baseline vs the shipped batch, one binary / one worker with a NULL
    /// control. A complete digraph K100 (every ordered pair a->b) makes 9900 directed edges
    /// collapse to 4950 undirected, so HALF the add_edge_with_attrs calls are merge-dups and
    /// each paid a per-edge policy record. Byte-identity asserted first.
    /// `#[ignore]`; run with
    /// `cargo test --release -p fnx-classes --lib to_undirected_batch_ab -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement; run with --release --ignored --nocapture"]
    fn to_undirected_batch_ab() {
        use std::hint::black_box;
        use std::time::Instant;

        let mut input = DiGraph::strict();
        for i in 0..200 {
            input.add_node(format!("{i}"));
        }
        for a in 0..200 {
            for b in 0..200 {
                if a != b {
                    input.add_edge(format!("{a}"), format!("{b}")).unwrap();
                }
            }
        }

        let build = |g: &DiGraph, batch: bool| -> crate::Graph {
            let mut out = crate::Graph::with_runtime_policy(g.runtime_policy.clone());
            for (node, attrs) in &g.nodes {
                out.add_node_with_attrs(node.clone(), attrs.clone());
            }
            if batch {
                let edges: Vec<(String, String, AttrMap)> = g
                    .edges_ordered()
                    .into_iter()
                    .map(|snap| (snap.left, snap.right, snap.attrs))
                    .collect();
                let _ = out.extend_edges_with_attrs_unrecorded(edges);
            } else {
                for snap in g.edges_ordered() {
                    let _ = out.add_edge_with_attrs(snap.left, snap.right, snap.attrs);
                }
            }
            out
        };

        let old = build(&input, false);
        let new = build(&input, true);
        assert_eq!(
            old.edges_ordered_borrowed(),
            new.edges_ordered_borrowed(),
            "batch to_undirected must equal the per-edge baseline"
        );
        assert_eq!(old.nodes_ordered(), new.nodes_ordered());

        let time = |batch: bool| -> f64 {
            let t0 = Instant::now();
            black_box(build(&input, batch));
            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_arm: bool| -> Vec<f64> {
            let mut v = Vec::with_capacity(rounds);
            for round in 0..rounds {
                let (tb, tc) = if round.is_multiple_of(2) {
                    let bt = time(base_arm);
                    let ct = time(cand);
                    (bt, ct)
                } else {
                    let ct = time(cand);
                    let bt = time(base_arm);
                    (bt, ct)
                };
                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!(
                "TOUNDIR_BATCH_AB {name}: median={:.4}x win_rate={wins}/{rounds} \
                 p5_p95=[{:.4},{:.4}]",
                median(ratios),
                sorted[rounds * 5 / 100],
                sorted[rounds * 95 / 100],
            );
        };
        println!("TOUNDIR_BATCH_AB K200_complete rounds={rounds} (>1 = batch faster)");
        report("BATCH_vs_string", &paired(true, false));
        report("NULL_batch_vs_batch", &paired(true, true));
    }

    #[test]
    fn snapshot_roundtrip() {
        let mut g = DiGraph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("weight".to_owned(), "3".into());
        g.add_edge_with_attrs("a", "b", attrs).unwrap();
        g.add_edge("b", "c").unwrap();
        g.add_edge("c", "a").unwrap();

        let snap = g.snapshot();
        let mut replayed = DiGraph::new(snap.mode);
        for node in &snap.nodes {
            let _ = replayed.add_node(node.clone());
        }
        for edge in &snap.edges {
            replayed
                .add_edge_with_attrs(edge.left.clone(), edge.right.clone(), edge.attrs.clone())
                .unwrap();
        }

        assert_eq!(replayed.snapshot(), snap);
        assert_digraph_core_invariants(&replayed);
    }

    #[test]
    fn multidigraph_tracks_parallel_edges_with_distinct_keys() {
        let mut graph = MultiDiGraph::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_multidigraph_core_invariants(&graph);
    }

    #[test]
    fn multidigraph_remove_node_clears_incoming_and_outgoing_parallel_edges() {
        let mut graph = MultiDiGraph::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", "a").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.successors("a"), Some(vec![]));
        assert_eq!(graph.predecessors("a"), Some(vec![]));
        assert_multidigraph_core_invariants(&graph);
    }

    #[test]
    fn multidigraph_clear_edges_preserves_nodes_attrs_and_rows() {
        let mut graph = MultiDiGraph::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_eq!(graph.edges_ordered(), Vec::<MultiDiEdgeSnapshot>::new());
        assert_eq!(graph.successors("a"), Some(vec![]));
        assert_eq!(graph.predecessors("a"), Some(vec![]));
        assert_eq!(
            graph.node_attrs("a").unwrap().get("color"),
            Some(&CgseValue::from("red"))
        );
        assert!(graph.revision() > before_revision);
        assert_multidigraph_core_invariants(&graph);
    }

    #[test]
    fn multidigraph_roundtrips_sparse_snapshot_keys() {
        let mut graph = MultiDiGraph::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 = MultiDiGraph::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.source.clone(),
                    edge.target.clone(),
                    edge.key,
                    edge.attrs.clone(),
                )
                .expect("snapshot replay should preserve explicit keys");
        }

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

    #[test]
    fn runtime_policy_tracks_hardened_multidigraph_recovery() {
        let mut g = MultiDiGraph::hardened();
        g.add_edge("a", "b")
            .expect("hardened multidigraph edge add should succeed");

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

    /// br-r37-c1-eo88t: directed mirror of the simple/multi pairing in
    /// `fnx-classes/src/lib.rs`. An ALLOWED edge add writes exactly one
    /// `add_edge` ledger record and it is the outcome one; a REFUSED add still
    /// writes its gate record, which is the rejected mutation's only audit
    /// trail because the outcome record never runs.
    fn add_edge_evidence_signals(records: &[DecisionRecord]) -> Vec<Vec<&str>> {
        records
            .iter()
            .filter(|record| record.operation == "add_edge")
            .map(|record| {
                record
                    .evidence
                    .iter()
                    .map(|term| term.signal.as_ref())
                    .collect()
            })
            .collect()
    }

    /// br-r37-c1-4c29a: `MultiDiGraph`'s adjacency rows moved from the default
    /// SipHash to `FxBuildHasher`. That is only admissible because `IndexMap`
    /// and `IndexSet` are INSERTION-ordered, so the hasher cannot reach
    /// iteration order — and iteration order is CGSE-observable here, since
    /// `edges_ordered` walks these rows. Asserted rather than asserted-by-faith:
    /// the endpoints below are inserted in an order that is neither sorted nor
    /// hash order, and must come back exactly as inserted.
    #[test]
    fn multidigraph_adjacency_iterates_in_insertion_order_under_fxhash() {
        let mut graph = MultiDiGraph::strict();
        for (source, target) in [
            ("zeta", "mid"),
            ("zeta", "alpha"),
            ("zeta", "omega"),
            ("zeta", "beta"),
            ("alpha", "zeta"),
        ] {
            graph
                .add_edge_with_attrs(source, target, AttrMap::new())
                .expect("edge is allowed");
        }
        // Parallel edges on an already-seen pair must append, not reorder.
        graph
            .add_edge_with_attrs("zeta", "alpha", AttrMap::new())
            .expect("parallel edge is allowed");

        let observed: Vec<(String, String, usize)> = graph
            .edges_ordered_borrowed()
            .into_iter()
            .map(|(source, target, key, _)| (source.to_owned(), target.to_owned(), key))
            .collect();
        assert_eq!(
            observed,
            vec![
                ("zeta".to_owned(), "mid".to_owned(), 0),
                ("zeta".to_owned(), "alpha".to_owned(), 0),
                ("zeta".to_owned(), "alpha".to_owned(), 1),
                ("zeta".to_owned(), "omega".to_owned(), 0),
                ("zeta".to_owned(), "beta".to_owned(), 0),
                ("alpha".to_owned(), "zeta".to_owned(), 0),
            ],
            "adjacency rows must stay insertion-ordered regardless of hasher"
        );
    }

    /// br-r37-c1-jc9e4: directed-multi mirror of the `Graph` fresh-bucket lock.
    /// `add_edge_impl` now TAKES the caller's attribute map when the keyed
    /// bucket is empty. The multigraph-only risk is that the take could land on
    /// the wrong parallel edge, so each key is asserted separately.
    #[test]
    fn multidigraph_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
        }

        let mut graph = MultiDiGraph::strict();
        let k0 = graph
            .add_edge_with_attrs("a", "b", weight(1))
            .expect("edge is allowed");
        // A PARALLEL edge gets its own fresh bucket and must not disturb k0.
        let k1 = graph
            .add_edge_with_attrs("a", "b", weight(2))
            .expect("parallel edge is allowed");
        assert_ne!(k0, k1);
        assert_eq!(
            graph.edge_attrs("a", "b", k0).and_then(|a| a.get("w")),
            Some(&CgseValue::Int(1))
        );
        assert_eq!(
            graph.edge_attrs("a", "b", k1).and_then(|a| a.get("w")),
            Some(&CgseValue::Int(2))
        );

        // A keyed edge created with EMPTY attrs still takes the empty-bucket
        // branch when attrs arrive later.
        let k2 = graph
            .add_edge_with_attrs("c", "d", AttrMap::new())
            .expect("edge is allowed");
        assert!(
            graph
                .edge_attrs("c", "d", k2)
                .expect("edge exists")
                .is_empty()
        );
        graph
            .add_edge_with_key_and_attrs("c", "d", k2, weight(7))
            .expect("edge is allowed");
        assert_eq!(
            graph.edge_attrs("c", "d", k2).and_then(|a| a.get("w")),
            Some(&CgseValue::Int(7))
        );

        // Non-empty bucket still merges rather than being replaced.
        let mut extra = AttrMap::new();
        extra.insert("k".to_owned(), CgseValue::Int(3));
        graph
            .add_edge_with_key_and_attrs("c", "d", k2, extra)
            .expect("edge is allowed");
        let stored = graph.edge_attrs("c", "d", k2).expect("edge exists");
        assert_eq!(stored.get("w"), Some(&CgseValue::Int(7)));
        assert_eq!(stored.get("k"), Some(&CgseValue::Int(3)));
    }

    /// br-r37-c1-jc9e4: `MultiDiGraph::add_node_with_attrs_unrecorded` stopped
    /// using `entry(node.clone()).or_default()` for the `successors` /
    /// `predecessors` rows and now probes borrowed, inserting only when the row
    /// is genuinely absent. The risk that swap introduces is a row that fails to
    /// get created, which would surface later as a lost edge rather than at the
    /// call itself, so this exercises row creation and row preservation
    /// directly through the degrees.
    #[test]
    fn multidigraph_add_node_creates_and_preserves_adjacency_rows() {
        let mut graph = MultiDiGraph::strict();

        // A node created by add_node — not by an edge — must still get usable
        // successor AND predecessor rows.
        graph.add_node("x");
        graph
            .add_edge_with_attrs("x", "y", AttrMap::new())
            .expect("edge is allowed");
        graph
            .add_edge_with_attrs("w", "x", AttrMap::new())
            .expect("edge is allowed");
        assert_eq!(graph.out_degree("x"), 1);
        assert_eq!(graph.in_degree("x"), 1);

        // Re-adding an EXISTING node now takes the borrowed path that skips the
        // insert entirely. It must not disturb the rows it skips.
        for _ in 0..5 {
            graph.add_node("x");
        }
        assert_eq!(graph.out_degree("x"), 1);
        assert_eq!(graph.in_degree("x"), 1);
        assert_eq!(graph.node_count(), 3);

        // Parallel edges still accumulate on the preserved row.
        graph
            .add_edge_with_attrs("x", "y", AttrMap::new())
            .expect("parallel edge is allowed");
        assert_eq!(graph.out_degree("x"), 2);
    }

    /// br-r37-c1-jc9e4: directed mirror of the `Graph` lock. Pins the endpoint
    /// resolution cases that collapsing the per-endpoint `contains_key` +
    /// `get_index_of` pair restructured — in particular the self-loop branch,
    /// which now returns the source index instead of probing for the target and
    /// still has to report `target_autocreated` as a COPY of
    /// `source_autocreated`. Direction is asserted alongside, because the
    /// successor/predecessor rows are now filled from the reused indices.
    #[test]
    fn digraph_add_edge_endpoint_resolution_preserves_autocreation_and_direction() {
        fn autocreated(graph: &DiGraph) -> (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("source_autocreated"), read("target_autocreated"))
        }

        // Self-loop that CREATES its node: both flags true, one node added.
        let mut graph = DiGraph::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);

        // Source exists, target 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: source resolved and inserted BEFORE target, so insertion
        // order is source-then-target and 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));

        // Direction survives filling succ/pred from the reused indices.
        assert!(graph.has_edge("z", "a"));
        assert!(!graph.has_edge("a", "z"));
        assert!(graph.has_edge("s", "t"));
        assert!(!graph.has_edge("t", "s"));
    }

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

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

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

        assert_eq!(
            add_edge_evidence_signals(g.evidence_ledger().records()),
            vec![vec![
                "edge_key",
                "edge_attr_count",
                "source_autocreated",
                "target_autocreated",
            ]]
        );
    }

    #[test]
    fn refused_multidigraph_add_edge_still_records_its_gate_decision() {
        let mut g = MultiDiGraph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("__fnx_incompatible_decoder".to_owned(), "v2".into());
        let err = g
            .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_evidence_signals(g.evidence_ledger().records()),
            vec![vec!["unknown_incompatible_feature"]]
        );
        assert_eq!(
            g.evidence_ledger().records().last().map(|r| r.action),
            Some(DecisionAction::FailClosed)
        );
    }

    #[test]
    fn strict_mode_fails_closed_for_incompatible_attrs() {
        let mut g = DiGraph::strict();
        let mut attrs = AttrMap::new();
        attrs.insert("__fnx_incompatible_decoder".to_owned(), "v2".into());
        let err = g
            .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(),
            }
        );
    }

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

        g.add_edge("a", "b").unwrap();
        let r2 = g.revision();
        assert!(r2 > r1);

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

    #[test]
    fn hardened_self_loop_records_allow() {
        let mut g = DiGraph::hardened();
        g.add_edge("loop", "loop").unwrap();

        let record = g
            .evidence_ledger()
            .records()
            .iter()
            .rev()
            .find(|r| r.operation == "add_edge")
            .expect("add_edge should emit ledger row");
        assert_decision_record_schema(record, CompatibilityMode::Hardened);
        assert_eq!(record.action, DecisionAction::Allow);
    }

    #[test]
    fn runtime_policy_tracks_hardened_digraph_recovery() {
        let mut g = DiGraph::hardened();
        g.add_edge("a", "b")
            .expect("hardened digraph edge add should succeed");

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

    /// br-r37-c1-p1tvg: the index probe answers the ORIENTED pair, and only
    /// for live nodes. Probing the undirected pair or a freed index would
    /// each pass a test that only checked present edges.
    #[test]
    fn has_edge_by_indices_is_oriented_and_range_checked() {
        let mut g = DiGraph::strict();
        g.add_edge("tail", "head").expect("edge add should succeed");
        g.add_edge("head", "third")
            .expect("edge add should succeed");

        let (tail, head, third) = (
            g.get_node_index("tail").expect("tail index"),
            g.get_node_index("head").expect("head index"),
            g.get_node_index("third").expect("third index"),
        );
        assert!(g.has_edge_by_indices(tail, head));
        assert!(!g.has_edge_by_indices(head, tail));
        assert!(!g.has_edge_by_indices(tail, third));
        assert!(!g.has_edge_by_indices(third, g.node_count() + 7));
        assert!(!g.has_edge_by_indices(g.node_count() + 7, third));

        // Removal renumbers: "third" takes the freed slot, so a stale key
        // left behind by the remap would answer for the wrong node pair.
        assert!(g.remove_node("tail"), "node removal should succeed");
        let head_after = g.get_node_index("head").expect("head index after removal");
        let third_after = g
            .get_node_index("third")
            .expect("third index after removal");
        assert!(g.has_edge_by_indices(head_after, third_after));
        assert!(!g.has_edge_by_indices(third_after, head_after));
        assert!(!g.has_edge_by_indices(head_after, g.node_count()));
    }

    // -- Proptest -----------------------------------------------------------

    proptest! {
        /// br-r37-c1-p1tvg: the index probe must agree with the String path
        /// on EVERY pair — present, absent, reversed, and out of range —
        /// through arbitrary add/remove sequences that renumber indices.
        #[test]
        fn prop_has_edge_by_indices_matches_the_name_path(
            ops in prop::collection::vec((0_u8..6, 0_u8..6, 0_u8..10), 1..60),
        ) {
            let mut g = DiGraph::strict();
            for (src_id, tgt_id, action) in ops {
                let (source, target) = (node_name(src_id), node_name(tgt_id));
                match action {
                    0..=6 => {
                        prop_assert!(g.add_edge(source, target).is_ok());
                    }
                    7 | 8 => {
                        let _ = g.remove_edge(&source, &target);
                    }
                    _ => {
                        let _ = g.remove_node(&source);
                    }
                }
            }

            let names: Vec<String> = g.nodes_ordered().iter().map(|n| (*n).to_owned()).collect();
            for (i, source) in names.iter().enumerate() {
                for (j, target) in names.iter().enumerate() {
                    prop_assert_eq!(
                        g.has_edge_by_indices(i, j),
                        g.has_edge(source, target),
                        "index pair ({}, {}) disagrees with ({}, {})",
                        i, j, source, target
                    );
                }
                prop_assert!(!g.has_edge_by_indices(i, names.len()));
                prop_assert!(!g.has_edge_by_indices(names.len(), i));
            }
        }

        #[test]
        fn prop_digraph_invariants_under_mixed_mutations(
            ops in prop::collection::vec((0_u8..8, 0_u8..8, any::<bool>()), 1..80),
        ) {
            let mut g = DiGraph::strict();
            let mut last_rev = g.revision();

            for (src_id, tgt_id, is_add) in ops {
                let src = node_name(src_id);
                let tgt = node_name(tgt_id);
                if is_add {
                    prop_assert!(g.add_edge(src, tgt).is_ok());
                } else {
                    let _ = g.remove_edge(&src, &tgt);
                }
                let rev = g.revision();
                prop_assert!(rev >= last_rev);
                last_rev = rev;
                assert_digraph_core_invariants(&g);
            }
        }

        #[test]
        fn prop_digraph_snapshot_deterministic(
            ops in prop::collection::vec((0_u8..8, 0_u8..8, 0_u8..3), 0..64),
        ) {
            let mut g1 = DiGraph::hardened();
            let mut g2 = DiGraph::hardened();

            for (src_id, tgt_id, attrs_variant) in ops {
                let src = node_name(src_id);
                let tgt = node_name(tgt_id);
                let mut attrs = AttrMap::new();
                if attrs_variant == 1 {
                    attrs.insert("weight".to_owned(), (src_id % 5).to_string().into());
                } else if attrs_variant == 2 {
                    attrs.insert("tag".to_owned(), format!("k{}", tgt_id % 4).into());
                }
                prop_assert!(g1.add_edge_with_attrs(src.clone(), tgt.clone(), attrs.clone()).is_ok());
                prop_assert!(g2.add_edge_with_attrs(src, tgt, attrs).is_ok());
            }

            prop_assert_eq!(g1.snapshot(), g2.snapshot());
        }

        #[test]
        fn prop_remove_node_clears_all_directed_edges(
            ops in prop::collection::vec((0_u8..8, 0_u8..8), 1..64),
            target_id in 0_u8..8,
        ) {
            let mut g = DiGraph::strict();
            for (src_id, tgt_id) in ops {
                prop_assert!(g.add_edge(node_name(src_id), node_name(tgt_id)).is_ok());
            }

            let target = node_name(target_id);
            let removed = g.remove_node(&target);
            if removed {
                prop_assert!(!g.has_node(&target));
                for node in g.nodes_ordered() {
                    prop_assert!(!g.has_edge(node, &target));
                    prop_assert!(!g.has_edge(&target, node));
                }
            }
            assert_digraph_core_invariants(&g);
        }

        #[test]
        fn prop_directed_edge_count_equals_successor_sum(
            ops in prop::collection::vec((0_u8..8, 0_u8..8), 1..64),
        ) {
            let mut g = DiGraph::strict();
            for (src_id, tgt_id) in ops {
                prop_assert!(g.add_edge(node_name(src_id), node_name(tgt_id)).is_ok());
            }

            let total_out: usize = g.nodes_ordered().iter().map(|n| g.out_degree(n)).sum();
            let total_in: usize = g.nodes_ordered().iter().map(|n| g.in_degree(n)).sum();
            prop_assert_eq!(g.edge_count(), total_out);
            prop_assert_eq!(g.edge_count(), total_in);
        }
    }
}