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

//! Classical logic decided by the SAT solver: the sequent `Γ ⊢ Δ` is
//! falsifiable exactly when the clauses of its negation, every formula of
//! `Γ` true and every formula of `Δ` false, have a model.
//!
//! The clauses are Tseitin's encoding with polarities (D. A. Plaisted and
//! S. Greenbaum, *A structure-preserving clause form translation*, J.
//! Symbolic Computation 2, 1986). Every subformula is a variable. A
//! formula gets the clauses of the directions of its definition that its
//! polarity needs. A formula that must be true gets "the formula implies
//! its definition", one that must be false "its definition implies the
//! formula", and one that must be both gets both.
//!
//! The answers are checked. A model of the clauses gives an assignment of
//! the atoms, a Kripke model of one world, which must falsify the sequent
//! by evaluation ([`Model::refutes`]). A refutation comes with the clauses
//! the solver learnt and deleted: a clausal proof. The checker of
//! [`drup`](super::drup) must accept it against the encoder's clauses
//! before the sequent is called valid, and the proof's counts are the
//! evidence ([`ClausalProof`]).

use super::drup::{ClausalProof, Rejection, Step};
use super::solver::{Answer, Batsat, Lit, Solver};
use super::{Outcome, Statistics};
use crate::Error;
use crate::kripke::{Model, World};
use crate::limits::{Limits, Phase, Progress};
use crate::linear::search::Reason;
use crate::linear::search::memory::Account;
use crate::ordinary::{Evidence, Formulas, Logic, Node, NodeId, Sequent, Verdict};

/// The polarity of a formula that must be true where the sequent fails,
/// as a hypothesis must.
const TRUE: u8 = 1;
/// The polarity of a formula that must be false where the sequent fails,
/// as a formula right of `⊢` must.
const FALSE: u8 = 2;

/// The clauses of a sequent's negation.
pub(super) struct Encoding {
    /// The variable of every formula of the arena that has one.
    pub(super) vars: Vec<Option<u32>>,
    /// How many variables there are; they are numbered from 0.
    pub(super) variables: u32,
    /// The clauses.
    pub(super) clauses: Vec<Vec<Lit>>,
}

/// Returns the polarity of every formula of the arena where `left ⊢
/// right` fails. `TRUE` marks a formula that must be true there, `FALSE`
/// one that must be false. The hypotheses are `TRUE` and the formulas
/// right of `⊢` are `FALSE`. A part takes its parent's polarity, flipped
/// under a negation and left of an implication; the parts of an
/// equivalence get both. A formula the sequent does not hold gets `0`.
fn polarities(formulas: &Formulas, left: &[NodeId], right: &[NodeId]) -> Vec<u8> {
    let mut polarity = vec![0u8; formulas.len()];
    for h in left {
        polarity[h.index()] |= TRUE;
    }
    for c in right {
        polarity[c.index()] |= FALSE;
    }
    // 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 & TRUE) << 1) | ((p & FALSE) >> 1);
        match formulas.node(NodeId(id as u32)) {
            Node::Atom(_) | Node::True | Node::False => {}
            Node::Not(a) => polarity[a.index()] |= flipped,
            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) => {
                polarity[a.index()] |= TRUE | FALSE;
                polarity[b.index()] |= TRUE | FALSE;
            }
        }
    }
    polarity
}

/// How many formulas the encoder takes, or clauses the solver is given,
/// between two polls of the stop.
const POLL: usize = 1 << 12;

/// How a clause of the encoding is charged to the memory account besides
/// its literals: its vector and the header of its allocation.
const CLAUSE_BYTES: usize = size_of::<Vec<Lit>>() + 16;

/// Returns the clauses of the negation of `left ⊢ right`, with a variable
/// for every formula the sequent holds. Each clause is charged to the
/// account. Refuses once the account is over, past `most` variables, or
/// when the stop fires, which is asked every [`POLL`] formulas.
///
/// Every clause holds when each variable takes its formula's value under
/// an assignment of the atoms, except the unit clauses of the sequent's
/// formulas, which hold exactly where the assignment falsifies the
/// sequent. So the clauses have a model wherever the sequent is
/// falsifiable, and a refutation of them shows it valid.
pub(super) fn encode(
    formulas: &Formulas,
    left: &[NodeId],
    right: &[NodeId],
    most: u32,
    account: &Account,
    stop: &mut impl FnMut(Progress) -> bool,
) -> Result<Encoding, Reason> {
    let over = || {
        account.over().then(|| Reason::MemoryLimit {
            limit_bytes: account.limit(),
        })
    };
    let polarity = polarities(formulas, left, right);
    let mut vars = vec![None; formulas.len()];
    let mut variables = 0u32;
    for (var, &p) in vars.iter_mut().zip(&polarity) {
        if p != 0 {
            if variables >= most {
                return Err(Reason::IndexLimit);
            }
            *var = Some(variables);
            variables += 1;
        }
    }
    let var = |x: NodeId| vars[x.index()].unwrap_or_else(|| unreachable!("a polarity"));
    let (t, f) = (|x| Lit::positive(var(x)), |x| Lit::negative(var(x)));
    let mut clauses: Vec<Vec<Lit>> = Vec::new();
    let mut add = |clause: Vec<Lit>| {
        account.charge(clause.len() * size_of::<Lit>() + CLAUSE_BYTES);
        clauses.push(clause);
        over()
    };
    for h in left {
        add(vec![t(*h)]).map_or(Ok(()), Err)?;
    }
    for c in right {
        add(vec![f(*c)]).map_or(Ok(()), Err)?;
    }
    for (id, &p) in polarity.iter().enumerate() {
        if id % POLL == 0 && stop(Progress::new(Phase::Search, POLL as u64, 0)) {
            return Err(Reason::Stopped);
        }
        if p == 0 {
            continue;
        }
        let x = NodeId(id as u32);
        // `forward`: `x` implies its definition; `backward`: its definition
        // implies `x`.
        let (forward, backward) = (p & TRUE != 0, p & FALSE != 0);
        let mut definition: Vec<Vec<Lit>> = Vec::new();
        match formulas.node(x) {
            Node::Atom(_) => {}
            Node::True => {
                if backward {
                    definition.push(vec![t(x)]);
                }
            }
            Node::False => {
                if forward {
                    definition.push(vec![f(x)]);
                }
            }
            Node::Not(a) => {
                if forward {
                    definition.push(vec![f(x), f(a)]);
                }
                if backward {
                    definition.push(vec![t(a), t(x)]);
                }
            }
            Node::And(a, b) => {
                if forward {
                    definition.push(vec![f(x), t(a)]);
                    definition.push(vec![f(x), t(b)]);
                }
                if backward {
                    definition.push(vec![f(a), f(b), t(x)]);
                }
            }
            Node::Or(a, b) => {
                if forward {
                    definition.push(vec![f(x), t(a), t(b)]);
                }
                if backward {
                    definition.push(vec![f(a), t(x)]);
                    definition.push(vec![f(b), t(x)]);
                }
            }
            Node::Implies(a, b) => {
                if forward {
                    definition.push(vec![f(x), f(a), t(b)]);
                }
                if backward {
                    definition.push(vec![t(a), t(x)]);
                    definition.push(vec![f(b), t(x)]);
                }
            }
            Node::Iff(a, b) => {
                if forward {
                    definition.push(vec![f(x), f(a), t(b)]);
                    definition.push(vec![f(x), t(a), f(b)]);
                }
                if backward {
                    definition.push(vec![t(a), t(b), t(x)]);
                    definition.push(vec![f(a), f(b), t(x)]);
                }
            }
        }
        for clause in definition {
            add(clause).map_or(Ok(()), Err)?;
        }
    }
    Ok(Encoding {
        vars,
        variables,
        clauses,
    })
}

/// Decides a classical sequent as [`super::decide`] does, with at most
/// `most` variables, which the tests lower.
pub(super) fn decide(
    sequent: &Sequent,
    limits: &Limits,
    mut stop: impl FnMut(Progress) -> bool,
    most: u32,
) -> Result<Outcome, Error> {
    let logic = Logic::Classical;
    let formulas = sequent.formulas();
    let account = Account::holding(limits.memory_bytes, 0);
    let mut statistics = Statistics::default();
    let encoded = encode(
        formulas,
        sequent.left(),
        sequent.right(),
        most,
        &account,
        &mut stop,
    );
    let found = encoded.and_then(|clauses| {
        statistics.clauses = clauses.clauses.len() as u64;
        let work = limits.work.unwrap_or(u64::MAX);
        let mut solver = Batsat::recording(work, &account, &mut stop);
        for _ in 0..clauses.variables {
            solver.new_var();
        }
        // The solver copies the clauses and is charged for them. Polling it
        // as they go in refuses a sequent past the memory bound before the
        // solver holds them all.
        for (n, clause) in clauses.clauses.iter().enumerate() {
            solver.add_clause(clause);
            if n % POLL == 0
                && let Some(reason) = solver.poll(POLL as u64)
            {
                return Err(reason);
            }
        }
        let answer = solver.solve(&[]);
        statistics.calls = solver.calls();
        statistics.conflicts = solver.conflicts();
        match answer {
            Answer::Satisfiable => {
                let atoms = assignment(formulas, &clauses, &solver);
                Ok(Found::Assignment(atoms))
            }
            Answer::Unsatisfiable => {
                let mut proof = solver.proof().unwrap_or_default();
                account.charge(Step::bytes(0));
                proof.push(Step::Add(Box::new([])));
                Ok(Found::Proof(clauses, proof))
            }
            Answer::Stopped(reason) => Err(reason),
        }
    });
    let (verdict, model) = match found {
        Err(reason) => (Verdict::Unknown(reason), None),
        Ok(Found::Assignment(atoms)) => {
            statistics.worlds = 1;
            let names = sequent.formulas().atom_names();
            let atoms = atoms.iter().map(|&a| names[a as usize].clone()).collect();
            let model = Model::new(vec![World::new(atoms, false, Vec::new())], 0);
            let model = super::super::Countermodel::found(
                sequent.clone(),
                model,
                logic,
                limits,
                &mut stop,
            )?;
            (Verdict::NotValid, model)
        }
        Ok(Found::Proof(clauses, proof)) => {
            statistics.proof_steps = proof.len() as u64;
            // The solver is dropped: the check's account holds only the
            // clauses and the proof.
            let held = clauses
                .clauses
                .iter()
                .map(|c| c.len() * size_of::<Lit>() + size_of::<Vec<Lit>>())
                .chain(proof.iter().map(|step| {
                    let (Step::Add(c) | Step::Delete(c)) = step;
                    Step::bytes(c.len())
                }))
                .sum::<usize>();
            let account = Account::holding(limits.memory_bytes, held as u64);
            match ClausalProof::checked(
                clauses.variables,
                &clauses.clauses,
                &proof,
                limits,
                &account,
                &mut stop,
            ) {
                Ok(checked) => (Verdict::Valid(Evidence::Clausal(checked)), None),
                Err(Rejection::Refused(refusal)) => return Err(Error::Refused(refusal)),
                Err(Rejection::Flaw(flaw)) => {
                    return Err(Error::ReadBack {
                        calculus: logic.calculus(),
                        reason: format!("the solver's clausal proof fails its check: {flaw}"),
                    });
                }
            }
        }
    };
    Ok(Outcome {
        verdict,
        logic,
        statistics,
        model,
    })
}

/// What the solver found.
enum Found {
    /// The atoms true in a model of the clauses, by index, ascending.
    Assignment(Vec<u32>),
    /// The clauses have none: the clauses, and the solver's proof, ending
    /// in the empty clause.
    Proof(Encoding, Vec<Step>),
}

/// Returns the atoms true in the solver's model, by index among the atom
/// names, ascending; an atom without a variable is false.
fn assignment(formulas: &Formulas, clauses: &Encoding, solver: &impl Solver) -> Vec<u32> {
    let mut atoms: Vec<u32> = (0..formulas.len())
        .filter_map(|id| match formulas.node(NodeId(id as u32)) {
            Node::Atom(a) => clauses.vars[id]
                .filter(|&v| solver.value(Lit::positive(v)))
                .map(|_| a),
            Node::True
            | Node::False
            | Node::Not(_)
            | Node::And(..)
            | Node::Or(..)
            | Node::Implies(..)
            | Node::Iff(..) => None,
        })
        .collect();
    atoms.sort_unstable();
    atoms
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::super::{MOST_VARIABLES, drup};
    use super::*;
    use crate::limits::Refusal;
    use crate::linear::search;
    use crate::linear::search::generate::Rng;
    use crate::ordinary::tests::{generated_sequent, valid_by_truth_table};
    use crate::ordinary::{Method, Options};

    /// Returns the pigeonhole sequent of `n + 1` pigeons and `n` holes:
    /// every pigeon in a hole and no two in one, which cannot all hold.
    /// From `n = 7` its refutation takes the solver thousands of conflicts,
    /// and the solver deletes clauses on the way.
    fn pigeons(n: usize) -> Sequent {
        let mut hypotheses = Vec::new();
        for i in 0..=n {
            let holes: Vec<String> = (0..n).map(|j| format!("p{i}h{j}")).collect();
            hypotheses.push(holes.join(" \\/ "));
        }
        for j in 0..n {
            for i in 0..=n {
                for k in i + 1..=n {
                    hypotheses.push(format!("~(p{i}h{j} /\\ p{k}h{j})"));
                }
            }
        }
        format!("{} |-", hypotheses.join(", ")).parse().unwrap()
    }

    /// Encodes the sequent and refutes its clauses, returning them and the
    /// solver's proof ending in the empty clause.
    fn refuted(sequent: &Sequent) -> (Encoding, Vec<Step>) {
        let account = Account::holding(None, 0);
        let clauses = encode(
            sequent.formulas(),
            sequent.left(),
            sequent.right(),
            MOST_VARIABLES,
            &account,
            &mut |_| false,
        )
        .unwrap();
        let mut stop = |_| false;
        let mut solver = Batsat::recording(u64::MAX, &account, &mut stop);
        for _ in 0..clauses.variables {
            solver.new_var();
        }
        for clause in &clauses.clauses {
            solver.add_clause(clause);
        }
        assert_eq!(solver.solve(&[]), Answer::Unsatisfiable);
        let mut proof = solver.proof().unwrap();
        proof.push(Step::Add(Box::new([])));
        (clauses, proof)
    }

    /// Checks the proof against the clauses within the default limits.
    fn checked(clauses: &Encoding, proof: &[Step]) -> Result<(), Rejection> {
        let limits = Limits::default();
        let account = Account::holding(limits.memory_bytes, 0);
        drup::check(
            clauses.variables,
            &clauses.clauses,
            proof,
            &limits,
            &account,
            |_| false,
        )
    }

    /// On generated sequents and a few written ones, some with several
    /// formulas right of `⊢`, the solver agrees with the truth table and
    /// with the embedding; each valid sequent has its clausal proof as
    /// evidence and each model refutes its sequent again.
    #[test]
    fn agrees_with_the_truth_table_and_the_embedding() {
        let limits = Limits::default();
        let mut rng = Rng::new(54);
        let written = [
            "a \\/ ~a",
            "((a -> b) -> a) -> a",
            "a \\/ b |- a, b",
            "a |- b, c",
            "|-",
            "a, ~a |-",
            "false |-",
            "|- true",
            "true |- false",
            "(a <-> b) <-> (b <-> a)",
            "a <-> b, b |- a",
            "a |- a",
        ]
        .map(|text| text.parse::<Sequent>().unwrap());
        let generated = (0..400).map(|_| generated_sequent(&mut rng));
        let (mut proved, mut refuted) = (0, 0);
        for sequent in written.into_iter().chain(generated) {
            let outcome = decide(&sequent, &limits, |_| false, MOST_VARIABLES)
                .unwrap_or_else(|e| panic!("{sequent}: {e}"));
            let valid = match &outcome.verdict {
                Verdict::Valid(Evidence::Clausal(proof)) => {
                    assert_eq!(proof.steps(), outcome.statistics.proof_steps, "{sequent}");
                    assert_eq!(proof.clauses(), outcome.statistics.clauses, "{sequent}");
                    assert!(proof.steps() > 0, "{sequent}");
                    proved += 1;
                    true
                }
                Verdict::NotValid => {
                    let model = &outcome.model.as_ref().unwrap().model;
                    assert_eq!(model.worlds.len(), 1, "{sequent}");
                    assert_eq!(
                        model.refutes(&sequent, Logic::Classical, &Limits::default(), |_| false),
                        Ok(())
                    );
                    refuted += 1;
                    false
                }
                verdict @ (Verdict::Valid(
                    Evidence::Derivation(_) | Evidence::Image | Evidence::Table,
                )
                | Verdict::Unknown(_)) => {
                    panic!("{sequent}: {verdict:?}")
                }
            };
            assert_eq!(valid, valid_by_truth_table(&sequent), "{sequent}");
            let options = Options::default().with_logic(Logic::Classical);
            let embedded = crate::ordinary::decide_within(
                &sequent,
                &options,
                &search::Options::default(),
                &limits,
                |_| false,
            )
            .unwrap();
            assert_eq!(
                valid,
                matches!(embedded.verdict, Verdict::Valid(_)),
                "{sequent}"
            );
        }
        assert!(
            proved > 50 && refuted > 50,
            "{proved} proved, {refuted} refuted"
        );
    }

    /// A proof of the pigeonhole sequent with a step planted wrong is
    /// refused: the learnt clauses taken away, a learnt clause replaced by
    /// a unit no propagation gives, and a model with a conclusion true.
    #[test]
    fn a_planted_wrong_proof_step_is_refused() {
        let sequent = pigeons(4);
        let (clauses, proof) = refuted(&sequent);
        assert_eq!(checked(&clauses, &proof), Ok(()));
        let last = proof.len() - 1;
        assert!(last > 1, "{proof:?}");
        assert_eq!(
            checked(&clauses, &proof[last..]),
            Err(Rejection::Flaw(drup::Flaw::NotRup { step: 0 }))
        );
        // The first pigeon in the first hole follows from no propagation.
        let mut planted = proof.clone();
        let first = Lit::positive(clauses.vars[0].unwrap());
        assert!(matches!(sequent.formulas().node(NodeId(0)), Node::Atom(_)));
        planted.insert(0, Step::Add(Box::new([first])));
        assert_eq!(
            checked(&clauses, &planted),
            Err(Rejection::Flaw(drup::Flaw::NotRup { step: 0 }))
        );
        // A one-world model that makes a formula right of `⊢` true.
        let sequent: Sequent = "a |- a, b".parse().unwrap();
        let model = Model::new(vec![World::new(vec!["a".to_owned()], false, Vec::new())], 0);
        let Err(Error::Model { reason }) =
            model.refutes(&sequent, Logic::Classical, &Limits::default(), |_| false)
        else {
            panic!("a true conclusion accepted");
        };
        assert!(reason.contains("forces the conclusion"), "{reason}");
        let two = Model::new(vec![model.worlds[0].clone(), World::default()], 0);
        assert!(
            two.refutes(&sequent, Logic::Classical, &Limits::default(), |_| false)
                .is_err()
        );
    }

    /// The work bound, the stop, the memory bound and the variables'
    /// bound end the search, each as its reason. The work bound also
    /// refuses the check of a proof that has more steps than the solver
    /// did work, as its deletions make it.
    #[test]
    fn the_search_and_the_check_keep_to_their_bounds() {
        let sequent = pigeons(7);
        let (_, proof) = refuted(&sequent);
        let adds = proof.iter().filter(|s| matches!(s, Step::Add(_))).count() as u64;
        let deletions = proof.len() as u64 - adds;
        assert!(
            deletions > 0 && adds > 100,
            "{adds} added, {deletions} deleted"
        );
        let limits = Limits::default();
        let at = |work| limits.with_work(Some(work));
        let outcome = decide(&sequent, &at(adds / 2), |_| false, MOST_VARIABLES).unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::WorkLimit { .. })
        ));
        let outcome = decide(&sequent, &limits, |_| true, MOST_VARIABLES).unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
        let tight = limits.with_memory_bytes(Some(1024));
        let outcome = decide(&sequent, &tight, |_| false, MOST_VARIABLES).unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::MemoryLimit { .. })
        ));
        let outcome = decide(&sequent, &limits, |_| false, 3).unwrap();
        assert!(matches!(
            outcome.verdict,
            Verdict::Unknown(Reason::IndexLimit)
        ));
        // The solver's work is a unit per clause learnt and one for its
        // call, the clauses added but the empty one; the check's is a unit
        // per step, deletions included.
        assert!(matches!(
            decide(&sequent, &at(adds), |_| false, MOST_VARIABLES),
            Err(Error::Refused(Refusal::Work { limit })) if limit == adds
        ));
    }

    /// A sequent is valid by its clausal proof where the embedding's
    /// bounds stop it first, and the proof is no derivation: a caller that
    /// needs one is told so by name and asks the embedding.
    #[test]
    fn valid_by_the_clausal_proof_where_the_embedding_stops() {
        let options = Options::default()
            .with_logic(Logic::Classical)
            .with_method(Some(Method::Embedding));
        let embedded = |sequent: &Sequent, limits: &Limits| {
            crate::ordinary::decide_within(
                sequent,
                &options,
                &search::Options::default(),
                limits,
                |_| false,
            )
            .unwrap()
            .verdict
        };
        let peirce: Sequent = "|- ((a -> b) -> a) -> a".parse().unwrap();
        let shallow = Limits::default().with_recursion_depth(1);
        let pigeons = pigeons(5);
        let short = Limits::default().with_work(Some(100_000));
        for (sequent, limits) in [(&peirce, &shallow), (&pigeons, &short)] {
            assert!(
                matches!(embedded(sequent, limits), Verdict::Unknown(_)),
                "{sequent}"
            );
            let outcome = decide(sequent, limits, |_| false, MOST_VARIABLES).unwrap();
            let Verdict::Valid(evidence @ Evidence::Clausal(proof)) = &outcome.verdict else {
                panic!("{sequent}: {:?}", outcome.verdict);
            };
            assert_eq!(proof.steps(), outcome.statistics.proof_steps);
            assert!(matches!(
                evidence.derivation(),
                Err(Error::NoDerivation { .. })
            ));
        }
        let Verdict::Valid(evidence) = embedded(&peirce, &Limits::default()) else {
            panic!("the embedding proves Peirce's law");
        };
        assert!(evidence.derivation().is_ok());
    }

    /// The outcome of a sequent valid by its clausal proof is written with
    /// the proof's counts in place of a derivation, at the ordinary
    /// outcome's level as a derivation's outcome is.
    #[cfg(feature = "serialize")]
    #[test]
    fn a_clausal_proof_is_written_as_its_counts() {
        let sequent: Sequent = "|- ((a -> b) -> a) -> a".parse().unwrap();
        let outcome = decide(&sequent, &Limits::default(), |_| false, MOST_VARIABLES).unwrap();
        let Verdict::Valid(Evidence::Clausal(proof)) = outcome.verdict else {
            panic!("{:?}", outcome.verdict);
        };
        let ordinary = crate::ordinary::Outcome::from(outcome);
        let json = serde_json::to_value(&ordinary).unwrap();
        assert_eq!(json["version"], crate::wire::SEARCH);
        assert_eq!(json["verdict"], "valid");
        assert_eq!(json["search"]["method"], "sat");
        assert!(json.get("derivation").is_none(), "{json}");
        assert_eq!(
            json["clausal_proof"],
            serde_json::json!({
                "variables": proof.variables(),
                "clauses": proof.clauses(),
                "steps": proof.steps(),
            })
        );
        assert_eq!(json["search"]["statistics"]["proof_steps"], proof.steps());
        let options = Options::default().with_logic(Logic::Classical);
        let embedded = crate::ordinary::decide_within(
            &sequent,
            &options,
            &search::Options::default(),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        let json = serde_json::to_value(&embedded).unwrap();
        assert_eq!(json["version"], crate::wire::SEARCH);
        assert!(json.get("clausal_proof").is_none(), "{json}");
    }

    /// A sequent of many formulas asks the stop while it is encoded,
    /// before the solver is called.
    #[test]
    fn the_encoder_asks_the_stop() {
        let atoms: Vec<String> = (0..3 * POLL).map(|i| format!("a{i}")).collect();
        let sequent: Sequent = format!("{} |-", atoms.join(" /\\ ")).parse().unwrap();
        let mut asked = 0;
        let outcome = decide(
            &sequent,
            &Limits::default(),
            |_| {
                asked += 1;
                asked > 1
            },
            MOST_VARIABLES,
        )
        .unwrap();
        assert!(matches!(outcome.verdict, Verdict::Unknown(Reason::Stopped)));
        assert_eq!(outcome.statistics.calls, 0);
    }

    /// The proof of the pigeonhole sequent of eight pigeons, written as
    /// DIMACS and DRUP text, is accepted by drat-trim, an outside checker,
    /// which must be on the `PATH` (`nix shell nixpkgs#drat-trim`). The
    /// proof deletes clauses, so the deletions are checked too.
    #[test]
    #[ignore = "needs drat-trim on the PATH: nix shell nixpkgs#drat-trim"]
    fn drat_trim_accepts_the_proof() {
        let directory = std::env::temp_dir().join(format!("deduxit-drup-{}", std::process::id()));
        std::fs::create_dir_all(&directory).unwrap();
        for (name, sequent) in [
            ("peirce", "|- ((a -> b) -> a) -> a".parse().unwrap()),
            ("pigeons-7", pigeons(7)),
        ] {
            let (clauses, proof) = refuted(&sequent);
            assert_eq!(checked(&clauses, &proof), Ok(()), "{name}");
            let deletions = proof
                .iter()
                .filter(|s| matches!(s, Step::Delete(_)))
                .count();
            let (cnf, drup) = drup::dimacs(clauses.variables, &clauses.clauses, &proof);
            let (cnf_path, drup_path) = (
                directory.join(format!("{name}.cnf")),
                directory.join(format!("{name}.drup")),
            );
            std::fs::write(&cnf_path, cnf).unwrap();
            std::fs::write(&drup_path, drup).unwrap();
            let output = std::process::Command::new("drat-trim")
                .arg(&cnf_path)
                .arg(&drup_path)
                .output()
                .expect("drat-trim on the PATH");
            let text = String::from_utf8_lossy(&output.stdout);
            println!(
                "{name}: {} clauses, {} steps, {deletions} deletions\n{text}",
                clauses.clauses.len(),
                proof.len()
            );
            assert!(
                text.lines().any(|l| l.trim() == "s VERIFIED"),
                "{name}: {text}"
            );
            if name == "pigeons-7" {
                assert!(deletions > 0, "{name} deletes no clause");
            }
        }
        std::fs::remove_dir_all(&directory).unwrap();
    }
}