deduxit 0.5.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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The focused engine's tests.

use super::*;
use crate::linear::Sequent;
use crate::linear::search::generate::{self, Rng, Rules};
use crate::linear::search::{Bias, Goal, Verdict, prove_goal};
use crate::{Limits, Progress};

/// Runs the focused engine on the roots of the forest in the fragment
/// and the mode given, polling `stop`, and returns the verdict with the
/// statistics. In intuitionistic mode it runs the two-sided engine.
///
/// `reading` is given exactly in intuitionistic mode. It is the forest's
/// own, which the front door reads again itself. The proof is not
/// checked: the tests check it themselves.
fn search(
    forest: &Forest,
    fragment: Fragment,
    mode: Mode,
    reading: Option<&Reading>,
    options: &Options,
    stop: &mut dyn FnMut(u64) -> bool,
) -> (Verdict, Statistics) {
    search_within(
        forest,
        fragment,
        mode,
        reading,
        options,
        &Limits::default(),
        stop,
    )
}

/// Runs the engine as [`search`] does, within `limits`.
fn search_within(
    forest: &Forest,
    fragment: Fragment,
    mode: Mode,
    reading: Option<&Reading>,
    options: &Options,
    limits: &Limits,
    stop: &mut dyn FnMut(u64) -> bool,
) -> (Verdict, Statistics) {
    assert_eq!(reading.is_some(), mode.intuitionistic);
    let engine = if mode.intuitionistic {
        crate::linear::search::Engine::TwoSided
    } else {
        crate::linear::search::Engine::Focus
    };
    let options = options
        .clone()
        .with_engine(Some(engine))
        .with_fragment(Some(fragment))
        .with_check(false);
    let outcome = prove_goal(
        Goal::conclusion(forest),
        mode,
        &options,
        limits,
        |progress: Progress| stop(progress.work),
    )
    .unwrap_or_else(|e| panic!("{}: {e}", forest.sequent()));
    (outcome.verdict, outcome.statistics)
}

/// Runs the engine on `input` under `mode` with `options`, checks the
/// proof if there is one, and returns the verdict and the statistics.
fn run(input: &str, mode: Mode, options: &Options) -> (Verdict, Statistics) {
    run_within(input, mode, options, &Limits::default())
}

/// Runs the engine as [`run`] does, within `limits`.
fn run_within(
    input: &str,
    mode: Mode,
    options: &Options,
    limits: &Limits,
) -> (Verdict, Statistics) {
    let s: Sequent = input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"));
    let forest = Forest::new(&s).unwrap();
    let reading = mode.intuitionistic.then(|| {
        Reading::new(&forest).unwrap_or_else(|e| panic!("{input:?}: {}", e.describe(&forest)))
    });
    let (verdict, statistics) = search_within(
        &forest,
        s.fragment(),
        mode,
        reading.as_ref(),
        options,
        limits,
        &mut |_| false,
    );
    if let Verdict::Proved(proof) = &verdict {
        assert_eq!(proof.sequent(), &s);
        proof
            .check(mode)
            .unwrap_or_else(|e| panic!("{input:?}: the proof is wrong: {e}"));
    }
    (verdict, statistics)
}

/// Forty literals over atoms of their own, as the rest of a sequent.
pub(crate) fn wide_context() -> String {
    let literals: Vec<String> = (0..40).map(|i| format!("x{i}")).collect();
    literals.join(", ")
}

/// Whether `input` is provable under `mode`, panicking on `Unknown`.
fn provable(input: &str, mode: Mode) -> bool {
    match run(input, mode, &Options::default()).0 {
        Verdict::Proved(_) => true,
        Verdict::Unprovable(_) => false,
        Verdict::Unknown(reason) => panic!("{input:?}: {reason}"),
    }
}

/// The classic small sequents, in `MLL` and `MALL`, get the verdicts
/// the textbooks give them.
#[test]
fn classic_sequents() {
    let m = Mode::CLASSICAL;
    for (input, expected) in [
        ("|- ~a, a", true),
        ("a |- a", true),
        ("|- a, a", false),
        ("|-", false),
        ("a * b |- a * b", true),
        ("|- a * b, ~a par ~b", true),
        ("|- a * b, ~a, ~b", true),
        ("|- a par b, ~a, ~b", false),
        ("|- (a * b) par (~a * ~b)", false),
        ("a, a -o b, b -o c |- c", true),
        ("a -o b, b -o c |- a -o c", true),
        ("a -o b |- b -o a", false),
        ("|- a & b, ~a + ~b", true),
        ("|- a + b, ~a", true),
        ("|- a & b, ~a", false),
        ("(a & b) + (a & c) |- a & (b + c)", true),
        ("a & (b + c) |- (a & b) + (a & c)", false),
        ("a * (b + c) |- (a * b) + (a * c)", true),
        ("(a * b) + (a * c) |- a * (b + c)", true),
        ("a & b |- a", true),
        ("a |- a & b", false),
        ("a |- a + b", true),
        ("a + b |- a", false),
    ] {
        assert_eq!(provable(input, m), expected, "{input:?}");
    }
}

/// The `&` rule polls the stop.
///
/// With `⊤` taken last, `⊢ a₁ & b₁, …, aₙ & bₙ, ⊤` has a proof of `2ⁿ`
/// branches that reaches no stable sequent (one where no invertible rule
/// applies). The search polls at stable sequents otherwise.
#[test]
fn with_rules_poll_the_stop() {
    let withs: Vec<String> = (0..24).map(|i| format!("a{i} & b{i}")).collect();
    let sequent: Sequent = format!("|- {}, top", withs.join(", ")).parse().unwrap();
    let options = Options::default()
        .with_engine(Some(crate::linear::search::Engine::Focus))
        .with_jobs(1);
    let mut polls = 0_u32;
    let outcome = crate::linear::search::prove_within(
        &sequent,
        Mode::CLASSICAL,
        &options,
        &Limits::default(),
        |progress| {
            // Only the search's own polls count, since the check of a
            // proof found polls too.
            polls += u32::from(progress.phase == crate::limits::Phase::Search);
            polls > 1
        },
    )
    .unwrap();
    assert!(
        matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)),
        "the search was not stopped"
    );
}

/// `⊢ a₁ & b₁, …, a₁₆ & b₁₆, ⊤`, whose proof of `&` rules closed by `⊤`
/// has 2¹⁷ nodes and reaches no stable sequent.
fn with_rules_closed_by_top() -> Sequent {
    let withs: Vec<String> = (0..16).map(|i| format!("a{i} & b{i}")).collect();
    format!("|- {}, top", withs.join(", ")).parse().unwrap()
}

/// That proof is made within the memory bound. Its two mebibytes of nodes
/// pass a bound of one mebibyte, and the search itself answers the bound,
/// before it has a proof.
#[test]
fn a_proof_of_with_rules_keeps_to_the_memory_bound() {
    let options = Options::default()
        .with_engine(Some(crate::linear::search::Engine::Focus))
        .with_jobs(1);
    let limits = Limits::default().with_memory_bytes(Some(1 << 20));
    let outcome = crate::linear::search::prove_within(
        &with_rules_closed_by_top(),
        Mode::CLASSICAL,
        &options,
        &limits,
        |_| false,
    )
    .unwrap();
    assert!(
        matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::MemoryLimit { .. })
        ),
        "{:?}",
        outcome.verdict
    );
}

/// The `&` rules are work, which `Limits::work` bounds, and that proof is
/// kept and built under the stop.
///
/// After the search's last poll that reports work come the polls of the
/// root's keep and of the proof's two passes: each polls once per 2¹⁶
/// nodes, and no more. Without these polls, a proof of 24 pairs takes a
/// second without one.
#[test]
fn with_rules_are_work_and_their_proof_is_polled() {
    let options = Options::default()
        .with_engine(Some(crate::linear::search::Engine::Focus))
        .with_jobs(1)
        .with_check(false);
    let sequent = with_rules_closed_by_top();
    let limits = Limits::default().with_work(Some(10_000));
    let outcome =
        crate::linear::search::prove_within(&sequent, Mode::CLASSICAL, &options, &limits, |_| {
            false
        })
        .unwrap();
    assert!(
        matches!(outcome.verdict, Verdict::Unknown(Reason::WorkLimit { .. })),
        "{:?}",
        outcome.verdict
    );
    let mut after = 0;
    let outcome = crate::linear::search::prove_within(
        &sequent,
        Mode::CLASSICAL,
        &options,
        &Limits::default(),
        |progress| {
            if progress.phase == crate::limits::Phase::Search {
                after = if progress.work > 0 { 0 } else { after + 1 };
            }
            false
        },
    )
    .unwrap();
    assert!(outcome.verdict.proof().is_some(), "{:?}", outcome.verdict);
    assert!(
        (6..=8).contains(&after),
        "{after} polls after the search's last work"
    );
}

/// An atom whose literals below an exponential all have one sign keeps
/// its count: copies can move it toward that sign alone.
///
/// So copies of `a` cannot pair with the `a` outside (`|- ?a, a`, and one
/// branch of `|- ?a, a & ~a`), while copies of `~a` can
/// (`|- ?~a, a * a`). A mutant whose goal needs an `a` that only the `!`
/// of a hypothesis holds is refuted classically and intuitionistically.
/// No copy bound decides it without these counts. The refutation of
/// `|- ?a, a` names the count.
#[test]
fn copies_of_one_sign_bound_the_count_one_way() {
    let mutant = "b, b, (!!!c * !b), (((b -o !b) -o (b -o (b * b))) -o !((b -o c) * (a -o c))) \
                  |- ((((((b -o c) -o c) * b) * a) * b) * (b -o b))";
    for (input, mode, expected) in [
        ("|- ?a, a", Mode::CLASSICAL, false),
        ("|- ?a, a & ~a", Mode::CLASSICAL, false),
        ("|- ?a, ~a", Mode::CLASSICAL, true),
        ("|- ?~a, a * a", Mode::CLASSICAL, true),
        ("|- ?a, ?~a, a", Mode::CLASSICAL, true),
        (mutant, Mode::CLASSICAL, false),
        (mutant, Mode::INTUITIONISTIC, false),
    ] {
        assert_eq!(
            decided(input, mode, &Options::default()),
            Some(expected),
            "{input:?} in {mode} mode"
        );
    }
    let outcome = crate::linear::search::prove(
        &"|- ?a, a".parse().unwrap(),
        Mode::CLASSICAL,
        &Options::default(),
    )
    .unwrap();
    let Verdict::Unprovable(disproof) = outcome.verdict else {
        panic!("{:?}", outcome.verdict)
    };
    assert_eq!(
        disproof.refutation(),
        &crate::linear::search::Refutation::OneSided(crate::linear::search::OneSided {
            atom: crate::linear::sequents::Atom::new(0),
            least: 1,
            most: 1,
            copied: crate::linear::occurrences::Sign::Atom,
        })
    );
}

/// The units follow their rules: `1` is proved only in an empty context,
/// `⊥` is dropped, `⊤` closes any context, and `0` closes none.
#[test]
fn units() {
    let m = Mode::CLASSICAL;
    for (input, expected) in [
        ("|- 1", true),
        ("|- bot, 1", true),
        ("|- 1 * 1", true),
        ("|- bot par 1", true),
        ("|- bot par bot", false),
        ("|- bot", false),
        ("|- 1, 1", false),
        ("|- 1, a, ~a", false),
        ("|- a * 1, ~a", true),
        ("|- top", true),
        ("|- top, a", true),
        ("|- top * a, ~a, b", true),
        ("|- a * top, b", false),
        ("|- a & top, ~a", true),
        ("|- 0", false),
        ("|- 0, top", true),
        ("|- 0, top + b", true),
        ("|- 0 * a, ~a, top + b", true),
        ("|- 0 + a, ~a", true),
        ("|- 0 * a, ~a", false),
        ("0 |- a", true),
        ("a |- top", true),
    ] {
        assert_eq!(provable(input, m), expected, "{input:?}");
    }
}

/// Mix proves exactly what needs it.
#[test]
fn mix() {
    let mix = Mode::CLASSICAL.with_mix();
    for (input, without, with) in [
        ("|- a par b, ~a, ~b", false, true),
        ("a * b |- a par b", false, true),
        ("|- a, ~a, b, ~b", false, true),
        ("|- 1, a, ~a", false, true),
        ("|- 1, 1", false, true),
        ("|- a * b, ~a, ~b", true, true),
        ("|- a, b", false, false),
        ("|- a + b, ~a, c, ~c", false, true),
        ("|- (a & b) par c, ~a, ~b, ~c", false, false),
        ("|- a & b, ~a, ~b", false, false),
        ("|-", false, false),
    ] {
        assert_eq!(provable(input, Mode::CLASSICAL), without, "{input:?}");
        assert_eq!(provable(input, mix), with, "{input:?} with Mix");
    }
}

/// The memo makes no difference to the verdicts, and the counters say
/// what the search did.
#[test]
fn memo_and_statistics() {
    let (verdict, statistics) = run("|- ~a, a", Mode::CLASSICAL, &Options::default());
    assert!(verdict.proof().is_some());
    assert_eq!(statistics.nodes, 1);
    assert_eq!(statistics.memo_hits, 0);
    assert_eq!(statistics.memo_entries, 1);
    assert_eq!(statistics.splits, 0);

    // ⊢ ~a ⊕ ~b, ~a ⊕ ~b, a ⊗ b, (x ⅋ ~x) ⊗ (y ⊗ ~y) is unprovable. The
    // two orders of choosing the `⊕` sides reach the stable sequent
    // ⊢ ~a, ~b, a ⊗ b, (x ⅋ ~x) ⊗ (y ⊗ ~y), whose refutation takes a few
    // stable sequents. The memo answers it the second time.
    let input = "|- ~a + ~b, ~a + ~b, a * b, (x par ~x) * (y * ~y)";
    let with_memo = run(input, Mode::CLASSICAL, &Options::default());
    let without = run(
        input,
        Mode::CLASSICAL,
        &Options::default().with_memo_limit(0),
    );
    assert!(matches!(with_memo.0, Verdict::Unprovable(_)));
    assert!(matches!(without.0, Verdict::Unprovable(_)));
    assert!(with_memo.1.memo_hits >= 1);
    assert_eq!(without.1.memo_hits, 0);
    assert_eq!(without.1.memo_entries, 0);
    assert!(without.1.nodes > with_memo.1.nodes);
}

/// The same input and options give the same proof, node for node.
#[test]
fn deterministic() {
    let input = "|- (a * b) + (a * c), ~a par (~b & ~c), a, ~a";
    let first = run(input, Mode::CLASSICAL.with_mix(), &Options::default());
    let second = run(input, Mode::CLASSICAL.with_mix(), &Options::default());
    assert_eq!(
        first.0.proof().unwrap().nodes(),
        second.0.proof().unwrap().nodes()
    );
    assert_eq!(first.1, second.1);
}

/// The stop condition and the recursion limit each end the search with
/// their reason, and no context is too wide to split.
#[test]
fn limits() {
    let input = "|- a * b, ~a, ~b";
    let s: Sequent = input.parse().unwrap();
    let forest = Forest::new(&s).unwrap();
    let mut calls = 0;
    let (verdict, _) = search(
        &forest,
        s.fragment(),
        Mode::CLASSICAL,
        None,
        &Options::default(),
        &mut |_| {
            calls += 1;
            calls >= 1
        },
    );
    assert!(matches!(verdict, Verdict::Unknown(Reason::Stopped)));

    let depth = |depth| Limits::default().with_recursion_depth(depth);
    let (verdict, _) = run_within(input, Mode::CLASSICAL, &Options::default(), &depth(2));
    assert!(matches!(
        verdict,
        Verdict::Unknown(Reason::RecursionLimit { .. })
    ));
    let (verdict, _) = run_within(input, Mode::CLASSICAL, &Options::default(), &depth(8));
    assert!(verdict.proof().is_some());

    // A `?` costs no level of recursion: three thousand of them stay
    // under the default limit.
    let hypotheses: Vec<String> = (0..3000).map(|i| format!("?a{i}")).collect();
    let many = format!("|- 1, {}", hypotheses.join(", "));
    let (verdict, _) = run(&many, Mode::CLASSICAL, &Options::default());
    assert!(verdict.proof().is_some());

    // Nor does a link of a tensor of literals, nested to the left as it
    // is read: the literal on the right forces every split. This runs on
    // a thread with the stack a front end gives the search, since the
    // parser and the checker recurse to the formula's depth.
    let literals = format!(
        "|- {}, {}",
        vec!["a"; 2500].join(" * "),
        vec!["~a"; 2500].join(", ")
    );
    // The same for a tensor of tensors of literals, which is proved
    // in place from the duals of all its literals.
    let pairs = format!(
        "|- {}, {}",
        vec!["(a * b)"; 2500].join(" * "),
        vec!["~a, ~b"; 2500].join(", ")
    );
    let proved = std::thread::Builder::new()
        .stack_size(Limits::default().stack_bytes())
        .spawn(move || {
            [literals, pairs].iter().all(|chain| {
                let (verdict, _) = run(chain, Mode::CLASSICAL, &Options::default());
                verdict.proof().is_some()
            })
        })
        .unwrap()
        .join()
        .unwrap();
    assert!(proved);

    // A free split over 126 formulas, in MALL so that the count equation
    // does not refute it first. No width is too much: the counts of `b`
    // refute every split at once.
    let wide = format!(
        "|- ((a & a) par b) * (~a par ~b), {}",
        (0..63).map(|_| "~a, a").collect::<Vec<_>>().join(", ")
    );
    let (verdict, _) = run(&wide, Mode::CLASSICAL, &Options::default());
    assert!(matches!(verdict, Verdict::Unprovable(_)));
}

/// A sequent whose search comes back to it, with other occurrences of
/// the same formulas, is refuted. Its own failure at the level before,
/// cut by the budget, does not leave it at the copy bound: such a failure
/// answers for its own sequent alone.
#[test]
fn repeats_up_to_equal_members() {
    for input in [
        "|- ~b, (1 * a), ?(b * ((a par ~b) * ~a))",
        "a, a, b, b, !(((b * a) * a) -o b), !(((b * a) * a) -o b) |- ((b * b) * b)",
    ] {
        assert!(!provable(input, Mode::CLASSICAL), "{input:?}");
    }
    // Here the relative is reached on another branch.
    let sibling = "!(!!(b -o c) -o !c), b |- (c * ((a -o a) * c))";
    assert!(!provable(sibling, Mode::INTUITIONISTIC));
}

/// The bias never changes what is provable, only what a copy bound
/// allows.
///
/// Chaining backward, the counter with eight tokens is proved within
/// three copies a branch. Chaining forward, it needs seven, but visits
/// less than a quarter of the stable sequents. The default bias finds the
/// forward proof.
#[test]
fn bias_option() {
    let (sequent, copies) = crate::linear::families::counter(8, false);
    let forest = Forest::new(&sequent).unwrap();
    let run = |options: &Options| {
        let fragment = sequent.fragment();
        search(
            &forest,
            fragment,
            Mode::CLASSICAL,
            None,
            options,
            &mut |_| false,
        )
    };
    let backward = Options::default()
        .with_bias(Bias::Rarer)
        .with_copies(Some(copies));
    let (verdict, slow) = run(&backward);
    assert!(verdict.proof().is_some());
    let forward = backward.clone().with_bias(Bias::Factors);
    let (verdict, _) = run(&forward);
    assert!(matches!(
        verdict,
        Verdict::Unknown(Reason::CopyBound { .. })
    ));
    let (verdict, fast) = run(&forward.with_copies(Some(7)));
    let proof = verdict.proof().expect("seven steps on one branch");
    assert_eq!(proof.check(Mode::CLASSICAL), Ok(()));
    assert!(fast.nodes * 4 < slow.nodes, "{fast:?} against {slow:?}");
    // The default runs both. The clauses are Horn, so the forward search
    // has its own bound, and its proof comes first, at its cost.
    let (verdict, default) = run(&Options::default().with_copies(Some(copies)));
    assert_eq!(verdict.proof().unwrap().check(Mode::CLASSICAL), Ok(()));
    // The forward search decided, at the level the explicit one did.
    assert_eq!(default.forward_copies, fast.copies);
    assert_eq!(
        Statistics {
            forward_copies: 0,
            ..default
        },
        fast
    );
}

/// Without a copy bound, the search goes on to the next level until it
/// decides, and says which level that was. With a bound, it ends there.
#[test]
fn an_unbounded_search_deepens() {
    let (sequent, _) = crate::linear::families::counter(8, false);
    let forest = Forest::new(&sequent).unwrap();
    let run = |options: &Options| {
        let fragment = sequent.fragment();
        let mode = Mode::CLASSICAL;
        search(&forest, fragment, mode, None, options, &mut |_| false)
    };
    let forward = Options::default().with_bias(Bias::Factors);
    let (verdict, statistics) = run(&forward.clone().with_copies(Some(3)));
    assert!(matches!(
        verdict,
        Verdict::Unknown(Reason::CopyBound { copies: 3 })
    ));
    assert_eq!(statistics.copies, 3);
    let (verdict, statistics) = run(&forward.with_copies(None));
    assert!(verdict.proof().is_some(), "seven steps on one branch");
    assert_eq!(statistics.copies, 7);
}

/// Without a copy bound, a level closes once its budget outlasts every
/// branch that ends in a repeat.
///
/// These intuitionistic non-theorems are images of propositional
/// formulas, with a few dozen stable sequents each. They are refuted
/// within thirty thousand units of work, at a level below twenty. That
/// needs a failure cut by the budget to count at its own level only.
/// Read as a cut in every later level, it would carry the cut on from
/// level to level, and each would pass a million levels without a
/// verdict.
///
/// They are refuted too on a pool of two whose memo of 64 entries, one
/// per shard, overflows within every level. There a key met again must
/// not look new at every level.
#[test]
fn deepening_closes_on_a_finite_space() {
    let limits = Limits::default().with_work(Some(1_000_000));
    let alone = Options::default().with_copies(None);
    #[cfg(feature = "parallel")]
    let pooled = [alone.clone().with_jobs(2).with_memo_limit(64)];
    #[cfg(not(feature = "parallel"))]
    let pooled: [Options; 0] = [];
    for input in [
        "!(!(!o11 -o 0) -o 0), !(!(!o21 -o 0) -o 0) |- !o11 + !o21",
        "|- !(!(!(!p -o !q) -o 0) -o !(!(!q -o !p) -o 0)) \
         * !(!(!(!q -o !p) -o 0) -o !(!(!p -o !q) -o 0))",
        "!(!(!a -o !b) -o 0) |- !(!(!b -o !(!(!a -o 0) -o 0)) -o 0)",
        "|- !(!(!a + !b) -o !(!(!!(a & !(!b -o 0)) -o !0) -o 0))",
    ] {
        for options in std::iter::once(&alone).chain(&pooled) {
            let (verdict, statistics) = run_within(input, Mode::INTUITIONISTIC, options, &limits);
            assert!(
                matches!(verdict, Verdict::Unprovable(_)),
                "{input}, jobs {:?}: {verdict:?} at level {}",
                options.jobs,
                statistics.copies
            );
        }
    }
}

/// The default bias runs two searches, and here they share one core.
///
/// In turns, each starts again from the beginning with more work each
/// turn. Here the backward search decides, after the forward one used up
/// turns and then its bound. With threads, they alternate in slices
/// instead: each search runs as it does alone, and none starts again.
#[test]
fn default_bias_takes_turns() {
    // The counter with eight tokens takes seven steps forward, more than
    // the forward bound here. The clauses that move a token between
    // places give the forward search markings to visit until then.
    let (mut clauses, marking, goal) = counter(8);
    for (body, head) in [
        ("a", "x"),
        ("x", "y"),
        ("y", "a"),
        ("a", "u"),
        ("u", "v"),
        ("v", "a"),
        ("b", "w"),
        ("w", "b"),
        ("x", "u"),
    ] {
        clauses.push((body.to_string(), head.to_string()));
    }
    let clauses: Vec<(&str, &str)> = clauses.iter().map(|(b, h)| (&**b, &**h)).collect();
    let text = horn(&clauses, &marking, &[goal]);
    let m = Mode::CLASSICAL;
    let options = Options::default().with_forward_copies(3);
    let (verdict, backward) = run(&text, m, &options.clone().with_bias(Bias::Rarer));
    assert!(verdict.proof().is_some());
    let (verdict, forward) = run(
        &text,
        m,
        &options
            .clone()
            .with_bias(Bias::Factors)
            .with_copies(Some(3)),
    );
    assert!(matches!(
        verdict,
        Verdict::Unknown(Reason::CopyBound { copies: 3 })
    ));

    let sequent: Sequent = text.parse().unwrap();
    let forest = Forest::new(&sequent).unwrap();
    let classes = Classes::new(&forest, None);
    let in_turns = || {
        let (first, second) = plan(&forest, forest.roots(), sequent.fragment(), m, &options);
        let second = second.expect("two searches");
        let counts = [first, second].map(|rule| Counts::new(&forest, rule.bias));
        let account = Account::new(None);
        let task = Task {
            forest: &forest,
            goal: forest.roots(),
            fragment: sequent.fragment(),
            mode: m,
            reading: None,
            roots: true,
            program: std::sync::OnceLock::new(),
        };
        let set_up = SetUp {
            task: &task,
            classes: &classes,
            options: &options,
            limits: &Limits::default(),
        };
        let Finished {
            result, statistics, ..
        } = turns::<Ground>(
            set_up,
            [
                (first, &counts[0], &account),
                (second, &counts[1], &account),
            ],
            &mut |_| false,
        );
        assert!(matches!(result, Ok(Some(_))));
        statistics
    };
    let both = in_turns();
    // What the turns cut short cost. For the forward search, it is less
    // than a third of the turn it ends in. For the backward search, which
    // then runs alone, it is at most that turn and the ones before it.
    let cut = both.nodes - forward.nodes - backward.nodes;
    assert!(
        0 < cut && cut < 7 * forward.nodes,
        "{cut} stable sequents in the turns cut short, {forward:?}, {backward:?}"
    );
    // One thread, so the run is a function of the input.
    assert_eq!(in_turns(), both);

    #[cfg(feature = "parallel")]
    {
        let (verdict, slices) = run(&text, m, &options);
        assert!(verdict.proof().is_some());
        assert_eq!(slices.nodes, forward.nodes + backward.nodes);
        assert_eq!(slices.splits, forward.splits + backward.splits);
        assert_eq!(slices.work, forward.work + backward.work);
        assert_eq!(run(&text, m, &options).1, slices);
        // Asked for, the turns run on a build with threads too.
        let turns = options
            .clone()
            .with_schedule(crate::linear::search::Schedule::Turns);
        // The front door adds the work, which the turns leave to it.
        let through = run(&text, m, &turns).1;
        assert_eq!(Statistics { work: 0, ..through }, both);
    }
}

/// Under a memory bound that the memo does not fit, the memo is emptied
/// whenever it reaches the bound, and the search still decides, in more
/// stable sequents. Under a bound that leaves the memo no room, the
/// search gives up and names the bound.
#[test]
fn memory_bound() {
    let (sequent, copies) = crate::linear::families::counter(16, false);
    let text = sequent.to_string();
    let options = Options::default()
        .with_copies(Some(copies))
        .with_bias(Bias::Rarer);
    let bounded = |bytes| {
        let limits = Limits::default().with_memory_bytes(Some(bytes));
        run_within(&text, Mode::CLASSICAL, &options, &limits)
    };
    let (verdict, whole) = run(&text, Mode::CLASSICAL, &options);
    assert!(verdict.proof().is_some());
    let (verdict, tight) = bounded(10 << 10);
    assert!(verdict.proof().is_some());
    assert!(
        tight.memo_entries < whole.memo_entries && tight.nodes > whole.nodes,
        "{tight:?} within 10 KiB, {whole:?} without a bound that binds"
    );
    let (verdict, _) = bounded(1 << 10);
    assert!(matches!(
        verdict,
        Verdict::Unknown(Reason::MemoryLimit { limit_bytes: 1024 })
    ));
}

/// A memo of a few entries is emptied at nearly every insertion, and the
/// kept proofs are collected as often. Whatever such a search proves is a
/// proof the checker accepts, and its verdict never contradicts the one a
/// memo of the default size gives.
///
/// A collection moves ids, so an id it moved and no one renamed would
/// break the proof. A search is given up after 20 000 polls, since with a
/// memo this small some take minutes.
#[test]
fn proofs_survive_collections() {
    let mut proved = 0;
    let within = |text: &str, mode: Mode, options: &Options| {
        let s: Sequent = text.parse().unwrap();
        let forest = Forest::new(&s).unwrap();
        let reading = mode.intuitionistic.then(|| Reading::new(&forest).unwrap());
        let mut polls = 0;
        let (verdict, _) = search(
            &forest,
            s.fragment(),
            mode,
            reading.as_ref(),
            options,
            &mut |_| {
                polls += 1;
                polls > 20_000
            },
        );
        match verdict {
            Verdict::Proved(proof) => {
                proof
                    .check(mode)
                    .unwrap_or_else(|e| panic!("{text:?}: the proof is wrong: {e}"));
                Some(true)
            }
            Verdict::Unprovable(_) => Some(false),
            Verdict::Unknown(_) => None,
        }
    };
    let mut check = |text: &str, mode: Mode, options: &Options| {
        for bias in [Bias::Rarer, Bias::Factors] {
            let options = options.clone().with_bias(bias);
            let whole = within(text, mode, &options);
            for limit in [1, 2, 5] {
                let small = within(text, mode, &options.clone().with_memo_limit(limit));
                assert!(
                    small.is_none() || whole.is_none() || small == whole,
                    "{text:?} in {mode} mode: {small:?} with a memo of {limit}, {whole:?}"
                );
                proved += u64::from(small == Some(true));
            }
        }
    };
    for (i, rules) in Rules::ALL.into_iter().enumerate() {
        let mut rng = Rng::new(700 + i as u64);
        for _ in 0..20 {
            let generate::Provable {
                mut formulas,
                copies,
            } = generate::provable(&mut rng, rules, 3, 8);
            let options = Options::default().with_copies(Some(copies));
            check(&generate::sequent(&formulas), mode_for(rules), &options);
            if generate::mutate(&mut rng, &mut formulas, 3) {
                check(&generate::sequent(&formulas), mode_for(rules), &options);
            }
        }
    }
    for (n, rules) in generate::IllRules::ALL.into_iter().enumerate() {
        let mut rng = Rng::new(800 + n as u64);
        for _ in 0..20 {
            let generate::Ill {
                hypotheses,
                goal,
                copies,
                ..
            } = generate::ill(&mut rng, rules, 3, 8);
            let options = Options::default().with_copies(Some(copies));
            let text = generate::two_sided(&hypotheses, &goal);
            check(&text, Mode::INTUITIONISTIC, &options);
        }
    }
    assert!(proved > 1000, "{proved} proofs");
}

/// The contract of the default bias: on a sequent with exponentials it
/// decides whatever the backward or the forward search decides under
/// the same options, with the same verdict, with and without the memo,
/// classically and intuitionistically.
#[test]
fn default_bias_decides_what_either_rule_does() {
    let (mut compared, mut over) = (0, 0);
    let mut check = |text: &str, mode: Mode, options: &Options| {
        // Each bias runs alone within the mutants' work. The default bias
        // runs unbounded, since its contract holds where no stop fires.
        // It runs only where one of them decided, since there is nothing
        // to compare otherwise.
        let ones = [Bias::Rarer, Bias::Factors]
            .map(|bias| (bias, bounded(text, mode, &options.clone().with_bias(bias))));
        over += ones
            .iter()
            .map(|(_, (_, out))| u64::from(*out))
            .sum::<u64>();
        if ones.iter().all(|(_, (one, _))| one.is_none()) {
            return;
        }
        let both = decided(text, mode, options);
        for (bias, (one, _)) in ones {
            assert!(
                one.is_none() || one == both,
                "{text:?} in {mode} mode: {one:?} under {bias:?}, {both:?} by default"
            );
            compared += u64::from(one.is_some());
        }
    };
    for (i, rules) in Rules::ALL.into_iter().enumerate() {
        if !rules.exponentials {
            continue;
        }
        let mut rng = Rng::new(200 + i as u64);
        for _ in 0..30 {
            let generate::Provable {
                mut formulas,
                copies,
            } = generate::provable(&mut rng, rules, 3, 8);
            let options = Options::default().with_copies(Some(copies));
            check(&generate::sequent(&formulas), mode_for(rules), &options);
            if generate::mutate(&mut rng, &mut formulas, 3) {
                let text = generate::sequent(&formulas);
                check(&text, mode_for(rules), &Options::default());
                // Without the memo a refutation under Mix takes seconds.
                if !rules.mix {
                    check(
                        &text,
                        mode_for(rules),
                        &Options::default().with_memo_limit(0),
                    );
                }
            }
        }
    }
    for (n, rules) in generate::IllRules::ALL.into_iter().enumerate() {
        let mut rng = Rng::new(300 + n as u64);
        for _ in 0..30 {
            let generate::Ill {
                mut hypotheses,
                mut goal,
                copies,
                ..
            } = generate::ill(&mut rng, rules, 3, 8);
            let options = Options::default().with_copies(Some(copies));
            let text = generate::two_sided(&hypotheses, &goal);
            check(&text, Mode::INTUITIONISTIC, &options);
            if generate::mutate_two_sided(&mut rng, &mut hypotheses, &mut goal, 3) {
                let text = generate::two_sided(&hypotheses, &goal);
                check(&text, Mode::INTUITIONISTIC, &Options::default());
            }
        }
    }
    assert!(compared > 1000, "{compared} verdicts compared");
    assert!(
        over * 50 < compared,
        "{over} searches past the mutants' work"
    );
}

/// A split search whose splits all fail in focus visits no stable
/// sequent, and still stops when asked.
///
/// With weakening, no count cuts the 2⁴² splits of this context. Each
/// fails at once, since no member is the `~p` its left side wants.
#[test]
fn stops_inside_a_split_search() {
    let input = format!(
        "|- p * q, 0 * (~p par ~p), 0 * (~q par ~q), {}",
        wide_context()
    );
    let s: Sequent = input.parse().unwrap();
    let forest = Forest::new(&s).unwrap();
    let mut polls = 0;
    let (verdict, statistics) = search(
        &forest,
        s.fragment(),
        Mode::CLASSICAL.with_affine(),
        None,
        &Options::default(),
        &mut |_| {
            polls += 1;
            polls > 3
        },
    );
    assert!(matches!(verdict, Verdict::Unknown(Reason::Stopped)));
    assert_eq!(statistics.nodes, 1);
    assert!(statistics.splits <= 4 * SPLITS_PER_POLL, "{statistics:?}");
}

/// A chain of forced splits visits no stable sequent, and still stops
/// when asked. Its factors are literals, one split each, or tensors of
/// literals closed in place.
///
/// Each tensor of 5 000 factors is one chain from the first stable
/// sequent. That sequent's poll is the first, and the second comes
/// inside the chain.
#[test]
fn stops_inside_a_forced_chain() {
    let chains = [
        format!(
            "|- {}, {}",
            vec!["a"; 5000].join(" * "),
            vec!["~a"; 5000].join(", ")
        ),
        format!(
            "|- {}, {}",
            vec!["(a * b)"; 5000].join(" * "),
            vec!["~a, ~b"; 5000].join(", ")
        ),
    ];
    for input in chains {
        let (verdict, statistics) = std::thread::Builder::new()
            .stack_size(Limits::default().stack_bytes())
            .spawn(move || {
                let s: Sequent = input.parse().unwrap();
                let forest = Forest::new(&s).unwrap();
                let mut polls = 0;
                search(
                    &forest,
                    s.fragment(),
                    Mode::CLASSICAL,
                    None,
                    &Options::default(),
                    &mut |_| {
                        polls += 1;
                        polls > 1
                    },
                )
            })
            .unwrap()
            .join()
            .unwrap();
        assert!(matches!(verdict, Verdict::Unknown(Reason::Stopped)));
        assert_eq!(statistics.nodes, 1);
        assert!(statistics.splits <= FORCED_PER_POLL, "{statistics:?}");
    }
}

/// Intuitionistic mode gets the textbook sequents of ILL right. It gets
/// right the cases that are easy to get wrong: `0` on the left proves
/// anything, `⊤` on the left is inert, and promotion needs an empty
/// linear context. And it refutes the sequent that classical linear
/// logic proves but intuitionistic linear logic does not.
#[test]
fn intuitionistic() {
    let i = Mode::INTUITIONISTIC;
    for (input, expected) in [
        ("a |- a", true),
        ("|- a -o a", true),
        ("a, a -o b |- b", true),
        ("a -o b, b -o c |- a -o c", true),
        ("a -o b |- b -o a", false),
        ("a * b |- b * a", true),
        ("a * b |- a", false),
        ("a |- a * a", false),
        ("(a * b) -o c |- a -o b -o c", true),
        ("a -o b -o c |- (a * b) -o c", true),
        ("a & b |- a", true),
        ("a & b |- a * b", false),
        ("a * b |- a & b", false),
        ("a |- a + b", true),
        ("a + b |- a", false),
        ("a + b |- b + a", true),
        ("a & (b + c) |- (a & b) + (a & c)", false),
        ("a * (b + c) |- (a * b) + (a * c)", true),
        ("(a -o b) -o a |- a", false),
        ("|- ((a -o b) -o a) -o a", false),
        ("(a -o 0) -o 0 |- a", false),
        ("|- 1", true),
        ("1 |- 1", true),
        ("a |- 1", false),
        ("1, a |- a", true),
        ("|- top", true),
        ("a |- top", true),
        ("a |- 0", false),
        // `0` on the left proves anything, `⊤` on the left is inert.
        ("0 |- a", true),
        ("0, b |- a", true),
        ("a -o 0, a |- b", true),
        ("a -o 0 |- a -o b", true),
        ("top |- a", false),
        ("top |- top", true),
        ("a, top |- a", false),
        ("top, 0 |- a", true),
        ("a -o top, a |- b", false),
        // `0` and `⊤` stand on the side they were written on.
        ("0 |- top", true),
        // Promotion needs an empty linear context.
        ("!a |- !a", true),
        ("a |- !a", false),
        ("!a, b |- !a", false),
        ("!a, !b |- !a", true),
        ("!a |- a * a", true),
        ("!a, !(a -o b) |- !b", true),
        ("!(a & b) |- !a * !b", true),
        ("!a * !b |- !(a & b)", true),
        ("!a, !(a -o b & c) |- b * c", true),
        ("!(a -o top), a |- b", false),
        ("!a, !(a -o 0) |- b", true),
    ] {
        assert_eq!(provable(input, i), expected, "{input:?}");
    }
    // Classical linear logic is not conservative over ILL with `0`. The
    // classical proof splits the `⊸L` with the goal on the antecedent's
    // side, which the two-sided search never does.
    let schellinx = "((a * top) & (b * top)) -o 0 |- (a -o c) + (b -o c)";
    assert!(provable(schellinx, Mode::CLASSICAL));
    assert!(!provable(schellinx, i));
    // Affine mode weakens hypotheses at the leaves, never the goal, and
    // lets promotion discard the linear context.
    for (input, expected) in [
        ("a, b |- a", true),
        ("a |- b", false),
        ("a |- 1", true),
        ("!a, b |- !a", true),
        ("a, b |- a * b", true),
        ("top |- a", false),
        ("a, top |- a", true),
        ("a & b |- a", true),
        ("!(a -o a * a), a |- a * a * a", true),
    ] {
        assert_eq!(provable(input, i.with_affine()), expected, "{input:?}");
    }
}

/// The classic MELL sequents: dereliction, weakening, contraction with
/// and without promotion, and what is unprovable, all within the
/// default copy bound.
#[test]
fn classic_exponentials() {
    let m = Mode::CLASSICAL;
    for (input, expected) in [
        ("!a |- a", true),
        ("!a |- 1", true),
        ("!a |- a * a", true),
        ("!a |- !a * !a", true),
        ("|- !(a -o a)", true),
        ("!a, !(a -o b) |- !b", true),
        ("!a, !a |- a", true),
        ("!a |- !!a", true),
        ("!!a |- !a", true),
        ("!a * !b |- !(a * b)", true),
        ("!a, !(a -o b), !(b -o c) |- !c", true),
        ("|- ?a, ?~a", true),
        ("!a, !~a |- 1", true),
        ("?a |- ?a par ?a", true),
        ("|- !1", true),
        ("a |- !a", false),
        ("?a |- a", false),
        ("!a |- b", false),
        ("!a, !(a -o b) |- c", false),
        // Every copy leaves a `b` that nothing consumes, which the counts
        // see at any bound.
        ("!(a * b) |- a", false),
        ("|- ?a", false),
        ("|- ?a, ?b, ~a", true),
        ("|- ?a, b, ~a", false),
        ("|- 0, ?top", true),
        ("|- ~b, 0 par (c * (0 + a)), ?(top + b)", true),
        ("|- 0, ?a", false),
    ] {
        assert_eq!(provable(input, m), expected, "{input:?}");
    }
    // Unprovable, but every copy grows the context, so no level of the
    // bound finishes, and the answer is unknown.
    for input in ["!(a * b) |- !a * !b", "!(a + b) |- !a + !b"] {
        assert!(
            matches!(
                run(input, m, &Options::default()).0,
                Verdict::Unknown(Reason::CopyBound { copies: 3 })
            ),
            "{input:?}"
        );
    }
}

/// Full LL: the additive and the dyadic rules compose, with and
/// without Mix.
#[test]
fn full_ll() {
    for (input, expected) in [
        ("!(a & b) |- !a * !b", true),
        ("!a * !b |- !(a & b)", true),
        ("?a par ?b |- ?(a + b)", true),
        ("?(a + b) |- ?a par ?b", true),
        ("!(a & b) |- !a & !b", true),
        ("!(a & b) |- !(a * b)", true),
        ("!a & !b |- !(a & b)", false),
        ("!a, !(a -o b & c) |- b * c", true),
        ("!(a -o top) |- b", false),
        ("!(a -o top), a |- b", false),
        ("!(a -o top), a |- top", true),
        ("!(0 -o a) |- a", false),
        ("!a, !(a -o 0) |- b", true),
    ] {
        assert_eq!(provable(input, Mode::CLASSICAL), expected, "{input:?}");
    }
    // The opponent chooses the side of the `&`, so it is unprovable. The
    // context grows with every copy, so it stays undecided within the
    // bound.
    assert!(matches!(
        run(
            "!a, !(a -o b + c) |- b * c",
            Mode::CLASSICAL,
            // The classical refuter would find b true and c false.
            &Options::default().with_classical_work(0)
        )
        .0,
        Verdict::Unknown(Reason::CopyBound { copies: 3 })
    ));
    let mix = Mode::CLASSICAL.with_mix();
    for (input, without, with) in [
        ("!a |- a, 1", false, true),
        ("!a, !b |- a * b, a", false, true),
        ("!a |- a, b", false, false),
    ] {
        assert_eq!(provable(input, Mode::CLASSICAL), without, "{input:?}");
        assert_eq!(provable(input, mix), with, "{input:?} with Mix");
    }
}

/// Affine mode proves what needs weakening and nothing more, in every
/// fragment, and decides what linear mode cannot.
#[test]
fn affine() {
    let affine = Mode::CLASSICAL.with_affine();
    for (input, linear, weakened) in [
        ("a |- 1", false, true),
        ("a, b |- a", false, true),
        ("a * b |- a", false, true),
        ("|- a, ~a, b", false, true),
        ("a & b |- 1", false, true),
        ("a |- 0 + 1", false, true),
        ("|- 0, a, ~a", false, true),
        ("!a, b |- a", false, true),
        ("a |- !1", false, true),
        ("a |- !b", false, false),
        ("|- a, b", false, false),
        ("|- 0", false, false),
        ("a * b |- a * b", true, true),
        ("a |- a * a", false, false),
        ("!a |- a * a", true, true),
        ("a & b |- a + b", true, true),
        ("(a * b) par c |- a, b, c", false, true),
        ("a -o b |- b", false, false),
    ] {
        assert_eq!(provable(input, Mode::CLASSICAL), linear, "{input:?}");
        assert_eq!(provable(input, affine), weakened, "{input:?} affinely");
    }
    // The context grows with every copy, so both modes give up at the
    // bound. A sequent that contains an ancestor is not redundant, and
    // affine mode is bounded like linear mode.
    let growing = "!(a -o a * a), a |- ?b";
    for mode in [Mode::CLASSICAL, affine] {
        assert!(matches!(
            // The classical refuter would find b false.
            run(growing, mode, &Options::default().with_classical_work(0)).0,
            Verdict::Unknown(Reason::CopyBound { copies: 3 })
        ));
    }
    // A sequent proved only through a larger one above it.
    for input in [
        "|- ?(a par ~a)",
        "|- ?!1",
        "!(a * ~a) |-",
        "|- ?(a par ~a), b",
    ] {
        assert!(provable(input, affine), "{input:?}");
    }
    // Weakening goes below a promotion, never above it.
    let (verdict, _) = run("b |- !(a -o a)", affine, &Options::default());
    let proof = verdict.proof().unwrap();
    let Node::Weaken(_, below) = proof.node(proof.root()) else {
        panic!("the leftover is weakened at the root");
    };
    assert!(matches!(proof.node(below), Node::Bang(..)));
}

/// The copy bound of one search, the backward one here. A level that hit
/// its bound never answers `Unprovable`, and a level that did not answers
/// it. A failure recorded at a smaller remaining budget is not reused at
/// a larger one. The bound is per branch.
#[test]
fn copy_bound() {
    let m = Mode::CLASSICAL;
    // The search alone, since the classical refuter would decide what
    // the bound leaves undecided.
    let with = |copies| {
        Options::default()
            .with_bias(Bias::Rarer)
            .with_copies(Some(copies))
            .with_classical_work(0)
    };
    // ⊢ ?~a, a needs one copy: bound 0 is hit, bound 1 proves.
    assert!(matches!(
        run("!a |- a", m, &with(0)).0,
        Verdict::Unknown(Reason::CopyBound { copies: 0 })
    ));
    assert!(run("!a |- a", m, &with(1)).0.proof().is_some());
    // ⊢ ?~a, a ⊗ a: the stable sequent ⊢ ~a ; a fails at level 0 for
    // lack of budget and must be searched again at level 1.
    assert!(run("!a |- a * a", m, &with(1)).0.proof().is_some());
    // The clause and one `~a` are copied on every branch to an `a`. So
    // the bound is 2, however many branches there are. The two branches
    // of ⊢ ?~a, (a ⊗ a) ⊗ a take one copy each.
    assert!(matches!(
        run("!a, !(a -o a -o a -o b) |- b", m, &with(1)).0,
        Verdict::Unknown(Reason::CopyBound { copies: 1 })
    ));
    assert!(
        run("!a, !(a -o a -o a -o b) |- b", m, &with(2))
            .0
            .proof()
            .is_some()
    );
    assert!(run("!a |- (a * a) * a", m, &with(1)).0.proof().is_some());
    // Unprovable, decided at a level that never hit the bound: after
    // one copy of ~a nothing is left to copy. (⊢ ?~a, b is refuted by
    // the balance of b before any copy.)
    assert!(matches!(
        run("!a |- b", m, &with(0)).0,
        Verdict::Unprovable(_)
    ));
    // ⊢ ?~a, ?b: level 0 can copy nothing. At level 1, each copy leaves a
    // literal that the copies to come, all of its own sign, cannot
    // balance, so the counts refute both.
    assert!(matches!(
        run("!a |- ?b", m, &with(0)).0,
        Verdict::Unknown(Reason::CopyBound { copies: 0 })
    ));
    for copies in [1, 2] {
        assert!(matches!(
            run("!a |- ?b", m, &with(copies)).0,
            Verdict::Unprovable(_)
        ));
    }
    // The loop check decides a sequent whose copies repeat a stable
    // sequent, without a bound to hit.
    assert!(matches!(
        run("!(a -o a), a |- b", m, &with(1)).0,
        Verdict::Unprovable(_)
    ));
    // A growing context is never decided within a bound.
    for copies in [0, 2, 5] {
        assert!(matches!(
            run("!(a -o a * a), a |- ?b", m, &with(copies)).0,
            Verdict::Unknown(Reason::CopyBound { copies: c }) if c == copies
        ));
    }
    assert_eq!(
        Reason::CopyBound { copies: 3 }.to_string(),
        "the copy bound of 3 was reached"
    );
}

/// The memo makes no difference to a MELL verdict, with and without
/// the copy bound binding, and the entries survive across levels.
#[test]
fn memo_across_levels() {
    for input in [
        "!a, !(a -o b), !(b -o c) |- c * c * c",
        "!(a -o a * a), a |- b",
        "!a, !(a -o b) |- c",
        "!(a & b) |- !a * !b",
    ] {
        for copies in [1, 3] {
            let options = Options::default().with_copies(Some(copies));
            let (with, stats) = run(input, Mode::CLASSICAL, &options);
            let (without, _) = run(input, Mode::CLASSICAL, &options.clone().with_memo_limit(0));
            assert_eq!(
                std::mem::discriminant(&with),
                std::mem::discriminant(&without),
                "{input:?} at {copies} copies: {with:?} with the memo, {without:?} without"
            );
            if copies == 3 && input.contains("c * c * c") {
                assert!(with.proof().is_some());
                assert!(stats.memo_hits > 0, "{input:?}: the memo was used");
            }
        }
    }
}

/// The dyadic proofs the engine finds unfold into the standard
/// derivations, with dereliction, contraction, weakening and promotion
/// where they belong.
#[test]
fn exponential_derivations() {
    let render = |input: &str, mode: Mode| {
        let (verdict, _) = run(input, mode, &Options::default());
        verdict.proof().unwrap().derivation().unwrap().to_string()
    };
    assert_eq!(
        render("!A |- A", Mode::CLASSICAL),
        ["─────── ax", "⊢ ~A, A", "──────── ?d", "⊢ ?~A, A"].join("\n")
    );
    assert_eq!(
        render("!A |- 1", Mode::CLASSICAL),
        ["  ─── 1", "  ⊢ 1", "──────── ?w", "⊢ ?~A, 1"].join("\n")
    );
    assert_eq!(
        render("!A |- A * A", Mode::CLASSICAL),
        [
            "─────── ax    ─────── ax",
            "⊢ ~A, A       ⊢ ~A, A",
            "──────── ?d   ──────── ?d",
            "⊢ ?~A, A      ⊢ ?~A, A",
            "────────────────────── ⊗",
            "  ⊢ ?~A, ?~A, A ⊗ A",
            "  ───────────────── ?c",
            "    ⊢ ?~A, A ⊗ A",
        ]
        .join("\n")
    );
    assert_eq!(
        render("!A, !(A -o B) |- !B", Mode::CLASSICAL),
        [
            "─────── ax",
            "⊢ ~A, A",
            "──────── ?d   ─────── ax",
            "⊢ ?~A, A      ⊢ ~B, B",
            "───────────────────── ⊗",
            "  ⊢ ?~A, A ⊗ ~B, B",
            " ─────────────────── ?d",
            " ⊢ ?~A, ?(A ⊗ ~B), B",
            " ──────────────────── !",
            " ⊢ ?~A, ?(A ⊗ ~B), !B",
        ]
        .join("\n")
    );
    assert_eq!(
        render("A, B |- A", Mode::CLASSICAL.with_affine()),
        ["  ─────── ax", "  ⊢ ~A, A", "─────────── wk", "⊢ ~A, ~B, A",].join("\n")
    );
}

/// The mode a generated sequent is proved in.
fn mode_for(rules: Rules) -> Mode {
    if rules.mix {
        Mode::CLASSICAL.with_mix()
    } else {
        Mode::CLASSICAL
    }
}

/// The verdict of `input` under `mode` with `options`, as a three-way
/// value: provable, unprovable, or undecided within the copy bound.
fn decided(input: &str, mode: Mode, options: &Options) -> Option<bool> {
    match run(input, mode, options).0 {
        Verdict::Proved(_) => Some(true),
        Verdict::Unprovable(_) => Some(false),
        Verdict::Unknown(Reason::CopyBound { .. }) => None,
        Verdict::Unknown(reason) => panic!("{input:?}: {reason}"),
    }
}

/// The work a generated mutant's search gets in the tests that compare
/// verdicts on mutants.
///
/// Measured on the tests' seeds, a decided mutant took 3.2 million units
/// at most, and nearly all took 0.4 million at most. The few that no copy
/// bound decides took up to 166 million, some seconds each in a debug
/// build, and comparing two undecided verdicts says nothing.
const MUTANT_WORK: u64 = 5_000_000;

/// Decides `input` as [`decided`] does within [`MUTANT_WORK`], and also
/// returns whether the work ran out.
fn bounded(input: &str, mode: Mode, options: &Options) -> (Option<bool>, bool) {
    let limits = Limits::default().with_work(Some(MUTANT_WORK));
    match run_within(input, mode, options, &limits).0 {
        Verdict::Proved(_) => (Some(true), false),
        Verdict::Unprovable(_) => (Some(false), false),
        Verdict::Unknown(Reason::CopyBound { .. }) => (None, false),
        Verdict::Unknown(Reason::WorkLimit { .. }) => (None, true),
        Verdict::Unknown(reason) => panic!("{input:?}: {reason}"),
    }
}

/// Proves `samples` generated sequents of up to `budget` rules per rule
/// set, with or without exponentials, each within the derelictions of
/// its proof. Decides one mutant of each with and without the memo,
/// within [`MUTANT_WORK`].
///
/// Returns, in order: how many sequents and how many mutants were
/// decided; how many mutants were provable; how many the memo's search
/// left undecided within the copy bound; how many a search ran past the
/// work; and the most stable sequents one search visited.
fn generated(samples: u64, budget: usize, exponentials: bool) -> (u64, u64, u64, u64, u64, u64) {
    let (mut sequents, mut mutants, mut provable_mutants, mut undecided, mut over, mut most_nodes) =
        (0, 0, 0, 0, 0, 0);
    for (i, rules) in Rules::ALL.into_iter().enumerate() {
        if rules.exponentials != exponentials {
            continue;
        }
        let mode = mode_for(rules);
        let mut rng = Rng::new(i as u64);
        for _ in 0..samples {
            let budget = 2 + rng.below(budget - 1);
            let generate::Provable {
                mut formulas,
                copies,
            } = generate::provable(&mut rng, rules, 3, budget);
            let text = generate::sequent(&formulas);
            let options = Options::default().with_copies(Some(copies));
            let (verdict, statistics) = run(&text, mode, &options);
            assert!(
                verdict.proof().is_some(),
                "{text:?} is provable in {mode} mode within {copies} copies, but the engine \
                 says {verdict:?}"
            );
            // A linear proof is an affine proof.
            let (affine, _) = run(&text, mode.with_affine(), &options);
            assert!(
                affine.proof().is_some(),
                "{text:?} is provable in {} mode within {copies} copies, but the engine \
                 says {affine:?}",
                mode.with_affine()
            );
            sequents += 1;
            most_nodes = most_nodes.max(statistics.nodes);
            if generate::mutate(&mut rng, &mut formulas, 3) {
                let text = generate::sequent(&formulas);
                let (with_memo, out) = bounded(&text, mode, &Options::default());
                let (without, too) = bounded(&text, mode, &Options::default().with_memo_limit(0));
                over += u64::from(out || too);
                // The memo never contradicts the memo-free search. Either
                // may decide where the other is undecided within the
                // bound, since an entry cut by the budget is a fact about
                // the sequent alone, while the loop check is a fact about
                // the branch.
                assert!(
                    with_memo.is_none() || without.is_none() || with_memo == without,
                    "{text:?} in {mode} mode: {with_memo:?} with the memo, {without:?} without"
                );
                mutants += 1;
                provable_mutants += u64::from(with_memo == Some(true));
                undecided += u64::from(with_memo.is_none() && !out);
            }
        }
    }
    (
        sequents,
        mutants,
        provable_mutants,
        undecided,
        over,
        most_nodes,
    )
}

/// Every generated provable sequent is proved with a checked proof within
/// the derelictions of its proof, in every fragment, with and without
/// Mix. Its mutant gets no contradicting verdicts with and without the
/// memo.
///
/// Without exponentials, the memo's search leaves no mutant undecided
/// within the copy bound. With them, it leaves fewer than a quarter. Fewer
/// than one mutant in fifty has a search run past [`MUTANT_WORK`].
#[test]
fn generated_sequents() {
    let (sequents, mutants, _, undecided, over, _) = generated(40, 10, false);
    assert_eq!(sequents, 320);
    assert!(mutants > 200, "{mutants} mutants");
    assert_eq!(undecided, 0);
    assert!(over * 50 < mutants, "{over} of {mutants} past the work");
    let (sequents, mutants, _, undecided, over, _) = generated(40, 10, true);
    assert_eq!(sequents, 320);
    assert!(mutants > 200, "{mutants} mutants");
    assert!(
        undecided < mutants / 4,
        "{undecided} of {mutants} mutants undecided"
    );
    assert!(over * 50 < mutants, "{over} of {mutants} past the work");
}

/// Proves `samples` generated intuitionistic sequents of up to `budget`
/// rules per rule set, each within the derelictions of its proof, in
/// linear and affine mode.
///
/// It also decides each sequent with the classical engine, on the same
/// one-sided sequent, and a mutant of each with both engines within
/// [`MUTANT_WORK`]. The verdicts must agree, except where `0` lets
/// classical linear logic prove more.
///
/// Returns, in order: how many sequents and how many mutants were
/// compared; how many mutants the classical engine proved that the
/// two-sided one refuted, which only `0` allows; and how many mutants an
/// engine searched past the work.
fn generated_ill(samples: u64, budget: usize) -> (u64, u64, u64, u64) {
    use crate::linear::search::generate::IllRules;
    let i = Mode::INTUITIONISTIC;
    let (mut sequents, mut mutants, mut non_conservative, mut over) = (0, 0, 0, 0);
    for (n, rules) in IllRules::ALL.into_iter().enumerate() {
        let mut rng = Rng::new(100 + n as u64);
        for _ in 0..samples {
            let budget = 2 + rng.below(budget - 1);
            let generate::Ill {
                mut hypotheses,
                mut goal,
                copies,
                ..
            } = generate::ill(&mut rng, rules, 3, budget);
            let text = generate::two_sided(&hypotheses, &goal);
            let options = Options::default().with_copies(Some(copies));
            let (verdict, _) = run(&text, i, &options);
            assert!(
                verdict.proof().is_some(),
                "{text:?} is provable in ILL within {copies} copies, but the engine says \
                 {verdict:?}"
            );
            let (affine, _) = run(&text, i.with_affine(), &options);
            assert!(affine.proof().is_some(), "{text:?} affine: {affine:?}");
            sequents += 1;
            // The classical engine on the same one-sided sequent.
            let classical = decided(&text, Mode::CLASSICAL, &options);
            assert!(
                classical != Some(false),
                "{text:?} is provable in ILL, so classically too, but the engine says \
                 {classical:?}"
            );
            if generate::mutate_two_sided(&mut rng, &mut hypotheses, &mut goal, 3) {
                let text = generate::two_sided(&hypotheses, &goal);
                let (two_sided, out) = bounded(&text, i, &Options::default());
                let (classical, too) = bounded(&text, Mode::CLASSICAL, &Options::default());
                over += u64::from(out || too);
                match (two_sided, classical) {
                    (Some(true), Some(false)) => panic!("{text:?}: provable in ILL only"),
                    (Some(false), Some(true)) => {
                        assert!(rules.zero, "{text:?}: provable classically only");
                        non_conservative += 1;
                    }
                    _ => {}
                }
                mutants += 1;
            }
        }
    }
    (sequents, mutants, non_conservative, over)
}

/// Every generated intuitionistic sequent is proved two-sided with a
/// checked proof within the derelictions of its proof, in every
/// intuitionistic fragment. The classical engine agrees on the mutants,
/// except where `0` makes classical linear logic prove more.
#[test]
fn generated_intuitionistic_sequents() {
    let (sequents, mutants, non_conservative, over) = generated_ill(40, 10);
    assert_eq!(sequents, 480);
    assert!(mutants > 300, "{mutants} mutants");
    assert!(
        non_conservative < mutants / 10,
        "{non_conservative} of {mutants}"
    );
    assert!(over * 50 < mutants, "{over} of {mutants} past the work");
}

/// The counts of an atom whose literals below the exponentials all have
/// one sign refute nothing that has a proof.
///
/// The test takes mutants of generated sequents with exponentials:
/// classical with and without Mix, and intuitionistic. None that a search
/// with those counts refutes at a copy bound of 3 is proved by the search
/// without them at a bound of 4, within [`MUTANT_WORK`] each. And the
/// counts do some work: they refute some mutants at the root of the
/// sequent, and some that the search without them leaves undecided.
#[test]
fn the_count_of_one_sign_refutes_nothing_provable() {
    use crate::linear::search::Refutation;
    use crate::linear::search::generate::IllRules;
    let limits = Limits::default().with_work(Some(MUTANT_WORK));
    // One search on this thread, since the switch that turns the counts
    // off is local to the thread.
    let decide = |text: &str, mode: Mode, bias: Bias, copies: u32| {
        let options = Options::default()
            .with_bias(bias)
            .with_copies(Some(copies))
            .with_jobs(1);
        run_within(text, mode, &options, &limits).0
    };
    let (mut mutants, mut refuted, mut at_the_root, mut gained) = (0, 0, 0, 0);
    let mut judge = |text: &str, mode: Mode| {
        mutants += 1;
        for bias in [Bias::Rarer, Bias::Factors] {
            let Verdict::Unprovable(disproof) = decide(text, mode, bias, 3) else {
                continue;
            };
            refuted += 1;
            at_the_root += u64::from(matches!(disproof.refutation(), Refutation::OneSided(_)));
            let without = counts::without_one_sided(|| decide(text, mode, bias, 4));
            assert!(
                without.proof().is_none(),
                "{text:?} in {mode} mode under {bias:?}: refuted with the counts of one sign, \
                 proved without them"
            );
            gained += u64::from(!matches!(without, Verdict::Unprovable(_)));
        }
    };
    for (i, rules) in Rules::ALL.into_iter().enumerate() {
        if !rules.exponentials {
            continue;
        }
        let mut rng = Rng::new(200 + i as u64);
        for _ in 0..100 {
            let budget = 2 + rng.below(9);
            let mut formulas = generate::provable(&mut rng, rules, 3, budget).formulas;
            if generate::mutate(&mut rng, &mut formulas, 3) {
                judge(&generate::sequent(&formulas), mode_for(rules));
            }
        }
    }
    for (n, rules) in IllRules::ALL.into_iter().enumerate() {
        if !rules.exponentials {
            continue;
        }
        let mut rng = Rng::new(300 + n as u64);
        for _ in 0..100 {
            let budget = 2 + rng.below(9);
            let generate::Ill {
                mut hypotheses,
                mut goal,
                ..
            } = generate::ill(&mut rng, rules, 3, budget);
            if generate::mutate_two_sided(&mut rng, &mut hypotheses, &mut goal, 3) {
                judge(
                    &generate::two_sided(&hypotheses, &goal),
                    Mode::INTUITIONISTIC,
                );
            }
        }
    }
    let numbers = format!(
        "{mutants} mutants, {refuted} refutations, {at_the_root} at the root, {gained} \
         undecided without the counts of one sign"
    );
    // Measured with these seeds: 1 227 mutants, 1 352 refutations, 30 at
    // the root and 64 left undecided without the counts.
    assert!(at_the_root >= 10 && gained >= 30, "{numbers}");
}

/// Encodes a Horn program with reusable clauses, as the ILLTP library
/// states Petri-net reachability. Every clause `body ⊸ head` (products of
/// atoms) is under a `!`. The initial marking is the hypotheses, and the
/// goal marking the conclusion.
fn horn(clauses: &[(&str, &str)], marking: &[&str], goal: &[&str]) -> String {
    let mut hypotheses: Vec<String> = clauses
        .iter()
        .map(|(body, head)| format!("!({body} -o {head})"))
        .collect();
    hypotheses.extend(marking.iter().map(|a| (*a).to_string()));
    format!("{} |- {}", hypotheses.join(", "), goal.join(" * "))
}

/// The counter program: `n` tokens `a`, two `a` make a `b`, two `b` a
/// `c`, and so on up the alphabet, with `n` a power of two.
fn counter(n: usize) -> (Vec<(String, String)>, Vec<&'static str>, &'static str) {
    let levels = n.trailing_zeros() as usize;
    let names = ["a", "b", "c", "d", "e", "f"];
    let clauses = (0..levels)
        .map(|i| {
            (
                format!("{} * {}", names[i], names[i]),
                names[i + 1].to_string(),
            )
        })
        .collect();
    (clauses, vec!["a"; n], names[levels])
}

/// Horn problems over reusable clauses:
/// - a chain of implications takes one copy per clause on one branch;
/// - the counter program reaches its goal within the copies its firings
///   take, and not below;
/// - an unreachable marking is refuted by the counts where an atom is
///   only a body's or only a head's below the `!`, and else by the
///   forward search alone;
/// - in affine mode, which reaches a goal that leaves a token over, an
///   unreachable marking is undecided within the bound.
#[test]
fn horn_programs() {
    let m = Mode::CLASSICAL;
    let chain: Vec<(String, String)> = (0..6)
        .map(|i| (format!("x{i}"), format!("x{}", i + 1)))
        .collect();
    let chain: Vec<(&str, &str)> = chain.iter().map(|(b, h)| (&**b, &**h)).collect();
    let text = horn(&chain, &["x0"], &["x6"]);
    assert!(
        run(&text, m, &Options::default().with_copies(Some(6)))
            .0
            .proof()
            .is_some()
    );
    // Five copies are too few for either search alone. The default's
    // forward search has a bound of its own on Horn clauses.
    for bias in [Bias::Rarer, Bias::Factors] {
        assert!(matches!(
            run(
                &text,
                m,
                &Options::default().with_bias(bias).with_copies(Some(5))
            )
            .0,
            Verdict::Unknown(Reason::CopyBound { copies: 5 })
        ));
    }
    assert!(
        run(&text, m, &Options::default().with_copies(Some(5)))
            .0
            .proof()
            .is_some()
    );
    assert!(matches!(
        run(
            &text,
            m,
            &Options::default()
                .with_copies(Some(5))
                .with_forward_copies(0)
        )
        .0,
        Verdict::Unknown(Reason::CopyBound { copies: 5 })
    ));

    let (clauses, marking, goal) = counter(4);
    let clauses: Vec<(&str, &str)> = clauses.iter().map(|(b, h)| (&**b, &**h)).collect();
    assert!(provable(&horn(&clauses, &marking, &[goal]), m));
    // A goal no firing reaches. Below the `!` an `a` is only a body's
    // and a `c` only a head's, so the counts bound what copies can
    // balance, and the backward search ends without a cut.
    let rarer = Options::default().with_bias(Bias::Rarer);
    assert!(matches!(
        run(&horn(&clauses, &marking, &[goal, "a"]), m, &rarer).0,
        Verdict::Unprovable(_)
    ));
    // With a clause from `c` back to `a`, both are heads and bodies, and
    // the counts say nothing of them. The backward search is cut at its
    // bound, and the forward one runs out of markings within its own.
    let mut back = clauses.clone();
    back.push(("c", "a"));
    let unreachable = horn(&back, &marking, &[goal, "a"]);
    assert!(matches!(
        run(&unreachable, m, &rarer).0,
        Verdict::Unknown(Reason::CopyBound { copies: 3 })
    ));
    assert!(matches!(
        run(&unreachable, m, &Options::default()).0,
        Verdict::Unprovable(_)
    ));
    assert!(matches!(
        run(
            &horn(&clauses, &marking, &[goal, "a"]),
            m.with_affine(),
            &Options::default()
        )
        .0,
        Verdict::Unknown(Reason::CopyBound { copies: 3 })
    ));
    let mut five = marking.clone();
    five.push("a");
    assert!(matches!(
        run(&horn(&clauses, &five, &[goal]), m, &Options::default()).0,
        Verdict::Unprovable(_)
    ));
    assert!(provable(&horn(&clauses, &five, &[goal]), m.with_affine()));
}

/// A 3-Partition instance with a solution is proved: the first bin
/// choices work out, so the search is short.
#[test]
fn three_partition_solved() {
    let yes = crate::linear::families::three_partition(&[1, 2, 3, 1, 2, 3], 2, 6).to_string();
    assert!(provable(&yes, Mode::CLASSICAL), "{yes}");
}

/// The Horn test reads the goal, not the forest's roots.
///
/// Here the goal holds the clause, the marking and the goal of a program,
/// so it is a Horn program. The sequent around it is not, since its other
/// hypothesis is a `&`. So the forward search gets its own bound on that
/// goal, and not on the whole sequent.
#[test]
fn the_horn_test_reads_the_goal() {
    let sequent: Sequent = "!(a -o b), a, c & d |- b".parse().unwrap();
    let forest = Forest::new(&sequent).unwrap();
    let roots = forest.roots();
    let program: Vec<OccId> = roots
        .iter()
        .copied()
        .filter(|&r| forest.kind(r) != Kind::Plus)
        .collect();
    assert_eq!(program.len(), 3);
    assert!(!schedule::chains(&forest, roots));
    assert!(schedule::chains(&forest, &program));
    let options = Options::default().with_forward_copies(30);
    let forward = |goal: &[OccId]| {
        plan(&forest, goal, sequent.fragment(), Mode::CLASSICAL, &options)
            .0
            .copies
    };
    assert_eq!(forward(roots), Options::DEFAULT_COPIES);
    assert_eq!(forward(&program), 30);

    // A clause that a dereliction left in the linear zone, used once, is
    // a step of the program too. The goal it leaves to close is proved
    // within the forward bound, as the sequent is.
    let sequent: Sequent =
        "!(a -o b), !(b -o c), !(c -o d), !(d -o e), !(e -o f), !(f -o g), a |- g"
            .parse()
            .unwrap();
    let forest = Forest::new(&sequent).unwrap();
    let mut goal = forest.roots().to_vec();
    for derelicted in &mut goal[1..3] {
        *derelicted = forest.left(*derelicted).unwrap();
    }
    assert!(schedule::chains(&forest, &goal));
    let goal: Vec<_> = goal.into_iter().map(crate::linear::Member::from).collect();
    for mode in [Mode::CLASSICAL, Mode::INTUITIONISTIC] {
        let limits = Limits::default();
        let outcome = prove_goal(
            Goal::new(&forest, &goal).unwrap(),
            mode,
            &Options::default(),
            &limits,
            |_| false,
        )
        .unwrap();
        assert!(matches!(outcome.verdict, Verdict::Proved(_)), "{mode}");
    }
}

/// Under Mix, a sequent none of whose parts is provable is refuted by its
/// parts with one member less.
///
/// The twelve members of `mix(6)` cost at most `12 · 2¹²` stable
/// sequents. Searching the partitions of every part instead would visit
/// 175 100, a third of `3¹²`.
#[test]
fn unprovable_parts_cost_no_partitions() {
    let sequent = crate::linear::families::mix(6);
    let forest = Forest::new(&sequent).unwrap();
    let (verdict, statistics) = search(
        &forest,
        sequent.fragment(),
        Mode::CLASSICAL.with_mix(),
        None,
        &Options::default(),
        &mut |_| false,
    );
    assert!(matches!(verdict, Verdict::Unprovable(_)), "{verdict:?}");
    assert!(statistics.nodes <= 12 << 12, "{statistics:?}");
}

/// A tensor of three hundred factors whose splits are searched is one
/// chain, searched in a loop with no level of recursion per link. So it
/// is proved under a recursion limit of a hundred.
#[test]
fn a_chain_of_free_splits_costs_one_level() {
    let sequent = crate::linear::families::wide(300, 1);
    let options = Options::default().with_engine(Some(crate::linear::search::Engine::Focus));
    let limits = Limits::default().with_recursion_depth(100);
    let outcome =
        crate::linear::search::prove_within(&sequent, Mode::CLASSICAL, &options, &limits, |_| {
            false
        })
        .unwrap();
    let Verdict::Proved(proof) = outcome.verdict else {
        panic!("{:?}", outcome.verdict);
    };
    assert_eq!(proof.check(Mode::CLASSICAL), Ok(()));
}

/// The parts of a Mix decide a sequent only where they are complete facts
/// and a memo keeps them.
///
/// A part cut by the copy budget, which the partitions never visit, must
/// not decide: it would leave `⊢ a, !?(s ⅋ a)` at its copy bound, where
/// the partitions refute it. Without a memo, searching the parts again at
/// every level would take two more levels of recursion than the
/// partitions to prove `⊢ ~b, ~c, b, ⊥ ⊕ ~b, ?(c ⊗ b)`.
#[test]
fn the_parts_of_a_mix_decide_only_as_facts() {
    let mode = Mode::CLASSICAL.with_mix();
    let (verdict, _) = run("|- a, !?(s par a)", mode, &Options::default());
    assert!(matches!(verdict, Verdict::Unprovable(_)), "{verdict:?}");
    let options = Options::default().with_copies(Some(1)).with_memo_limit(0);
    let limits = Limits::default().with_recursion_depth(9);
    let (verdict, _) = run_within(
        "|- ~b, ~c, b, (bot + ~b), ?(c * b)",
        mode,
        &options,
        &limits,
    );
    assert!(verdict.proof().is_some(), "{verdict:?}");
}

/// With weakening, Mix proves nothing new, so the engine leaves it out.
///
/// Affine mode with Mix searches exactly what affine mode does. It
/// refutes the four pairs of the Mix family in 32 265 stable sequents,
/// where trying Mix as well would take 46 537.
#[test]
fn affine_mode_leaves_mix_out() {
    let sequent = crate::linear::families::mix(4);
    let forest = Forest::new(&sequent).unwrap();
    let decide = |mode: Mode| {
        search(
            &forest,
            sequent.fragment(),
            mode,
            None,
            &Options::default(),
            &mut |_| false,
        )
    };
    let (with, with_statistics) = decide(Mode::CLASSICAL.with_affine().with_mix());
    let (without, without_statistics) = decide(Mode::CLASSICAL.with_affine());
    assert!(matches!(with, Verdict::Unprovable(_)), "{with:?}");
    assert!(matches!(without, Verdict::Unprovable(_)), "{without:?}");
    assert_eq!(with_statistics, without_statistics);
}

/// Interchangeable members share a memo entry.
///
/// The three copies of one `⊕` are chosen in every order. The refutation
/// of the stable sequent they reach is looked up under its canonical
/// key. A search without that key would not find it.
#[test]
fn interchangeable_members_share_an_entry() {
    let input = "|- ~a + ~b, ~a + ~b, ~a + ~b, a * b * b, (x par ~x) * (y * ~y)";
    let (verdict, statistics) = run(input, Mode::CLASSICAL, &Options::default());
    assert!(matches!(verdict, Verdict::Unprovable(_)));
    assert_eq!(
        (
            statistics.nodes,
            statistics.memo_hits,
            statistics.memo_entries
        ),
        (43, 16, 27)
    );
}

/// A `⊗` of `⊗`s of positive literals whose duals lie in the linear zone
/// forces its split down the whole tree. That is one split per `⊗` where
/// weakening is off (classical, Mix), and a search over the contexts
/// where it is on.
#[test]
fn nested_tensors_of_literals_force_their_splits() {
    let input = "|- (a * b) * (c * d), ~a, ~b, ~c, ~d";
    let options = Options::default().with_engine(Some(crate::linear::search::Engine::Focus));
    for mode in [Mode::CLASSICAL, Mode::CLASSICAL.with_mix()] {
        let (verdict, statistics) = run(input, mode, &options);
        assert!(verdict.proof().is_some());
        assert_eq!(statistics.splits, 3, "{mode:?}");
    }
    let (verdict, statistics) = run(input, Mode::CLASSICAL.with_affine(), &options);
    assert!(verdict.proof().is_some());
    assert!(statistics.splits > 30, "{} splits", statistics.splits);
}

/// The default bias's two searches answer as one.
///
/// The answer is, in order of preference:
/// - a verdict of either (the second's with its arena);
/// - else the stop;
/// - else the backward search's reason, as the options and limits name
///   it, whatever the forward search's is.
///
/// The level under the copy bound is the deciding search's, else the
/// backward one's. The forward one's is kept apart.
#[cfg(feature = "parallel")]
#[test]
fn the_pair_answers_by_the_backward_search() {
    use super::schedule::merged;
    use crate::linear::occurrences::Member;
    use crate::linear::search::{Finished, Reason, Statistics};
    let options = Options::default().with_copies(Some(3));
    let limits = Limits::default().with_memory_bytes(Some(1 << 20));
    let finished = |result, copies| Finished {
        result,
        nodes: Vec::new(),
        statistics: Statistics {
            copies,
            ..Statistics::default()
        },
        instances: None,
    };
    let undecided = [
        (
            Reason::CopyBound { copies: 30 },
            Reason::RecursionLimit { depth: 9 },
        ),
        (
            Reason::RecursionLimit { depth: 9 },
            Reason::CopyBound { copies: 2 },
        ),
        (
            Reason::WorkLimit { limit: 5 },
            Reason::MemoryLimit {
                limit_bytes: 1 << 19,
            },
        ),
    ];
    let reasons = undecided.map(|(forward, backward)| {
        let pair = merged(
            finished(Err(forward), 30),
            finished(Err(backward), 2),
            &options,
            &limits,
        );
        (
            pair.result,
            pair.statistics.copies,
            pair.statistics.forward_copies,
        )
    });
    assert_eq!(
        reasons,
        [
            (Err(Reason::RecursionLimit { depth: 9 }), 2, 30),
            (Err(Reason::CopyBound { copies: 3 }), 2, 30),
            (
                Err(Reason::MemoryLimit {
                    limit_bytes: 1 << 20
                }),
                2,
                30
            ),
        ]
    );
    for (forward, backward) in [
        (Err(Reason::Stopped), Err(Reason::CopyBound { copies: 2 })),
        (Err(Reason::CopyBound { copies: 30 }), Err(Reason::Stopped)),
    ] {
        let pair = merged(
            finished(forward, 30),
            finished(backward, 2),
            &options,
            &limits,
        );
        assert_eq!(pair.result, Err(Reason::Stopped));
    }
    let refuted = merged(
        finished(Ok(None), 4),
        finished(Err(Reason::Stopped), 2),
        &options,
        &limits,
    );
    assert_eq!((refuted.result, refuted.statistics.copies), (Ok(None), 4));
    let mut proved = finished(Ok(Some(NodeId::new(0))), 2);
    proved.nodes = vec![Node::One(Member::from(OccId::new(0)))];
    let pair = merged(
        finished(Err(Reason::CopyBound { copies: 30 }), 30),
        proved,
        &options,
        &limits,
    );
    assert_eq!(
        (pair.result, pair.nodes.len(), pair.statistics.copies),
        (Ok(Some(NodeId::new(0))), 1, 2)
    );
}

/// A worker of a pool drops a failure that rests on a stable sequent of
/// the spawning engine's branch, and lets nothing wait on it. The worker
/// never sees that sequent's search close.
///
/// Here one ancestor stands for that branch: the stable sequent
/// `⊢ e ; c, ~c`. The goal's one way on reaches it again, so the loop
/// check prunes it, and the goal's failure rests on depth 0, above the
/// worker's own stack.
#[test]
fn a_worker_drops_what_rests_on_the_spawning_branch() {
    let sequent: Sequent = "|- (c par ~c) + 0, ?e".parse().unwrap();
    let forest = Forest::new(&sequent).unwrap();
    let options = Options::default().with_copies(Some(1));
    let (first, _) = plan(
        &forest,
        forest.roots(),
        sequent.fragment(),
        Mode::CLASSICAL,
        &options,
    );
    let counts = Counts::new(&forest, first.bias);
    let classes = Classes::new(&forest, None);
    let task = crate::linear::search::Task {
        forest: &forest,
        goal: forest.roots(),
        fragment: sequent.fragment(),
        mode: Mode::CLASSICAL,
        reading: None,
        roots: true,
        program: std::sync::OnceLock::new(),
    };
    let set_up = SetUp {
        task: &task,
        classes: &classes,
        options: &options,
        limits: &Limits::default(),
    };
    // `{e}` under the id the run's table gives it, as the run's own `?`
    // rule will find it.
    let mut table = Table::own(options.memo_entries());
    let mut with_e = forest.empty_set();
    with_e.insert(forest.left(forest.roots()[1]).unwrap());
    let account = Account::new(None);
    let mut ancestor = memo::Key {
        theta: table.intern(&with_e, &account),
        ..memo::Key::default()
    };
    let before_e = forest.roots()[1].index();
    ancestor.members.extend(
        (0..before_e)
            .map(|o| OccId::new(o as u32))
            .filter(|&o| matches!(forest.kind(o), Kind::Atom | Kind::DualAtom)),
    );
    let hashes = [ancestor.zones().hash()];
    let branch = [ancestor];
    let mut never = |_| false;
    let mut worker = Run::new(
        Problem::new(set_up, &counts, first.copies, &account),
        Stop::Closure(&mut never),
        table,
        Arena::new(arena::Kept::Own(Vec::new()), &account),
        Ground::new(&forest, &Options::default()),
    );
    worker.ancestors.push((&branch, &hashes));
    assert!(matches!(worker.run(forest.roots()), Ok(None)));
    assert!(worker.waiting.is_empty(), "{:?}", worker.waiting.len());
}

/// A first-order search stops with `Reason::IndexLimit` before it makes a
/// member past the ids it may give.
///
/// Here the test lowers the bound to one short of the forest's length
/// and both instances' spans, so the second instance's span passes it.
/// One more id lets the search prove the sequent.

#[test]
fn a_first_order_search_past_its_member_ids_stops() {
    let sequent: Sequent = "|- exists x. exists y. (p(x) * p(y)), ~p(a), ~p(b)"
        .parse()
        .unwrap();
    let forest = Forest::new(&sequent).unwrap();
    let options = Options::default();
    let search = |limit: u32| {
        framed::MEMBER_LIMIT.with(|cell| cell.set(limit));
        let task = Task {
            forest: &forest,
            goal: forest.roots(),
            fragment: sequent.fragment(),
            mode: Mode::CLASSICAL,
            reading: None,
            roots: true,
            program: std::sync::OnceLock::new(),
        };
        let found = search_goal::<Framed>(
            &task,
            &options,
            &Limits::default(),
            &Account::new(None),
            &Work::new(None),
            &mut |_| false,
        );
        framed::MEMBER_LIMIT.with(|cell| cell.set(u32::MAX));
        found.result
    };
    // The outer `∃` has a body of four occurrences, the inner one of
    // three.
    let n = forest.len() as u32;
    assert_eq!(search(n + 4 + 2), Err(Reason::IndexLimit));
    assert!(matches!(search(n + 4 + 3), Ok(Some(_))));
}