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

//! The additive fast path: it decides a sequent of two additive-only
//! formulas, `⊢ A, B` classically or `A ⊢ B` intuitionistically.
//!
//! It is a recursion on pairs of subformula occurrences, memoized on the
//! pair. While the memo holds every pair, it takes time proportional to
//! the product of the two formulas' sizes. The memo is emptied when it
//! reaches the options' `memo_limit`, which costs time and never an
//! answer.
//!
//! Every rule of the additive fragment replaces one formula of a
//! two-formula sequent by a subformula. So every sequent of a proof is a
//! pair of occurrences, one below each root. The rules on a pair:
//! - a `⊤` closes it;
//! - a `&` needs both its subformulas against the other side;
//! - a `⊕` needs one of its subformulas;
//! - two dual literals are an axiom;
//! - nothing else proves anything, `0` in particular.
//!
//! `&` is invertible, so it is decomposed first. Which `⊕` to decompose
//! is a real choice: a `&` below the other formula's `⊕` may need both
//! sides of this one. So both are tried, and the memo decides a pair
//! reached along two orders once.
//!
//! The procedure is the same in every mode. Two-sided, the rules are the
//! same: `&` on a hypothesis is `⊕` on the one-sided sequent, and so on.
//! Every sequent keeps one goal by itself. Neither weakening nor Mix can
//! help a sequent of two formulas.

use super::memory::{Account, bytes_of};
use super::{Answer, Decide, Engine, Finished, NotTaken, Options, Reason, Statistics, Task, Work};
use crate::Error;
use crate::hash::HashMap;
use crate::limits::Limits;
use crate::linear::fragment::Fragment;
use crate::linear::occurrences::{Forest, Member, OccId};
use crate::linear::proofs::{Branch, Node, NodeId};
use crate::linear::sequents::Kind;

/// The additive fast path, as the front door calls it.
pub(crate) struct Additive;

impl Decide for Additive {
    /// Refuses anything but two formulas of the additive fragment.
    fn admits(&self, task: &Task<'_>) -> Result<(), Error> {
        let because = if !Fragment::ADDITIVE.contains(task.fragment) {
            NotTaken::Fragment {
                decides: Fragment::ADDITIVE,
                goal: task.fragment,
            }
        } else if task.goal.len() != 2 {
            NotTaken::Shape
        } else {
            return Ok(());
        };
        Err(Error::EngineRefused {
            engine: Engine::Additive,
            because,
        })
    }

    /// Decides the pair on the calling thread, whatever
    /// [`Options::jobs`] says.
    fn decide(
        &self,
        task: &Task<'_>,
        options: &Options,
        limits: &Limits,
        account: &Account,
        _work: &Work,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Result<Answer, Error> {
        let found = search_goal(task.forest, task.goal, options, limits, account, stop);
        Ok(Answer::of_arena(task.forest, found, stop))
    }
}

/// Decides a goal of exactly two additive-only occurrences of the
/// forest, the roots or any other pair.
///
/// Returns the node proving the goal (`None` when it is unprovable, or
/// the reason the search gave up), the arena the node lives in, and the
/// statistics. It polls `stop` every [`PAIRS_PER_POLL`] pairs of
/// occurrences, and charges the memo and the arena to `account`.
///
/// The mode plays no part: the additive rules keep one goal by
/// themselves, and neither weakening nor Mix can help a sequent of two
/// formulas.
pub(crate) fn search_goal(
    forest: &Forest,
    goal: &[OccId],
    options: &Options,
    limits: &Limits,
    account: &Account,
    stop: &mut dyn FnMut(u64) -> bool,
) -> Finished {
    let [x, y] = goal else {
        unreachable!("the dispatch sends goals of two formulas here");
    };
    let mut engine = Pairs {
        forest,
        memo: HashMap::default(),
        memo_limit: options.memo_entries(),
        memo_peak: 0,
        nodes: Vec::new(),
        statistics: Statistics::default(),
        depth: 0,
        recursion_limit: limits.recursion_depth,
        account,
        charged: 0,
        stop,
    };
    let result = engine.pair(*x, *y).map_err(|r| r.as_set(options, limits));
    // The pairs since the last poll are work too, so the stop is told
    // them. Its answer is ignored: the search has ended.
    let _ = (engine.stop)(engine.statistics.nodes % PAIRS_PER_POLL);
    let statistics = Statistics {
        memo_entries: engine.memo_peak as u64,
        ..engine.statistics
    };
    Finished {
        result,
        nodes: engine.nodes,
        statistics,
        instances: None,
    }
}

/// How many pairs the search decides between two polls of its stop,
/// some microseconds of work.
const PAIRS_PER_POLL: u64 = 1 << 10;

/// The state of one run: the problem, the memo of pairs, the proof arena
/// and the counters.
struct Pairs<'a> {
    /// The problem.
    forest: &'a Forest,
    /// The pairs decided, each with the node proving it, or `None` when
    /// it is unprovable.
    memo: HashMap<(OccId, OccId), Option<NodeId>>,
    /// The most pairs the memo holds; zero switches it off.
    memo_limit: usize,
    /// The most pairs the memo held at once.
    memo_peak: usize,
    /// The proof arena.
    nodes: Vec<Node>,
    /// The counters: `nodes` is the pairs visited, memo hits included.
    statistics: Statistics,
    /// How deep the recursion on pairs is now.
    depth: u32,
    /// The deepest nesting allowed.
    recursion_limit: u32,
    /// The account the memo and the arena are charged to.
    account: &'a Account,
    /// The bytes of the memo and the arena charged so far.
    charged: usize,
    /// The caller's stop condition.
    stop: &'a mut dyn FnMut(u64) -> bool,
}

impl Pairs<'_> {
    /// Decides the sequent of the two occurrences. Returns the node
    /// proving it, `None` when it is unprovable, or the reason the search
    /// stops.
    fn pair(&mut self, x: OccId, y: OccId) -> Result<Option<NodeId>, Reason> {
        self.statistics.nodes += 1;
        // A pair is the unit of work. The stop is told them in batches:
        // asking it at every pair costs a twentieth of the search.
        if self.statistics.nodes.is_multiple_of(PAIRS_PER_POLL) && (self.stop)(PAIRS_PER_POLL) {
            return Err(Reason::Stopped);
        }
        self.settle()?;
        if let Some(&node) = self.memo.get(&(x, y)) {
            self.statistics.memo_hits += 1;
            return Ok(node);
        }
        if self.depth >= self.recursion_limit {
            return Err(Reason::RecursionLimit {
                depth: self.recursion_limit,
            });
        }
        self.depth += 1;
        let result = self.decide(x, y);
        self.depth -= 1;
        let node = result?;
        if self.memo_limit != 0 {
            // A full memo is emptied. Every entry is a fact the search can
            // find again, and the arena keeps the nodes of the proofs.
            if self.memo.len() >= self.memo_limit {
                self.memo.clear();
            }
            self.memo.insert((x, y), node);
            self.memo_peak = self.memo_peak.max(self.memo.len());
        }
        Ok(node)
    }

    /// Applies the rules to the pair and returns the node proving it, or
    /// `None`. The order: `⊤`, then the invertible `&` on either side,
    /// then the axiom, then a `⊕` on either side, one side at a time.
    fn decide(&mut self, x: OccId, y: OccId) -> Result<Option<NodeId>, Reason> {
        let f = self.forest;
        let (kx, ky) = (f.kind(x), f.kind(y));
        if kx == Kind::Top {
            return Ok(Some(self.push(Node::Top(Member::from(x)))));
        }
        if ky == Kind::Top {
            return Ok(Some(self.push(Node::Top(Member::from(y)))));
        }
        // `&` on either side: both subformulas against the other formula.
        for (o, other, x_first) in [(x, y, true), (y, x, false)] {
            if f.kind(o) != Kind::With {
                continue;
            }
            let (l, r) = (f.left(o).unwrap(), f.right(o).unwrap());
            let Some(left) = self.ordered(l, other, x_first)? else {
                return Ok(None);
            };
            let Some(right) = self.ordered(r, other, x_first)? else {
                return Ok(None);
            };
            return Ok(Some(self.push(Node::With(Member::from(o), left, right))));
        }
        // Two literals: an axiom if they are dual; `0` and a lone literal
        // prove nothing.
        if kx.is_literal() && ky.is_literal() {
            let dual = f.dual_literals(x, y);
            return Ok(dual.then(|| self.push(Node::Ax(x.into(), y.into()))));
        }
        // `⊕` on either side: one subformula against the other formula.
        for (o, other, x_first) in [(x, y, true), (y, x, false)] {
            if f.kind(o) != Kind::Plus {
                continue;
            }
            for (side, sub) in [
                (Branch::Left, f.left(o).unwrap()),
                (Branch::Right, f.right(o).unwrap()),
            ] {
                if let Some(premise) = self.ordered(sub, other, x_first)? {
                    return Ok(Some(self.push(Node::Plus(Member::from(o), side, premise))));
                }
            }
        }
        Ok(None)
    }

    /// Decides the pair of a subformula `sub` of one side and the other
    /// formula. It keeps the memo's order: the occurrence below the first
    /// root comes first.
    fn ordered(
        &mut self,
        sub: OccId,
        other: OccId,
        sub_first: bool,
    ) -> Result<Option<NodeId>, Reason> {
        if sub_first {
            self.pair(sub, other)
        } else {
            self.pair(other, sub)
        }
    }

    /// Charges the account what the memo and the arena grew by. When that
    /// passes the bound, it drops the memo to make room.
    ///
    /// Fails when the arena alone is over the bound, or holds as many
    /// nodes as an id can name. A pair adds one node at most, so the
    /// check before each pair suffices.
    fn settle(&mut self) -> Result<(), Reason> {
        /// The bytes of a slot of the memo: a pair, a node, a control byte.
        const SLOT: usize = size_of::<((OccId, OccId), Option<NodeId>)>() + 1;
        if self.nodes.len() >= u32::MAX as usize {
            return Err(Reason::IndexLimit);
        }
        let held = self.memo.capacity() * SLOT + bytes_of(&self.nodes);
        if held == self.charged {
            return Ok(());
        }
        self.account.resize(self.charged, held);
        self.charged = held;
        if self.account.over() {
            self.memo = HashMap::default();
            self.account.resize(self.charged, bytes_of(&self.nodes));
            self.charged = bytes_of(&self.nodes);
            if self.account.over() {
                return Err(Reason::MemoryLimit {
                    limit_bytes: self.account.limit(),
                });
            }
        }
        Ok(())
    }

    /// Appends a node to the arena and returns its id.
    fn push(&mut self, node: Node) -> NodeId {
        let id = NodeId::new(self.nodes.len() as u32);
        self.nodes.push(node);
        id
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::linear::Sequent;
    use crate::linear::fragment::Mode;
    use crate::linear::search::generate::Rng;
    use crate::linear::search::{Engine as Which, Verdict, prove};

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

    /// Decides `input` under `mode` with the engine given, checks the proof
    /// if there is one, and returns whether it is provable.
    fn decide(input: &str, mode: Mode, engine: Which) -> bool {
        let s = sequent(input);
        let outcome = prove(&s, mode, &Options::default().with_engine(Some(engine)))
            .unwrap_or_else(|e| panic!("{input:?} by {engine}: {e}"));
        assert_eq!(outcome.engine, engine);
        match outcome.verdict {
            Verdict::Proved(proof) => {
                assert_eq!(proof.sequent(), &s);
                proof.check(mode).unwrap_or_else(|e| {
                    panic!("{input:?} by {engine}: {}", e.describe(proof.forest()))
                });
                true
            }
            Verdict::Unprovable(_) => false,
            Verdict::Unknown(reason) => panic!("{input:?} by {engine}: {reason}"),
        }
    }

    /// A memo that fills up is emptied and the verdict stays: the identity
    /// of depth 8, which decides thousands of pairs, with room for 64.
    #[test]
    fn capped_memo() {
        let instance = crate::linear::families::find("additive")
            .unwrap()
            .instance(8, 0)
            .unwrap();
        let options = Options::default().with_memo_limit(64);
        let outcome = prove(&instance.sequent, instance.mode, &options).unwrap();
        assert_eq!(outcome.engine, Which::Additive);
        assert_eq!(outcome.statistics.memo_entries, 64);
        let Verdict::Proved(proof) = outcome.verdict else {
            panic!("the identity is provable");
        };
        assert_eq!(proof.check(instance.mode), Ok(()));
    }

    /// The stop is asked as the pairs are decided, every so many of them:
    /// the identity of depth 8 stops at the first poll when the stop says
    /// so from the start.
    #[test]
    fn stops_between_pairs() {
        let instance = crate::linear::families::find("additive")
            .unwrap()
            .instance(8, 0)
            .unwrap();
        let outcome = crate::linear::search::prove_within(
            &instance.sequent,
            instance.mode,
            &Options::default(),
            &crate::Limits::default(),
            |_| true,
        )
        .unwrap();
        assert_eq!(outcome.engine, Which::Additive);
        assert!(
            matches!(
                outcome.verdict,
                Verdict::Unknown(crate::linear::search::Reason::Stopped)
            ),
            "{:?}",
            outcome.verdict
        );
        assert_eq!(outcome.statistics.nodes, super::PAIRS_PER_POLL);
    }

    /// The additive fragment's textbook sequents, classically and
    /// intuitionistically.
    #[test]
    fn additive_sequents() {
        for (input, expected) in [
            ("a |- a", true),
            ("a |- b", false),
            ("a & b |- a", true),
            ("a |- a & b", false),
            ("a |- a + b", true),
            ("a + b |- a", false),
            ("a & b |- a + b", true),
            ("a + b |- a & b", false),
            ("a & b |- b & a", true),
            ("a + b |- b + a", true),
            ("a & (b + c) |- (a & b) + (a & c)", false),
            ("(a & b) + (a & c) |- a & (b + c)", true),
            ("|- top, 0", true),
            ("0 |- a", true),
            ("a |- 0", false),
            ("top |- a", false),
            ("a |- top", true),
            ("0 |- top", true),
            ("a & top |- a", true),
            ("a |- a & top", true),
            ("a + 0 |- a", true),
            ("a |- a + 0", true),
            ("0 + b |- a", false),
            ("(a + top) & b |- b", true),
            ("|- a & b, ~a + ~b", true),
            ("|- a & b, ~a", false),
            // A `&` below the second formula's `⊕` needs both sides of the
            // first formula's `⊕`, so the second `⊕` must be tried too.
            ("|- ~c + ~a, b + (c & a)", true),
            ("b + (c & a) |- b + (c & a)", true),
            ("c & a |- b + (c & a)", true),
        ] {
            for mode in [
                Mode::CLASSICAL,
                Mode::CLASSICAL.with_affine(),
                Mode::CLASSICAL.with_mix(),
            ] {
                assert_eq!(
                    decide(input, mode, Which::Additive),
                    expected,
                    "{input:?} {mode}"
                );
                assert_eq!(
                    decide(input, mode, Which::Focus),
                    expected,
                    "{input:?} {mode}"
                );
            }
            if !input.starts_with("|-") {
                let i = Mode::INTUITIONISTIC;
                assert_eq!(decide(input, i, Which::Additive), expected, "{input:?} {i}");
                assert_eq!(decide(input, i, Which::TwoSided), expected, "{input:?} {i}");
            }
        }
    }

    /// A random additive formula in the parser's syntax.
    fn formula(rng: &mut Rng, depth: usize) -> String {
        if depth == 0 || rng.one_in(4) {
            return match rng.below(8) {
                0 => "top".into(),
                1 => "0".into(),
                n => ["a", "b", "c", "~a", "~b", "~c"][n - 2].into(),
            };
        }
        let (l, r) = (formula(rng, depth - 1), formula(rng, depth - 1));
        if rng.one_in(2) {
            format!("({l} & {r})")
        } else {
            format!("({l} + {r})")
        }
    }

    /// On random pairs of additive formulas the fast path agrees with the
    /// focused engine, classically and, where the pair is an intuitionistic
    /// sequent, with the two-sided engine.
    #[test]
    fn agrees_with_the_focused_engine() {
        let mut rng = Rng::new(11);
        let (mut compared, mut provable) = (0, 0);
        for _ in 0..300 {
            let input = format!("|- {}, {}", formula(&mut rng, 3), formula(&mut rng, 3));
            let expected = decide(&input, Mode::CLASSICAL, Which::Focus);
            assert_eq!(
                decide(&input, Mode::CLASSICAL, Which::Additive),
                expected,
                "{input:?}"
            );
            let i = Mode::INTUITIONISTIC;
            if prove(&sequent(&input), i, &Options::default()).is_ok() {
                let expected = decide(&input, i, Which::TwoSided);
                assert_eq!(decide(&input, i, Which::Additive), expected, "{input:?}");
            }
            compared += 1;
            provable += usize::from(expected);
        }
        assert!(
            provable > 30 && provable < compared,
            "{provable} of {compared}"
        );
    }

    /// The memo bounds the work by the product of the sizes. Two deep `⊕`
    /// towers over atoms that never match are refuted with at most as
    /// many pairs decided as there are subformula pairs, not one per
    /// order of choices.
    #[test]
    fn memoized() {
        let mut left = String::from("a");
        let mut right = String::from("~b");
        for _ in 0..7 {
            left = format!("({left} + {left})");
            right = format!("({right} + {right})");
        }
        let s = sequent(&format!("|- {left}, {right}"));
        let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
        assert_eq!(outcome.engine, Which::Additive);
        assert!(matches!(outcome.verdict, Verdict::Unprovable(_)));
        // 2⁸ − 1 subformulas on each side, so at most that squared pairs
        // decided; every other visit is a memo hit.
        let s = outcome.statistics;
        assert!(s.memo_entries <= 255 * 255, "{}", s.memo_entries);
        assert!(s.memo_hits > 0);
        assert_eq!(s.memo_entries + s.memo_hits, s.nodes);
    }
}