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

//! Intuitionistic and minimal logic decided by a SAT solver, the
//! algorithm of intuit (K. Claessen and D. Rosén, *SAT modulo
//! intuitionistic implications*, LPAR-20, 2015) with the restarts of
//! intuitR (C. Fiorentini, *Efficient SAT-based proof search in
//! intuitionistic propositional logic*, CADE-28, 2021).
//!
//! Every subformula of the sequent is a variable of the solver. Each
//! connective's rules become clauses between a formula and its parts.
//! Most are flat clauses, which hold classically and intuitionistically
//! alike. The exception is the implication clause `(a → b) → c`, where `c`
//! is the variable of `a → b`, one for every implication the sequent needs
//! to prove. The solver cannot read it, so the search handles it.
//!
//! The search looks for worlds: models of the flat clauses in which the
//! goal is false. A world where `a`, `b` and `c` are all false needs a
//! world above it that has `a` and not `b`. The solver looks for one, with
//! `a`, `¬b` and the world as assumptions. Where there is none, the
//! world's assumptions that the refutation used, `A`, give the clause
//! `A → c`. The search learns it and starts again. Where every world has
//! the worlds it needs, they are a Kripke model in which the goal fails.
//! Where the goal holds in every model of the clauses, the sequent is
//! valid.
//!
//! Both answers are checked. "Valid" comes with a derivation of LJ that
//! [`Derivation::check`] accepts. It is read off the learnt clauses and
//! the last call (the correspondence of Fiorentini, Goré and
//! Graham-Lengrand, *A proof-theoretic perspective on SMT-solving for
//! intuitionistic propositional logic*, TABLEAUX 2019), or found by
//! [`ljt`] where a bound refuses that derivation. "Not valid" comes with
//! the Kripke model, which
//! [`Model::refutes`](crate::kripke::Model::refutes) checks. Minimal logic
//! is the same search with `⊥` a variable like an atom.
//!
//! Classical logic takes one call of the solver on the clauses of the
//! sequent's negation (Tseitin's encoding with polarities). "Not valid"
//! comes with a model of one world, the assignment that falsifies the
//! sequent, which [`Model::refutes`](crate::kripke::Model::refutes)
//! checks by evaluation. "Valid" comes with the clauses the solver learnt
//! and deleted, recorded as a clausal proof (DRUP). This module's own
//! checker accepts it by unit propagation against the clauses
//! ([`ClausalProof`]). A clausal proof is no derivation:
//! [`decide`](super::decide()) with
//! [`Method::Embedding`](super::Method::Embedding) gives the derivation of
//! LK.
//!
//! Needs the cargo feature `sat`.
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::Limits;
//! use deduxit::ordinary::{self, Logic, Verdict, sat};
//!
//! let sequent: ordinary::Sequent = "~~(a \\/ ~a)".parse()?;
//! let outcome = sat::decide(&sequent, Logic::Intuitionistic, &Limits::default(), |_| false)?;
//! assert!(matches!(outcome.verdict, Verdict::Valid(_)));
//! let sequent: ordinary::Sequent = "a \\/ ~a".parse()?;
//! let outcome = sat::decide(&sequent, Logic::Intuitionistic, &Limits::default(), |_| false)?;
//! assert!(matches!(outcome.verdict, Verdict::NotValid));
//! let countermodel = outcome.model.expect("a model refutes it");
//! assert_eq!(countermodel.model.worlds.len(), 2);
//! # Ok::<(), deduxit::Error>(())
//! ```

mod classical;
mod drup;
mod read_back;
mod solver;

pub use drup::ClausalProof;

use crate::kripke::{Model, World};

use self::solver::{Answer, Batsat, Lit, MOST_VARIABLES, Solver};
use super::{Derivation, Evidence, Formulas, Logic, Node, NodeId, Sequent, Verdict, ljt};
use crate::Error;
use crate::limits::{Limits, Progress, Refusal};
use crate::linear::search::Reason;
use crate::linear::search::memory::Account;

/// What deciding a sequent by the SAT solver found.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Outcome {
    /// The verdict, with the evidence of a valid sequent: a derivation of
    /// LJ, or in classical logic a clausal proof.
    pub verdict: Verdict,
    /// The logic decided.
    pub logic: Logic,
    /// What the search cost.
    pub statistics: Statistics,
    /// The Kripke model that refutes a sequent that is not valid, with the
    /// sequent, checked. `None` for any other verdict, and where the model
    /// is too large to check.
    pub model: Option<super::Countermodel>,
}

/// What a search by the SAT solver cost.
///
/// # JSON
///
/// With the feature `serialize` it is written and read back as
/// `{"calls": 7, "conflicts": 2, "lemmas": 1, "worlds": 0, "facts": 12,
/// "clauses": 0, "proof_steps": 0, "ljt": null}`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default))]
pub struct Statistics {
    /// The calls of the SAT solver.
    pub calls: u64,
    /// The conflicts the SAT solver met.
    pub conflicts: u64,
    /// The clauses learnt from implications, each followed by a restart.
    pub lemmas: u64,
    /// The worlds of the model that refutes the sequent, counted also where
    /// the model is too large to keep.
    pub worlds: u64,
    /// The facts the read-back of the derivation derived.
    pub facts: u64,
    /// In classical logic, the clauses of the sequent's negation the
    /// solver was given.
    pub clauses: u64,
    /// In classical logic, the steps of the clausal proof that the
    /// clauses have no model, which the checker accepted: the clauses the
    /// solver learnt and deleted, and the empty clause.
    pub proof_steps: u64,
    /// LJT's statistics where its search gave the derivation: where a
    /// bound refused the read-back, or where the logic's default prefers
    /// LJT's derivation ([`decide_preferring_ljt`]).
    pub ljt: Option<ljt::Statistics>,
}

/// How many pairs of a world and an implication the search examines
/// between two polls of the stop.
const POLL: u64 = 1 << 8;

/// The polarity of a formula that the search's clauses take apart, as a
/// hypothesis does.
const NEGATIVE: u8 = 1;
/// The polarity of a formula that the search's clauses build, as a goal
/// is built.
const POSITIVE: u8 = 2;

/// A clause learnt from an implication `c = a → b` (or `c = ¬a`, `b`
/// being `⊥`): `body → c`, from a call that found `body, a ⊢ b`.
#[derive(Clone, Debug)]
struct Lemma {
    /// The formulas assumed, in ascending order.
    body: Vec<NodeId>,
    /// `a`.
    antecedent: NodeId,
    /// `b`.
    consequent: NodeId,
    /// `c`.
    made: NodeId,
}

/// Decides a sequent by the SAT solver within `limits`.
///
/// The stop is asked:
/// - at every call of the solver, the first included, and at every
///   decision in it;
/// - while the worlds are scanned for an implication they do not realise,
///   every 256 pairs;
/// - while the worlds of a model are ordered, every 256 comparisons, and
///   by the model's check
///   ([`Countermodel::check`](super::Countermodel::check)), once per world
///   in each of its passes;
/// - while a valid sequent's derivation is read off the search, by LJT
///   where it gives that derivation, and by the derivation's check
///   ([`Derivation::check`]);
/// - in classical logic, while the sequent is encoded, every 4 096
///   formulas, while its clauses are handed to the solver, every 4 096
///   clauses, and by the clausal proof's check.
///
/// A conflict or a call is a unit of `limits.work`, and the clauses
/// and worlds are charged to `limits.memory_bytes`. A valid sequent's
/// derivation of LJ is read off the search within
/// `limits.derivation_bytes`, `limits.memory_bytes` and `limits.work`
/// facts. Where a bound, not the stop, refuses it, [`ljt::decide`]
/// finds one within the same limits. Either derivation is checked. A
/// sequent that is not valid gets its Kripke model, checked, unless the
/// model is too large to check: then the verdict stands without it. A
/// sequent with nothing right of `⊢` is decided as `Γ ⊢ ⊥`, and its
/// derivation concludes that sequent.
///
/// In classical logic a valid sequent's evidence is its clausal proof
/// ([`ClausalProof`]), checked within the same limits. A step of it is a
/// unit of `limits.work`; the solver and the check each have the whole
/// bound. A clausal proof is no derivation: [`decide`](super::decide())
/// with [`Method::Embedding`](super::Method::Embedding) gives one. A
/// sequent that is not valid gets a model of one world, checked.
///
/// # Errors
///
/// - [`Error::Succedents`] for more than one formula right of `⊢` in
///   intuitionistic or minimal logic.
/// - [`Refusal::Output`], [`Refusal::Memory`], [`Refusal::Work`],
///   [`Refusal::Index`] or [`Refusal::Stopped`] where a bound or the stop
///   refused the derivation of a proof (where LJT gave none either), the
///   check of a model or, in classical logic, the check of the clausal
///   proof. None of them is a verdict.
/// - As [`Derivation::check`].
/// - [`Error::ReadBack`] where the derivation or the clausal proof fails
///   its check, or where LJT refutes a sequent the search proved, and
///   [`Error::Countermodel`] where the model fails its check: each a
///   defect.
pub fn decide(
    sequent: &Sequent,
    logic: Logic,
    limits: &Limits,
    stop: impl FnMut(Progress) -> bool,
) -> Result<Outcome, Error> {
    run(
        sequent,
        logic,
        limits,
        stop,
        MOST_VARIABLES,
        Derive::ReadOff,
    )
}

/// Decides a sequent as [`decide`] does, but takes a valid sequent's
/// derivation of LJ from [`ljt::decide`] where LJT gives one within the
/// limits and before the stop, and otherwise the one read off the search.
/// LJT's derivations are smaller, and their lambda-terms have fewer
/// redexes. The verdict is the search's either way. The logic's default
/// decides intuitionistic and minimal logic this way
/// ([`decide`](super::decide()) with no method given). In classical logic
/// this function is [`decide`].
///
/// # Errors
///
/// As [`decide`].
pub fn decide_preferring_ljt(
    sequent: &Sequent,
    logic: Logic,
    limits: &Limits,
    stop: impl FnMut(Progress) -> bool,
) -> Result<Outcome, Error> {
    run(
        sequent,
        logic,
        limits,
        stop,
        MOST_VARIABLES,
        Derive::PreferLjt,
    )
}

/// Where the derivation of a valid sequent comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Derive {
    /// Read off the search, and by LJT where a bound refuses that.
    ReadOff,
    /// By LJT alone, which the tests ask for.
    #[cfg(test)]
    Ljt,
    /// By LJT, and read off the search where LJT gives none.
    PreferLjt,
}

/// [`decide`] with at most `most` variables, which the tests lower, and
/// the derivation from where `derive` says.
fn run(
    sequent: &Sequent,
    logic: Logic,
    limits: &Limits,
    mut stop: impl FnMut(Progress) -> bool,
    most: u32,
    derive: Derive,
) -> Result<Outcome, Error> {
    if logic == Logic::Classical {
        return classical::decide(sequent, limits, stop, most);
    }
    if sequent.right().len() > 1 {
        return Err(Error::Succedents {
            count: sequent.right().len(),
        });
    }
    let mut formulas = sequent.formulas().clone();
    let falsity = formulas.add(Node::False)?;
    // The clauses of `a ↔ b` go through `a → b` and `b → a`, which are
    // added here. The range is fixed before the loop adds any, and an
    // implication added is no equivalence, so one pass adds them all.
    for id in 0..formulas.len() {
        if let Node::Iff(a, b) = formulas.node(NodeId(id as u32)) {
            formulas.add(Node::Implies(a, b))?;
            formulas.add(Node::Implies(b, a))?;
        }
    }
    let goal = sequent.right().first().copied().unwrap_or(falsity);
    let polarity = polarities(&formulas, sequent.left(), goal, falsity);
    let account = Account::holding(limits.memory_bytes, 0);
    account.charge(formulas.len() * (4 * size_of::<Node>() + size_of::<u32>() + 1));
    let mut statistics = Statistics::default();
    let found = {
        let work = limits.work.unwrap_or(u64::MAX);
        let mut solver = Batsat::new(work, &account, &mut stop);
        let found = Search::new(
            &mut solver,
            &formulas,
            &polarity,
            logic,
            falsity,
            most,
            &account,
        )
        .and_then(|mut search| {
            let found = search.run(sequent.left(), goal, &account);
            statistics.lemmas = search.lemmas.len() as u64;
            found.map(|found| (found, search.lemmas, search.nodes))
        });
        statistics.calls = solver.calls();
        statistics.conflicts = solver.conflicts();
        found
    };
    let (verdict, model) = match found {
        Err(reason) => (Verdict::Unknown(reason), None),
        Ok((Found::Worlds(worlds), _, nodes)) => {
            statistics.worlds = worlds.len() as u64;
            // The check computes at least a cell per world and formula.
            // Past its bound the model is not built, and a model the check
            // refuses for its size (its arrows count too) is dropped. Below
            // the bound the worlds' indices fit a `u32`.
            let cells = statistics
                .worlds
                .saturating_mul(sequent.formulas().len() as u64);
            if cells > super::MODEL_CELLS {
                // Too large to show and to check: the verdict stands
                // without its model, and the statistics count its worlds.
                (Verdict::NotValid, None)
            } else {
                match kripke(
                    &formulas,
                    logic,
                    (falsity, &nodes),
                    worlds,
                    &account,
                    &mut stop,
                ) {
                    Ok(model) => {
                        let model = super::Countermodel::found(
                            sequent.clone(),
                            model,
                            logic,
                            limits,
                            &mut stop,
                        )?;
                        (Verdict::NotValid, model)
                    }
                    // The worlds' order would pass the memory bound: the
                    // verdict stands without its model.
                    Err(Reason::MemoryLimit { .. }) => (Verdict::NotValid, None),
                    Err(reason) => (Verdict::Unknown(reason), None),
                }
            }
        }
        Ok((Found::Valid, lemmas, _)) => {
            let refused = Error::Refused(Refusal::Output {
                what: "derivation",
                estimate_bytes: 0,
                limit_bytes: 0,
                least_bytes: None,
            });
            let read = if matches!(derive, Derive::ReadOff | Derive::PreferLjt) {
                read_back::derivation(
                    formulas,
                    logic,
                    &polarity,
                    (falsity, goal),
                    sequent.left(),
                    &lemmas,
                    limits,
                    account.used(),
                    &mut stop,
                )
            } else {
                Err(refused)
            };
            let derivation = match read {
                Ok((derivation, facts)) => {
                    statistics.facts = facts;
                    derivation
                }
                Err(Error::Refused(refusal)) if !matches!(refusal, Refusal::Stopped { .. }) => {
                    let (derivation, ljt) = by_ljt(sequent, logic, limits, &mut stop, refusal)?;
                    statistics.ljt = Some(ljt);
                    derivation
                }
                Err(error) => return Err(error),
            };
            derivation.check(limits, &mut stop)?;
            let derivation = if derive == Derive::PreferLjt && statistics.ljt.is_none() {
                prefer_ljt(
                    sequent,
                    logic,
                    limits,
                    &mut stop,
                    derivation,
                    &mut statistics,
                )?
            } else {
                derivation
            };
            (
                Verdict::Valid(Evidence::Derivation(Box::new(derivation))),
                None,
            )
        }
    };
    Ok(Outcome {
        verdict,
        logic,
        statistics,
        model,
    })
}

/// Returns LJT's derivation of a sequent the search proved and whose
/// `derivation` it read off and checked, with LJT's statistics in
/// `statistics`, or that derivation where LJT gives none within the
/// limits and before the stop.
fn prefer_ljt(
    sequent: &Sequent,
    logic: Logic,
    limits: &Limits,
    stop: &mut impl FnMut(Progress) -> bool,
    derivation: Derivation,
    statistics: &mut Statistics,
) -> Result<Derivation, Error> {
    let Ok(outcome) = ljt::decide(sequent, logic, limits, &mut *stop) else {
        return Ok(derivation);
    };
    match outcome.verdict {
        Verdict::Valid(Evidence::Derivation(ljt)) => {
            statistics.ljt = Some(outcome.statistics);
            Ok(*ljt)
        }
        Verdict::NotValid => Err(Error::ReadBack {
            calculus: logic.calculus(),
            reason: "LJT refutes a sequent the SAT search proved".to_owned(),
        }),
        // LJT never gives a clausal proof or an image's proof. An unknown,
        // from a bound or the stop, leaves the derivation read off the
        // search.
        Verdict::Valid(Evidence::Clausal(_) | Evidence::Image | Evidence::Table)
        | Verdict::Unknown(_) => Ok(derivation),
    }
}

/// Returns LJT's derivation of a sequent the search proved, and LJT's
/// statistics. Where the stop ends LJT, returns that stop; where another
/// bound does, the read-back's `refusal`; where LJT refutes the sequent,
/// [`Error::ReadBack`].
fn by_ljt(
    sequent: &Sequent,
    logic: Logic,
    limits: &Limits,
    stop: &mut impl FnMut(Progress) -> bool,
    refusal: Refusal,
) -> Result<(Derivation, ljt::Statistics), Error> {
    let outcome = match ljt::decide(sequent, logic, limits, &mut *stop) {
        Ok(outcome) => outcome,
        // A stop stays a stop; another bound is the read-back's refusal.
        Err(Error::Refused(stopped @ Refusal::Stopped { .. })) => {
            return Err(Error::Refused(stopped));
        }
        Err(Error::Refused(_)) => return Err(Error::Refused(refusal)),
        Err(other) => return Err(other),
    };
    match outcome.verdict {
        Verdict::Valid(Evidence::Derivation(derivation)) => Ok((*derivation, outcome.statistics)),
        // LJT never gives a clausal proof or an image's proof.
        Verdict::Valid(Evidence::Clausal(_)) => Err(Error::NoDerivation {
            evidence: "a checked clausal proof",
        }),
        Verdict::Valid(Evidence::Image) => Err(Error::NotBuilt),
        Verdict::Valid(Evidence::Table) => Err(Error::NoDerivation {
            evidence: "its truth table",
        }),
        Verdict::Unknown(Reason::Stopped) => Err(Error::Refused(Refusal::Stopped {
            phase: crate::limits::Phase::Search,
        })),
        Verdict::Unknown(_) => Err(Error::Refused(refusal)),
        Verdict::NotValid => Err(Error::ReadBack {
            calculus: logic.calculus(),
            reason: "LJT refutes a sequent the SAT search proved".to_owned(),
        }),
    }
}

/// Returns the polarity of every formula of the arena that the clauses
/// of `left ⊢ goal` name: negative for those taken apart, as hypotheses
/// are, positive for those built, as the goal is, both for the parts of
/// an equivalence; `⊥` takes the polarity of every negation.
fn polarities(formulas: &Formulas, left: &[NodeId], goal: NodeId, falsity: NodeId) -> Vec<u8> {
    let mut polarity = vec![0u8; formulas.len()];
    for h in left {
        polarity[h.index()] |= NEGATIVE;
    }
    polarity[goal.index()] |= POSITIVE;
    // Every formula comes after its parts, so a pass from the last formula
    // to the first meets each before its parts.
    for id in (0..formulas.len()).rev() {
        let p = polarity[id];
        if p == 0 {
            continue;
        }
        let flipped = ((p & NEGATIVE) << 1) | ((p & POSITIVE) >> 1);
        match formulas.node(NodeId(id as u32)) {
            Node::Atom(_) | Node::True | Node::False => {}
            Node::Not(a) => {
                polarity[a.index()] |= flipped;
                polarity[falsity.index()] |= p;
            }
            Node::And(a, b) | Node::Or(a, b) => {
                polarity[a.index()] |= p;
                polarity[b.index()] |= p;
            }
            Node::Implies(a, b) => {
                polarity[a.index()] |= flipped;
                polarity[b.index()] |= p;
            }
            Node::Iff(a, b) => {
                // The implications may come after the equivalence, and this
                // pass has then gone by them: the parts get here what the
                // implications would give them, both polarities.
                polarity[a.index()] |= NEGATIVE | POSITIVE;
                polarity[b.index()] |= NEGATIVE | POSITIVE;
                for i in [Node::Implies(a, b), Node::Implies(b, a)] {
                    if let Some(i) = formulas.find(i) {
                        polarity[i.index()] |= p;
                    }
                }
            }
        }
    }
    polarity
}

/// What the search found.
enum Found {
    /// The goal holds in every model of the clauses.
    Valid,
    /// The worlds of a Kripke model in which it fails, each the
    /// variables true in it, the first the least.
    Worlds(Vec<Bits>),
}

/// A set of variables, as bits.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Bits(Vec<u64>);

impl Bits {
    /// The empty set of `len` variables.
    fn new(len: usize) -> Self {
        Self(vec![0; len.div_ceil(64)])
    }

    /// Returns whether the set holds `v`.
    fn has(&self, v: u32) -> bool {
        self.0[v as usize / 64] >> (v % 64) & 1 == 1
    }

    /// Adds `v`.
    fn insert(&mut self, v: u32) {
        self.0[v as usize / 64] |= 1 << (v % 64);
    }

    /// Returns whether every member of `self` is one of `other`.
    fn within(&self, other: &Self) -> bool {
        self.0.iter().zip(&other.0).all(|(a, b)| a & !b == 0)
    }

    /// Returns the members, in ascending order.
    fn members(&self) -> impl Iterator<Item = u32> + '_ {
        self.0.iter().enumerate().flat_map(|(k, &word)| {
            (0..64u32)
                .filter(move |b| word >> b & 1 == 1)
                .map(move |b| k as u32 * 64 + b)
        })
    }

    /// Returns the bytes it holds.
    fn bytes(&self) -> usize {
        self.0.len() * size_of::<u64>()
    }
}

/// The search: the solver with the clauses of a sequent, and the
/// implications it must realise.
struct Search<'a, S> {
    /// The solver.
    solver: &'a mut S,
    /// The formula of every variable.
    nodes: Vec<NodeId>,
    /// The variable of every formula that has one.
    vars: Vec<Option<u32>>,
    /// The implications `(a → b) → c`, by their variables `[a, b, c]`.
    implications: Vec<[u32; 3]>,
    /// The clauses learnt.
    lemmas: Vec<Lemma>,
}

impl<'a, S: Solver> Search<'a, S> {
    /// Gives the solver the clauses of the formulas `polarity` names, with
    /// at most `most` variables. Each variable and clause is charged to the
    /// account as it is made, and the setup is refused once the account is
    /// over.
    fn new(
        solver: &'a mut S,
        formulas: &Formulas,
        polarity: &[u8],
        logic: Logic,
        falsity: NodeId,
        most: u32,
        account: &Account,
    ) -> Result<Self, Reason> {
        let over = || {
            account.over().then(|| Reason::MemoryLimit {
                limit_bytes: account.limit(),
            })
        };
        let mut vars = vec![None; formulas.len()];
        let mut nodes = Vec::new();
        for (id, var) in vars.iter_mut().enumerate() {
            if polarity[id] != 0 || id == falsity.index() {
                if nodes.len() >= most as usize {
                    return Err(Reason::IndexLimit);
                }
                *var = Some(solver.new_var());
                nodes.push(NodeId(id as u32));
                if let Some(reason) = over() {
                    return Err(reason);
                }
            }
        }
        let var = |x: NodeId| vars[x.index()].unwrap_or_else(|| unreachable!("a name"));
        let (pos, neg) = (|x| Lit::positive(var(x)), |x| Lit::negative(var(x)));
        let mut clauses: Vec<Vec<Lit>> = Vec::new();
        let mut implications = Vec::new();
        // The clauses of one formula at a time go to the solver, so that
        // nothing beside it holds them all.
        let mut flush = |clauses: &mut Vec<Vec<Lit>>| {
            for clause in clauses.drain(..) {
                solver.add_clause(&clause);
            }
            over()
        };
        if logic == Logic::Intuitionistic {
            clauses.push(vec![neg(falsity)]);
        }
        for (id, &p) in polarity.iter().enumerate() {
            if let Some(reason) = flush(&mut clauses) {
                return Err(reason);
            }
            if p == 0 {
                continue;
            }
            let x = NodeId(id as u32);
            let (negative, positive) = (p & NEGATIVE != 0, p & POSITIVE != 0);
            match formulas.node(x) {
                Node::Atom(_) | Node::False => {}
                Node::True => {
                    if positive {
                        clauses.push(vec![pos(x)]);
                    }
                }
                Node::And(a, b) => {
                    if negative {
                        clauses.push(vec![neg(x), pos(a)]);
                        clauses.push(vec![neg(x), pos(b)]);
                    }
                    if positive {
                        clauses.push(vec![neg(a), neg(b), pos(x)]);
                    }
                }
                Node::Or(a, b) => {
                    if negative {
                        clauses.push(vec![neg(x), pos(a), pos(b)]);
                    }
                    if positive {
                        clauses.push(vec![neg(a), pos(x)]);
                        clauses.push(vec![neg(b), pos(x)]);
                    }
                }
                Node::Implies(a, b) => {
                    if negative {
                        clauses.push(vec![neg(x), neg(a), pos(b)]);
                    }
                    if positive {
                        clauses.push(vec![neg(b), pos(x)]);
                        implications.push([var(a), var(b), var(x)]);
                    }
                }
                Node::Not(a) => {
                    if negative {
                        clauses.push(vec![neg(x), neg(a), pos(falsity)]);
                    }
                    if positive {
                        clauses.push(vec![neg(falsity), pos(x)]);
                        implications.push([var(a), var(falsity), var(x)]);
                    }
                }
                Node::Iff(a, b) => {
                    let i = formulas.find(Node::Implies(a, b));
                    let j = formulas.find(Node::Implies(b, a));
                    let (Some(i), Some(j)) = (i, j) else {
                        unreachable!("the implications of every equivalence were added")
                    };
                    if negative {
                        clauses.push(vec![neg(x), pos(i)]);
                        clauses.push(vec![neg(x), pos(j)]);
                    }
                    if positive {
                        clauses.push(vec![neg(i), neg(j), pos(x)]);
                    }
                }
            }
        }
        if let Some(reason) = flush(&mut clauses) {
            return Err(reason);
        }
        Ok(Self {
            solver,
            nodes,
            vars,
            implications,
            lemmas: Vec::new(),
        })
    }

    /// Runs intuitR's loop on `left ⊢ goal`, charging the worlds to the
    /// account.
    fn run(&mut self, left: &[NodeId], goal: NodeId, account: &Account) -> Result<Found, Reason> {
        let var = |x: NodeId| self.vars[x.index()].unwrap_or_else(|| unreachable!("a name"));
        let units: Vec<Lit> = left.iter().map(|&h| Lit::positive(var(h))).collect();
        for unit in units {
            self.solver.add_clause(&[unit]);
        }
        let goal = var(goal);
        loop {
            match self.solver.solve(&[Lit::negative(goal)]) {
                Answer::Unsatisfiable => return Ok(Found::Valid),
                Answer::Stopped(reason) => return Err(reason),
                Answer::Satisfiable => {}
            }
            let mut worlds = vec![self.world()];
            let mut held = worlds[0].bytes();
            account.charge(held);
            let learnt = self.realise(&mut worlds, account, &mut held);
            match learnt {
                Ok(true) => account.release(held),
                // The worlds stay charged while the model is made of them.
                Ok(false) => return Ok(Found::Worlds(worlds)),
                Err(reason) => {
                    account.release(held);
                    return Err(reason);
                }
            }
        }
    }

    /// Adds worlds until every implication is realised at every world,
    /// answering `false`, or until a call learns a clause, answering
    /// `true`, which restarts the search.
    fn realise(
        &mut self,
        worlds: &mut Vec<Bits>,
        account: &Account,
        held: &mut usize,
    ) -> Result<bool, Reason> {
        // A pair passed over is realised, and stays so as worlds are
        // added, so each world keeps a cursor over the implications. The
        // oldest world is examined first: newest first leaves ILTP's
        // SYJ212+1.020 undecided after 20 s, which this order refutes in
        // 130 calls.
        let mut next: Vec<usize> = vec![0; worlds.len()];
        let mut scanned = 0u64;
        loop {
            let mut pair = None;
            'scan: for (w, at) in next.iter_mut().enumerate() {
                while let Some(&[a, b, c]) = self.implications.get(*at) {
                    scanned += 1;
                    if scanned.is_multiple_of(POLL)
                        && let Some(reason) = self.solver.poll(POLL)
                    {
                        return Err(reason);
                    }
                    if unrealised(worlds, w, [a, b, c]) {
                        pair = Some((w, [a, b, c]));
                        break 'scan;
                    }
                    *at += 1;
                }
            }
            let Some((w, [a, b, c])) = pair else {
                return Ok(false);
            };
            // `a` and `¬b` first: the solver blames a conflict on the first
            // assumptions that imply it. So what `a` implies is not blamed
            // on the world, whose variables would tie the clause learnt to
            // that one world.
            let mut assumptions = vec![Lit::positive(a), Lit::negative(b)];
            assumptions.extend(worlds[w].members().map(Lit::positive));
            match self.solver.solve(&assumptions) {
                Answer::Satisfiable => {
                    let world = self.world();
                    *held += world.bytes();
                    account.charge(world.bytes());
                    worlds.push(world);
                    next.push(0);
                    if account.over() {
                        return Err(Reason::MemoryLimit {
                            limit_bytes: account.limit(),
                        });
                    }
                    next[w] += 1;
                }
                Answer::Unsatisfiable => {
                    let mut body: Vec<u32> = self
                        .solver
                        .failed()
                        .into_iter()
                        .filter(|l| l.is_positive() && l.var() != a)
                        .map(Lit::var)
                        .collect();
                    body.sort_unstable();
                    body.dedup();
                    let mut clause: Vec<Lit> = body.iter().map(|&v| Lit::negative(v)).collect();
                    clause.push(Lit::positive(c));
                    self.solver.add_clause(&clause);
                    let node = |v: u32| self.nodes[v as usize];
                    let mut body: Vec<NodeId> = body.into_iter().map(node).collect();
                    body.sort_unstable();
                    self.lemmas.push(Lemma {
                        body,
                        antecedent: node(a),
                        consequent: node(b),
                        made: node(c),
                    });
                    return Ok(true);
                }
                Answer::Stopped(reason) => return Err(reason),
            }
        }
    }

    /// Returns the variables true in the solver's model.
    fn world(&self) -> Bits {
        let mut world = Bits::new(self.nodes.len());
        for v in 0..self.nodes.len() as u32 {
            if self.solver.value(Lit::positive(v)) {
                world.insert(v);
            }
        }
        world
    }
}

/// Returns whether the implication `(a → b) → c` is unrealised at the
/// world `w`: `a`, `b` and `c` are false there, and no world above it has
/// `a` and not `b` (intuitR's realisability).
fn unrealised(worlds: &[Bits], w: usize, [a, b, c]: [u32; 3]) -> bool {
    let world = &worlds[w];
    if world.has(a) || world.has(b) || world.has(c) {
        return false;
    }
    // A world that has `a` is not `w`, so it is above `w` where it holds
    // every variable of `w`.
    !worlds
        .iter()
        .any(|other| other.has(a) && !other.has(b) && world.within(other))
}

/// Returns the Kripke model of the worlds: ordered by inclusion, the
/// least first, each with the atoms whose variables it holds, and `⊥`
/// where it holds `⊥` in minimal logic. Finding the order takes a bit per
/// pair of worlds, charged to the account. Returns the reason past the
/// memory bound, or when the stop fires (asked every `POLL` comparisons
/// of worlds).
fn kripke(
    formulas: &Formulas,
    logic: Logic,
    (falsity, nodes): (NodeId, &[NodeId]),
    mut worlds: Vec<Bits>,
    account: &Account,
    stop: &mut impl FnMut(Progress) -> bool,
) -> Result<Model, Reason> {
    // A world strictly above another has more variables.
    worlds.sort_by_key(|w| w.members().count());
    let n = worlds.len();
    let bytes = n.saturating_mul(Bits::new(n).bytes());
    account.charge(bytes);
    if account.over() {
        account.release(bytes);
        return Err(Reason::MemoryLimit {
            limit_bytes: account.limit(),
        });
    }
    let mut compared = 0u64;
    let mut poll = |by: usize| {
        let before = compared;
        compared = compared.saturating_add(by as u64);
        if before / POLL != compared / POLL
            && stop(Progress::new(crate::limits::Phase::Search, POLL, compared))
        {
            return Err(Reason::Stopped);
        }
        Ok(())
    };
    let found = (|| -> Result<Vec<Vec<u32>>, Reason> {
        // Every world strictly below each, as bits over the worlds.
        let mut below: Vec<Bits> = Vec::with_capacity(n);
        for j in 0..n {
            let mut set = Bits::new(n);
            for i in 0..j {
                poll(1)?;
                if worlds[i] != worlds[j] && worlds[i].within(&worlds[j]) {
                    set.insert(i as u32);
                }
            }
            below.push(set);
        }
        // The worlds directly below each: below it, and below no other
        // world below it.
        let mut above = vec![Vec::new(); n];
        for (j, set) in below.iter().enumerate() {
            let mut direct = set.clone();
            for i in set.members() {
                poll(1)?;
                for (word, under) in direct.0.iter_mut().zip(&below[i as usize].0) {
                    *word &= !under;
                }
            }
            for i in direct.members() {
                above[i as usize].push(j as u32);
            }
        }
        Ok(above)
    })();
    account.release(bytes);
    let above = found?;
    let models = worlds.iter().zip(above).map(|(world, above)| {
        let mut atoms = Vec::new();
        let mut forces_falsity = false;
        for v in world.members() {
            let x = nodes[v as usize];
            match formulas.node(x) {
                Node::Atom(a) => atoms.push(a),
                Node::False if x == falsity && logic == Logic::Minimal => forces_falsity = true,
                Node::True
                | Node::False
                | Node::Not(_)
                | Node::And(..)
                | Node::Or(..)
                | Node::Implies(..)
                | Node::Iff(..) => {}
            }
        }
        atoms.sort_unstable();
        let names = formulas.atom_names();
        World::new(
            atoms.iter().map(|&a| names[a as usize].clone()).collect(),
            forces_falsity,
            above,
        )
    });
    Ok(Model::new(models.collect(), 0))
}

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

    /// Decides `text` by the SAT solver in `logic` within the default
    /// limits.
    fn sat(text: &str, logic: Logic) -> Outcome {
        let sequent: Sequent = text.parse().unwrap();
        decide(&sequent, logic, &Limits::default(), |_| false).unwrap()
    }

    /// Returns whether the verdict is valid, panicking on an unknown one.
    fn valid(outcome: &Outcome) -> bool {
        match &outcome.verdict {
            Verdict::Valid(_) => true,
            Verdict::NotValid => false,
            Verdict::Unknown(reason) => panic!("unknown: {reason:?}"),
        }
    }

    /// On generated sequents the SAT solver decides every one in
    /// intuitionistic and minimal logic as LJT does; each derivation is
    /// read off the search and passes the checker again, and each model
    /// refutes its sequent again.
    #[test]
    fn agrees_with_ljt() {
        const SEQUENTS: usize = 400;
        let limits = Limits::default();
        let mut rng = Rng::new(54);
        let (mut proved, mut refuted) = (0, 0);
        for _ in 0..SEQUENTS {
            let sequent = super::super::tests::generated_sequent(&mut rng);
            for logic in [Logic::Intuitionistic, Logic::Minimal] {
                let outcome = decide(&sequent, logic, &limits, |_| false)
                    .unwrap_or_else(|e| panic!("{sequent} in {logic} logic: {e}"));
                let answer = match &outcome.verdict {
                    Verdict::Valid(evidence) => {
                        let derivation = evidence.derivation().unwrap();
                        assert_eq!(derivation.check(&limits, |_| false), Ok(()), "{sequent}");
                        assert_eq!(outcome.statistics.ljt, None, "{sequent}: read off");
                        proved += 1;
                        true
                    }
                    Verdict::NotValid => {
                        let model = &outcome.model.as_ref().unwrap().model;
                        assert_eq!(
                            model.refutes(&sequent, logic, &Limits::default(), |_| false),
                            Ok(())
                        );
                        refuted += 1;
                        false
                    }
                    Verdict::Unknown(reason) => panic!("{sequent} in {logic} logic: {reason:?}"),
                };
                let ljt = ljt::decide(&sequent, logic, &limits, |_| false).unwrap();
                assert_eq!(
                    answer,
                    matches!(ljt.verdict, Verdict::Valid(_)),
                    "{sequent} in {logic} logic"
                );
            }
        }
        assert!(
            proved >= SEQUENTS / 4 && refuted >= SEQUENTS / 4,
            "{proved}, {refuted}"
        );
    }

    /// The sequents that separate the logics, and those of every rule.
    #[test]
    fn decides_the_separating_sequents() {
        // (sequent, intuitionistic, minimal)
        let cases = [
            ("a -> a", true, true),
            ("a \\/ ~a", false, false),
            ("~~(a \\/ ~a)", true, true),
            ("~~a -> a", false, false),
            ("((a -> b) -> a) -> a", false, false),
            ("false -> a", true, false),
            ("a \\/ b, ~a |- b", true, false),
            ("(a /\\ b -> c) |- a -> b -> c", true, true),
            ("(a \\/ b -> c) |- (a -> c) /\\ (b -> c)", true, true),
            ("((a -> b) -> c), b |- c", true, true),
            ("((a <-> b) -> c), a, b |- c", true, true),
            ("(true -> a) |- a", true, true),
            ("~(a /\\ b), a |- ~b", true, true),
            ("~(a \\/ b) |- ~a /\\ ~b", true, true),
            ("~(a -> b) |- ~b", true, true),
            ("a <-> b, a |- b", true, true),
            ("a, a, b |- a /\\ b", true, true),
            ("|- ~(a /\\ ~a)", true, true),
            ("a |-", false, false),
            ("a, ~a |-", true, true),
            ("~~~a -> ~a", true, true),
            ("((((a -> b) -> a) -> a) -> b) -> b", true, true),
            ("(a <-> b) <-> (b <-> a)", true, true),
            ("|- true", true, true),
            ("false |- false", true, true),
        ];
        for (text, intuitionistic, minimal) in cases {
            assert_eq!(
                valid(&sat(text, Logic::Intuitionistic)),
                intuitionistic,
                "{text}"
            );
            assert_eq!(
                valid(&sat(text, Logic::Minimal)),
                minimal,
                "{text} minimally"
            );
        }
        // Classical logic is decided too, by the clauses of the negation.
        assert!(valid(&sat("|- a \\/ ~a", Logic::Classical)));
    }

    /// A model changed in any of the ways the check guards against is
    /// refused, each for its own reason.
    #[test]
    fn a_planted_wrong_model_is_refused() {
        let text = "((a -> b) -> a) -> a";
        let sequent: Sequent = text.parse().unwrap();
        let logic = Logic::Intuitionistic;
        let model = sat(text, logic).model.unwrap().model;
        assert_eq!(
            model.refutes(&sequent, logic, &Limits::default(), |_| false),
            Ok(())
        );
        assert!(model.worlds.len() >= 2, "{model:?}");
        let refused = |model: &Model, why: &str| {
            let Err(Error::Model { reason }) =
                model.refutes(&sequent, logic, &Limits::default(), |_| false)
            else {
                panic!("{why}: {model:?} is accepted");
            };
            assert!(reason.contains(why), "{reason} for {why}");
        };
        let both = || vec!["a".to_owned(), "b".to_owned()];
        // The root's conclusion made true everywhere.
        let mut planted = model.clone();
        for world in &mut planted.worlds {
            world.atoms = both();
        }
        refused(&planted, "forces the conclusion");
        // A world above that forgets an atom below it.
        let mut planted = model.clone();
        let up = planted.worlds[0].arrows[0] as usize;
        planted.worlds[0].atoms.push("a".to_owned());
        planted.worlds[up].atoms.clear();
        refused(&planted, "does not force all it forces");
        // The arrows taken away: the root alone forces the formula.
        let mut planted = model.clone();
        planted.worlds.truncate(1);
        planted.worlds[0].arrows.clear();
        refused(&planted, "forces the conclusion");
        // An arrow back, an arrow to no world, ⊥ forced, the model's world
        // missing.
        let mut planted = model.clone();
        let last = planted.worlds.len() - 1;
        planted.worlds[last].arrows.push(last as u32);
        refused(&planted, "the arrows go round");
        let mut planted = model.clone();
        planted.worlds[0].arrows.push(99);
        refused(&planted, "which the model does not have");
        let mut planted = model.clone();
        planted.worlds[0].falsity = true;
        refused(&planted, "forces ⊥ in intuitionistic logic");
        let mut planted = model;
        planted.world = 99;
        refused(&planted, "is not one of its");
    }

    /// The search stops at the work bound, the stop and the memory bound,
    /// and refuses a sequent of more formulas than it has variables. A
    /// derivation past its bound is refused when LJT gives none either.
    /// The model's check refuses past its cells.
    #[test]
    fn the_search_keeps_to_its_bounds() {
        let sequent: Sequent = "((a -> b) -> a) -> a".parse().unwrap();
        let logic = Logic::Intuitionistic;
        let free = decide(&sequent, logic, &Limits::default(), |_| false).unwrap();
        assert!(matches!(free.verdict, Verdict::NotValid));
        let calls = free.statistics.calls;
        assert!(calls > 2, "{calls}");
        let at = |work| Limits::default().with_work(Some(work));
        let outcome = decide(&sequent, logic, &at(calls - 1), |_| false).unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::WorkLimit { .. })
        ));
        let outcome = decide(&sequent, logic, &Limits::default(), |_| true).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
        let tight = Limits::default().with_memory_bytes(Some(64));
        let outcome = decide(&sequent, logic, &tight, |_| false).unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::MemoryLimit { .. })
        ));
        // Five formulas and `⊥` need six variables.
        let outcome = run(
            &sequent,
            logic,
            &Limits::default(),
            |_| false,
            5,
            Derive::ReadOff,
        )
        .unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::IndexLimit)
        ));
        assert!(matches!(
            run(
                &sequent,
                logic,
                &Limits::default(),
                |_| false,
                6,
                Derive::ReadOff
            )
            .unwrap()
            .verdict,
            Verdict::NotValid
        ));
        let sequent: Sequent = "a, b, c |- a /\\ (b /\\ c)".parse().unwrap();
        let small = Limits::default().with_derivation_bytes(Some(100));
        assert!(matches!(
            decide(&sequent, logic, &small, |_| false),
            Err(Error::Refused(Refusal::Output { .. }))
        ));
        // A model of more cells than the check computes.
        let chain: Vec<String> = (0..1 << 14).map(|i| format!("a{i}")).collect();
        let sequent: Sequent = format!("|- {}", chain.join(" /\\ ")).parse().unwrap();
        let worlds = (super::super::MODEL_CELLS as usize).div_ceil(sequent.formulas().len()) + 1;
        let model = Model::new(vec![World::default(); worlds], 0);
        assert!(matches!(
            model.refutes(&sequent, logic, &Limits::default(), |_| false),
            Err(Error::Refused(Refusal::Memory { .. }))
        ));
    }

    /// The stop is asked while the worlds are scanned for an unrealised
    /// pair, which takes no call of the solver: a goal of `k` implications
    /// in a disjunction is refuted by `k + 1` worlds, whose last scan
    /// examines every pair.
    #[test]
    fn the_scan_of_the_worlds_asks_the_stop() {
        let k = 64;
        let chain: Vec<String> = (0..k).map(|i| format!("(a{i} -> a{})", i + 1)).collect();
        let sequent: Sequent = format!("|- {}", chain.join(" \\/ ")).parse().unwrap();
        let logic = Logic::Intuitionistic;
        let mut scans = 0;
        let free = decide(&sequent, logic, &Limits::default(), |p| {
            scans += u64::from(p.work == POLL);
            false
        })
        .unwrap();
        assert_eq!(free.statistics.worlds, k + 1);
        assert!(scans >= k * k / POLL, "{scans}");
        let mut asked = 0;
        let outcome = decide(&sequent, logic, &Limits::default(), |p| {
            asked += u64::from(p.work == POLL);
            asked == scans
        })
        .unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
    }

    /// The order of a model's worlds is found within the memory bound and
    /// until the stop fires: a chain of worlds, each a variable more.
    #[test]
    fn the_model_s_order_keeps_to_its_bounds() {
        let sequent: Sequent = "|- a".parse().unwrap();
        let formulas = sequent.formulas();
        let n = 1000;
        let chain = || {
            (0..n)
                .map(|k| {
                    let mut world = Bits::new(n);
                    (0..k).for_each(|v| world.insert(v as u32));
                    world
                })
                .collect::<Vec<_>>()
        };
        let nodes = vec![NodeId(0); n];
        let free = Account::holding(None, 0);
        let model = kripke(
            formulas,
            Logic::Intuitionistic,
            (NodeId(0), &nodes),
            chain(),
            &free,
            &mut |_| false,
        );
        let model = model.unwrap();
        assert_eq!(model.worlds[0].arrows, vec![1]);
        assert_eq!(free.used(), 0);
        let small = Account::holding(Some(n as u64 * 8), 0);
        let refused = kripke(
            formulas,
            Logic::Intuitionistic,
            (NodeId(0), &nodes),
            chain(),
            &small,
            &mut |_| false,
        );
        assert!(matches!(refused, Err(Reason::MemoryLimit { .. })));
        let stopped = kripke(
            formulas,
            Logic::Intuitionistic,
            (NodeId(0), &nodes),
            chain(),
            &free,
            &mut |_| true,
        );
        assert!(matches!(stopped, Err(Reason::Stopped)));
    }

    /// Where a bound refuses the derivation read off the search, LJT
    /// gives it.
    #[test]
    fn ljt_gives_the_derivation_the_read_back_cannot() {
        let sequent: Sequent = "a, a -> b, b -> c |- c".parse().unwrap();
        let logic = Logic::Intuitionistic;
        let outcome = run(
            &sequent,
            logic,
            &Limits::default(),
            |_| false,
            MOST_VARIABLES,
            Derive::Ljt,
        );
        let outcome = outcome.unwrap();
        assert!(matches!(outcome.verdict, Verdict::Valid(_)), "{outcome:?}");
        assert!(outcome.statistics.ljt.is_some(), "{:?}", outcome.statistics);
        // The stop during LJT is the stop, not the read-back's refusal:
        // it fires at the first poll of the search after the solver's.
        let search = |p: &Progress| p.phase == crate::limits::Phase::Search;
        let mut solver = 0;
        let counted = |p: Progress| {
            solver += u64::from(search(&p));
            false
        };
        run(
            &sequent,
            logic,
            &Limits::default(),
            counted,
            MOST_VARIABLES,
            Derive::ReadOff,
        )
        .unwrap();
        let mut asked = 0;
        let ljt = |p: Progress| {
            asked += u64::from(search(&p));
            asked > solver
        };
        let stopped = run(
            &sequent,
            logic,
            &Limits::default(),
            ljt,
            MOST_VARIABLES,
            Derive::Ljt,
        );
        assert!(
            matches!(stopped, Err(Error::Refused(Refusal::Stopped { .. }))),
            "{stopped:?}"
        );
    }
}