semi-persistent-egraph 0.2.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! The semi-persistent e-graph: add, merge, find, rebuild, mark, restore.

use crate::canon::{MSetCanon, MSetClamp, VarCanon};
use crate::classes::EClasses;
use crate::config::EGraphConfig;
use crate::containers::DenseId;
use crate::containers::IndexLike;
use crate::containers::ShrinkPolicy;
use crate::literal::{LitVal, LitValStore, LitValStoreToken};
use crate::multiplicity::MultiplicityLike;
use crate::node_store::{Added, NodeStore, NodeStoreToken};
use crate::registry::{
    AxiomRegistry, AxiomRegistryToken, OpKind, OpRegistry, OpRegistryToken, RuleRegistry,
    RuleRegistryToken, SortRegistry, SortRegistryToken,
};
use crate::typed_routing::NodeRef;
use crate::union_find::{Justification, ProofBuf};

/// How a completion op's monomial counts are bounded during normalization (design "three
/// independent axes"): unbounded ℕ (MSet plain AC), clamped to {0,1} by dedup (Set idempotent =
/// ACI), or reduced mod `order` (nilpotent, e.g. XOR at order 2 — stored MSet, the clamp is the
/// algebra axis, not the storage axis). Selects the normalize/reduct
/// reduction in `cc_round`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CompletionClamp {
    Multiset,
    Idempotent,
    Nilpotent { order: u8 },
}

#[derive(Clone, Copy, Debug)]
pub struct EGraphToken {
    classes: crate::classes::EClassesToken,
    nodes: NodeStoreToken,
    sorts: SortRegistryToken,
    ops: OpRegistryToken,
    rules: RuleRegistryToken,
    axioms: AxiomRegistryToken,
    lits: LitValStoreToken,
    unit_node: crate::containers::MapToken,
    inverse_op: crate::containers::MapToken,
    /// The completion outcome at mark time. `mark()` rebuilds first, so this value
    /// describes exactly the state being snapshotted; `restore` puts it back so a caller
    /// can never observe an outcome from a discarded scope.
    completion_outcome: Option<CompletionOutcome>,
}

pub struct EGraph<
    Cfg: EGraphConfig,
    L: LitVal,
    const TRACK: bool = true,
    const PROOFS: bool = false,
> {
    sorts: SortRegistry<Cfg::S, TRACK>,
    ops: OpRegistry<Cfg::O, Cfg::S, TRACK>,
    rules: RuleRegistry<TRACK>,
    axioms: AxiomRegistry<Cfg::G, TRACK>,
    lits: LitValStore<L, Cfg::V, TRACK>,
    classes: EClasses<Cfg::G, Cfg::ClassKey, Cfg::UL, Cfg::UN, TRACK, PROOFS>,
    nodes: NodeStore<Cfg::G, Cfg::O, Cfg::V, Cfg::C, Cfg::Ids, TRACK, PROOFS>,
    worklist: Vec<(Cfg::UL, Cfg::G)>,
    collisions: Vec<(Cfg::G, Cfg::G)>,
    /// Reusable scratch for a node's child ids as bare `G` (the canonical-children buffer for
    /// every representation except MSet). Paired with `mset_buf`, which holds the MSet variant.
    g_buf: Vec<Cfg::G>,
    /// Reusable scratch for MSet children, child type `C` = `(G, mult)` (the multiset
    /// representation needs the multiplicity that bare `G` in `g_buf` cannot carry).
    mset_buf: Vec<Cfg::C>,
    /// Semi-naive touched log: node ids created or recanonicalized since the
    /// last `clear_touched`. Round-local scratch (cleared on `restore`);
    /// drives the per-round delta index. Not part of persistent state.
    touched: Vec<Cfg::G>,
    /// When set, every class merge also records the absorbed side's member
    /// nodes in `touched` (see `merge_in_classes`). Only semi-naive saturation
    /// consumes it; off everywhere else so merges pay no ring walk.
    track_merge_members: bool,
    /// Survivor policy for class merges (see [`UnionBy`]).
    union_by: UnionBy,
    /// Goal pair for goal-directed completion (the lazy-check transaction):
    /// the completion loop polls it between passes and inside a round's apply
    /// loops, and stops with [`CompletionOutcome::GoalMet`] as soon as the
    /// two classes join. `None` everywhere else.
    cc_goal: Option<(Cfg::G, Cfg::G)>,
    /// Node count at the start of the current completion run, for the
    /// in-round budget check (`cc_should_stop`): a single blown-up round is
    /// stopped mid-apply instead of only between rounds.
    cc_start_nodes: usize,
    /// Whether `rebuild` runs the AC congruence-completion pass (superposition +
    /// inter-reduction). **Default off** because ground AC completion is doubly
    /// exponential in the worst case. The growth backstop is checked between rounds and
    /// inside the apply loops, but a bounded node count does not make the algorithm cheap.
    /// See `doc/future/ac-completion-limitations.md` section 1. Opt in with
    /// [`set_cc`](Self::set_cc).
    cc: bool,
    /// Whether `rebuild` runs the AC reduced-basis invariant checks (`cc_basis_dump`:
    /// `min_monomial` minimality, the Kapur-reduced antichain, etc., see `ac_invariants.rs`).
    /// **Default off** and only consulted when `cc` is on: the ground-truth checks
    /// brute-force per-class minima and multi-step normalization (superlinear), so they are
    /// diagnostic/test-only, never on the production hot path. Seeded from the `AC_BASIS_DUMP`
    /// env var at construction (so existing diagnostic runs keep working) and overridable via
    /// [`set_basis_checks`](Self::set_basis_checks).
    basis_checks: bool,
    /// Reusable scratch for comparing two nodes' AC monomials (`monomial_cmp` on the
    /// per-class `min_monomial`, §9a). Two buffers to hold both sides without aliasing;
    /// cleared and refilled per comparison, never grown per merge.
    cmp_buf_a: Vec<(Cfg::G, Cfg::M)>,
    cmp_buf_b: Vec<(Cfg::G, Cfg::M)>,
    /// Reusable scratch for flattening nested same-op AC children (`WF_flat`,
    /// design §6c). Worklist of children still to expand; never grown per add.
    flatten_buf: Vec<Cfg::G>,
    /// Per-op identity (unit) element node, for completion ops declared with `:identity e`
    /// (`x ∘ e = x`; the unit drops from monomials). Resolved to a real node at registration
    /// (sortcheck has the model to parse the term and builds the node), keyed by op id. Stored
    /// here rather than on `OpKind<S>` because a node id is `Cfg::G`, which `OpKind<S>` cannot
    /// carry. Semi-persistent (its own token), so it rolls back with the op declarations that
    /// created the units. Absent key = the op has no declared identity.
    unit_node: crate::containers::SpMap<Cfg::O, Cfg::G, <Cfg::O as DenseId>::Index, TRACK>,
    /// Per-op group inverse operator, for AC ops declared with `:inverse neg`
    /// (`x ∘ neg(x) = e`). Resolved to a real op id at registration (sortcheck validates
    /// the unary signature). Same persistence story as `unit_node`. Absent key = no
    /// declared inverse. NOTE: gate-level group support — inverse-PAIR cancellation only,
    /// not Kapur §5.4's full Abelian-group completion (no Gaussian elimination).
    inverse_op: crate::containers::SpMap<Cfg::O, Cfg::O, <Cfg::O as DenseId>::Index, TRACK>,
    /// Outcome of the most recent `rebuild` when `cc` is enabled. Lets callers distinguish
    /// convergence from a growth-budget abort. `None` if completion hasn't run yet.
    completion_outcome: Option<CompletionOutcome>,
    /// Node-growth budget for one completion-enabled `rebuild`: if completion mints more
    /// than this many nodes beyond where the rebuild started, it stops (sound-but-
    /// incomplete, reported as [`CompletionOutcome::AbortedGrowthLimit`]) rather than
    /// allowing unbounded node growth. This is NOT a termination argument or a complete
    /// work bound; it is the resource backstop described in
    /// `doc/future/ac-completion-limitations.md`. A config knob like
    /// `cc`/`basis_checks`, not
    /// semi-persistent state; default [`DEFAULT_COMPLETION_NODE_BUDGET`], overridable via
    /// [`set_completion_node_budget`](Self::set_completion_node_budget) (tests use a tiny
    /// budget to exercise the abort path directly).
    completion_node_budget: usize,
}

/// Default node-growth budget for one completion-enabled `rebuild` (see
/// [`EGraph::set_completion_node_budget`]).
pub const DEFAULT_COMPLETION_NODE_BUDGET: usize = 50_000;

/// Outcome of the AC congruence-completion pass inside `rebuild`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompletionOutcome {
    /// Completion was not enabled (`set_cc(false)`).
    Disabled,
    /// The implemented completion passes reached an unchanged full-round fixpoint.
    ///
    /// This is an operational stopping condition, not by itself a certificate
    /// that the abstract AC/ACI theory is complete.
    ///
    /// For associative-only operators this does not claim completeness for
    /// arbitrary asserted ground equations; that general word problem is
    /// undecidable. See `doc/future/ac-completion-limitations.md` section 8.
    Converged { rounds: usize },
    /// Completion aborted because the node-growth budget was exceeded. The e-graph is
    /// sound-but-incomplete: some AC-entailed equalities may be missing.
    AbortedGrowthLimit { added_nodes: usize, limit: usize },
    /// Completion stopped early because the goal pair (`set_cc_goal`) joined.
    /// The e-graph is a valid plain-congruence-closed state; completion is
    /// deliberately unfinished — the caller asked a question and it is
    /// answered. Only the lazy-check transaction sets a goal.
    GoalMet { rounds: usize },
}

/// Aggregate counts from [`EGraph::dump_all_proofs`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ProofDumpStats {
    /// One proof-path record is emitted for every e-node, including representatives.
    pub terms: usize,
    /// Records with at least one proof edge.
    pub nontrivial_proofs: usize,
    /// Total proof edges written across all certificates.
    pub steps: usize,
}

/// Survivor policy for class merges (`--union-by`). `Rank` leaves the choice
/// to the union-find's rank heuristic (the historical default). The directed
/// criteria absorb the cheap side, reading the verified per-class counters:
/// `Size` compares member counts (bounds the semi-naive touched-log pushes to
/// amortized O(n log n) — a node is absorbed at most log n times), `Uses`
/// compares use-list lengths (bounds recanonization work the same way), and
/// `Sum` adds the two, bounding their aggregate movement. Survivor identity is
/// intended to be semantically irrelevant because class payloads are
/// merge-folded (design doc §9a), and finite differential tests compare the
/// policies. This is not an end-to-end equivalence theorem; budget-, goal-, or
/// order-sensitive runs may follow different operational paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum UnionBy {
    #[default]
    Rank,
    Size,
    Uses,
    Sum,
}

/// Shortlex order on canonical element lists: shorter first, ties broken
/// element-wise by id. The orientation of the A-only inter-reduction rules
/// (`a_round`); well-founded, so rewriting under it terminates.
fn shortlex<G: crate::containers::DenseId>(a: &[G], b: &[G]) -> std::cmp::Ordering {
    a.len().cmp(&b.len()).then_with(|| {
        a.iter()
            .map(|g| g.to_usize())
            .cmp(b.iter().map(|g| g.to_usize()))
    })
}

/// Type alias for the default 31-bit configuration.
pub type EGraph31<L, const TRACK: bool = true, const PROOFS: bool = false> =
    EGraph<crate::nodes::DefaultConfig, L, TRACK, PROOFS>;

/// Type alias for the 63-bit configuration.
pub type EGraph63<L, const TRACK: bool = true, const PROOFS: bool = false> =
    EGraph<crate::nodes::Config64, L, TRACK, PROOFS>;

/// Type alias for 31-bit ids with a 16-bit multiplicity ([`crate::nodes::ConfigM16`]).
pub type EGraphM16<L, const TRACK: bool = true, const PROOFS: bool = false> =
    EGraph<crate::nodes::ConfigM16, L, TRACK, PROOFS>;

impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool> Default
    for EGraph<Cfg, L, TRACK, PROOFS>
where
    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
    EGraph<Cfg, L, TRACK, PROOFS>
where
    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
    pub fn new() -> Self {
        Self {
            sorts: SortRegistry::new(),
            ops: OpRegistry::new(),
            rules: RuleRegistry::new(),
            axioms: AxiomRegistry::new(),
            lits: LitValStore::new(),
            classes: EClasses::new(),
            nodes: NodeStore::new(),
            worklist: Vec::new(),
            collisions: Vec::new(),
            g_buf: Vec::new(),
            mset_buf: Vec::new(),
            touched: Vec::new(),
            track_merge_members: false,
            union_by: UnionBy::Rank,
            cc_goal: None,
            cc_start_nodes: 0,
            cc: false,
            basis_checks: std::env::var_os("AC_BASIS_DUMP").is_some(),
            cmp_buf_a: Vec::new(),
            cmp_buf_b: Vec::new(),
            flatten_buf: Vec::new(),
            unit_node: crate::containers::SpMap::new(),
            inverse_op: crate::containers::SpMap::new(),
            completion_outcome: None,
            completion_node_budget: DEFAULT_COMPLETION_NODE_BUDGET,
        }
    }

    /// Outcome of the most recent `rebuild` when `cc` is enabled. `None` before the first
    /// rebuild. Callers can use this to distinguish convergence from a growth-budget abort.
    pub fn completion_outcome(&self) -> Option<CompletionOutcome> {
        self.completion_outcome
    }

    /// Set the node-growth budget for one completion-enabled `rebuild` (default
    /// [`DEFAULT_COMPLETION_NODE_BUDGET`]). Exceeding it aborts completion soundly and
    /// records [`CompletionOutcome::AbortedGrowthLimit`]. A config knob (like
    /// [`set_cc`](Self::set_cc)), not semi-persistent state.
    pub fn set_completion_node_budget(&mut self, budget: usize) {
        self.completion_node_budget = budget;
    }

    /// Enable or disable the AC congruence-completion pass in `rebuild` (default off).
    /// See the `cc` field docs and `doc/future/ac-completion-limitations.md` §1.
    pub fn set_cc(&mut self, enabled: bool) {
        self.cc = enabled;
    }

    /// Select the merge survivor policy (see [`UnionBy`]).
    pub fn set_union_by(&mut self, u: UnionBy) {
        self.union_by = u;
    }

    /// The weight the `--union-by` criterion assigns to the class of repr `r`.
    fn union_weight(&self, r: Cfg::G) -> usize {
        let Some(k) = self.classes.repr_id(r) else {
            return 0;
        };
        match self.union_by {
            UnionBy::Rank => 0,
            UnionBy::Size => self.classes.class_size(k),
            UnionBy::Uses => self.classes.use_list_len(k),
            UnionBy::Sum => self
                .classes
                .class_size(k)
                .saturating_add(self.classes.use_list_len(k)),
        }
    }

    /// Set or clear the completion goal pair (see the `cc_goal` field). With a
    /// goal set, `rebuild` under completion returns
    /// [`CompletionOutcome::GoalMet`] as soon as the pair joins, without
    /// finishing the closure.
    pub fn set_cc_goal(&mut self, goal: Option<(Cfg::G, Cfg::G)>) {
        self.cc_goal = goal;
    }

    /// Goal-directed early stop for the completion loops: the goal pair
    /// joined, or the in-round node budget is exhausted. `rebuild` sorts out
    /// which of the two happened.
    fn cc_should_stop(&self) -> bool {
        if let Some((a, b)) = self.cc_goal
            && self.classes.find_const(a) == self.classes.find_const(b)
        {
            return true;
        }
        self.node_count()
            > self
                .cc_start_nodes
                .saturating_add(self.completion_node_budget)
    }

    /// Enable or disable the AC reduced-basis invariant checks in `rebuild` (default off,
    /// seeded from the `AC_BASIS_DUMP` env var). When on (and `cc` is on), each
    /// completion round prints `cc_basis_dump`, which runs the ground-truth checkers
    /// (`min_monomial` minimality, Kapur-reducedness). These are superlinear brute-force checks,
    /// so leave this off outside diagnosis and tests. See `ac_invariants.rs`.
    pub fn set_basis_checks(&mut self, enabled: bool) {
        self.basis_checks = enabled;
    }

    /// Create an e-graph with built-in sorts and reserved op names from a `LitModel`.
    pub fn from_model(model: &impl crate::lit_model::LitModel<Value = L>) -> Self {
        let mut eg = Self::new();
        let sort_names: Vec<&str> = model.sorts().iter().map(|s| s.name).collect();
        eg.sorts.register_builtins(&sort_names);
        eg.ops.register_builtins(model, &eg.sorts);
        eg
    }

    /// Create an e-graph with pre-built registries (from sortcheck).
    pub fn with_registries(
        sorts: SortRegistry<Cfg::S, TRACK>,
        ops: OpRegistry<Cfg::O, Cfg::S, TRACK>,
    ) -> Self {
        let mut eg = Self::new();
        eg.sorts = sorts;
        eg.ops = ops;
        eg
    }

    pub fn len(&self) -> usize {
        self.nodes.len()
    }
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Every node id in the store, ascending.
    ///
    /// The one place a full scan should get its ids from. The obvious spelling —
    /// `for i in 0..eg.len() { Cfg::G::from_usize(i) }` — is sound but not *locally*
    /// justified: `Cfg::G::Index` spans twice the id space for a bit-stealing id, and
    /// `from_usize` rejects positions outside the smaller payload range. What keeps the
    /// routing table inside that range is that [`TypedRouting::reserve`] mints every entry
    /// through `try_new`, three modules away. Stating that once here means a new scan
    /// inherits the argument instead of re-deriving it.
    ///
    /// [`TypedRouting::reserve`]: crate::typed_routing::TypedRouting::reserve
    pub fn node_ids(&self) -> impl Iterator<Item = Cfg::G> + '_ {
        use crate::containers::DenseId;
        (0..self.len()).map(Cfg::G::from_usize)
    }
    pub fn sorts(&self) -> &SortRegistry<Cfg::S, TRACK> {
        &self.sorts
    }
    pub fn sorts_mut(&mut self) -> &mut SortRegistry<Cfg::S, TRACK> {
        &mut self.sorts
    }
    pub fn ops(&self) -> &OpRegistry<Cfg::O, Cfg::S, TRACK> {
        &self.ops
    }

    pub fn ops_mut(&mut self) -> &mut OpRegistry<Cfg::O, Cfg::S, TRACK> {
        &mut self.ops
    }
    pub fn lits(&self) -> &LitValStore<L, Cfg::V, TRACK> {
        &self.lits
    }
    pub fn lits_mut(&mut self) -> &mut LitValStore<L, Cfg::V, TRACK> {
        &mut self.lits
    }

    pub fn rules(&self) -> &RuleRegistry<TRACK> {
        &self.rules
    }
    pub fn register_rule(&mut self, name: &str, lhs: &str, rhs: &str) -> crate::id::RuleId {
        self.rules.register(name, lhs, rhs)
    }

    pub fn axioms(&self) -> &AxiomRegistry<Cfg::G, TRACK> {
        &self.axioms
    }
    pub fn register_axiom(&mut self, name: &str, lhs: Cfg::G, rhs: Cfg::G) -> crate::id::AxiomId {
        self.axioms.register(name, lhs, rhs)
    }

    // Sorts
    pub fn intern_sort(&mut self, name: &str) -> Cfg::S {
        self.sorts.intern(name)
    }
    pub fn sort_name(&self, id: Cfg::S) -> &str {
        self.sorts.name(id)
    }

    pub fn register_op0(&mut self, name: &str, ret: Cfg::S) -> Cfg::O {
        self.ops.register(name, &[], ret)
    }
    pub fn register_op1(&mut self, name: &str, a: Cfg::S, ret: Cfg::S) -> Cfg::O {
        self.ops.register(name, &[a], ret)
    }
    pub fn register_op2(&mut self, name: &str, a: Cfg::S, b: Cfg::S, ret: Cfg::S) -> Cfg::O {
        self.ops.register(name, &[a, b], ret)
    }
    pub fn register_op3(
        &mut self,
        name: &str,
        a: Cfg::S,
        b: Cfg::S,
        c: Cfg::S,
        ret: Cfg::S,
    ) -> Cfg::O {
        self.ops.register(name, &[a, b, c], ret)
    }
    pub fn register_opn(&mut self, name: &str, args: &[Cfg::S], ret: Cfg::S) -> Cfg::O {
        self.ops.register(name, args, ret)
    }
    pub fn register_c(&mut self, name: &str, arg_sorts: [Cfg::S; 2], ret: Cfg::S) -> Cfg::O {
        self.ops.register_c(name, arg_sorts, ret)
    }
    /// Register an op from a resolved kind plus its non-algebraic metadata (constructor-ness,
    /// `:cost`, `:unextractable`). The surface layer's single registration entry point — see
    /// [`crate::registry::OpRegistry::register_kind_meta`].
    pub fn register_kind_meta(
        &mut self,
        name: &str,
        ret: Cfg::S,
        kind: crate::registry::OpKind<Cfg::S>,
        meta: crate::registry::OpMeta,
    ) -> Cfg::O {
        self.ops.register_kind_meta(name, ret, kind, meta)
    }
    pub fn register_a(
        &mut self,
        name: &str,
        arg: Cfg::S,
        ret: Cfg::S,
        dir: crate::registry::AssocDir,
    ) -> Cfg::O {
        self.ops.register_a(name, arg, ret, dir)
    }
    pub fn register_mset(&mut self, name: &str, arg: Cfg::S, ret: Cfg::S) -> Cfg::O {
        self.ops.register_mset(name, arg, ret)
    }
    pub fn register_set(&mut self, name: &str, arg: Cfg::S, ret: Cfg::S) -> Cfg::O {
        self.ops.register_set(name, arg, ret)
    }
    /// Register an op from a fully-resolved `OpKind` (the property-tag resolver in `sortcheck`).
    pub fn register_kind(&mut self, name: &str, ret: Cfg::S, kind: OpKind<Cfg::S>) -> Cfg::O {
        self.ops.register_kind(name, ret, kind)
    }
    /// Record `op`'s identity (unit) element node (`x ∘ e = x`; the unit drops from monomials).
    /// Called by the resolver in `sortcheck` after it builds the `:identity` term to a node.
    pub fn set_unit_node(&mut self, op: Cfg::O, unit: Cfg::G) {
        self.unit_node
            .try_insert(op, unit)
            .expect("unit/inverse-op map exhausted its index word");
    }
    /// The identity (unit) element node of `op`, or `None` if `op` has no declared identity.
    pub fn unit_node(&self, op: Cfg::O) -> Option<Cfg::G> {
        self.unit_node.get_by_key(&op).copied()
    }
    pub fn set_inverse_op(&mut self, op: Cfg::O, inv: Cfg::O) {
        self.inverse_op
            .try_insert(op, inv)
            .expect("unit/inverse-op map exhausted its index word");
    }
    /// The group inverse operator of `op` (`:inverse neg`), or `None` if none declared.
    pub fn inverse_op(&self, op: Cfg::O) -> Option<Cfg::O> {
        self.inverse_op.get_by_key(&op).copied()
    }

    /// Cancel inverse pairs in a canonical monomial of an op declared `:inverse inv`
    /// (the group law `x ∘ inv(x) = e` applied at pair level, Kapur §5.4's simplest
    /// instance): for each summand class `x`, if the class of the EXISTING node `inv(x)`
    /// is also a summand, matched pairs are removed; a self-inverse class
    /// (`find(inv(x)) == x`) cancels within its own count. Lookup-only (hash-cons probe of
    /// the inverse op's unary partition); removing a pair is sound because the pair equals
    /// the unit, which canonical monomials do not carry (`f({}) = e`). Returns whether the
    /// monomial changed; zeroed entries are dropped. This is NOT full group completion —
    /// no Gaussian elimination, and pairs whose inverse node was never built are not seen.
    /// Cancels `:inverse`-related summand pairs in place, at the configured
    /// multiplicity width. Purely subtractive — `rem_order(2)` and pairwise
    /// cancellation by the smaller of two counts — so no step can overflow.
    pub(crate) fn group_cancel_pairs(&self, inv: Cfg::O, m: &mut Vec<(Cfg::G, Cfg::M)>) -> bool {
        let zero = Cfg::M::ZERO;
        let mut changed = false;
        for i in 0..m.len() {
            let (x, xc) = (m[i].0, m[i].1);
            if xc == zero {
                continue;
            }
            let Some(inv_node) = self.nodes.plain1.probe(&inv, &[x]) else {
                continue;
            };
            let y = self.classes.find_const(inv_node);
            if y == x {
                // x is its own inverse: copies cancel pairwise (x ∘ x = e here).
                if xc
                    >= Cfg::M::ONE
                        .checked_add(Cfg::M::ONE)
                        .expect("2 fits every width")
                {
                    m[i].1 = xc.rem_order(2);
                    changed = true;
                }
            } else if let Ok(j) = m.binary_search_by(|p| p.0.cmp(&y)) {
                // The probe is one-directional (inv(y)'s node may not exist), so cancel
                // eagerly on first sight; the mirrored visit then finds a zeroed side.
                let k = m[i].1.min(m[j].1);
                if k > zero {
                    m[i].1 = m[i].1.saturating_sub(k);
                    m[j].1 = m[j].1.saturating_sub(k);
                    changed = true;
                }
            }
        }
        if changed {
            m.retain(|p| p.1 != zero);
        }
        changed
    }
    pub fn register_lit(&mut self, name: &str, ret: Cfg::S) -> Cfg::O {
        self.ops.register_lit(name, ret)
    }
    pub fn op(&self, name: &str) -> Option<Cfg::O> {
        self.ops.id_by_name(name)
    }
    pub fn intern_lit(&mut self, value: L) -> Cfg::V {
        self.lits.intern(value)
    }

    // ── Node operations ──

    /// Run a compiled query plan against this e-graph.
    pub fn run_query(
        &self,
        plan: &crate::schedule::QueryPlan<Cfg::O, Cfg::Index, L>,
    ) -> Vec<crate::ematch::Match<Cfg>> {
        let index = crate::index::IndexStore::build(self);
        let vindex = crate::index::VariantIndex::naive(&index);
        let empty: crate::resolve::GlobalCtx<Cfg::S, Cfg::G> = crate::resolve::GlobalCtx::new();
        crate::ematch::run_query(plan, self, &vindex, &empty)
    }

    /// Saturate: apply rules to fixpoint or until `limit` iterations.
    pub fn saturate<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        limit: usize,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
    ) -> crate::saturate::SatResult {
        crate::saturate::saturate(rules, self, model, limit, globals)
    }

    /// Semi-naive saturation via delta variants. The driver does not switch
    /// wholesale to naive; rules without safe delta coverage use a full-index match.
    pub fn saturate_semi<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        limit: usize,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
    ) -> crate::saturate::SatResult {
        crate::saturate::saturate_semi(rules, self, model, limit, globals)
    }

    /// Saturate under a full [`RunSpec`](crate::saturate::RunSpec) — budget, ruleset, and
    /// `:until` goal. The interpreter's `(run …)` path.
    pub fn saturate_spec<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        spec: &crate::saturate::RunSpec<Cfg::G>,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
    ) -> crate::saturate::SatResult {
        crate::saturate::saturate_spec(rules, self, model, spec, globals)
    }

    /// Semi-naive counterpart of [`saturate_spec`](Self::saturate_spec).
    pub fn saturate_semi_spec<
        M: crate::lit_model::LitModel<Value = L>,
        S: crate::DenseId + Copy,
    >(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        spec: &crate::saturate::RunSpec<Cfg::G>,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
    ) -> crate::saturate::SatResult {
        crate::saturate::saturate_semi_spec(rules, self, model, spec, globals)
    }

    /// [`saturate_spec`](Self::saturate_spec) over a caller-owned index scratch,
    /// so its span arenas survive the call. See
    /// [`saturate_spec_in`](crate::saturate::saturate_spec_in).
    pub fn saturate_spec_in<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        spec: &crate::saturate::RunSpec<Cfg::G>,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
        scratch: &mut crate::index::IndexScratch<Cfg>,
    ) -> crate::saturate::SatResult {
        crate::saturate::saturate_spec_in(rules, self, model, spec, globals, scratch)
    }

    /// Semi-naive counterpart of [`saturate_spec_in`](Self::saturate_spec_in).
    pub fn saturate_semi_spec_in<
        M: crate::lit_model::LitModel<Value = L>,
        S: crate::DenseId + Copy,
    >(
        &mut self,
        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
        model: &M,
        spec: &crate::saturate::RunSpec<Cfg::G>,
        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
        scratch: &mut crate::index::IndexScratch<Cfg>,
    ) -> crate::saturate::SatResult {
        // Semi-naive is the one consumer of the merge-membership delta (see
        // `merge_in_classes`); the flag keeps the per-merge ring walks off
        // everywhere else.
        self.track_merge_members = true;
        let r = crate::saturate::saturate_semi_spec_in(rules, self, model, spec, globals, scratch);
        self.track_merge_members = false;
        r
    }

    /// The number of distinct e-classes over the current node set. A scan, not a maintained
    /// counter: `(print-size)` / `(print-stats)` ask for it a handful of times per program.
    pub fn class_count(&self) -> usize {
        let n = self.len();
        let mut seen = vec![false; n];
        let mut count = 0;
        for id in self.node_ids() {
            let r = self.find_const(id).to_usize();
            if !seen[r] {
                seen[r] = true;
                count += 1;
            }
        }
        count
    }

    /// Node counts per operator, indexed by op id (ops with no nodes read 0).
    pub fn op_node_counts(&self) -> Vec<usize> {
        let mut counts = vec![0usize; self.ops.meta_table().len()];
        for id in self.node_ids() {
            let op = self.node_op(id).to_usize();
            if op < counts.len() {
                counts[op] += 1;
            }
        }
        counts
    }

    pub fn find(&mut self, x: Cfg::G) -> Cfg::G {
        self.classes.find(x)
    }

    pub fn find_const(&self, x: Cfg::G) -> Cfg::G {
        self.classes.find_const(x)
    }

    pub fn add(&mut self, op: Cfg::O, children: &[Cfg::G]) -> Cfg::G {
        #[cfg(debug_assertions)]
        {
            let info = self.ops.info(op);
            match &info.kind {
                OpKind::Normal { arg_sorts } => {
                    debug_assert_eq!(
                        children.len(),
                        arg_sorts.len(),
                        "operator '{}' expects {} children, got {}",
                        info.name,
                        arg_sorts.len(),
                        children.len()
                    );
                    for (i, (&c, &s)) in children.iter().zip(arg_sorts.iter()).enumerate() {
                        let got = self.node_sort(c);
                        debug_assert_eq!(
                            got,
                            s,
                            "operator '{}' expected sort '{}' at position {}, got '{}'",
                            info.name,
                            self.sorts.name(s),
                            i,
                            self.sorts.name(got)
                        );
                    }
                }
                OpKind::Commutative { arg_sorts } => {
                    debug_assert_eq!(
                        children.len(),
                        2,
                        "operator '{}' (commutative) expects 2 children, got {}",
                        info.name,
                        children.len()
                    );
                    for (i, (&c, &s)) in children.iter().zip(arg_sorts.iter()).enumerate() {
                        let got = self.node_sort(c);
                        debug_assert_eq!(
                            got,
                            s,
                            "operator '{}' expected sort '{}' at position {}, got '{}'",
                            info.name,
                            self.sorts.name(s),
                            i,
                            self.sorts.name(got)
                        );
                    }
                }
                OpKind::A { arg_sort, .. }
                | OpKind::MSet { arg_sort, .. }
                | OpKind::Set { arg_sort, .. } => {
                    for (i, &c) in children.iter().enumerate() {
                        let got = self.node_sort(c);
                        debug_assert_eq!(
                            got,
                            *arg_sort,
                            "operator '{}' expected sort '{}' at position {}, got '{}'",
                            info.name,
                            self.sorts.name(*arg_sort),
                            i,
                            self.sorts.name(got)
                        );
                    }
                }
                OpKind::Lit => {}
            }
        }
        self.g_buf.clear();
        self.g_buf
            .extend(children.iter().map(|&c| self.classes.find(c)));

        // Flatten nested same-op AC children (associativity, `WF_flat`, design §6c): splice
        // any child whose class is a pure same-op sum, keyed on the class's canonical
        // summand form (atomic-aware), so `+(+(a,b), c)` becomes `+(a,b,c)`. An atomic child
        // (e.g. `c` used as `neg`'s child in §5b) is kept as a summand. BOTH completion
        // representations flatten; otherwise `(Or (Or x y) z)` and `(Or x y z)`
        // differ for Set (ACI) ops with completion off. See set_flatten_build.egg.
        if matches!(
            self.ops.info(op).kind,
            OpKind::MSet { .. } | OpKind::Set { .. }
        ) {
            self.flatten_ac_children(op);
        }

        // The A-only (`Seq`) counterpart of the same law. Every associative spelling
        // (`:assoc-left`, `:assoc-right`, and `:assoc`) currently has the same flattened
        // sequence semantics; `AssocDir` is retained registration metadata. Only the merge
        // step differs from AC: an order-preserving splice here, because associativity permits
        // re-association but not reordering.
        if matches!(self.ops.info(op).kind, OpKind::A { .. }) {
            self.flatten_seq_children(op);
        }

        // Canonization must *establish* the op's algebraic normal form at build time (not defer
        // it to completion): coalesce/dedup, drop the identity's unit class, apply the count clamp
        // (nilpotent mod-n), and resolve a degenerate arity. Degeneracy is an equality, so the
        // last step returns an *existing* class id instead of a fresh node:
        //   - empty multiset  ⇒ the term IS the unit  (`xor(a,a) → {} = e`)
        //   - single mult-1    ⇒ the term IS that child (`+(a, e) → {a} = a`, `and(a,a) → {a} = a`)
        // These hold with completion off; completion only adds the cross-rule (superposition)
        // consequences. `find_unit`/degeneracy read `unit_node`, resolved at registration.
        // The constructor bit is stamped at creation, not written back after:
        // `set_node_flag` would have to resolve the routing table and dispatch
        // on the node kind again, for a node the store has just built.
        let node_flags = if self.ops.info(op).is_constructor {
            crate::node_types::FLAG_CONSTRUCTOR
        } else {
            0
        };
        let result = match self.ops.info(op).kind {
            OpKind::MSet { .. } => {
                // Only the two completion arms read the identity, and looking it
                // up is a hash probe of the semi-persistent unit map — a cost the
                // plain-op path used to pay on every `add`.
                let unit = self.unit_node(op);
                self.g_buf.sort_by_key(|id| id.to_usize());
                self.mset_buf.clear();
                for &id in &self.g_buf {
                    if let Some(last) = self.mset_buf.last_mut()
                        && Cfg::mset_child_merge(last, id)
                    {
                        continue;
                    }
                    self.mset_buf.push(Cfg::mset_child_single(id));
                }
                // Identity: drop the unit's class (`+(a, e) → {a}`).
                if let Some(u) = unit {
                    let uc = self.classes.find_const(u);
                    self.mset_buf.retain(|c| Cfg::mset_child_id(c) != uc);
                }
                // Nilpotent clamp: reduce each multiplicity mod n, drop zeros (`xor(a,a) → {}`).
                // Routed through the SINGLE source of the mod-n law, `MSetCanon::clamp_multiset`
                // (also used by the recanonize path), so the two paths cannot drift. `Cfg::C` is
                // concretely `(G, Multiplicity)` but opaque to generic code, so we convert the
                // buffer through the config accessors around the shared call. Nilpotent-only, so
                // the conversion never touches the common plain-AC / idempotent build.
                if let crate::registry::Clamp::Nilpotent { order } = self.op_clamp_kind(op) {
                    // prod-parity: `clamp_multiset` operates on `Pair<G, Mult>`
                    // (was `(G, Mult)`; Verus can't impl `Tagged` for a tuple).
                    // The pair carries `Cfg::M` directly — no narrowing round trip
                    // through a fixed width, which is what used to truncate here.
                    let mut tuples: Vec<crate::containers::Pair<Cfg::G, Cfg::M>> = self
                        .mset_buf
                        .iter()
                        .map(|c| crate::containers::Pair {
                            a: Cfg::mset_child_id(c),
                            b: Cfg::mset_child_mult(c),
                        })
                        .collect();
                    MSetCanon::clamp_multiset(&mut tuples, MSetClamp::Nilpotent { order });
                    self.mset_buf.clear();
                    self.mset_buf
                        .extend(tuples.iter().map(|p| Cfg::mset_child_with_mult(p.a, p.b)));
                }
                // Group inverse-pair cancellation (`x ∘ inv(x) = e`): summand pairs related
                // by the op's declared `:inverse` cancel at build, like the unit drop. Rare
                // (inverse ops only), so the tuple conversion is off the common path.
                if let Some(inv) = self.inverse_op(op) {
                    let mut tuples: Vec<(Cfg::G, Cfg::M)> = self
                        .mset_buf
                        .iter()
                        .map(|c| (Cfg::mset_child_id(c), Cfg::mset_child_mult(c)))
                        .collect();
                    if self.group_cancel_pairs(inv, &mut tuples) {
                        self.mset_buf.clear();
                        self.mset_buf.extend(
                            tuples
                                .iter()
                                .map(|(g, m)| Cfg::mset_child_with_mult(*g, *m)),
                        );
                    }
                }
                // Degenerate arity ⇒ an existing class, not a fresh node. An empty monomial is the
                // unit; a single mult-1 summand is that summand's class. Empty *without* a declared
                // unit is an API-contract violation (the surface layer rejects it at sortcheck):
                // the empty monomial names nothing in a semigroup, so minting a node for it would
                // put a meaningless term in the graph — panic in ALL builds, like the other
                // registration invariants.
                match self.mset_buf.len() {
                    0 => match unit {
                        Some(u) => return u,
                        None => panic!(
                            "zero-child MSet term without a declared identity — \
                             the empty monomial has no algebraic meaning for a semigroup op"
                        ),
                    },
                    1 if Cfg::mset_child_mult(&self.mset_buf[0]) == Cfg::M::ONE => {
                        return self.classes.find(Cfg::mset_child_id(&self.mset_buf[0]));
                    }
                    _ => self.nodes.add_mset(op, &self.mset_buf, node_flags),
                }
            }
            OpKind::Set { .. } => {
                let unit = self.unit_node(op);
                self.g_buf.sort_by_key(|id| id.to_usize());
                self.g_buf.dedup();
                // Identity: drop the unit's class (`and(a, unit) → {a}`).
                if let Some(u) = unit {
                    let uc = self.classes.find_const(u);
                    self.g_buf.retain(|&g| g != uc);
                }
                // Degenerate arity ⇒ an existing class (idempotent has no nilpotent clamp, so a
                // Set monomial only reaches {} via identity-drop, and size-1 via dedup/drop).
                // Empty without a declared unit is an API-contract violation — panic (see the
                // MSet counterpart above).
                match self.g_buf.len() {
                    0 => match unit {
                        Some(u) => return u,
                        None => panic!(
                            "zero-child Set term without a declared identity — \
                             the empty monomial has no algebraic meaning for a semigroup op"
                        ),
                    },
                    1 => return self.classes.find(self.g_buf[0]),
                    _ => self.nodes.add_set(op, &self.g_buf, node_flags),
                }
            }
            OpKind::A { .. } => {
                // Degenerate arity ⇒ an existing class, the A-only counterpart of the MSet/Set
                // degeneracy above: a one-element sequence IS its element (`seq(x) = x`),
                // so return that child's class instead of minting a node for it. There is
                // no empty case to resolve — an A-only op cannot declare `:identity` (the
                // property resolver rejects `:identity` without `:comm`, `sortcheck.rs`),
                // so the empty sequence names nothing in the algebra. Sortcheck already
                // rejects a zero-argument A application; reaching here is an API-contract
                // violation, and panics in ALL builds like the MSet/Set counterparts.
                match self.g_buf.len() {
                    0 => panic!(
                        "zero-child A term — an A-only operator has no identity, so the \
                         empty sequence has no algebraic meaning for a semigroup op"
                    ),
                    1 => return self.classes.find(self.g_buf[0]),
                    _ => self.nodes.add(op, &self.g_buf, &self.ops, node_flags),
                }
            }
            _ => self.nodes.add(op, &self.g_buf, &self.ops, node_flags),
        };

        let id = self.register_if_fresh(result, op);
        if result.is_fresh() {
            match self.ops.info(op).kind {
                OpKind::MSet { .. } => {
                    for c in &self.mset_buf {
                        let child = Cfg::mset_child_id(c);
                        if let Some(repr) = self.classes.repr_id(child) {
                            self.classes.add_use(repr, id);
                        }
                    }
                }
                _ => {
                    for &child in &self.g_buf {
                        if let Some(repr) = self.classes.repr_id(child) {
                            self.classes.add_use(repr, id);
                        }
                    }
                }
            }
        }
        id
    }

    pub fn add_lit(&mut self, op: Cfg::O, lit: Cfg::V) -> Cfg::G {
        let result = self.nodes.add_lit(op, lit, 0);
        self.register_if_fresh(result, op)
    }

    /// Build a *ground* checked term (a literal or a constructor applied to ground args) into a
    /// node, returning its id. Mirrors the interpreter's `build_cterm` for the ground cases; it
    /// has no access to globals, so a `CTerm::Global` is unreachable here (a unit is always
    /// ground) and panics. Used by the property-tag resolver to materialize an op's `:identity`
    /// unit at registration.
    pub fn build_ground_cterm(
        &mut self,
        ct: &crate::sortcheck::CTerm<Cfg::O, Cfg::S, L>,
    ) -> Cfg::G {
        match ct {
            crate::sortcheck::CTerm::Lit(val, sort) => {
                let lit_op = self
                    .ops
                    .lit_op_for_sort(*sort)
                    .expect("no lit op for identity's sort");
                let vid = self.lits.intern(val.clone());
                self.add_lit(lit_op, vid)
            }
            crate::sortcheck::CTerm::App { op, children, .. } => {
                let child_ids: Vec<Cfg::G> = children
                    .iter()
                    .map(|c| self.build_ground_cterm(c))
                    .collect();
                self.add(*op, &child_ids)
            }
            crate::sortcheck::CTerm::Global(..) => {
                panic!("identity unit must be a ground term, not a global reference")
            }
        }
    }

    /// Fill `buf` with `node`'s monomial for `monomial_cmp`: its canonical AC child
    /// multiset if it is an AC node, else the singleton `{node}` (a non-AC node is a
    /// size-1 monomial, §9b). Children are `find`-canonicalized and coalesced.
    pub(crate) fn node_monomial_into(&self, node: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) {
        buf.clear();
        match self.node_ref(node) {
            NodeRef::MSet(_) => {
                // Children find-canonicalized, then sorted + coalesced in place in the
                // destination (same form as MSetCanon), with no intermediate Vec.
                self.for_each_child(node, |g, mult| {
                    buf.push((self.classes.find_const(g), mult));
                });
                buf.sort_by_key(|p| p.0);
                let mut w = 0usize;
                for r in 1..buf.len() {
                    if buf[r].0 == buf[w].0 {
                        // Coalescing after find-canonicalization is the one step here
                        // that grows a multiplicity, so it is the one that can exceed
                        // the configured width. Detected, not wrapped: a wrapped sum
                        // would shrink the monomial — to zero at exactly the wrong
                        // values — and the caller's clamps would then drop the summand,
                        // making the e-graph assert an equality that does not hold.
                        buf[w].1 = buf[w].1.checked_add(buf[r].1).expect(
                            "monomial coalescing overflowed EGraphConfig::M; \
                             the configured multiplicity width is too narrow for this e-graph",
                        );
                    } else {
                        w += 1;
                        buf[w] = buf[r];
                    }
                }
                if !buf.is_empty() {
                    buf.truncate(w + 1);
                }
            }
            NodeRef::Set(_) => {
                // Set semantics: find-canonicalize, sort, DEDUP — multiplicity stays 1
                // (two summands whose classes merged count once, the idempotent join).
                // This is the ACI monomial, same form as SetCanon.
                self.for_each_child(node, |g, _| {
                    buf.push((self.classes.find_const(g), Cfg::M::ONE));
                });
                buf.sort_by_key(|p| p.0);
                buf.dedup_by_key(|p| p.0);
            }
            _ => {
                buf.push((self.classes.find_const(node), Cfg::M::ONE));
            }
        }
        // No clamp / unit-drop here: canonization (`add`, `recanonize_node`) already established
        // the op's algebraic normal form (nilpotent mod-n, identity unit-drop) in the stored node,
        // and `cc_round` only runs after `rebuild_congruence` recanonicalizes every node. So a
        // stored MSet/Set node's children are already the canonical monomial; reading them
        // back is enough. Unit dropping on the recanonize path is enforced by
        // `CanonMode.unit` plus the became-a-unit sweep in `rebuild_congruence`;
        // completion does not reapply canonization.
    }

    /// The completion column of `node`'s op (its position in the registry `completion_ops`
    /// array), or `None` if `node`'s op is not a completion (MSet/Set) op.
    fn completion_column(&self, node: Cfg::G) -> Option<usize> {
        self.ops.completion_column(self.node_op(node))
    }

    /// The op's registry count `Clamp` (`None` / `Idempotent` / `Nilpotent`). The build/canonize
    /// path reads this directly (the algebraic normal form), where `op_clamp`'s `CompletionClamp`
    /// projection is completion-shaped. `None` for a non-AC op.
    fn op_clamp_kind(&self, op: Cfg::O) -> crate::registry::Clamp {
        match self.ops.info(op).kind {
            OpKind::MSet { clamp, .. } | OpKind::Set { clamp, .. } => clamp,
            _ => crate::registry::Clamp::None,
        }
    }

    /// Whether the op is declared cancelative (`:cancellative`, or implied by `:inverse` —
    /// groups are cancelative, Kapur §5.4). Drives the §5 cancel-closure inferences.
    fn op_cancellative(&self, op: Cfg::O) -> bool {
        match self.ops.info(op).kind {
            OpKind::MSet { cancellative, .. } | OpKind::Set { cancellative, .. } => cancellative,
            _ => false,
        }
    }

    /// The normalization clamp for an op's completion monomials: unbounded (MSet), clamp-to-1
    /// (Set idempotent, ACI), or mod-n (nilpotent — stored MSet). Determines how reducts and normal forms
    /// are reduced (design "three independent axes").
    pub(crate) fn op_clamp(&self, op: Cfg::O) -> CompletionClamp {
        use crate::registry::Clamp;
        match self.ops.info(op).kind {
            // Nilpotent is stored MSet (keeps multiplicities); its clamp is read here.
            OpKind::MSet {
                clamp: Clamp::Nilpotent { order },
                ..
            } => CompletionClamp::Nilpotent { order },
            OpKind::MSet { .. } => CompletionClamp::Multiset,
            OpKind::Set {
                clamp: Clamp::Idempotent,
                ..
            } => CompletionClamp::Idempotent,
            // A Set with any other clamp is never constructed (resolver invariant); treat as ACI.
            OpKind::Set { .. } => CompletionClamp::Idempotent,
            _ => CompletionClamp::Multiset, // non-completion op; never reached in the round
        }
    }

    /// Fill `buf` with the completion rule right-hand side for the class of `node`: the
    /// **empty monomial** if the class is `node`'s op's identity (unit) class, the size-1
    /// monomial `{find(node)}` if the class is `atomic` (referenced as a child), else
    /// the monomial of the class's stored min-monomial for `node`'s op column (§9a). Reads the
    /// per-class pool slot; O(1) plus the monomial read. Returns `false` if `node` has no class
    /// (or, in the non-atomic case, no stored monomial for its op — a genuine rule always has
    /// one, so this only guards the degenerate case).
    ///
    /// The unit case is Kapur's `f({}) = e` convention (§2.4) and it is load-bearing: a rule
    /// whose class is the identity must rewrite `f(M) → f({})`, NOT `f(M) → {e}`. With the
    /// atom form, every monomial built from the RHS — superposition reducts, axiom critical
    /// pairs, normalization steps — would carry the unit as a summand that `normalize_*`
    /// (which has no `f(x,e) = x` law) can never remove and that no stored node matches
    /// (canonization unit-drops). The empty-monomial form folds the identity law into the
    /// representation, so rewriting can never insert a unit anywhere.
    pub(crate) fn class_rhs_into(&self, node: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) -> bool {
        let cls = self.classes.find_const(node);
        let Some(repr) = self.classes.repr_id(cls) else {
            return false;
        };
        if self
            .unit_node(self.node_op(node))
            .is_some_and(|u| self.classes.find_const(u) == cls)
        {
            buf.clear();
            return true;
        }
        if self.classes.atomic(repr) {
            buf.clear();
            buf.push((cls, Cfg::M::ONE));
            return true;
        }
        let Some(col) = self.completion_column(node) else {
            return false;
        };
        let Some(min) = self.classes.min_monomial(repr, col) else {
            return false;
        };
        self.node_monomial_into(min, buf);
        true
    }

    /// Lookup-only resolution of a canonical monomial to the class of an existing node of
    /// `op`: degenerate monomials resolve structurally (empty → the op's unit class, size-1
    /// mult-1 → that child's class); otherwise the op's partition is probed by hash-cons and
    /// the found node's class returned. `None` if no such node exists. Read-only diagnostic
    /// helper for the axiom-CP joinability checker (`ac_invariants`); never mutates.
    pub(crate) fn resolve_monomial_class(
        &self,
        op: Cfg::O,
        m: &[(Cfg::G, Cfg::M)],
    ) -> Option<Cfg::G> {
        if m.is_empty() {
            return self.unit_node(op).map(|u| self.classes.find_const(u));
        }
        if m.len() == 1 && m[0].1 == Cfg::M::ONE {
            return Some(self.classes.find_const(m[0].0));
        }
        let node = match self.ops.info(op).kind {
            OpKind::MSet { .. } => {
                let elems: Vec<Cfg::C> = m
                    .iter()
                    .map(|&(g, mult)| Cfg::mset_child_with_mult(g, mult))
                    .collect();
                self.nodes.mset.probe(op, &elems)
            }
            OpKind::Set { .. } => {
                let elems: Vec<Cfg::G> = m.iter().map(|&(g, _)| g).collect();
                self.nodes.set.probe(op, &elems)
            }
            _ => None,
        };
        node.map(|n| self.classes.find_const(n))
    }

    /// After a merge, fold the absorbed class's per-class AC data into the survivor's,
    /// per completion column: keep the `monomial_cmp`-least min-monomial node for each op, and
    /// OR-in the `atomic` flag (§9a). O(nb_completion) columns, each O(1) plus a monomial read,
    /// into reusable buffers. Done here, not in `EClasses`, because the comparison needs node
    /// (AC-children) access and the op→column map. Best-effort under merge-cascade staleness;
    /// completion's read-time orientation guard makes that safe (§9b).
    fn fold_min_monomial(
        &mut self,
        survivor: Cfg::G,
        absorbed_min_row: Option<<Cfg::G as DenseId>::Index>,
        absorbed_atomic: bool,
    ) {
        let surv_repr = match self.classes.repr_id(self.classes.find_const(survivor)) {
            Some(r) => r,
            None => return,
        };
        if absorbed_atomic {
            self.classes.set_atomic(surv_repr);
        }
        let mut a = std::mem::take(&mut self.cmp_buf_a);
        let mut b = std::mem::take(&mut self.cmp_buf_b);
        for col in 0..self.classes.min_width() {
            let Some(absorbed_min) = self.classes.min_monomial_at_row(absorbed_min_row, col) else {
                continue; // absorbed class has no monomial for this op
            };
            match self.classes.min_monomial(surv_repr, col) {
                None => {
                    // survivor had no monomial for this op; take the absorbed one.
                    self.classes.set_min_monomial(surv_repr, col, absorbed_min);
                }
                Some(surv_min) if surv_min != absorbed_min => {
                    self.node_monomial_into(surv_min, &mut a);
                    self.node_monomial_into(absorbed_min, &mut b);
                    if crate::multiset::monomial_cmp(&b, &a) == std::cmp::Ordering::Less {
                        self.classes.set_min_monomial(surv_repr, col, absorbed_min);
                    }
                }
                Some(_) => {} // equal; nothing to do
            }
        }
        self.cmp_buf_a = a;
        self.cmp_buf_b = b;
    }

    pub fn merge(&mut self, a: Cfg::G, b: Cfg::G) -> Option<(Cfg::G, Cfg::G)> {
        debug_assert_eq!(
            self.node_sort(a),
            self.node_sort(b),
            "cannot merge e-classes of different sorts: '{}' has sort '{}', '{}' has sort '{}'",
            self.node_op_name(a),
            self.sorts.name(self.node_sort(a)),
            self.node_op_name(b),
            self.sorts.name(self.node_sort(b))
        );
        debug_assert!(
            !self.sorts.is_concrete(self.node_sort(a)),
            "cannot merge concrete sort '{}' e-classes",
            self.sorts.name(self.node_sort(a))
        );
        let m = self.merge_in_classes(a, b, None)?;
        self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
        self.worklist.push((m.absorbed_uses, m.survivor));
        Some((m.survivor, m.absorbed))
    }

    /// Class merge, recording the absorbed side's member nodes in the
    /// semi-naive touched log when `track_merge_members` is set.
    ///
    /// A merge can create matches without changing any node's canonical form:
    /// when the surviving representative is the id the parents already store,
    /// nothing recanonicalizes, yet nodes of the absorbed side changed class.
    /// The variant decomposition's premise — every new match shows up as a new
    /// or re-canonicalized tuple in some atom's relation — then needs the
    /// membership change itself in the delta, and the absorbed members are
    /// exactly that change: a new match either recanonicalizes a parent
    /// (already touched) or connects through a node whose class assignment
    /// moved. Collection walks both rings before the merge splices them,
    /// because the survivor is not known until the union decides; the flag
    /// keeps the walk off outside semi-naive saturation, where nothing
    /// consumes the log.
    fn merge_in_classes(
        &mut self,
        a: Cfg::G,
        b: Cfg::G,
        just: Option<Justification<Cfg::G>>,
    ) -> Option<crate::classes::MergeInfo<Cfg::G, Cfg::UL>> {
        let ra = self.classes.find_const(a);
        let rb = self.classes.find_const(b);
        if ra == rb {
            return None;
        }
        // Survivor policy (--union-by): `Rank` leaves the choice to the
        // union-find; the directed criteria keep the heavier side, so the
        // absorbed side is the cheap one and is known before the union.
        let prefer_a = match self.union_by {
            UnionBy::Rank => None,
            _ => Some(self.union_weight(ra) >= self.union_weight(rb)),
        };
        // Semi-naive merge tracking: collect the absorbed side's members
        // before the splice. Under a directed policy only the (small)
        // absorbed ring is walked; under rank the survivor is unknown until
        // the union decides, so both rings are collected and the absorbed
        // one pushed after.
        let pre = if self.track_merge_members {
            match prefer_a {
                Some(pa) => {
                    let absorbed_repr = if pa { rb } else { ra };
                    let v: Vec<Cfg::G> = self.classes.iter_class(absorbed_repr).collect();
                    Some((absorbed_repr, v, None))
                }
                None => {
                    let va: Vec<Cfg::G> = self.classes.iter_class(ra).collect();
                    let vb: Vec<Cfg::G> = self.classes.iter_class(rb).collect();
                    Some((ra, va, Some(vb)))
                }
            }
        } else {
            None
        };
        let m = match (prefer_a, just) {
            (None, None) => self.classes.merge(a, b),
            (None, Some(j)) => self.classes.merge_justified(a, b, j),
            (Some(pa), None) => self.classes.merge_directed_with(a, b, pa),
            (Some(pa), Some(j)) => self.classes.merge_justified_directed_with(a, b, pa, j),
        }?;
        if let Some((r0, v0, v1)) = pre {
            let absorbed = match v1 {
                None => v0,
                Some(v1) => {
                    if m.absorbed == r0 {
                        v0
                    } else {
                        v1
                    }
                }
            };
            self.touched.extend(absorbed);
        }
        Some(m)
    }

    pub fn merge_justified(
        &mut self,
        a: Cfg::G,
        b: Cfg::G,
        just: Justification<Cfg::G>,
    ) -> Option<(Cfg::G, Cfg::G)> {
        debug_assert_eq!(
            self.node_sort(a),
            self.node_sort(b),
            "cannot merge e-classes of different sorts: '{}' has sort '{}', '{}' has sort '{}'",
            self.node_op_name(a),
            self.sorts.name(self.node_sort(a)),
            self.node_op_name(b),
            self.sorts.name(self.node_sort(b))
        );
        debug_assert!(
            !self.sorts.is_concrete(self.node_sort(a)),
            "cannot merge concrete sort '{}' e-classes",
            self.sorts.name(self.node_sort(a))
        );
        let m = self.merge_in_classes(a, b, Some(just))?;
        self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
        self.worklist.push((m.absorbed_uses, m.survivor));
        Some((m.survivor, m.absorbed))
    }

    pub fn explain(&self, a: Cfg::G, b: Cfg::G, buf: &mut ProofBuf<Cfg::G>) -> bool {
        self.classes.explain(a, b, buf)
    }

    /// Write a deterministic, line-oriented proof-path record for every e-node.
    ///
    /// Each record names the node's current operator, children, representative,
    /// proof-tree LCA, and every justified edge from the node to that
    /// representative. One Euler-tour table is built in O(n), then each LCA is
    /// queried in O(1); writing the proof paths costs O(number of emitted
    /// steps). Representative records have an empty reflexive proof.
    ///
    /// The dump is available only when `PROOFS = true`. Any successful
    /// justified merge or restore invalidates the table, so the complete build
    /// and write happen under this single immutable borrow.
    pub fn dump_all_proofs<W: std::io::Write>(
        &self,
        mut out: W,
    ) -> std::io::Result<ProofDumpStats> {
        if !PROOFS {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proof dump requires an EGraph with PROOFS=true",
            ));
        }

        let lca = {
            let parents = self.classes.proof_parent().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "PROOFS=true e-graph has no proof-parent forest",
                )
            })?;
            crate::lca::LcaTable::build(parents, self.len())
        };

        writeln!(out, "# semi-persistent-proof-dump v1")?;
        writeln!(
            out,
            "# each term record proves node == representative; ids are decimal"
        )?;
        writeln!(out, "terms {}", self.len())?;

        let mut stats = ProofDumpStats::default();
        let mut buf = ProofBuf::new();
        let mut children = Vec::new();

        for node in self.node_ids() {
            let representative = self.find_const(node);
            let ancestor = lca.lca(node, representative).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "proof forest has no LCA for equivalent nodes {} and {}",
                        node.to_usize(),
                        representative.to_usize()
                    ),
                )
            })?;

            buf.clear();
            if !self
                .classes
                .explain_with_lca(node, representative, ancestor, &mut buf)
            {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "LCA {} is not on both proof paths for nodes {} and {}",
                        ancestor.to_usize(),
                        node.to_usize(),
                        representative.to_usize()
                    ),
                ));
            }

            write!(
                out,
                "term {} representative {} op {:?}",
                node.to_usize(),
                representative.to_usize(),
                self.node_op_name(node)
            )?;
            match self.get_lit_val(node) {
                Some(value) => write!(out, " literal {:?}", value.to_string())?,
                None => write!(out, " literal -")?,
            }
            children.clear();
            self.for_each_child(node, |child, mult| {
                children.push((child, mult.to_u64()));
            });
            write!(out, " children [")?;
            for (i, (child, mult)) in children.iter().enumerate() {
                if i > 0 {
                    write!(out, ",")?;
                }
                write!(out, "{}:{}", child.to_usize(), mult)?;
            }
            writeln!(out, "]")?;

            writeln!(
                out,
                "proof lca {} steps {}",
                ancestor.to_usize(),
                buf.steps.len()
            )?;
            for &(from, to, justification) in &buf.steps {
                write!(out, "step {} {} ", from.to_usize(), to.to_usize())?;
                self.write_proof_dump_justification(&mut out, justification)?;
                writeln!(out)?;
            }
            writeln!(out, "end")?;

            stats.terms += 1;
            stats.nontrivial_proofs += usize::from(!buf.steps.is_empty());
            stats.steps += buf.steps.len();
        }

        writeln!(
            out,
            "summary terms {} nontrivial {} steps {}",
            stats.terms, stats.nontrivial_proofs, stats.steps
        )?;
        Ok(stats)
    }

    fn write_proof_dump_justification<W: std::io::Write>(
        &self,
        out: &mut W,
        justification: Justification<Cfg::G>,
    ) -> std::io::Result<()> {
        match justification {
            Justification::Filler => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "proof path contains a filler justification",
            )),
            Justification::Rewrite { rule_id } => {
                write!(out, "rewrite rule={}", rule_id.to_usize())
            }
            Justification::Congruence { node_a, node_b } => write!(
                out,
                "congruence nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
            Justification::Axiom { axiom_id } => {
                write!(out, "axiom id={}", axiom_id.to_usize())
            }
            Justification::ACSuperposition { node_a, node_b } => write!(
                out,
                "ac-superposition nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
            Justification::ACInterReduction { node_a, node_b } => write!(
                out,
                "ac-inter-reduction nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
            Justification::ACAxiomCP { node_a, node_b } => write!(
                out,
                "ac-axiom-cp nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
            Justification::Cancellative { node_a, node_b } => write!(
                out,
                "cancellative nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
            Justification::InverseCancel { node_a, node_b } => write!(
                out,
                "inverse-cancel nodes={},{}",
                node_a.to_usize(),
                node_b.to_usize()
            ),
        }
    }

    /// Deep explanation: expand Congruence justifications into child-pair proofs.
    /// Appends all steps (including recursive child explanations) to `buf.steps`.
    /// Uses an iterative worklist — no recursion.
    ///
    /// For C/AC/ACI nodes, children are matched by canonical representative
    /// (group-by-find), not by position. This avoids combinatorial search.
    pub fn explain_deep(&self, a: Cfg::G, b: Cfg::G, buf: &mut ProofBuf<Cfg::G>) -> bool {
        if !self.classes.explain(a, b, buf) {
            return false;
        }

        let mut ac_scratch: Vec<Cfg::C> = Vec::new();
        let mut i = 0;
        while i < buf.steps.len() {
            if let Justification::Congruence { node_a, node_b } = buf.steps[i].2 {
                buf.children_a.clear();
                buf.children_b.clear();
                self.collect_original_children(node_a, &mut buf.children_a, &mut ac_scratch);
                self.collect_original_children(node_b, &mut buf.children_b, &mut ac_scratch);

                let is_ordered = matches!(
                    self.node_ref(node_a),
                    NodeRef::Plain1(_)
                        | NodeRef::Plain2(_)
                        | NodeRef::Plain3(_)
                        | NodeRef::PlainN(_)
                        | NodeRef::Seq(_)
                );

                if is_ordered {
                    let n = buf.children_a.len().min(buf.children_b.len());
                    for j in 0..n {
                        let ca = buf.children_a[j];
                        let cb = buf.children_b[j];
                        if ca != cb && self.classes.find_const(ca) == self.classes.find_const(cb) {
                            self.classes.explain(ca, cb, buf);
                        }
                    }
                } else {
                    self.explain_grouped(buf);
                }
            }
            i += 1;
        }
        true
    }

    fn explain_grouped(&self, buf: &mut ProofBuf<Cfg::G>) {
        buf.group_a.clear();
        buf.group_a.extend_from_slice(&buf.children_a);
        buf.group_a
            .sort_by_key(|c| self.classes.find_const(*c).to_usize());

        buf.group_b.clear();
        buf.group_b.extend_from_slice(&buf.children_b);
        buf.group_b
            .sort_by_key(|c| self.classes.find_const(*c).to_usize());

        buf.children_a.clear();
        let mut ia = 0;
        let mut ib = 0;
        while ia < buf.group_a.len() && ib < buf.group_b.len() {
            let ra = self.classes.find_const(buf.group_a[ia]).to_usize();
            let rb = self.classes.find_const(buf.group_b[ib]).to_usize();
            if ra < rb {
                ia += 1;
            } else if ra > rb {
                ib += 1;
            } else {
                let ca = buf.group_a[ia];
                let cb = buf.group_b[ib];
                if ca != cb {
                    buf.children_a.push(ca);
                    buf.children_a.push(cb);
                }
                ia += 1;
                ib += 1;
            }
        }

        let mut k = 0;
        while k < buf.children_a.len() {
            let ca = buf.children_a[k];
            let cb = buf.children_a[k + 1];
            self.classes.explain(ca, cb, buf);
            k += 2;
        }
    }

    fn collect_original_children(
        &self,
        id: Cfg::G,
        out: &mut Vec<Cfg::G>,
        ac_scratch: &mut Vec<Cfg::C>,
    ) {
        ac_scratch.clear();
        if self.nodes.original_children(id, out, ac_scratch) {
            for c in ac_scratch.iter() {
                out.push(Cfg::mset_child_id(c));
            }
            return;
        }
        self.for_each_child(id, |child, _mult| out.push(child));
    }

    // -----------------------------------------------------------------------
    // Rebuild — worklist-based congruence closure
    // -----------------------------------------------------------------------

    /// Rebuild to a plain-congruence-closed state.
    ///
    /// Plain congruence closure always runs. AC/ACI completion is opt-in through
    /// [`set_cc`](Self::set_cc); it is disabled by default. When enabled, two
    /// closures are interleaved (see `doc/design/ac-congruence-completeness.md`
    /// section 8, rebuild = Kapur's Algorithm 3):
    /// - `rebuild_congruence`: ordinary worklist-driven
    ///   congruence closure (substitutes equal *atoms* into recanonicalized nodes);
    /// - `cc_round`: AC completion (substitutes
    ///   equal *sub-sums*), which canonization alone misses.
    ///
    /// A completion round may push new merges onto the worklist; we drain them with
    /// another congruence pass, then complete again, until a whole completion round
    /// adds nothing. Only [`CompletionOutcome::Converged`] reports that joint
    /// fixpoint. [`CompletionOutcome::Disabled`], [`CompletionOutcome::GoalMet`],
    /// and [`CompletionOutcome::AbortedGrowthLimit`] guarantee plain congruence
    /// closure but not complete AC/ACI congruence closure. Inspect
    /// [`completion_outcome`](Self::completion_outcome) after each call.
    pub fn rebuild(&mut self) {
        // Ordinary atom-level congruence closure always runs. AC completion runs only
        // when opted in (default off for divergence scoping — see the `cc` field docs).
        if !self.cc {
            self.rebuild_congruence();
            self.completion_outcome = Some(CompletionOutcome::Disabled);
            return;
        }
        // Multiple MSet symbols are supported: the per-class min-monomial pool stores a
        // separate least-monomial per completion op (step 3), and the round groups rules by op
        // (superposition/normalization filter on `r.op`, RHS via the node's own op column). Two
        // MSet ops therefore complete as independent rule sets sharing only the constant pool;
        // a class holding monomials of both (`a+b = a*b`) keeps each in its own column, and
        // union-find records the cross-op equality (Kapur's shared-constant case). Set (ACI)
        // completion is driven too: `completion_node_ids` yields both partitions, reducts
        // normalize in the op's count domain (idempotent clamp / mod-n / ℕ), and each rule
        // additionally superposes with its op's own axiom (Kapur §4 per-rule critical
        // pairs).
        let trace = std::env::var_os("AC_COMPLETE_TRACE").is_some();
        // Safety backstop against an expensive or nonterminating completion run (minting
        // critical-pair nodes): the configurable node-growth budget (see
        // `set_completion_node_budget`). If the AC node count grows past the budget beyond
        // where it started, we stop rather than continue materializing nodes. This is NOT a
        // termination argument or a work bound — it is a growth guard, and the
        // abort is REPORTED (`CompletionOutcome::AbortedGrowthLimit`), never silent.
        let budget = self.completion_node_budget;
        let start_nodes = self.node_count();
        self.cc_start_nodes = start_nodes;
        let basis_dump = self.basis_checks;
        let mut round = 0usize;
        // Watermark into the `touched` log: rules whose `(op, monomial)` changed since the
        // previous round are approximated by nodes touched (created or recanonicalized) in the
        // slice `touched[prev_mark..mark]`. Superposition (B) is incremental over this delta
        // (S3b): round 0 is a full pass (base case), each later round superposes only pairs
        // with ≥1 endpoint in the delta. A later full confirmation round compensates for
        // changes, such as a rule RHS shift, that this node-touch delta does not name.
        let mut prev_mark = 0usize;
        // Incremental rounds run until one finds nothing; then a single *full* confirmation
        // round checks the whole implemented rule set before reporting its operational
        // fixpoint. The node-touch delta misses a
        // pair only if a rule's RHS shifted without its node being recanonicalized (its own
        // class merged, not a child's); a full round closes any such pair. Convergence is
        // reported only when a *full* round is unchanged. This is an implementation stopping
        // condition, not a machine-checked completeness theorem. Full rounds run at the base
        // case and after an unchanged incremental round; their cost is input-dependent.
        let mut full = true; // round 0 is full (base case)
        loop {
            self.rebuild_congruence();
            // Goal-directed early stop (the lazy-check transaction): the pair
            // joined, so the question is answered — stop mid-closure. The
            // graph is plain-congruence-closed at this point, a valid state.
            if let Some((ga, gb)) = self.cc_goal
                && self.classes.find_const(ga) == self.classes.find_const(gb)
            {
                self.completion_outcome = Some(CompletionOutcome::GoalMet { rounds: round });
                return;
            }
            if basis_dump {
                self.cc_basis_dump(&format!("round {round} pre"));
            }
            let before = self.node_count();
            let mark = self.touched.len();
            let was_full = full;
            // `|`, not `||`: the A-only pass runs every iteration, its changes
            // and the AC round's alike drain through the same fixpoint.
            let changed = self.cc_round(full, prev_mark, mark) | self.a_round();
            prev_mark = mark;
            if trace {
                eprintln!(
                    "[ac-complete] round {round}{}: nodes {before} -> {} (+{}), changed={changed}",
                    if was_full { " (full)" } else { "" },
                    self.node_count(),
                    self.node_count() - before
                );
            }
            round += 1;
            if !changed {
                // Incremental round found nothing: confirm with a full round before exiting.
                // A full round that also finds nothing is the implemented fixpoint reported
                // by CompletionOutcome::Converged.
                if was_full {
                    self.completion_outcome = Some(CompletionOutcome::Converged { rounds: round });
                    return;
                }
                full = true;
                continue;
            }
            // Made progress: stay incremental for the next round.
            full = false;
            let added = self.node_count() - start_nodes;
            if added > budget {
                // Sound-but-incomplete stop: drain the pending congruence work so the
                // graph is a valid (plain-congruence-closed) state, then report the abort
                // through `completion_outcome` — the caller decides what to do with a
                // partial completion (there is deliberately NO assert here: the abort is
                // an expected, reported condition on pathological inputs, and tests drive
                // it directly with a tiny budget).
                self.rebuild_congruence();
                self.completion_outcome = Some(CompletionOutcome::AbortedGrowthLimit {
                    added_nodes: added,
                    limit: budget,
                });
                if trace {
                    eprintln!(
                        "[ac-complete] ABORT: added {added} nodes > budget {budget} \
                         without converging"
                    );
                }
                return;
            }
        }
    }

    /// If a (just-recanonized) MSet/Set node has a degenerate canonical arity, return the
    /// equality `(node, target)` it now denotes: an empty monomial equals the op's unit, a
    /// single mult-1 summand equals that summand's class. Returns `None` for a well-formed
    /// (≥2, or size-1-with-mult>1) monomial or a non-AC node. This is canonization's
    /// "AC-of-nothing/one" law read off the stored form; the caller merges the pair. Mirrors
    /// the build-path (`add`) degeneracy resolution, for nodes that go degenerate via a child
    /// merge rather than at build.
    fn degeneracy_merge(&self, node: Cfg::G) -> Option<(Cfg::G, Cfg::G)> {
        // Peek the node's canonical child span length (no child read, no alloc) and act only on a
        // degenerate arity — the common ≥2 case returns immediately. Recanonize has already
        // written the coalesced/clamped children, so the span length *is* the canonical child
        // count. Only when arity is exactly 1 do we read that one child.
        match self.node_ref(node) {
            NodeRef::MSet(l) => {
                let n = self.nodes.mset.get(l);
                let (s, e) = n.span();
                match e - s {
                    0 => self.unit_node(self.node_op(node)).map(|u| (node, u)),
                    1 => {
                        let c = self.nodes.mset.pool_get(s);
                        // Size-1 collapses to the child only at multiplicity 1 (`{a:2}` is not a
                        // degenerate `a`; for a nilpotent op it would already have clamped to `{}`).
                        (Cfg::mset_child_mult(&c) == Cfg::M::ONE)
                            .then(|| (node, Cfg::mset_child_id(&c)))
                    }
                    _ => None,
                }
            }
            NodeRef::Set(l) => {
                let n = self.nodes.set.get(l);
                let (s, e) = n.span();
                match e - s {
                    0 => self.unit_node(self.node_op(node)).map(|u| (node, u)),
                    1 => Some((node, self.nodes.set.pool_get(s))),
                    _ => None,
                }
            }
            _ => None,
        }
    }

    /// Recanonize one parent node — find-canonicalize its children and apply the op's
    /// algebraic canonization laws (count clamp, identity unit-drop) — and record any
    /// resulting hash-cons collision or degenerate-arity merge into `self.collisions`.
    /// Shared by the absorbed-uses sweep and the became-a-unit sweep in
    /// [`rebuild_congruence`](Self::rebuild_congruence).
    fn recanonize_parent(&mut self, parent: Cfg::G) {
        let find = |g: Cfg::G| self.classes.find_const(g);
        // The op's identity as a *class* under the current union-find: recanonize drops it
        // from MSet/Set children (`f(x,e) = x`), so a summand that merged into the unit's
        // class after the node was built is dropped exactly as it would have been at build
        // (Kapur Lemma 4.3's normalization assumption). Field-precise captures keep the
        // borrows disjoint from `self.nodes`.
        let units = &self.unit_node;
        let classes = &self.classes;
        let unit_of = |op: Cfg::O| {
            units
                .get_by_key(&op)
                .copied()
                .map(|u| classes.find_const(u))
        };
        self.nodes.recanonize_node(
            parent,
            find,
            unit_of,
            &mut self.g_buf,
            &mut self.mset_buf,
            &mut self.collisions,
            &mut self.touched,
            &self.ops,
        );
        // Canonization can shrink an MSet/Set node to a degenerate arity (a child merge
        // pushes a nilpotent count to 0, or coalesces/drops to a single summand): the node
        // then *equals* an existing class — empty ⇒ the unit, size-1 mult-1 ⇒ that child.
        // Recanonize (representation) can't express that equality, so record it as a merge
        // here (the congruence layer), alongside the hash-cons collisions. `and(a,b)` after
        // `a=b` becomes `{a}` = `a`; `xor(a,b)` after `a=b` becomes `{}` = the unit.
        if let Some(pair) = self.degeneracy_merge(parent) {
            self.collisions.push(pair);
        }
    }

    /// Ordinary worklist-driven congruence closure: drain the merge worklist,
    /// recanonicalizing the parents of each absorbed class and merging the
    /// resulting hash-cons collisions, to a fixpoint.
    fn rebuild_congruence(&mut self) {
        while let Some((absorbed_uses, survivor)) = self.worklist.pop() {
            self.collisions.clear();
            // Hot path: iterate the absorbed use list directly (no allocation). The body
            // mirrors `recanonize_parent` — it cannot be a method call here because the
            // use-list iterator holds `self.classes` for the whole loop, and only inline
            // field-disjoint borrows split around it.
            for parent in self.classes.uses().iter(absorbed_uses) {
                let find = |g: Cfg::G| self.classes.find_const(g);
                let units = &self.unit_node;
                let classes = &self.classes;
                let unit_of = |op: Cfg::O| {
                    units
                        .get_by_key(&op)
                        .copied()
                        .map(|u| classes.find_const(u))
                };
                self.nodes.recanonize_node(
                    parent,
                    find,
                    unit_of,
                    &mut self.g_buf,
                    &mut self.mset_buf,
                    &mut self.collisions,
                    &mut self.touched,
                    &self.ops,
                );
                if let Some(pair) = self.degeneracy_merge(parent) {
                    self.collisions.push(pair);
                }
            }

            let current_surv = self.classes.find_const(survivor);
            let surv_repr = self.classes.repr_id(current_surv).unwrap();
            let surv_list = self.classes.use_list_id(surv_repr);
            self.classes.splice_uses(surv_list, absorbed_uses);

            // If this merge made the merged class an op's identity (unit) class, the
            // unit-drop law now applies to EVERY parent holding this class as a summand —
            // including parents on the *surviving* side, which the absorbed-uses sweep
            // never visits (their children's `find` did not change; their canonization
            // mode did). Sweep the full spliced use list; parents that are already
            // canonical early-return inside recanonize. Rare path (a class becomes a unit
            // class at most once per op), so the scratch collection is acceptable.
            let merged_is_unit = {
                let units = &self.unit_node;
                let classes = &self.classes;
                self.ops.mset_ops().chain(self.ops.set_ops()).any(|op| {
                    units
                        .get_by_key(&op)
                        .copied()
                        .is_some_and(|u| classes.find_const(u) == current_surv)
                })
            };
            if merged_is_unit {
                let parents: Vec<Cfg::G> = self.classes.uses().iter(surv_list).collect();
                for parent in parents {
                    self.recanonize_parent(parent);
                }
            }

            for i in 0..self.collisions.len() {
                let (a, b) = self.collisions[i];
                let m = if PROOFS {
                    self.merge_in_classes(
                        a,
                        b,
                        Some(Justification::Congruence {
                            node_a: a,
                            node_b: b,
                        }),
                    )
                } else {
                    self.merge_in_classes(a, b, None)
                };
                if let Some(m) = m {
                    self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
                    self.worklist.push((m.absorbed_uses, m.survivor));
                }
            }
        }
    }

    /// One A-only (`Seq`) inter-reduction round: the transfer of the AC
    /// repair to associativity-only operators, run inside the same completion
    /// loop (so only when completion is enabled — plain mode is untouched and
    /// its node counts stand).
    ///
    /// The gap it closes: build-time flattening splices a pure-`op`-sequence
    /// child into its parents, erasing the class reference, and a class can
    /// never *become* pure late (merges only add members, and an atom member
    /// never leaves) — so the one way an A-equation escapes congruence is two
    /// pure-sequence classes merging. That class then holds two distinct
    /// `op`-sequence spellings: a ground string equation `seq_1 = seq_2` that
    /// parents which spliced different spellings cannot see. Each such
    /// equation is oriented shortlex (longer to shorter, ties by element ids)
    /// and contiguous occurrences of the larger spelling inside other
    /// `op`-sequences are rewritten: the rewritten sequence is added and
    /// merged with its source, justification `ACInterReduction` (the same
    /// sub-term-for-class substitution shape as the AC case).
    ///
    /// Every rewrite is shortlex-decreasing, so a round terminates, and the
    /// loop above drains rounds to a joint fixpoint under the same budget and
    /// goal polls as the AC pass. **Deliberately no critical-pair chase**:
    /// completing a ground string system is Knuth-Bendix on a semi-Thue
    /// system, and the word problem for finitely presented monoids is
    /// undecidable — unlike the AC side, where Dickson's Lemma bounds the
    /// basis, there is no completeness theorem to aim for. This pass closes
    /// the single-substitution gap (the erased-reference case above) and
    /// stops; what it derives is sound, what it misses is documented.
    fn a_round(&mut self) -> bool {
        use crate::containers::DenseId;
        use crate::typed_routing::NodeIds;
        let n_seq = self.nodes.seq.len().to_usize();
        if n_seq == 0 {
            return false;
        }
        // (op, class) -> the class's `op`-sequence spellings.
        let mut groups: std::collections::HashMap<(Cfg::O, Cfg::G), Vec<Cfg::G>> =
            std::collections::HashMap::new();
        for i in 0..n_seq {
            let l = <Cfg::Ids as NodeIds>::LSeq::from_usize(i);
            let g = self.nodes.seq.get(l).global_id();
            let cls = self.classes.find_const(g);
            groups.entry((self.node_op(g), cls)).or_default().push(g);
        }
        // Oriented rules: larger spelling -> the class's shortlex-least one.
        let mut rules: Vec<(Cfg::O, Vec<Cfg::G>, Vec<Cfg::G>)> = Vec::new();
        let mut buf: Vec<Cfg::G> = Vec::new();
        for ((op, _cls), nodes) in groups.iter().filter(|(_, v)| v.len() > 1) {
            let mut spellings: Vec<Vec<Cfg::G>> = Vec::with_capacity(nodes.len());
            for &n in nodes {
                self.seq_children(n, &mut buf);
                for e in buf.iter_mut() {
                    *e = self.classes.find_const(*e);
                }
                spellings.push(buf.clone());
            }
            let least = spellings
                .iter()
                .min_by(|a, b| shortlex(a, b))
                .expect("non-empty spelling group")
                .clone();
            for elems in spellings {
                if shortlex(&elems, &least) == std::cmp::Ordering::Greater {
                    rules.push((*op, elems, least.clone()));
                }
            }
        }
        if rules.is_empty() {
            return false;
        }
        // Rewrite pass over the round-start sequences (nodes added below are
        // visited next round). One rewrite per node per round: the fixpoint
        // loop supplies the iteration.
        let mut changed = false;
        let mut new_children: Vec<Cfg::G> = Vec::new();
        for i in 0..n_seq {
            if self.cc_should_stop() {
                break;
            }
            let l = <Cfg::Ids as NodeIds>::LSeq::from_usize(i);
            let g = self.nodes.seq.get(l).global_id();
            let g_op = self.node_op(g);
            self.seq_children(g, &mut buf);
            for e in buf.iter_mut() {
                *e = self.classes.find_const(*e);
            }
            for (op, lhs, rhs) in &rules {
                if *op != g_op || lhs.len() > buf.len() {
                    continue;
                }
                let Some(s) =
                    (0..=buf.len() - lhs.len()).find(|&s| &buf[s..s + lhs.len()] == lhs.as_slice())
                else {
                    continue;
                };
                new_children.clear();
                new_children.extend_from_slice(&buf[..s]);
                new_children.extend_from_slice(rhs);
                new_children.extend_from_slice(&buf[s + lhs.len()..]);
                let nid = self.add(*op, &new_children);
                if self.classes.find_const(nid) != self.classes.find_const(g) {
                    let m = if PROOFS {
                        self.merge_justified(
                            g,
                            nid,
                            Justification::ACInterReduction {
                                node_a: g,
                                node_b: nid,
                            },
                        )
                    } else {
                        self.merge(g, nid)
                    };
                    changed |= m.is_some();
                }
                break;
            }
        }
        changed
    }

    /// One AC congruence-completion round (Kapur FSCD 2021 Algorithm 1, the steps our
    /// rebuild otherwise omits). Returns `true` if it scheduled any new merge.
    ///
    /// Reading each non-subsumed AC node `+M = d` as a ground rule `+M → d`,
    /// for each pair of partners found through the class use-lists (same op,
    /// sharing ≥1 child class):
    ///
    /// - **(A) inter-reduction + Collapse** — if `A ⊊ M`, the sub-sum `+A` equals `a`,
    ///   so the residual `(M − A) ⊎ {a}`, **normalized to a fixpoint**, equals `d`:
    ///   merge, then **mark `+M` subsumed** so it leaves the active set. The collapse
    ///   is intended to maintain the active-rule antichain required by the conditional
    ///   Dickson argument (design doc §6b).
    /// - **(B) superposition** — if `A` and `M` overlap but neither contains the other,
    ///   build the lcm `AB`, **normalize both reducts** `(AB−M)⊎{d}` and `(AB−A)⊎{a}`
    ///   to normal form, and merge if they still differ (design doc §4b, §6 (B)).
    ///
    /// Disjoint partners are skipped (trivial critical pair). The crucial corrections
    /// over a naïve materialize-and-merge (design §6b): every reduct is reduced to
    /// **normal form before** being materialized (a raw reduct can be a superset of an
    /// existing rule's LHS, hence itself reducible, and would persist as a runaway
    /// superposition source), and reducible source rules are **collapsed** (subsumed).
    ///
    /// Completion collapse is the non-deletable form of Kapur/Conchon's rule retirement:
    /// the node and the equality it established stay in the DAG, but completion's
    /// active-rule projection skips it, so it is no longer a completion partner.
    /// `FLAG_AC_COLLAPSED` does not remove the node from matching; user-level
    /// `FLAG_SUBSUMED` does.
    /// One AC completion round. Superposition (B) is incremental (S3b): when `full` is
    /// false, only critical pairs with ≥1 endpoint among the *delta rules* (nodes touched
    /// in `self.touched[delta_lo..delta_hi]`, i.e. created or recanonicalized since the
    /// previous round) are generated. A later full round rechecks every pair, including
    /// old×old pairs whose effective RHS changed without touching their node. `full`
    /// generates every pair. The (A′)
    /// collapse/normalize pass and the antichain `reducible` check stay full scans: a small
    /// new rule must still be able to collapse a large old one.
    fn cc_round(&mut self, full: bool, delta_lo: usize, delta_hi: usize) -> bool {
        use crate::multiset::{
            NfIndex, NfRuleRef, NfRules, multiset_disjoint, multiset_lcm_into, multiset_subset,
            multiset_subtract_into, multiset_union, normalize_ms_into, normalize_nilpotent_into,
            normalize_set_into,
        };

        // Canonical monomial of a completion node as sorted (class-repr, mult): coalesced
        // multiplicities for an MSet op, deduped set (all mult 1) for a Set (ACI) op.
        // Delegates to `node_monomial_into`, which dispatches on the node's representation.
        let multiset_of = |eg: &Self, id: Cfg::G| -> Vec<(Cfg::G, Cfg::M)> {
            let mut out = Vec::new();
            eg.node_monomial_into(id, &mut out);
            out
        };

        use crate::multiset::monomial_cmp;
        use crate::node_types::{FLAG_AC_COLLAPSED, FLAG_SUBSUMED};

        // Completion's active set excludes nodes that are user-subsumed (not matchable)
        // OR AC-collapsed (reducible by a smaller rule). Either way they are not rules.
        let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;

        // Each active AC node is a candidate rule `+M → rhs(class)`, where the RHS comes
        // from the per-class slot (`class_rhs_into`: `{class}` if atomic, else the stored
        // `min_monomial` monomial, §9a) — not recomputed per round. The orientation guard keeps
        // only nodes whose own monomial `M` is strictly `≫_f`-greater than that RHS: those
        // are the currently oriented rules (a node equal to the maintained class candidate
        // is no rule, and a
        // mis-oriented `M ≺ rhs` is dropped, §9b axis-2a). `node` lets us collapse it.
        struct Rule<G, O, M> {
            /// The typed op id, not a widened `usize` copy of one. Storing the id itself
            /// keeps the row at the config's op width and — more to the point — leaves
            /// nothing to re-mint: the round used to spend a masking
            /// `Cfg::O::from_usize` per rule to undo a `to_usize` performed a few lines
            /// above, and only the op's own registration bound kept that honest.
            op: O,
            lhs: Vec<(G, M)>,
            rhs: Vec<(G, M)>,
            node: G,
        }
        let mut rules: Vec<Rule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();
        let mut rhs_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        // Iterate the AC node partition directly (ascending global id), not all nodes: the
        // `is_mset` filter is implicit and the non-AC majority is never visited.
        for gid in self.completion_node_ids() {
            if self.node_flags(gid) & inactive != 0 {
                continue;
            }
            let op = self.node_op(gid);
            let lhs = multiset_of(self, gid);
            if !self.class_rhs_into(gid, &mut rhs_buf) {
                continue;
            }
            // Read-time orientation guard (§9b): only `M ≫ rhs` is a rule.
            if monomial_cmp(&lhs, &rhs_buf) == std::cmp::Ordering::Greater {
                rules.push(Rule {
                    op,
                    lhs,
                    rhs: rhs_buf.clone(),
                    node: gid,
                });
            }
        }
        // Dedup the reducer/superposition set by (op, LHS). Congruent AC nodes can
        // recanonicalize to the same monomial after a child merge without being hash-consed
        // into one node, so the same rule `+M → r` appears as several nodes. Kapur step 2
        // discards a duplicate equation and keeps one; here we keep the lowest-node-id copy
        // as the canonical rule and drop the rest from `rules`. This is what makes the active
        // set Kapur-*reduced* (no LHS reducible by another's), not merely a strict-containment
        // antichain: identical-LHS copies were the whole measured gap between `reducible_pairs`
        // and the ground-truth `kapur_lhs_reducible` (ac_invariants). The dropped copies are
        // NOT lost: they remain in `targets`, so (A′) still collapses each (its monomial
        // reduces to the shared RHS via the kept rule) and still merges any differing-RHS copy
        // (the implied equality fires through `targets`, not `rules`). Without the dedup, every
        // copy reduces every other copy, so they mutually collapse and the rule vanishes
        // entirely (the §6b "merge before mark" / self-reduction hazard, at the set level).
        // Clone-free: sort by (op, lhs, node) with borrowed
        // comparisons, drop adjacent (op, lhs) duplicates keeping the first (= lowest node
        // id), then restore node order for the (B) binary search.
        rules.sort_unstable_by(|x, y| {
            x.op.cmp(&y.op)
                .then_with(|| x.lhs.cmp(&y.lhs))
                .then_with(|| x.node.cmp(&y.node))
        });
        rules.dedup_by(|later, earlier| later.op == earlier.op && later.lhs == earlier.lhs);

        // The (B) partner search binary-searches `rules` by global node id, so it must be
        // sorted by `node`. Distinct nodes ⇒ strictly sorted.
        rules.sort_unstable_by_key(|r| r.node);
        debug_assert!(rules.windows(2).all(|w| w[0].node < w[1].node));

        // Delta rule-node set for incremental (B): sorted, dedup'd node ids touched since
        // the previous round. `touched` may contain duplicates; sort+dedup once, then test
        // a rule's membership by binary search (mirrors the `rules` binary-search idiom).
        let delta: Vec<Cfg::G> = if full {
            Vec::new()
        } else {
            let mut d: Vec<Cfg::G> = self.touched[delta_lo..delta_hi].to_vec();
            d.sort_unstable();
            d.dedup();
            d
        };
        let in_delta = |n: Cfg::G| -> bool { full || delta.binary_search(&n).is_ok() };

        // Reducibility flag per rule: a rule whose LHS strictly contains another rule's LHS
        // (same op) is reducible by it, so collapse will retire it. Kapur superposes only
        // over the inter-reduced *antichain*, never over a reducible rule (FSCD'21 Algo 1:
        // collapse before superpose). The batch round collapses these only on the *next*
        // round, so excluding them as (B) sources/partners here is what keeps the active
        // set an antichain within the round and stops the critical-pair blowup.
        // O(rules²) over the small active set; acceptable while the worklist rewrite (S3b)
        // is pending.
        let phase_time = std::env::var_os("AC_PHASE_TIME").is_some();
        let t_reducible = std::time::Instant::now();
        let reducible: Vec<bool> = (0..rules.len())
            .map(|i| {
                rules.iter().enumerate().any(|(j, rj)| {
                    j != i
                        && rj.op == rules[i].op
                        && rj.lhs != rules[i].lhs
                        && multiset_subset(&rj.lhs, &rules[i].lhs)
                })
            })
            .collect();
        let dt_reducible = t_reducible.elapsed();

        // Expand a multiset to a flat child list into a reused scratch; `add` re-sorts and
        // re-coalesces. The expansion (O(total count), not O(distinct summands)) stays for
        // now: `add`'s whole canonize pipeline — flatten, unit-drop, clamp, degeneracy —
        // operates on child lists, and counts are bounded by the lcm of existing monomials.
        // A pair-based `add` entry could multiply multiplicities through the splice
        // without materializing repeated children.
        let mut mat_buf: Vec<Cfg::G> = Vec::new();
        let materialize =
            |eg: &mut Self, op: Cfg::O, ms: &[(Cfg::G, Cfg::M)], buf: &mut Vec<Cfg::G>| {
                buf.clear();
                for (g, mult) in ms {
                    for _ in 0..mult.to_usize() {
                        buf.push(*g);
                    }
                }
                eg.add(op, buf)
            };
        let do_merge = |eg: &mut Self, x: Cfg::G, y: Cfg::G, just: Justification<Cfg::G>| -> bool {
            if eg.classes.find_const(x) == eg.classes.find_const(y) {
                return false;
            }
            let m = if PROOFS {
                eg.merge_in_classes(x, y, Some(just))
            } else {
                eg.merge_in_classes(x, y, None)
            };
            match m {
                Some(m) => {
                    eg.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
                    eg.worklist.push((m.absorbed_uses, m.survivor));
                    true
                }
                None => false,
            }
        };

        // Collect work over pairs of rules (same op), then apply (so the rule set we
        // normalize against does not shift mid-scan). Superposition (B) and collapse (A)
        // both range over *rules*: Kapur superposes/inter-reduces rule left sides, and a
        // class's minimal monomial (a normal form) is never a rule, so it cannot be a
        // source or a collapse target. The search ranges over the `rules` Vec directly
        // (already the small active set), via an all-pairs loop.
        //   targets — (A): collapse a node's class into its residual's normal form.
        //   crit    — (B): merge the normal forms of the two lcm reducts.
        // Each critical pair carries its ORIGIN so the close-time merge records the
        // faithful proof justification (pairwise superposition vs. per-rule semantic
        // axiom CP vs. cancelative closure) instead of a catch-all label.
        #[derive(Clone, Copy)]
        enum CpOrigin {
            Superposition,
            AxiomCp,
            Cancellative,
        }
        let mut crit: Vec<(
            Cfg::O,
            CpOrigin,
            Vec<(Cfg::G, Cfg::M)>,
            Vec<(Cfg::G, Cfg::M)>,
        )> = Vec::new();

        // (A′) Normalize every active monomial node against the rules and merge its
        // normal form back in (Kapur Algo 2 step 2, "normalize Sf"). This subsumes plain
        // inter-reduction (A): a node +{a,b,neg(c)} with rule +{a,b}→{c} reduces to
        // +{c,neg(c)}, which is *materialized* so the ordinary matcher reaches it
        // (design §5b). `(op, monomial, class, node, is_rule)`: a node that was itself a
        // rule (its own LHS reducible) is collapsed/subsumed after the merge (design §6b).
        let t_gen = std::time::Instant::now();
        let mut targets: Vec<(Cfg::O, Vec<(Cfg::G, Cfg::M)>, Cfg::G, Cfg::G, bool)> = Vec::new();
        // AC partition only, same as the rules scan (no full-graph walk, no `is_mset` filter).
        for gid in self.completion_node_ids() {
            if self.node_flags(gid) & inactive != 0 {
                continue;
            }
            let op = self.node_op(gid);
            targets.push((
                op,
                multiset_of(self, gid),
                self.classes.find_const(gid),
                gid,
                rules.iter().any(|r| r.node == gid),
            ));
        }

        // (B) Superposition critical pairs over pairs of *rules* sharing ≥1 child class,
        // neither containing the other (overlap). Partners are found via the use-lists
        // (`iter_uses`), not an O(rules²) all-pairs scan: a partner of rule `+M` must
        // share a child with `M`, so it appears in some `iter_uses(x)` for `x ∈ M`. `rules`
        // is built in node-id order, so it is sorted by `node`; look a partner's rule up by
        // binary search (no map, no per-round allocation). Each unordered pair is processed
        // once (`ti.node < partner.node`). Both reducts are normalized before merge.
        let mut partner_buf: Vec<Cfg::G> = Vec::new();
        // Reusable temporaries for the (B) reduct arithmetic: the
        // lcm and residual are per-pair scratch; only the stored reducts (`crit` entries)
        // allocate. Grown once, reused across every pair.
        let mut ab_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        let mut sub_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        let mut delta_skipped = 0usize;
        let delta_in_rules = rules.iter().filter(|r| in_delta(r.node)).count();
        for ti in 0..rules.len() {
            // A reducible rule is not a member of the antichain: collapse will retire it,
            // so it must not seed critical pairs.
            if reducible[ti] {
                continue;
            }
            let op = rules[ti].op;
            let m_node = rules[ti].node;

            // Per-rule axiom critical pairs (Kapur §4): superpose the rule with
            // the op's own semantic axiom. The count clamp canonizes counts
            // *within* a monomial but cannot produce these cross-rule consequences — e.g.
            // or(a,b)=c ⟹ or(a,c)=c, and xor(a,b)=c ⟹ xor(a,c)=b — so without these
            // pairs completion is incomplete (Lemmas 4.1(ii), 4.2(ii)/4.5). Generated for
            // antichain members only (like (B) sources), when the rule is in the delta;
            // the full confirmation round is the completeness net, as for (B).
            if in_delta(m_node) {
                match self.op_clamp(op) {
                    CompletionClamp::Idempotent => {
                        // x∘x = x: for each a ∈ M, the pair (N ⊎ {a}, N). Since M → N by
                        // the rule itself, joinability of Kapur's (f(M), f(N∪{a})) reduces
                        // to exactly this pair. a ∈ N clamps to N — trivial, skip early.
                        for &(a, _) in &rules[ti].lhs {
                            let mut r1 = crate::multiset::multiset_union(
                                &rules[ti].rhs,
                                &[(a, Cfg::M::ONE)],
                            );
                            crate::multiset::clamp_idempotent(&mut r1);
                            if r1 != rules[ti].rhs {
                                crit.push((op, CpOrigin::AxiomCp, r1, rules[ti].rhs.clone()));
                            }
                        }
                    }
                    CompletionClamp::Nilpotent { order } => {
                        // xⁿ = e: for a with multiplicity m in M, superpose M with aⁿ → e
                        // on the lcm M ⊎ {a: n−m}. The rule reduct is N ⊎ {a: n−m}; the
                        // axiom reduct is (M − {a: m}) ⊎ {e}, whose unit drops (stored
                        // monomials never carry the unit). At n=2, m=1 this is literally
                        // Kapur's (f(N ∪ {a}), f((M − {a}) ∪ {e})).
                        for &(a, m) in &rules[ti].lhs {
                            // `order` is a `u8`, so the deficit is below 256 and
                            // representable at every supported multiplicity width.
                            let ord = Cfg::M::try_from_u64(u64::from(order))
                                .expect("a u8 nilpotent order fits every multiplicity width");
                            let k = ord.saturating_sub(m);
                            if k == Cfg::M::ZERO {
                                continue; // m ≡ 0 (mod n) never stored; defensive
                            }
                            let mut r1 = crate::multiset::multiset_union(&rules[ti].rhs, &[(a, k)]);
                            crate::multiset::clamp_nilpotent(&mut r1, order);
                            let r2 = crate::multiset::multiset_subtract(&rules[ti].lhs, &[(a, m)]);
                            crit.push((op, CpOrigin::AxiomCp, r1, r2));
                        }
                    }
                    CompletionClamp::Multiset => {} // plain AC / identity-only: none (Lemma 4.3)
                }
            }

            // Gather candidate partner nodes from the use-lists of M's distinct children.
            partner_buf.clear();
            for &(x, _) in &rules[ti].lhs {
                if let Some(x_repr) = self.classes.repr_id(self.classes.find_const(x)) {
                    for p in self.classes.iter_uses(x_repr) {
                        partner_buf.push(p);
                    }
                }
            }
            partner_buf.sort_unstable();
            partner_buf.dedup();

            for k in 0..partner_buf.len() {
                let p_node = partner_buf[k];
                // Process each unordered pair once; skip self.
                if p_node <= m_node {
                    continue;
                }
                if self.node_flags(p_node) & inactive != 0 || self.node_op(p_node) != op {
                    continue;
                }
                // The partner must itself be a rule: binary-search the sorted `rules`.
                let Ok(pi) = rules.binary_search_by(|r| r.node.cmp(&p_node)) else {
                    continue;
                };
                // ...and a member of the antichain (a reducible partner will be collapsed).
                if reducible[pi] {
                    continue;
                }
                // Incremental (B): an unordered pair is a *new* critical pair only if at
                // least one of its rules changed since the previous round (S3b). When
                // neither endpoint is in the delta the pair was closed in an earlier round
                // and stays closed; skip it. `full` (round 0) makes `in_delta` always true.
                if !in_delta(m_node) && !in_delta(p_node) {
                    delta_skipped += 1;
                    continue;
                }
                let m = &rules[ti].lhs;
                let a = &rules[pi].lhs;
                // Shared by construction; skip the non-overlap / containment cases
                // (containment is handled by the (A′) normalize pass).
                debug_assert!(!multiset_disjoint(a, m));
                if multiset_subset(a, m) || multiset_subset(m, a) {
                    continue;
                }
                multiset_lcm_into(&mut ab_buf, m, a);
                multiset_subtract_into(&mut sub_buf, &ab_buf, m);
                let mut r1 = multiset_union(&sub_buf, &rules[ti].rhs);
                multiset_subtract_into(&mut sub_buf, &ab_buf, a);
                let mut r2 = multiset_union(&sub_buf, &rules[pi].rhs);
                // Clamp the reducts to the op's normal-form count domain before the pair is
                // closed: idempotent → {0,1} (ACI union), nilpotent → mod-n (symmetric
                // difference). Multiset (plain AC) keeps ℕ counts, no clamp.
                match self.op_clamp(op) {
                    CompletionClamp::Idempotent => {
                        crate::multiset::clamp_idempotent(&mut r1);
                        crate::multiset::clamp_idempotent(&mut r2);
                    }
                    CompletionClamp::Nilpotent { order } => {
                        crate::multiset::clamp_nilpotent(&mut r1, order);
                        crate::multiset::clamp_nilpotent(&mut r2, order);
                    }
                    CompletionClamp::Multiset => {}
                }
                crit.push((op, CpOrigin::Superposition, r1, r2));
            }
        }

        // ── Cancelative facet (Kapur §5) ──
        // (C1) Cancel-close every antichain rule of a cancelative op (§5.2): a rule
        // f(M) → f(R) is an equation; canceling the common part C = M ∩ R entails
        // f(M−C) = f(R−C). (C2) Cancelative disjoint superposition (§5.3): for two rules
        // of the same cancelative op, the disjoint join f(M₁⊎M₂) = f(R₁⊎R₂) may not be
        // cancelatively closed; its cancel-closure yields further critical pairs (Kapur's
        // SC2/SC3 examples — without these, orienting the input equations is canonical but
        // NOT a cancelative congruence closure, Thm 5.1/5.2).
        //
        // Empty-side policy after canceling: with a declared identity the empty side IS
        // the unit (f({}) = e) and the pair closes against it. Without one, Kapur's
        // §5.2(iii)(b) applies: an equation f(A) = f(B) whose cancelation empties one side
        // entails f((A−B) ∪ {c}) = f({c}) for EVERY constant c (his SC2 derives
        // f(a,a,b) = a this way). Kapur's constant set C is fixed by purification; ours is
        // incremental, so the closure is generated over the op's CURRENT summand pool (the
        // distinct classes appearing in its active monomials) — a class that appears later
        // is covered by the full confirmation round that sees it, the same net that covers
        // every other delta miss.
        let cancel_close = |a: &[(Cfg::G, Cfg::M)],
                            b: &[(Cfg::G, Cfg::M)]|
         -> Option<(Vec<(Cfg::G, Cfg::M)>, Vec<(Cfg::G, Cfg::M)>)> {
            let c = crate::multiset::multiset_intersect(a, b);
            if c.is_empty() {
                return None;
            }
            Some((
                crate::multiset::multiset_subtract(a, &c),
                crate::multiset::multiset_subtract(b, &c),
            ))
        };
        // The op's summand pool, for the per-constant closure (computed only when an
        // empty-side cancelation actually occurs — rare).
        let summand_pool = |targets: &[(Cfg::O, Vec<(Cfg::G, Cfg::M)>, Cfg::G, Cfg::G, bool)],
                            want: Cfg::O|
         -> Vec<Cfg::G> {
            let mut pool: Vec<Cfg::G> = targets
                .iter()
                .filter(|t| t.0 == want)
                .flat_map(|t| t.1.iter().map(|p| p.0))
                .collect();
            pool.sort_unstable();
            pool.dedup();
            pool
        };
        let push_cancel = |crit: &mut Vec<(
            Cfg::O,
            CpOrigin,
            Vec<(Cfg::G, Cfg::M)>,
            Vec<(Cfg::G, Cfg::M)>,
        )>,
                           op: Cfg::O,
                           has_unit: bool,
                           pool: &[Cfg::G],
                           m: Vec<(Cfg::G, Cfg::M)>,
                           r: Vec<(Cfg::G, Cfg::M)>| {
            if (!m.is_empty() && !r.is_empty()) || has_unit {
                crit.push((op, CpOrigin::Cancellative, m, r));
            } else {
                // §5.2(iii)(b): f(ne ∪ {c}) = f({c}) for every constant c in the pool.
                let ne = if m.is_empty() { r } else { m };
                for &g in pool {
                    let one = [(g, Cfg::M::ONE)];
                    crit.push((
                        op,
                        CpOrigin::Cancellative,
                        crate::multiset::multiset_union(&ne, &one),
                        one.to_vec(),
                    ));
                }
            }
        };
        for ti in 0..rules.len() {
            if reducible[ti] {
                continue;
            }
            let op = rules[ti].op;
            if !self.op_cancellative(op) {
                continue;
            }
            let has_unit = self.unit_node(op).is_some();
            // Lazily computed at most once per rule that needs it; empty-side cases are rare.
            let mut pool: Option<Vec<Cfg::G>> = None;
            let pool_ref = |pool: &mut Option<Vec<Cfg::G>>| -> Vec<Cfg::G> {
                pool.get_or_insert_with(|| summand_pool(&targets, op))
                    .clone()
            };
            // (C1) — regenerated when the rule is in the delta; the full confirmation
            // round is the completeness net, as for (B) and the axiom pairs.
            if in_delta(rules[ti].node)
                && let Some((m, r)) = cancel_close(&rules[ti].lhs, &rules[ti].rhs)
            {
                let needs_pool = (m.is_empty() || r.is_empty()) && !has_unit;
                let pl = if needs_pool {
                    pool_ref(&mut pool)
                } else {
                    Vec::new()
                };
                push_cancel(&mut crit, op, has_unit, &pl, m, r);
            }
            // (C2) cancelative disjoint superposition — each unordered same-op antichain
            // pair once. O(rules²) but only over the (rare) cancelative ops' rules.
            for pj in ti + 1..rules.len() {
                if reducible[pj] || rules[pj].op != rules[ti].op {
                    continue;
                }
                if !in_delta(rules[ti].node) && !in_delta(rules[pj].node) {
                    continue;
                }
                let u1 = crate::multiset::multiset_union(&rules[ti].lhs, &rules[pj].lhs);
                let u2 = crate::multiset::multiset_union(&rules[ti].rhs, &rules[pj].rhs);
                if let Some((m, r)) = cancel_close(&u1, &u2) {
                    let needs_pool = (m.is_empty() || r.is_empty()) && !has_unit;
                    let pl = if needs_pool {
                        pool_ref(&mut pool)
                    } else {
                        Vec::new()
                    };
                    push_cancel(&mut crit, op, has_unit, &pl, m, r);
                }
            }
        }

        // Critical-pair reducts are normalized to multisets (each step strictly lowers the
        // multiset in degree-lex order against the rule set, so it terminates), then only a
        // genuinely-divergent pair is materialized — this is what stops the runaway
        // (design §6b). See the (B) close loop below.

        if std::env::var_os("AC_COMPLETE_TRACE").is_some() {
            eprintln!(
                "[ac-complete]   active(rules)={} targets(A′)={} crit(B)={}",
                rules.len(),
                targets.len(),
                crit.len()
            );
        }

        let dt_gen = t_gen.elapsed();
        let mut changed = false;
        let t_aprime = std::time::Instant::now();
        // (A′) normalize each monomial; materialize+merge its normal form; collapse rules.
        // A node is normalized by all OTHER rules, never by its own node-rule (a rule's
        // LHS is in normal form w.r.t. itself; reducing it by itself would subsume the
        // rule before it can superpose — the §4b regression). So a node is collapsed only
        // when a *different*, strictly-contained rule reduces it (genuine inter-reduction).
        // Borrowed rule views plus reused normalize buffers:
        // the per-target rule set is a `clear`+`extend` refill of `Copy` views into the
        // round's rule table — no deep clones — and the normal form lands in a reused
        // destination buffer. Zero steady-state allocation per target.
        let mut nf_refs: Vec<NfRuleRef<'_, Cfg::G, Cfg::M>> = Vec::with_capacity(rules.len());
        let mut nf_out: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        let mut nf_ping: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        for (op, mset, class, node, _is_rule) in targets {
            // In-round stop: the goal pair joined, or this round's minting
            // blew the node budget — bail mid-apply instead of burning the
            // rest of the round. `rebuild` reads which outcome occurred.
            if self.cc_should_stop() {
                break;
            }
            nf_refs.clear();
            nf_refs.extend(
                rules
                    .iter()
                    .filter(|r| r.op == op && r.node != node)
                    .map(|r| NfRuleRef {
                        lhs: &r.lhs,
                        rhs: &r.rhs,
                    }),
            );
            // Normalize in the op's count domain: idempotent → set (clamp to 1); nilpotent →
            // mod-n; plain AC (MSet) → ℕ.
            // Linear, not indexed: this rule slice is refilled per target (each target is
            // normalized by every rule but its own), so there is no reuse to amortize an
            // index over. Any relative phase cost is workload-dependent and belongs in the
            // Criterion completion benchmark, not in this correctness comment.
            let nf = NfRules::linear(&nf_refs);
            match self.op_clamp(op) {
                CompletionClamp::Idempotent => {
                    normalize_set_into(&mut nf_out, &mut nf_ping, &mset, nf)
                }
                CompletionClamp::Nilpotent { order } => {
                    normalize_nilpotent_into(&mut nf_out, &mut nf_ping, &mset, nf, order)
                }
                CompletionClamp::Multiset => {
                    normalize_ms_into(&mut nf_out, &mut nf_ping, &mset, nf)
                }
            }
            // Inverse-pair cancellation on the normal form (group ops): normalization can
            // bring x and inv(x) together in one monomial; cancel before comparing. Track
            // whether it fired: a merge produced by pair cancellation is a group-law
            // inference (`x ∘ inv(x) = e`), not plain rule inter-reduction, and the proof
            // label must say so.
            let mut inverse_cancelled = false;
            if let Some(inv) = self.inverse_op(op) {
                inverse_cancelled = self.group_cancel_pairs(inv, &mut nf_out);
            }
            let normal = &nf_out;
            // If normalization by the other rules changed the monomial, materialize the normal
            // form and merge. `materialize` calls `add`, which now resolves a degenerate result
            // itself: an emptied monomial (`a ⊕ a → {}`, or `+(a,e)`-style cancellation) becomes
            // the unit, and a single mult-1 summand (`a ⊕ a ⊕ b → {b}`) becomes that class — so
            // this one branch covers the empty/size-1 cases too (a completion target always has
            // `mset.len() ≥ 2`, canonization never stores a degenerate node, so any empty/size-1
            // `normal` differs from `mset` and lands here).
            if *normal != mset {
                let c_prime = materialize(self, op, normal, &mut mat_buf);
                let just = if inverse_cancelled {
                    Justification::InverseCancel {
                        node_a: c_prime,
                        node_b: node,
                    }
                } else {
                    Justification::ACInterReduction {
                        node_a: c_prime,
                        node_b: node,
                    }
                };
                changed |= do_merge(self, c_prime, class, just);
                // Collapse: the node was reducible by another rule (proper containment),
                // so retire it from the active AC rule set (design §6b). FLAG_AC_COLLAPSED,
                // NOT subsume — the node stays matchable and a legal child; only
                // completion's active set excludes it. Merge first, mark second.
                self.set_cc_collapsed(node);
            }
        }
        let dt_aprime = t_aprime.elapsed();
        let t_bclose = std::time::Instant::now();
        // (B) close each critical pair by merging the normal forms of its two reducts.
        // Normalize BOTH reducts to multisets first; if they coincide the pair is already
        // joinable (a trivial critical pair) — skip it, minting no node and no merge.
        // Materializing trivial pairs was a second blowup source: each spurious node became
        // a fresh rule that fed the next round. Only genuinely divergent pairs
        // are materialized and merged.
        let mut trivial = 0usize;
        let mut nontrivial = 0usize;
        let mut trivial_after_nf = 0usize; // trivial pairs that needed full normalize to see it
        // The rule set used to normalize a reduct is the same for every pair of a given op, so
        // build the per-op rule sets ONCE (outside the loop), not per pair — the `Bclose` hoist
        // (perf doc §2). A reduct of op X must normalize ONLY against op-X rules: a different
        // op's LHS is a set of class ids that could spuriously match inside X's monomial. So
        // group `nf_rules` by op. Keyed by the typed op id (not a widened copy of one);
        // lookup is a small linear scan (few ops).
        let mut nf_by_op: Vec<(Cfg::O, Vec<NfRuleRef<'_, Cfg::G, Cfg::M>>)> = Vec::new();
        for r in &rules {
            let entry = match nf_by_op.iter_mut().find(|(o, _)| *o == r.op) {
                Some(e) => &mut e.1,
                None => {
                    nf_by_op.push((r.op, Vec::new()));
                    &mut nf_by_op.last_mut().unwrap().1
                }
            };
            entry.push(NfRuleRef {
                lhs: &r.lhs,
                rhs: &r.rhs,
            });
        }
        // Index each op's table by LHS-minimum class, hoisted with the table itself. This
        // The index is amortized over all reduct normalizations for the op. Its performance
        // effect is tracked by the Criterion completion benchmark.
        let nf_index_by_op: Vec<NfIndex<Cfg::G>> =
            nf_by_op.iter().map(|(_, v)| NfIndex::build(v)).collect();
        let empty_nf: Vec<NfRuleRef<'_, Cfg::G, Cfg::M>> = Vec::new();
        let crit_generated = crit.len();
        let mut n1_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        let mut n2_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
        for (op, origin, r1, r2) in crit {
            // Same in-round stop as the (A′) loop above.
            if self.cc_should_stop() {
                break;
            }
            // Cheap raw-equality reject: most critical pairs are trivial (the two reducts
            // already coincide as multisets), so skip the two full normalizations entirely
            // when r1 == r2 already.
            if r1 == r2 {
                trivial += 1;
                continue;
            }
            let nf_rules = match nf_by_op.iter().position(|(o, _)| *o == op) {
                Some(i) => NfRules::indexed(&nf_by_op[i].1, &nf_index_by_op[i]),
                None => NfRules::linear(&empty_nf),
            };
            // Normalize both reducts in the op's count domain (idempotent → set, nilpotent →
            // mod-n, plain AC → ℕ) before comparing/merging.
            match self.op_clamp(op) {
                CompletionClamp::Idempotent => {
                    normalize_set_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules);
                    normalize_set_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules);
                }
                CompletionClamp::Nilpotent { order } => {
                    normalize_nilpotent_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules, order);
                    normalize_nilpotent_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules, order);
                }
                CompletionClamp::Multiset => {
                    normalize_ms_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules);
                    normalize_ms_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules);
                }
            }
            if let Some(inv) = self.inverse_op(op) {
                self.group_cancel_pairs(inv, &mut n1_buf);
                self.group_cancel_pairs(inv, &mut n2_buf);
            }
            let (n1, n2) = (&n1_buf, &n2_buf);
            if n1 == n2 {
                trivial += 1;
                trivial_after_nf += 1;
                continue;
            }
            nontrivial += 1;
            // `materialize` calls `add`, which resolves a degenerate reduct itself: an emptied
            // reduct (nilpotent cancellation / identity drop) becomes the unit, a single mult-1
            // summand becomes that class. So no empty/size-1 special-casing is needed here.
            let c1 = materialize(self, op, n1, &mut mat_buf);
            let c2 = materialize(self, op, n2, &mut mat_buf);
            // The proof label reflects the pair's ORIGIN: pairwise rule superposition
            // (Kapur Def 3.2), the op's own semantic-axiom CP (§4), or cancelative
            // closure (§5.2/§5.3).
            let just = match origin {
                CpOrigin::Superposition => Justification::ACSuperposition {
                    node_a: c1,
                    node_b: c2,
                },
                CpOrigin::AxiomCp => Justification::ACAxiomCP {
                    node_a: c1,
                    node_b: c2,
                },
                CpOrigin::Cancellative => Justification::Cancellative {
                    node_a: c1,
                    node_b: c2,
                },
            };
            changed |= do_merge(self, c1, c2, just);
        }
        if std::env::var_os("AC_COMPLETE_TRACE").is_some() {
            eprintln!(
                "[ac-complete]   crit(B) trivial={trivial} (raw-eq={}, after-nf={trivial_after_nf}) nontrivial={nontrivial}",
                trivial - trivial_after_nf
            );
            eprintln!(
                "[ac-complete]   full={full} rules={} delta_in_rules={delta_in_rules} delta_skipped_pairs={delta_skipped} crit_generated={crit_generated}",
                rules.len(),
            );
        }
        if phase_time {
            let dt_bclose = t_bclose.elapsed();
            eprintln!(
                "[ac-phase] rules={} reducible={:.1}ms gen+targets={:.1}ms A'={:.1}ms Bclose={:.1}ms",
                rules.len(),
                dt_reducible.as_secs_f64() * 1e3,
                dt_gen.as_secs_f64() * 1e3,
                dt_aprime.as_secs_f64() * 1e3,
                dt_bclose.as_secs_f64() * 1e3,
            );
        }
        changed
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> EGraphToken {
        self.rebuild();
        EGraphToken {
            classes: self.classes.mark(shrink),
            nodes: self.nodes.mark(shrink),
            sorts: self.sorts.mark(shrink),
            ops: self.ops.mark(shrink),
            rules: self.rules.mark(shrink),
            axioms: self.axioms.mark(shrink),
            lits: self.lits.mark(shrink),
            unit_node: self
                .unit_node
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            inverse_op: self
                .inverse_op
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            completion_outcome: self.completion_outcome,
        }
    }

    pub fn restore(&mut self, token: EGraphToken) {
        self.classes.restore(token.classes);
        self.nodes.restore(token.nodes);
        self.sorts.restore(token.sorts);
        self.ops.restore(token.ops);
        self.rules.restore(token.rules);
        self.axioms.restore(token.axioms);
        self.lits.restore(token.lits);
        self.unit_node
            .try_restore(token.unit_node)
            .expect("restore: token minted by this container's own mark");
        self.inverse_op
            .try_restore(token.inverse_op)
            .expect("restore: token minted by this container's own mark");
        // Roll the outcome back with the graph: the mark-time value describes exactly the
        // restored state (mark() rebuilds first), so a post-restore reader never sees an
        // outcome computed for the discarded scope.
        self.completion_outcome = token.completion_outcome;
        self.worklist.clear();
        self.collisions.clear();
        self.touched.clear();
    }

    fn register_if_fresh(&mut self, result: Added<Cfg::G>, op: Cfg::O) -> Cfg::G {
        if result.is_fresh() {
            let id = result.id();
            let repr = self.classes.add_singleton(id);
            // Seed the per-class min-monomial pool. A completion node (MSet or Set) is its
            // class's only monomial for its own op, so seed that op's column to itself. A
            // non-completion node instead makes its class `atomic`: the class has a member
            // that is not a monomial, so the size-1 monomial `{class}` is its normal-form
            // representative (the completion rule RHS, §9a). Completion nodes are not atomic
            // by themselves; they become atomic only when referenced as a child (`add_use`).
            match self.ops.completion_column(op) {
                Some(col) => {
                    // Fix the pool row width to nb_completion on first completion-node seed.
                    // Ops are declared before terms (declare-before-build), so the count is
                    // stable here; `set_min_width` is idempotent when unchanged and rejects a
                    // change once rows exist.
                    self.classes.set_min_width(self.ops.completion_op_count());
                    self.classes.set_min_monomial(repr, col, id);
                }
                None => self.classes.set_atomic(repr),
            }
            self.touched.push(id);
        }
        result.id()
    }

    /// Semi-naive: node ids created or recanonicalized since the last
    /// `clear_touched` (or `restore`). May contain duplicates; the delta
    /// index builder deduplicates. Superset of all genuinely-changed nodes.
    pub fn touched(&self) -> &[Cfg::G] {
        &self.touched
    }

    /// Clear the touched log (call at a semi-naive round boundary, after the
    /// delta index for the round has been built).
    pub fn clear_touched(&mut self) {
        self.touched.clear();
    }

    // -----------------------------------------------------------------------
    // Read-only inspection
    // -----------------------------------------------------------------------

    pub fn node_count(&self) -> usize {
        self.nodes.routing().len()
    }

    pub fn class_repr(&self, id: Cfg::G) -> Cfg::G {
        self.classes.find_const(id)
    }

    /// The minimum-monomial node stored for `id`'s class in `id`'s op column (the completion
    /// rule RHS, §9a). Maintained on merge by `fold_min_monomial`. Returns `None` if `id` has
    /// no class or its op has no stored monomial for that class. Read by tests only.
    #[allow(dead_code)]
    pub(crate) fn class_min_monomial(&self, id: Cfg::G) -> Option<Cfg::G> {
        let repr = self.classes.repr_id(self.classes.find_const(id))?;
        let col = self.completion_column(id)?;
        self.classes.min_monomial(repr, col)
    }

    /// Whether `id`'s class is `atomic` (referenced as a child / has a non-AC node, so
    /// `{class}` is its canonical summand form, §9a). `None` if `id` has no class.
    #[allow(dead_code)]
    pub(crate) fn class_atomic(&self, id: Cfg::G) -> Option<bool> {
        let repr = self.classes.repr_id(self.classes.find_const(id))?;
        Some(self.classes.atomic(repr))
    }

    pub fn node_ref(&self, id: Cfg::G) -> NodeRef<Cfg::Ids> {
        self.nodes.routing().get(id)
    }

    pub fn node_op(&self, id: Cfg::G) -> Cfg::O {
        match self.node_ref(id) {
            NodeRef::Plain0(l) => self.nodes.plain0.get(l).op(),
            NodeRef::Plain1(l) => self.nodes.plain1.get(l).op(),
            NodeRef::Plain2(l) => self.nodes.plain2.get(l).op(),
            NodeRef::Plain3(l) => self.nodes.plain3.get(l).op(),
            NodeRef::SPair(l) => self.nodes.spair.get(l).op(),
            NodeRef::PlainN(l) => self.nodes.plain_n.get(l).op(),
            NodeRef::Seq(l) => self.nodes.seq.get(l).op(),
            NodeRef::MSet(l) => self.nodes.mset.get(l).op(),
            NodeRef::Set(l) => self.nodes.set.get(l).op(),
            NodeRef::Lit(l) => self.nodes.lit.get(l).op(),
        }
    }

    pub fn node_op_name(&self, id: Cfg::G) -> &str {
        &self.ops.info(self.node_op(id)).name
    }

    /// Global ids of every AC e-node, ascending (the AC partition is append-only, so local
    /// id order is global-id order). The completion round iterates this instead of all
    /// `node_count()` nodes: it visits only AC nodes, never the non-AC majority (leaves,
    /// `Plain`/`Lit`/other-op nodes). On AC-dense stress graphs this is ~neutral, but on a
    /// general e-graph (mostly non-AC structure) the AC nodes are a small fraction, so the
    /// per-round scan drops from O(total nodes) to O(AC nodes). Includes collapsed/subsumed
    /// AC nodes; the caller filters by flag.
    fn completion_node_ids(&self) -> impl Iterator<Item = Cfg::G> + '_ {
        use crate::containers::DenseId;
        use crate::typed_routing::NodeIds;
        // Both completion partitions: MSet (plain AC or nilpotent) and Set (idempotent/ACI).
        //
        // The bare `from_usize` mints below need no bound check, unlike the global-id scans
        // (see [`node_ids`](Self::node_ids)): these arenas are indexed *by* the local id, so
        // the container's own capacity guard IS the id bound — `IndexLike::max_nat()` for a
        // dense id is its `id_bound()`. A position the arena can hold therefore always has a
        // local id, and `len()` hands one back typed rather than as a raw count.
        let n_mset = self.nodes.mset.len().to_usize();
        let n_set = self.nodes.set.len().to_usize();
        let mset = (0..n_mset).map(move |i| {
            let l = <Cfg::Ids as NodeIds>::LMSet::from_usize(i);
            self.nodes.mset.get(l).global_id()
        });
        let set = (0..n_set).map(move |i| {
            let l = <Cfg::Ids as NodeIds>::LSet::from_usize(i);
            self.nodes.set.get(l).global_id()
        });
        mset.chain(set)
    }

    pub fn node_flags(&self, id: Cfg::G) -> u8 {
        match self.node_ref(id) {
            NodeRef::Plain0(l) => self.nodes.plain0.get(l).flags,
            NodeRef::Plain1(l) => self.nodes.plain1.get(l).flags,
            NodeRef::Plain2(l) => self.nodes.plain2.get(l).flags,
            NodeRef::Plain3(l) => self.nodes.plain3.get(l).flags,
            NodeRef::SPair(l) => self.nodes.spair.get(l).flags,
            NodeRef::PlainN(l) => self.nodes.plain_n.get(l).flags,
            NodeRef::Seq(l) => self.nodes.seq.get(l).flags,
            NodeRef::MSet(l) => self.nodes.mset.get(l).flags,
            NodeRef::Set(l) => self.nodes.set.get(l).flags,
            NodeRef::Lit(l) => self.nodes.lit.get(l).flags,
        }
    }

    /// Set one of the per-node control flags ([`FLAG_SUBSUMED`](crate::node_types::FLAG_SUBSUMED),
    /// [`FLAG_AC_COLLAPSED`](crate::node_types::FLAG_AC_COLLAPSED)) on `id`'s node.
    fn set_node_flag(&mut self, id: Cfg::G, flag: u8) {
        macro_rules! flag {
            ($store:expr, $l:expr) => {{
                let mut n = $store.get($l);
                n.flags |= flag;
                $store.set($l, n);
            }};
        }
        match self.node_ref(id) {
            NodeRef::Plain0(l) => flag!(self.nodes.plain0, l),
            NodeRef::Plain1(l) => flag!(self.nodes.plain1, l),
            NodeRef::Plain2(l) => flag!(self.nodes.plain2, l),
            NodeRef::Plain3(l) => flag!(self.nodes.plain3, l),
            NodeRef::SPair(l) => flag!(self.nodes.spair, l),
            NodeRef::PlainN(l) => flag!(self.nodes.plain_n, l),
            NodeRef::Seq(l) => flag!(self.nodes.seq, l),
            NodeRef::MSet(l) => flag!(self.nodes.mset, l),
            NodeRef::Set(l) => flag!(self.nodes.set, l),
            NodeRef::Lit(l) => flag!(self.nodes.lit, l),
        }
    }

    /// User-level subsumption: exclude `id` from future pattern matching (the matcher's
    /// indices skip `FLAG_SUBSUMED`). Distinct from AC-collapse — see `FLAG_AC_COLLAPSED`.
    pub fn subsume(&mut self, id: Cfg::G) {
        self.set_node_flag(id, crate::node_types::FLAG_SUBSUMED);
    }

    /// AC-completion collapse: retire `id` from the active AC rule set (its child
    /// multiset is reducible by a smaller AC rule, so it is no longer a superposition or
    /// inter-reduction source). The node stays **matchable** and a legal child; only
    /// completion's active set excludes it (design §6b). Distinct from `subsume`.
    pub(crate) fn set_cc_collapsed(&mut self, id: Cfg::G) {
        debug_assert!(
            matches!(self.node_ref(id), NodeRef::MSet(_) | NodeRef::Set(_)),
            "set_cc_collapsed on a non-completion node"
        );
        self.set_node_flag(id, crate::node_types::FLAG_AC_COLLAPSED);
    }

    /// If `id` is a literal node, return its interned value. Otherwise `None`.
    pub fn get_lit_val(&self, id: Cfg::G) -> Option<&L> {
        if let NodeRef::Lit(l) = self.node_ref(id) {
            Some(self.lits.get(self.nodes.lit.get(l).lit))
        } else {
            None
        }
    }

    /// If `id` is a literal node, return its interned LitValId.
    pub fn get_lit_val_id(&self, id: Cfg::G) -> Option<Cfg::V> {
        if let NodeRef::Lit(l) = self.node_ref(id) {
            Some(self.nodes.lit.get(l).lit)
        } else {
            None
        }
    }

    /// Return sort of a node (from its operator's signature).
    pub fn node_sort(&self, id: Cfg::G) -> Cfg::S {
        self.ops.info(self.node_op(id)).return_sort
    }

    /// Debug: verify all nodes in each e-class have the same sort.
    /// Panics on violation. Only useful in tests / debug builds.
    pub fn debug_check_sort_invariant(&self) {
        use std::collections::HashMap;
        let mut class_sort: HashMap<Cfg::G, Cfg::S> = HashMap::new();
        for gid in self.node_ids() {
            let repr = self.find_const(gid);
            let sort = self.node_sort(gid);
            if let Some(&existing) = class_sort.get(&repr) {
                assert_eq!(
                    existing,
                    sort,
                    "sort invariant violated: e-class of '{}' has sort {:?}, but '{}' has sort {:?}",
                    self.node_op_name(repr),
                    existing,
                    self.node_op_name(gid),
                    sort
                );
            } else {
                class_sort.insert(repr, sort);
            }
        }
    }

    pub fn for_each_child(&self, id: Cfg::G, mut f: impl FnMut(Cfg::G, Cfg::M)) -> usize {
        match self.node_ref(id) {
            NodeRef::Plain0(_) => 0,
            NodeRef::Plain1(l) => {
                for &c in &self.nodes.plain1.get(l).children {
                    f(c, Cfg::M::ONE);
                }
                1
            }
            NodeRef::Plain2(l) => {
                for &c in &self.nodes.plain2.get(l).children {
                    f(c, Cfg::M::ONE);
                }
                2
            }
            NodeRef::Plain3(l) => {
                for &c in &self.nodes.plain3.get(l).children {
                    f(c, Cfg::M::ONE);
                }
                3
            }
            NodeRef::SPair(l) => {
                for &c in &self.nodes.spair.get(l).children {
                    f(c, Cfg::M::ONE);
                }
                2
            }
            NodeRef::PlainN(l) => {
                let n = self.nodes.plain_n.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    f(self.nodes.plain_n.pool_get(i), Cfg::M::ONE);
                }
                e - s
            }
            NodeRef::Seq(l) => {
                let n = self.nodes.seq.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    f(self.nodes.seq.pool_get(i), Cfg::M::ONE);
                }
                e - s
            }
            NodeRef::MSet(l) => {
                let n = self.nodes.mset.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    let c = self.nodes.mset.pool_get(i);
                    f(Cfg::mset_child_id(&c), Cfg::mset_child_mult(&c));
                }
                e - s
            }
            NodeRef::Set(l) => {
                let n = self.nodes.set.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    f(self.nodes.set.pool_get(i), Cfg::M::ONE);
                }
                e - s
            }
            NodeRef::Lit(_) => 0,
        }
    }

    /// Read the child at position `pos` from a fixed-arity node. O(1).
    /// Panics if `pos` is out of range or node is variadic/lit.
    pub fn child_at(&self, id: Cfg::G, pos: Cfg::Index) -> Cfg::G {
        // `Cfg::Index`-wide: a position offsets into the node's span in the child pool,
        // which is sized by that word (see `IndexStore::by_child_pos`). `as_usize` is
        // exact for every `IndexLike`, so no check is needed on the way in; an
        // out-of-range position still lands on the arm's bounds check or the `panic!`.
        let p = pos.as_usize();
        match self.node_ref(id) {
            NodeRef::Plain1(l) => self.nodes.plain1.get(l).children[p],
            NodeRef::Plain2(l) => self.nodes.plain2.get(l).children[p],
            NodeRef::Plain3(l) => self.nodes.plain3.get(l).children[p],
            NodeRef::SPair(l) => self.nodes.spair.get(l).children[p],
            NodeRef::PlainN(l) => {
                let n = self.nodes.plain_n.get(l);
                let (s, _) = n.span();
                self.nodes.plain_n.pool_get(s + p)
            }
            NodeRef::Seq(l) => {
                let n = self.nodes.seq.get(l);
                let (s, _) = n.span();
                self.nodes.seq.pool_get(s + p)
            }
            _ => panic!("child_at: not a plain/sequence node or pos out of range"),
        }
    }

    /// Read AC children as `(id, multiplicity)` pairs into `buf`.
    pub fn mset_children(&self, id: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) {
        buf.clear();
        match self.node_ref(id) {
            NodeRef::MSet(l) => {
                let n = self.nodes.mset.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    let c = self.nodes.mset.pool_get(i);
                    buf.push((Cfg::mset_child_id(&c), Cfg::mset_child_mult(&c)));
                }
            }
            _ => panic!("mset_children: not an MSet node"),
        }
    }

    /// Flatten nested same-op AC children of `op` in `self.g_buf`, to a fixpoint
    /// (`WF_flat`, design §6c). Each element is examined by its class's *canonical summand
    /// form* (`summand_form`, §9a), NOT by its union-find representative (which depends on
    /// merge order and is therefore non-canonical):
    ///
    /// - if the child's class is **non-`atomic`** (a pure `op`-sum), splice in that class's
    ///   `min_monomial` children (each by multiplicity), recursively;
    /// - otherwise (the class is `atomic`: referenced as a child, or has a non-AC node) the
    ///   single atom `{class}` is its canonical summand form, so keep the child as a summand.
    ///
    /// `g_buf` already holds `find`'d ids. Preserves §5b: `+{a,b}` used as `neg`'s child is
    /// `atomic`, so it is kept, not flattened. The semantic invariants make recursive
    /// expansion well-founded; a work/output budget is nevertheless enforced in every build
    /// profile so corrupted cyclic state is refused instead of looping or returning a
    /// partially flattened node.
    fn flatten_ac_children(&mut self, op: Cfg::O) {
        // Move the buffers out to satisfy the borrow checker while reading `self`.
        let mut work = std::mem::take(&mut self.flatten_buf);
        let mut out = std::mem::take(&mut self.g_buf);
        // Seed the worklist with the current children (reverse, so popping preserves
        // a stable order — order doesn't matter for AC but keeps traces readable).
        work.clear();
        work.extend(out.iter().rev().copied());
        out.clear();

        // Safety cap on the children *splicing adds*, which is the only unbounded
        // quantity here. Each splice replaces a child by a strictly smaller monomial, so
        // a well-formed graph drains well under this bound; the cap only guards a
        // degenerate cyclic class, which we must not loop on.
        //
        // Measured from the caller's own child count, not from zero: the seeded children
        // are given, not generated, and a monomial may legitimately be far wider than the
        // graph is deep. Anchoring at zero made a plain `f(a, a, …)` with more children
        // than `1 + 64 * node_count()` trip the assertion below — a large-but-well-formed
        // input diagnosed as a cyclic class.
        let cap = work
            .len()
            .saturating_add(1)
            .saturating_add(64usize.saturating_mul(self.node_count()));
        let op_col = self.ops.completion_column(op);
        let mut expansions = 0usize;
        while let Some(g) = work.pop() {
            let cls = self.classes.find_const(g);
            // A child is a pure `op`-sum to splice iff its class is non-atomic AND its
            // canonical summand for `op`'s column (`min_monomial`) is an AC node of this same
            // `op`. Both reads are representative-independent (per-class pool), never
            // `find`-keyed.
            let mut spliced = false;
            if let Some(col) = op_col
                && let Some(repr) = self.classes.repr_id(cls)
                && !self.classes.atomic(repr)
                && let Some(min_node) = self.classes.min_monomial(repr, col)
                && self.node_op(min_node) == op
                && matches!(self.node_ref(min_node), NodeRef::MSet(_) | NodeRef::Set(_))
            {
                assert!(
                    expansions < cap && out.len() <= cap,
                    "flatten_ac_children exceeded work cap (degenerate cyclic AC class?)"
                );
                expansions += 1;
                // Expand the canonical summand form; `for_each_child` yields (class, count)
                // for either representation (a Set member counts once).
                self.for_each_child(min_node, |cg, times| {
                    for _ in 0..times.to_usize() {
                        work.push(cg);
                    }
                });
                spliced = true;
            }
            if !spliced {
                out.push(g);
            }
        }
        assert!(
            out.len() <= cap,
            "flatten_ac_children exceeded cap (degenerate cyclic AC class?)"
        );

        self.g_buf = out;
        self.flatten_buf = work;
    }

    /// The canonical same-`op` sequence node of `g`'s class, or `None` if the class is not a
    /// **pure `op`-sequence** — i.e. if any member is something other than an `op` `Seq` node.
    ///
    /// This is the A-only counterpart of the AC `summand_form` predicate
    /// (`ac-congruence-completeness.md` §6c) and it is chosen for the same reason: the answer
    /// must be a function of the class's *membership*, not of whichever node the union-find
    /// picked as representative (a representative-keyed test flattens or not depending on
    /// merge order, so it is not canonical — §6c's representative trap). Two consequences,
    /// both deliberate:
    ///
    /// - **Purity, not AC's `atomic`.** `atomic` cannot serve here: `register_if_fresh` sets
    ///   it on every class without a completion column, which includes every `Seq` class, so
    ///   for A-only ops it is constantly true. Purity plays the same role — a class holding
    ///   only `op`-sequences has no standalone atom form, so spelling it out is forced — and
    ///   it is what keeps a class that is *also* an atom from being spliced. That case is not
    ///   hypothetical: once a rule proves `gmul(b, inv(b)) = I`, `I`'s class holds a `Seq`
    ///   node, and splicing it into every later sequence would rewrite uphill and grow terms
    ///   without bound.
    /// - **The `op`-least member.** A class may hold several distinct `op`-sequences that were
    ///   merged; picking the least node id makes the choice a function of the class, and node
    ///   ids are assigned at creation and never renumbered, so this is merge-order independent.
    ///   Every spelling of the child therefore splices to the same sequence and the parents
    ///   land in one class.
    ///
    /// Cost is one class-ring walk, with an early exit on the first non-`op` member — so an
    /// ordinary atom child (a leaf, a constructor) costs its class's first member, and the
    /// full walk is paid only by classes that really are pure sequences.
    fn pure_seq_node(&self, g: Cfg::G, op: Cfg::O) -> Option<Cfg::G> {
        let cls = self.classes.find_const(g);
        let mut best: Option<Cfg::G> = None;
        for n in self.classes.iter_class(cls) {
            if self.node_op(n) != op || !matches!(self.node_ref(n), NodeRef::Seq(_)) {
                return None;
            }
            if best.is_none_or(|b| n.to_usize() < b.to_usize()) {
                best = Some(n);
            }
        }
        best
    }

    /// Flatten nested same-op children of an A-only (`Seq`) op in `self.g_buf`, to a fixpoint,
    /// **preserving order**: associativity licenses re-association, not reordering, so a
    /// spliced child's elements take the child's position in the parent's sequence.
    ///
    /// A child is spliced iff [`pure_seq_node`](Self::pure_seq_node) names an `op`-sequence
    /// for its class; otherwise it is kept as one element. Splicing recurses, because a
    /// spliced sequence's own elements may since have been merged into pure `op`-sequence
    /// classes.
    ///
    /// `g_buf` already holds `find`'d ids. The least-node choice makes expansion
    /// well-founded for a valid append-only graph. The same work/output budget as
    /// `flatten_ac_children` is still enforced in every build profile: malformed state such
    /// as `X = {seq(X)}` is refused rather than looping or producing a partial normal form.
    fn flatten_seq_children(&mut self, op: Cfg::O) {
        // Move the buffers out to satisfy the borrow checker while reading `self`.
        let mut work = std::mem::take(&mut self.flatten_buf);
        let mut out = std::mem::take(&mut self.g_buf);
        // Seed the worklist reversed, so popping yields the children in sequence order — for
        // A this is load-bearing, not cosmetic as in the AC counterpart.
        work.clear();
        work.extend(out.iter().rev().copied());
        out.clear();
        let cap = work
            .len()
            .saturating_add(1)
            .saturating_add(64usize.saturating_mul(self.node_count()));
        let mut expansions = 0usize;
        while let Some(g) = work.pop() {
            let mut spliced = false;
            if let Some(inner) = self.pure_seq_node(g, op)
                && let NodeRef::Seq(l) = self.node_ref(inner)
            {
                assert!(
                    expansions < cap && out.len() <= cap,
                    "flatten_seq_children exceeded work cap (degenerate cyclic A class?)"
                );
                expansions += 1;
                let (s, e) = self.nodes.seq.get(l).span();
                // Reversed again, so the elements pop back in their stored order.
                for i in (s..e).rev() {
                    work.push(self.nodes.seq.pool_get(i));
                }
                spliced = true;
            }
            if !spliced {
                out.push(g);
            }
        }
        assert!(
            out.len() <= cap,
            "flatten_seq_children exceeded cap (degenerate cyclic A class?)"
        );

        self.g_buf = out;
        self.flatten_buf = work;
    }

    /// Read ACI children (ids only, no multiplicities) into `buf`.
    pub fn set_children(&self, id: Cfg::G, buf: &mut Vec<Cfg::G>) {
        buf.clear();
        match self.node_ref(id) {
            NodeRef::Set(l) => {
                let n = self.nodes.set.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    buf.push(self.nodes.set.pool_get(i));
                }
            }
            _ => panic!("set_children: not a Set node"),
        }
    }

    /// Read A/PlainN children into `buf` in sequence order.
    pub fn seq_children(&self, id: Cfg::G, buf: &mut Vec<Cfg::G>) {
        buf.clear();
        match self.node_ref(id) {
            NodeRef::PlainN(l) => {
                let n = self.nodes.plain_n.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    buf.push(self.nodes.plain_n.pool_get(i));
                }
            }
            NodeRef::Seq(l) => {
                let n = self.nodes.seq.get(l);
                let (s, e) = n.span();
                for i in s..e {
                    buf.push(self.nodes.seq.pool_get(i));
                }
            }
            _ => panic!("seq_children: not a sequence node"),
        }
    }

    pub fn node_lit(&self, id: Cfg::G) -> Option<Cfg::V> {
        match self.node_ref(id) {
            NodeRef::Lit(l) => Some(self.nodes.lit.get(l).lit),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::id::{OpId, SortId};
    use crate::lit_model::LitModel;
    use crate::literal::NiraLitVal;

    struct Th {
        int: SortId,
        x: OpId,
        y: OpId,
        z: OpId,
        w: OpId,
        f: OpId,
        g: OpId,
        h: OpId,
        eq: OpId,
        plus: OpId,
        and: OpId,
        sub: OpId,
        f4: OpId,
    }

    fn eg<const T: bool, const P: bool>() -> (EGraph31<NiraLitVal, T, P>, Th) {
        let mut eg = EGraph31::new();
        let int = eg.intern_sort("Int");
        let th = Th {
            int,
            x: eg.register_op0("x", int),
            y: eg.register_op0("y", int),
            z: eg.register_op0("z", int),
            w: eg.register_op0("w", int),
            f: eg.register_op1("f", int, int),
            g: eg.register_op2("g", int, int, int),
            h: eg.register_op3("h", int, int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            plus: eg.register_mset("plus", int, int),
            and: eg.register_set("and", int, int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            f4: eg.register_opn("f4", &[int, int, int, int], int),
        };
        (eg, th)
    }

    /// Randomized canonization coverage for the AC count-clamp / identity-drop / degenerate-arity
    /// normal form, with completion OFF (these are canonization facts, not completion — see the
    /// design doc "Canonization, not completion"). The oracle is an *independent* reference
    /// normalizer (`ref_normal`), so `add` is checked against a from-scratch computation of what
    /// the canonical class should be, over random inputs — the coverage the hand-written fixtures
    /// lack. Exercises plain AC, nilpotent order 2 AND order 3, idempotent, and identity, and both
    /// the build path (`add`) and the recanonize path (build distinct, then merge children).
    mod canonize_prop {
        use super::*;
        use crate::registry::{Clamp, OpKind};
        use proptest::prelude::*;
        use std::collections::BTreeMap;

        type Cfg31G = crate::id::ENodeId;

        /// Which AC op a random term uses; each is a distinct registered op sharing one sort.
        #[derive(Clone, Copy, Debug)]
        enum Kind {
            PlainAc,      // + : ℕ counts, no unit
            Nilpotent2,   // xor : count mod 2, unit e
            Nilpotent3,   // nz  : count mod 3, unit e
            Idempotent,   // and : count → 1
            IdentityPlus, // ip  : ℕ counts, unit e dropped
        }

        struct Env {
            eg: EGraph31<NiraLitVal, false, false>,
            atoms: Vec<Cfg31G>, // the 4 leaf classes usable as children
            unit: Cfg31G,       // the declared unit `e`
            plain: OpId,
            nil2: OpId,
            nil3: OpId,
            idem: OpId,
            ident: OpId,
        }

        fn op_of(env: &Env, k: Kind) -> OpId {
            match k {
                Kind::PlainAc => env.plain,
                Kind::Nilpotent2 => env.nil2,
                Kind::Nilpotent3 => env.nil3,
                Kind::Idempotent => env.idem,
                Kind::IdentityPlus => env.ident,
            }
        }

        fn make_env() -> Env {
            let mut eg = EGraph31::<NiraLitVal, false, false>::new();
            let s = eg.intern_sort("E");
            let e_op = eg.register_op0("e", s);
            let unit = eg.add(e_op, &[]);
            // The descriptor's `identity: UnitRef` is only read by the sortcheck resolver; the
            // egraph resolves the unit via `set_unit_node` (below), so pass `None` here. The clamp
            // field is what canonization reads.
            let mk = |eg: &mut EGraph31<NiraLitVal, false, false>, name: &str, clamp: Clamp| {
                eg.register_kind(
                    name,
                    s,
                    OpKind::MSet {
                        arg_sort: s,
                        clamp,
                        identity: None,
                        cancellative: false,
                    },
                )
            };
            let plain = mk(&mut eg, "plus", Clamp::None);
            let nil2 = mk(&mut eg, "xr2", Clamp::Nilpotent { order: 2 });
            let nil3 = mk(&mut eg, "xr3", Clamp::Nilpotent { order: 3 });
            let idem = eg.register_kind(
                "andop",
                s,
                OpKind::Set {
                    arg_sort: s,
                    clamp: Clamp::Idempotent,
                    identity: None,
                    cancellative: false,
                },
            );
            let ident = mk(&mut eg, "ip", Clamp::None);
            eg.set_unit_node(nil2, unit);
            eg.set_unit_node(nil3, unit);
            eg.set_unit_node(ident, unit);
            let a = eg.register_op0("a", s);
            let b = eg.register_op0("b", s);
            let c = eg.register_op0("c", s);
            let d = eg.register_op0("d", s);
            let atoms = vec![
                eg.add(a, &[]),
                eg.add(b, &[]),
                eg.add(c, &[]),
                eg.add(d, &[]),
            ];
            Env {
                eg,
                atoms,
                unit,
                plain,
                nil2,
                nil3,
                idem,
                ident,
            }
        }

        /// Independent reference: the canonical class a well-formed AC term over `children` (given
        /// as current class ids) should land in, computed from scratch — the oracle. Mirrors the
        /// *spec*: coalesce by class → drop unit (ops with an identity) → clamp counts → resolve
        /// degeneracy (empty ⇒ unit, single mult-1 ⇒ that child, else a built node).
        fn ref_normal(env: &mut Env, k: Kind, children: &[Cfg31G]) -> Cfg31G {
            let has_unit = matches!(k, Kind::Nilpotent2 | Kind::Nilpotent3 | Kind::IdentityPlus);
            let unit_cls = env.eg.find(env.unit);
            let mut counts: BTreeMap<u32, u32> = BTreeMap::new();
            for &g in children {
                *counts.entry(env.eg.find(g).raw()).or_insert(0) += 1;
            }
            if has_unit {
                counts.remove(&unit_cls.raw());
            }
            match k {
                Kind::Idempotent => {
                    for v in counts.values_mut() {
                        *v = 1;
                    }
                }
                Kind::Nilpotent2 => counts.retain(|_, v| {
                    *v %= 2;
                    *v != 0
                }),
                Kind::Nilpotent3 => counts.retain(|_, v| {
                    *v %= 3;
                    *v != 0
                }),
                Kind::PlainAc | Kind::IdentityPlus => {}
            }
            let total: u32 = counts.values().sum();
            if total == 0 {
                return env.eg.find(env.unit);
            }
            if counts.len() == 1 && *counts.values().next().unwrap() == 1 {
                return env
                    .eg
                    .find(crate::id::ENodeId::new(*counts.keys().next().unwrap()));
            }
            let mut flat: Vec<Cfg31G> = Vec::new();
            for (cls, cnt) in &counts {
                for _ in 0..*cnt {
                    flat.push(crate::id::ENodeId::new(*cls));
                }
            }
            let op = op_of(env, k);
            env.eg.add(op, &flat)
        }

        fn all_kinds() -> impl Strategy<Value = Kind> {
            prop_oneof![
                Just(Kind::PlainAc),
                Just(Kind::Nilpotent2),
                Just(Kind::Nilpotent3),
                Just(Kind::Idempotent),
                Just(Kind::IdentityPlus),
            ]
        }

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(400))]

            /// `add` must agree with the independent reference normalizer, and be permutation-
            /// invariant (AC). Child index 4 selects the unit, so unit-drop is exercised.
            /// Completion is OFF: this is pure canonization.
            #[test]
            fn add_matches_reference(
                k in all_kinds(),
                idxs in proptest::collection::vec(0usize..5, 1..8),
                perm_seed in any::<u64>(),
            ) {
                let mut env = make_env();
                let pick = |i: usize, env: &Env| if i < 4 { env.atoms[i] } else { env.unit };
                let children: Vec<Cfg31G> = idxs.iter().map(|&i| pick(i, &env)).collect();

                let op = op_of(&env, k);
                let built = env.eg.add(op, &children);
                let expected = ref_normal(&mut env, k, &children);
                prop_assert_eq!(
                    env.eg.find(built),
                    env.eg.find(expected),
                    "add vs reference: kind={:?} idxs={:?}", k, idxs
                );

                let mut shuffled = children.clone();
                let n = shuffled.len();
                for i in 0..n {
                    let j = ((perm_seed.wrapping_mul(6364136223846793005).wrapping_add(i as u64))
                        as usize) % n;
                    shuffled.swap(i, j);
                }
                let built2 = env.eg.add(op, &shuffled);
                prop_assert_eq!(env.eg.find(built), env.eg.find(built2), "permutation invariance");
            }

            /// Recanonize path: build a node with distinct children, merge a pair of children,
            /// rebuild (completion OFF → congruence + canonization only). The node's class must
            /// match the reference recomputed with the merge applied.
            #[test]
            fn recanonize_matches_reference(
                k in all_kinds(),
                idxs in proptest::collection::vec(0usize..4, 2..6),
                mi in 0usize..4,
                mj in 0usize..4,
            ) {
                prop_assume!(mi != mj);
                let mut env = make_env();
                let children: Vec<Cfg31G> = idxs.iter().map(|&i| env.atoms[i]).collect();
                let op = op_of(&env, k);
                let node = env.eg.add(op, &children);

                env.eg.merge(env.atoms[mi], env.atoms[mj]);
                env.eg.rebuild();

                let expected = ref_normal(&mut env, k, &children);
                prop_assert_eq!(
                    env.eg.find(node),
                    env.eg.find(expected),
                    "recanonize vs reference: kind={:?} idxs={:?} merge {}->{}", k, idxs, mi, mj
                );
            }
        }
    }

    #[test]
    fn congruence_plain() {
        let (ref mut eg, th) = eg::<false, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let fx = eg.add(th.f, &[x]);
        let fy = eg.add(th.f, &[y]);
        assert_ne!(eg.find(fx), eg.find(fy));
        eg.merge(x, y);
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));
    }

    #[test]
    fn commutative_dedup() {
        let (ref mut eg, th) = eg::<false, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        assert_eq!(eg.add(th.eq, &[x, y]), eg.add(th.eq, &[y, x]));
    }

    // The per-class min-monomial pool column for the `plus` op tracks the degree-lex-least
    // `plus`-monomial across merges, and rolls back with the e-graph token. A leaf constant is
    // NOT a `plus`-monomial (it has no `plus` column); merging it in makes the class `atomic`
    // rather than lowering the `plus` column. See design §9a and the pool design in
    // `doc/design/ac-algebraic-properties.md`.
    #[test]
    fn min_monomial_tracks_least_and_rolls_back() {
        let (ref mut eg, th) = eg::<true, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let c = eg.add(th.w, &[]); // a leaf constant, to merge a sum into
        let s_xy = eg.add(th.plus, &[x, y]); // +{x,y}, size 2
        let s_xyz = eg.add(th.plus, &[x, y, z]); // +{x,y,z}, size 3

        // A fresh `plus` node's class holds itself in the `plus` column; a non-completion
        // constant has no completion column at all.
        assert_eq!(eg.class_min_monomial(s_xy), Some(s_xy));
        assert_eq!(eg.class_min_monomial(c), None);

        // Merge the two sums: the smaller monomial (+{x,y}, size 2) wins over +{x,y,z}.
        eg.merge(s_xy, s_xyz);
        let repr_min = eg.class_min_monomial(s_xy).unwrap();
        assert_eq!(eg.class_repr(repr_min), eg.class_repr(s_xy));
        assert_eq!(repr_min, s_xy, "min_monomial should pick the smaller sum");

        // Snapshot, then merge the leaf constant c in: the class becomes `atomic` (a constant
        // is its normal-form representative), while the `plus` column still holds the sum.
        let token = eg.mark(ShrinkPolicy::Never);
        eg.merge(c, s_xy);
        assert_eq!(
            eg.class_atomic(c),
            Some(true),
            "merging a constant in makes the class atomic"
        );
        assert_eq!(
            eg.class_min_monomial(s_xy),
            Some(s_xy),
            "the plus column keeps the least sum after the constant merge"
        );

        // Restore: the post-token merge is undone, atomicity reverts.
        eg.restore(token);
        assert_eq!(
            eg.class_min_monomial(s_xy),
            Some(s_xy),
            "min_monomial must roll back with the e-graph token"
        );
        assert_eq!(
            eg.class_atomic(s_xy),
            Some(false),
            "atomicity must roll back with the e-graph token"
        );
    }

    #[test]
    fn congruence_undone_by_restore() {
        let (ref mut eg, th) = eg::<true, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let fx = eg.add(th.f, &[x]);
        let fy = eg.add(th.f, &[y]);
        let token = eg.mark(ShrinkPolicy::Never);
        eg.merge(x, y);
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));
        eg.restore(token);
        assert_ne!(eg.find(fx), eg.find(fy));
    }

    #[test]
    fn cascading_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let fx = eg.add(th.f, &[x]);
        let fy = eg.add(th.f, &[y]);
        let ffx = eg.add(th.f, &[fx]);
        let ffy = eg.add(th.f, &[fy]);
        eg.merge(x, y);
        eg.rebuild();
        assert_eq!(eg.find(ffx), eg.find(ffy));
    }

    #[test]
    fn ac_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
        let n1 = eg.add(th.plus, &[a, b]);
        let n2 = eg.add(th.plus, &[a, c]);
        eg.merge(b, c);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    #[test]
    fn aci_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
        let n1 = eg.add(th.and, &[a, b]);
        let n2 = eg.add(th.and, &[a, c]);
        eg.merge(b, c);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    #[test]
    fn aci_dedup_after_merge() {
        let (ref mut eg, th) = eg::<false, false>();
        let a = eg.add(th.x, &[]);
        let b = eg.add(th.y, &[]);
        let ab = eg.add(th.and, &[a, b]);
        let aa = eg.add(th.and, &[a]);
        eg.merge(a, b);
        eg.rebuild();
        assert_eq!(eg.find(ab), eg.find(aa));
    }

    #[test]
    fn hashcons_dedup() {
        let (ref mut eg, th) = eg::<false, false>();
        let x = eg.add(th.x, &[]);
        assert_eq!(eg.add(th.f, &[x]), eg.add(th.f, &[x]));
        assert_eq!(eg.len(), 2);
    }

    #[test]
    fn add_canonicalizes() {
        let (ref mut eg, th) = eg::<false, false>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let fx = eg.add(th.f, &[x]);
        eg.merge(x, y);
        assert_eq!(fx, eg.add(th.f, &[y]));
    }

    #[test]
    fn rebuild_empty() {
        let (ref mut eg, _) = eg::<false, false>();
        eg.rebuild();
    }

    #[test]
    fn add_after_restore() {
        let (ref mut eg, th) = eg::<true, false>();
        let x = eg.add(th.x, &[]);
        let token = eg.mark(ShrinkPolicy::Never);
        eg.add(th.f, &[x]);
        assert_eq!(eg.len(), 2);
        eg.restore(token);
        assert_eq!(eg.len(), 1);
        let gxx = eg.add(th.g, &[x, x]);
        assert_eq!(gxx, eg.add(th.g, &[x, x]));
    }

    #[test]
    fn rebuild_after_restore() {
        let (ref mut eg, th) = eg::<true, false>();
        let (x, y, z) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
        let (fx, fy, fz) = (eg.add(th.f, &[x]), eg.add(th.f, &[y]), eg.add(th.f, &[z]));
        let token = eg.mark(ShrinkPolicy::Never);
        eg.merge(x, y);
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));
        eg.restore(token);
        assert_ne!(eg.find(fx), eg.find(fy));
        eg.merge(x, z);
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fz));
        assert_ne!(eg.find(fx), eg.find(fy));
    }

    // -- Proofs --

    #[test]
    fn explain_non_equivalent() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let mut buf = ProofBuf::new();
        assert!(!eg.explain(x, y, &mut buf));
    }

    #[test]
    fn explain_axiom() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(42),
            },
        );
        let mut buf = ProofBuf::new();
        eg.explain(x, y, &mut buf);
        assert!(buf.steps.iter().any(|&(_, _, j)| j
            == Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(42)
            }));
    }

    #[test]
    fn explain_chain() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(1),
            },
        );
        eg.merge_justified(
            y,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(2),
            },
        );
        let mut buf = ProofBuf::new();
        eg.explain(x, z, &mut buf);
        for (from, to, just) in &buf.steps {
            eprintln!("  {:?} ≡ {:?}  by {:?}", from, to, just);
        }
        assert!(buf.steps.len() >= 2);
    }

    #[test]
    fn lca_batch_explanations_match_regular_explanations() {
        let (ref mut eg, th) = eg::<false, true>();
        let nodes = [
            eg.add(th.x, &[]),
            eg.add(th.y, &[]),
            eg.add(th.z, &[]),
            eg.add(th.w, &[]),
        ];
        for (i, &(a, b)) in [
            (nodes[0], nodes[1]),
            (nodes[2], nodes[3]),
            (nodes[1], nodes[2]),
        ]
        .iter()
        .enumerate()
        {
            eg.merge_justified(
                a,
                b,
                Justification::Axiom {
                    axiom_id: crate::id::AxiomId::new(i as u16),
                },
            );
        }

        let table = crate::lca::LcaTable::build(
            eg.classes
                .proof_parent()
                .expect("PROOFS=true has a proof forest"),
            eg.len(),
        );
        for node in nodes {
            let representative = eg.find_const(node);
            let lca = table
                .lca(node, representative)
                .expect("equivalent nodes share a proof tree");
            let mut ordinary = ProofBuf::new();
            let mut indexed = ProofBuf::new();
            assert!(eg.explain(node, representative, &mut ordinary));
            assert!(
                eg.classes
                    .explain_with_lca(node, representative, lca, &mut indexed)
            );
            assert_eq!(indexed.steps, ordinary.steps);
        }
    }

    #[test]
    fn dump_all_proofs_covers_every_node() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(7),
            },
        );
        eg.merge_justified(
            y,
            z,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(8),
            },
        );

        let mut dump = Vec::new();
        let stats = eg.dump_all_proofs(&mut dump).expect("proof dump");
        assert_eq!(stats.terms, eg.len());
        assert_eq!(stats.nontrivial_proofs, 2);
        assert!(stats.steps >= 2);

        let text = String::from_utf8(dump).expect("UTF-8 proof dump");
        assert!(text.starts_with("# semi-persistent-proof-dump v1\n"));
        assert_eq!(
            text.lines()
                .filter(|line| line.starts_with("term "))
                .count(),
            3
        );
        assert!(text.contains("axiom id=7"));
        assert!(text.contains("axiom id=8"));
        assert!(text.contains("summary terms 3 nontrivial 2"));
    }

    #[test]
    fn dump_all_proofs_rejects_proof_disabled_graph() {
        let (ref mut eg, th) = eg::<false, false>();
        eg.add(th.x, &[]);
        let err = eg
            .dump_all_proofs(Vec::new())
            .expect_err("PROOFS=false must reject proof dumps");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
    }

    #[test]
    fn explain_after_restore() {
        let (ref mut eg, th) = eg::<true, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let token = eg.mark(ShrinkPolicy::Never);
        eg.merge_justified(
            x,
            y,
            Justification::Axiom {
                axiom_id: crate::id::AxiomId::new(0),
            },
        );
        let mut buf = ProofBuf::new();
        assert!(eg.explain(x, y, &mut buf));
        eg.restore(token);
        buf.clear();
        assert!(!eg.explain(x, y, &mut buf));
    }

    /// Regression: `union()` on a PROOFS=true UF must panic, not silently
    /// leave a stale justification.
    #[test]
    #[should_panic(expected = "union() called on a PROOFS=true UnionFind")]
    fn union_without_justification_panics_on_proofs() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        eg.merge(x, y); // must panic
    }

    /// Every step returned by `explain()` must carry the justification that
    /// was explicitly provided via `merge_justified`, never a stale default.
    #[test]
    fn explain_no_stale_justifications() {
        let (ref mut eg, th) = eg::<false, true>();
        let x = eg.add(th.x, &[]);
        let y = eg.add(th.y, &[]);
        let z = eg.add(th.z, &[]);
        let ax1 = crate::id::AxiomId::new(10);
        let ax2 = crate::id::AxiomId::new(20);
        eg.merge_justified(x, y, Justification::Axiom { axiom_id: ax1 });
        eg.merge_justified(y, z, Justification::Axiom { axiom_id: ax2 });
        let mut buf = ProofBuf::new();
        eg.explain(x, z, &mut buf);
        for &(_, _, just) in &buf.steps {
            match just {
                Justification::Axiom { axiom_id } => {
                    assert!(
                        axiom_id == ax1 || axiom_id == ax2,
                        "unexpected axiom_id {axiom_id:?} in proof step"
                    );
                }
                Justification::Congruence { .. } => {}
                Justification::Rewrite { .. } => {}
                Justification::Filler => unreachable!("filler is never a real proof step"),
                Justification::ACSuperposition { .. }
                | Justification::ACInterReduction { .. }
                | Justification::ACAxiomCP { .. }
                | Justification::Cancellative { .. }
                | Justification::InverseCancel { .. } => {
                    panic!("algebraic justification in a non-completion test")
                }
            }
        }
    }

    // -- Rebuild coverage ---------------------------------------------------

    /// Plain3 congruence: h(x,y,z) ≡ h(w,y,z) after merge(x,w)
    #[test]
    fn congruence_plain3() {
        let (ref mut eg, th) = eg::<false, false>();
        let (x, y, z, w) = (
            eg.add(th.x, &[]),
            eg.add(th.y, &[]),
            eg.add(th.z, &[]),
            eg.add(th.w, &[]),
        );
        let n1 = eg.add(th.h, &[x, y, z]);
        let n2 = eg.add(th.h, &[w, y, z]);
        eg.merge(x, w);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    /// C-node congruence: eq(a,b) and eq(w,c) collide after merge(a,w), merge(b,c)
    #[test]
    fn commutative_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c, w) = (
            eg.add(th.x, &[]),
            eg.add(th.y, &[]),
            eg.add(th.z, &[]),
            eg.add(th.w, &[]),
        );
        let e1 = eg.add(th.eq, &[a, b]);
        let e2 = eg.add(th.eq, &[w, c]);
        eg.merge(a, w);
        eg.merge(b, c);
        eg.rebuild();
        assert_eq!(eg.find(e1), eg.find(e2));
    }

    /// C-node: find changes order but no collision (just reindex)
    #[test]
    fn commutative_reorder_no_collision() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
        let e = eg.add(th.eq, &[a, b]);
        eg.merge(a, b);
        eg.rebuild();
        let _ = eg.find(e);
    }

    /// PlainN congruence: f4(a,b,c,d) ≡ f4(a,e,c,d) after merge(b,e)
    #[test]
    fn plain_n_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let a = eg.add(th.x, &[]);
        let b = eg.add(th.y, &[]);
        let c = eg.add(th.z, &[]);
        let d = eg.add(th.w, &[]);
        let e_op = eg.register_op0("e", th.int);
        let e = eg.add(e_op, &[]);
        let n1 = eg.add(th.f4, &[a, b, c, d]);
        let n2 = eg.add(th.f4, &[a, e, c, d]);
        eg.merge(b, e);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    /// A-node congruence (associative, ordered)
    #[test]
    fn a_congruence() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
        let n1 = eg.add(th.sub, &[a, b]);
        let n2 = eg.add(th.sub, &[a, c]);
        eg.merge(b, c);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    /// The flattening guard must count expansion work, not only emitted output.
    /// A malformed self-expansion emits nothing, so the former `out.len()` guard
    /// never advanced and this call looped forever. Production construction cannot
    /// create this state; mutating the private child pool models defensive handling
    /// of corrupted data at the exact boundary the guard protects.
    #[test]
    #[should_panic(expected = "flatten_seq_children exceeded work cap")]
    fn associative_flatten_refuses_nonprogressing_cycle() {
        let (ref mut eg, th) = eg::<false, false>();
        let a = eg.add(th.x, &[]);
        let seq = eg.add(th.sub, &[a, a]);
        let NodeRef::Seq(local) = eg.node_ref(seq) else {
            panic!("associative node must use the Seq partition");
        };
        let (start, end) = eg.nodes.seq.get(local).span();
        assert_eq!(end - start, 2);
        eg.nodes.seq.pool_set(start, seq);
        eg.nodes.seq.pool_set(start + 1, seq);

        eg.g_buf.clear();
        eg.g_buf.push(seq);
        eg.flatten_seq_children(th.sub);
    }

    /// AC: different multiplicities after merge → no false collision
    #[test]
    fn ac_multiplicity_no_false_collision() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c, d) = (
            eg.add(th.x, &[]),
            eg.add(th.y, &[]),
            eg.add(th.z, &[]),
            eg.add(th.w, &[]),
        );
        let n1 = eg.add(th.plus, &[a, b, c]); // plus(a,b,c)
        let n2 = eg.add(th.plus, &[a, d]); // plus(a,d)
        eg.merge(b, d);
        eg.merge(c, d);
        eg.rebuild();
        // n1 → plus(a,2*repr_d), n2 → plus(a,repr_d) — NOT equal
        assert_ne!(eg.find(n1), eg.find(n2));
    }

    /// AC shrink: plus(a,a,b) after merge(a,b) → plus((repr,3))
    #[test]
    fn ac_shrink_after_merge() {
        let (ref mut eg, th) = eg::<false, false>();
        let a = eg.add(th.x, &[]);
        let b = eg.add(th.y, &[]);
        let n1 = eg.add(th.plus, &[a, a, b]); // plus((a,2),(b,1))
        let n2 = eg.add(th.plus, &[a, a, a]); // plus((a,3))
        eg.merge(a, b);
        eg.rebuild();
        assert_eq!(eg.find(n1), eg.find(n2));
    }

    /// Multiple merges before rebuild: worklist starts with >1 entry
    #[test]
    fn multiple_merges_before_rebuild() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b, c, d) = (
            eg.add(th.x, &[]),
            eg.add(th.y, &[]),
            eg.add(th.z, &[]),
            eg.add(th.w, &[]),
        );
        let fa = eg.add(th.f, &[a]);
        let fb = eg.add(th.f, &[b]);
        let fc = eg.add(th.f, &[c]);
        let fd = eg.add(th.f, &[d]);
        eg.merge(a, b);
        eg.merge(c, d);
        eg.rebuild();
        assert_eq!(eg.find(fa), eg.find(fb));
        assert_eq!(eg.find(fc), eg.find(fd));
        assert_ne!(eg.find(fa), eg.find(fc));
    }

    /// Diamond: g(a,b) uses both a and b; merge a and b
    #[test]
    fn diamond_fan_in() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
        let gab = eg.add(th.g, &[a, b]);
        eg.merge(a, b);
        eg.rebuild();
        let _ = eg.find(gab);
    }

    /// Fan-out: many parents of different kinds share the same child
    #[test]
    fn fan_out_many_parents() {
        let (ref mut eg, th) = eg::<false, false>();
        let a = eg.add(th.x, &[]);
        let b = eg.add(th.y, &[]);
        let p0 = eg.add(th.f, &[a]);
        let p1 = eg.add(th.g, &[a, a]);
        let p2 = eg.add(th.eq, &[a, a]);
        let p3 = eg.add(th.plus, &[a, b]);
        let p4 = eg.add(th.and, &[a, b]);
        eg.merge(a, b);
        eg.rebuild();
        for &p in &[p0, p1, p2, p3, p4] {
            let _ = eg.find(p);
        }
    }

    /// Deep cascade: merge at leaf propagates through 4 levels
    #[test]
    fn deep_cascade_4_levels() {
        let (ref mut eg, th) = eg::<false, false>();
        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
        let fa = eg.add(th.f, &[a]);
        let fb = eg.add(th.f, &[b]);
        let ffa = eg.add(th.f, &[fa]);
        let ffb = eg.add(th.f, &[fb]);
        let fffa = eg.add(th.f, &[ffa]);
        let fffb = eg.add(th.f, &[ffb]);
        let ffffa = eg.add(th.f, &[fffa]);
        let ffffb = eg.add(th.f, &[fffb]);
        eg.merge(a, b);
        eg.rebuild();
        assert_eq!(eg.find(ffffa), eg.find(ffffb));
    }

    #[test]
    fn egraph63_smoke() {
        let mut eg = EGraph63::<NiraLitVal, false, false>::new();
        let int = eg.intern_sort("Int");
        let f = eg.register_op1("f", int, int);
        let x_op = eg.register_op0("x", int);
        let y_op = eg.register_op0("y", int);
        let x = eg.add(x_op, &[]);
        let y = eg.add(y_op, &[]);
        let fx = eg.add(f, &[x]);
        let fy = eg.add(f, &[y]);
        eg.merge(x, y);
        eg.rebuild();
        assert_eq!(eg.find(fx), eg.find(fy));
    }

    #[test]
    fn from_model_registers_builtins() {
        use crate::literal::NiraModel;
        let model = NiraModel;
        let eg = EGraph31::<NiraLitVal, false, false>::from_model(&model);
        for sort_desc in model.sorts() {
            let id = eg.sorts().id_by_name(sort_desc.name).unwrap();
            assert!(
                eg.sorts().is_builtin(id),
                "sort '{}' should be builtin",
                sort_desc.name
            );
        }
        for op_desc in model.ops() {
            let id = eg.ops().id_by_name(op_desc.name).unwrap();
            assert!(
                eg.ops().is_builtin(id),
                "op '{}' should be builtin",
                op_desc.name
            );
        }
    }

    #[test]
    #[should_panic(expected = "already registered")]
    fn from_model_rejects_op_collision() {
        use crate::literal::NiraModel;
        let mut eg = EGraph31::<NiraLitVal, false, false>::from_model(&NiraModel);
        let int = eg.intern_sort("Int");
        // "+" is a builtin op from NiraModel, registering again should panic
        eg.register_op2("+", int, int, int);
    }

    // Multiple MSet symbols are now supported (per-op min-monomial pool, step 4): rebuild with
    // two AC ops registered no longer panics. (End-to-end independence is checked by the
    // `ac_complete_multi_mset.egg` fixture.)
    #[test]
    fn cc_allows_two_mset_symbols() {
        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
        let int = eg.intern_sort("Int");
        let _plus = eg.register_mset("plus", int, int);
        let _times = eg.register_mset("times", int, int);
        eg.set_cc(true);
        eg.rebuild(); // two MSet ops => allowed, completes each independently
    }

    // One MSet op plus a Set (ACI) op is fine.
    #[test]
    fn cc_allows_one_mset_symbol() {
        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
        let int = eg.intern_sort("Int");
        let _plus = eg.register_mset("plus", int, int);
        let _and = eg.register_set("and", int, int);
        eg.set_cc(true);
        eg.rebuild();
    }
}

/// Run all core e-graph tests with both 31-bit and 63-bit configs.
#[cfg(test)]
mod dual_config_tests {
    use crate::canon::{MSetCanon, VarCanon};
    use crate::config::EGraphConfig;
    use crate::containers::ShrinkPolicy;
    use crate::egraph::EGraph;
    use crate::literal::NiraLitVal;
    use crate::union_find::{Justification, ProofBuf};

    struct Th<Cfg: EGraphConfig> {
        x: Cfg::O,
        y: Cfg::O,
        z: Cfg::O,
        w: Cfg::O,
        f: Cfg::O,
        h: Cfg::O,
        eq: Cfg::O,
        plus: Cfg::O,
        and: Cfg::O,
        sub: Cfg::O,
        f4: Cfg::O,
        lit_op: Cfg::O,
    }

    fn setup<Cfg: EGraphConfig, const T: bool, const P: bool>()
    -> (EGraph<Cfg, NiraLitVal, T, P>, Th<Cfg>)
    where
        MSetCanon: VarCanon<Cfg::G, Cfg::C>,
    {
        let mut eg = EGraph::new();
        let int = eg.intern_sort("Int");
        let th = Th {
            x: eg.register_op0("x", int),
            y: eg.register_op0("y", int),
            z: eg.register_op0("z", int),
            w: eg.register_op0("w", int),
            f: eg.register_op1("f", int, int),
            h: eg.register_op3("h", int, int, int, int),
            eq: eg.register_c("eq", [int, int], int),
            plus: eg.register_mset("plus", int, int),
            and: eg.register_set("and", int, int),
            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
            f4: eg.register_opn("f4", &[int, int, int, int], int),
            lit_op: eg.register_lit("lit", int),
        };
        (eg, th)
    }

    macro_rules! dual {
        ($(fn $name:ident<$Cfg:ident>() $body:block)*) => {$(
            mod $name {
                use super::*;
                fn run<$Cfg: EGraphConfig>() where MSetCanon: VarCanon<$Cfg::G, $Cfg::C> $body
                #[test] fn bits31() { run::<crate::nodes::DefaultConfig>(); }
                #[test] fn bits63() { run::<crate::nodes::Config64>(); }
            }
        )*};
    }

    dual! {
        fn congruence_plain<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let fx = eg.add(th.f, &[x]);
            let fy = eg.add(th.f, &[y]);
            eg.merge(x, y);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fy));
        }

        fn commutative_dedup<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            assert_eq!(eg.add(th.eq, &[x, y]), eg.add(th.eq, &[y, x]));
        }

        fn cascading_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let fx = eg.add(th.f, &[x]);
            let fy = eg.add(th.f, &[y]);
            let ffx = eg.add(th.f, &[fx]);
            let ffy = eg.add(th.f, &[fy]);
            eg.merge(x, y);
            eg.rebuild();
            assert_eq!(eg.find(ffx), eg.find(ffy));
        }

        fn ac_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
            let n1 = eg.add(th.plus, &[a, b]);
            let n2 = eg.add(th.plus, &[a, c]);
            eg.merge(b, c);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn aci_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
            let n1 = eg.add(th.and, &[a, b]);
            let n2 = eg.add(th.and, &[a, c]);
            eg.merge(b, c);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn aci_dedup_after_merge<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let a = eg.add(th.x, &[]);
            let b = eg.add(th.y, &[]);
            let ab = eg.add(th.and, &[a, b]);
            let aa = eg.add(th.and, &[a]);
            eg.merge(a, b);
            eg.rebuild();
            assert_eq!(eg.find(ab), eg.find(aa));
        }

        fn hashcons_dedup<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let x = eg.add(th.x, &[]);
            assert_eq!(eg.add(th.f, &[x]), eg.add(th.f, &[x]));
            assert_eq!(eg.len(), 2);
        }

        fn add_canonicalizes<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let fx = eg.add(th.f, &[x]);
            eg.merge(x, y);
            assert_eq!(fx, eg.add(th.f, &[y]));
        }

        fn congruence_undone_by_restore<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, true, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let fx = eg.add(th.f, &[x]);
            let fy = eg.add(th.f, &[y]);
            let token = eg.mark(ShrinkPolicy::Never);
            eg.merge(x, y);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fy));
            eg.restore(token);
            assert_ne!(eg.find(fx), eg.find(fy));
        }

        fn rebuild_after_restore<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, true, false>();
            let (x, y, z) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
            let (fx, fy, fz) = (eg.add(th.f, &[x]), eg.add(th.f, &[y]), eg.add(th.f, &[z]));
            let token = eg.mark(ShrinkPolicy::Never);
            eg.merge(x, y);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fy));
            eg.restore(token);
            assert_ne!(eg.find(fx), eg.find(fy));
            eg.merge(x, z);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fz));
            assert_ne!(eg.find(fx), eg.find(fy));
        }

        fn congruence_plain3<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (x, y, z, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
            let n1 = eg.add(th.h, &[x, y, z]);
            let n2 = eg.add(th.h, &[w, y, z]);
            eg.merge(x, w);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn commutative_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b, c, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
            let e1 = eg.add(th.eq, &[a, b]);
            let e2 = eg.add(th.eq, &[w, c]);
            eg.merge(a, w);
            eg.merge(b, c);
            eg.rebuild();
            assert_eq!(eg.find(e1), eg.find(e2));
        }

        fn a_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
            let n1 = eg.add(th.sub, &[a, b]);
            let n2 = eg.add(th.sub, &[a, c]);
            eg.merge(b, c);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn ac_shrink_after_merge<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let a = eg.add(th.x, &[]);
            let b = eg.add(th.y, &[]);
            let n1 = eg.add(th.plus, &[a, a, b]);
            let n2 = eg.add(th.plus, &[a, a, a]);
            eg.merge(a, b);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn deep_cascade_4_levels<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
            let fa = eg.add(th.f, &[a]);
            let fb = eg.add(th.f, &[b]);
            let ffa = eg.add(th.f, &[fa]);
            let ffb = eg.add(th.f, &[fb]);
            let fffa = eg.add(th.f, &[ffa]);
            let fffb = eg.add(th.f, &[ffb]);
            let ffffa = eg.add(th.f, &[fffa]);
            let ffffb = eg.add(th.f, &[fffb]);
            eg.merge(a, b);
            eg.rebuild();
            assert_eq!(eg.find(ffffa), eg.find(ffffb));
        }

        fn multiple_merges_before_rebuild<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b, c, d) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
            let fa = eg.add(th.f, &[a]);
            let fb = eg.add(th.f, &[b]);
            let fc = eg.add(th.f, &[c]);
            let fd = eg.add(th.f, &[d]);
            eg.merge(a, b);
            eg.merge(c, d);
            eg.rebuild();
            assert_eq!(eg.find(fa), eg.find(fb));
            assert_eq!(eg.find(fc), eg.find(fd));
            assert_ne!(eg.find(fa), eg.find(fc));
        }

        fn explain_proof<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, true>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let z = eg.add(th.z, &[]);
            eg.merge_justified(x, y, Justification::Axiom { axiom_id: crate::id::AxiomId::new(1) });
            eg.merge_justified(y, z, Justification::Axiom { axiom_id: crate::id::AxiomId::new(2) });
            let mut buf = ProofBuf::new();
            eg.explain(x, z, &mut buf);
            assert!(buf.steps.len() >= 2);
        }

        fn explain_deep_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, true>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let fx = eg.add(th.f, &[x]);
            let fy = eg.add(th.f, &[y]);
            eg.merge_justified(x, y, Justification::Axiom { axiom_id: crate::id::AxiomId::new(10) });
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fy));
            let mut buf = ProofBuf::new();
            assert!(eg.explain_deep(fx, fy, &mut buf));
            assert!(buf.steps.iter().any(|(_, _, j)| matches!(j, Justification::Congruence { .. })));
            assert!(buf.steps.iter().any(|(_, _, j)| *j == Justification::Axiom { axiom_id: crate::id::AxiomId::new(10) }));
        }

        fn plain_n_congruence<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (x, y, z, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
            let n1 = eg.add(th.f4, &[x, y, z, w]);
            let n2 = eg.add(th.f4, &[x, y, z, x]);
            eg.merge(w, x);
            eg.rebuild();
            assert_eq!(eg.find(n1), eg.find(n2));
        }

        fn a_not_commutative<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
            let ab = eg.add(th.sub, &[a, b]);
            let ba = eg.add(th.sub, &[b, a]);
            assert_ne!(eg.find(ab), eg.find(ba));
        }

        fn lit_node<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            use crate::literal::NiraLitVal;
            use num_bigint::BigInt;
            let v1 = eg.intern_lit(NiraLitVal::Int(BigInt::from(42)));
            let v2 = eg.intern_lit(NiraLitVal::Int(BigInt::from(42)));
            assert_eq!(v1, v2);
            let n1 = eg.add_lit(th.lit_op, v1);
            let n2 = eg.add_lit(th.lit_op, v1);
            assert_eq!(n1, n2);
            let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(99)));
            let n3 = eg.add_lit(th.lit_op, v3);
            assert_ne!(n1, n3);
        }

        fn is_empty_check<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, false, false>();
            // setup registers ops which add nodes, but is_empty checks node count
            let before = eg.len();
            let x = eg.add(th.x, &[]);
            assert_eq!(eg.len(), before + 1);
            let _ = x;
        }

        fn nested_mark_restore<Cfg>() {
            let (ref mut eg, th) = setup::<Cfg, true, false>();
            let x = eg.add(th.x, &[]);
            let y = eg.add(th.y, &[]);
            let z = eg.add(th.z, &[]);
            let fx = eg.add(th.f, &[x]);
            let fy = eg.add(th.f, &[y]);
            let fz = eg.add(th.f, &[z]);
            let t1 = eg.mark(ShrinkPolicy::Never);
            eg.merge(x, y);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fy));
            let t2 = eg.mark(ShrinkPolicy::Never);
            eg.merge(x, z);
            eg.rebuild();
            assert_eq!(eg.find(fx), eg.find(fz));
            eg.restore(t2);
            assert_eq!(eg.find(fx), eg.find(fy));
            assert_ne!(eg.find(fx), eg.find(fz));
            eg.restore(t1);
            assert_ne!(eg.find(fx), eg.find(fy));
            assert_ne!(eg.find(fx), eg.find(fz));
        }
    }
}