deduxit 0.4.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Proof search: decide whether a sequent is provable, and get its proof
//! or the reason it has none.
//!
//! [`prove`] decides a sequent, [`prove_within`] does so under
//! [`Limits`] and a stop condition, and [`prove_goal`] decides a
//! [`Goal`], any multiset of a forest's occurrences. Each returns an
//! [`Outcome`], whose [`Verdict`] is a checked proof, a [`Disproof`], or
//! the [`Reason`] the search gave up. [`Options`] picks the engine and
//! tunes the search.
//!
//! The library picks an engine by the sequent's fragment and the mode.
//! [`Engine`] lists the engines, and its documentation says which one
//! decides which sequents. [`batch`] decides many sequents in one call.

/// The additive fast path.
pub(crate) mod additive;
/// The check of a refutation by the basis of a backward search, apart
/// from the search.
mod basis;
pub mod batch;
/// The classical refuter: it looks for an assignment of truth values
/// that makes the goal's classical reading false.
mod classical;
/// Essential-net search for unit-free IMLL.
mod essential;
/// The focused sequent engine.
pub(crate) mod focus;
/// Random provable sequents for the tests.
#[cfg(all(test, feature = "parse"))]
pub(crate) mod generate;
/// The Horn engine: reachability of markings.
pub(crate) mod horn;
/// The focused inverse method, a search forward from the axioms.
mod inverse;
/// The count of the bytes a search holds.
pub(crate) mod memory;
/// The proof-net engine.
pub(crate) mod net;
#[cfg(feature = "parallel")]
mod parallel;
/// The planar criterion of the linking searches, for the ordered modes.
mod planar;
/// A reference prover for the tests: the plain unfocused calculus.
#[cfg(all(test, feature = "parse"))]
pub(crate) mod reference;
/// A first-order reference prover for the tests: the plain unfocused
/// calculus with unification and the eigenvariable condition by
/// freshness.
#[cfg(all(test, feature = "parse"))]
pub(crate) mod reference_fo;
/// Why a sequent is unprovable, and the disproof that says so.
mod refutation;
/// The check of a refutation by a saturated set, apart from the search.
mod saturated;
/// The weighted count that certifies a one-sided count and a Horn
/// program's state equation, apart from the search.
pub(crate) mod weighted;
/// A search's count of its work, and the values its threads share.
mod work;

#[cfg(feature = "parallel")]
pub use parallel::Pool;
pub use refutation::{
    Basis, Classical, Disproof, Equation, Marking, OneSided, OneSidedSymbol, Refutation,
    RefutationFault, Saturated, Stable, StateEquation, Unbalanced, UnbalancedSymbol,
};

use crate::Error;
use crate::limits::{Limits, Phase, Progress, Refusal};
use crate::linear::fragment::{Fragment, Mode, Order};
use crate::linear::nets::ProofStructure;
use crate::linear::occurrences::{Forest, Member, OccId, Reading};
use crate::linear::proofs::{Bytes, CheckError, Node, NodeId, Proof};
use crate::linear::sequents::Sequent;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::OnceLock;

#[cfg(feature = "parallel")]
pub(crate) use work::taken;
pub(crate) use work::{Counted, Work, lock};

/// An engine's stop condition: the caller's in a sequential search, a
/// worker's chain of stop flags in a parallel one. Each poll is told the
/// units of work done since the last.
pub(crate) enum Stop<'a> {
    /// The caller's condition.
    Closure(&'a mut dyn FnMut(u64) -> bool),
    /// The caller's condition, and the work left in this turn, after
    /// which the search stops too. It is one turn of a search that takes
    /// turns with another.
    Turn(&'a mut dyn FnMut(u64) -> bool, u64),
    /// A condition told at every poll the work since the last, and
    /// whether a slice of work has passed since it was last told so. The
    /// fields are the condition, the work left in the slice, and the
    /// slice.
    ///
    /// It is one of two searches that alternate: it gives way to the
    /// other at the end of each slice.
    #[cfg_attr(
        not(feature = "parallel"),
        expect(
            dead_code,
            reason = "only threads alternate the two searches in slices"
        )
    )]
    Slice(&'a mut dyn FnMut(u64, bool) -> bool, u64, u64),
    /// A worker's flags, and its count of the search's work.
    #[cfg(feature = "parallel")]
    Flags(parallel::Flags<'a>, Counted<'a>),
}

impl<'a> Stop<'a> {
    /// Polls the condition after `work` more units of work, in the
    /// polling engine's unit. Returns whether the search must stop.
    pub(crate) fn fired(&mut self, work: u64) -> bool {
        match self {
            Self::Closure(stop) => stop(work),
            Self::Turn(stop, left) => {
                *left = left.saturating_sub(work);
                // The caller is told the units of the poll that ends the
                // turn too.
                let stopped = stop(work);
                *left == 0 || stopped
            }
            Self::Slice(stop, left, slice) => {
                *left = left.saturating_sub(work);
                let passed = *left == 0;
                if passed {
                    *left = *slice;
                }
                stop(work, passed)
            }
            #[cfg(feature = "parallel")]
            Self::Flags(flags, counted) => flags.fired(work, counted),
        }
    }

    /// A worker's stop: its flags, and its own count of the search's work.
    /// The count adds its units to the search's in batches, and the rest
    /// when the worker ends.
    #[cfg(feature = "parallel")]
    pub(crate) fn flags(flags: parallel::Flags<'a>) -> Self {
        Self::Flags(flags, flags.counted())
    }
}

/// The occurrences a forest must have for a search to poll the stop
/// condition between the passes that set it up.
///
/// A pass over fewer takes under a millisecond. Below it, a condition
/// that counts its polls sees the engine's own polls and no others.
const SET_UP_POLL: usize = 1 << 16;

/// Polls the caller's stop condition between two passes that set a
/// search up, when the forest has at least [`SET_UP_POLL`] occurrences.
/// Returns whether to stop.
///
/// On millions of occurrences the set-up takes a second, and the
/// engine's first poll comes after it.
pub(crate) fn set_up_stopped(forest: &Forest, stop: &mut dyn FnMut(u64) -> bool) -> bool {
    forest.len() >= SET_UP_POLL && stop(0)
}

/// Decides a sequent in a mode, and returns the outcome.
///
/// The outcome holds the verdict (with the proof, if there is one), the
/// fragment detected, the engine that ran and the statistics of the run.
/// The engine is the one the sequent's fragment and the mode call for,
/// unless the options force one. The search runs under the default
/// [`Limits`] and never stops early; [`prove_within`] takes limits and a
/// stop condition.
///
/// Every proof returned has passed the checker, unless [`Options::check`]
/// is off.
///
/// # Errors
///
/// - [`Error::FragmentMismatch`]: the sequent is outside the fragment the
///   options assert.
/// - [`Error::NotIntuitionistic`]: in intuitionistic mode, the sequent
///   has no intuitionistic reading.
/// - [`Error::IntuitionisticMix`]: intuitionistic mode with Mix.
/// - [`Error::EngineRefused`]: the options force an engine that does not
///   search this sequent, with the [`NotTaken`] that says why. The net
///   engine takes unit-free MLL only, and not in affine mode. The focused
///   engine is refused in intuitionistic mode, the two-sided engine in
///   classical mode. The additive engine takes two additive-only formulas
///   only, the Horn engine a Horn program only.
/// - [`Refusal::Occurrences`]: the sequent unfolds to more subformula
///   occurrences than `limits.occurrences` allows.
/// - [`Error::Rejected`]: the checker rejects a proof an engine found.
///   This is a defect of the library, not a verdict.
/// - [`Error::ThreadPool`]: on several threads, they cannot start.
///
/// A check of the proof that a bound or the stop gives up is no error.
/// The verdict is then [`Verdict::Unknown`]: with [`Reason::Unchecked`]
/// when the check would hold more than `limits.memory_bytes`, and with
/// [`Reason::WorkLimit`] or [`Reason::Stopped`] when `limits.work` or the
/// stop ends it.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Engine, Options, Verdict, prove};
/// use deduxit::linear::{Fragment, Mode, Sequent};
///
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
/// assert_eq!(outcome.fragment, Fragment::MLL);
/// assert_eq!(outcome.engine, Engine::Focus);
/// let net = Options::default().with_engine(Some(Engine::Net));
/// let by_net = prove(&sequent, Mode::CLASSICAL, &net)?;
/// assert!(by_net.net.is_some(), "the net engine returns the net it found");
/// let Verdict::Proved(proof) = outcome.verdict else {
///     panic!("provable");
/// };
/// assert_eq!(
///     proof.derivation()?.to_string(),
///     "─────── ax   ─────── ax\n\
///      ⊢ ~A, A      ⊢ ~B, B\n\
///      ──────────────────── ⊗\n\
///     \x20 ⊢ ~A, A ⊗ ~B, B"
/// );
///
/// let sequent: Sequent = "|- A par B, ~A, ~B".parse()?;
/// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
/// assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
/// let outcome = prove(&sequent, Mode::CLASSICAL.with_mix(), &Options::default())?;
/// assert!(matches!(outcome.verdict, Verdict::Proved(_)));
/// # Ok::<(), deduxit::Error>(())
/// ```
pub fn prove(sequent: &Sequent, mode: Mode, options: &Options) -> Result<Outcome, Error> {
    prove_within(sequent, mode, options, &Limits::default(), |_| false)
}

/// Decides a sequent as [`prove`] does, within `limits`, and gives up
/// with [`Reason::Stopped`] once `stop` returns true.
///
/// The limits bound:
/// - the sequent's forest, by `limits.occurrences`;
/// - the search's structures and the check of its proof, by
///   `limits.memory_bytes`;
/// - the search's recursion, by `limits.recursion_depth`;
/// - the search's work, and the check's, each by `limits.work`.
///
/// The stop condition is the caller's: a deadline on the caller's clock,
/// or a flag an interrupt handler sets. This crate has no clock of its
/// own. `|_| false` never stops. The condition is told the [`Progress`]
/// at every poll: [`Phase::Search`] during the
/// search, [`Phase::Refute`] while a refuter looks
/// for a disproof after it, and [`Phase::Check`]
/// while what it found is checked.
///
/// Where it is polled: the engines poll at every stable sequent or
/// literal chosen, and inside every loop that can run long between two of
/// them. On a forest of tens of thousands of occurrences, they also poll
/// between the passes that set the search up. The check of a proof found
/// polls every 4 096 nodes. The building of the forest before the search
/// is not polled, nor are single passes over the forest, each linear in
/// it.
///
/// Make the condition cheap to ask, and ask it at every poll. One that
/// reads a clock only every so many polls is late by that many polls, and
/// on a large sequent a poll can come many milliseconds after the last.
///
/// # Errors
///
/// Those of [`prove`], under `limits`.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Options, Reason, Verdict, prove_within};
/// use deduxit::{Limits, Phase, Progress, linear::{Mode, Sequent}};
/// use std::time::{Duration, Instant};
///
/// let sequent: Sequent = "|- (a & b) + (a & c), ~a par (~b & ~c)".parse()?;
/// let (options, limits) = (Options::default(), Limits::default());
///
/// // `|_| false` never stops: the search ends at a verdict or a bound.
/// let outcome = prove_within(&sequent, Mode::CLASSICAL, &options, &limits, |_| false)?;
/// assert!(!matches!(outcome.verdict, Verdict::Unknown(_)));
///
/// // A deadline on the caller's clock.
/// let deadline = Instant::now() + Duration::from_secs(10);
/// let outcome = prove_within(&sequent, Mode::CLASSICAL, &options, &limits, |_| {
///     Instant::now() >= deadline
/// })?;
/// assert!(!matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
///
/// // A deadline for the search alone. What runs after the search (the
/// // refuters, the check) runs on within its own bounds.
/// let outcome = prove_within(&sequent, Mode::CLASSICAL, &options, &limits, |p: Progress| {
///     p.phase == Phase::Search && Instant::now() >= deadline
/// })?;
/// assert!(!matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
/// # Ok::<(), deduxit::Error>(())
/// ```
pub fn prove_within(
    sequent: &Sequent,
    mode: Mode,
    options: &Options,
    limits: &Limits,
    stop: impl FnMut(Progress) -> bool,
) -> Result<Outcome, Error> {
    let forest = Forest::within(sequent, limits)?;
    prove_goal(Goal::conclusion(&forest), mode, options, limits, stop)
}

/// Decides a goal of a forest with cut formulas by `run` on a forest of
/// its own, so that no engine sees a cut formula.
///
/// The own forest is that of a cut-free sequent over the same arena,
/// whose roots are the goal's formulas. Intuitionistically, the
/// hypotheses come first, left of `⊢`, then the goal's output. It
/// numbers each formula's occurrences as the goal's forest does, shifted.
///
/// A proof found is carried back by the shift, as a proof of the goal.
/// It is checked again there when it was checked. A disproof is the own
/// sequent's, whose formulas are the goal's.
fn on_own_forest(
    goal: Goal<'_>,
    mode: Mode,
    limits: &Limits,
    stop: &mut dyn FnMut(Progress) -> bool,
    run: impl FnOnce(&Forest, &mut dyn FnMut(Progress) -> bool) -> Result<Outcome, Error>,
) -> Result<Outcome, Error> {
    let forest = goal.forest;
    let mut members: Vec<OccId> = goal.occurrences().into_owned();
    let antecedents = if mode.is_intuitionistic() {
        let reading = Reading::of_mode(forest, mode).map_err(Error::NotIntuitionistic)?;
        let outputs = reading.outputs(members.iter().copied());
        if outputs != 1 {
            return Err(Error::GoalOutputs { count: outputs });
        }
        // Stable, so the hypotheses keep their order.
        members.sort_by_key(|&o| reading.position(o) == crate::linear::Side::Output);
        Some(members.len() as u32 - 1)
    } else {
        None
    };
    let sequent = forest.sequent();
    let own = Sequent {
        terms: sequent.terms().to_vec(),
        roots: members.iter().map(|&o| forest.term(o)).collect(),
        atoms: sequent.atom_names().to_vec(),
        antecedents,
        cuts: vec![],
        fo: sequent.fo.clone(),
    };
    let own = Forest::within(&own, limits)?;
    let mut outcome = run(&own, stop)?;
    let Verdict::Proved(proof) = &outcome.verdict else {
        return Ok(outcome);
    };
    // An occurrence of the own forest, in the goal's forest: its formula's
    // member, plus how far into the formula it lies.
    let lift = |m: Member| {
        let o = m.occ();
        let root = own.root(o);
        let i = own.roots().partition_point(|&r| r < root);
        Ok::<_, Error>(Member::from(OccId::new(
            members[i].get() + (o.get() - root.get()),
        )))
    };
    let nodes = proof
        .nodes()
        .iter()
        .map(|&node| node.renamed(lift))
        .collect::<Result<Vec<_>, _>>()?;
    let carried = if goal.conclusion {
        Proof::new(forest.clone(), nodes, proof.root())?
    } else {
        Proof::new_of_goal(forest.clone(), goal.members, nodes, proof.root())?
    };
    let carried = match proof.mode() {
        Some(mode) => carried.with_mode(mode),
        None => carried,
    };
    if outcome.checked {
        match carried.check_within(mode, limits, &mut *stop) {
            Ok(()) => {}
            Err(e @ CheckError::Invalid(_)) => return Err(Error::Rejected(Box::new(e))),
            Err(e @ CheckError::Refused(_)) => {
                return Err(Error::Check(e));
            }
        }
    }
    outcome.verdict = Verdict::Proved(Box::new(carried));
    Ok(outcome)
}

/// What a search decides: a multiset of a forest's occurrences, read as
/// the sequent of those subformulas.
///
/// It is the forest's conclusion (its roots, in any order) or any other
/// multiset of its occurrences, such as a goal an interactive proof left
/// open. [`prove_goal`] decides it.
#[derive(Clone, Copy, Debug)]
pub struct Goal<'a> {
    /// The forest.
    forest: &'a Forest,
    /// The members, as given; empty for the conclusion.
    members: &'a [Member],
    /// Whether the members are the roots.
    conclusion: bool,
}

impl<'a> Goal<'a> {
    /// Returns the forest's conclusion, the sequent itself, as a goal.
    pub fn conclusion(forest: &'a Forest) -> Self {
        Self {
            forest,
            members: &[],
            conclusion: true,
        }
    }

    /// Returns the goal of the members given, in any order and with
    /// repeats. The roots in any order are the conclusion.
    ///
    /// # Errors
    ///
    /// [`Error::IndexOutOfBounds`] for a member outside the forest.
    pub fn new(forest: &'a Forest, members: &'a [Member]) -> Result<Self, Error> {
        if let Some(m) = members.iter().find(|m| m.index() >= forest.len()) {
            return Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Occurrence,
                index: m.index(),
                len: forest.len(),
            });
        }
        let occurrences: Vec<OccId> = members.iter().map(|m| m.occ()).collect();
        Ok(Self {
            forest,
            members,
            conclusion: forest.is_roots(&occurrences),
        })
    }

    /// Returns whether the goal is the forest's conclusion.
    pub fn is_conclusion(&self) -> bool {
        self.conclusion
    }

    /// Returns the forest.
    pub fn forest(&self) -> &'a Forest {
        self.forest
    }

    /// Returns the goal's occurrences: the roots in the forest's order
    /// for the conclusion, the members as given otherwise.
    fn occurrences(&self) -> std::borrow::Cow<'a, [OccId]> {
        if self.conclusion {
            std::borrow::Cow::Borrowed(self.forest.roots())
        } else {
            std::borrow::Cow::Owned(self.members.iter().map(|m| m.occ()).collect())
        }
    }
}

/// Decides a [`Goal`] within `limits` and until `stop` returns true, as
/// [`prove_within`] does.
///
/// A goal is a multiset of a forest's occurrences, given in any order,
/// read as the sequent of those subformulas. The roots are the sequent
/// itself, and [`prove_within`] is this function on them. Any other goal
/// is one an interactive proof leaves open. The engine is the one the
/// goal's own fragment calls for, except that the net engine works on the
/// roots only.
///
/// The proof of a goal other than the roots is a [`Proof`] whose root
/// concludes the goal. It records the goal ([`Proof::goal`]), and
/// [`Proof::check`] checks it against that goal. It is meant to be
/// grafted onto the goal, as the interactive state does. Where a proof of
/// the sequent is needed, it is refused ([`Error::GoalProof`]). Every
/// proof records the mode it was found in ([`Proof::mode`]).
///
/// # Errors
///
/// Those of [`prove`], plus [`Error::GoalOutputs`] for an
/// intuitionistic goal without exactly one formula on the right of `⊢`,
/// and [`Error::EngineRefused`] with [`NotTaken::Goal`] for the net engine
/// forced on a goal other than the roots.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Goal, Options, Verdict, prove_goal};
/// use deduxit::{Limits, linear::{Forest, Member, Mode, Sequent}};
///
/// // The sequent is ⊢ ~A, A ⊗ ~B, B, with the occurrences 0: ~A,
/// // 1: A ⊗ ~B, 2: A, 3: ~B, 4: B. The goal ⊢ ~A, A is the left premise
/// // of the ⊗.
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let forest = Forest::new(&sequent)?;
/// let members = [Member::new(0), Member::new(2)];
/// let goal = Goal::new(&forest, &members)?;
/// let limits = Limits::default();
/// let outcome = prove_goal(goal, Mode::CLASSICAL, &Options::default(), &limits, |_| false)?;
/// assert!(matches!(outcome.verdict, Verdict::Proved(_)));
/// # Ok::<(), deduxit::Error>(())
/// ```
pub fn prove_goal(
    goal: Goal<'_>,
    mode: Mode,
    options: &Options,
    limits: &Limits,
    mut stop: impl FnMut(Progress) -> bool,
) -> Result<Outcome, Error> {
    if goal.forest.has_cuts() {
        return on_own_forest(goal, mode, limits, &mut stop, |own, stop| {
            prove_goal(Goal::conclusion(own), mode, options, limits, stop)
        });
    }
    // The search holds the input as long as it runs, so the bound counts
    // the input too.
    let account = memory::Account::holding(limits.memory_bytes, goal.forest.held_bytes() as u64);
    let work = Work::new(limits.work);
    decide_goal(goal, mode, options, limits, &account, &work, &mut stop)
}

/// Decides a goal as [`prove_goal`] does, on at most `threads` threads,
/// the calling one counted.
///
/// From three threads, one search starts on the calling thread. Once
/// `add_pool` returns true at one of its polls, a pool of the other
/// `threads − 1` threads starts the search afresh beside it. The first to
/// decide answers and stops the other. Both draw on one memory bound and
/// one bound on work. The single search goes on beside the pool, since a
/// pool may search worse than one thread.
///
/// Below three threads, in an ordered mode, or for an engine that
/// searches on one thread ([`Engine::parallel`]), it runs one search on
/// `threads` threads, and `add_pool` is never asked. With two threads,
/// that is a pool of two from the start.
///
/// The single search runs on the calling thread, whose stack must hold
/// the recursion ([`Limits::stack_bytes`]). `add_pool` is told the single
/// search's progress, so a front end decides with its own clock when to
/// add the pool. Both searches ask `stop`, from two threads. The outcome
/// is the deciding search's, with both searches' counters
/// ([`Statistics::add`]).
///
/// Needs the cargo feature `parallel` (off by default).
///
/// # Errors
///
/// Those of [`prove_goal`], and [`Error::ThreadPool`] when the pool's
/// threads cannot start.
#[cfg(feature = "parallel")]
pub fn race(
    goal: Goal<'_>,
    mode: Mode,
    options: &Options,
    limits: &Limits,
    threads: usize,
    mut add_pool: impl FnMut(Progress) -> bool,
    stop: impl Fn(Progress) -> bool + Sync,
) -> Result<Outcome, Error> {
    use std::sync::atomic::{AtomicBool, Ordering};
    if goal.forest.has_cuts() {
        // One instance of the function, whatever the stop's type.
        let stop: &(dyn Fn(Progress) -> bool + Sync) = &stop;
        return on_own_forest(goal, mode, limits, &mut |p| stop(p), |own, _| {
            race(
                Goal::conclusion(own),
                mode,
                options,
                limits,
                threads,
                add_pool,
                stop,
            )
        });
    }
    let threads = threads.clamp(1, Options::MAX_JOBS);
    let whole = std::sync::Arc::new(memory::Account::holding(
        limits.memory_bytes,
        goal.forest.held_bytes() as u64,
    ));
    let work = Work::new(limits.work);
    if threads < 3 || mode.is_ordered() || !engine_for(goal, mode, options)?.parallel() {
        let options = options.clone().with_jobs(threads);
        let account = memory::Account::part_of(&whole);
        return decide_goal(goal, mode, &options, limits, &account, &work, &mut |p| {
            stop(p)
        });
    }
    let decided = AtomicBool::new(false);
    let settled = |answered: &Result<Answered<'_>, Error>| matches!(answered, Ok(a) if a.answer.result.is_ok());
    let (single, pooled) = (
        options.clone().with_jobs(1),
        options.clone().with_jobs(threads - 1),
    );
    let answered = std::thread::scope(|scope| {
        let (whole, work, stop, decided) = (&whole, &work, &stop, &decided);
        let pooled = &pooled;
        let mut pool = None;
        let account = memory::Account::part_of(whole);
        // A panic on either side stops the other, which the scope waits for.
        let _raise = parallel::RaiseOnPanic(decided);
        let first = answer_goal(
            goal,
            mode,
            &single,
            limits,
            &account,
            work,
            &mut |progress| {
                if pool.is_none() && add_pool(progress) {
                    // A pool whose thread cannot start leaves the single
                    // search alone.
                    pool = Some(
                        std::thread::Builder::new()
                            .name("deduxit-race".into())
                            .stack_size(limits.stack_bytes())
                            .spawn_scoped(scope, move || {
                                let _raise = parallel::RaiseOnPanic(decided);
                                let account = memory::Account::part_of(whole);
                                let answered = answer_goal(
                                    goal,
                                    mode,
                                    pooled,
                                    limits,
                                    &account,
                                    work,
                                    &mut |p| stop(p) || decided.load(Ordering::Relaxed),
                                );
                                if settled(&answered) {
                                    decided.store(true, Ordering::Relaxed);
                                }
                                answered
                            })
                            .ok(),
                    );
                }
                stop(progress) || decided.load(Ordering::Relaxed)
            },
        );
        if settled(&first) {
            decided.store(true, Ordering::Relaxed);
        }
        let Some(Some(handle)) = pool else {
            return first;
        };
        let second = handle
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
        // A decision of either side answers, whatever the other ended
        // with (a pool that could not start its threads, say). Without
        // one, an error of either side answers.
        let (mut answered, other) = match (first, second) {
            (first, second) if settled(&first) => (first?, second.ok()),
            (first, second) if settled(&second) => (second?, first.ok()),
            (first, second) => (second?, Some(first?)),
        };
        if let Some(other) = other {
            answered.answer.statistics.add(&other.answer.statistics);
        }
        answered.answer.statistics.work = work.done();
        Ok(answered)
    })?;
    // Both sides have ended, so the verdict's check or refutation has
    // what the bound leaves beside the input.
    let account = memory::Account::part_of(&whole);
    answered.concluded(goal, options, limits, &account, &mut |p| stop(p))
}

/// Decides a goal as [`prove_goal`] does, charging what the search holds
/// to `account` and counting its work in `work`.
fn decide_goal(
    goal: Goal<'_>,
    mode: Mode,
    options: &Options,
    limits: &Limits,
    account: &memory::Account,
    work: &Work,
    stop: &mut impl FnMut(Progress) -> bool,
) -> Result<Outcome, Error> {
    answer_goal(goal, mode, options, limits, account, work, stop)?
        .concluded(goal, options, limits, account, stop)
}

/// What a search of a goal answered, before the verdict is made of it:
/// the engine's answer, and the goal's occurrences, fragment, mode and
/// engine.
struct Answered<'a> {
    /// The engine's answer, with the counters.
    answer: Answer,
    /// The goal's occurrences, as the engine was handed them.
    occurrences: std::borrow::Cow<'a, [OccId]>,
    /// The fragment searched in.
    fragment: Fragment,
    /// The mode.
    mode: Mode,
    /// The engine that ran.
    engine: Engine,
}

impl Answered<'_> {
    /// Makes the verdict of the answer ([`conclude`]) and returns the
    /// outcome. The verdict's check or refutation draws on `account` too.
    fn concluded(
        self,
        goal: Goal<'_>,
        options: &Options,
        limits: &Limits,
        account: &memory::Account,
        stop: &mut dyn FnMut(Progress) -> bool,
    ) -> Result<Outcome, Error> {
        let Self {
            answer,
            occurrences,
            fragment,
            mode,
            engine,
        } = self;
        let verdict = conclude(
            answer.result,
            answer.refutation,
            Concluding {
                forest: goal.forest,
                occurrences: &occurrences,
                fragment,
                mode,
                roots: goal.conclusion,
            },
            goal.members,
            options,
            limits,
            account,
            stop,
        )?;
        let checked = options.check && matches!(verdict, Verdict::Proved(_));
        Ok(Outcome {
            verdict,
            fragment,
            mode,
            engine,
            statistics: answer.statistics,
            net: answer.net.map(Box::new),
            checked,
        })
    }
}

/// Searches a goal as [`decide_goal`] does, and returns what the engine
/// answered without making the verdict of it.
///
/// A race makes the verdict once both of its searches have ended.
fn answer_goal<'a>(
    goal: Goal<'a>,
    mode: Mode,
    options: &Options,
    limits: &Limits,
    account: &memory::Account,
    work: &Work,
    stop: &mut impl FnMut(Progress) -> bool,
) -> Result<Answered<'a>, Error> {
    let forest = goal.forest;
    let occurrences = goal.occurrences();
    let fragment = fragment_of(forest, &occurrences, options)?;
    let reading = read(forest, mode)?;
    let mut held = memory::Charged::new(account);
    held.charge(reading.as_ref().map_or(0, Reading::held_bytes));
    let (task, engine) = prepare(
        goal,
        &occurrences,
        mode,
        fragment,
        options,
        reading.as_ref(),
    )?;
    let implementation = engine.implementation();
    // The inverse method's turns beside the engine. `due` is the search's
    // work, the turns' included, at which the next turn is due.
    let (head_start, share) = turn_bounds();
    let mut due = head_start;
    let turns = std::cell::RefCell::new(Turns {
        spent: 0,
        asked: false,
        share,
        answer: None,
    });
    // Every poll on this thread counts its units of work. It tells the
    // caller's stop those units and the units of every thread of the
    // search. Past the bound on work, the search ends. Where other threads
    // read the shared count, this one adds its units to it in batches.
    let mut mine = Counted::new(work);
    // The fragment, the reading and the dispatch were passes over the
    // forest, so the caller's condition is asked before the engine polls.
    if set_up_stopped(forest, &mut |units| poll(&mut mine, &mut *stop, units).0) {
        // This thread has done no work yet. So either another thread's
        // work passed the bound, or the caller stopped.
        let reason = if work.passed() {
            Reason::WorkLimit {
                limit: work.limit(),
            }
        } else {
            Reason::Stopped
        };
        return Ok(Answered {
            answer: Answer {
                result: Err(reason),
                statistics: Statistics::default(),
                net: None,
                refutation: None,
            },
            occurrences,
            fragment,
            mode,
            engine,
        });
    }
    // No more threads than the machine runs at once. `held` is what the
    // account holds before the engine runs, which a handover rewinds to.
    #[cfg(feature = "parallel")]
    let options = &options
        .clone()
        .with_jobs(parallel::threads(options.threads()));
    let held = account.used();
    let mut answer = if probes(&task, options) {
        // A turn comes only at a poll of the engine's own work on this
        // thread. While a second thread of the default bias has its turn,
        // this one polls without units and waits. A search whose row gives
        // no turn polls without the comparison: on every poll it costs some
        // instructions, a quarter of a percent of a focused search.
        implementation.decide(&task, options, limits, account, work, &mut |units| {
            let (stopped, done) = poll(&mut mine, &mut *stop, units);
            if stopped || done < due || units == 0 {
                return stopped;
            }
            let (ended, next) = turns.borrow_mut().take(
                done,
                &task,
                options,
                limits,
                account,
                work,
                &mut mine,
                &mut |progress| stop(progress),
            );
            due = next;
            ended
        })?
    } else {
        implementation.decide(&task, options, limits, account, work, &mut |units| {
            poll(&mut mine, &mut *stop, units).0
        })?
    };
    let probe = turns.borrow_mut().answer.take();
    let engine = if let Some(probe) = probe {
        // The engine stopped at the poll at which the inverse method
        // decided. The turn's answer and counters replace the engine's, as
        // at a handover.
        drop(answer);
        answer = probe?;
        Engine::Inverse
    } else if engine != Engine::Net && handed_over(options, &task, &answer) {
        let mut taker = if matches!(answer.result, Err(Reason::MemoryLimit { .. }))
            && !task.mode.is_intuitionistic()
            && !task.mode.has_mix()
            && Engine::Inverse.implementation().admits(&task).is_ok()
        {
            Engine::Inverse
        } else {
            Engine::Net
        };
        loop {
            account.rewind(held);
            answer = taker.implementation().decide(
                &task,
                options,
                limits,
                account,
                work,
                &mut |units| poll(&mut mine, &mut *stop, units).0,
            )?;
            // The inverse method's own bound leaves the goal to the net
            // engine, which holds less.
            if taker == Engine::Net
                || !matches!(
                    answer.result,
                    Err(Reason::MemoryLimit { .. } | Reason::IndexLimit)
                )
            {
                break taker;
            }
            taker = Engine::Net;
        }
    } else {
        engine
    };
    drop(mine);
    answer.statistics.work = work.done();
    if work.passed() && matches!(answer.result, Err(Reason::Stopped)) {
        answer.result = Err(Reason::WorkLimit {
            limit: work.limit(),
        });
    }
    drop(task);
    Ok(Answered {
        answer,
        occurrences,
        fragment,
        mode,
        engine,
    })
}

/// Counts a poll's units in `mine` and asks the caller's `stop`. Returns
/// whether the search ends, and the search's units in all.
///
/// The caller is told the poll that passes the bound on work too.
fn poll(
    mine: &mut Counted<'_>,
    stop: &mut impl FnMut(Progress) -> bool,
    units: u64,
) -> (bool, u64) {
    let done = mine.add(units);
    let stopped = stop(Progress::new(Phase::Search, units, done));
    (stopped || mine.passed(), done)
}

/// Returns whether another engine takes over a goal on which the
/// dispatch's engine ended at its recursion limit or memory bound.
///
/// It does when no engine is forced, and the goal is unit-free MLL, the
/// roots, in a mode without weakening, with a forced linking
/// ([`one_linking`]). The focused engines recurse once per stable
/// sequent and keep a memo. So a long chain of links reaches the
/// recursion limit, and a wide enough sequent the memory bound.
///
/// Which engine takes over:
/// - after the recursion limit, the net engine. It does not recurse, and
///   on a chain it is twice as fast as the inverse method;
/// - after the memory bound in classical mode without Mix, the inverse
///   method. It is three to four times as fast as the net engine on a
///   wide sequent there. Where it meets a bound of its own, the net
///   engine takes over after it;
/// - elsewhere, the net engine. Under Mix, the inverse method ran past a
///   minute where the net engine proved the same wide sequent.
///
/// What the searches before left charged is given back first, so the
/// proof is checked under the bound as if its engine had run alone. The
/// last answer replaces the ones before, and drops their counters (in a
/// race the other search's are added, as always). The work counted is
/// every search's, each in its engine's unit.
fn handed_over(options: &Options, task: &Task<'_>, answer: &Answer) -> bool {
    options.engine.is_none()
        && matches!(
            answer.result,
            Err(Reason::RecursionLimit { .. } | Reason::MemoryLimit { .. })
        )
        && Engine::Net.implementation().admits(task).is_ok()
        && one_linking(task.forest)
}

/// Returns whether every atom of the forest occurs at most once with each
/// sign, so that its axiom linking is the only one.
///
/// The net engine's search then makes one link per pair and backtracks
/// over none. Each link costs a scan of the atoms and a test of the
/// criterion, so the search is quadratic in all. On equal literals its
/// search is exponential: taking over a goal on which a focused engine
/// met its limit would trade a quick "unknown" for a search without end.
fn one_linking(forest: &Forest) -> bool {
    use crate::linear::occurrences::Sign;
    (0..forest.sequent().atom_names().len() as u32).all(|a| {
        let atom = crate::linear::sequents::Atom::new(a);
        forest.literals(atom, Sign::Atom).len() <= 1 && forest.literals(atom, Sign::Dual).len() <= 1
    })
}

/// What [`conclude`] reads of the goal an answer is of.
struct Concluding<'a> {
    /// The forest.
    forest: &'a Forest,
    /// The goal's occurrences, as the engine was handed them.
    occurrences: &'a [OccId],
    /// The fragment searched in.
    fragment: Fragment,
    /// The mode.
    mode: Mode,
    /// Whether the goal is the sequent's roots.
    roots: bool,
}

/// Returns the verdict of an engine's answer. This is the one place a
/// verdict is made.
///
/// The verdict is one of:
/// - a proof that passed the checker, which records the goal it
///   concludes and the mode;
/// - an exhausted search, with the engine's refutation or the counts';
/// - why the search stopped.
///
/// No engine is trusted with its own proof. The checker has the last word
/// on every proof, of the sequent or of a goal, in every build. A check
/// that a bound or the stop gave up is no verdict on the proof, so no
/// proof is returned unchecked. The exception is [`Options::check`] off:
/// the proof is then the engine's word, and `Outcome::checked` says so.
///
/// The check of a proof and the refutation hold their memory on
/// `account`, beside what it holds, within the same bound as the search.
/// The check of a saturated set or a basis holds its own memory outside
/// it. That is of the order of the set, which the search held within the
/// bound.
///
/// # Errors
///
/// [`Error::Rejected`] for a proof the checker rejects, and
/// [`Error::Refutation`] for a saturated set or a basis its check
/// refuses: defects.
#[expect(
    clippy::too_many_arguments,
    reason = "the answer, the goal, and the settings of the search it came from"
)]
fn conclude(
    result: Result<Option<Proof>, Reason>,
    refutation: Option<Refutation>,
    goal: Concluding<'_>,
    members: &[Member],
    options: &Options,
    limits: &Limits,
    account: &memory::Account,
    stop: &mut dyn FnMut(Progress) -> bool,
) -> Result<Verdict, Error> {
    let (forest, mode) = (goal.forest, goal.mode);
    let verdict = match result {
        Ok(Some(proof)) if goal.roots => Verdict::Proved(Box::new(proof.with_mode(mode))),
        Ok(Some(proof)) => {
            Verdict::Proved(Box::new(proof.concluding(goal.occurrences).with_mode(mode)))
        }
        Ok(None) => {
            // A saturated set and a basis are the refutations of last
            // resort: the counts' and the classical one are smaller and rest
            // on simpler invariants.
            let (refutation, last) = match refutation {
                Some(last @ (Refutation::Saturated(_) | Refutation::Basis(_))) => {
                    (None, Some(last))
                }
                refutation => (refutation, None),
            };
            // Where the engine has no refutation of its own: what the
            // counts of the goal rule out, under the same bound as the
            // search. Failing that, a classical assignment, where one is
            // found.
            let refutation = refutation.unwrap_or_else(|| {
                let mut polled = |_| stop(Progress::new(Phase::Refute, 0, 0));
                focus::counts::refutation(
                    forest,
                    goal.occurrences,
                    goal.fragment,
                    mode,
                    account,
                    &mut polled,
                )
            });
            let refutation = match refutation {
                Refutation::Exhausted => classical(&goal, options, account, stop)
                    .map_or(Refutation::Exhausted, Refutation::Classical),
                refutation => refutation,
            };
            let refutation = match (refutation, last) {
                (Refutation::Exhausted, Some(last)) => {
                    // The set or the basis is checked as a proof is, by code
                    // apart from the engine that found it, unless the check
                    // is off, within a work bound of its own, as a proof's
                    // check is.
                    if options.check {
                        let mut done = 0u64;
                        let mut polled = |units: u64| {
                            done = done.saturating_add(units);
                            stop(Progress::new(Phase::Check, units, done))
                                || limits.work.is_some_and(|limit| done > limit)
                        };
                        let checked = match &last {
                            Refutation::Saturated(set) => {
                                saturated::check(forest, goal.occurrences, mode, set, &mut polled)
                                    .map_err(|failed| match failed {
                                        saturated::Failed::Stopped => None,
                                        saturated::Failed::Fault(fault) => Some(fault),
                                    })
                            }
                            Refutation::Basis(basis) => {
                                basis::check(forest, goal.occurrences, basis, &mut polled).map_err(
                                    |failed| match failed {
                                        basis::Failed::Stopped => None,
                                        basis::Failed::Fault(fault) => Some(fault),
                                    },
                                )
                            }
                            _ => unreachable!("only a set or a basis is kept for last"),
                        };
                        match checked {
                            Ok(()) => {}
                            Err(None) => {
                                return Ok(Verdict::Unknown(match limits.work {
                                    Some(limit) if done > limit => Reason::WorkLimit { limit },
                                    _ => Reason::Stopped,
                                }));
                            }
                            Err(Some(fault)) => return Err(Error::Refutation(fault)),
                        }
                    }
                    last
                }
                (refutation, _) => refutation,
            };
            unprovable(forest, mode, refutation, &goal, members)
        }
        // A search that did not decide is unprovable where an assignment
        // makes the classical reading false. Otherwise it stays as it
        // ended.
        Err(reason) => match classical(&goal, options, account, stop) {
            Some(assignment) => unprovable(
                forest,
                mode,
                Refutation::Classical(assignment),
                &goal,
                members,
            ),
            None => Verdict::Unknown(reason),
        },
    };
    let Verdict::Proved(proof) = &verdict else {
        return Ok(verdict);
    };
    if !options.check {
        debug_assert_eq!(proof.check(mode), Ok(()), "an engine's proof");
        return Ok(verdict);
    }
    // The check gets what the bound leaves beside the input. A refusal
    // names the option's bound.
    let left = (*limits).with_memory_bytes(account.left());
    match proof.check_within(mode, &left, stop) {
        Ok(()) => Ok(verdict),
        Err(e @ CheckError::Invalid(_)) => Err(Error::Rejected(Box::new(e))),
        Err(CheckError::Refused(refused)) => {
            Ok(Verdict::Unknown(unchecked(refused.refusal, limits)?))
        }
    }
}

/// Returns the verdict that the goal is unprovable for `refutation`.
fn unprovable(
    forest: &Forest,
    mode: Mode,
    refutation: Refutation,
    goal: &Concluding<'_>,
    members: &[Member],
) -> Verdict {
    let disproof = Disproof::new(forest.sequent().clone(), mode, refutation);
    Verdict::Unprovable(Box::new(if goal.roots {
        disproof
    } else {
        disproof.of_goal(members.into())
    }))
}

/// Returns an assignment that makes the classical reading of the goal
/// false, or `None` where none is found.
///
/// The search for it runs within [`Options::classical_work`] and what the
/// memory bound leaves, and its polls ask `stop`.
fn classical(
    goal: &Concluding<'_>,
    options: &Options,
    account: &memory::Account,
    stop: &mut dyn FnMut(Progress) -> bool,
) -> Option<Classical> {
    classical::refute(
        goal.forest,
        goal.occurrences,
        options.classical_work,
        account,
        stop,
    )
}

/// Returns why a search whose proof's check was given up is unknown: the
/// stop, the work bound, or the memory bound of `limits` the check would
/// have passed.
///
/// # Errors
///
/// A refusal that no check makes stays the error it is.
fn unchecked(refusal: Refusal, limits: &Limits) -> Result<Reason, Error> {
    match refusal {
        Refusal::Stopped { .. } => Ok(Reason::Stopped),
        Refusal::Memory { limit_bytes, .. } => Ok(Reason::Unchecked {
            limit_bytes: limits.memory_bytes.unwrap_or(limit_bytes),
        }),
        Refusal::Work { limit } => Ok(Reason::WorkLimit { limit }),
        refusal => Err(Error::Refused(refusal)),
    }
}

/// Returns the engine [`prove_goal`] runs on a goal under the options:
/// the one they force, or the one the dispatch picks.
///
/// It costs what `prove_goal` does before it searches: a pass over the
/// goal for its fragment, in intuitionistic mode the reading of the
/// forest, and the dispatch's test of the goal's shape. A front end asks
/// it to say which engine will run. `race` (feature `parallel`) asks it
/// before it adds a pool beside a single thread, since an engine that
/// runs on one thread ([`Engine::parallel`]) would only search again.
///
/// # Errors
///
/// Those of [`prove_goal`] that come before the search.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Engine, Goal, Options, engine_for};
/// use deduxit::linear::{Forest, Mode, Sequent};
///
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let forest = Forest::new(&sequent)?;
/// let goal = Goal::conclusion(&forest);
/// let options = Options::default();
/// assert_eq!(engine_for(goal, Mode::CLASSICAL, &options)?, Engine::Focus);
/// assert_eq!(engine_for(goal, Mode::INTUITIONISTIC, &options)?, Engine::TwoSided);
/// # Ok::<(), deduxit::Error>(())
/// ```
pub fn engine_for(goal: Goal<'_>, mode: Mode, options: &Options) -> Result<Engine, Error> {
    let occurrences = goal.occurrences();
    let fragment = fragment_of(goal.forest, &occurrences, options)?;
    let reading = read(goal.forest, mode)?;
    prepare(
        goal,
        &occurrences,
        mode,
        fragment,
        options,
        reading.as_ref(),
    )
    .map(|(_, engine)| engine)
}

/// Returns the fragment a goal is searched in: the one the options
/// assert, or else the goal's own.
///
/// # Errors
///
/// [`Error::FragmentMismatch`] when the goal is outside the asserted
/// fragment.
fn fragment_of(forest: &Forest, goal: &[OccId], options: &Options) -> Result<Fragment, Error> {
    let detected = goal_fragment(forest, goal);
    match options.fragment {
        Some(asserted) if !asserted.contains(detected) => {
            Err(Error::FragmentMismatch { asserted, detected })
        }
        Some(asserted) => Ok(asserted),
        None => Ok(detected),
    }
}

/// Returns the forest's intuitionistic reading in intuitionistic mode,
/// and `None` in classical mode.
///
/// # Errors
///
/// The mode's own error from [`Mode::check`], and
/// [`Error::NotIntuitionistic`] for a forest with no reading.
fn read(forest: &Forest, mode: Mode) -> Result<Option<Reading<'_>>, Error> {
    mode.check()?;
    if !mode.intuitionistic {
        return Ok(None);
    }
    Reading::of_mode(forest, mode)
        .map(Some)
        .map_err(Error::NotIntuitionistic)
}

/// Returns the task of a goal searched in `fragment`, and the engine that
/// decides it, which admits it.
///
/// # Errors
///
/// [`Error::GoalOutputs`] for an intuitionistic goal without exactly one
/// output under the reading given, [`Error::OrderedFragment`] for an
/// ordered mode beyond unit-free MLL, and [`Error::EngineRefused`] for an
/// engine that does not take the goal. The dispatch's own error where no
/// engine does.
fn prepare<'a>(
    goal: Goal<'a>,
    occurrences: &'a [OccId],
    mode: Mode,
    fragment: Fragment,
    options: &Options,
    reading: Option<&'a Reading<'a>>,
) -> Result<(Task<'a>, Engine), Error> {
    if let Some(reading) = reading {
        let outputs = reading.outputs(occurrences.iter().copied());
        if outputs != 1 {
            return Err(Error::GoalOutputs { count: outputs });
        }
    }
    // The roots in any order are the sequent itself, which the engines
    // are handed in the forest's order.
    let task = Task {
        forest: goal.forest,
        goal: occurrences,
        fragment,
        mode,
        reading,
        roots: goal.conclusion,
        program: OnceLock::new(),
    };
    if mode.is_ordered() && !Fragment::MLL.contains(fragment) {
        return Err(Error::OrderedFragment { fragment, mode });
    }
    let engine = match options.engine {
        Some(Engine::Unknown) => {
            return Err(Error::UnknownName {
                what: "engine",
                name: Engine::Unknown.name().into(),
                known: Engine::NAMES,
            });
        }
        Some(engine) => engine,
        None => dispatch(&task)?,
    };
    // Only the planar searches keep the order of the formulas: the net
    // engine's in the cyclic mode, the essential one's in the Lambek
    // calculus.
    let planar = if mode.intuitionistic {
        Engine::Essential
    } else {
        Engine::Net
    };
    if mode.is_ordered() && engine != planar {
        return Err(Error::EngineRefused {
            engine,
            because: NotTaken::Mode { mode },
        });
    }
    engine.implementation().admits(&task)?;
    Ok((task, engine))
}

/// A goal as the engines are handed it: its occurrences of the forest,
/// the fragment and the mode it is searched in, and in intuitionistic
/// mode the forest's reading.
pub(crate) struct Task<'a> {
    /// The forest.
    pub(crate) forest: &'a Forest,
    /// The goal's occurrences. When the goal is the sequent itself, they
    /// are the roots in the forest's order.
    pub(crate) goal: &'a [OccId],
    /// The fragment searched in: the goal's own, or the one the options
    /// assert.
    pub(crate) fragment: Fragment,
    /// The mode.
    pub(crate) mode: Mode,
    /// The intuitionistic reading, in intuitionistic mode.
    pub(crate) reading: Option<&'a Reading<'a>>,
    /// Whether the goal is the sequent's roots.
    pub(crate) roots: bool,
    /// The Horn program the goal is, or `None` when it is none.
    ///
    /// The first to ask reads it: the dispatch's feature, the Horn
    /// engine's `admits` or its search. So a goal is read once.
    program: OnceLock<Option<horn::Program>>,
}

/// What a search that keeps its proofs in an arena ended with: the
/// result, the arena, the counters and, for a first-order proof, its
/// instance table.
pub(crate) struct Finished {
    /// The node proving the goal, `None` for an unprovable goal, or why
    /// the search stopped.
    pub(crate) result: Result<Option<NodeId>, Reason>,
    /// The arena the node lives in.
    pub(crate) nodes: Vec<Node>,
    /// The counters.
    pub(crate) statistics: Statistics,
    /// The instance table of a first-order proof, whose members and
    /// witnesses the arena's nodes name; `None` for a propositional one.
    pub(crate) instances: Option<Box<crate::linear::Instances>>,
}

impl Finished {
    /// Returns the end of a search that gave up for `reason` before it
    /// found anything.
    pub(crate) fn gave_up(reason: Reason) -> Self {
        Self {
            result: Err(reason),
            nodes: Vec::new(),
            statistics: Statistics::default(),
            instances: None,
        }
    }
}

/// What an engine's search ended with: the result, its counters, the
/// proof net the net engine read its proof off, and the engine's own
/// refutation.
pub(crate) struct Answer {
    /// The proof, `None` for an unprovable goal, or why the search
    /// stopped.
    pub(crate) result: Result<Option<Proof>, Reason>,
    /// The counters.
    pub(crate) statistics: Statistics,
    /// The net found, from the net engine.
    pub(crate) net: Option<ProofStructure>,
    /// For an unprovable goal, why it is unprovable, where the engine
    /// knows more than that its search was exhaustive.
    pub(crate) refutation: Option<Refutation>,
}

impl Answer {
    /// Returns the answer of an engine that keeps its proofs as nodes of
    /// an arena.
    ///
    /// The proof is built in the arena's own vector. The build asks
    /// `stop` as it goes, and a stop there ends it as a stop of the
    /// search does.
    pub(crate) fn of_arena(
        forest: &Forest,
        Finished {
            result,
            nodes,
            statistics,
            instances,
        }: Finished,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Self {
        let result = result.and_then(|root| {
            root.map(|root| match instances {
                // A table that the proof's ids no longer number has run
                // past its indices.
                Some(table) => Proof::with_instances(forest.clone(), *table, nodes, root)
                    .map_err(|_| Reason::IndexLimit),
                None => {
                    Proof::build(forest.clone(), nodes, root, &mut || stop(0)).map_err(
                        |e| match e {
                            Error::Refused(Refusal::Stopped { .. }) => Reason::Stopped,
                            e => panic!("the engine pushes premises before conclusions: {e}"),
                        },
                    )
                }
            })
            .transpose()
        });
        Self {
            result,
            statistics,
            net: None,
            refutation: None,
        }
    }
}

/// What every engine implements: which goals it takes, and how it decides
/// one.
///
/// An engine reads the options its variant of [`Engine`] names, and no
/// others.
pub(crate) trait Decide {
    /// Refuses a goal the engine does not decide.
    ///
    /// # Errors
    ///
    /// The error the options get when they force the engine there:
    /// [`Error::EngineRefused`] with the [`NotTaken`] that says why.
    fn admits(&self, task: &Task<'_>) -> Result<(), Error>;

    /// Decides the goal under the options, and returns the engine's
    /// answer.
    ///
    /// It polls `stop` with the units of work done since the last poll,
    /// which `work` adds up for every thread of the search. It charges
    /// what the search holds to `account`.
    ///
    /// # Errors
    ///
    /// [`Error::ThreadPool`] when the threads of a parallel search cannot
    /// start.
    fn decide(
        &self,
        task: &Task<'_>,
        options: &Options,
        limits: &Limits,
        account: &memory::Account,
        work: &Work,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Result<Answer, Error>;
}

/// Returns the engine the dispatch picks for a goal: that of the first
/// row of [`DISPATCH`] that takes it.
///
/// # Errors
///
/// [`Error::NoEngine`] when no row takes the goal, which only a mode or a
/// fragment that no row names would meet.
fn dispatch(task: &Task<'_>) -> Result<Engine, Error> {
    DISPATCH
        .iter()
        .find(|row| row.takes(task))
        .map(|row| row.engine)
        .ok_or(Error::NoEngine {
            fragment: task.fragment,
            mode: task.mode,
        })
}

/// Returns whether the inverse method takes turns beside the engine of a
/// search.
///
/// It does when the dispatch's row says so ([`Row::probe`]), no engine is
/// forced, the search runs on one thread, and the inverse method admits
/// the goal. So a race's pool searches without turns.
fn probes(task: &Task<'_>, options: &Options) -> bool {
    #[cfg(feature = "parallel")]
    let alone = options.threads() == 1;
    #[cfg(not(feature = "parallel"))]
    let alone = true;
    alone
        && options.engine.is_none()
        && DISPATCH
            .iter()
            .find(|row| row.takes(task))
            .is_some_and(|row| row.probe)
        && Engine::Inverse.implementation().admits(task).is_ok()
}

/// The dispatch, read from the first row down. For each fragment, mode
/// and feature of a goal, it names the engine a measurement shows fastest
/// there. The documentation of [`Engine`] tabulates the rows with the
/// measurements. The last two rows take every goal, each in its own
/// modes.
const DISPATCH: [Row; 8] = [
    Row {
        fragment: Fragment::MLL,
        modes: Modes::Lambek,
        feature: Feature::Any,
        engine: Engine::Essential,
        probe: false,
    },
    Row {
        fragment: Fragment::MLL,
        modes: Modes::Cyclic,
        feature: Feature::Any,
        engine: Engine::Net,
        probe: false,
    },
    Row {
        fragment: Fragment::ADDITIVE,
        modes: Modes::Any,
        feature: Feature::TwoFormulas,
        engine: Engine::Additive,
        probe: false,
    },
    Row {
        fragment: Fragment::MELL,
        modes: Modes::Any,
        feature: Feature::PetriNet,
        engine: Engine::Horn,
        probe: false,
    },
    Row {
        fragment: Fragment::LL1,
        modes: Modes::Intuitionistic,
        feature: Feature::Exponentials,
        engine: Engine::TwoSided,
        probe: true,
    },
    Row {
        fragment: Fragment::LL1,
        modes: Modes::Intuitionistic,
        feature: Feature::Any,
        engine: Engine::TwoSided,
        probe: false,
    },
    Row {
        fragment: Fragment::LL1,
        modes: Modes::Mix,
        feature: Feature::Any,
        engine: Engine::Focus,
        probe: true,
    },
    Row {
        fragment: Fragment::LL1,
        modes: Modes::Classical,
        feature: Feature::Any,
        engine: Engine::Focus,
        probe: false,
    },
];

/// The work a row's engine does alone before the inverse method takes its
/// first turn beside it, where the row gives turns ([`Row::probe`]).
///
/// It is in the dispatched engine's units, with every thread of the
/// search counted but the turns. On the intuitionistic rows measured, it
/// is some hundredths of a second. A goal decided within it is decided as
/// without the turns.
const PROBE_AFTER: u64 = 1 << 24;

/// The share of the engine's own work that a turn of the inverse method
/// may do: a turn does at most the engine's work over this, in the
/// inverse method's units.
///
/// A turn comes each time the engine's work has doubled, and starts
/// afresh. So the turns together do at most a sixteenth of the engine's
/// work. A share of 16 makes the turns an eighth, which takes a row the
/// engine proves in 54 s of a 60 s limit past the limit.
const TURN_SHARE: u64 = 32;

#[cfg(test)]
thread_local! {
    /// The head start and the turns' share on a test's thread. A test may
    /// set them other than [`PROBE_AFTER`] and [`TURN_SHARE`], to see
    /// turns on small goals. A share of 0 lets a turn run to its end.
    static TURN: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((PROBE_AFTER, TURN_SHARE)) };
}

/// Returns the head start before the inverse method's first turn and the
/// share of the engine's work a turn may do: [`PROBE_AFTER`] and
/// [`TURN_SHARE`], or in a test what its thread set.
fn turn_bounds() -> (u64, u64) {
    #[cfg(test)]
    {
        TURN.with(std::cell::Cell::get)
    }
    #[cfg(not(test))]
    {
        (PROBE_AFTER, TURN_SHARE)
    }
}

/// The inverse method's turns beside an engine's search ([`Row::probe`]).
///
/// A turn comes each time the engine's own work has doubled past the head
/// start. Each turn runs the inverse method from its start, and does at
/// most a share of that work. So the turns together do at most twice the
/// last one's share.
struct Turns {
    /// The work the turns did.
    spent: u64,
    /// Whether the row was asked whether it gives turns.
    asked: bool,
    /// The share of the engine's work a turn may do: [`TURN_SHARE`], or a
    /// test's (0 lets a turn run to its end).
    share: u64,
    /// What the turn that decided answered, or `None` while none has.
    answer: Option<Result<Answer, Error>>,
}

impl Turns {
    /// Takes the turn due when the search has done `done` units, the
    /// turns' included.
    ///
    /// On the first turn it asks whether the row gives turns. Then it runs
    /// the inverse method on the task within its share. It counts the
    /// turn's work in `mine`, and asks `stop` and the bound on work at the
    /// turn's polls.
    ///
    /// Returns whether the engine must stop, and the work at which the
    /// next turn is due. The engine must stop when the turn decided (the
    /// turn's answer is kept), or the caller's stop or the bound on work
    /// fired. No turn is due (`u64::MAX`) when the row gives none, or when
    /// the turn met the memory bound or an index limit, which a longer
    /// turn would meet sooner.
    ///
    /// It is kept apart from the poll, which it leaves one comparison.
    /// Inlined there, it makes every poll some seven instructions dearer.
    #[cold]
    #[inline(never)]
    #[expect(
        clippy::too_many_arguments,
        reason = "the search's task, settings, account, work and stop, which the turn shares"
    )]
    fn take(
        &mut self,
        done: u64,
        task: &Task<'_>,
        options: &Options,
        limits: &Limits,
        account: &memory::Account,
        work: &Work,
        mine: &mut Counted<'_>,
        stop: &mut dyn FnMut(Progress) -> bool,
    ) -> (bool, u64) {
        if !self.asked {
            self.asked = true;
            if !probes(task, options) {
                return (false, u64::MAX);
            }
        }
        let own = done.saturating_sub(self.spent);
        let budget = own.checked_div(self.share).unwrap_or(u64::MAX);
        let mut turn = 0u64;
        let mut ended = false;
        let answer = Engine::Inverse.implementation().decide(
            task,
            options,
            limits,
            account,
            work,
            &mut |units| {
                turn = turn.saturating_add(units);
                let done = mine.add(units);
                ended = stop(Progress::new(Phase::Search, units, done)) || mine.passed();
                ended || turn >= budget
            },
        );
        self.spent = self.spent.saturating_add(turn);
        // A decision answers, and so does an error. The caller's stop or
        // the bound on work ends the engine too. Otherwise what the turn
        // kept goes, and the engine goes on.
        let decided = !matches!(answer, Ok(Answer { result: Err(_), .. }));
        let over = matches!(
            answer,
            Ok(Answer {
                result: Err(Reason::MemoryLimit { .. } | Reason::IndexLimit),
                ..
            })
        );
        if decided {
            self.answer = Some(answer);
        }
        let next = if over {
            u64::MAX
        } else {
            own.saturating_mul(2).saturating_add(self.spent)
        };
        (decided || ended, next)
    }
}

/// A row of the dispatch. A goal whose fragment lies within `fragment`,
/// searched in one of `modes`, with `feature`, goes to `engine`.
#[derive(Clone, Copy, Debug)]
struct Row {
    /// The largest fragment the row takes.
    fragment: Fragment,
    /// The modes it takes.
    modes: Modes,
    /// What it asks of a goal besides.
    feature: Feature,
    /// The engine its goals go to.
    engine: Engine,
    /// Whether the inverse method takes turns beside the engine.
    ///
    /// The first turn comes once the engine has done [`PROBE_AFTER`] units
    /// of work without deciding, and another each time its work has
    /// doubled. Each turn runs the inverse method from its start, on the
    /// thread that polls. It does at most a [`TURN_SHARE`]th of that work,
    /// in the inverse method's units. Then the engine goes on where it
    /// stopped. Where a turn decides first, its answer is the search's.
    probe: bool,
}

impl Row {
    /// Returns whether the row takes the goal.
    fn takes(&self, task: &Task<'_>) -> bool {
        self.fragment.contains(task.fragment) && self.modes.take(task.mode) && self.feature.of(task)
    }
}

/// The modes a row of the dispatch takes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Modes {
    /// Every commutative mode.
    Any,
    /// Classical mode, with or without weakening and Mix.
    Classical,
    /// Intuitionistic mode, with or without weakening.
    Intuitionistic,
    /// Classical mode with Mix, without weakening.
    Mix,
    /// The classical mode that keeps the order of the formulas.
    Cyclic,
    /// The intuitionistic modes that keep it: the Lambek calculus, with
    /// or without empty antecedents.
    Lambek,
}

impl Modes {
    /// Returns whether a mode is one of these.
    fn take(self, mode: Mode) -> bool {
        #[expect(
            clippy::unneeded_field_pattern,
            reason = "every field named, so that a new one must be placed here"
        )]
        let Mode {
            intuitionistic,
            affine,
            mix,
            order,
            empty_antecedents: _,
        } = mode;
        let commutative = order == Order::Commutative;
        match self {
            Modes::Any => commutative,
            Modes::Classical => commutative && !intuitionistic,
            Modes::Mix => commutative && !intuitionistic && mix && !affine,
            Modes::Intuitionistic => commutative && intuitionistic,
            Modes::Cyclic => !commutative && !intuitionistic,
            Modes::Lambek => !commutative && intuitionistic,
        }
    }
}

/// What a row of the dispatch asks of a goal beyond its fragment and mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Feature {
    /// Nothing more.
    Any,
    /// Exactly two formulas, with an additive connective or unit among
    /// them (two literals are no additive problem).
    TwoFormulas,
    /// A Horn program with a clause under `!`: a Petri net with a marking
    /// to reach.
    PetriNet,
    /// An exponential in the goal.
    Exponentials,
}

impl Feature {
    /// Returns whether the goal has the feature.
    fn of(self, task: &Task<'_>) -> bool {
        match self {
            Feature::Any => true,
            Feature::TwoFormulas => task.goal.len() == 2 && !task.fragment.is_empty(),
            // The options may assert a fragment larger than the goal's, so
            // the fragment test only spares a goal that is no Horn program
            // the reading.
            Feature::PetriNet => task.fragment.has_exponentials() && horn::is_net(task),
            Feature::Exponentials => task.fragment.has_exponentials(),
        }
    }
}

/// Returns the smallest fragment the goal's subformulas lie in: the
/// sequent's own fragment for the roots, and possibly a smaller one for an
/// open goal deeper in the forest.
pub(crate) fn goal_fragment(forest: &Forest, goal: &[OccId]) -> Fragment {
    let mut fragment = Fragment::EMPTY;
    for &o in goal {
        for x in forest.subtree(o) {
            fragment |= forest.kind(x).fragment();
        }
    }
    fragment
}

/// The proof-search engines. An [`Outcome`] names the one that ran, and
/// [`Options::engine`] forces one.
///
/// Each variant describes its engine: how it searches, which options it
/// reads, and its unit of work.
///
/// # Which engine decides a goal
///
/// Unless [`Options::engine`] forces one, a goal goes to the engine of the
/// first row of this table that it fits. A row asks for a fragment the
/// goal lies in (detected, or asserted by [`Options::fragment`]), a mode,
/// and sometimes one more feature. Each row's engine is the one that
/// measured fastest there, or the only one that decides there at all.
///
/// | fragment | mode | feature | engine | measured (one thread) |
/// |---|---|---|---|---|
/// | unit-free MLL | Lambek, with or without empty antecedents | | [`Essential`](Engine::Essential) | the one engine of the Lambek calculus, by planar essential nets: chains `a₀, a₀ \ a₁, … ⊢ aₙ` of 1 024 and 4 096 links in 59 ms and 2.8 s, written with `/` in 23 and 393 ms, products of 4 096 atoms entailing themselves in 0.66 s, the exchanged and reversed forms refuted in 88 and 159 ms; 20 random derivations of the calculus over two atoms all proved in at most 4.7 ms (9.8 ms in all) and their exchanged forms decided in at most 0.4 ms, where the classical net search on the same one-sided sequents ran past 60 s on 8 of 20 and the focused engine took up to 3.5 s; without empty antecedents the products `x ⊢ x ⊗ ((a₀ \ a₀) ⊗ …)` of 16 to 256 factors refuted in 14 to 81 ms, with them proved in under 3 ms (`bench/problems/lambek.txt`) |
/// | unit-free MLL | cyclic | | [`Net`](Engine::Net) | the one engine that keeps the order, by planar linkings: chains `a₀, a₀ ⊸ a₁, … ⊢ aₙ` of 4 096 links in 0.46 s and products of 4 096 atoms entailing themselves in 0.89 s, as fast as the classical net search on the same sequents, which links them alike; their exchanged forms refuted in 0.08 and 0.16 s; random derivations of the cyclic calculus over two atoms decided in 23 µs to 0.4 ms, where the classical net search on the same sequents ran past 60 s on 2 of 20 (`bench/problems/cyclic.txt`) |
/// | additives only | any | two formulas, an additive connective or unit among them | [`Additive`](Engine::Additive) | `A ⊢ A` for `A` a complete tree of `&` and `⊕`: depth 8 in 0.5 ms against 1.4 ms on the focused engine, depth 14 in 0.1 to 0.2 s against 2.7 s, depth 16 in 0.3 s against over 20 s, in either mode |
/// | MELL | any, classical or intuitionistic, with or without Mix | a Horn program with a clause under `!`: a Petri net | [`Horn`](Engine::Horn) | in affine mode, the 176 coverability problems of the qcover suite at 5 s, intuitionistic: decides 162 (59 provable, 103 not, 155 within a second) where the two-sided engine decides 8, no verdict against another and every proof checked; 10 464 random affine Horn programs of one to four atoms and clauses, classical and intuitionistic: decides all, at most 0.2 ms each, where the focused engines leave 886 undecided at 1 s and are slower by more than a millisecond on 467. In linear mode, the library's 3 137 Petri nets at 5 s, intuitionistic, against the forward focused search (the factor bias within 30 copies, the better of the focused engine's two searches there): decides 3 026 nets against 1 628 (1 400 only by the Horn engine, 2 only by the forward search, no verdict against the other), in 0.23 ms against 1.2 ms in the median of the 1 626 both decide, faster on 1 013 of them; 2 670 within 10 ms against 1 103; the counter with 64 tokens proved in 0.07 ms and with the unreachable goal refuted in 0.6 ms, where the focused engine reaches its limit after 10 s; with the state equation, the dead transitions dropped and the backward search beside it, 3 071 of the nets; and of 7 000 random programs near the Horn shape it decides 4 303 of the 4 318 each linear mode sends it at 1 s, every one the focused engines decide and 548 to 580 more. Horn programs without `!` stay with the focused engines, whose counts decide the Partition encodings up to a hundred times faster (12 items: 15 ms against 2.0 s) |
/// | any, quantifiers too | intuitionistic | an exponential | [`TwoSided`](Engine::TwoSided), and a turn of [`Inverse`](Engine::Inverse) beside it | the inverse method refuses quantifiers, so a first-order goal is the two-sided engine's alone; where the two-sided engine alone ends at the time limit: on the library's intuitionistic problems at 60 s, one thread (the held-out sets, the rows no tool decided at 10 s, Sympli's ten proofs and six refutations; 1 113 rows), the turns decide 102 rows the two-sided engine alone does not and lose none, all ten proofs in 0.17 to 0.29 s and the six refutations in 0.15 to 22.8 s, with no verdict against another; the time with the turns over the time without is 1.00 in the median at every speed of the engine alone, at worst 1.24 from 10 ms to 1 s, 1.11 from 1 to 10 s and 1.42 over 10 s. The inverse method alone, which loses 20 rows the two-sided engine decides (the pigeonhole formulas `SYJ201` and `SYJ206`, `SYJ207`, `SYJ212`), gets no row of its own |
/// | any, quantifiers too | intuitionistic | | [`TwoSided`](Engine::TwoSided) | the general engine, and the one engine of intuitionistic first-order linear logic, by unification, on one thread or a pool; on unit-free IMLL faster than the net engine wherever both decide: wide (`a₀ ⊗ b₀, … ⊢ (bₙ ⊗ aₙ) ⊗ …`) and curried (`(a₀ ⊗ … ⊗ aₙ) ⊸ c ⊢ a₀ ⊸ (… ⊸ c)`) sequents of 1 024 and 4 096 atoms in 5 to 83 ms against 0.05 to 2.2 s, the Horn encodings of Partition 10 to 10⁴ times faster |
/// | any, quantifiers too | Mix, classical without weakening | | [`Focus`](Engine::Focus), and a turn of [`Inverse`](Engine::Inverse) beside it | the inverse method refuses quantifiers, so a first-order goal is the focused engine's alone; on the family `mix` the inverse method alone refutes every size measured (4 to 11) in at most 0.06 ms, where the focused engine takes 0.46 ms to 9.5 s and leaves sizes 10 and 11 to the classical refuter after 60 s; with the turns, sizes 8 to 11 are refuted in 0.42 to 0.47 s, and 4 and 6 within the head start, as without them. No other Mix sequent was measured, and some that the inverse method leaves undecided for seconds the focused engine decides in milliseconds, within the head start |
/// | any, quantifiers too | classical | | [`Focus`](Engine::Focus) | the general engine, the same on the one-sided sequent, and the one engine of first-order linear logic, by unification, on one thread or a pool; on unit-free MLL, with or without Mix, faster than the net engine wherever both decide: `wide` sequents of 8 to 4 096 literals, each once to four times, 1.07 to 3.6 times faster (`wide-m4` with 2 048: 166 ms against 594 ms), the Horn encodings of Partition and 3-Partition 1.6 to 32 000 times faster (`3-partition-mll-no/8` 37 µs against 2.8 ms) |
///
/// The bias of the focused engines, [`Bias::Auto`], is chosen per goal as
/// well, by the measurements its documentation names. Engines are ordered
/// as [`ALL`](Self::ALL) lists them.
///
/// # When another engine takes over
///
/// The focused engines recurse once per stable sequent and keep a memo.
/// So they may end at their recursion limit or memory bound. When that
/// happens on a unit-free MLL sequent in a mode without weakening, whose
/// atoms each occur once with each sign, the linking is forced, and
/// another engine takes the sequent over:
/// - After the recursion limit, the net engine. It keeps neither a
///   recursion nor a memo, and ends within one pass. On the chain
///   `a₀, a₀ ⊸ a₁, … ⊢ aₙ` of 1 024 and 4 096 links, the two-sided engine
///   meets the recursion limit after 11 and 46 ms. The net engine then
///   proves the chain in 26 ms and 0.43 s more, where the inverse method
///   took 51 ms and 1.0 s.
/// - After the memory bound in classical mode without Mix, the inverse
///   method, and the net engine after it where the inverse method meets a
///   bound of its own. The inverse method proves `wide-m1` with 4 096,
///   8 192 and 16 384 literals in 1.48, 3.05 and 11.8 s, against 3.09,
///   9.48 and 37.4 s by the net engine, and with 32 768 in 49.3 s, where
///   the net engine passes 60 s. Wide sequents shuffled or of triples that
///   reach the memory bound take it 0.017 to 0.33 of the net engine's
///   time.
/// - Under Mix and in intuitionistic mode, the net engine. Under Mix, the
///   inverse method ran past 60 s on `wide-m1` with 4 096 and 8 192
///   literals, which the net engine proved.
///
/// On every other goal measured, the focused engines decided first. Which
/// goals reach a limit depends on the limits, which the dispatch's
/// features (fragment, mode, the roots, the shape of a Horn program) do
/// not see.
///
/// # The inverse method's turns
///
/// Where a row names the inverse method beside its engine, the engine
/// first searches alone until it has done 2²⁴ units of its work (every
/// thread counted), some hundredths of a second. A goal it decides within
/// that never sees a turn. Then, and each time the engine's work has
/// doubled, the inverse method takes a turn on the same thread. Each turn
/// starts the inverse method afresh and does at most a thirty-second of
/// the engine's work, in the inverse method's own units. Then the engine
/// goes on where it stopped. So the turns together do at most a sixteenth
/// of the engine's work. A goal the inverse method decides in `w` of its
/// units is decided once the engine has done some thirty-two times `w`.
///
/// When a turn decides, its answer is the search's. Its proof is checked,
/// and so is its refutation ([`Refutation::Saturated`]). The outcome then
/// names [`Inverse`](Engine::Inverse) and carries its counters. Otherwise
/// the turn's sequents go, and the engine's answer is the search's.
/// [`Statistics::work`] counts the turns' work beside the engine's. After
/// a turn that met the memory bound or an index limit, no turn comes
/// again.
///
/// Turns come only to a search on one thread with no engine forced (a
/// race's pool searches beside the thread that takes them), and only at a
/// poll of the engine's own work. So where the default bias's second
/// search runs alone after the first ended, no turn comes. A turn's share
/// is counted in the inverse method's units, whose time can differ much
/// from the engine's.
///
/// Where the dispatch gives no turn, either the inverse method decided no
/// goal the engines did not, or its turns would slow or lose a goal the
/// engine decides:
/// - intuitionistic linear sequents without exponentials (`euler`, slower
///   at every size);
/// - classical sequents without exponentials or Mix (the generated
///   families);
/// - intuitionistic affine mode. There the turns decided `pigeonhole` #0
///   from 5 holes (2.1 s to 0.54 s, and 6 holes in 18 s where the
///   two-sided engine passes a minute). But they made #1 with 7 holes,
///   which the two-sided engine refutes in 1 s, 1.27 times slower. A share
///   small enough to spare it would have left 6 holes past the minute.
/// - classical goals with an exponential. There the turns decided the
///   family `chain` from 256 clauses on, and 100 classical readings of the
///   library's problems that the command leaves at its 2 s limit. But
///   where the inverse method's units ran some fifteen times slower than
///   the focused engine's, the turns took up to 2.8 times the engine's
///   time. On one thread they lost `SYJ212+1.015`, which the focused
///   engine refutes in 1.9 s, to the 2 s limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Engine {
    /// The focused sequent engine, one-sided: classical mode, every
    /// fragment.
    ///
    /// It searches backward over dyadic sequents `⊢ Θ ; Γ`. `Θ` holds the
    /// formulas that came under a `?` and may be copied, `Γ` the formulas
    /// each used once. The asynchronous phase decomposes the negative
    /// formulas, whose rules need no choice, until a stable sequent
    /// remains, one with no negative formula left. The memo of stable
    /// sequents may decide it. Otherwise the counts of each atom's
    /// literals may refute it without a search, or a focus proves it: the
    /// rules of a positive formula of `Γ`, or of a copy from `Θ`, applied
    /// in one go.
    ///
    /// The copies are bounded per branch, and the bound deepens.
    /// `Unprovable` comes only from a level that never met its bound. With
    /// Mix, a stable sequent may be split in two. In affine mode, a leaf
    /// weakens what is left.
    ///
    /// It reads every option but [`Options::test_period`], which is the
    /// net engine's. Its unit of work ([`Progress::work`],
    /// [`Limits::work`]) is a stable sequent, weighed by the size of its
    /// zones, members and copies, and a step of a split search. Forced
    /// splits count none.
    Focus,
    /// The proof-net engine, for unit-free MLL with or without Mix.
    ///
    /// In intuitionistic mode it decides IMLL through the embedding into
    /// MLL. In the cyclic mode it decides cyclic MLL, the only engine that
    /// does. In the commutative modes, the dispatch gives it a goal only
    /// where the focused engines end at their recursion limit or memory
    /// bound ("When another engine takes over", above). Forced, it decides
    /// any goal it admits.
    ///
    /// A cut-free proof of MLL is its axiom linking. So the engine links
    /// dual literals by backtracking over a [`ProofStructure`], and keeps
    /// the first linking the correctness criterion accepts. The count
    /// equation and each atom's balance refuse most unprovable sequents
    /// before any link. The net found is sequentialized into the proof
    /// returned.
    ///
    /// In the cyclic mode it keeps the linking planar. A link is admitted
    /// only when it crosses no link made and the literals between its ends
    /// are balanced in every atom. The symmetry breaks are off there,
    /// since an exchange of equal literals can make two links cross, and
    /// it runs on one thread.
    ///
    /// Of the options it reads [`Options::jobs`] and the pool,
    /// [`Options::test_period`], [`Options::check`] and the occurrence
    /// limit. A unit-free MLL sequent has no copies to bound, and the
    /// engine keeps no memo and does not recurse. So the copy bounds, the
    /// bias, the memo limit and the recursion limit have nothing to bound
    /// here. Its structure, scratch and tables of interchangeable literals
    /// are linear in the forest, and are not counted under
    /// [`Limits::memory_bytes`](crate::Limits::memory_bytes).
    ///
    /// Its unit of work is a literal chosen and an exact test that fails.
    Net,
    /// The focused sequent engine, two-sided: intuitionistic mode.
    ///
    /// It is the search of `Focus` on the one-sided sequent. That search
    /// keeps one goal on every branch by itself, except at the split of a
    /// hypothesis `A ⊸ B`, where the goal must go with `B`. That split is
    /// the one place it reads the sequent's [`Reading`]. It reads the
    /// options `Focus` does, and counts its work as `Focus` does.
    TwoSided,
    /// The fast path for a sequent of two additive-only formulas, in every
    /// mode.
    ///
    /// It is a recursion on pairs of subformula occurrences, one below
    /// each root, memoized on the pair. It takes time proportional to the
    /// product of the two formulas' sizes.
    ///
    /// It reads [`Options::memo_limit`] and [`Options::check`], and the
    /// limits' recursion depth and memory bound. It runs on the calling
    /// thread whatever [`Options::jobs`] says. Two additive formulas have
    /// no copies and no atoms to bias. Its unit of work is a pair decided,
    /// which it counts at its polls, every 1 024 pairs.
    Additive,
    /// The engine for Horn programs, which it reads as Petri nets.
    ///
    /// A Horn program here has clauses under `!` that may be used any
    /// number of times, implications used once, atoms, and one goal that
    /// is a tensor of atoms. It is a Petri net with a marking to reach. In
    /// `!(a ⊗ b ⊸ c), a, b ⊢ c`, the clause is a transition, the atoms on
    /// the left are the tokens, and the goal is the marking.
    ///
    /// It searches the markings instead of sequents. Each marking is
    /// reached once, and kept as a count of tokens per atom. The marking
    /// nearest to the goal is expanded first; the distance is the number of
    /// tokens by which the two differ. An implication used once is a
    /// transition that takes a token of its own.
    ///
    /// A firing sequence that reaches the goal is the proof. Every firing
    /// is a copy of its clause, whose body takes its tokens by axioms and
    /// whose head adds its atoms to the context. Once every marking reached
    /// has been expanded without reaching the goal, the goal is
    /// `Unprovable`, since a proof of a Horn program is a firing sequence
    /// read upward. So is, before any search, a goal whose atom counts
    /// cannot balance, as for every engine.
    ///
    /// Beside the search, a simplex solves the net's state equation: are
    /// the goal's tokens the start's plus some number of firings of each
    /// clause? It runs a slice at a time, and never does more work than the
    /// search has done. Where the equation has no solution, Farkas' lemma
    /// gives each atom a weight under which no clause raises the weighted
    /// count of the tokens, while the goal asks it raised. An exact check
    /// in integers confirms the weights. The goal is then `Unprovable` with
    /// that [`Refutation::StateEquation`], however many markings the net
    /// has.
    ///
    /// A net whose markings grow without end and whose equation has a
    /// solution is searched until the stop or
    /// [`Limits::memory_bytes`](crate::Limits::memory_bytes), which counts
    /// the markings kept and the simplex's basis. Two more refutations
    /// reach such nets:
    /// - a clause with an atom that no reachable marking holds never
    ///   fires, and is left out;
    /// - once the search has done some work, the same search runs backward
    ///   from the goal beside it, with a quarter of the work. If it
    ///   exhausts its markings, the goal is refuted. Its firing sequence,
    ///   read backward, is a proof.
    ///
    /// In affine mode, the tokens and the clauses a firing sequence leaves
    /// are weakened. So the question is whether a marking that covers the
    /// goal is reachable, and the engine decides it backward. From the
    /// goal, it computes the least markings from which a firing leads to
    /// one that covers it, and keeps each unless a smaller one is kept. It
    /// ends when one lies below the start (the proof), or when no new one
    /// comes (`Unprovable`), which Dickson's lemma says happens. The state
    /// equation runs beside it as in linear mode.
    ///
    /// It searches classical or intuitionistic, with or without Mix, which
    /// no proof of such a goal can use. It reads [`Options::check`] and the
    /// limits' memory bound, and runs on the calling thread whatever
    /// [`Options::jobs`] says. It needs no copy bound, memo limit or
    /// recursion limit: it keeps every marking once and does not recurse.
    /// Its unit of work is a marking taken from the frontier or an element
    /// from the queue, a marking computed backward, and a pivot of the
    /// state equation.
    Horn,
    /// The essential-net engine, for unit-free IMLL: intuitionistic mode
    /// without weakening, and the Lambek calculus.
    ///
    /// In the commutative modes the dispatch gives it no goal; forced, it
    /// decides any goal it admits. In the Lambek calculus it is the
    /// default and the only engine. There the criterion is that of planar
    /// essential nets (Lamarche and Retoré). A link is admitted only when
    /// it crosses no link made and the literals between its ends are
    /// balanced, and the symmetry breaks are off, as for the net engine's
    /// cyclic linking. Without empty antecedents, a complete linking is a
    /// proof only when, besides, the body of every implication but the
    /// goal has a free hypothesis other than the one it binds, so that no
    /// sequent of the proof is without one. A goal off the roots is
    /// searched as a sequent of its own.
    ///
    /// It is the net engine's search over the sequent's polarized
    /// structure, Lamarche's essential net, whose edges the [`Reading`]
    /// directs from the hypotheses toward the goal. A linking is a proof
    /// net when the directed graph has no cycle, and every implication
    /// `A ⊸ B` of output position dominates its antecedent: every path
    /// from `A` to the goal passes through it
    /// ([`ProofStructure::is_essential`]).
    ///
    /// It keeps the reflexive transitive closure of the graph as a bit
    /// matrix, quadratic in the sequent's size. The matrix and its undo
    /// log are counted under
    /// [`Limits::memory_bytes`](crate::Limits::memory_bytes). A link that
    /// would close a cycle, or lead an antecedent's literal to the goal
    /// around its implication, is rejected at once. The dominator
    /// condition is tested where the net engine runs its exact test. It
    /// counts, breaks symmetries and chooses literals as the net engine
    /// does, and sequentializes the net found into the proof returned.
    ///
    /// Of the options it reads [`Options::test_period`] and
    /// [`Options::check`]. It runs on the calling thread whatever
    /// [`Options::jobs`] says. Its unit of work is a literal chosen and a
    /// test that fails.
    ///
    /// Measured on one thread on the intuitionistic sequents the net
    /// engine was measured on, it is slower than the two-sided engine on
    /// all of them but the chain of 64 links (0.18 ms against 0.22 ms).
    /// Wide and curried sequents of 64 to 4 096 atoms take it 2.3 to 25
    /// times as long. The Horn encodings of Partition take it 1.3 to 4.5
    /// times as long, or run out of time at 60 s where the two-sided
    /// engine takes 13 and 75 ms. On the chains of 1 024 and 4 096 links,
    /// where the two-sided engine meets its recursion limit, it is 2.2 and
    /// 6 times slower than the net engine, which takes those over. It is
    /// faster than the net engine on the Partition encodings (16 to 660
    /// times) and on wide and curried sequents up to 1 024 atoms. So the
    /// dispatch gives it no goal.
    Essential,
    /// The focused inverse method, in every commutative mode and fragment.
    ///
    /// It is a forward search: it derives stable sequents from the axioms
    /// upward, instead of decomposing the goal. Its rules are whole
    /// focusing phases, compiled from the sequent before the search. A
    /// rule is a focus on a positive formula, or on a copy of a `?`
    /// formula's subformula, with the asynchronous phases of what it
    /// releases. There is one rule for each choice of `⊕` sides. A rule's
    /// premises are stable sequents derived before, and its axioms take a
    /// negative literal for each positive one.
    ///
    /// A derived sequent stands for itself, or, with a `⊤` above it or in
    /// affine mode, for every larger one. It is kept unless one kept
    /// already stands for all it does (subsumption, found through an index
    /// of the kept sequents by their members). It is also dropped when it
    /// cannot stand in a proof of the goal: when it has a member twice, or
    /// two members a `⊗`, `&` or `⊕` separates, outside the subformulas of
    /// a `?`, or, under the intuitionistic reading, other than one goal.
    ///
    /// The smallest sequent is taken up first. It is applied to every rule
    /// beside those taken up before it, and with Mix joined to each. The
    /// goal is proved once every stable sequent of its own asynchronous
    /// phase is. The proof is written from the record each sequent keeps
    /// of its rule and premises. Without exponentials the sequents are
    /// finitely many, and the search decides. With them, it proves every
    /// provable goal given time, needs no copy bound, and answers
    /// `Unprovable` only where nothing new comes.
    ///
    /// It reads [`Options::bias`], which says which atoms' literals are
    /// positive, and [`Options::check`]. It runs on the calling thread
    /// whatever [`Options::jobs`] says. The copy bounds, the memo limit and
    /// the recursion limit have nothing to bound here. Its rules, the
    /// sequents kept, their indices and records and the queue are counted
    /// under [`Limits::memory_bytes`](crate::Limits::memory_bytes). Over
    /// it, the search answers `Unknown`, since the sequents kept cannot be
    /// given back without losing what was derived.
    ///
    /// It refuses a goal within the sequent two of whose members no
    /// sequent of a proof holds together: one twice or below another, or
    /// two a `⊗`, `&` or `⊕` separates, outside a `?`. No derivation of the
    /// sequent has such a goal.
    ///
    /// Its units of work: a step of a rule written, a choice of `⊕` sides
    /// looked at, a literal looked at for an axiom's partner, and a member
    /// copied into the rules' tables; in the saturation, a member of a
    /// linear zone copied, compared or indexed, an entry looked up in the
    /// index of the kept sequents, and an application of a rule or Mix or
    /// a choice of premises given up. So its work grows with its time,
    /// whatever the size of its sequents.
    Inverse,
    /// An engine this version of the crate does not know: one a later
    /// version ran, named in an outcome read from its document. No search
    /// runs it, so forced through [`Options::engine`] it is refused
    /// ([`Error::UnknownName`]); it lists no counters, is not in
    /// [`ALL`](Self::ALL), and its name is `unknown`.
    Unknown,
}

impl Display for Engine {
    /// Writes the engine's name: `focus`, `net`, `two-sided`, `additive`,
    /// `horn`, `essential` or `inverse`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())
    }
}

/// A counter of [`Statistics`] as an engine fills it
/// ([`Engine::counters`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Counter {
    /// The field's name in the statistics' JSON form.
    pub key: &'static str,
    /// A short label, for a line of statistics.
    pub label: &'static str,
    /// The label in affine mode, where an engine may count something
    /// else: the Horn engine searches backward there.
    pub affine_label: &'static str,
    /// What it counts for the engine.
    pub meaning: &'static str,
}

impl Counter {
    /// Returns a counter with the key, the label (in every mode) and the
    /// meaning given.
    const fn new(key: &'static str, label: &'static str, meaning: &'static str) -> Self {
        Self {
            key,
            label,
            affine_label: label,
            meaning,
        }
    }

    /// Returns the counter with another label in affine mode.
    const fn affine(self, affine_label: &'static str) -> Self {
        Self {
            affine_label,
            ..self
        }
    }

    /// Returns the label for a search in the mode given.
    #[must_use]
    pub const fn label_in(&self, mode: Mode) -> &'static str {
        if mode.is_affine() {
            self.affine_label
        } else {
            self.label
        }
    }
}

/// Why an engine the options force does not take a goal.
///
/// Each engine checks, in this order: the largest fragment it decides,
/// its modes, whether the goal is the sequent itself, and the goal's
/// shape.
///
/// In JSON (feature `serialize`), as the `because` of an
/// `engine_refused` error's `details` beside its `engine`, tagged by
/// `kind`: `{"kind": "fragment", "decides": "MLL", "goal": "MELL"}`,
/// `{"kind": "mode", "mode": "affine"}`, `{"kind": "goal"}` or
/// `{"kind": "shape"}`; written, never read.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NotTaken {
    /// The goal lies beyond the largest fragment the engine decides.
    #[non_exhaustive]
    Fragment {
        /// The largest fragment the engine decides.
        decides: Fragment,
        /// The fragment the goal was searched in.
        goal: Fragment,
    },
    /// The engine does not search in the mode.
    #[non_exhaustive]
    Mode {
        /// The mode asked for.
        mode: Mode,
    },
    /// The goal is not the sequent itself, the only goal the engine takes.
    Goal,
    /// The goal is not of the engine's shape: two additive-only formulas
    /// for the additive engine, a Horn program for the Horn engine, and
    /// for the inverse method a goal within the sequent whose members can
    /// stand together in one sequent of a proof.
    Shape,
}

impl NotTaken {
    /// Returns the sentence that says why `engine` does not take the goal.
    pub fn explained(self, engine: Engine) -> impl Display {
        Explained(engine, self)
    }
}

/// The sentence of a refusal of a forced engine.
struct Explained(Engine, NotTaken);

impl Display for Explained {
    /// Writes why the engine does not take the goal, in the engine's
    /// words where it has them.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Explained(engine, because) = *self;
        match (engine, because) {
            (Engine::Net, NotTaken::Fragment { goal, .. }) => {
                write!(
                    f,
                    "proof nets exist for MLL without units only, not for {goal}"
                )
            }
            (Engine::Essential, NotTaken::Fragment { goal, .. }) => {
                write!(
                    f,
                    "essential nets exist for IMLL without units only, not for {goal}"
                )
            }
            (Engine::Net, NotTaken::Mode { mode }) if mode.is_ordered() => write!(
                f,
                "the net engine does not search in {mode} mode, whose planar essential nets the \
                 essential engine searches"
            ),
            (Engine::Net, NotTaken::Mode { mode }) => write!(
                f,
                "proof nets exist in linear mode only, with or without Mix, not in {mode} mode"
            ),
            (_, NotTaken::Goal) => write!(
                f,
                "the {engine} engine decides the whole sequent only, not a goal within it"
            ),
            (_, NotTaken::Mode { mode }) => {
                write!(f, "the {engine} engine does not search in {mode} mode")
            }
            (Engine::Additive, NotTaken::Fragment { goal, .. }) => write!(
                f,
                "the additive engine decides a sequent of two additive-only formulas, not one of \
                 {goal}"
            ),
            (Engine::Additive, NotTaken::Shape) => f.write_str(
                "the additive engine decides a sequent of two additive-only formulas only",
            ),
            (Engine::Horn, NotTaken::Fragment { .. } | NotTaken::Shape) => f.write_str(
                "the horn engine decides a Horn program only: atoms, implications between \
                 tensors of atoms, such implications under !, and one goal that is a tensor of \
                 atoms",
            ),
            (_, NotTaken::Fragment { decides, goal }) => {
                write!(
                    f,
                    "the {engine} engine decides {decides} at most, not {goal}"
                )
            }
            (Engine::Inverse, NotTaken::Shape) => f.write_str(
                "the inverse engine does not take a goal two of whose members no sequent of a \
                 proof holds together: one twice or below another, or two that a ⊗, & or ⊕ \
                 separates, outside the formula under a ?",
            ),
            (_, NotTaken::Shape) => {
                write!(f, "the {engine} engine does not take a goal of this shape")
            }
        }
    }
}

/// How the focused engine chooses the positive literal of every atom.
///
/// Focusing is complete for every choice, so no rule changes what is
/// provable. The rules differ in speed and, with exponentials, in the
/// copies a branch of the proofs they lead to needs.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Bias {
    /// The rule chosen per sequent:
    /// - [`Factors`](Self::Factors) for a sequent without exponentials;
    /// - [`Rarer`](Self::Rarer) for a search with weakening;
    /// - for a sequent with a `!` or a `?` in linear mode, a search under
    ///   each rule. It answers with the first that decides, so it decides
    ///   whatever either does: the backward search within the copy bound,
    ///   the forward one within a bound of its own where the goal is a
    ///   Horn program. This holds without a stop; under a time limit, each
    ///   search has its share of the time.
    ///
    /// Each choice is what measured best there:
    /// - without exponentials, the factor rule visits up to a third of the
    ///   stable sequents of the rarer one (unsolvable 3-Partition with bins
    ///   of five: 971 against 3 373; a random QBF of 20 variables: 60 883
    ///   against 105 667);
    /// - under weakening nothing forces a split, and the factor rule
    ///   visited up to 700 times the stable sequents of the rarer one on
    ///   random affine sequents;
    /// - with exponentials neither rule wins. Of the Petri nets of the
    ///   LLTP library within 5 s, the pair decides 1 520, the backward
    ///   search run alone 442 and the forward one run alone 1 576. Where
    ///   each decides, the pair costs 1.3 times the backward search and
    ///   1.6 times the forward one.
    #[default]
    Auto,
    /// The literal with fewer occurrences in the sequent is positive, and
    /// `Atom` when both have the same number. With Horn-like hypotheses
    /// this mostly chains backward from the goal, which keeps the copies
    /// per branch low.
    Rarer,
    /// The literal that is more often a direct factor of a `⊗` is
    /// positive, an occurrence counting half for every `&` or `⊕` above
    /// it. On a tie, the rarer literal is. A `⊗` with a positive literal
    /// for a factor takes exactly the dual literal for it, so its split
    /// needs no search. With Horn-like hypotheses this chains forward from
    /// the facts, one copy per step on a single branch. That is fast, but
    /// needs a copy bound as large as the number of steps.
    Factors,
}

impl Engine {
    /// Every engine, in the order of [`NAMES`](Self::NAMES).
    pub const ALL: &'static [Self] = &[
        Self::Focus,
        Self::Net,
        Self::TwoSided,
        Self::Additive,
        Self::Horn,
        Self::Essential,
        Self::Inverse,
    ];

    /// The engines' names, as [`name`](Self::name) writes them and
    /// [`FromStr`] reads them.
    pub const NAMES: &'static [&'static str] = &[
        "focus",
        "net",
        "two-sided",
        "additive",
        "horn",
        "essential",
        "inverse",
    ];

    /// Returns the counters of [`Statistics`] the engine fills, each with
    /// its key in the statistics' JSON form, a label and what it counts
    /// for this engine. The other counters stay zero. A front end shows
    /// these.
    pub const fn counters(self) -> &'static [Counter] {
        /// The unit of work, which every engine counts.
        const WORK: Counter = Counter::new("work", "units of work", "the engine's unit of work");
        /// The focused engines' counters.
        const FOCUSED: &[Counter] = &[
            Counter::new(
                "nodes",
                "stable sequents visited",
                "stable sequents visited, memo hits included",
            ),
            Counter::new(
                "memo_hits",
                "from the memo",
                "stable sequents the memo answered",
            ),
            Counter::new(
                "memo_entries",
                "memo entries at most",
                "the most entries the memo held at once",
            ),
            Counter::new(
                "splits",
                "splits examined",
                "steps of the split searches and forced splits",
            ),
            Counter::new(
                "copies",
                "copy bound reached",
                "the level of the search that decided, else of the backward one",
            ),
            Counter::new(
                "forward_copies",
                "forward search's copy bound reached",
                "the forward search's level under the default bias",
            ),
            Counter::new(
                "unifications",
                "unifications tried",
                "unifications of two literals tried, on a first-order sequent",
            ),
            Counter::new(
                "bindings",
                "metavariables bound",
                "metavariables bound, on a first-order sequent",
            ),
            WORK,
        ];
        /// The net engine's counters.
        const NET: &[Counter] = &[
            Counter::new(
                "nodes",
                "literals chosen",
                "literals the search chose a partner for",
            ),
            Counter::new("links", "links tried", "axiom links made"),
            Counter::new("tests", "exact tests run", "exact acyclicity tests"),
            WORK,
        ];
        /// The essential-net engine's counters.
        const ESSENTIAL: &[Counter] = &[
            Counter::new(
                "nodes",
                "literals chosen",
                "literals the search chose a partner for",
            ),
            Counter::new("links", "links tried", "axiom links made"),
            Counter::new(
                "tests",
                "dominator tests run",
                "tests of the dominator condition",
            ),
            WORK,
        ];
        /// The additive path's counters.
        const ADDITIVE: &[Counter] = &[
            Counter::new(
                "nodes",
                "pairs of subformulas visited",
                "pairs decided, memo hits included",
            ),
            Counter::new("memo_hits", "from the memo", "pairs the memo answered"),
            Counter::new(
                "memo_entries",
                "memo entries",
                "the most pairs the memo held at once",
            ),
            WORK,
        ];
        /// The Horn engine's counters.
        const HORN: &[Counter] = &[
            Counter::new(
                "nodes",
                "markings reached",
                "markings reached from either end, or in affine mode computed backward",
            )
            .affine("markings computed backward"),
            Counter::new(
                "memo_hits",
                "markings met again",
                "markings kept already, or covered already",
            )
            .affine("markings covered already"),
            Counter::new("memo_entries", "markings kept", "markings kept"),
            WORK,
        ];
        /// The inverse method's counters.
        const INVERSE: &[Counter] = &[
            Counter::new(
                "nodes",
                "sequents taken up",
                "derived sequents taken up and applied to the rules",
            ),
            Counter::new(
                "memo_hits",
                "sequents subsumed",
                "derived sequents a kept one subsumed",
            ),
            Counter::new("memo_entries", "sequents kept", "derived sequents kept"),
            WORK,
        ];
        match self {
            Self::Focus | Self::TwoSided => FOCUSED,
            Self::Net => NET,
            Self::Essential => ESSENTIAL,
            Self::Additive => ADDITIVE,
            Self::Horn => HORN,
            Self::Inverse => INVERSE,
            Self::Unknown => &[],
        }
    }

    /// Returns the engine's name: `focus`, `net`, `two-sided`, `additive`,
    /// `horn`, `essential` or `inverse`, and `unknown` for
    /// [`Unknown`](Self::Unknown).
    pub const fn name(self) -> &'static str {
        match self {
            Self::Focus => "focus",
            Self::Net => "net",
            Self::TwoSided => "two-sided",
            Self::Additive => "additive",
            Self::Horn => "horn",
            Self::Essential => "essential",
            Self::Inverse => "inverse",
            Self::Unknown => "unknown",
        }
    }

    /// Returns whether the engine searches on several threads when
    /// [`Options::jobs`] asks for them.
    ///
    /// The focused engines do, and so does the net engine in a commutative
    /// mode. The additive, Horn, essential-net and inverse engines run on
    /// the calling thread whatever `jobs` says.
    pub const fn parallel(self) -> bool {
        match self {
            Engine::Focus | Engine::Net | Engine::TwoSided => true,
            Engine::Additive
            | Engine::Horn
            | Engine::Essential
            | Engine::Inverse
            | Engine::Unknown => false,
        }
    }

    /// Returns the implementation of the engine.
    fn implementation(self) -> &'static dyn Decide {
        match self {
            Engine::Focus => &focus::ONE_SIDED,
            Engine::TwoSided => &focus::TWO_SIDED,
            Engine::Net => &net::Nets,
            Engine::Additive => &additive::Additive,
            Engine::Horn => &horn::Horn,
            Engine::Essential => &essential::Essentials,
            Engine::Inverse => &inverse::Inverse,
            Engine::Unknown => unreachable!("the front door refuses an engine it does not know"),
        }
    }
}

impl FromStr for Engine {
    type Err = Error;

    /// Reads an engine's name, one of [`NAMES`](Self::NAMES).
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::ALL
            .iter()
            .copied()
            .find(|engine| engine.name() == name)
            .ok_or_else(|| Error::UnknownName {
                what: "engine",
                name: name.into(),
                known: Self::NAMES,
            })
    }
}

impl Bias {
    /// Every rule, in the order of [`NAMES`](Self::NAMES).
    pub const ALL: &'static [Self] = &[Self::Auto, Self::Rarer, Self::Factors];

    /// The rules' names, as [`name`](Self::name) writes them and
    /// [`FromStr`] reads them.
    pub const NAMES: &'static [&'static str] = &["auto", "rarer", "factors"];

    /// Returns the rule's name: `auto`, `rarer` or `factors`.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Rarer => "rarer",
            Self::Factors => "factors",
        }
    }
}

impl Display for Bias {
    /// Writes the rule's [`name`](Self::name).
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())
    }
}

impl FromStr for Bias {
    type Err = Error;

    /// Reads a rule's name, one of [`NAMES`](Self::NAMES).
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::ALL
            .iter()
            .copied()
            .find(|bias| bias.name() == name)
            .ok_or_else(|| Error::UnknownName {
                what: "bias",
                name: name.into(),
                known: Self::NAMES,
            })
    }
}

/// How many threads a search may use. In JSON it is `"auto"` or the
/// number.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Jobs {
    /// Every thread the machine runs at once, as the platform tells, or
    /// one where it does not tell. A front end resolves it once to the
    /// count it shows.
    Auto,
    /// This many. One runs the sequential engines, whose proof is a
    /// function of the input. Zero counts as one, and more than
    /// [`Options::MAX_JOBS`] as that many.
    Count(usize),
}

impl Default for Jobs {
    /// One thread.
    fn default() -> Self {
        Self::Count(1)
    }
}

impl From<usize> for Jobs {
    /// That many threads.
    fn from(count: usize) -> Self {
        Self::Count(count)
    }
}

impl Jobs {
    /// Returns the number of threads: the count asked for, or the
    /// machine's for [`Auto`](Self::Auto), at least one and at most
    /// [`Options::MAX_JOBS`].
    pub fn count(self) -> usize {
        let count = match self {
            Self::Auto => std::thread::available_parallelism().map_or(1, NonZeroUsize::get),
            Self::Count(count) => count,
        };
        count.clamp(1, Options::MAX_JOBS)
    }
}

/// How often the net engines run their test. In JSON it is `"auto"` or
/// the number of links between two tests.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Cadence {
    /// After every link on a structure of at most
    /// [`AUTO_SMALL`](Self::AUTO_SMALL) occurrences, and after every
    /// [`AUTO_PERIOD`](Self::AUTO_PERIOD)th link on a larger one.
    #[default]
    Auto,
    /// After this many links; zero counts as one.
    Every(u32),
}

impl Cadence {
    /// The most occurrences a structure has on which [`Auto`](Self::Auto)
    /// tests after every link.
    pub const AUTO_SMALL: usize = 200;

    /// How many links go between two tests of [`Auto`](Self::Auto) on a
    /// larger structure.
    pub const AUTO_PERIOD: u32 = 4;
}

impl From<u32> for Cadence {
    /// Every so many links.
    fn from(links: u32) -> Self {
        Self::Every(links)
    }
}

impl From<Option<u32>> for Cadence {
    /// Every so many links, or the default for `None`.
    fn from(links: Option<u32>) -> Self {
        links.map_or(Self::Auto, Self::Every)
    }
}

/// How the two searches of the default bias share one thread. In JSON
/// it is `"auto"` or `"turns"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum Schedule {
    /// In slices on two threads where the feature `parallel` starts a
    /// second one, and in turns otherwise.
    #[default]
    Auto,
    /// In turns on the calling thread, each turn from the search's start.
    /// So the polls and the answer are the same on every build, the
    /// WebAssembly build included.
    Turns,
}

/// The knobs of a search: which engine and fragment to use instead of the
/// detected ones, how many copies to allow, how much to remember, and how
/// many threads to use.
///
/// The defaults suit a sequent of a few hundred occurrences on a thread
/// with the usual stack. The bounds on memory, occurrences, recursion and
/// work are not options: they are the [`Limits`] a search is given. The
/// bounds on memory and work bind the check of the proof found as well.
///
/// Every field has a builder, so the options chain from the default.
///
/// # JSON
///
/// With the feature `serialize`, the options are an object of the fields
/// below. A missing field takes its default, and a misspelt one is
/// refused.
/// - `"engine"` and `"fragment"`: a name or `"auto"`;
/// - `"bias"` and `"schedule"`: a name;
/// - `"copies"`: a number, or `null` for no bound;
/// - `"forward_copies"`, `"memo_limit"`, `"classical_work"`,
///   `"witness_depth"` and `"instances"`: numbers;
/// - `"test_period"` and `"jobs"`: a number or `"auto"`;
/// - `"check"`: a boolean.
///
/// The pool is never written.
///
/// # Examples
///
/// ```
/// use deduxit::linear::Fragment;
/// use deduxit::linear::search::{Bias, Options};
///
/// // Search in MALL with a smaller memo, the rarer bias and no copy bound.
/// let options = Options::default()
///     .with_memo_limit(1 << 16)
///     .with_fragment(Some(Fragment::MALL))
///     .with_bias(Bias::Rarer)
///     .with_copies(None);
/// assert_eq!(options.copies, None);
/// assert_eq!(options.bias, Bias::Rarer);
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct Options {
    /// The engine to use, or `None` for the one the detected fragment and
    /// the mode call for.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::auto"))]
    pub engine: Option<Engine>,
    /// The fragment to search in, or `None` for the detected one.
    ///
    /// A sequent outside it is refused. A fragment larger than the
    /// detected one switches off the prunes that only hold in the smaller
    /// one.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::auto"))]
    pub fragment: Option<Fragment>,
    /// How the focused engine picks the positive literal of every atom.
    /// No choice changes what is provable.
    ///
    /// [`Bias::Rarer`] mostly chains backward from the goal, and
    /// [`Bias::Factors`] forward from the hypotheses. Take a sequent with
    /// exponentials whose hypotheses are Horn clauses, such as a Petri
    /// net. The forward search often decides it in milliseconds where the
    /// backward one does not decide at all. But its proofs take one copy
    /// per step on a single branch.
    ///
    /// The default, [`Bias::Auto`], is `Factors` without exponentials and
    /// `Rarer` under weakening. On a sequent with exponentials in linear
    /// mode it runs both searches, the backward one within
    /// [`copies`](Self::copies) and the forward one within
    /// [`forward_copies`](Self::forward_copies), and answers with the first
    /// that decides. Either rule named explicitly is that search alone,
    /// within `copies`. Only the focused engine reads it.
    pub bias: Bias,
    /// The most copies of `?` formulas one branch of a proof may take, or
    /// `None` for no bound.
    ///
    /// The search deepens the bound from zero, one level after another. A
    /// sequent that has no proof within the bound is [`Reason::CopyBound`].
    /// The exception is a level that finished without ever reaching its
    /// bound: that makes the sequent [`Verdict::Unprovable`].
    ///
    /// Without a bound, the search goes on to the next level until it
    /// decides, its stop condition fires or a limit binds.
    /// [`Statistics::copies`] then says how far it got. That is the choice
    /// of a caller with a time limit, such as the command: some provable
    /// sequent needs more copies than any given bound, and full linear
    /// logic is undecidable.
    ///
    /// Without exponentials the bound has no effect. A proof found at some
    /// level may reuse a memoized subproof found with more copies left, so
    /// the bound limits the search, not the proof returned. Only the
    /// focused engine reads it: the net and additive engines' goals have no
    /// exponentials, and the Horn engine keeps every marking once and
    /// needs no bound.
    pub copies: Option<u32>,
    /// The most copies of `?` formulas one branch may take in the forward
    /// search that [`Bias::Auto`] runs beside the backward one on a Horn
    /// program.
    ///
    /// A Horn program here is clauses `!(a ⊗ b ⊸ c ⊗ d)` (or such a clause
    /// used once), a marking and a goal of atoms, as a Petri net is. A
    /// forward chain takes a copy per step, all on one branch, so it wants
    /// a larger bound than [`copies`](Self::copies). The forward search
    /// runs within the larger of the two, never within less than `copies`.
    ///
    /// It has no effect on any other goal, under another bias, under Mix,
    /// under weakening, or without a copy bound: unbounded, the forward
    /// search deepens as far as its share of the work takes it. Only the
    /// focused engine reads it.
    pub forward_copies: u32,
    /// The most stable sequents the memo holds at once. Zero switches the
    /// memo off.
    ///
    /// A full memo is emptied, which costs time but not correctness. The
    /// two searches that [`Bias::Auto`] runs on a sequent with
    /// exponentials hold a memo of this size each. This is the finer knob
    /// beside the memory bound
    /// ([`Limits::memory_bytes`](crate::Limits::memory_bytes)), which
    /// bounds the memo in bytes: a table that fits the processor's cache
    /// can be faster than one that fits the memory. The focused engine and
    /// the additive path read it; the net engine keeps no memo.
    pub memo_limit: u32,
    /// How often the net engine runs its exact acyclicity test, and the
    /// essential-net engine its test of the dominator condition.
    ///
    /// The test also runs on every complete linking. So the cadence trades
    /// time per link against how long a doomed branch is followed. Only
    /// those two engines read it.
    pub test_period: Cadence,
    /// How many threads the search may use.
    ///
    /// One, the default, runs the sequential engines, whose proof is a
    /// function of the input. More than one, with the `parallel` feature,
    /// runs the focused engine and the net engine on that many threads of
    /// a pool of their own. The pool may find a different proof, but never
    /// contradicts the sequential verdict. One of the two may decide where
    /// the other stops at the copy bound or the recursion limit, and which
    /// one depends on how the threads interleave. Without the feature, or
    /// for the engines that are not [`Engine::parallel`], the search stays
    /// sequential.
    ///
    /// A search starts no more threads than the machine runs at once
    /// ([`std::thread::available_parallelism`], where the platform tells).
    /// Threads beyond that only take turns on the same processors.
    pub jobs: Jobs,
    /// How the two searches of the default bias share one thread.
    pub schedule: Schedule,
    /// Whether a proof passes the checker ([`Proof::check`], which shares
    /// no code with the engines) before the search returns it.
    ///
    /// A proof that does not pass is [`Error::Rejected`], never a verdict.
    /// A proof of a goal is checked against the goal. Without the check,
    /// the proof is the engine's word. A caller that checks it itself, or
    /// times the search alone, may prefer that.
    pub check: bool,
    /// The most work the classical refuter may do after a search that did
    /// not prove the goal, in terms evaluated. Zero switches it off.
    ///
    /// The refuter looks for an assignment of truth values to the atoms
    /// under which the goal's classical reading is false. That reading
    /// erases `!` and `?`, reads `⊗` and `&` as "and", `⅋` and `⊕` as "or",
    /// `1` and `⊤` as true, and `⊥` and `0` as false. No provable sequent
    /// has such an assignment, in any mode. So an assignment makes an
    /// undecided search [`Verdict::Unprovable`] with
    /// [`Refutation::Classical`]. It also gives an exhausted search that
    /// certificate, where the counts give none.
    ///
    /// It never changes a verdict the search gave, nor its counters. It
    /// runs under the caller's stop and the memory bound, on the calling
    /// thread, whatever engine searched.
    pub classical_work: u64,
    /// The deepest term a metavariable of a first-order search may be
    /// bound to.
    ///
    /// A constant's depth is 0, and an application's is one more than its
    /// deepest argument's, measured as the binding is made. The focused
    /// engine searches a first-order sequent with a metavariable for every
    /// witness of an `∃`, and binds it where an axiom unifies two atoms. A
    /// branch whose binding would be deeper is cut there. A search that
    /// cut one is not [`Verdict::Unprovable`] but [`Reason::WitnessDepth`].
    ///
    /// A sequent without exponentials needs no witness deeper than its
    /// terms together. So the bound matters where copies of a `∀`
    /// hypothesis build a term step by step. Only the focused engine reads
    /// it, on first-order sequents.
    pub witness_depth: u32,
    /// The most instances of quantified formulas a first-order search may
    /// hold at once.
    ///
    /// Every `∀` and `∃` step on the branches of the proof in the making
    /// opens one. A step past the bound cuts its branch, and a search that
    /// cut one is not [`Verdict::Unprovable`] but [`Reason::Instances`].
    /// It bounds what the instances hold, which the copies of quantified
    /// hypotheses multiply. Only the focused engine reads it, on
    /// first-order sequents.
    pub instances: u32,
    /// The thread pools a parallel search borrows instead of starting
    /// threads of its own. `None`, the default, is a pool built for the
    /// search and dropped with it.
    ///
    /// A pool changes nothing a search does or finds. It only starts its
    /// threads once for many searches. Options are equal only if they name
    /// clones of the same pool, or both name none. The pool is never
    /// written.
    ///
    /// Needs the cargo feature `parallel` (off by default).
    #[cfg(feature = "parallel")]
    #[cfg_attr(feature = "serialize", serde(skip))]
    pub pool: Option<Pool>,
}

impl Default for Options {
    /// Returns the default options:
    /// - the engine and fragment chosen by detection, and the default bias;
    /// - a copy bound of [`DEFAULT_COPIES`](Self::DEFAULT_COPIES), and one
    ///   of [`DEFAULT_FORWARD_COPIES`](Self::DEFAULT_FORWARD_COPIES) for the
    ///   forward search of the default bias;
    /// - a memo of at most [`DEFAULT_MEMO_LIMIT`](Self::DEFAULT_MEMO_LIMIT)
    ///   stable sequents;
    /// - the net engine's exact test at its default cadence;
    /// - one thread, and the default schedule;
    /// - every proof checked ([`DEFAULT_CHECK`](Self::DEFAULT_CHECK));
    /// - the classical refuter's bound
    ///   [`DEFAULT_CLASSICAL_WORK`](Self::DEFAULT_CLASSICAL_WORK);
    /// - the first-order bounds
    ///   [`DEFAULT_WITNESS_DEPTH`](Self::DEFAULT_WITNESS_DEPTH) and
    ///   [`DEFAULT_INSTANCES`](Self::DEFAULT_INSTANCES).
    fn default() -> Self {
        Self {
            engine: None,
            fragment: None,
            bias: Bias::Auto,
            copies: Some(Self::DEFAULT_COPIES),
            forward_copies: Self::DEFAULT_FORWARD_COPIES,
            memo_limit: Self::DEFAULT_MEMO_LIMIT,
            test_period: Cadence::Auto,
            jobs: Jobs::Count(1),
            schedule: Schedule::Auto,
            check: Self::DEFAULT_CHECK,
            classical_work: Self::DEFAULT_CLASSICAL_WORK,
            witness_depth: Self::DEFAULT_WITNESS_DEPTH,
            instances: Self::DEFAULT_INSTANCES,
            #[cfg(feature = "parallel")]
            pool: None,
        }
    }
}

impl Options {
    /// The memo limit of the default options: 2²⁰ stable sequents.
    pub const DEFAULT_MEMO_LIMIT: u32 = 1 << 20;

    /// The copy bound of the default options: three copies per branch, the
    /// bound llprover searches with by default.
    ///
    /// The default options keep a bound because a search without one ends
    /// only when it decides, its stop condition fires or a limit binds,
    /// and [`prove`] has no stop condition. A front end with a clock lifts
    /// it ([`copies`](Self::copies)).
    pub const DEFAULT_COPIES: u32 = 3;

    /// The forward search's copy bound of the default options: thirty
    /// steps of a forward chain.
    ///
    /// A deeper bound decided nothing more within seconds on Petri nets
    /// from practice. The price of the bound is what an undecided search to
    /// that depth costs: mostly milliseconds on a small Horn program, a
    /// second and more on one whose markings grow in several places at
    /// once.
    pub const DEFAULT_FORWARD_COPIES: u32 = 30;

    /// Whether the default options check a proof before returning it: they
    /// do. The check is one pass over the proof, in memory proportional to
    /// it.
    pub const DEFAULT_CHECK: bool = true;

    /// The classical refuter's bound of the default options: 2²⁶ terms
    /// evaluated. That is enough to try every assignment of a goal of 18
    /// atoms and 256 terms, and far more where a partial assignment decides
    /// the reading.
    pub const DEFAULT_CLASSICAL_WORK: u64 = 1 << 26;

    /// The witness depth of the default options: terms 64 applications
    /// deep. That is far past any depth a sequent written by hand asks
    /// for, and a branch that builds a term forever reaches it quickly.
    pub const DEFAULT_WITNESS_DEPTH: u32 = 64;

    /// The instances of the default options: 2¹⁶ instances of quantified
    /// formulas held at once, some megabytes of the search's tables.
    pub const DEFAULT_INSTANCES: u32 = 1 << 16;

    /// The most threads the options name: more are taken as this many.
    ///
    /// A pool beyond it has no known use, and a count without a bound
    /// starts whatever it is given: ten thousand threads on `A ⊢ A` cost
    /// three minutes of processor time.
    pub const MAX_JOBS: usize = 256;

    /// Returns the options with another bound on the classical refuter's
    /// work ([`classical_work`](Self::classical_work)), zero for none.
    #[must_use]
    pub fn with_classical_work(self, classical_work: u64) -> Self {
        Self {
            classical_work,
            ..self
        }
    }

    /// Returns the options with another
    /// [`witness_depth`](Self::witness_depth).
    #[must_use]
    pub fn with_witness_depth(self, witness_depth: u32) -> Self {
        Self {
            witness_depth,
            ..self
        }
    }

    /// Returns the options with another bound on
    /// [`instances`](Self::instances).
    #[must_use]
    pub fn with_instances(self, instances: u32) -> Self {
        Self { instances, ..self }
    }

    /// Returns the options with another [`engine`](Self::engine).
    #[must_use]
    pub fn with_engine(self, engine: Option<Engine>) -> Self {
        Self { engine, ..self }
    }

    /// Returns the options with another [`fragment`](Self::fragment).
    #[must_use]
    pub fn with_fragment(self, fragment: Option<Fragment>) -> Self {
        Self { fragment, ..self }
    }

    /// Returns the options with another [`bias`](Self::bias).
    #[must_use]
    pub fn with_bias(self, bias: Bias) -> Self {
        Self { bias, ..self }
    }

    /// Returns the options with another copy bound
    /// ([`copies`](Self::copies)).
    #[must_use]
    pub fn with_copies(self, copies: Option<u32>) -> Self {
        Self { copies, ..self }
    }

    /// Returns the options with another copy bound for the forward search
    /// ([`forward_copies`](Self::forward_copies)).
    #[must_use]
    pub fn with_forward_copies(self, forward_copies: u32) -> Self {
        Self {
            forward_copies,
            ..self
        }
    }

    /// Returns the options with another [`memo_limit`](Self::memo_limit).
    #[must_use]
    pub fn with_memo_limit(self, memo_limit: u32) -> Self {
        Self { memo_limit, ..self }
    }

    /// Returns the options with another cadence of the net engines' test
    /// ([`test_period`](Self::test_period)).
    #[must_use]
    pub fn with_test_period(self, test_period: impl Into<Cadence>) -> Self {
        Self {
            test_period: test_period.into(),
            ..self
        }
    }

    /// Returns the options with another number of threads
    /// ([`jobs`](Self::jobs)).
    #[must_use]
    pub fn with_jobs(self, jobs: impl Into<Jobs>) -> Self {
        Self {
            jobs: jobs.into(),
            ..self
        }
    }

    /// Returns the options with another [`schedule`](Self::schedule).
    #[must_use]
    pub fn with_schedule(self, schedule: Schedule) -> Self {
        Self { schedule, ..self }
    }

    /// Returns the options with or without the [`check`](Self::check) of
    /// a proof.
    #[must_use]
    pub fn with_check(self, check: bool) -> Self {
        Self { check, ..self }
    }

    /// Returns the options with another [`pool`](Self::pool).
    ///
    /// Needs the cargo feature `parallel` (off by default).
    #[cfg(feature = "parallel")]
    #[must_use]
    pub fn with_pool(self, pool: Option<Pool>) -> Self {
        Self { pool, ..self }
    }

    /// Returns the copy bound as the engines count it. No bound is the
    /// largest, which no search reaches: every level visits a stable
    /// sequent and polls at it, and four billion levels take hours at the
    /// least.
    pub(crate) fn copy_bound(&self) -> u32 {
        self.copies.unwrap_or(u32::MAX)
    }

    /// Returns the threads the search may use: [`Jobs::count`].
    #[cfg(feature = "parallel")]
    pub(crate) fn threads(&self) -> usize {
        self.jobs.count()
    }

    /// Returns the most stable sequents a memo holds.
    pub(crate) fn memo_entries(&self) -> usize {
        usize::try_from(self.memo_limit).unwrap_or(usize::MAX)
    }
}

/// What a search returned: the verdict, and how it was reached.
///
/// # JSON
///
/// With the feature `serialize`, an outcome is written as one object
/// ([`wire`](crate::wire)) and read back from it. Its keys:
/// - `version`, and `deduxit`, the version of the crate that wrote it;
/// - `verdict`: `"proved"`, `"unprovable"` or `"unknown"`;
/// - `checked`, for a proved sequent;
/// - `refutation`, for an unprovable one, in the form [`Refutation`]
///   gives;
/// - `reason`, for an unknown one, in the form [`Reason`] gives, tagged
///   by `kind`;
/// - `fragment`, its name in the mode, as [`Fragment::name_in`] gives it;
/// - `mode`, its name;
/// - `engine` and `statistics`;
/// - for a proved sequent, the proof's own keys `sequent`, `nodes` and
///   `goal`, so that the outcome reads back as a [`Proof`];
/// - for an unprovable one, the [`Disproof`]'s `sequent` and `goal`.
///
/// The command's `prove --format json` writes it. Reading checks every
/// index the proof or the disproof names, not the proof or the
/// refutation: [`Proof::check`] and [`Disproof::check`] do that. An engine
/// name this version does not know reads as [`Engine::Unknown`], the
/// `deduxit` key is not read, `checked` is false where it is missing, and
/// [`net`](Self::net) is `None`.
///
#[cfg_attr(all(feature = "parse", feature = "serialize"), doc = "```")]
#[cfg_attr(not(all(feature = "parse", feature = "serialize")), doc = "```ignore")]
/// use deduxit::linear::{Mode, Outcome, Sequent, prove, search::Options};
///
/// let sequent: Sequent = "A |- A".parse()?;
/// let text = serde_json::to_string(&prove(&sequent, Mode::CLASSICAL, &Options::default())?)?;
/// let outcome: Outcome = serde_json::from_str(&text)?;
/// if let Some(proof) = outcome.verdict.proof() {
///     proof.check(outcome.mode)?;
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Engine, Options, prove};
/// use deduxit::linear::{Mode, Sequent};
///
/// let sequent: Sequent = "|- a, ~a".parse()?;
/// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
/// assert_eq!(outcome.verdict.name(), "proved");
/// assert!(outcome.checked);
/// assert_eq!(outcome.engine, Engine::Focus);
/// println!("{} units of work", outcome.statistics.work);
/// # Ok::<(), deduxit::Error>(())
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Outcome {
    /// The verdict, with the proof if there is one.
    pub verdict: Verdict,
    /// The fragment searched in: the detected one, or the one the options
    /// asserted.
    pub fragment: Fragment,
    /// The mode searched in.
    pub mode: Mode,
    /// The engine that ran.
    pub engine: Engine,
    /// What the search cost.
    pub statistics: Statistics,
    /// The proof net the proof was read off, when the net engine found
    /// one. `None` for the other engines and for any other verdict.
    pub net: Option<Box<ProofStructure>>,
    /// Whether the proof passed the checker before it was returned. It is
    /// false only where [`Options::check`] switched the check off, and for
    /// every verdict but a proof. In an outcome read from a document it is
    /// what the document says: [`Proof::check`] checks the proof.
    pub checked: bool,
}

/// What a search found: a proof, that there is none, or that it could not
/// tell.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::search::{Options, Verdict, prove};
/// use deduxit::linear::{Mode, Sequent};
///
/// let sequent: Sequent = "|- a, a".parse()?;
/// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
/// match &outcome.verdict {
///     Verdict::Proved(proof) => println!("{}", proof.derivation()?),
///     // The disproof prints why the sequent has no proof.
///     Verdict::Unprovable(d) => println!("{d}"),
///     Verdict::Unknown(reason) => println!("unknown: {reason}"),
/// }
/// assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
/// # Ok::<(), deduxit::Error>(())
/// ```
#[derive(Clone, Debug)]
pub enum Verdict {
    /// The sequent is provable, with a proof. It is boxed because a proof
    /// carries its forest.
    Proved(Box<Proof>),
    /// The sequent is not provable, with what can be said of why. The
    /// search was exhaustive, or a refuter found a refutation. It is boxed
    /// as a proof is.
    Unprovable(Box<Disproof>),
    /// The search stopped before it could decide, for the reason given.
    Unknown(Reason),
}

impl Verdict {
    /// The words of the verdicts, as [`Verdict::name`] gives them and the
    /// JSON form's `verdict` writes them.
    pub const NAMES: &'static [&'static str] = &["proved", "unprovable", "unknown"];

    /// Returns the verdict's word: `proved`, `unprovable` or `unknown`.
    pub const fn name(&self) -> &'static str {
        match self {
            Verdict::Proved(_) => "proved",
            Verdict::Unprovable(_) => "unprovable",
            Verdict::Unknown(_) => "unknown",
        }
    }

    /// Returns the proof, if the sequent was proved.
    pub fn proof(&self) -> Option<&Proof> {
        match self {
            Verdict::Proved(proof) => Some(proof),
            _ => None,
        }
    }
}

/// Why a search stopped without deciding.
///
/// In JSON (feature `serialize`), a reason is tagged by `kind`:
/// `{"kind": "stopped"}`, `{"kind": "recursion_limit", "depth": 2048}`,
/// `{"kind": "copy_bound", "copies": 3}`, `{"kind": "memory_limit",
/// "limit_bytes": 1073741824}`, `{"kind": "index_limit"}`, `{"kind":
/// "work_limit", "limit": 1000000}`, `{"kind": "unchecked",
/// "limit_bytes": 1073741824}`, `{"kind": "witness_depth", "depth": 64}`
/// or `{"kind": "instances", "instances": 65536}`. A reader refuses a
/// kind it does not know.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reason {
    /// The caller's stop condition fired: a time limit or an interruption.
    Stopped,
    /// The engine's recursion reached
    /// [`Limits::recursion_depth`](crate::Limits::recursion_depth).
    #[non_exhaustive]
    RecursionLimit {
        /// The recursion depth the limits allowed.
        depth: u32,
    },
    /// Every level up to the bound [`Options::copies`] set hit its bound
    /// on some branch. So a proof with more copies of a `?` formula per
    /// branch may exist.
    #[non_exhaustive]
    CopyBound {
        /// The copy bound.
        copies: u32,
    },
    /// The search would have held more than
    /// [`Limits::memory_bytes`](crate::Limits::memory_bytes).
    ///
    /// That is with its memo emptied, where it keeps one. Or there was no
    /// room left for a memo, the Horn engine's markings, or a proof's
    /// nodes.
    #[non_exhaustive]
    MemoryLimit {
        /// The memory bound, in bytes. It is `u64::MAX` where there was no
        /// bound and the allocator refused what the search asked for.
        limit_bytes: u64,
    },
    /// A structure of the search outgrew what its indices address.
    ///
    /// The limits: the proof arena at 2³¹ nodes, the additive path's at
    /// 2³² nodes, the count invariants at 2³² row entries, the Horn
    /// engine's markings at 2³², and a count of its tokens at 2³². Only a
    /// search without a memory bound gets this far, except for the tokens:
    /// a clause that adds thousands of them at each firing can pass the
    /// limit in a few hundred thousand markings.
    IndexLimit,
    /// The search did the most work [`Limits::work`](crate::Limits::work)
    /// allows, or the check of the proof it found would have done more.
    #[non_exhaustive]
    WorkLimit {
        /// The bound on work.
        limit: u64,
    },
    /// The search found a proof whose check would have held more than
    /// [`Limits::memory_bytes`](crate::Limits::memory_bytes). No proof is
    /// returned that has not passed the checker.
    #[non_exhaustive]
    Unchecked {
        /// The memory bound, in bytes.
        limit_bytes: u64,
    },
    /// A first-order search cut a branch where a metavariable would have
    /// been bound to a term deeper than [`Options::witness_depth`], and
    /// found no proof.
    #[non_exhaustive]
    WitnessDepth {
        /// The witness depth.
        depth: u32,
    },
    /// A first-order search cut a branch where it would have held more
    /// instances of quantified formulas than [`Options::instances`], and
    /// found no proof.
    #[non_exhaustive]
    Instances {
        /// The bound on instances.
        instances: u32,
    },
}

impl Reason {
    /// The words of the reasons, as [`Reason::name`] gives them and the
    /// JSON form's `kind` writes them.
    pub const NAMES: &'static [&'static str] = &[
        "stopped",
        "recursion_limit",
        "copy_bound",
        "memory_limit",
        "index_limit",
        "work_limit",
        "unchecked",
        "witness_depth",
        "instances",
    ];

    /// Returns the reason's word, its `kind` in the JSON form.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Stopped => "stopped",
            Self::RecursionLimit { .. } => "recursion_limit",
            Self::CopyBound { .. } => "copy_bound",
            Self::MemoryLimit { .. } => "memory_limit",
            Self::IndexLimit => "index_limit",
            Self::WorkLimit { .. } => "work_limit",
            Self::Unchecked { .. } => "unchecked",
            Self::WitnessDepth { .. } => "witness_depth",
            Self::Instances { .. } => "instances",
        }
    }

    /// Returns the reason a search under the options gives up with, given
    /// the reason one of its searches gave.
    ///
    /// A copy bound is [`Options::copies`], the least bound every search
    /// ran within. A memory limit is [`Limits::memory_bytes`], of which a
    /// search may have had a part.
    pub(crate) fn as_set(self, options: &Options, limits: &Limits) -> Self {
        match self {
            Self::CopyBound { .. } => Self::CopyBound {
                copies: options.copy_bound(),
            },
            Self::MemoryLimit { limit_bytes: bytes } => Self::MemoryLimit {
                limit_bytes: limits.memory_bytes.unwrap_or(bytes),
            },
            reason => reason,
        }
    }

    /// Returns the settings key whose bound the search reached, which a
    /// caller raises to search further.
    ///
    /// It is `None` for what no setting lifts: the stop, the indices, and
    /// the allocator's refusal where there was no memory bound.
    pub const fn setting(&self) -> Option<&'static str> {
        match self {
            Self::Stopped
            | Self::IndexLimit
            | Self::MemoryLimit {
                limit_bytes: u64::MAX,
            } => None,
            Self::RecursionLimit { .. } => Some("limits.recursion_depth"),
            Self::CopyBound { .. } => Some("search.copies"),
            Self::MemoryLimit { .. } | Self::Unchecked { .. } => Some("limits.memory_bytes"),
            Self::WorkLimit { .. } => Some("limits.work"),
            Self::WitnessDepth { .. } => Some("search.witness_depth"),
            Self::Instances { .. } => Some("search.instances"),
        }
    }
}

impl Display for Reason {
    /// Writes the reason as a phrase, such as `the copy bound of 3 was
    /// reached`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            Reason::Stopped => f.write_str("the search was stopped"),
            Reason::RecursionLimit { depth } => {
                write!(f, "the recursion limit of {depth} was reached")
            }
            Reason::CopyBound { copies } => {
                write!(f, "the copy bound of {copies} was reached")
            }
            Reason::MemoryLimit {
                limit_bytes: u64::MAX,
            } => f.write_str("the memory the allocator would give was used up"),
            Reason::MemoryLimit { limit_bytes } => {
                write!(f, "the memory limit of {} was reached", Bytes(*limit_bytes))
            }
            Reason::IndexLimit => f.write_str("the search outgrew what its indices address"),
            Reason::WorkLimit { limit } => write!(f, "the work limit of {limit} was reached"),
            Reason::Unchecked { limit_bytes } => write!(
                f,
                "a proof was found, but its check would hold more than the memory limit of {}",
                Bytes(*limit_bytes)
            ),
            Reason::WitnessDepth { depth } => {
                write!(f, "the witness depth of {depth} was reached")
            }
            Reason::Instances { instances } => {
                write!(f, "the bound of {instances} instances was reached")
            }
        }
    }
}

/// What a search cost.
///
/// [`Engine::counters`] says which counters an engine fills, and what
/// each counts for it. Every engine counts `work`. The counters an engine
/// does not list stay zero.
///
/// In JSON (feature `serialize`), it is an object of the counters by
/// name. A missing one reads back as zero. The first-order counters are
/// written only where they are not zero, so a propositional search's
/// object has no first-order keys.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default))]
#[non_exhaustive]
pub struct Statistics {
    /// The nodes of the search. They are, by engine:
    /// - the focused engines: the stable sequents visited, memo hits
    ///   included;
    /// - the net engine: the literals it chose a partner for;
    /// - the additive path: the pairs of subformulas it decided;
    /// - the Horn engine: the markings it reached, the initial one
    ///   included, with those its backward search reached from the goal
    ///   (in affine mode, the elements it computed backward).
    ///
    /// [`Engine::counters`] lists every engine's.
    pub nodes: u64,
    /// The visits answered from the memo. For the focused engines, a
    /// failure that waits on an open ancestor answers some too. For the
    /// Horn engine, the markings it had kept already, in either direction,
    /// and in affine mode the elements an element kept already covers.
    pub memo_hits: u64,
    /// The most stable sequents the memo held at once.
    ///
    /// - On a pool, whose memo is shards each emptied by itself, it is the
    ///   sum of the shards' peaks, which bounds it from above.
    /// - Of the default bias's two searches, where they ran together, it
    ///   is the two memos' together. Where they took turns from their
    ///   start, it is the most of one turn.
    /// - For the additive path, it is the pairs of subformulas its memo
    ///   held at once.
    /// - For the Horn engine, it is the markings it kept in either
    ///   direction, or in affine mode the elements.
    ///
    /// It is a `u64` on every target, as every counter is.
    pub memo_entries: u64,
    /// The context splits examined for `⊗` and Mix. The counts reject most
    /// of them.
    pub splits: u64,
    /// The axiom links the net engine tried. Each was made, and taken back
    /// again unless it is part of the net found.
    pub links: u64,
    /// The exact acyclicity tests the net engine ran.
    pub tests: u64,
    /// The copy bound the last level of the focused engine's deepening
    /// began under. So it says how far a search without a bound got before
    /// it was stopped.
    ///
    /// It is that of the search that decided, else of the one under
    /// [`Options::copies`] (the backward one of the default bias's two).
    /// It is zero without exponentials and for the other engines.
    pub copies: u32,
    /// The copy bound the last level of the forward search of
    /// [`Bias::Auto`] began under. That search runs within
    /// [`Options::forward_copies`] on a Horn program. It is zero where the
    /// forward search did not run.
    pub forward_copies: u32,
    /// The units of work the search did, in its engine's unit (each
    /// [`Engine`] variant says which).
    ///
    /// Where another engine took the goal over at a limit, or the inverse
    /// method took turns beside the engine, it is every engine's units
    /// together. Where every search runs on the calling thread (one
    /// thread, and the default bias's two searches in
    /// [`Schedule::Turns`]), it is what the [`Progress::work`] of the polls
    /// adds up to. Other threads' units come into [`Progress::done`] only.
    pub work: u64,
    /// The unifications of two literals the focused engines tried on a
    /// first-order sequent, at an identity or against a copy of the
    /// unrestricted zone, whether they unified or not.
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "is_zero"))]
    pub unifications: u64,
    /// The bindings of a metavariable the focused engines made on a
    /// first-order sequent. A binding that an undo took back and the
    /// search made again counts again.
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "is_zero"))]
    pub bindings: u64,
}

/// Returns whether a counter is zero, which its JSON then leaves out.
#[cfg(feature = "serialize")]
#[cfg_attr(
    target_pointer_width = "64",
    expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "serde's skip_serializing_if passes a reference"
    )
)]
fn is_zero(n: &u64) -> bool {
    *n == 0
}

impl Statistics {
    /// Adds the counters of another search, one that ran beside this one
    /// or after it, to these.
    ///
    /// The work done adds up. The memo's peak and the copy bounds reached
    /// are the larger of the two, since each search had a memo and a
    /// deepening of its own.
    pub fn add(&mut self, other: &Statistics) {
        self.add_run(other);
        self.memo_hits += other.memo_hits;
        self.memo_entries = self.memo_entries.max(other.memo_entries);
        self.forward_copies = self.forward_copies.max(other.forward_copies);
        self.work += other.work;
    }

    /// Adds another engine's counters to these, except the memo's. Those
    /// describe a table, not a run, and a parallel search reads them off
    /// the one table its workers share.
    pub(crate) fn add_run(&mut self, other: &Statistics) {
        self.nodes += other.nodes;
        self.splits += other.splits;
        self.links += other.links;
        self.tests += other.tests;
        self.copies = self.copies.max(other.copies);
        self.unifications += other.unifications;
        self.bindings += other.bindings;
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::linear::sequents::Atom;

    /// A forest with cut formulas is searched on a cut-free forest of the
    /// goal's formulas, by every engine that takes the goal. No engine
    /// sees a cut formula. Every proof found is cut-free, and checks
    /// against the goal, which may hold occurrences of the cut formulas.
    /// A sequent with cut formulas is proved as its conclusion.
    #[cfg(feature = "parse")]
    #[test]
    fn a_forest_with_cuts_is_searched_without_them() {
        let mut sequent: Sequent = "A, A -o B |- B".parse().unwrap();
        sequent.add_cut("|- A -o B".parse().unwrap()).unwrap();
        // 0 ~A, 1 A ⊗ ~B, 2 A, 3 ~B, 4 B, then 5 ~A ⅋ B and its dual 8.
        let forest = Forest::new(&sequent).unwrap();
        let cut_free = |proof: &Proof| !proof.nodes().iter().any(|n| matches!(n, Node::Cut(..)));
        let limits = Limits::default();
        for mode in [Mode::CLASSICAL, Mode::INTUITIONISTIC] {
            let focused = if mode.intuitionistic {
                Engine::TwoSided
            } else {
                Engine::Focus
            };
            for engine in [None, Some(focused), Some(Engine::Net)] {
                let options = Options::default().with_engine(engine);
                let outcome =
                    prove_goal(Goal::conclusion(&forest), mode, &options, &limits, |_| {
                        false
                    })
                    .unwrap();
                let proof = outcome.verdict.proof().expect("provable");
                assert!(cut_free(proof) && proof.goal().is_none());
                assert_eq!(proof.sequent(), &sequent);
                assert_eq!(proof.check(mode), Ok(()));
            }
            let members = [Member::new(1), Member::new(5)];
            let goal = Goal::new(&forest, &members).unwrap();
            let outcome = prove_goal(goal, mode, &Options::default(), &limits, |_| false).unwrap();
            let proof = outcome.verdict.proof().expect("A ⊸ B ⊢ A ⊸ B");
            assert!(cut_free(proof));
            assert_eq!(proof.goal(), Some(&members[..]));
            assert_eq!(proof.check(mode), Ok(()));
            // The dual and the goal: ⊢ A ⊗ ~B, B has no proof.
            let members = [Member::new(8), Member::new(4)];
            let goal = Goal::new(&forest, &members).unwrap();
            let outcome = prove_goal(goal, mode, &Options::default(), &limits, |_| false).unwrap();
            assert!(matches!(outcome.verdict, Verdict::Unprovable(_)), "{mode}");
        }
    }

    /// Parses `input`.
    fn sequent(input: &str) -> Sequent {
        input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"))
    }

    /// An outcome is checked exactly when it is a proof and the options
    /// ask for the check. A cadence of links converts from a number.
    #[test]
    fn checked_when_proved_and_asked() {
        let tautology = sequent("|- a, ~a");
        let proved = prove(&tautology, Mode::CLASSICAL, &Options::default()).unwrap();
        assert!(proved.checked);
        let unchecked = Options::default().with_check(false);
        assert!(
            !prove(&tautology, Mode::CLASSICAL, &unchecked)
                .unwrap()
                .checked
        );
        let refuted = prove(&sequent("|- a, a"), Mode::CLASSICAL, &Options::default()).unwrap();
        assert!(matches!(refuted.verdict, Verdict::Unprovable(_)) && !refuted.checked);
        assert_eq!(Cadence::from(7), Cadence::Every(7));
    }

    /// Every counter an engine lists is a field of the statistics' JSON
    /// form, once.
    #[cfg(feature = "serialize")]
    #[test]
    fn counters_are_fields() {
        // Every counter is set, since the first-order ones are written only
        // when they are not zero.
        let written = serde_json::to_value(Statistics {
            unifications: 1,
            bindings: 1,
            ..Statistics::default()
        })
        .unwrap();
        for &engine in Engine::ALL {
            let keys: Vec<&str> = engine.counters().iter().map(|c| c.key).collect();
            for key in &keys {
                assert!(written.get(key).is_some(), "{engine}: {key}");
            }
            let mut unique = keys.clone();
            unique.sort_unstable();
            unique.dedup();
            assert_eq!(unique.len(), keys.len(), "{engine}");
        }
    }

    /// Every reason has its word, listed in `NAMES` in its order, and in
    /// JSON its `kind` is that word. The same holds for the verdicts'
    /// words.
    #[test]
    fn reasons_and_verdicts_are_named() {
        let reasons = [
            Reason::Stopped,
            Reason::RecursionLimit { depth: 1 },
            Reason::CopyBound { copies: 1 },
            Reason::MemoryLimit { limit_bytes: 1 },
            Reason::IndexLimit,
            Reason::WorkLimit { limit: 1 },
            Reason::Unchecked { limit_bytes: 1 },
            Reason::WitnessDepth { depth: 1 },
            Reason::Instances { instances: 1 },
        ];
        // No wildcard: a new reason fails to compile here until listed.
        let at = |reason: &Reason| match reason {
            Reason::Stopped => 0,
            Reason::RecursionLimit { .. } => 1,
            Reason::CopyBound { .. } => 2,
            Reason::MemoryLimit { .. } => 3,
            Reason::IndexLimit => 4,
            Reason::WorkLimit { .. } => 5,
            Reason::Unchecked { .. } => 6,
            Reason::WitnessDepth { .. } => 7,
            Reason::Instances { .. } => 8,
        };
        assert_eq!(reasons.len(), Reason::NAMES.len());
        for (i, reason) in reasons.iter().enumerate() {
            assert_eq!(at(reason), i);
            assert_eq!(reason.name(), Reason::NAMES[i]);
            #[cfg(feature = "serialize")]
            assert_eq!(serde_json::to_value(reason).unwrap()["kind"], reason.name());
        }
        // The verdicts likewise, each written as its word.
        let verdict_at = |verdict: &Verdict| match verdict {
            Verdict::Proved(_) => 0,
            Verdict::Unprovable(_) => 1,
            Verdict::Unknown(_) => 2,
        };
        let bounded = Options::default()
            .with_engine(Some(Engine::Focus))
            .with_bias(Bias::Rarer)
            .with_copies(Some(0));
        let mut seen = Vec::new();
        for (text, options) in [
            ("a |- a", Options::default()),
            ("a |- b", Options::default()),
            ("!a |- a * a", bounded),
        ] {
            let outcome = prove(&sequent(text), Mode::CLASSICAL, &options).unwrap();
            let i = verdict_at(&outcome.verdict);
            assert_eq!(outcome.verdict.name(), Verdict::NAMES[i]);
            #[cfg(feature = "serialize")]
            assert_eq!(
                serde_json::to_value(&outcome).unwrap()["verdict"],
                outcome.verdict.name()
            );
            seen.push(i);
        }
        assert_eq!((seen, Verdict::NAMES.len()), (vec![0, 1, 2], 3));
        // And the refutations, each its JSON `kind`.
        let refutations = [
            Refutation::Exhausted,
            Refutation::Unbalanced(Unbalanced {
                atom: Atom::new(0),
                least: 1,
                most: 1,
            }),
            Refutation::OneSided(OneSided {
                atom: Atom::new(0),
                least: 1,
                most: 1,
                copied: crate::linear::occurrences::Sign::Atom,
            }),
            Refutation::Equation(Equation {
                formulas: 1,
                needed: 2,
                tensors: 0,
                pars: 0,
                ones: 0,
                bottoms: 0,
                mix: false,
            }),
            Refutation::StateEquation(StateEquation {
                atoms: Vec::new(),
                clauses: Vec::new(),
                dropped: Vec::new(),
            }),
            Refutation::Classical(Classical {
                assignment: Vec::new(),
            }),
            Refutation::Saturated(Saturated::new(Vec::new(), Vec::new())),
            Refutation::UnbalancedSymbol(UnbalancedSymbol {
                symbol: crate::linear::sequents::Symbol::new(0),
                least: 1,
                most: 1,
            }),
            Refutation::OneSidedSymbol(OneSidedSymbol {
                symbol: crate::linear::sequents::Symbol::new(0),
                least: 1,
                most: 1,
                copied: crate::linear::occurrences::Sign::Atom,
            }),
            Refutation::Basis(Basis::new(
                crate::linear::occurrences::Sign::Atom,
                Vec::new(),
                Vec::new(),
            )),
        ];
        let refutation_at = |refutation: &Refutation| match refutation {
            Refutation::Exhausted => 0,
            Refutation::Unbalanced(_) => 1,
            Refutation::OneSided(_) => 2,
            Refutation::Equation(_) => 3,
            Refutation::StateEquation(_) => 4,
            Refutation::Classical(_) => 5,
            Refutation::Saturated(_) => 6,
            Refutation::UnbalancedSymbol(_) => 7,
            Refutation::OneSidedSymbol(_) => 8,
            Refutation::Basis(_) => 9,
        };
        assert_eq!(refutations.len(), Refutation::NAMES.len());
        for (i, refutation) in refutations.iter().enumerate() {
            assert_eq!(refutation_at(refutation), i);
            assert_eq!(refutation.name(), Refutation::NAMES[i]);
            #[cfg(feature = "serialize")]
            assert_eq!(
                serde_json::to_value(refutation).unwrap()["kind"],
                refutation.name()
            );
        }
    }

    /// The listed names are the names written, in order, and each reads
    /// back as its value.
    #[test]
    fn names_are_listed() {
        // Every variant has an arm, with no wildcard, and its place in the
        // list. A new variant fails to compile here until it has an arm,
        // and the lengths differ until it is listed.
        let engine_at = |engine| match engine {
            Engine::Focus => 0,
            Engine::Net => 1,
            Engine::TwoSided => 2,
            Engine::Additive => 3,
            Engine::Horn => 4,
            Engine::Essential => 5,
            Engine::Inverse => 6,
            // Not listed: no search runs it.
            Engine::Unknown => usize::MAX,
        };
        let bias_at = |bias| match bias {
            Bias::Auto => 0,
            Bias::Rarer => 1,
            Bias::Factors => 2,
        };
        assert_eq!(Engine::ALL.len(), 7);
        assert_eq!(Bias::ALL.len(), 3);
        for (i, &engine) in Engine::ALL.iter().enumerate() {
            assert_eq!(engine_at(engine), i);
        }
        for (i, &bias) in Bias::ALL.iter().enumerate() {
            assert_eq!(bias_at(bias), i);
        }
        let engines: Vec<_> = Engine::ALL.iter().map(|e| e.name()).collect();
        let biases: Vec<_> = Bias::ALL.iter().map(|b| b.name()).collect();
        assert_eq!(engines, Engine::NAMES);
        assert_eq!(biases, Bias::NAMES);
        for &engine in Engine::ALL {
            assert_eq!(engine.to_string().parse::<Engine>().unwrap(), engine);
        }
        for &bias in Bias::ALL {
            assert_eq!(bias.to_string().parse::<Bias>().unwrap(), bias);
        }
    }

    /// An engine's proof that the checker rejects is a defect, never a
    /// verdict. The proof here has a weakening in classical mode, as an
    /// affine search would leave it.
    #[test]
    fn a_rejected_proof_is_an_error() {
        let s = sequent("|- a, b, ~a");
        let forest = Forest::new(&s).unwrap();
        let (m, n) = (Member::new, NodeId::new);
        let nodes = vec![Node::Ax(m(0), m(2)), Node::Weaken(m(1), n(0))];
        let proof = Proof::new(forest.clone(), nodes, n(1)).unwrap();
        let goal = Concluding {
            forest: &forest,
            occurrences: forest.roots(),
            fragment: s.fragment(),
            mode: Mode::CLASSICAL,
            roots: true,
        };
        let verdict = conclude(
            Ok(Some(proof)),
            None,
            goal,
            &[],
            &Options::default(),
            &Limits::default(),
            &memory::Account::new(None),
            &mut |_| false,
        );
        assert!(matches!(verdict, Err(Error::Rejected(_))), "{verdict:?}");
    }

    /// A proof whose check a bound gives up is not returned. The verdict
    /// is unknown, by the bound that refused the check. For memory that is
    /// the bound as the limits set it, of which the check had what the
    /// input left.
    #[test]
    fn a_refused_check_is_unknown() {
        let refusals = [
            Refusal::Stopped {
                phase: Phase::Check,
            },
            Refusal::Memory {
                phase: Phase::Check,
                limit_bytes: 48,
                needed_bytes: None,
            },
            Refusal::Work { limit: 1 },
        ];
        let limits = Limits::default().with_memory_bytes(Some(64));
        let reasons = refusals.map(|r| unchecked(r, &limits).unwrap());
        assert_eq!(
            reasons,
            [
                Reason::Stopped,
                Reason::Unchecked { limit_bytes: 64 },
                Reason::WorkLimit { limit: 1 }
            ]
        );
        // The check counts its work too, so a proof the search finds within
        // a bound of one unit is unknown.
        let work = Limits::default().with_work(Some(1));
        let outcome = prove_within(
            &sequent("a, b |- a * b"),
            Mode::CLASSICAL,
            &Options::default(),
            &work,
            |_| false,
        )
        .unwrap();
        assert!(
            matches!(
                outcome.verdict,
                Verdict::Unknown(Reason::WorkLimit { limit: 1 })
            ),
            "{:?}",
            outcome.verdict
        );
        assert!(!outcome.checked);
    }

    /// A proof the search finds within the memory bound, but whose check
    /// would need more, is unknown by that bound: neither a proof nor an
    /// error.
    ///
    /// The Horn engine holds a counter's firing sequence of 3 000 tokens in
    /// less memory than the check of its proof holds (a state per firing,
    /// each waiting for its reader). So the first bound, upwards from
    /// 512 KiB, at which the search no longer ends at the bound is one
    /// that the check passes.
    #[test]
    fn a_check_past_the_memory_bound_is_unknown() {
        let counter = sequent(&format!(
            "!(a -o a * b), a |- a * {}",
            vec!["b"; 3000].join(" * ")
        ));
        let first = (16..64u64).map(|k| k << 15).find_map(|bytes| {
            let limits = Limits::default().with_memory_bytes(Some(bytes));
            let outcome = prove_within(
                &counter,
                Mode::INTUITIONISTIC,
                &Options::default(),
                &limits,
                |_| false,
            )
            .unwrap();
            match outcome.verdict {
                Verdict::Unknown(Reason::MemoryLimit { .. }) => None,
                verdict => Some((bytes, verdict, outcome.checked)),
            }
        });
        assert!(
            matches!(
                first,
                Some((bytes, Verdict::Unknown(Reason::Unchecked { limit_bytes }), false))
                    if limit_bytes == bytes
            ),
            "{first:?}"
        );
    }

    /// The memory bound counts the input too: the forest with its
    /// sequent.
    ///
    /// `⊢ a, ~a` with an atom's name of a mebibyte, which the search itself
    /// never copies, ends at a bound one byte short of the input, at its
    /// first stable sequent. That holds through the front door and through
    /// the race of the command's default alike. With half the input more,
    /// it proves. So the input is counted once, and the proof's check has
    /// the room beside it.
    #[test]
    fn the_memory_bound_holds_the_input() {
        let name = "a".repeat(1 << 20);
        let s = sequent(&format!("|- {name}, ~{name}"));
        let forest = Forest::new(&s).unwrap();
        let goal = Goal::conclusion(&forest);
        let input = forest.held_bytes() as u64;
        assert!(input > 1 << 20);
        let options = Options::default().with_engine(Some(Engine::Focus));
        for (bytes, proved) in [(input - 1, false), (input + input / 2, true)] {
            let limits = Limits::default().with_memory_bytes(Some(bytes));
            let alone = prove_goal(goal, Mode::CLASSICAL, &options, &limits, |_| false);
            #[cfg(feature = "parallel")]
            let raced = race(
                goal,
                Mode::CLASSICAL,
                &options,
                &limits,
                3,
                |_| true,
                |_| false,
            );
            #[cfg(not(feature = "parallel"))]
            let raced = prove_goal(goal, Mode::CLASSICAL, &options, &limits, |_| false);
            for outcome in [alone, raced] {
                let verdict = outcome.unwrap().verdict;
                let expected = if proved {
                    matches!(verdict, Verdict::Proved(_))
                } else {
                    matches!(verdict, Verdict::Unknown(Reason::MemoryLimit { limit_bytes })
                        if limit_bytes == bytes)
                };
                let shown = match &verdict {
                    Verdict::Unknown(reason) => format!("{reason:?}"),
                    Verdict::Proved(_) => "proved".to_string(),
                    Verdict::Unprovable(_) => "unprovable".to_string(),
                };
                assert!(expected, "under {bytes} bytes: {shown}");
            }
        }
    }

    /// Every poll tells the stop the work done since the last and in all,
    /// in the engine's units. The bound on work ends a search there, with
    /// an unknown verdict that names the bound.
    #[test]
    fn the_search_counts_its_work() {
        let partition = crate::linear::families::FAMILIES
            .iter()
            .find(|f| f.name == "partition-no")
            .unwrap()
            .instance(3, 0)
            .unwrap();
        let atoms: Vec<String> = (0..8).map(|i| format!("a{i}")).collect();
        let tensor = sequent(&format!("{} |- {}", atoms.join(", "), atoms.join(" * ")));
        for (sequent, mode, engine) in [
            (&partition.sequent, partition.mode, Engine::Focus),
            (&tensor, Mode::CLASSICAL, Engine::Net),
        ] {
            // The search's work alone, without the classical refuter's.
            let options = Options::default()
                .with_engine(Some(engine))
                .with_classical_work(0);
            let (mut sum, mut last, mut polls) = (0, 0, 0);
            let outcome = prove_within(sequent, mode, &options, &Limits::default(), |progress| {
                assert_eq!(progress.phase, Phase::Search);
                sum += progress.work;
                last = progress.done;
                polls += 1;
                false
            })
            .unwrap();
            assert!(!matches!(outcome.verdict, Verdict::Unknown(_)), "{engine}");
            assert!(
                polls > 1 && last > 1 && sum == last,
                "{engine}: {sum} {last}"
            );
            assert_eq!(outcome.statistics.work, last, "{engine}");
            let bound = Limits::default().with_work(Some(last / 2));
            let mut told = 0;
            let outcome = prove_within(sequent, mode, &options, &bound, |progress| {
                told += progress.work;
                false
            })
            .unwrap();
            assert!(
                matches!(outcome.verdict, Verdict::Unknown(Reason::WorkLimit { limit }) if limit == last / 2),
                "{engine}: {:?}",
                outcome.verdict
            );
            // The poll that passes the bound is told too.
            assert_eq!(outcome.statistics.work, told, "{engine}");
        }
    }

    /// A turn tells the caller the units of every poll, including the one
    /// that ends it.
    #[test]
    fn a_turn_tells_the_caller_every_poll() {
        let mut told = 0;
        let mut caller = |units| {
            told += units;
            false
        };
        {
            let mut turn = Stop::Turn(&mut caller, 5);
            assert!(!turn.fired(3));
            assert!(turn.fired(3), "the turn is over");
        }
        assert_eq!(told, 6);
    }

    /// Beside the default bias's second search, which reads the shared
    /// count, the bound on work is late by a few batches at most. The
    /// calling thread adds its units in batches too. If it kept them to
    /// the end, the second search would run a whole slice past the bound.
    #[cfg(feature = "parallel")]
    #[test]
    fn the_work_bound_holds_beside_the_second_search() {
        let tokens = vec!["a"; 32].join(", ");
        let s = sequent(&format!(
            "!(a * a -o b), !(b * b -o c), !(c * c -o d), !(d * d -o e), !(e * e -o f), \
             !(a -o x), !(x -o y), !(y -o a), !(a -o u), !(u -o v), !(v -o a), !(b -o w), \
             !(w -o b), !(x -o u), {tokens} |- f * a"
        ));
        let options = Options::default()
            .with_engine(Some(Engine::Focus))
            .with_copies(None)
            .with_jobs(1);
        let limit = 300_000;
        let limits = Limits::default().with_work(Some(limit));
        let outcome = prove_within(&s, Mode::CLASSICAL, &options, &limits, |_| false).unwrap();
        assert!(
            matches!(outcome.verdict, Verdict::Unknown(Reason::WorkLimit { .. })),
            "{:?}",
            outcome.verdict
        );
        assert!(
            outcome.statistics.work < limit + 4 * Work::BATCH,
            "{} units under a bound of {limit}",
            outcome.statistics.work
        );
    }

    /// The race answers with the side that decided, whichever it is. The
    /// caller's stop ends one side at its first poll (the pool's thread is
    /// told by its name), and the other side proves the sequent.
    #[cfg(feature = "parallel")]
    #[test]
    fn the_race_answers_with_the_side_that_decided() {
        let s = sequent("!(a -o b), !(b -o c), a |- c * !(d -o d)");
        let forest = Forest::new(&s).unwrap();
        let goal = Goal::conclusion(&forest);
        for pool_stops in [false, true] {
            let outcome = race(
                goal,
                Mode::CLASSICAL,
                &Options::default(),
                &Limits::default(),
                3,
                |_| true,
                |_| (std::thread::current().name() == Some("deduxit-race")) == pool_stops,
            )
            .unwrap();
            assert!(
                matches!(outcome.verdict, Verdict::Proved(_)),
                "the pool stopped: {pool_stops}, {:?}",
                outcome.verdict
            );
        }
    }

    /// Where the engine of a row with turns runs past its head start, the
    /// inverse method takes its turn, and its decision answers. Where the
    /// turn does not decide, the engine answers as it does alone, with its
    /// own counters and the turn's work added.
    ///
    /// The head start and the turn are set low on this thread, so that
    /// small goals reach them. Under Mix, the focused engine searches the
    /// partitions of `mix(8)`'s context for a second, and the two-sided
    /// engine takes some hundred units on the intuitionistic goal. The
    /// inverse method refutes both at once. At the head start and share of
    /// every search, it refutes a goal that the two-sided engine, deepening
    /// its copy bound, would leave to the time limit.
    #[test]
    fn the_inverse_method_takes_its_turn() {
        let options = Options::default().with_jobs(1);
        let intuitionistic = sequent("!(a -o b & c), a |- b * c");
        let alone = prove(&intuitionistic, Mode::INTUITIONISTIC, &options).unwrap();
        assert_eq!(alone.engine, Engine::TwoSided);
        TURN.with(|t| t.set((16, 0)));
        for (s, mode) in [
            (crate::linear::families::mix(8), Mode::CLASSICAL.with_mix()),
            (intuitionistic.clone(), Mode::INTUITIONISTIC),
        ] {
            let outcome = prove(&s, mode, &options).unwrap();
            assert_eq!(outcome.engine, Engine::Inverse, "{mode}");
            assert!(
                matches!(outcome.verdict, Verdict::Unprovable(_)),
                "{:?}",
                outcome.verdict
            );
        }
        // Turns that end before they decide.
        TURN.with(|t| t.set((16, u64::MAX)));
        let turned = prove(&intuitionistic, Mode::INTUITIONISTIC, &options).unwrap();
        TURN.with(|t| t.set((PROBE_AFTER, TURN_SHARE)));
        assert_eq!(turned.engine, Engine::TwoSided);
        assert_eq!(
            format!("{:?}", turned.verdict),
            format!("{:?}", alone.verdict)
        );
        let counters = |s: &Statistics| (s.nodes, s.splits, s.memo_hits, s.memo_entries);
        assert_eq!(counters(&turned.statistics), counters(&alone.statistics));
        assert!(turned.statistics.work > alone.statistics.work);
        // With the head start and share of every search: the two-sided
        // engine, deepening without a copy bound as the command does,
        // leaves this goal to the time limit. A turn refutes it once the
        // engine's work passes the head start.
        let saturating = sequent("!(a -o a * a * a), !(a -o a), a |- a * (a + 0)");
        let deepening = options.clone().with_copies(None);
        let outcome = prove(&saturating, Mode::INTUITIONISTIC, &deepening).unwrap();
        assert_eq!(outcome.engine, Engine::Inverse);
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
    }

    /// The caller's stop ends both sides of the race, whether or not the
    /// other has decided. Asked from the pool too, it stops a search that
    /// would prove the sequent, and the race answers unknown.
    #[cfg(feature = "parallel")]
    #[test]
    fn the_caller_s_stop_ends_both_sides_of_the_race() {
        let s = crate::linear::families::mix(5);
        let forest = Forest::new(&s).unwrap();
        let outcome = race(
            Goal::conclusion(&forest),
            Mode::CLASSICAL.with_mix(),
            &Options::default(),
            &Limits::default(),
            3,
            |_| true,
            |_| true,
        )
        .unwrap();
        assert!(
            matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)),
            "{:?}",
            outcome.verdict
        );
    }

    /// A panic on one side of the race stops the other side, and then
    /// reaches the caller. Here the pool's stop panics, and the single
    /// search, which would take minutes, ends at its next poll.
    #[cfg(feature = "parallel")]
    #[test]
    fn a_panic_on_one_side_of_the_race_stops_the_other() {
        let (sender, ended) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let s = crate::linear::families::mix(11);
            let forest = Forest::new(&s).unwrap();
            let goal = Goal::conclusion(&forest);
            let panicked = std::panic::catch_unwind(|| {
                race(
                    goal,
                    Mode::CLASSICAL.with_mix(),
                    &Options::default(),
                    &Limits::default(),
                    3,
                    |_| true,
                    |_| {
                        let pool = std::thread::current().name() == Some("deduxit-race");
                        assert!(!pool, "the pool's stop panics");
                        false
                    },
                )
            });
            sender.send(panicked.is_err()).unwrap();
        });
        let panicked = ended.recv_timeout(std::time::Duration::from_secs(20));
        assert_eq!(panicked, Ok(true));
    }

    /// The race counts every thread. Below three, it asks nothing and
    /// searches as one call with that many threads would. From three, it
    /// starts the pool once, when asked to, and answers as one thread
    /// does.
    #[cfg(feature = "parallel")]
    #[test]
    fn the_race_counts_every_thread() {
        let s = sequent("!(a -o b), !(b -o c), a |- c * !(d -o d)");
        let forest = Forest::new(&s).unwrap();
        let goal = Goal::conclusion(&forest);
        let (options, limits) = (Options::default(), Limits::default());
        for threads in [1, 2] {
            let outcome = race(
                goal,
                Mode::CLASSICAL,
                &options,
                &limits,
                threads,
                |_| panic!("no pool is added below three threads"),
                |_| false,
            )
            .unwrap();
            assert!(outcome.verdict.proof().is_some(), "{threads}");
        }
        let alone = prove(&s, Mode::CLASSICAL, &options).unwrap();
        let mut asked = 0;
        let raced = race(
            goal,
            Mode::CLASSICAL,
            &options,
            &limits,
            3,
            |_| {
                asked += 1;
                true
            },
            |_| false,
        )
        .unwrap();
        assert_eq!(asked, 1);
        assert!(raced.verdict.proof().is_some());
        assert_eq!(raced.engine, alone.engine);
    }

    /// The front door's plain parts:
    /// - a sequent past the bound on occurrences is refused before
    ///   anything unfolds;
    /// - the engines that search on a pool are the focused engines and the
    ///   net engine;
    /// - the default options are their documented constants;
    /// - each refutation says its counts in words, with the singular, a
    ///   range, the minus sign and Mix's inequality where they apply.
    #[test]
    fn the_front_door_s_plain_parts() {
        let tight = Limits::default().with_occurrences(Some(2));
        let error = prove_within(
            &sequent("|- a, ~a, b"),
            Mode::CLASSICAL,
            &Options::default(),
            &tight,
            |_| false,
        )
        .unwrap_err();
        assert!(
            matches!(error, Error::Refused(Refusal::Occurrences { limit: 2, .. })),
            "{error}"
        );
        let parallel: Vec<bool> = Engine::ALL.iter().map(|e| e.parallel()).collect();
        assert_eq!(parallel, [true, true, true, false, false, false, false]);
        let defaults = Options::default();
        assert_eq!(
            (
                defaults.copies,
                defaults.forward_copies,
                defaults.memo_limit,
                defaults.check
            ),
            (
                Some(Options::DEFAULT_COPIES),
                Options::DEFAULT_FORWARD_COPIES,
                Options::DEFAULT_MEMO_LIMIT,
                Options::DEFAULT_CHECK
            )
        );
        assert_eq!(
            (Options::DEFAULT_COPIES, Options::DEFAULT_MEMO_LIMIT),
            (3, 1 << 20)
        );
        let atom = Atom::new(0);
        for (refutation, says) in [
            (
                Refutation::Unbalanced(Unbalanced {
                    atom,
                    least: 1,
                    most: 1,
                }),
                "#0 occurs 1 more time than ~#0 in the one-sided sequent, so",
            ),
            (
                Refutation::Unbalanced(Unbalanced {
                    atom,
                    least: -3,
                    most: -2,
                }),
                "~#0 occurs 2 to 3 more times than #0 in the one-sided sequent, whichever",
            ),
            (
                Refutation::OneSided(OneSided {
                    atom,
                    least: 1,
                    most: 1,
                    copied: crate::linear::occurrences::Sign::Atom,
                }),
                "#0 occurs 1 more time than ~#0 outside the exponentials of the one-sided \
                 sequent, and every literal of the atom below one, which copies add, is #0, so",
            ),
            (
                // The copies' literal is written as the fields name it, even
                // where a form read from JSON contradicts the counts.
                Refutation::OneSided(OneSided {
                    atom,
                    least: -2,
                    most: -1,
                    copied: crate::linear::occurrences::Sign::Atom,
                }),
                "~#0 occurs 1 to 2 more times than #0 outside the exponentials of the one-sided \
                 sequent, whichever additive alternatives a proof takes, and every literal of the \
                 atom below one, which copies add, is #0, so",
            ),
            (
                Refutation::Equation(Equation {
                    formulas: 3,
                    needed: -1,
                    tensors: 0,
                    pars: 3,
                    ones: 0,
                    bottoms: 0,
                    mix: true,
                }),
                "has at least #⊗ − #⅋ − #1 + #⊥ + 2 formulas, here 0 − 3 − 0 + 0 + 2 = −1, and this \
                 one has 3",
            ),
            (
                Refutation::StateEquation(StateEquation {
                    atoms: vec![(atom, -2), (Atom::new(1), 1)],
                    clauses: vec![(OccId::new(4), 1)],
                    dropped: Vec::new(),
                }),
                "weighting each #0 by −2, #1 by 1 and the clauses used once by weights of their \
                 own, no clause",
            ),
        ] {
            let text = refutation.to_string();
            assert!(text.contains(says), "{text}");
        }
    }

    /// A reason names the settings key a caller raises to search further,
    /// and says the bound it reached.
    #[test]
    fn reasons_name_their_setting() {
        for (reason, setting, text) in [
            (Reason::Stopped, None, "the search was stopped"),
            (
                Reason::RecursionLimit { depth: 7 },
                Some("limits.recursion_depth"),
                "the recursion limit of 7 was reached",
            ),
            (
                Reason::CopyBound { copies: 3 },
                Some("search.copies"),
                "the copy bound of 3 was reached",
            ),
            (
                Reason::MemoryLimit {
                    limit_bytes: 1 << 20,
                },
                Some("limits.memory_bytes"),
                "the memory limit of 1 MiB was reached",
            ),
            (
                Reason::MemoryLimit {
                    limit_bytes: u64::MAX,
                },
                None,
                "the memory the allocator would give was used up",
            ),
            (
                Reason::IndexLimit,
                None,
                "the search outgrew what its indices address",
            ),
            (
                Reason::WorkLimit { limit: 9 },
                Some("limits.work"),
                "the work limit of 9 was reached",
            ),
            (
                Reason::Unchecked { limit_bytes: 1024 },
                Some("limits.memory_bytes"),
                "a proof was found, but its check would hold more than the memory limit of 1 KiB",
            ),
        ] {
            assert_eq!(
                (reason.setting(), reason.to_string().as_str()),
                (setting, text)
            );
        }
    }

    /// Two searches' counters add up, except the memo's peak and the copy
    /// bounds reached, which are the larger of the two.
    #[test]
    fn statistics_add_up() {
        let mut first = Statistics {
            nodes: 3,
            memo_hits: 1,
            memo_entries: 7,
            splits: 2,
            links: 1,
            tests: 4,
            copies: 2,
            forward_copies: 9,
            work: 10,
            unifications: 6,
            bindings: 2,
        };
        let second = Statistics {
            nodes: 5,
            memo_hits: 2,
            memo_entries: 4,
            splits: 1,
            links: 3,
            tests: 1,
            copies: 5,
            forward_copies: 0,
            work: 20,
            unifications: 1,
            bindings: 3,
        };
        first.add(&second);
        assert_eq!(
            first,
            Statistics {
                nodes: 8,
                memo_hits: 3,
                memo_entries: 7,
                splits: 3,
                links: 4,
                tests: 5,
                copies: 5,
                forward_copies: 9,
                work: 30,
                unifications: 7,
                bindings: 5,
            }
        );
    }

    /// Classical inputs without exponentials go to the focused engine,
    /// unit-free MLL included, and two formulas with an additive
    /// connective or unit to the additive path. The outcome says which
    /// fragment it was searched in.
    #[test]
    fn dispatch() {
        for (input, fragment, engine) in [
            ("|- a, ~a", Fragment::EMPTY, Engine::Focus),
            ("a, a -o b |- b", Fragment::MLL, Engine::Focus),
            ("a * a |- a * a", Fragment::MLL, Engine::Focus),
            ("|- 1, bot", Fragment::MULTIPLICATIVE_UNITS, Engine::Focus),
            ("|- a & b, ~a + ~b", Fragment::ADDITIVES, Engine::Additive),
            ("|- top, 0", Fragment::ADDITIVE_UNITS, Engine::Additive),
            ("|- top, a, b", Fragment::ADDITIVE_UNITS, Engine::Focus),
            ("|- (a * top) + 1, ~a, bot", Fragment::MALL, Engine::Focus),
        ] {
            let outcome = prove(&sequent(input), Mode::CLASSICAL, &Options::default()).unwrap();
            assert_eq!(outcome.fragment, fragment, "{input:?}");
            assert_eq!(outcome.engine, engine, "{input:?}");
            assert_eq!(outcome.net.is_some(), engine == Engine::Net, "{input:?}");
            assert!(outcome.verdict.proof().is_some(), "{input:?}");
        }
    }

    /// Another engine takes over where the focused engine the dispatch
    /// picked ends at a limit on unit-free MLL whose linking is forced.
    /// After the recursion limit, the net engine decides the sequent, in
    /// classical and intuitionistic mode. After the memory bound in
    /// classical mode without Mix, the inverse method does, or the net
    /// engine after it. No engine takes over where an engine is forced, on
    /// equal literals, or outside unit-free MLL.
    #[test]
    fn another_engine_takes_over_at_a_limit() {
        let limits = Limits::default().with_recursion_depth(8);
        let decide = |input: &str, mode: Mode, options: &Options| {
            prove_within(&sequent(input), mode, options, &limits, |_| false).unwrap()
        };
        let chain = "a0, a0 -o a1, a1 -o a2, a2 -o a3, a3 -o a4, a4 -o a5, a5 -o a6, \
                     a6 -o a7, a7 -o a8, a8 -o a9, a9 -o a10 |- a10";
        for mode in [Mode::CLASSICAL, Mode::INTUITIONISTIC] {
            let outcome = decide(chain, mode, &Options::default());
            assert_eq!(outcome.engine, Engine::Net, "{mode}");
            assert!(outcome.verdict.proof().is_some(), "{mode}");
            assert!(outcome.net.is_some(), "{mode}");
        }
        let forced = Options::default().with_engine(Some(Engine::TwoSided));
        let outcome = decide(chain, Mode::INTUITIONISTIC, &forced);
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::RecursionLimit { .. })
        ));
        // The focused engine's set-up meets a bound of 1 MiB on `wide` with
        // 256 pairs, and the inverse method takes over. Under 64 KiB on 64
        // pairs, the inverse method meets the bound too, and the net engine
        // proves the sequent. What each search charged is given back before
        // the next one's proof is checked under the same bound. Under Mix
        // the net engine takes over at once.
        for (pairs, bytes, mode, engine) in [
            (256, 1 << 20, Mode::CLASSICAL, Engine::Inverse),
            (64, 1 << 16, Mode::CLASSICAL, Engine::Net),
            (256, 1 << 20, Mode::CLASSICAL.with_mix(), Engine::Net),
        ] {
            let tight = Limits::default().with_memory_bytes(Some(bytes));
            let wide = crate::linear::families::wide(pairs, 1);
            let outcome =
                prove_within(&wide, mode, &Options::default(), &tight, |_| false).unwrap();
            assert_eq!(outcome.engine, engine, "{pairs} {mode}");
            assert!(outcome.verdict.proof().is_some(), "{:?}", outcome.verdict);
        }
        // Equal literals: the net engine's search could run without end
        // where the focused engine gave up quickly, so the goal stays given
        // up.
        let equal = "a, a, a -o (a -o b0), b0 -o b1, b1 -o b2, b2 -o b3, b3 -o b4, \
                     b4 -o b5, b5 -o b6, b6 -o b7, b7 -o b8, b8 -o b9 |- b9";
        let outcome = decide(equal, Mode::INTUITIONISTIC, &Options::default());
        assert_eq!(outcome.engine, Engine::TwoSided);
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::RecursionLimit { .. })
        ));
        let with_unit = format!("{chain}, 1");
        let outcome = decide(&with_unit, Mode::CLASSICAL, &Options::default());
        assert_eq!(outcome.engine, Engine::Focus);
    }

    /// An unprovable sequent says why, where its counts tell: an atom
    /// whose literals cannot pair up, also across additive alternatives,
    /// or the count equation. Otherwise it says that the search was
    /// exhaustive.
    #[test]
    fn refutations() {
        let refuted = |input: &str, mode: Mode| {
            let outcome = prove(&sequent(input), mode, &Options::default()).unwrap();
            let Verdict::Unprovable(disproof) = outcome.verdict else {
                panic!("{input:?}: {:?}", outcome.verdict);
            };
            assert_eq!(
                (disproof.sequent(), disproof.mode()),
                (&sequent(input), mode)
            );
            *disproof
        };
        let unbalanced = |least, most| {
            Refutation::Unbalanced(Unbalanced {
                atom: Atom::new(0),
                least,
                most,
            })
        };
        let classical = Mode::CLASSICAL;
        assert_eq!(
            refuted("|- a, a", classical).refutation(),
            &unbalanced(2, 2)
        );
        assert_eq!(
            refuted("a |- b", Mode::INTUITIONISTIC).refutation(),
            &unbalanced(-1, -1)
        );
        let hull = refuted("|- (a * a) + (a * a * a), ~a", classical);
        assert_eq!(hull.refutation(), &unbalanced(1, 2));
        assert_eq!(
            hull.to_string(),
            "a occurs 1 to 2 more times than ~a in the one-sided sequent, whichever additive \
             alternatives a proof takes, so they cannot all meet in axioms"
        );
        assert!(
            hull.refutation()
                .to_string()
                .starts_with("#0 occurs 1 to 2 more times than ~#0")
        );
        let equation = refuted("|- a par b, ~a, ~b", classical);
        assert!(matches!(
            equation.refutation(),
            Refutation::Equation(Equation { needed: 1, .. })
        ));
        assert_eq!(
            equation.to_string(),
            "the count equation fails: a provable one-sided sequent of MLL has exactly #⊗ − #⅋ − \
             #1 + #⊥ + 2 formulas, here 0 − 1 − 0 + 0 + 2 = 1, and this one has 3"
        );
        // Where the counts rule out nothing, an assignment that makes the
        // classical reading false certifies the verdict. A tautology leaves
        // only the search's word.
        assert_eq!(
            refuted("|- a par ~a, b * ~b", classical).refutation(),
            &Refutation::Exhausted
        );
        let assigned = refuted("|- a & b, ~a", classical);
        assert_eq!(
            assigned.refutation(),
            &Refutation::Classical(Classical {
                assignment: vec![true, false]
            })
        );
        assert_eq!(
            assigned.to_string(),
            "the classical reading is false where a is true and every other atom false (! and ? \
             erased, ⊗ and & as and, ⅋ and ⊕ as or, 1 and ⊤ true, ⊥ and 0 false), and every \
             provable sequent reads as a tautology"
        );
    }

    /// A goal is a multiset. The roots in another order are the sequent
    /// itself, which the net engine takes, forced or by default.
    #[test]
    fn goal_in_any_order() {
        let s = sequent("a, a -o b |- b");
        let forest = Forest::new(&s).unwrap();
        let goal: Vec<Member> = forest
            .roots()
            .iter()
            .rev()
            .map(|&o| Member::from(o))
            .collect();
        assert_ne!(goal[0], Member::from(forest.roots()[0]));
        assert!(Goal::new(&forest, &goal).unwrap().is_conclusion());
        let classical = Mode::CLASSICAL;
        let outcome = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            classical,
            &Options::default(),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::Focus);
        assert!(outcome.verdict.proof().is_some());
        let net = Options::default().with_engine(Some(Engine::Net));
        let outcome = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            classical,
            &net,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert!(outcome.verdict.proof().is_some());
    }

    /// `Options::engine` forces an engine: the focused engine on MLL, and
    /// the net engine on MLL with Mix. The net engine forced outside MLL
    /// is an error.
    #[test]
    fn engine_override() {
        let s = sequent("|- a * b, ~a par ~b");
        let focus = Options::default().with_engine(Some(Engine::Focus));
        let outcome = prove(&s, Mode::CLASSICAL, &focus).unwrap();
        assert_eq!(outcome.engine, Engine::Focus);
        assert!(outcome.verdict.proof().is_some());
        assert!(outcome.net.is_none());
        let net = Options::default().with_engine(Some(Engine::Net));
        let outcome = prove(
            &sequent("|- a, ~a, b, ~b"),
            Mode::CLASSICAL.with_mix(),
            &net,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::Net);
        assert!(outcome.verdict.proof().is_some());
        for (input, options) in [
            ("|- 1", net.clone()),
            ("|- a & b, ~a", net.clone()),
            ("|- a, ~a", net.clone().with_fragment(Some(Fragment::MALL))),
        ] {
            let error = prove(&sequent(input), Mode::CLASSICAL, &options).unwrap_err();
            assert!(
                matches!(
                    error,
                    Error::EngineRefused {
                        engine: Engine::Net,
                        because: NotTaken::Fragment { .. },
                        ..
                    }
                ),
                "{input:?}: {error}"
            );
        }
        assert_eq!(
            prove(&sequent("|- 1"), Mode::CLASSICAL, &net)
                .unwrap_err()
                .to_string(),
            "proof nets exist for MLL without units only, not for MLL with units"
        );
    }

    /// The asserted fragment must contain the sequent's. The search runs
    /// in it, and it picks the engine.
    #[test]
    fn fragment_override() {
        let s = sequent("|- a * b, ~a, ~b");
        let outcome = prove(
            &s,
            Mode::CLASSICAL,
            &Options::default().with_fragment(Some(Fragment::MALL)),
        )
        .unwrap();
        assert_eq!(outcome.fragment, Fragment::MALL);
        assert_eq!(outcome.engine, Engine::Focus);
        assert!(outcome.verdict.proof().is_some());
        let error = prove(
            &sequent("|- a & b, ~a"),
            Mode::CLASSICAL,
            &Options::default().with_fragment(Some(Fragment::MLL)),
        )
        .unwrap_err();
        assert!(matches!(
            error,
            Error::FragmentMismatch {
                asserted: Fragment::MLL,
                detected: Fragment::ADDITIVES,
            }
        ));
        assert_eq!(
            error.to_string(),
            "the sequent lies in ALL, outside MLL, the fragment asked for"
        );
    }

    /// The table "Which engine decides a goal" of `Engine`'s
    /// documentation lists the rows of `DISPATCH` in their order. Each line
    /// has the row's fragment, its modes by the cell's first word, a
    /// feature exactly where the row asks one, its engine, and the inverse
    /// method beside it exactly where the row gives it turns.
    #[test]
    fn the_documented_dispatch_is_the_dispatch() {
        let section = include_str!("mod.rs")
            .split("/// # Which engine decides a goal")
            .nth(1)
            .expect("the section");
        let rows: Vec<Vec<&str>> = section
            .lines()
            .skip(1)
            .map_while(|line| line.strip_prefix("///"))
            .map(str::trim)
            .filter(|line| line.starts_with('|'))
            .skip(2)
            .map(|line| line.trim_matches('|').split('|').map(str::trim).collect())
            .collect();
        assert_eq!(rows.len(), DISPATCH.len(), "{rows:?}");
        for (cells, row) in rows.iter().zip(&DISPATCH) {
            let fragment = match cells[0] {
                "additives only" => Fragment::ADDITIVE,
                "unit-free MLL" => Fragment::MLL,
                "MELL" => Fragment::MELL,
                "any" => Fragment::LL,
                "any, quantifiers too" => Fragment::LL1,
                other => panic!("a fragment the test does not know: {other:?}"),
            };
            let modes = match cells[1].split([',', ' ']).next() {
                Some("any") => Modes::Any,
                Some("classical") => Modes::Classical,
                Some("intuitionistic") => Modes::Intuitionistic,
                Some("cyclic") => Modes::Cyclic,
                Some("Lambek") => Modes::Lambek,
                Some("Mix") => Modes::Mix,
                other => panic!("modes the test does not know: {other:?}"),
            };
            let engine = cells[3]
                .split_once("(Engine::")
                .and_then(|(_, rest)| rest.split_once(')'))
                .map(|(name, _)| name);
            let probe = cells[3].contains("(Engine::Inverse)");
            assert_eq!(
                (fragment, modes, cells[2].is_empty(), engine, probe),
                (
                    row.fragment,
                    row.modes,
                    row.feature == Feature::Any,
                    Some(format!("{:?}", row.engine).as_str()),
                    row.probe
                ),
                "{cells:?}"
            );
        }
    }

    /// A Horn program with a clause under `!` goes to the Horn engine in
    /// every mode, with Mix and in affine mode too. The other sequents with
    /// exponentials go to the focused engine. The net engine is refused in
    /// affine mode.
    #[test]
    fn dispatch_by_mode() {
        for (input, mode, fragment, engine) in [
            (
                "a, b |- a",
                Mode::CLASSICAL.with_affine(),
                Fragment::EMPTY,
                Engine::Focus,
            ),
            (
                "!a |- a",
                Mode::CLASSICAL,
                Fragment::EXPONENTIALS,
                Engine::Horn,
            ),
            (
                "!(a -o a * b), a |- a * b * b",
                Mode::CLASSICAL.with_mix(),
                Fragment::MLL | Fragment::EXPONENTIALS,
                Engine::Horn,
            ),
            (
                "a |- !a -o a",
                Mode::CLASSICAL,
                Fragment::MLL | Fragment::EXPONENTIALS,
                Engine::Focus,
            ),
            (
                "!a |- a & a",
                Mode::CLASSICAL.with_mix(),
                Fragment::ADDITIVES | Fragment::EXPONENTIALS,
                Engine::Focus,
            ),
            (
                "!a, b |- a",
                Mode::CLASSICAL.with_affine(),
                Fragment::EXPONENTIALS,
                Engine::Horn,
            ),
            (
                "!a, b |- a & a",
                Mode::CLASSICAL.with_affine(),
                Fragment::ADDITIVES | Fragment::EXPONENTIALS,
                Engine::Focus,
            ),
        ] {
            let outcome = prove(&sequent(input), mode, &Options::default()).unwrap();
            assert_eq!(outcome.engine, engine, "{input:?}");
            assert_eq!(outcome.fragment, fragment, "{input:?}");
            assert!(outcome.verdict.proof().is_some(), "{input:?}");
        }
        let net = Options::default().with_engine(Some(Engine::Net));
        let error = prove(&sequent("a, b |- a"), Mode::CLASSICAL.with_affine(), &net).unwrap_err();
        assert!(matches!(
            error,
            Error::EngineRefused {
                because: NotTaken::Mode { .. },
                ..
            }
        ));
        assert_eq!(
            error.to_string(),
            "proof nets exist in linear mode only, with or without Mix, not in classical affine mode"
        );
    }

    /// Intuitionistic mode: two formulas with an additive connective or
    /// unit go to the additive path, and a Horn program with a clause
    /// under `!` to the Horn engine. Everything else, unit-free IMLL
    /// included, goes to the two-sided engine. A sequent with no
    /// intuitionistic reading, Mix, and an engine forced for the other
    /// mode are errors.
    #[test]
    fn dispatch_intuitionistic() {
        let i = Mode::INTUITIONISTIC;
        for (input, fragment, engine) in [
            ("a, a -o b |- b", Fragment::MLL, Engine::TwoSided),
            ("1 |- 1", Fragment::MULTIPLICATIVE_UNITS, Engine::TwoSided),
            ("a & b |- a", Fragment::ADDITIVES, Engine::Additive),
            ("a & b, 0 |- a", Fragment::ADDITIVE, Engine::TwoSided),
            (
                "!a |- a * a",
                Fragment::MLL | Fragment::EXPONENTIALS,
                Engine::Horn,
            ),
            ("!a |- !a", Fragment::EXPONENTIALS, Engine::TwoSided),
        ] {
            let outcome = prove(&sequent(input), i, &Options::default()).unwrap();
            assert_eq!(outcome.fragment, fragment, "{input:?}");
            assert_eq!(outcome.engine, engine, "{input:?}");
            let proof = outcome
                .verdict
                .proof()
                .unwrap_or_else(|| panic!("{input:?}"));
            assert_eq!(proof.check(i), Ok(()), "{input:?}");
        }
        let outcome = prove(&sequent("a, b |- a"), i.with_affine(), &Options::default()).unwrap();
        assert_eq!(outcome.engine, Engine::TwoSided);
        assert!(outcome.verdict.proof().is_some());

        let error = prove(&sequent("|- a par b"), i, &Options::default()).unwrap_err();
        assert!(matches!(error, Error::NotIntuitionistic(_)));
        assert_eq!(
            error.to_string(),
            "not an intuitionistic sequent: the subformula a ⅋ b is neither an intuitionistic \
             formula nor the negation of one: intuitionistic linear logic has ⅋ only in A ⊸ B \
             (~A ⅋ B), and ? only under a negation"
        );
        let error = prove(&sequent("a |- a"), i.with_mix(), &Options::default()).unwrap_err();
        assert_eq!(
            error.to_string(),
            "Mix has no intuitionistic form: one premise of a Mix would have nothing right of ⊢"
        );
        let focus = Options::default().with_engine(Some(Engine::Focus));
        let error = prove(&sequent("a |- a"), i, &focus).unwrap_err();
        assert_eq!(
            error.to_string(),
            "the focus engine does not search in intuitionistic mode"
        );
        let two_sided = Options::default().with_engine(Some(Engine::TwoSided));
        let error = prove(&sequent("a |- a"), Mode::CLASSICAL, &two_sided).unwrap_err();
        assert!(matches!(
            error,
            Error::EngineRefused {
                because: NotTaken::Mode { .. },
                ..
            }
        ));
        let outcome = prove(&sequent("a, a -o b |- b"), i, &two_sided).unwrap();
        assert_eq!(outcome.engine, Engine::TwoSided);
        assert!(outcome.verdict.proof().is_some());
        let additive = Options::default().with_engine(Some(Engine::Additive));
        let error = prove(&sequent("a & b, c |- a"), i, &additive).unwrap_err();
        assert!(matches!(
            error,
            Error::EngineRefused {
                engine: Engine::Additive,
                ..
            }
        ));
        assert_eq!(
            error.to_string(),
            "the additive engine decides a sequent of two additive-only formulas only"
        );
    }

    /// IMLL by embedding. On generated intuitionistic sequents over `⊗`
    /// and `⊸`, and their mutants, the net engine forced on the one-sided
    /// sequent gives the two-sided engine's verdict. Every net-engine proof
    /// passes the intuitionistic checker, since every sequent of a cut-free
    /// MLL proof of an intuitionistic sequent has one goal.
    #[test]
    fn embedding_agrees_with_the_two_sided_engine() {
        use crate::linear::search::generate::{self, IllRules, Rng};
        let i = Mode::INTUITIONISTIC;
        let rules = IllRules {
            units: false,
            additives: false,
            zero: false,
            exponentials: false,
        };
        let mut rng = Rng::new(7);
        let (mut compared, mut provable) = (0, 0);
        for _ in 0..200 {
            let budget = 2 + rng.below(8);
            let generate::Ill {
                mut hypotheses,
                mut goal,
                ..
            } = generate::ill(&mut rng, rules, 3, budget);
            for mutated in [false, true] {
                if mutated && !generate::mutate_two_sided(&mut rng, &mut hypotheses, &mut goal, 3) {
                    continue;
                }
                let text = generate::two_sided(&hypotheses, &goal);
                let s = sequent(&text);
                // No literal more than twice, so that a debug build decides
                // the sample quickly.
                let forest = Forest::new(&s).unwrap();
                if forest
                    .all_literals()
                    .chunk_by(|x, y| {
                        forest.atom(*x) == forest.atom(*y) && forest.sign(*x) == forest.sign(*y)
                    })
                    .any(|group| group.len() > 2)
                {
                    continue;
                }
                let net = Options::default().with_engine(Some(Engine::Net));
                let by_net = prove(&s, i, &net).unwrap();
                let two_sided = Options::default().with_engine(Some(Engine::TwoSided));
                let by_two_sided = prove(&s, i, &two_sided).unwrap();
                assert_eq!(by_two_sided.engine, Engine::TwoSided);
                let verdict = |outcome: Outcome| match outcome.verdict {
                    Verdict::Proved(proof) => {
                        assert_eq!(proof.check(i), Ok(()), "{text:?} by {}", outcome.engine);
                        assert_eq!(outcome.net.is_some(), outcome.engine == Engine::Net);
                        true
                    }
                    Verdict::Unprovable(_) => false,
                    Verdict::Unknown(reason) => panic!("{text:?} by {}: {reason}", outcome.engine),
                };
                let (net, focus) = (verdict(by_net), verdict(by_two_sided));
                assert_eq!(net, focus, "{text:?}: net {net}, two-sided {focus}");
                assert!(mutated || net, "{text:?} is provable");
                compared += 1;
                provable += usize::from(net);
            }
        }
        assert!(
            compared > 100 && provable > 50 && provable < compared,
            "{provable} of {compared}"
        );
    }

    /// A goal below the roots is decided in its own fragment: by the
    /// focused engine, two additive-only occurrences by the additive path,
    /// and in intuitionistic mode by the two-sided engine. The net engine
    /// is refused off the roots, and an intuitionistic goal must have one
    /// output.
    #[test]
    fn goals() {
        let o = |ids: &[u32]| ids.iter().map(|&i| Member::new(i)).collect::<Vec<_>>();
        // 0: ~a, 1: (a ⊗ ~b) ⊗ ?c, 2: a ⊗ ~b, 3: a, 4: ~b, 5: ?c, 6: c, 7: b.
        let s = sequent("|- ~a, (a * ~b) * ?c, b");
        let forest = Forest::new(&s).unwrap();
        let options = Options::default();
        let goal = o(&[0, 3]);
        let outcome = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            Mode::CLASSICAL,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::Focus);
        assert_eq!(outcome.fragment, Fragment::EMPTY);
        let proof = outcome.verdict.proof().unwrap();
        // A goal proof is checked against the goal it records.
        assert!(proof.goal().is_some());
        assert_eq!(proof.check(Mode::CLASSICAL), Ok(()));
        let outcome = prove_goal(
            Goal::new(&forest, &o(&[0, 2, 7])).unwrap(),
            Mode::CLASSICAL,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert!(outcome.verdict.proof().is_some());
        assert_eq!(outcome.fragment, Fragment::MLL);
        let outcome = prove_goal(
            Goal::new(&forest, &o(&[4, 5])).unwrap(),
            Mode::CLASSICAL,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert!(
            matches!(outcome.verdict, Verdict::Unprovable(_)),
            "{:?}",
            outcome.verdict
        );
        assert_eq!(outcome.fragment, Fragment::EXPONENTIALS);
        assert!(!Goal::new(&forest, &goal).unwrap().is_conclusion());
        let net = Options::default().with_engine(Some(Engine::Net));
        let error = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            Mode::CLASSICAL,
            &net,
            &Limits::default(),
            |_| false,
        )
        .unwrap_err();
        assert!(
            matches!(
                error,
                Error::EngineRefused {
                    because: NotTaken::Goal,
                    ..
                }
            ),
            "{error}"
        );
        let error = Goal::new(&forest, &o(&[9])).unwrap_err();
        assert!(
            matches!(
                error,
                Error::IndexOutOfBounds {
                    space: crate::limits::Space::Occurrence,
                    index: 9,
                    len: 8
                }
            ),
            "{error}"
        );

        // 0: (~a & ~b) ⅋ (a & b), 1: ~a & ~b, 2: ~a, 3: ~b, 4: a & b, 5: a,
        // 6: b. The additive path decides the pair below the ⅋.
        let s = sequent("|- (~a & ~b) par (a & b)");
        let forest = Forest::new(&s).unwrap();
        let outcome = prove_goal(
            Goal::new(&forest, &o(&[1, 4])).unwrap(),
            Mode::CLASSICAL,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::Additive);
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
        let outcome = prove_goal(
            Goal::new(&forest, &o(&[5, 2])).unwrap(),
            Mode::CLASSICAL,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::Focus);
        assert!(outcome.verdict.proof().is_some());

        // 0: ~a, 1: a ⊗ ~b, 2: a, 3: ~b, 4: b, read as a, a ⊸ b ⊢ b. The
        // goal ⊢ ~a, a is a ⊢ a two-sided. ⊢ ~a alone has no output, and
        // ⊢ a, b has two.
        let s = sequent("a, a -o b |- b");
        let forest = Forest::new(&s).unwrap();
        let i = Mode::INTUITIONISTIC;
        let outcome = prove_goal(
            Goal::new(&forest, &o(&[0, 2])).unwrap(),
            i,
            &options,
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(outcome.engine, Engine::TwoSided);
        assert!(outcome.verdict.proof().is_some());
        for (goal, outputs) in [(o(&[0]), 0), (o(&[2, 4]), 2)] {
            let error = prove_goal(
                Goal::new(&forest, &goal).unwrap(),
                i,
                &options,
                &Limits::default(),
                |_| false,
            )
            .unwrap_err();
            assert!(
                matches!(error, Error::GoalOutputs { count: n } if n == outputs),
                "{error}"
            );
        }
    }

    /// A proof of a goal records the goal and the mode it was found in,
    /// passes the checker against the goal, and is refused where a proof
    /// of the sequent is needed.
    #[test]
    fn a_goal_proof_records_its_goal() {
        // 0: a ⊗ b, 1: a, 2: b, 3: ~a, 4: ~b, 5: c, 6: ~c
        let sequent: Sequent = "|- a * b, ~a, ~b, c, ~c".parse().unwrap();
        let forest = Forest::new(&sequent).unwrap();
        let goal = [Member::new(6), Member::new(5)];
        let mode = Mode::CLASSICAL;
        let outcome = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            mode,
            &Options::default(),
            &Limits::default(),
            |_| false,
        );
        let Verdict::Proved(proof) = outcome.unwrap().verdict else {
            panic!("⊢ ~c, c is provable");
        };
        let members = [crate::linear::Member::new(6), crate::linear::Member::new(5)];
        assert_eq!(
            (proof.goal(), proof.mode()),
            (Some(&members[..]), Some(mode))
        );
        assert_eq!(proof.check(mode), Ok(()));
        assert!(matches!(
            ProofStructure::from_proof(
                &proof,
                crate::linear::Criterion::MLL,
                &Limits::default(),
                |_| { false }
            ),
            Err(Error::GoalProof)
        ));
        #[cfg(feature = "rocq")]
        {
            let derivation = proof.derivation().unwrap();
            let options = crate::export::rocq::Options::default();
            let written =
                crate::export::rocq::write(&derivation, &options, &mut String::new(), |_| false);
            assert!(matches!(written, Err(Error::GoalProof)));
        }
    }

    /// A thread count is taken as at least one and at most
    /// [`Options::MAX_JOBS`], whatever is asked for.
    #[test]
    fn jobs_are_bounded() {
        assert_eq!(Jobs::Count(usize::MAX).count(), Options::MAX_JOBS);
        assert_eq!(Jobs::Count(0).count(), 1);
        assert!((1..=Options::MAX_JOBS).contains(&Jobs::Auto.count()));
        #[cfg(feature = "parallel")]
        assert_eq!(Options::default().with_jobs(2).threads(), 2);
    }
}