bitwright 0.32.11

Hash-consed fixed-width bit-vector expressions: exact evaluation, bit-level facts, and verified simplification.
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
//! Many questions at once (feature `prove`): simplifications, constants and validity proofs,
//! answered in the order asked, on as many threads as the caller gives, with the work that
//! questions share done once. See `docs/proposals/parallel-proofs.md`.
//!
//! A [`Session`] owns what outlives a call: its engines, its solver and a store of answers.
//! [`Session::run`] takes questions about expressions of one context ([`Ask`]) and returns a
//! [`Reply`] for each. A question is copied into a context of its own and decided there, so
//! what it costs and what it answers depend on the question and the session's [`Config`]
//! alone: not on the other questions, their order, the number of threads, what the store
//! already holds, or what was cancelled.
//!
//! With [`Split`], a question is cut where its noise cancels. Every node is evaluated at a
//! few assignments of the symbols; a node with one value at all of them, over something that
//! varies, is a *hub*, and is asked on its own: "is this the constant it looks like?". Hubs
//! proved are replaced by their constants, in the hubs above them first and in the question
//! last. Sampling only chooses where to cut: a constant is substituted when the engine folded
//! the hub to it or the search proved the equality, never because the samples agreed. A hub
//! is one task however many questions contain it, and its answer is kept in the store.
//!
//! A question asked [under assumptions](Ask::under) is sampled where they hold. Where no
//! point satisfies them (a symbol held below a bound, say) an assignment that does is
//! searched for, and the question's value read there; the search only chooses where to
//! look, as the samples do. A node with one value wherever the assumptions hold, which
//! moves where they do not, is a hub of those assumptions ([`Split::assumed`]): it is asked
//! under them, and replaced only in questions and hubs asked under the same.
//!
//! ```
//! use bitwright::batch::{Answer, Ask, Config, Session};
//! use bitwright::{BitVec, Context, ParseOptions, Width};
//!
//! let mut cx = Context::new();
//! let o = ParseOptions::width(Width::W64);
//! // An address with a block of noise that cancels, and an identity.
//! let address = cx.parse("0x1000 + ((x ^ y) + 2 * (x & y) - x - y) * z", &o)?;
//! let identity = cx.parse("(x | y) + (x & y) == x + y", &o)?;
//! let session = Session::new(Config::default().with_threads(2));
//! let replies = session.run(&mut cx, &[Ask::constant(address), Ask::valid(identity)])?;
//! assert_eq!(replies[0].answer, Answer::Constant(BitVec::from_u64(Width::W64, 0x1000).unwrap()));
//! assert_eq!(replies[1].answer, Answer::Proved);
//! // Asked again, both are answered from the store, at the cost they had.
//! let again = session.run(&mut cx, &[Ask::valid(identity)])?;
//! assert_eq!(again[0].cost, replies[1].cost);
//! # Ok::<(), bitwright::Error>(())
//! ```

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};

use crate::engine::{Allowance, Budget, Clock, Deadline, End, Exhausted, Run};
use crate::error::Error;
use crate::expr::{Context, ContextConfig, Expr, OpCode};
use crate::facts::{Assumptions, Facts};
use crate::hash::IdMap;
use crate::prove::{self, Env, Limits, Model, Outcome, Question, Simplifiers, Unknown};
use crate::{BinOp, BitVec, CmpOp, SymbolKey, UnOp, Width};

/// Where questions are cut ([`Config::split`]).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Split {
    /// Ask each hub (a node with one value at every sample, over something that varies) as a
    /// question of its own, and replace those proved constant.
    pub hubs: bool,
    /// When a hub is not proved as written, ask the hubs below it and then the hub with
    /// those proved replaced, and so on down. Without it only the topmost hubs of a
    /// question are asked, each as written.
    pub nested: bool,
    /// Regroup a chain of `+` or of `^` by the symbols its terms read, where that brings
    /// terms together whose sum is constant at the samples: the group is then a hub.
    pub terms: bool,
    /// How many times a proof that stops at its limits (a question's, or a hub's) is split
    /// in two on a condition it tests: the one most of its selects test or, without
    /// selects, the smallest comparison of a claim built with `&`, `|`, `^` and `~`. Each
    /// half is a question of its own, asked under the condition (or its negation) as one
    /// more assumption, with the condition written as its value: what is constant in that
    /// case is found and proved as under any assumption. 2 (the default) means up to four
    /// cases; 0: never.
    pub cases: u8,
    /// Ask the lowest hubs first, and each hub above with those proved below it written as
    /// constants: every block of noise is then proved once, however many hubs and
    /// questions lie above it, and a hub above is small when it is asked. The hubs are then
    /// the nodes where a value that varies meets one that cancels it, not the topmost
    /// constant ones. Without it (the default) a hub is asked as written first, which is
    /// one proof where the engine folds it whole, and shares nothing below.
    pub bottom_up: bool,
    /// Ask a question whole first, and cut it only when that does not decide it (a
    /// simplification is its own answer, so an [`Ask::simplify`] is then never cut). A
    /// question the engine settles by itself costs what it costs today, and its hubs are
    /// neither asked nor stored: right for questions that share little, or that the
    /// engine folds whole. [`Split::eager`] asks the hubs first. On by default.
    pub whole_first: bool,
    /// Under a question's assumptions, also ask the nodes that have one value wherever the
    /// assumptions hold though they vary elsewhere, each under those assumptions, and
    /// replace those proved in the questions asked under the same assumptions: a
    /// comparison the assumptions decide, hidden in arithmetic, is then a small proof of
    /// its own and not part of every question above it. On by default.
    pub assumed: bool,
    /// Assignments of the symbols every node is evaluated at to find hubs (at least 2; the
    /// first two are all zeros and all ones).
    pub points: u32,
    /// A hub of fewer nodes than this (as a tree) is left to the question it is in.
    pub min_nodes: u32,
}

impl Default for Split {
    /// Proofs asked whole first; then hubs, nested, with terms regrouped and two levels of
    /// case split, from 64 points.
    fn default() -> Self {
        Split {
            hubs: true,
            nested: true,
            terms: true,
            cases: 2,
            bottom_up: false,
            whole_first: true,
            assumed: true,
            points: 64,
            min_nodes: 4,
        }
    }
}

impl Split {
    /// The default, with every question's hubs asked before the question
    /// ([`whole_first`](Self::whole_first) off): for questions over shared structure that
    /// are not decided whole, where a hub proved once serves every question that contains
    /// it and no question pays for a first attempt that fails. Where the engine folds a
    /// question whole it costs more than asking whole: a hub the engine cannot fold on its
    /// own is asked, fails, and is asked again below.
    pub fn eager() -> Split {
        Split::default().with_whole_first(false)
    }

    /// For questions that share most of their structure (the words of one machine state,
    /// say): hubs first and from the bottom ([`eager`](Self::eager) with
    /// [`bottom_up`](Self::bottom_up)). A block of noise is proved once for every hub and
    /// question above it. On a deobfuscator's walk of 714 such questions, 97% of whose
    /// nodes an earlier question had, it took a third of the work of asking each hub as
    /// written.
    pub fn shared() -> Split {
        Split::eager().with_bottom_up(true)
    }

    /// No cut: every question is asked whole, as [`prove::valid_under`] or
    /// [`Engine::run`](crate::engine::Engine::run) would be in a context of its own.
    pub fn none() -> Split {
        Split {
            hubs: false,
            nested: false,
            terms: false,
            cases: 0,
            bottom_up: false,
            whole_first: false,
            assumed: false,
            points: 64,
            min_nodes: 4,
        }
    }
}

setters!(Split {
    with_hubs: hubs: bool,
    with_nested: nested: bool,
    with_terms: terms: bool,
    with_cases: cases: u8,
    with_bottom_up: bottom_up: bool,
    with_whole_first: whole_first: bool,
    with_assumed: assumed: bool,
    with_points: points: u32,
    with_min_nodes: min_nodes: u32,
});

/// A session's configuration, fixed when it is made: every answer and cost is a function of
/// the question and of this.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
    /// Threads a call may use, the calling thread among them (0: as many as the machine
    /// runs at once). The others live for the call only; a session keeps no pool. It
    /// changes how long a call takes and nothing else.
    pub threads: usize,
    /// How every task is decided: the search's limits, the simplifier's budget
    /// ([`prove::Config::simplify_budget`], also the budget of a [`Ask::simplify`]), and
    /// the rest. Certificates are not kept: a split question's proof is of its parts.
    ///
    /// The limits are each proof's, not the question's: a question cut in parts makes
    /// several proofs (its hubs', unless [`hub`](Self::hub) says otherwise, the search for
    /// an assignment its assumptions hold at, its own), each within
    /// [`max_conflicts`](prove::Config::max_conflicts) and
    /// [`max_propagations`](prove::Config::max_propagations), whichever is reached first,
    /// and each swept first within half of them again. An
    /// [`Unknown::Budget`] answer carries what the question's last
    /// proof did, sweep included; [`Reply::cost`] is the sum over all of them.
    pub prove: prove::Config,
    /// The MBA phase of the session's engines, when not the prover's own (the default with
    /// the opaque-constant sweep).
    #[cfg(feature = "mba")]
    pub mba: Option<crate::mba::MbaConfig>,
    /// How a hub is proved constant, when not as [`prove`](Self::prove) says: a hub is
    /// one of many, and a search that a question deserves is long for each of them.
    pub hub: Option<prove::Config>,
    /// Where questions are cut.
    pub split: Split,
    /// The most nodes the store's context may hold when a call begins; past it the store
    /// is emptied first (its context and every answer). It bounds memory between calls, and
    /// changes how long a call takes and nothing else.
    pub store_nodes: usize,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            threads: 0,
            prove: prove::Config::default(),
            #[cfg(feature = "mba")]
            mba: None,
            hub: None,
            split: Split::default(),
            store_nodes: 1 << 20,
        }
    }
}

setters!(Config {
    with_threads: threads: usize,
    with_prove: prove: prove::Config,
    with_hub: hub ? prove::Config,
    with_split: split: Split,
    with_store_nodes: store_nodes: usize,
});

#[cfg(feature = "mba")]
impl Config {
    /// Sets [`mba`](Self::mba).
    #[must_use]
    pub fn with_mba(mut self, mba: crate::mba::MbaConfig) -> Self {
        self.mba = Some(mba);
        self
    }
}

/// Stops the questions it was given to ([`Ask::cancellable`]) once [`cancel`](Self::cancel)
/// is called, from any thread. Clones are one flag.
#[derive(Clone, Debug, Default)]
pub struct Cancel(Arc<AtomicBool>);

impl Cancel {
    /// A flag not yet set.
    pub fn new() -> Cancel {
        Cancel::default()
    }

    /// Sets it: for good.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Release);
    }

    /// Whether it is set.
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }
}

#[derive(Copy, Clone, Debug)]
enum Kind {
    Simplify(Expr),
    Constant(Expr),
    Valid(Expr),
    Equal(Expr, Expr),
}

/// A question about expressions of the context given to [`Session::run`].
#[derive(Clone, Debug)]
pub struct Ask<'a> {
    kind: Kind,
    assumptions: Option<&'a Assumptions>,
    cancel: Option<Cancel>,
}

impl<'a> Ask<'a> {
    fn of(kind: Kind) -> Self {
        Ask {
            kind,
            assumptions: None,
            cancel: None,
        }
    }

    /// `e` simplified ([`Answer::Simplified`]).
    pub fn simplify(e: Expr) -> Self {
        Ask::of(Kind::Simplify(e))
    }

    /// Whether `e` has one value for every value of its symbols, and which
    /// ([`Answer::Constant`], [`Answer::Varies`]).
    pub fn constant(e: Expr) -> Self {
        Ask::of(Kind::Constant(e))
    }

    /// Whether the 1-bit `p` is true for every value of its symbols ([`Answer::Proved`],
    /// [`Answer::Refuted`]).
    pub fn valid(p: Expr) -> Self {
        Ask::of(Kind::Valid(p))
    }

    /// Whether `a` and `b`, of one width, are equal for every value of their symbols.
    pub fn equal(a: Expr, b: Expr) -> Self {
        Ask::of(Kind::Equal(a, b))
    }

    /// The question wherever these constraints hold, and not everywhere.
    #[must_use]
    pub fn under(mut self, assumptions: &'a Assumptions) -> Self {
        self.assumptions = Some(assumptions);
        self
    }

    /// Stopped by `cancel`. A task several questions share stops when all of them are
    /// cancelled.
    #[must_use]
    pub fn cancellable(mut self, cancel: &Cancel) -> Self {
        self.cancel = Some(cancel.clone());
        self
    }
}

/// What a question was answered.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Answer {
    /// Of [`Ask::simplify`]: an expression of the caller's context equal to the one asked
    /// about (wherever the assumptions hold), and how the engine ended.
    Simplified {
        /// The result.
        expr: Expr,
        /// Whether it is final.
        end: End,
    },
    /// Of [`Ask::constant`]: this value, at every value of the symbols (that the
    /// assumptions allow). Proved, not sampled.
    Constant(BitVec),
    /// Of [`Ask::constant`]: not a constant. At these two assignments, at which the
    /// assumptions hold, the expression has two values (checked by evaluation).
    Varies(Box<(Model, Model)>),
    /// Of [`Ask::valid`] and [`Ask::equal`]: it holds.
    Proved,
    /// Of [`Ask::valid`] and [`Ask::equal`]: it fails at these values of the symbols
    /// (checked by evaluation of the question as asked).
    Refuted(Model),
    /// Not decided: why.
    Unknown(Unknown),
    /// Stopped by its [`Cancel`] before it was decided.
    Cancelled,
}

/// The work a question took, in counts and never in time: the same for a question whenever
/// and however it is asked of a session with the same [`Config`]. With [`Split`] it is the
/// work of the question's own tasks and of every hub below it, each counted once.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cost {
    /// What the engine spent, in the units of its budget.
    pub simplify: Budget,
    /// The search's conflicts.
    pub conflicts: u64,
    /// The search's propagations.
    pub propagations: u64,
    /// The search's decisions.
    pub decisions: u64,
    /// AIG nodes of the circuits built.
    pub circuit_nodes: u64,
    /// Assignments the prover evaluated before searching.
    pub samples: u64,
    /// Tasks solved for it: engine runs and proofs.
    pub tasks: u64,
}

impl Default for Cost {
    /// No work.
    fn default() -> Self {
        Cost {
            simplify: Budget::ZERO,
            conflicts: 0,
            propagations: 0,
            decisions: 0,
            circuit_nodes: 0,
            samples: 0,
            tasks: 0,
        }
    }
}

impl Cost {
    fn add(&mut self, o: &Cost) {
        let (a, b) = (&mut self.simplify, &o.simplify);
        a.node_visits = a.node_visits.saturating_add(b.node_visits);
        a.candidates = a.candidates.saturating_add(b.candidates);
        a.match_steps = a.match_steps.saturating_add(b.match_steps);
        a.rewrites = a.rewrites.saturating_add(b.rewrites);
        a.new_nodes = a.new_nodes.saturating_add(b.new_nodes);
        a.fact_work = a.fact_work.saturating_add(b.fact_work);
        a.pass_work = a.pass_work.saturating_add(b.pass_work);
        a.mba_calls = a.mba_calls.saturating_add(b.mba_calls);
        a.mba_steps = a.mba_steps.saturating_add(b.mba_steps);
        a.eqsat_nodes = a.eqsat_nodes.saturating_add(b.eqsat_nodes);
        a.eqsat_work = a.eqsat_work.saturating_add(b.eqsat_work);
        self.conflicts = self.conflicts.saturating_add(o.conflicts);
        self.propagations = self.propagations.saturating_add(o.propagations);
        self.decisions = self.decisions.saturating_add(o.decisions);
        self.circuit_nodes = self.circuit_nodes.saturating_add(o.circuit_nodes);
        self.samples = self.samples.saturating_add(o.samples);
        self.tasks = self.tasks.saturating_add(o.tasks);
    }
}

/// Where a reply came from. It says how the time was spent, not what the answer is.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Source {
    /// Decided in this call.
    Solved,
    /// The store had the question's answer.
    Stored,
}

/// The reply to an [`Ask`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reply {
    /// The answer.
    pub answer: Answer,
    /// What it took. Of an [`Answer::Cancelled`]: what was spent until it stopped, which
    /// depends on when that was.
    pub cost: Cost,
    /// Where it came from.
    pub source: Source,
}

/// What a session has done, for its caller's accounting (hit rates, memory). Counts of
/// events, which depend on the order of calls: no answer does.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stats {
    /// Questions asked.
    pub asks: u64,
    /// ...answered whole from the store...
    pub asks_stored: u64,
    /// ...or the same as an earlier question of their call.
    pub asks_repeated: u64,
    /// Nodes of the questions asked, each question's counted alone...
    pub nodes_asked: u64,
    /// ...and those the store's context did not hold yet.
    pub nodes_new: u64,
    /// Engine runs and proofs done.
    pub tasks_solved: u64,
    /// Tasks (hubs, remainders, cases) found in the store while a question was planned.
    pub tasks_stored: u64,
    /// Hubs asked...
    pub hubs: u64,
    /// ...and proved constant.
    pub hubs_proved: u64,
    /// Chains of `+` or `^` regrouped.
    pub regrouped: u64,
    /// Questions split in two on a condition.
    pub case_splits: u64,
    /// Tasks stopped by a [`Cancel`].
    pub cancelled: u64,
    /// Of `hubs`, those that are one only under their question's assumptions
    /// ([`Split::assumed`]).
    pub hubs_assumed: u64,
    /// Nodes of the store's context now.
    pub store_nodes: u64,
    /// Answers the store holds now.
    pub store_answers: u64,
    /// Times the store was emptied.
    pub flushes: u64,
}

/// What a task is, with its root and assumptions: its identity in the store.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum What {
    /// The engine on the root.
    LeafSimplify,
    /// A proof of the root.
    LeafValid,
    /// A proof of the root, `x == k`, by the engine on `x` first: within a hub's limits
    /// ([`Config::hub`])...
    LeafHub,
    /// ...or a question's.
    LeafConstant,
    /// The root is a hub: is it its constant? With the case splits already made above it.
    Hub(u8),
    /// The questions as asked: planned, split.
    AskSimplify,
    AskConstant,
    /// With the case splits already made above it.
    AskValid(u8),
}

/// A question's constraints, in the order given: their expressions in the store's context.
type Assumed = Arc<[(u32, Facts)]>;

impl What {
    /// The case splits made above the task.
    fn depth(self) -> u8 {
        match self {
            What::Hub(d) | What::AskValid(d) => d,
            _ => 0,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Key {
    what: What,
    /// A node of the store's context.
    root: u32,
    /// The constraints, in the order given: their expressions in the store's context.
    assume: Assumed,
    /// Of a proof that the root is a constant: which.
    k: Option<BitVec>,
}

/// A task's answer, as the store keeps it (expressions are nodes of its context).
#[derive(Clone, Debug)]
enum Res {
    Simplified { expr: u32, end: End },
    Constant(BitVec),
    Varies(Box<(Model, Model)>),
    Proved,
    Refuted(Model),
    Unknown(Unknown),
}

#[derive(Debug)]
struct Entry {
    /// Unique in its session: what a cost is counted once by.
    id: u64,
    res: Res,
    /// The task's own work.
    own: Cost,
    /// Of a question: its own work and that of everything below it, each once.
    total: Cost,
    /// The tasks it was made of.
    parts: Vec<Arc<Entry>>,
    /// Of a hub: the proved constants to write for it. Itself, when proved; otherwise
    /// those of the hubs below it.
    subst: Arc<[(u32, BitVec)]>,
}

/// The asks a task works for.
#[derive(Clone, Debug, Default)]
struct Wanted {
    /// By an ask that cannot be cancelled.
    always: bool,
    flags: Vec<Cancel>,
}

impl Wanted {
    fn stopped(&self) -> bool {
        !self.always && self.flags.iter().all(Cancel::is_cancelled)
    }

    /// Whether `o` added something.
    fn join(&mut self, o: &Wanted) -> bool {
        if self.always {
            return false;
        }
        if o.always {
            self.always = true;
            self.flags.clear();
            return true;
        }
        let mut grew = false;
        for f in &o.flags {
            if !self.flags.iter().any(|g| Arc::ptr_eq(&g.0, &f.0)) {
                self.flags.push(f.clone());
                grew = true;
            }
        }
        grew
    }
}

impl Clock for Wanted {
    fn now_ticks(&self) -> u64 {
        u64::from(self.stopped())
    }
}

#[derive(Debug)]
enum State {
    /// Waiting for `waiting` tasks.
    Pending,
    /// In the queue.
    Ready,
    Running,
    Done(Arc<Entry>),
    Cancelled,
}

#[derive(Debug)]
enum Plan {
    Leaf,
    Hub {
        /// Its value at the samples.
        k: BitVec,
        /// The hubs nearest below it, once it was not proved as written.
        below: Vec<usize>,
        /// Its proofs: as written, and with the hubs below it replaced.
        proofs: [Option<usize>; 2],
        /// The hubs below it that were not proved were asked again under its assumptions.
        again: bool,
        /// What its last proof was of: itself, with the hubs below it replaced.
        asked: u32,
        /// The two cases it was split in, when that proof stopped at its limits.
        cases: Option<(usize, usize)>,
    },
    Ask {
        /// Of a constant question: the value at the samples and the point it was read at.
        /// `None` with `fallback`: no sample satisfied the assumptions.
        candidate: Option<(BitVec, u32)>,
        fallback: bool,
        /// No sample satisfied the assumptions: an assignment that does is searched for
        /// first (`found`, the task that does), and the candidate read there.
        search: bool,
        found: Option<usize>,
        read: bool,
        /// Its hubs that were not proved were asked again under its assumptions.
        again: bool,
        /// The root with its chains regrouped.
        root: u32,
        /// The topmost hubs below it.
        hubs: Vec<usize>,
        /// The question asked whole ([`Split::whole_first`]).
        first: Option<usize>,
        /// What the remainder asked ([`advance`](Session::advance) fills them in).
        pred: u32,
        rest: Option<usize>,
        cases: Option<(usize, usize)>,
    },
}

#[derive(Debug)]
struct Job {
    key: Key,
    plan: Plan,
    /// The tasks it needs; the first `base` are those it was planned with.
    deps: Vec<usize>,
    base: usize,
    waiting: usize,
    dependents: Vec<usize>,
    state: State,
    stage: u8,
    wanted: Wanted,
    /// What it had spent when it was cancelled.
    partial: Cost,
}

/// The tasks of one call.
#[derive(Debug, Default)]
struct Graph {
    jobs: Vec<Job>,
    by_key: HashMap<Key, usize>,
    ready: VecDeque<usize>,
    running: usize,
    /// Asks not answered yet (distinct tasks).
    open: usize,
    tops: HashSet<usize>,
    error: Option<Error>,
}

struct Store {
    cx: Context,
    done: HashMap<Key, Arc<Entry>>,
    config: Option<ContextConfig>,
    registry: Option<Arc<crate::ext::Registry>>,
    /// What the samples say of the context's nodes.
    sampled: Sampled,
    /// Per set of assumptions that does not hold at every point: where it holds.
    views: HashMap<Assumed, View>,
    next_id: u64,
    stats: Stats,
    graph: Graph,
}

impl Store {
    fn empty(&mut self, src: &Context) {
        let mut cx = Context::with_config(src.config().clone());
        cx.registry = src.registry.clone();
        self.cx = cx;
        self.sampled = Sampled::default();
        self.views.clear();
        self.done.clear();
        self.config = Some(src.config().clone());
        self.registry = src.registry.clone();
    }

    fn entry(&mut self, res: Res, own: Cost, parts: Vec<Arc<Entry>>) -> Entry {
        self.next_id += 1;
        Entry {
            id: self.next_id,
            res,
            own,
            total: own,
            parts,
            subst: Arc::from([]),
        }
    }
}

/// What the samples say of a node: whether it had one value at every point, its value at
/// the first, and whether something below it (or itself) varies. A function of the node.
type Sampled = IdMap<u32, (bool, BitVec, bool)>;

/// The sample points at which a set of assumptions holds, and what they say of the nodes
/// there. A function of the assumptions.
#[derive(Debug, Default)]
struct View {
    /// Symbols held at one value at every point: an assignment found by search, when the
    /// assumptions hold at no point otherwise.
    fixed: Model,
    /// Per point, whether the assumptions hold there.
    holds: Vec<bool>,
    /// They hold at every point, with nothing fixed: the samples are the store's own.
    all: bool,
    /// `fixed` came from a search.
    searched: bool,
    /// Assignments at which the assumptions may turn ([`probes`]).
    probes: Vec<Model>,
    /// The nodes that move at a point where the assumptions do not hold, or at a probe.
    moves: HashSet<u32>,
    sampled: Sampled,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Looked {
    /// At some point, as the view says.
    Holds,
    /// At no point: an assignment is to be searched for.
    Search,
    /// At no point, with the assignment a search found.
    Nowhere,
}

/// The nodes whose value at every point was asked for.
type Watched = IdMap<u32, Vec<BitVec>>;

/// The value of a symbol at sample point `p`: zeros, ones, then seeded by the key, always
/// with the bits its declaration fixes.
fn point_value(key: &SymbolKey, w: Width, known: Option<crate::KnownBits>, p: u32) -> BitVec {
    let v = match p {
        0 => BitVec::zero(w),
        1 => BitVec::ones(w),
        _ => {
            let h = crate::hash::mix64(
                key.structural_hash() ^ u64::from(p).wrapping_mul(0x9e37_79b9_7f4a_7c15),
            );
            let limbs = [
                h,
                h.rotate_left(17) ^ 0x5851_f42d_4c95_7f2d,
                !h.rotate_left(29),
                h.rotate_left(41) ^ 0x1405_7b7e_f767_814f,
                crate::hash::mix64(h),
                crate::hash::mix64(!h),
                crate::hash::mix64(h ^ 0xa5a5),
                crate::hash::mix64(h.rotate_left(7)),
            ];
            BitVec::wrapping_from_limbs(w, &limbs)
        }
    };
    declared(v, known)
}

/// `v` with the bits a declaration fixes.
fn declared(v: BitVec, known: Option<crate::KnownBits>) -> BitVec {
    match known {
        Some(k) => {
            let v = BitVec::bin_unchecked(BinOp::Or, &v, &k.known_one());
            let keep = BitVec::un_unchecked(UnOp::Not, &k.known_zero());
            BitVec::bin_unchecked(BinOp::And, &v, &keep)
        }
        None => v,
    }
}

/// The symbols below `roots`: key, width and what is declared of each.
fn symbols_below(
    cx: &mut Context,
    roots: &[u32],
) -> Result<Vec<(SymbolKey, Width, Option<crate::KnownBits>)>, Error> {
    let roots: Vec<Expr> = roots.iter().map(|&i| cx.handle(i)).collect();
    let mut symbols = Vec::new();
    for id in cx.symbols_in(&roots)? {
        if let (Some(key), Some(w)) = (cx.symbol_key(id).cloned(), cx.symbol_width(id)) {
            let known = cx.find_symbol(&key).and_then(|s| cx.declared_at(s.index()));
            symbols.push((key, w, known));
        }
    }
    Ok(symbols)
}

/// The symbols below `roots`, each with its value at point `p`.
fn point_model(cx: &mut Context, roots: &[u32], p: u32) -> Result<Model, Error> {
    Ok(symbols_below(cx, roots)?
        .into_iter()
        .map(|(key, w, known)| {
            let v = point_value(&key, w, known, p);
            (key, v)
        })
        .collect())
}

/// Samples the nodes below `roots` into `known`, where they are not there yet, and returns
/// the values of the nodes `watch` at every point.
fn sample(
    cx: &mut Context,
    known: &mut Sampled,
    roots: &[u32],
    watch: &[u32],
    points: u32,
) -> Result<Watched, Error> {
    sample_where(cx, known, roots, watch, points, None)
}

impl View {
    /// Whether the view can tell what is constant because of the assumptions from what
    /// varies: not when it is the store's own, when a search fixed the assumptions'
    /// symbols (nothing over them varies then), or when they hold at a few points only.
    fn tells(&self) -> bool {
        let held = self.holds.iter().filter(|&&h| h).count();
        !self.all && !self.searched && held * 8 >= self.holds.len()
    }
}

/// Where [`sample_where`] counts: the points at which a set of assumptions holds.
struct Where<'a> {
    fixed: &'a [(SymbolKey, BitVec)],
    /// Per point; every point when `None`.
    holds: Option<&'a [bool]>,
    probes: &'a [Model],
    /// The nodes with another value at a point that is not counted, or at a probe.
    moves: &'a mut HashSet<u32>,
}

/// [`sample`] where a set of assumptions holds: with the symbols `fixed` held at their
/// values and only the points `holds` counted (a node's first value is at the first of
/// them). The values of `watch` are at every point, then at every probe.
fn sample_where(
    cx: &mut Context,
    known: &mut Sampled,
    roots: &[u32],
    watch: &[u32],
    points: u32,
    at_view: Option<Where<'_>>,
) -> Result<Watched, Error> {
    let n = points.max(2) as usize;
    let (fixed, holds, probes, mut moves) = match at_view {
        Some(w) => (w.fixed, w.holds, w.probes, Some(w.moves)),
        None => (&[][..], None, &[][..], None),
    };
    let total = n + probes.len();
    let blank = BitVec::zero(Width::W1);
    let mut watched: Watched = watch.iter().map(|&i| (i, vec![blank; total])).collect();
    // A node is sampled with everything below it.
    let missing: Vec<u32> = (roots.iter().copied())
        .filter(|i| !known.contains_key(i))
        .chain(watch.iter().copied())
        .collect();
    if missing.is_empty() {
        return Ok(watched);
    }
    let order = cx.post_order_ids(&missing);
    let handles: Vec<Expr> = order.iter().map(|&i| cx.handle(i)).collect();
    let symbols = symbols_below(cx, &missing)?;
    let mut first: Vec<BitVec> = Vec::new();
    let mut konst = vec![true; order.len()];
    let mut moved = vec![false; order.len()];
    let at: IdMap<u32, usize> = order.iter().enumerate().map(|(k, &i)| (i, k)).collect();
    // The points that count first: the others are compared with them.
    let counts = |p: usize| p < n && holds.is_none_or(|h| h.get(p).copied().unwrap_or(false));
    let turn = (0..total)
        .filter(|&p| counts(p))
        .chain((0..total).filter(|&p| !counts(p)));
    for p in turn {
        let mut env: HashMap<SymbolKey, BitVec> = symbols
            .iter()
            .map(|(key, w, known)| (key.clone(), point_value(key, *w, *known, p as u32)))
            .collect();
        let probe = probes.get(p.wrapping_sub(n)).map_or(&[][..], |m| &m[..]);
        for (key, v) in fixed.iter().chain(probe) {
            if let Some(slot) = env.get_mut(key) {
                *slot = *v;
            }
        }
        let vals = cx.eval(&handles, &env)?;
        for (&w, kept) in &mut watched {
            if let Some(&k) = at.get(&w) {
                kept[p] = vals[k];
            }
        }
        if !counts(p) {
            for (k, v) in vals.iter().enumerate() {
                moved[k] |= first.get(k).is_some_and(|f| f != v);
            }
        } else if first.is_empty() {
            first = vals;
        } else {
            for (k, v) in vals.iter().enumerate() {
                konst[k] &= *v == first[k];
            }
        }
    }
    if first.is_empty() {
        return Ok(watched);
    }
    for (k, &i) in order.iter().enumerate() {
        // (Operands come first in the order.)
        let varies = !konst[k]
            || cx
                .node(i)
                .children()
                .any(|c| known.get(&c).is_some_and(|x| x.2));
        known.insert(i, (konst[k], first[k], varies));
        if let Some(m) = moves.as_deref_mut()
            && moved[k]
        {
            m.insert(i);
        }
    }
    Ok(watched)
}

/// Assignments at which a comparison of the assumptions `es` may turn: one of their
/// symbols (the first eight by key) at 0, 1, all ones, or next to a constant they mention,
/// the others as at a point of their own. A node that is constant wherever the assumptions
/// hold and moves at one of these is constant because of them.
fn probes(cx: &mut Context, es: &[u32]) -> Result<Vec<Model>, Error> {
    let mut consts: Vec<BitVec> = (cx.post_order_ids(es).into_iter())
        .filter_map(|i| cx.const_val(i))
        .collect();
    consts.sort_by(|a, b| (a.width(), a.limbs()).cmp(&(b.width(), b.limbs())));
    consts.dedup();
    let mut out = Vec::new();
    for (key, w, known) in symbols_below(cx, es)?.into_iter().take(8) {
        let one = BitVec::wrapping_from_limbs(w, &[1]);
        let mut values = vec![BitVec::zero(w), one, BitVec::ones(w)];
        for c in consts.iter().filter(|c| c.width() == w).take(6) {
            values.push(BitVec::bin_unchecked(BinOp::Sub, c, &one));
            values.push(*c);
            values.push(BitVec::bin_unchecked(BinOp::Add, c, &one));
        }
        for v in values {
            out.push(vec![(key.clone(), declared(v, known))]);
        }
    }
    Ok(out)
}

/// The hubs nearest below the nodes `from` (those themselves, when they are hubs). A hub
/// is a node with one value at the samples though something below it varies: where noise
/// cancels. Of a chain of such nodes that only add a literal constant to the one below
/// (or negate it, or mask it), the lowest is the hub: what many questions share is the
/// noise, and each has its own constant on top.
fn hubs_below(cx: &Context, s: &Sampled, from: &[u32], split: &Split) -> Vec<u32> {
    let cancels = |i: u32| s.get(&i).is_some_and(|x| x.0 && x.2);
    let mut seen: HashSet<u32> = HashSet::new();
    let mut stack: Vec<u32> = from.to_vec();
    let mut hubs = Vec::new();
    while let Some(i) = stack.pop() {
        if !seen.insert(i) || !s.get(&i).is_some_and(|x| x.2) {
            continue;
        }
        let n = cx.node(i);
        if !cancels(i) {
            stack.extend(n.children());
            continue;
        }
        if split.bottom_up {
            // Where something that varies is cancelled; above that, constants meet.
            let meets = n.children().any(|c| s.get(&c).is_some_and(|x| !x.0));
            if !meets {
                stack.extend(n.children());
            } else if cx
                .tree_size(cx.handle(i))
                .is_ok_and(|t| t >= split.min_nodes)
            {
                hubs.push(i);
            }
            continue;
        }
        let mut inner = n.children().filter(|&c| cx.node(c).op != OpCode::Const);
        match (inner.next(), inner.next()) {
            (Some(only), None) if cancels(only) => stack.push(only),
            _ if cx
                .tree_size(cx.handle(i))
                .is_ok_and(|t| t >= split.min_nodes) =>
            {
                hubs.push(i)
            }
            _ => {}
        }
    }
    hubs
}

/// The terms of the chain of `op` at `i`: its operands, and theirs while they are `op` too.
fn chain(cx: &Context, i: u32, op: OpCode, terms: &mut Vec<u32>) {
    let mut stack = vec![i];
    while let Some(j) = stack.pop() {
        let n = cx.node(j);
        if n.op == op && terms.len() + stack.len() < 4096 {
            stack.push(n.b);
            stack.push(n.a);
        } else {
            terms.push(j);
        }
    }
}

/// `roots` with their chains of `+` and of `^` regrouped: the terms that read a symbol in
/// common are summed together where that sum is constant at the samples (then a hub) and
/// the chain as written is not. Associativity and commutativity only, through the
/// constructors: each result equals its root at every value. Returns how many chains changed.
fn regroup(
    cx: &mut Context,
    known: &mut Sampled,
    roots: &mut [u32],
    points: u32,
    min_terms: usize,
) -> Result<u64, Error> {
    // The symbols each node reads, as a small set; a question over more symbols than fit
    // is left as it is.
    let order = cx.post_order_ids(roots);
    let mut slot: HashMap<u32, u32> = HashMap::new();
    let mut reads: IdMap<u32, u128> = IdMap::default();
    for &i in &order {
        let n = cx.node(i);
        let set = match n.op {
            OpCode::Sym => {
                let next = slot.len() as u32;
                let k = *slot.entry(i).or_insert(next);
                if k >= 128 {
                    return Ok(0);
                }
                1u128 << k
            }
            _ => n.children().fold(0, |acc, c| acc | reads[&c]),
        };
        reads.insert(i, set);
    }
    // The chains, from their tops: a node of the operator that no chain above it took.
    let mut inner: HashSet<u32> = HashSet::new();
    let mut candidates: Vec<(u32, OpCode, Vec<Vec<u32>>)> = Vec::new();
    for &i in order.iter().rev() {
        let n = cx.node(i);
        if !matches!(n.op, OpCode::Add | OpCode::Xor) || inner.contains(&i) {
            continue;
        }
        let mut terms = Vec::new();
        chain(cx, i, n.op, &mut terms);
        for &t in &[n.a, n.b] {
            let mut stack = vec![t];
            while let Some(j) = stack.pop() {
                let m = cx.node(j);
                if m.op == n.op && inner.insert(j) {
                    stack.push(m.a);
                    stack.push(m.b);
                }
            }
        }
        if terms.len() < min_terms {
            continue;
        }
        // Groups of terms joined by a symbol in common, in the order of their first term.
        let mut groups: Vec<(u128, Vec<u32>)> = Vec::new();
        for &t in &terms {
            let set = reads[&t];
            let mut joined: (u128, Vec<u32>) = (set, vec![t]);
            let mut k = 0;
            let mut place = None;
            while k < groups.len() {
                if set != 0 && groups[k].0 & joined.0 != 0 {
                    let g = groups.remove(k);
                    joined.0 |= g.0;
                    let mut all = g.1;
                    all.append(&mut joined.1);
                    joined.1 = all;
                    place.get_or_insert(k);
                    // A merged group may now touch earlier ones.
                    k = 0;
                    continue;
                }
                k += 1;
            }
            match place {
                Some(p) => groups.insert(p.min(groups.len()), joined),
                None => groups.push(joined),
            }
        }
        if groups.len() < 2 || groups.iter().all(|g| g.1.len() < 2) {
            continue;
        }
        candidates.push((i, n.op, groups.into_iter().map(|g| g.1).collect()));
    }
    if candidates.is_empty() {
        return Ok(0);
    }
    // Each group of several terms, summed; the samples say which are constant.
    let bin = |op: OpCode| {
        if op == OpCode::Add {
            BinOp::Add
        } else {
            BinOp::Xor
        }
    };
    let mut sums: Vec<Vec<Option<u32>>> = Vec::new();
    let mut probe: Vec<u32> = Vec::new();
    for (_, op, groups) in &candidates {
        let mut row = Vec::new();
        for g in groups {
            if g.len() < 2 {
                row.push(None);
                continue;
            }
            let mut acc = g[0];
            for &t in &g[1..] {
                acc = cx.c_bin(bin(*op), acc, t)?;
            }
            probe.push(acc);
            row.push(Some(acc));
        }
        sums.push(row);
    }
    let mut all: Vec<u32> = roots.to_vec();
    all.extend_from_slice(&probe);
    sample(cx, known, &all, &[], points)?;
    let konst = |i: u32| known.get(&i).is_some_and(|x| x.0);
    let mut map: Vec<(Expr, Expr)> = Vec::new();
    for ((i, op, groups), row) in candidates.iter().zip(&sums) {
        // Worth it when a group is constant though one of its terms is not, and the chain
        // is not constant as a whole (then it is a hub as written).
        let folds = |g: &Vec<u32>, sum: &Option<u32>| {
            sum.is_some_and(konst) && g.iter().any(|&t| !konst(t))
        };
        if konst(*i) || !groups.iter().zip(row).any(|(g, sum)| folds(g, sum)) {
            continue;
        }
        // The constant groups as their sums, the other terms as they were, in order.
        let mut acc: Option<u32> = None;
        for (g, sum) in groups.iter().zip(row) {
            let parts: Vec<u32> = match sum {
                Some(x) if folds(g, sum) => vec![*x],
                _ => g.clone(),
            };
            for t in parts {
                acc = Some(match acc {
                    None => t,
                    Some(a) => cx.c_bin(bin(*op), a, t)?,
                });
            }
        }
        if let Some(a) = acc
            && a != *i
        {
            map.push((cx.handle(*i), cx.handle(a)));
        }
    }
    if map.is_empty() {
        return Ok(0);
    }
    let handles: Vec<Expr> = roots.iter().map(|&i| cx.handle(i)).collect();
    let new = cx.substitute(&handles, &map)?;
    for (r, e) in roots.iter_mut().zip(new) {
        *r = cx.id(e)?;
    }
    Ok(map.len() as u64)
}

/// The condition to split the claim `root` on: the one the selects below it test most
/// or, when it has no select, the smallest comparison among the claims it is made of by
/// `&`, `|`, `^` and `~` (ties: by the nodes' own hashes, which no context changes).
fn condition(cx: &mut Context, root: u32) -> Option<u32> {
    let mut count: HashMap<u32, u32> = HashMap::new();
    for i in cx.post_order_ids(&[root]) {
        let n = cx.node(i);
        if n.op == OpCode::Select && cx.const_val(n.a).is_none() {
            *count.entry(n.a).or_default() += 1;
        }
    }
    let tested = count
        .into_iter()
        .max_by_key(|&(c, n)| {
            let h = cx.structural_hash(cx.handle(c)).unwrap_or(0);
            (n, h, cx.tree_size(cx.handle(c)).unwrap_or(0))
        })
        .map(|(c, _)| c);
    if tested.is_some() {
        return tested;
    }
    let mut atoms: Vec<u32> = Vec::new();
    let mut seen: HashSet<u32> = HashSet::new();
    let mut stack = vec![root];
    while let Some(i) = stack.pop() {
        if cx.wid(i) != 1 || !seen.insert(i) {
            continue;
        }
        let n = cx.node(i);
        match n.op {
            OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Not => stack.extend(n.children()),
            OpCode::Const | OpCode::Sym => {}
            _ if i != root => atoms.push(i),
            _ => {}
        }
    }
    atoms.into_iter().min_by_key(|&c| {
        let h = cx.structural_hash(cx.handle(c)).unwrap_or(0);
        (cx.tree_size(cx.handle(c)).unwrap_or(0), h)
    })
}

/// A task for a worker: a context of its own holding the root and the constraints.
struct Spec {
    job: usize,
    simplify: bool,
    hub: bool,
    /// Whether the root is this constant: the engine on the root first.
    constant: Option<BitVec>,
    cx: Context,
    root: Expr,
    assume: Vec<(Expr, Facts)>,
    wanted: Wanted,
}

/// What a worker made of a task.
struct Solved {
    job: usize,
    cx: Context,
    /// `None`: stopped by its cancel flags.
    res: Option<SolvedRes>,
    cost: Cost,
}

enum SolvedRes {
    Simplified(Expr, End),
    Outcome(Outcome),
}

enum Step {
    Solve(Box<Spec>),
    /// Waiting for tasks, finished, or cancelled.
    Settled,
}

/// The search between two readings of the cancel flags.
const SLICE: Limits = Limits {
    conflicts: 2_000,
    propagations: 2_000_000,
};

/// Questions answered in batches, on the caller's threads, with a store of what was proved.
/// See the [module](self).
pub struct Session {
    config: Config,
    simplifiers: Simplifiers,
    store: Mutex<Store>,
    wake: Condvar,
    /// One call at a time: the store's context is the calls' workspace.
    calls: Mutex<()>,
}

impl core::fmt::Debug for Session {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Session")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl Session {
    /// A session with an empty store and engines of its own.
    pub fn new(config: Config) -> Session {
        #[cfg(feature = "mba")]
        let simplifiers = match config.mba {
            Some(m) => Simplifiers::new().with_mba(m),
            None => Simplifiers::new(),
        };
        #[cfg(not(feature = "mba"))]
        let simplifiers = Simplifiers::new();
        Session::with_simplifiers(config, simplifiers)
    }

    /// A session that simplifies with these engines (a solver shared with other sessions,
    /// say: its memo answers as solving again would, so sharing it changes no answer).
    /// [`Config::mba`] is then theirs to have set.
    pub fn with_simplifiers(mut config: Config, simplifiers: Simplifiers) -> Session {
        config.prove.certificate = false;
        if let Some(h) = &mut config.hub {
            h.certificate = false;
        }
        Session {
            config,
            simplifiers,
            store: Mutex::new(Store {
                cx: Context::new(),
                done: HashMap::new(),
                config: None,
                registry: None,
                sampled: Sampled::default(),
                views: HashMap::new(),
                next_id: 0,
                stats: Stats::default(),
                graph: Graph::default(),
            }),
            wake: Condvar::new(),
            calls: Mutex::new(()),
        }
    }

    /// Its configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// What it has done so far.
    pub fn stats(&self) -> Stats {
        let st = self.lock();
        Stats {
            store_nodes: st.cx.len() as u64,
            store_answers: st.done.len() as u64,
            ..st.stats
        }
    }

    /// Empties the store. The next answers are the same, and take the time they first did.
    pub fn forget(&self) {
        let _call = self.calls.lock().unwrap_or_else(|e| e.into_inner());
        let mut st = self.lock();
        st.cx = Context::new();
        st.sampled = Sampled::default();
        st.views.clear();
        st.done.clear();
        st.config = None;
        st.stats.flushes += 1;
    }

    fn lock(&self) -> MutexGuard<'_, Store> {
        self.store.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Answers `asks`, questions about expressions of `cx`: `replies[i]` answers `asks[i]`.
    /// The calling thread and up to [`Config::threads`]` - 1` others, started here and gone
    /// when this returns, decide them; results that are expressions are built in `cx`.
    ///
    /// An error is of the questions as posed (an expression of another context, widths
    /// that do not fit) or a broken invariant; a question not decided is an
    /// [`Answer::Unknown`], not an error.
    pub fn run(&self, cx: &mut Context, asks: &[Ask<'_>]) -> Result<Vec<Reply>, Error> {
        let _call = self.calls.lock().unwrap_or_else(|e| e.into_inner());
        let (tops, stored) = {
            let mut st = self.lock();
            st.graph = Graph::default();
            let planned = self.plan(&mut st, cx, asks);
            if planned.is_err() {
                st.graph = Graph::default();
            }
            planned?
        };
        let threads = match self.config.threads {
            0 => std::thread::available_parallelism().map_or(1, |n| n.get()),
            n => n,
        };
        let pending = self.lock().graph.open;
        let threads = threads.clamp(1, pending.max(1));
        if pending > 0 {
            let work = || self.work();
            std::thread::scope(|s| {
                for _ in 1..threads {
                    if crate::threads::builder().spawn_scoped(s, work).is_err() {
                        break;
                    }
                }
                work();
            });
        }
        let mut st = self.lock();
        let graph = core::mem::take(&mut st.graph);
        if let Some(e) = graph.error {
            return Err(e);
        }
        let mut replies = Vec::with_capacity(asks.len());
        for (&j, &was_stored) in tops.iter().zip(&stored) {
            let job = &graph.jobs[j];
            replies.push(match &job.state {
                State::Done(entry) => {
                    let answer = match &entry.res {
                        Res::Simplified { expr, end } => {
                            let e = st.cx.handle(*expr);
                            Answer::Simplified {
                                expr: cx.import(&st.cx, &[e])?[0],
                                end: *end,
                            }
                        }
                        Res::Constant(v) => Answer::Constant(*v),
                        Res::Varies(m) => Answer::Varies(m.clone()),
                        Res::Proved => Answer::Proved,
                        Res::Refuted(m) => Answer::Refuted(m.clone()),
                        Res::Unknown(why) => Answer::Unknown(why.clone()),
                    };
                    Reply {
                        answer,
                        cost: entry.total,
                        source: match was_stored {
                            true => Source::Stored,
                            false => Source::Solved,
                        },
                    }
                }
                _ => Reply {
                    answer: Answer::Cancelled,
                    cost: spent_below(&graph, j),
                    source: Source::Solved,
                },
            });
        }
        Ok(replies)
    }

    /// Copies the questions into the store's context and plans those it has no answer to:
    /// each ask's task, and whether the store had its answer.
    fn plan(
        &self,
        st: &mut Store,
        src: &Context,
        asks: &[Ask<'_>],
    ) -> Result<(Vec<usize>, Vec<bool>), Error> {
        for a in asks {
            if let Some(a) = a.assumptions {
                a.check_context(src)?;
            }
        }
        // A store too large, or of contexts configured otherwise, starts again.
        let same = st.config.as_ref() == Some(src.config())
            && match (&st.registry, &src.registry) {
                (None, None) => true,
                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
                _ => false,
            };
        if !same || st.cx.len() > self.config.store_nodes {
            if st.config.is_some() {
                st.stats.flushes += 1;
            }
            st.empty(src);
        }
        if !self.declarations_agree(st, src, asks)? {
            // The store holds a symbol declared otherwise: its answers are of other
            // questions.
            st.stats.flushes += 1;
            st.empty(src);
        }
        let keys = self.import(st, src, asks)?;
        st.stats.asks += asks.len() as u64;
        let mut tops = Vec::with_capacity(asks.len());
        let mut stored = Vec::with_capacity(asks.len());
        let mut fresh: Vec<usize> = Vec::new();
        for (key, ask) in keys.into_iter().zip(asks) {
            let wanted = match &ask.cancel {
                Some(c) => Wanted {
                    always: false,
                    flags: vec![c.clone()],
                },
                None => Wanted {
                    always: true,
                    flags: Vec::new(),
                },
            };
            let had = st.done.contains_key(&key);
            stored.push(had);
            if had {
                st.stats.asks_stored += 1;
            } else if st.graph.by_key.contains_key(&key) {
                st.stats.asks_repeated += 1;
            }
            let known = st.graph.by_key.contains_key(&key);
            let j = self.job(st, key, &wanted);
            if !had && !known {
                fresh.push(j);
            }
            if st.graph.tops.insert(j) && !matches!(st.graph.jobs[j].state, State::Done(_)) {
                st.graph.open += 1;
            }
            tops.push(j);
        }
        self.plan_asks(st, &fresh)?;
        Ok((tops, stored))
    }

    /// The asks' keys: their expressions copied into the store's context.
    fn import(&self, st: &mut Store, src: &Context, asks: &[Ask<'_>]) -> Result<Vec<Key>, Error> {
        let mut keys = Vec::with_capacity(asks.len());
        for a in asks {
            let before = st.cx.len();
            let (what, root) = match a.kind {
                Kind::Simplify(e) => (What::AskSimplify, st.cx.import(src, &[e])?[0]),
                Kind::Constant(e) => (What::AskConstant, st.cx.import(src, &[e])?[0]),
                Kind::Valid(p) => {
                    let w = src.wid(src.id(p)?);
                    if w != 1 {
                        return Err(crate::WidthError::Mismatch { left: 1, right: w }.into());
                    }
                    (What::AskValid(0), st.cx.import(src, &[p])?[0])
                }
                Kind::Equal(x, y) => {
                    let both = st.cx.import(src, &[x, y])?;
                    (What::AskValid(0), st.cx.cmp(CmpOp::Eq, both[0], both[1])?)
                }
            };
            let mut assume = Vec::new();
            if let Some(asm) = a.assumptions {
                for (_, e, facts) in asm.constraints() {
                    let e = st.cx.import(src, &[e])?[0];
                    assume.push((st.cx.id(e)?, facts));
                }
            }
            let mut all = vec![root];
            all.extend(assume.iter().map(|x| st.cx.handle(x.0)));
            st.stats.nodes_asked += st.cx.post_order(&all)?.len() as u64;
            st.stats.nodes_new += (st.cx.len() - before) as u64;
            keys.push(Key {
                what,
                root: st.cx.id(root)?,
                assume: assume.into(),
                k: None,
            });
        }
        Ok(keys)
    }

    /// Whether every symbol of the asks that the store's context holds is declared there as
    /// in `src`.
    fn declarations_agree(
        &self,
        st: &mut Store,
        src: &Context,
        asks: &[Ask<'_>],
    ) -> Result<bool, Error> {
        let mut roots: Vec<Expr> = Vec::new();
        for a in asks {
            match a.kind {
                Kind::Simplify(e) | Kind::Constant(e) | Kind::Valid(e) => roots.push(e),
                Kind::Equal(x, y) => roots.extend([x, y]),
            }
            if let Some(asm) = a.assumptions {
                roots.extend(asm.constraints().map(|c| c.1));
            }
        }
        let ids = src.ids(&roots)?;
        let mut seen: HashSet<u32> = HashSet::new();
        let mut stack = ids;
        while let Some(i) = stack.pop() {
            if !seen.insert(i) {
                continue;
            }
            let n = src.node(i);
            if n.op == OpCode::Sym {
                let key = &src.symbols.entries[n.a as usize].key;
                // (A symbol the store has not met is declared as it arrives.)
                if let Some(theirs) = st.cx.find_symbol(key)
                    && st.cx.declared_at(theirs.index()) != src.declared_at(i)
                {
                    return Ok(false);
                }
            }
            stack.extend(n.children());
        }
        Ok(true)
    }

    /// The task of `key`, made if this call has none: done when the store has its answer.
    /// A new one that is not a leaf waits to be planned.
    fn job(&self, st: &mut Store, key: Key, wanted: &Wanted) -> usize {
        if let Some(&j) = st.graph.by_key.get(&key) {
            self.want(st, j, wanted);
            return j;
        }
        let state = match st.done.get(&key) {
            Some(e) => State::Done(e.clone()),
            None => State::Pending,
        };
        let plan = match key.what {
            What::LeafSimplify | What::LeafValid | What::LeafHub | What::LeafConstant => Plan::Leaf,
            What::Hub(_) => Plan::Hub {
                k: BitVec::zero(Width::W1),
                below: Vec::new(),
                proofs: [None, None],
                again: false,
                asked: key.root,
                cases: None,
            },
            _ => Plan::Ask {
                candidate: None,
                fallback: false,
                search: false,
                found: None,
                read: false,
                again: false,
                root: key.root,
                hubs: Vec::new(),
                first: None,
                pred: key.root,
                rest: None,
                cases: None,
            },
        };
        let j = st.graph.jobs.len();
        st.graph.by_key.insert(key.clone(), j);
        st.graph.jobs.push(Job {
            key,
            plan,
            deps: Vec::new(),
            base: 0,
            waiting: 0,
            dependents: Vec::new(),
            state,
            stage: 0,
            wanted: wanted.clone(),
            partial: Cost::default(),
        });
        j
    }

    /// `j` and the tasks it needs also work for `wanted`; one that was cancelled starts
    /// again.
    fn want(&self, st: &mut Store, j: usize, wanted: &Wanted) {
        let mut stack = vec![j];
        while let Some(j) = stack.pop() {
            let job = &mut st.graph.jobs[j];
            let grew = job.wanted.join(wanted);
            if matches!(job.state, State::Cancelled) && !job.wanted.stopped() {
                self.revive(st, j);
            } else if !grew {
                continue;
            }
            stack.extend(st.graph.jobs[j].deps.iter().copied());
        }
    }

    /// A cancelled task that is wanted again: from its beginning.
    fn revive(&self, st: &mut Store, j: usize) {
        let job = &mut st.graph.jobs[j];
        job.deps.truncate(job.base);
        job.stage = 0;
        job.partial = Cost::default();
        job.dependents.clear();
        job.waiting = 0;
        job.state = State::Pending;
        let base = job.base;
        if let Plan::Hub {
            below,
            proofs,
            again,
            cases,
            ..
        } = &mut job.plan
        {
            below.truncate(job.base);
            *proofs = [None, None];
            *again = false;
            *cases = None;
        }
        if let Plan::Ask {
            rest,
            cases,
            first,
            hubs,
            found,
            read,
            again,
            ..
        } = &mut job.plan
        {
            (*rest, *cases, *first) = (None, None, None);
            (*found, *read, *again) = (None, false, false);
            hubs.truncate(base);
        }
        if st.graph.tops.contains(&j) {
            st.graph.open += 1;
        }
        let wanted = job.wanted.clone();
        for d in st.graph.jobs[j].deps.clone() {
            st.graph.jobs[d].wanted.join(&wanted);
            if matches!(st.graph.jobs[d].state, State::Cancelled) {
                self.revive(st, d);
            }
            if !matches!(st.graph.jobs[d].state, State::Done(_)) {
                st.graph.jobs[d].dependents.push(j);
                st.graph.jobs[j].waiting += 1;
            }
        }
        self.ready_if(st, j);
    }

    fn ready_if(&self, st: &mut Store, j: usize) {
        let job = &mut st.graph.jobs[j];
        if job.waiting == 0 && matches!(job.state, State::Pending) {
            job.state = State::Ready;
            st.graph.ready.push_back(j);
        }
    }

    /// `j` needs `d`.
    fn depend(&self, st: &mut Store, j: usize, d: usize) {
        st.graph.jobs[j].deps.push(d);
        if !matches!(st.graph.jobs[d].state, State::Done(_)) {
            st.graph.jobs[d].dependents.push(j);
            st.graph.jobs[j].waiting += 1;
        }
    }

    /// Plans the new questions `asks` (tasks of this call): samples them together,
    /// regroups their chains, and makes the tasks of their hubs.
    fn plan_asks(&self, st: &mut Store, asks: &[usize]) -> Result<(), Error> {
        let split = self.config.split;
        let asks: Vec<usize> = asks
            .iter()
            .copied()
            .filter(|&j| matches!(st.graph.jobs[j].state, State::Pending))
            .collect();
        if asks.is_empty() {
            return Ok(());
        }
        let mut roots: Vec<u32> = asks.iter().map(|&j| st.graph.jobs[j].key.root).collect();
        let constants: Vec<usize> = (0..asks.len())
            .filter(|&k| st.graph.jobs[asks[k]].key.what == What::AskConstant)
            .collect();
        if !split.hubs && constants.is_empty() {
            for &j in &asks {
                st.graph.jobs[j].base = 0;
                self.ready_if(st, j);
            }
            return Ok(());
        }
        if split.hubs && split.terms {
            let store = &mut *st;
            let n = regroup(
                &mut store.cx,
                &mut store.sampled,
                &mut roots,
                split.points,
                3,
            )?;
            st.stats.regrouped += n;
        }
        for (k, &j) in asks.iter().enumerate() {
            if let Plan::Ask { root, .. } = &mut st.graph.jobs[j].plan {
                *root = roots[k];
            }
        }
        let store = &mut *st;
        sample(&mut store.cx, &mut store.sampled, &roots, &[], split.points)?;
        // Where each set of assumptions holds: a constant question's value is read there,
        // and a hub may be one there only.
        let mut groups: Vec<(Assumed, Vec<usize>)> = Vec::new();
        for (k, &j) in asks.iter().enumerate() {
            let key = &st.graph.jobs[j].key;
            let constant = key.what == What::AskConstant;
            if !constant && (key.assume.is_empty() || !split.hubs || !split.assumed) {
                continue;
            }
            match groups.iter_mut().find(|g| g.0 == key.assume) {
                Some(g) => g.1.push(k),
                None => groups.push((key.assume.clone(), vec![k])),
            }
        }
        for (assume, members) in groups {
            if self.look(st, &assume, None)? == Looked::Search {
                for &k in &members {
                    if let Plan::Ask { search, .. } = &mut st.graph.jobs[asks[k]].plan {
                        *search = true;
                    }
                }
                continue;
            }
            let constant: Vec<usize> = (members.iter().copied())
                .filter(|k| constants.contains(k))
                .collect();
            if constant.is_empty() {
                continue;
            }
            let watch: Vec<u32> = constant.iter().map(|&k| roots[k]).collect();
            let watched = self.sample_under(st, &assume, &watch, &watch)?;
            for &k in &constant {
                self.read(st, asks[k], &watched[&roots[k]])?;
            }
        }
        if split.hubs {
            // A proof asked whole first makes its hubs' tasks only if it must; one whose
            // assumptions are searched for, once that is done.
            for (&j, &root) in asks.iter().zip(&roots) {
                let searching = matches!(st.graph.jobs[j].plan, Plan::Ask { search: true, .. });
                if !searching && !self.whole_first(st, j) {
                    self.plan_hubs(st, j, &[root])?;
                    st.graph.jobs[j].base = st.graph.jobs[j].deps.len();
                }
            }
        }
        let n = st.graph.jobs.len();
        for j in 0..n {
            self.ready_if(st, j);
        }
        Ok(())
    }

    /// Where the assumptions `assume` hold among the sample points, kept as their view:
    /// with the symbols of `found` (an assignment a search returned) held at its values,
    /// when given.
    fn look(
        &self,
        st: &mut Store,
        assume: &Assumed,
        found: Option<&Model>,
    ) -> Result<Looked, Error> {
        if assume.is_empty() {
            return Ok(Looked::Holds);
        }
        if let Some(v) = st.views.get(assume) {
            // (A view that was searched for is reached through its search, whose cost is
            // then every such question's.)
            return Ok(match v.searched && found.is_none() {
                true => Looked::Search,
                false => Looked::Holds,
            });
        }
        let es: Vec<u32> = assume.iter().map(|x| x.0).collect();
        let points = self.config.split.points;
        let n = points.max(2) as usize;
        let store = &mut *st;
        let probes = probes(&mut store.cx, &es)?;
        let mut scratch = (Sampled::default(), HashSet::new());
        let at_view = Where {
            fixed: found.map_or(&[][..], |m| &m[..]),
            holds: None,
            probes: &probes,
            moves: &mut scratch.1,
        };
        let cx = &mut store.cx;
        let watched = sample_where(cx, &mut scratch.0, &es, &es, points, Some(at_view))?;
        let at = |p: usize| assume.iter().all(|(e, f)| f.contains(&watched[e][p]));
        let holds: Vec<bool> = (0..n).map(at).collect();
        if !holds.iter().any(|&h| h) {
            return Ok(match found {
                None => Looked::Search,
                Some(_) => Looked::Nowhere,
            });
        }
        let view = View {
            fixed: found.cloned().unwrap_or_default(),
            all: found.is_none() && (0..n + probes.len()).all(at),
            searched: found.is_some(),
            holds,
            probes,
            moves: HashSet::new(),
            sampled: Sampled::default(),
        };
        st.views.insert(assume.clone(), view);
        Ok(Looked::Holds)
    }

    /// Samples the nodes below `roots`, at every point and where `assume` holds: the
    /// values of `watch` at every point of the assumptions' view.
    fn sample_under(
        &self,
        st: &mut Store,
        assume: &Assumed,
        roots: &[u32],
        watch: &[u32],
    ) -> Result<Watched, Error> {
        let points = self.config.split.points;
        let store = &mut *st;
        let everywhere = sample(&mut store.cx, &mut store.sampled, roots, watch, points)?;
        match store.views.get_mut(assume) {
            Some(v) if !v.all => {
                let at_view = Where {
                    fixed: &v.fixed,
                    holds: Some(&v.holds),
                    probes: &v.probes,
                    moves: &mut v.moves,
                };
                sample_where(
                    &mut store.cx,
                    &mut v.sampled,
                    roots,
                    watch,
                    points,
                    Some(at_view),
                )
            }
            _ => Ok(everywhere),
        }
    }

    /// The assignment at point `p` for the question `key`: its symbols' values there, with
    /// what the view of its assumptions holds fixed.
    fn point(&self, st: &mut Store, key: &Key, p: u32) -> Result<Model, Error> {
        let mut near = vec![key.root];
        near.extend(key.assume.iter().map(|x| x.0));
        let mut model = point_model(&mut st.cx, &near, p)?;
        if let Some(v) = st.views.get(&key.assume) {
            for (k, value) in &v.fixed {
                if let Some(slot) = model.iter_mut().find(|x| x.0 == *k) {
                    slot.1 = *value;
                }
            }
        }
        Ok(model)
    }

    /// A constant question's candidate from the values of its root at every point of its
    /// assumptions' view: its value where they hold, or its answer when it has two there.
    fn read(&self, st: &mut Store, j: usize, values: &[BitVec]) -> Result<(), Error> {
        let key = st.graph.jobs[j].key.clone();
        let held: Vec<usize> = match st.views.get(&key.assume) {
            Some(v) => (0..v.holds.len()).filter(|&p| v.holds[p]).collect(),
            None => (0..values.len()).collect(),
        };
        let at = held.first().copied();
        let other = held
            .iter()
            .copied()
            .find(|&p| Some(values[p]) != at.map(|q| values[q]));
        if let (Some(p), Some(q)) = (at, other) {
            // Two values where the assumptions hold: evaluated, so decided.
            let a = self.point(st, &key, p as u32)?;
            let b = self.point(st, &key, q as u32)?;
            let parts = self.parts(st, j);
            let entry = st.entry(Res::Varies(Box::new((a, b))), Cost::default(), parts);
            self.finish(st, j, entry);
            return Ok(());
        }
        if let Plan::Ask {
            candidate,
            fallback,
            ..
        } = &mut st.graph.jobs[j].plan
        {
            match at {
                Some(p) => *candidate = Some((values[p], p as u32)),
                None => *fallback = true,
            }
        }
        Ok(())
    }

    /// Whether the question `j` is asked whole before it is cut.
    fn whole_first(&self, st: &Store, j: usize) -> bool {
        let job = &st.graph.jobs[j];
        let fallback = matches!(job.plan, Plan::Ask { fallback: true, .. });
        self.config.split.whole_first && !fallback
    }

    /// Makes the tasks of the hubs nearest below the nodes `from` and has `parent` (a
    /// question, or a hub that was not proved as written) wait for them, from the samples
    /// `s` of those nodes.
    fn plan_hubs(&self, st: &mut Store, parent: usize, from: &[u32]) -> Result<(), Error> {
        if matches!(st.graph.jobs[parent].state, State::Done(_)) {
            return Ok(());
        }
        let split = self.config.split;
        let wanted = st.graph.jobs[parent].wanted.clone();
        let mut made: Vec<usize> = Vec::new();
        let mut work: Vec<(usize, Vec<u32>)> = vec![(parent, from.to_vec())];
        while let Some((parent, from)) = work.pop() {
            // Under the parent's assumptions, where they do not hold everywhere: a hub
            // there is asked under them, unless it is one everywhere.
            let assume = st.graph.jobs[parent].key.assume.clone();
            let depth = st.graph.jobs[parent].key.what.depth();
            self.sample_under(st, &assume, &from, &[])?;
            let under = split.assumed && st.views.get(&assume).is_some_and(View::tells);
            let found = match under {
                true => hubs_below(&st.cx, &st.views[&assume].sampled, &from, &split),
                false => hubs_below(&st.cx, &st.sampled, &from, &split),
            };
            for h in found {
                let everywhere = !under
                    || (st.sampled.get(&h).is_some_and(|x| x.0)
                        && !st.views[&assume].moves.contains(&h));
                let (assumed, value) = match everywhere {
                    true => (Arc::from([]), st.sampled[&h].1),
                    false => (assume.clone(), st.views[&assume].sampled[&h].1),
                };
                let key = Key {
                    what: What::Hub(depth),
                    root: h,
                    assume: assumed,
                    k: None,
                };
                let new = !st.graph.by_key.contains_key(&key);
                let stored = st.done.contains_key(&key);
                let j = self.job(st, key, &wanted);
                if new && stored {
                    st.stats.tasks_stored += 1;
                } else if new {
                    st.stats.hubs += 1;
                    st.stats.hubs_assumed += u64::from(!everywhere);
                    if let Plan::Hub { k, .. } = &mut st.graph.jobs[j].plan {
                        *k = value;
                    }
                    made.push(j);
                    if split.bottom_up {
                        // The hubs below it are part of its plan.
                        work.push((j, st.cx.node(h).children().collect()));
                    }
                }
                self.depend(st, parent, j);
                match &mut st.graph.jobs[parent].plan {
                    Plan::Ask { hubs, .. } => hubs.push(j),
                    Plan::Hub { below, .. } => below.push(j),
                    Plan::Leaf => {}
                }
            }
        }
        // Ready once everything below each is attached.
        for j in made {
            if split.bottom_up {
                st.graph.jobs[j].base = st.graph.jobs[j].deps.len();
            }
            self.ready_if(st, j);
        }
        Ok(())
    }

    /// Two questions for the claim `pred` of the task `j`, which its proof left undecided:
    /// where a condition it tests holds, and where it does not. The condition is an
    /// assumption of each (so what is constant because of it is found and proved as under
    /// any other), and is written as its value in the claim. `None` when `pred` tests none.
    fn split_cases(
        &self,
        st: &mut Store,
        j: usize,
        pred: u32,
        depth: u8,
    ) -> Result<Option<(usize, usize)>, Error> {
        let Some(c) = condition(&mut st.cx, pred) else {
            return Ok(None);
        };
        let assume = st.graph.jobs[j].key.assume.clone();
        let mut halves = [0usize; 2];
        for (h, value) in halves.iter_mut().zip([true, false]) {
            let b = st.cx.bool(value)?;
            let fixed = st
                .cx
                .substitute(&[st.cx.handle(pred)], &[(st.cx.handle(c), b)])?[0];
            let bit = BitVec::wrapping_from_limbs(Width::W1, &[u64::from(value)]);
            let mut under = assume.to_vec();
            under.push((c, Facts::constant(&bit)));
            let key = Key {
                what: What::AskValid(depth + 1),
                root: st.cx.id(fixed)?,
                assume: under.into(),
                k: None,
            };
            let new = !st.graph.by_key.contains_key(&key);
            if new && st.done.contains_key(&key) {
                st.stats.tasks_stored += 1;
            }
            let wanted = st.graph.jobs[j].wanted.clone();
            let child = self.job(st, key, &wanted);
            if new {
                self.plan_asks(st, &[child])?;
            }
            self.depend(st, j, child);
            *h = child;
        }
        st.stats.case_splits += 1;
        Ok(Some((halves[0], halves[1])))
    }

    /// The hubs below `j` (a question or a hub, asked under assumptions) that were asked
    /// without assumptions and not proved, asked under `j`'s: a node that is constant
    /// because of the assumptions can look constant everywhere, when what moves it is a
    /// corner no sample or probe is in. Only those that read a symbol the assumptions read.
    fn ask_again(&self, st: &mut Store, j: usize) -> Result<(), Error> {
        let split = self.config.split;
        let assume = st.graph.jobs[j].key.assume.clone();
        let hubs = match &mut st.graph.jobs[j].plan {
            Plan::Hub { below, again, .. } => {
                *again = true;
                below.clone()
            }
            Plan::Ask { hubs, again, .. } => {
                *again = true;
                hubs.clone()
            }
            Plan::Leaf => Vec::new(),
        };
        if assume.is_empty() || !split.assumed || !st.views.contains_key(&assume) {
            return Ok(());
        }
        let es: Vec<u32> = assume.iter().map(|x| x.0).collect();
        let theirs: HashSet<SymbolKey> = (symbols_below(&mut st.cx, &es)?.into_iter())
            .map(|x| x.0)
            .collect();
        let wanted = st.graph.jobs[j].wanted.clone();
        for d in hubs {
            let hub = &st.graph.jobs[d];
            let open = match &hub.state {
                State::Done(e) => !matches!(e.res, Res::Constant(_)),
                _ => false,
            };
            let What::Hub(depth) = hub.key.what else {
                continue;
            };
            if !hub.key.assume.is_empty() || !open {
                continue;
            }
            let h = hub.key.root;
            if !(symbols_below(&mut st.cx, &[h])?.iter()).any(|x| theirs.contains(&x.0)) {
                continue;
            }
            // Its value where the assumptions hold.
            self.sample_under(st, &assume, &[h], &[])?;
            let seen = match st.views.get(&assume) {
                Some(v) if !v.all => v.sampled.get(&h),
                _ => st.sampled.get(&h),
            };
            let Some(&(true, value, _)) = seen else {
                continue;
            };
            let key = Key {
                what: What::Hub(depth),
                root: h,
                assume: assume.clone(),
                k: None,
            };
            let new = !st.graph.by_key.contains_key(&key);
            let stored = st.done.contains_key(&key);
            let again = self.job(st, key, &wanted);
            if new && stored {
                st.stats.tasks_stored += 1;
            } else if new {
                st.stats.hubs += 1;
                st.stats.hubs_assumed += 1;
                if let Plan::Hub { k, .. } = &mut st.graph.jobs[again].plan {
                    *k = value;
                }
                if split.bottom_up {
                    let kids: Vec<u32> = st.cx.node(h).children().collect();
                    self.plan_hubs(st, again, &kids)?;
                    st.graph.jobs[again].base = st.graph.jobs[again].deps.len();
                }
                self.ready_if(st, again);
            }
            self.depend(st, j, again);
            match &mut st.graph.jobs[j].plan {
                Plan::Ask { hubs, .. } => hubs.push(again),
                Plan::Hub { below, .. } => below.push(again),
                Plan::Leaf => {}
            }
        }
        Ok(())
    }

    /// The proved constants to write for the tasks `deps` of a hub or a question.
    fn substitution(&self, st: &Store, deps: &[usize]) -> Vec<(u32, BitVec)> {
        let mut seen: HashSet<u32> = HashSet::new();
        let mut pairs = Vec::new();
        for &d in deps {
            if let State::Done(e) = &st.graph.jobs[d].state {
                for (i, v) in e.subst.iter() {
                    if seen.insert(*i) {
                        pairs.push((*i, *v));
                    }
                }
            }
        }
        pairs
    }

    fn substituted(
        &self,
        st: &mut Store,
        root: u32,
        pairs: &[(u32, BitVec)],
    ) -> Result<u32, Error> {
        if pairs.is_empty() {
            return Ok(root);
        }
        let mut map = Vec::with_capacity(pairs.len());
        for (i, v) in pairs {
            let c = st.cx.mk_const(v)?;
            map.push((st.cx.handle(*i), st.cx.handle(c)));
        }
        let e = st.cx.substitute(&[st.cx.handle(root)], &map)?[0];
        st.cx.id(e)
    }

    fn parts(&self, st: &Store, j: usize) -> Vec<Arc<Entry>> {
        let mut parts = Vec::new();
        for &d in &st.graph.jobs[j].deps {
            if let State::Done(e) = &st.graph.jobs[d].state {
                parts.push(e.clone());
            }
        }
        parts
    }

    /// A leaf task, as a dependency of `j`.
    fn leaf(
        &self,
        st: &mut Store,
        j: usize,
        what: What,
        root: u32,
        assume: Assumed,
        k: Option<BitVec>,
    ) -> usize {
        let key = Key {
            what,
            root,
            assume,
            k,
        };
        if !st.graph.by_key.contains_key(&key) && st.done.contains_key(&key) {
            st.stats.tasks_stored += 1;
        }
        let wanted = st.graph.jobs[j].wanted.clone();
        let l = self.job(st, key, &wanted);
        self.depend(st, j, l);
        self.ready_if(st, l);
        l
    }

    /// Takes the ready task `j` as far as it goes without a worker's own work: to a leaf
    /// to solve, to waiting for tasks it has just made, or to its end.
    fn advance(&self, st: &mut Store, j: usize) -> Result<Step, Error> {
        loop {
            let job = &st.graph.jobs[j];
            if job
                .deps
                .iter()
                .any(|&d| matches!(st.graph.jobs[d].state, State::Cancelled))
            {
                // Its tasks work for all it works for, so they were cancelled with it.
                if !job.wanted.stopped() {
                    return Err(Error::Contract("a wanted task's part was cancelled".into()));
                }
                self.cancel(st, j, Cost::default());
                return Ok(Step::Settled);
            }
            if job.waiting > 0 {
                st.graph.jobs[j].state = State::Pending;
                return Ok(Step::Settled);
            }
            let (key, stage) = (job.key.clone(), job.stage);
            match &job.plan {
                Plan::Leaf => {
                    let mut cx = Context::with_config(st.cx.config().clone());
                    cx.registry = st.cx.registry.clone();
                    let root = cx.import(&st.cx, &[st.cx.handle(key.root)])?[0];
                    let mut assume = Vec::with_capacity(key.assume.len());
                    for (e, f) in key.assume.iter() {
                        assume.push((cx.import(&st.cx, &[st.cx.handle(*e)])?[0], *f));
                    }
                    return Ok(Step::Solve(Box::new(Spec {
                        job: j,
                        simplify: key.what == What::LeafSimplify,
                        hub: key.what == What::LeafHub,
                        constant: key.k,
                        cx,
                        root,
                        assume,
                        wanted: st.graph.jobs[j].wanted.clone(),
                    })));
                }
                Plan::Hub {
                    k,
                    below,
                    proofs,
                    again,
                    asked,
                    cases,
                } => {
                    let (k, below, proofs, again) = (*k, below.clone(), *proofs, *again);
                    let (asked, cases) = (*asked, *cases);
                    let proved_by = |st: &Store, l: Option<usize>| {
                        l.is_some_and(|l| match &st.graph.jobs[l].state {
                            State::Done(e) => matches!(e.res, Res::Proved),
                            _ => false,
                        })
                    };
                    let bottom_up = self.config.split.bottom_up;
                    if stage == 0 && bottom_up {
                        // Its hubs below are done: asked once, with them replaced.
                        st.graph.jobs[j].stage = 2;
                        continue;
                    }
                    if stage == 0 {
                        // As written: where the engine folds the noise by itself, one
                        // proof serves for all that is below.
                        let l =
                            self.leaf(st, j, What::LeafHub, key.root, key.assume.clone(), Some(k));
                        if let Plan::Hub { proofs, .. } = &mut st.graph.jobs[j].plan {
                            proofs[0] = Some(l);
                        }
                        st.graph.jobs[j].stage = 1;
                        continue;
                    }
                    let mut proved = proved_by(st, proofs[0]);
                    if stage == 1 && !proved && self.config.split.nested {
                        // The hubs below it first, then.
                        let kids: Vec<u32> = st.cx.node(key.root).children().collect();
                        self.plan_hubs(st, j, &kids)?;
                        st.graph.jobs[j].stage = 2;
                        continue;
                    }
                    if stage == 2 && !again {
                        self.ask_again(st, j)?;
                        continue;
                    }
                    let pairs = self.substitution(st, &below);
                    if stage == 2 && (bottom_up || !pairs.is_empty()) {
                        let hub = self.substituted(st, key.root, &pairs)?;
                        if st.cx.const_val(hub) == Some(k) {
                            // Folded by the constants below it.
                            proved = true;
                        } else {
                            let l =
                                self.leaf(st, j, What::LeafHub, hub, key.assume.clone(), Some(k));
                            if let Plan::Hub { proofs, asked, .. } = &mut st.graph.jobs[j].plan {
                                proofs[1] = Some(l);
                                *asked = hub;
                            }
                            st.graph.jobs[j].stage = 3;
                            continue;
                        }
                    }
                    proved |= proved_by(st, proofs[1]);
                    let depth = key.what.depth();
                    let stopped = (proofs[1].or(proofs[0])).is_some_and(|l| {
                        matches!(
                            &st.graph.jobs[l].state,
                            State::Done(e) if matches!(
                                e.res,
                                Res::Unknown(Unknown::Budget { .. } | Unknown::TooLarge { .. })
                            )
                        )
                    });
                    if !proved && stage < 4 && stopped && depth < self.config.split.cases {
                        // "It is its constant", in two cases.
                        let pred = match st.cx.wid(asked) {
                            1 if k.is_zero() => st.cx.c_un(UnOp::Not, asked)?,
                            1 => asked,
                            _ => {
                                let konst = st.cx.mk_const(&k)?;
                                st.cx.c_cmp(CmpOp::Eq, asked, konst)?
                            }
                        };
                        if let Some(halves) = self.split_cases(st, j, pred, depth)? {
                            if let Plan::Hub { cases, .. } = &mut st.graph.jobs[j].plan {
                                *cases = Some(halves);
                            }
                            st.graph.jobs[j].stage = 4;
                            continue;
                        }
                    }
                    if let Some((a, b)) = cases {
                        let done = |d: usize| matches!(&st.graph.jobs[d].state, State::Done(e) if matches!(e.res, Res::Proved));
                        proved |= done(a) && done(b);
                    }
                    let parts = self.parts(st, j);
                    let res = match proved {
                        true => Res::Constant(k),
                        false => Res::Unknown(Unknown::Unsupported("not proved constant".into())),
                    };
                    let mut entry = st.entry(res, Cost::default(), parts);
                    entry.subst = match proved {
                        true => Arc::from([(key.root, k)]),
                        false => pairs.into(),
                    };
                    st.stats.hubs_proved += u64::from(proved);
                    self.finish(st, j, entry);
                    return Ok(Step::Settled);
                }
                Plan::Ask {
                    candidate,
                    fallback,
                    root,
                    hubs,
                    first,
                    pred,
                    rest,
                    cases,
                    search,
                    found,
                    read,
                    again,
                } => {
                    let (candidate, fallback, root, pred) = (*candidate, *fallback, *root, *pred);
                    let (rest, cases, first) = (*rest, *cases, *first);
                    let (search, found, read, again) = (*search, *found, *read, *again);
                    let hubs = hubs.clone();
                    let done = |st: &Store, d: usize| match &st.graph.jobs[d].state {
                        State::Done(e) => Ok(e.clone()),
                        _ => Err(Error::Contract("a task ready before its parts".into())),
                    };
                    if stage == 0 && search && !read {
                        let Some(l) = found else {
                            // An assignment that satisfies the assumptions: what refutes
                            // "false" under them.
                            let no = st.cx.bool(false)?;
                            let no = st.cx.id(no)?;
                            let l = self.leaf(st, j, What::LeafValid, no, key.assume.clone(), None);
                            if let Plan::Ask { found, .. } = &mut st.graph.jobs[j].plan {
                                *found = Some(l);
                            }
                            continue;
                        };
                        let constant = key.what == What::AskConstant;
                        let held = match &done(st, l)?.res {
                            Res::Refuted(m) => {
                                self.look(st, &key.assume, Some(m))? == Looked::Holds
                            }
                            Res::Proved if constant => {
                                let why = "the assumptions cannot hold together".into();
                                let parts = self.parts(st, j);
                                let res = Res::Unknown(Unknown::Unsupported(why));
                                let entry = st.entry(res, Cost::default(), parts);
                                self.finish(st, j, entry);
                                return Ok(Step::Settled);
                            }
                            _ => false,
                        };
                        if constant && held {
                            let watched = self.sample_under(st, &key.assume, &[root], &[root])?;
                            self.read(st, j, &watched[&root])?;
                            if matches!(st.graph.jobs[j].state, State::Done(_)) {
                                return Ok(Step::Settled);
                            }
                        }
                        if let Plan::Ask { read, fallback, .. } = &mut st.graph.jobs[j].plan {
                            *read = true;
                            *fallback |= constant && !held;
                        }
                        if self.config.split.hubs && !self.whole_first(st, j) {
                            self.plan_hubs(st, j, &[root])?;
                        }
                        continue;
                    }
                    if stage == 0 {
                        if self.whole_first(st, j) {
                            // The question as asked, before any cut.
                            let whole = match candidate {
                                Some((k, _)) if key.what == What::AskConstant => {
                                    let konst = st.cx.mk_const(&k)?;
                                    st.cx.c_cmp(CmpOp::Eq, key.root, konst)?
                                }
                                _ => key.root,
                            };
                            let l = match (key.what, candidate) {
                                (What::AskSimplify, _) => {
                                    let what = What::LeafSimplify;
                                    self.leaf(st, j, what, key.root, key.assume.clone(), None)
                                }
                                (What::AskConstant, Some((k, _))) => {
                                    let what = What::LeafConstant;
                                    self.leaf(st, j, what, key.root, key.assume.clone(), Some(k))
                                }
                                _ => self.leaf(
                                    st,
                                    j,
                                    What::LeafValid,
                                    whole,
                                    key.assume.clone(),
                                    None,
                                ),
                            };
                            if let Plan::Ask { first, pred, .. } = &mut st.graph.jobs[j].plan {
                                (*first, *pred) = (Some(l), whole);
                            }
                            st.graph.jobs[j].stage = 1;
                        } else {
                            st.graph.jobs[j].stage = 2;
                        }
                        continue;
                    }
                    if stage == 1 {
                        let l = first.ok_or_else(|| Error::Contract("no first attempt".into()))?;
                        let whole = done(st, l)?;
                        // (A simplification is an answer as it is.)
                        if matches!(
                            whole.res,
                            Res::Proved | Res::Refuted(_) | Res::Simplified { .. }
                        ) {
                            let res =
                                self.answer(st, &key, candidate, fallback, whole.res.clone())?;
                            let parts = self.parts(st, j);
                            let entry = st.entry(res, Cost::default(), parts);
                            self.finish(st, j, entry);
                            return Ok(Step::Settled);
                        }
                        if self.config.split.hubs {
                            self.plan_hubs(st, j, &[root])?;
                            st.graph.jobs[j].stage = 2;
                        } else {
                            if let Plan::Ask { rest, .. } = &mut st.graph.jobs[j].plan {
                                *rest = Some(l);
                            }
                            st.graph.jobs[j].stage = 3;
                        }
                        continue;
                    }
                    if stage == 2 && !again {
                        self.ask_again(st, j)?;
                        continue;
                    }
                    if stage == 2 {
                        let pairs = self.substitution(st, &hubs);
                        let left = self.substituted(st, root, &pairs)?;
                        let mut is = None;
                        let (what, asked) = match (key.what, candidate) {
                            (What::AskSimplify, _) => (What::LeafSimplify, left),
                            (What::AskConstant, _) if fallback => (What::LeafSimplify, left),
                            (What::AskConstant, Some((k, _))) => {
                                if let Some(v) = st.cx.const_val(left) {
                                    // What is left is a constant: of every value.
                                    let parts = self.parts(st, j);
                                    let entry = st.entry(Res::Constant(v), Cost::default(), parts);
                                    self.finish(st, j, entry);
                                    return Ok(Step::Settled);
                                }
                                let konst = st.cx.mk_const(&k)?;
                                is = Some(k);
                                (What::LeafConstant, st.cx.c_cmp(CmpOp::Eq, left, konst)?)
                            }
                            _ => (What::LeafValid, left),
                        };
                        // A constant is asked of the expression; the equality is what a
                        // case split would be of.
                        let of = if is.is_some() { left } else { asked };
                        let l = self.leaf(st, j, what, of, key.assume.clone(), is);
                        if let Plan::Ask { pred, rest, .. } = &mut st.graph.jobs[j].plan {
                            (*pred, *rest) = (asked, Some(l));
                        }
                        st.graph.jobs[j].stage = 3;
                        continue;
                    }
                    let rest = rest.ok_or_else(|| Error::Contract("no remainder".into()))?;
                    let answer = done(st, rest)?;
                    let depth = match key.what {
                        What::AskValid(d) => d,
                        _ => 0,
                    };
                    let mut res = answer.res.clone();
                    if stage == 3
                        && matches!(key.what, What::AskValid(_) | What::AskConstant)
                        && !fallback
                        && depth < self.config.split.cases
                        && matches!(
                            res,
                            Res::Unknown(Unknown::Budget { .. } | Unknown::TooLarge { .. })
                        )
                        && let Some(halves) = self.split_cases(st, j, pred, depth)?
                    {
                        if let Plan::Ask { cases, .. } = &mut st.graph.jobs[j].plan {
                            *cases = Some(halves);
                        }
                        st.graph.jobs[j].stage = 4;
                        continue;
                    }
                    if let Some((a, b)) = cases {
                        let (a, b) = (done(st, a)?, done(st, b)?);
                        res = match (&a.res, &b.res) {
                            (Res::Proved, Res::Proved) => Res::Proved,
                            (Res::Refuted(m), _) | (_, Res::Refuted(m)) => Res::Refuted(m.clone()),
                            _ => res,
                        };
                    }
                    let res = self.answer(st, &key, candidate, fallback, res)?;
                    let parts = self.parts(st, j);
                    let entry = st.entry(res, Cost::default(), parts);
                    self.finish(st, j, entry);
                    return Ok(Step::Settled);
                }
            }
        }
    }

    /// The answer of the question `key` from that of its remainder, a counterexample
    /// replayed on the question as asked.
    fn answer(
        &self,
        st: &mut Store,
        key: &Key,
        candidate: Option<(BitVec, u32)>,
        fallback: bool,
        res: Res,
    ) -> Result<Res, Error> {
        let mut near = vec![key.root];
        near.extend(key.assume.iter().map(|x| x.0));
        // The values of the question and its constraints at a counterexample.
        let replay = |st: &mut Store, model: &mut Model| -> Result<(BitVec, bool), Error> {
            let given: HashSet<SymbolKey> = model.iter().map(|x| x.0.clone()).collect();
            for (k, v) in point_model(&mut st.cx, &near, 0)? {
                if !given.contains(&k) {
                    model.push((k, v));
                }
            }
            let env: HashMap<SymbolKey, BitVec> = model.iter().cloned().collect();
            let handles: Vec<Expr> = near.iter().map(|&i| st.cx.handle(i)).collect();
            let vals = st.cx.eval(&handles, &env)?;
            let holds = (key.assume.iter().zip(&vals[1..])).all(|((_, f), v)| f.contains(v));
            Ok((vals[0], holds))
        };
        let unsound = || Error::Contract("a counterexample does not refute its question".into());
        Ok(match (key.what, res) {
            (What::AskConstant, Res::Simplified { expr, .. }) if fallback => {
                match st.cx.const_val(expr) {
                    Some(v) => Res::Constant(v),
                    None => Res::Unknown(Unknown::Unsupported(
                        "no assignment that satisfies the assumptions was found".into(),
                    )),
                }
            }
            (What::AskConstant, Res::Proved) => match candidate {
                Some((k, _)) => Res::Constant(k),
                None => return Err(Error::Contract("a constant without a candidate".into())),
            },
            (What::AskConstant, Res::Refuted(mut m)) => {
                let Some((k, p)) = candidate else {
                    return Err(unsound());
                };
                let (v, holds) = replay(st, &mut m)?;
                if v == k || !holds {
                    return Err(unsound());
                }
                let other = self.point(st, key, p)?;
                Res::Varies(Box::new((other, m)))
            }
            (What::AskValid(_), Res::Refuted(mut m)) => {
                let (v, holds) = replay(st, &mut m)?;
                if !v.is_zero() || !holds {
                    return Err(unsound());
                }
                Res::Refuted(m)
            }
            (_, res) => res,
        })
    }

    /// `j` is done: kept in the store, and the tasks waiting for it are told.
    fn finish(&self, st: &mut Store, j: usize, mut entry: Entry) {
        if st.graph.tops.contains(&j) || matches!(st.graph.jobs[j].plan, Plan::Ask { .. }) {
            // A question's cost: every task below it, once.
            let mut total = entry.own;
            let mut seen: HashSet<u64> = HashSet::new();
            let mut stack: Vec<&Arc<Entry>> = entry.parts.iter().collect();
            while let Some(e) = stack.pop() {
                if seen.insert(e.id) {
                    total.add(&e.own);
                    stack.extend(e.parts.iter());
                }
            }
            entry.total = total;
        }
        let entry = Arc::new(entry);
        let key = st.graph.jobs[j].key.clone();
        st.done.insert(key, entry.clone());
        st.graph.jobs[j].state = State::Done(entry);
        self.settled(st, j);
    }

    /// `j` stopped for its cancel flags, having spent `partial`.
    fn cancel(&self, st: &mut Store, j: usize, partial: Cost) {
        st.stats.cancelled += 1;
        st.graph.jobs[j].partial = partial;
        st.graph.jobs[j].state = State::Cancelled;
        self.settled(st, j);
    }

    fn settled(&self, st: &mut Store, j: usize) {
        if st.graph.tops.contains(&j) {
            st.graph.open -= 1;
        }
        for d in core::mem::take(&mut st.graph.jobs[j].dependents) {
            let job = &mut st.graph.jobs[d];
            job.waiting = job.waiting.saturating_sub(1);
            self.ready_if(st, d);
        }
        self.wake.notify_all();
    }

    /// A worker: takes ready tasks until every ask is answered.
    fn work(&self) {
        let mut st = self.lock();
        loop {
            if st.graph.error.is_some() || st.graph.open == 0 {
                self.wake.notify_all();
                return;
            }
            let Some(j) = st.graph.ready.pop_front() else {
                if st.graph.running == 0 {
                    st.graph.error = Some(Error::Contract("tasks left with none ready".into()));
                    continue;
                }
                st = self.wake.wait(st).unwrap_or_else(|e| e.into_inner());
                continue;
            };
            if !matches!(st.graph.jobs[j].state, State::Ready) {
                continue;
            }
            if st.graph.jobs[j].wanted.stopped() {
                self.cancel(&mut st, j, Cost::default());
                continue;
            }
            let spec = match self.advance(&mut st, j) {
                Ok(Step::Settled) => continue,
                Ok(Step::Solve(spec)) => spec,
                Err(e) => {
                    st.graph.error = Some(e);
                    continue;
                }
            };
            st.graph.jobs[j].state = State::Running;
            st.graph.running += 1;
            drop(st);
            let solved =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.solve(*spec)));
            st = self.lock();
            st.graph.running -= 1;
            let merged = match solved {
                Ok(Ok(s)) => self.merge(&mut st, s),
                Ok(Err(e)) => Err(e),
                Err(_) => Err(Error::Contract("a task panicked".into())),
            };
            if let Err(e) = merged {
                st.graph.error = Some(e);
            }
        }
    }

    /// A worker's result, into the store.
    fn merge(&self, st: &mut Store, s: Solved) -> Result<(), Error> {
        let j = s.job;
        let Some(res) = s.res else {
            if st.graph.jobs[j].wanted.stopped() {
                self.cancel(st, j, s.cost);
            } else {
                // Wanted again since it started: from its beginning.
                st.graph.jobs[j].state = State::Ready;
                st.graph.ready.push_back(j);
                self.wake.notify_all();
            }
            return Ok(());
        };
        let res = match res {
            SolvedRes::Simplified(e, end) => {
                let e = st.cx.import(&s.cx, &[e])?[0];
                Res::Simplified {
                    expr: st.cx.id(e)?,
                    end,
                }
            }
            SolvedRes::Outcome(Outcome::Proved(_)) => Res::Proved,
            SolvedRes::Outcome(Outcome::Refuted(m)) => Res::Refuted(m),
            SolvedRes::Outcome(Outcome::Unknown(why)) => Res::Unknown(why),
        };
        st.stats.tasks_solved += 1;
        let entry = st.entry(res, s.cost, Vec::new());
        self.finish(st, j, entry);
        Ok(())
    }

    /// Decides a leaf in its own context: the engine on its root, or a proof of it.
    fn solve(&self, spec: Spec) -> Result<Solved, Error> {
        let Spec {
            job,
            simplify,
            hub,
            constant,
            mut cx,
            mut root,
            assume,
            wanted,
        } = spec;
        let cfg = match (hub, &self.config.hub) {
            (true, Some(h)) => h,
            _ => &self.config.prove,
        };
        let mut assumptions = Assumptions::new();
        for (e, facts) in &assume {
            assumptions.assume(&mut cx, *e, *facts)?;
        }
        let assumptions = (!assume.is_empty()).then_some(&assumptions);
        let deadline = (!wanted.always).then(|| Deadline::new(&wanted, 1));
        let mut cost = Cost {
            tasks: 1,
            ..Cost::default()
        };
        if simplify {
            let mut spent = Allowance::new(Budget::UNLIMITED);
            let mut run = Run::default()
                .with_per_call(cfg.simplify_budget)
                .with_allowance(&mut spent);
            if let Some(a) = assumptions {
                run = run.with_assumptions(a);
            }
            if let Some(d) = deadline {
                run = run.with_deadline(d);
            }
            let engine = self.simplifiers.engine(cfg.strict, cfg.proved_words);
            let out = engine.run(&mut cx, &[root], run)?.roots[0];
            cost.simplify = spent.spent();
            let stopped = out.end == End::BudgetTerminated(Exhausted::Deadline);
            return Ok(Solved {
                job,
                res: (!stopped).then_some(SolvedRes::Simplified(out.expr, out.end)),
                cx,
                cost,
            });
        }
        if let Some(k) = constant {
            // The engine on the expression. Asked of the equality with `k` it moves terms
            // across it, and what cancels on one side no longer meets.
            let konst = cx.constant(&k)?;
            if cfg.simplify {
                let mut spent = Allowance::new(Budget::UNLIMITED);
                let mut run = Run::default()
                    .with_per_call(cfg.simplify_budget)
                    .with_allowance(&mut spent);
                if let Some(a) = assumptions {
                    run = run.with_assumptions(a);
                }
                if let Some(d) = deadline {
                    run = run.with_deadline(d);
                }
                let engine = self.simplifiers.engine(cfg.strict, cfg.proved_words);
                let out = engine.run(&mut cx, &[root], run)?.roots[0];
                cost.simplify = spent.spent();
                if out.end == End::BudgetTerminated(Exhausted::Deadline) {
                    return Ok(Solved {
                        job,
                        res: None,
                        cx,
                        cost,
                    });
                }
                if out.expr == konst {
                    return Ok(Solved {
                        job,
                        res: Some(SolvedRes::Outcome(Outcome::Proved(None))),
                        cx,
                        cost,
                    });
                }
                root = out.expr;
            }
            root = cx.cmp(CmpOp::Eq, root, konst)?;
        }
        let env = Env {
            simplifiers: &self.simplifiers,
            deadline,
        };
        let before_build = cost.simplify;
        let mut q = Question::build(&mut cx, root, assumptions, &[], cfg, env)?;
        let total = cfg.limits();
        let before = q.stats();
        let outcome = loop {
            let now = q.stats();
            // What is left of the limits, counted from the first search as one search's are.
            let left = Limits {
                conflicts: total
                    .conflicts
                    .saturating_sub(now.conflicts - before.conflicts),
                propagations: total
                    .propagations
                    .saturating_sub(now.propagations - before.propagations),
            };
            // (A limit used up leaves nothing to slice: the search says so itself.)
            let whole = wanted.always || left.conflicts == 0 || left.propagations == 0;
            let slice = match whole {
                true => left,
                false => Limits {
                    conflicts: left.conflicts.min(SLICE.conflicts),
                    propagations: left.propagations.min(SLICE.propagations),
                },
            };
            match q.solve(&mut cx, slice)? {
                Outcome::Unknown(Unknown::Budget { .. }) if slice != left && !wanted.stopped() => {}
                Outcome::Unknown(Unknown::Budget { .. }) if slice != left => break None,
                Outcome::Unknown(Unknown::Deadline) => break None,
                o => break Some(o),
            }
        };
        let stats = q.stats();
        cost.simplify = stats.simplification.spent;
        cost.add(&Cost {
            simplify: before_build,
            ..Cost::default()
        });
        cost.conflicts = stats.conflicts;
        cost.propagations = stats.propagations;
        cost.decisions = stats.decisions;
        cost.circuit_nodes = stats.nodes as u64;
        cost.samples = stats.samples;
        Ok(Solved {
            job,
            res: outcome.map(SolvedRes::Outcome),
            cx,
            cost,
        })
    }
}

/// What the tasks below `j` spent, finished or stopped, each once.
fn spent_below(graph: &Graph, j: usize) -> Cost {
    let mut total = Cost::default();
    let mut jobs: HashSet<usize> = HashSet::new();
    let mut entries: HashSet<u64> = HashSet::new();
    let mut stack = vec![j];
    while let Some(j) = stack.pop() {
        if !jobs.insert(j) {
            continue;
        }
        let job = &graph.jobs[j];
        match &job.state {
            State::Done(e) => {
                let mut es = vec![e];
                while let Some(e) = es.pop() {
                    if entries.insert(e.id) {
                        total.add(&e.own);
                        es.extend(e.parts.iter());
                    }
                }
            }
            _ => {
                total.add(&job.partial);
                stack.extend(job.deps.iter().copied());
            }
        }
    }
    total
}