deduxit 0.4.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Many sequents decided in one call. Problems go in and results come
//! out, in the order of the problems, each as soon as it and those before
//! it are decided. So a stream of questions is answered one by one.
//!
//! The machine's threads go either across the sequents, one sequent per
//! worker on the sequential engines, or within one sequent at a time
//! ([`Cores`]). The memory bound of each search and the batch's own bound
//! decide how many workers run at once (the [`Plan`] each work call is
//! handed). The options of every sequent's search and the [`Limits`] each
//! runs within are arguments of the batch beside its own options. Without
//! the `parallel` feature a batch runs on the caller's thread.
//!
//! # Examples
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::Limits;
//! use deduxit::linear::search::{self, Verdict};
//! use deduxit::linear::search::batch::{Options, Problem, prove};
//!
//! let problems = ["A |- A", "A |- B"].map(|text| Problem::new(text, text.parse().unwrap(), None));
//! let search = search::Options::default();
//! let proved: Vec<bool> = prove(problems, &Options::default(), &search, &Limits::default())
//!     .map(|answer| matches!(answer.outcome.unwrap().verdict, Verdict::Proved(_)))
//!     .collect();
//! assert_eq!(proved, [true, false]);
//! ```

use super::{Options as SearchOptions, Outcome};
use crate::{
    Error, Limits,
    linear::{Mode, Sequent},
};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// How a batch spends the machine's threads. In JSON (feature
/// `serialize`) it is `"auto"`, `"across"` or `"within"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Cores {
    /// Across the sequents when the batch has at least as many as there
    /// are workers, else within each.
    #[default]
    Auto,
    /// One sequent per worker, each searched by the sequential engines,
    /// whose outcome is a function of the input.
    Across,
    /// One sequent at a time, searched with the threads of the search
    /// options.
    Within,
}

/// How a batch shares the machine among its sequents. The options of each
/// sequent's search and the limits it runs within are separate arguments
/// of [`run`] and [`prove`]. `Limits::memory_bytes` is each search's
/// bound.
///
/// # JSON
///
/// With the feature `serialize`, an object of the fields. A missing field
/// takes its default, and a misspelt one is refused. `"mode"` is a mode's
/// name (`"classical"`), `"cores"` one of `"auto"`, `"across"` and
/// `"within"`, `"workers"` a number, and `"total_memory_bytes"` a number,
/// or `null` for no bound.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct Options {
    /// The mode of a problem that names none.
    pub mode: Mode,
    /// Where the threads go.
    pub cores: Cores,
    /// The most sequents decided at once, across the sequents. Zero is
    /// taken as one, and a number above
    /// [`MAX_JOBS`](SearchOptions::MAX_JOBS) as that many.
    pub workers: usize,
    /// The most memory all the searches of the batch may hold together,
    /// or `None` for no bound but each search's.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub total_memory_bytes: Option<u64>,
}

impl Options {
    /// The default number of workers: one, since this crate does not ask
    /// the machine how many threads it runs; a front end sets it.
    pub const DEFAULT_WORKERS: usize = 1;
    /// The default bound of the whole batch, 4 GiB: four searches at the
    /// default bound of each.
    pub const DEFAULT_TOTAL_MEMORY_BYTES: u64 = 4 << 30;

    /// Returns the options with another default [`mode`](Self::mode).
    #[must_use]
    pub const fn with_mode(self, mode: Mode) -> Self {
        Self { mode, ..self }
    }

    /// Returns the options with another use of the [`cores`](Self::cores).
    #[must_use]
    pub const fn with_cores(self, cores: Cores) -> Self {
        Self { cores, ..self }
    }

    /// Returns the options with another number of [`workers`](Self::workers).
    #[must_use]
    pub const fn with_workers(self, workers: usize) -> Self {
        Self { workers, ..self }
    }

    /// Returns the options with another bound on the whole batch's memory
    /// ([`total_memory_bytes`](Self::total_memory_bytes)).
    #[must_use]
    pub const fn with_total_memory_bytes(self, total_memory_bytes: Option<u64>) -> Self {
        Self {
            total_memory_bytes,
            ..self
        }
    }

    /// Returns how the batch runs, `within` its sequents or across them.
    ///
    /// Across, as many workers run as the batch's bound holds searches at
    /// the bound of each, each on one thread. There is at least one, whose
    /// bound is then the batch's. Within, one worker runs at the batch's
    /// bound. A race of one thread against a pool of the others shares
    /// that bound between its two searches ([`race`](super::race),
    /// feature `parallel`).
    pub(crate) fn plan(&self, within: bool, search: &SearchOptions, limits: &Limits) -> Plan {
        let search = search.clone();
        let mut limits = *limits;
        let total = self.total_memory_bytes;
        if within {
            limits.memory_bytes = smaller(limits.memory_bytes, total);
            return Plan {
                workers: 1,
                search,
                limits,
            };
        }
        let most = self.workers.clamp(1, SearchOptions::MAX_JOBS);
        let workers = match (limits.memory_bytes, total) {
            (Some(each), Some(total)) => usize::try_from(total / each.max(1)).unwrap_or(usize::MAX),
            (None, Some(total)) => {
                limits.memory_bytes = Some(total / u64::try_from(most).unwrap_or(u64::MAX));
                usize::MAX
            }
            (_, None) => usize::MAX,
        };
        limits.memory_bytes = smaller(limits.memory_bytes, total);
        Plan {
            workers: workers.clamp(1, most),
            search: search.with_jobs(1),
            limits,
        }
    }
}

/// Returns the smaller of two bounds, `None` being none.
fn smaller(a: Option<u64>, b: Option<u64>) -> Option<u64> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, None) => a,
        (None, b) => b,
    }
}

impl Default for Options {
    /// The classical mode, [`DEFAULT_WORKERS`](Self::DEFAULT_WORKERS) and
    /// [`DEFAULT_TOTAL_MEMORY_BYTES`](Self::DEFAULT_TOTAL_MEMORY_BYTES).
    fn default() -> Self {
        Self {
            mode: Mode::CLASSICAL,
            cores: Cores::Auto,
            workers: Self::DEFAULT_WORKERS,
            total_memory_bytes: Some(Self::DEFAULT_TOTAL_MEMORY_BYTES),
        }
    }
}

/// How a batch runs: how many workers, and the options and limits of
/// each search.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Plan {
    /// The sequents decided at once.
    pub workers: usize,
    /// The options of each sequent's search.
    pub search: SearchOptions,
    /// The limits each search runs within.
    pub limits: Limits,
}

impl Plan {
    /// Returns the plan of one sequent decided alone, with these options
    /// and limits.
    pub const fn alone(search: SearchOptions, limits: Limits) -> Self {
        Self {
            workers: 1,
            search,
            limits,
        }
    }
}

/// A problem of [`prove`].
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Problem {
    /// Its name, which its answer carries.
    pub name: String,
    /// The sequent.
    pub sequent: Sequent,
    /// Its mode, or `None` for the batch's.
    pub mode: Option<Mode>,
}

impl Problem {
    /// Returns the problem `name` of deciding `sequent`, in `mode` or the
    /// batch's.
    pub fn new(name: impl Into<String>, sequent: Sequent, mode: Option<Mode>) -> Self {
        Self {
            name: name.into(),
            sequent,
            mode,
        }
    }
}

/// The answer to a problem of [`prove`].
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Answer {
    /// The problem's name.
    pub name: String,
    /// What the search returned.
    pub outcome: Result<Outcome, Error>,
}

/// Decides the problems, and returns their answers in order, as they are
/// decided. Each search ends at the limits, or when the results are
/// cancelled ([`Results::cancel`]) or dropped. A front end that needs a
/// time limit of its own calls [`run`].
pub fn prove(
    problems: impl IntoIterator<Item = Problem, IntoIter: Send + 'static>,
    options: &Options,
    search: &SearchOptions,
    limits: &Limits,
) -> Results<Answer> {
    let mode = options.mode;
    run(
        problems,
        options,
        search,
        limits,
        move |problem: Problem, plan: &Plan, cancel: &Cancel| {
            let mode = problem.mode.unwrap_or(mode);
            let outcome =
                super::prove_within(&problem.sequent, mode, &plan.search, &plan.limits, |_| {
                    cancel.is_cancelled()
                });
            Answer {
                outcome,
                name: problem.name,
            }
        },
    )
}

/// Applies `work` to every problem, with the options of its search as the
/// plan says, and returns the results in the order of the problems, each
/// as soon as it and those before it are done.
///
/// `work` is handed the batch's [`Cancel`], which its stop asks.
/// `Cores::Auto` reads up to as many problems as there are workers before
/// the first starts, so a stream whose next problem waits on an answer
/// wants `Across` or `Within`. Workers that cannot start, because the
/// stack the limits ask for is not to be had, leave the batch to those
/// that did, or to the caller's thread.
///
/// # Panics
///
/// The iterator resumes a panic in `work` at its problem's place, after
/// the results before it. The batch then takes no more problems and is
/// cancelled, so the other workers end.
///
/// # Examples
///
/// Each problem's work proves its sequent within a time limit of its own,
/// and stops early when the batch is cancelled:
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::Limits;
/// use deduxit::linear::search::{self, batch};
/// use deduxit::linear::{Mode, Sequent, Verdict, prove_within};
/// use std::time::{Duration, Instant};
///
/// let problems: Vec<Sequent> = vec!["A |- A".parse()?, "A |- B".parse()?];
/// let results = batch::run(
///     problems,
///     &batch::Options::default(),
///     &search::Options::default(),
///     &Limits::default(),
///     |sequent: Sequent, plan: &batch::Plan, cancel: &batch::Cancel| {
///         let start = Instant::now();
///         let outcome = prove_within(&sequent, Mode::CLASSICAL, &plan.search, &plan.limits, |_| {
///             cancel.is_cancelled() || start.elapsed() > Duration::from_secs(2)
///         });
///         matches!(outcome.map(|o| o.verdict), Ok(Verdict::Proved(_)))
///     },
/// );
/// assert_eq!(results.collect::<Vec<bool>>(), [true, false]);
/// # Ok::<(), deduxit::Error>(())
/// ```
pub fn run<P, R>(
    problems: impl IntoIterator<Item = P, IntoIter: Send + 'static>,
    options: &Options,
    search: &SearchOptions,
    limits: &Limits,
    work: impl Fn(P, &Plan, &Cancel) -> R + Send + Sync + 'static,
) -> Results<R>
where
    P: Send + 'static,
    R: Send + 'static,
{
    let mut problems = problems.into_iter();
    let mut first = Vec::new();
    let within = match options.cores {
        Cores::Across => false,
        Cores::Within => true,
        Cores::Auto => {
            let workers = options.workers.clamp(1, SearchOptions::MAX_JOBS);
            first.extend(problems.by_ref().take(workers));
            first.len() < workers
        }
    };
    let problems: Box<dyn Iterator<Item = P> + Send> = Box::new(first.into_iter().chain(problems));
    let plan = options.plan(within, search, limits);
    let cancel = Cancel::default();
    #[cfg(feature = "parallel")]
    let (problems, work) = if plan.workers > 1 {
        match workers::Workers::start(problems, plan.clone(), cancel.clone(), work) {
            Ok(workers) => {
                return Results {
                    inner: Inner::Workers(workers),
                    cancel,
                };
            }
            Err(unstarted) => unstarted,
        }
    } else {
        (problems, work)
    };
    let canceller = cancel.clone();
    Results {
        inner: Inner::Here(Box::new(
            problems.map(move |problem| work(problem, &plan, &canceller)),
        )),
        cancel,
    }
}

/// Asks the work of a batch to end. [`Results::cancel`] raises it, and so
/// does dropping the results. The work's stop asks it, so a search in
/// flight ends as `Unknown(Reason::Stopped)`.
#[derive(Clone, Debug, Default)]
pub struct Cancel(Arc<AtomicBool>);

impl Cancel {
    /// Returns whether the batch was cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Relaxed)
    }

    /// Cancels the batch.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Relaxed);
    }
}

/// The results of a batch, in the order of its problems. Dropping them
/// cancels the work still running.
pub struct Results<R> {
    /// Where the work runs.
    inner: Inner<R>,
    /// What the work asks whether to end.
    cancel: Cancel,
}

impl<R> Results<R> {
    /// Cancels the work: every search in flight ends at its next poll, and
    /// the problems not yet begun are answered as their work answers a
    /// cancelled batch.
    pub fn cancel(&self) {
        self.cancel.cancel();
    }

    /// Returns a handle that cancels the work from elsewhere, such as a
    /// handler of an interruption.
    pub fn canceller(&self) -> Cancel {
        self.cancel.clone()
    }
}

impl<R> Drop for Results<R> {
    /// Cancels the work still running.
    fn drop(&mut self) {
        self.cancel.cancel();
    }
}

impl<R> std::fmt::Debug for Results<R> {
    /// Writes the type's name only: what it holds is the workers' state.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Results").finish_non_exhaustive()
    }
}

/// Where a batch runs.
enum Inner<R> {
    /// On the caller's thread, one problem per result asked for.
    Here(Box<dyn Iterator<Item = R> + Send>),
    /// On workers of its own.
    #[cfg(feature = "parallel")]
    Workers(workers::Workers<R>),
}

impl<R> Iterator for Results<R> {
    type Item = R;

    fn next(&mut self) -> Option<R> {
        match &mut self.inner {
            Inner::Here(results) => results.next(),
            #[cfg(feature = "parallel")]
            Inner::Workers(workers) => workers.next(),
        }
    }
}

/// The workers of a batch, on threads of their own.
#[cfg(feature = "parallel")]
mod workers {
    use super::{Cancel, Plan};
    use std::collections::BTreeMap;
    use std::panic::AssertUnwindSafe;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::mpsc::{Receiver, channel};
    use std::sync::{Arc, Condvar, Mutex};
    use std::thread::JoinHandle;
    use std::time::Duration;

    /// How many problems per worker may be taken beyond the first result
    /// not yet given out, so that the results held for their turn stay
    /// few while a slow problem is decided.
    pub(super) const AHEAD: usize = 4;

    /// How long a worker waits for its turn before it looks again. A lost
    /// wake-up costs this much, not a hang.
    const WAIT: Duration = Duration::from_millis(10);

    /// The problems not yet taken, and where the workers are in them.
    struct Queue<P> {
        /// The problems not yet taken.
        problems: Box<dyn Iterator<Item = P> + Send>,
        /// How many were taken.
        taken: usize,
        /// Whether the problems ran out.
        ended: bool,
    }

    /// What the workers share.
    struct Shared<P> {
        /// The queue, locked only to take a problem.
        queue: Mutex<Queue<P>>,
        /// How many results were given out. The iterator raises it without
        /// the lock: a worker that waits on a stream for the next problem
        /// holds the lock, and the client may send that problem only after
        /// the answer, so giving the answer out must not take the lock.
        given: AtomicUsize,
        /// Woken when a result is given out.
        turn: Condvar,
        /// Whether the batch ended: its results were dropped, or a work
        /// panicked. It is set and read without the lock, which a worker
        /// waiting on a stream holds. A mark under the lock would have to
        /// be set with `try_lock`, which can miss, and a worker waiting at
        /// the window would then wait for good.
        over: AtomicBool,
    }

    /// The workers and the results they sent before their turn.
    pub(super) struct Workers<R> {
        /// The results as they are done, with their places, or the panic
        /// of the work at that place.
        done: Receiver<(usize, std::thread::Result<R>)>,
        /// Results done before those ahead of them.
        held: BTreeMap<usize, std::thread::Result<R>>,
        /// The place of the next result to give out.
        next: usize,
        /// Raises `given` and wakes the workers.
        given: Box<dyn Fn(usize) + Send>,
        /// Ends the queue, so that no worker takes another problem.
        end: Box<dyn Fn() + Send>,
        /// The threads.
        threads: Vec<JoinHandle<()>>,
    }

    impl<R: Send + 'static> Workers<R> {
        /// Starts the workers the plan names on the problems, as many as
        /// can start, or gives the problems and the work back when none
        /// can.
        pub(super) fn start<P: Send + 'static, W>(
            problems: Box<dyn Iterator<Item = P> + Send>,
            plan: Plan,
            cancel: Cancel,
            work: W,
        ) -> Result<Self, (Box<dyn Iterator<Item = P> + Send>, W)>
        where
            W: Fn(P, &Plan, &Cancel) -> R + Send + Sync + 'static,
        {
            let shared = Arc::new(Shared {
                queue: Mutex::new(Queue {
                    problems,
                    taken: 0,
                    ended: false,
                }),
                given: AtomicUsize::new(0),
                turn: Condvar::new(),
                over: AtomicBool::new(false),
            });
            let work = Arc::new(work);
            let (sender, done) = channel();
            let ahead = AHEAD * plan.workers;
            let mut threads = Vec::with_capacity(plan.workers);
            for _ in 0..plan.workers {
                let (shared, work, sender) = (shared.clone(), work.clone(), sender.clone());
                let (plan, cancel) = (plan.clone(), cancel.clone());
                let started = std::thread::Builder::new()
                    .name("batch".into())
                    .stack_size(plan.limits.stack_bytes())
                    .spawn(move || {
                        loop {
                            let (place, problem) = {
                                let mut queue = crate::linear::search::lock(&shared.queue);
                                while !queue.ended
                                    && !shared.over.load(Ordering::Acquire)
                                    && queue.taken >= shared.given.load(Ordering::Acquire) + ahead
                                {
                                    queue = shared
                                        .turn
                                        .wait_timeout(queue, WAIT)
                                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                                        .0;
                                }
                                if queue.ended || shared.over.load(Ordering::Acquire) {
                                    return;
                                }
                                let next = std::panic::catch_unwind(AssertUnwindSafe(|| {
                                    queue.problems.next()
                                }));
                                let place = queue.taken;
                                match next {
                                    Ok(Some(problem)) => {
                                        queue.taken += 1;
                                        (place, problem)
                                    }
                                    Ok(None) => {
                                        queue.ended = true;
                                        return;
                                    }
                                    // The problems' own panic ends the batch
                                    // at its place, as a work's does.
                                    Err(panic) => {
                                        queue.taken += 1;
                                        drop(queue);
                                        let _ = sender.send((place, Err(panic)));
                                        cancel.cancel();
                                        shared.over.store(true, Ordering::Release);
                                        shared.turn.notify_all();
                                        return;
                                    }
                                }
                            };
                            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                                work(problem, &plan, &cancel)
                            }));
                            let panicked = result.is_err();
                            if sender.send((place, result)).is_err() || panicked {
                                if panicked {
                                    // The batch ends at the panic: no worker
                                    // takes another problem, and the work in
                                    // flight is asked to stop. A worker that
                                    // holds the queue waits on a stream, and
                                    // ends at its next send.
                                    cancel.cancel();
                                    shared.over.store(true, Ordering::Release);
                                    shared.turn.notify_all();
                                }
                                return;
                            }
                        }
                    });
                match started {
                    Ok(thread) => threads.push(thread),
                    Err(_) => break,
                }
            }
            if threads.is_empty() {
                // Nothing else holds the queue or the work now.
                let queue = Arc::try_unwrap(shared).ok().map(|s| s.queue);
                let work = Arc::try_unwrap(work).ok();
                if let (Some(queue), Some(work)) = (queue, work) {
                    let Queue { problems, .. } = crate::linear::search::taken(queue);
                    return Err((problems, work));
                }
                unreachable!("no worker started, so none holds the queue or the work");
            }
            let (raise, end) = (shared.clone(), shared);
            Ok(Self {
                done,
                held: BTreeMap::new(),
                next: 0,
                given: Box::new(move |n| {
                    raise.given.store(n, Ordering::Release);
                    raise.turn.notify_all();
                }),
                end: Box::new(move || {
                    end.over.store(true, Ordering::Release);
                    end.turn.notify_all();
                }),
                threads,
            })
        }
    }

    impl<R> Workers<R> {
        /// Returns the next result in order, waiting for it; resumes the
        /// panic of the work at its place, and at the end a worker's own.
        pub(super) fn next(&mut self) -> Option<R> {
            loop {
                if let Some(result) = self.held.remove(&self.next) {
                    self.next += 1;
                    (self.given)(self.next);
                    match result {
                        Ok(result) => return Some(result),
                        Err(panic) => std::panic::resume_unwind(panic),
                    }
                }
                match self.done.recv() {
                    Ok((place, result)) => {
                        self.held.insert(place, result);
                    }
                    Err(_) => {
                        for thread in self.threads.drain(..) {
                            if let Err(panic) = thread.join() {
                                std::panic::resume_unwind(panic);
                            }
                        }
                        return None;
                    }
                }
            }
        }
    }

    impl<R> Drop for Workers<R> {
        /// Lets the workers finish the problems they hold and take no more.
        fn drop(&mut self) {
            (self.end)();
        }
    }
}

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

    /// The answers come in the order of the problems, on one worker and on
    /// several, whatever order the workers finish in.
    #[test]
    fn answers_keep_the_problems_order() {
        let texts: Vec<String> = (0..40)
            .map(|i| match i % 3 {
                0 => format!("a{i} |- a{i}"),
                1 => format!("a{i} |- b{i}"),
                _ => format!("a{i}, a{i} -o b{i} |- b{i}"),
            })
            .collect();
        for (workers, cores) in [(1, Cores::Auto), (4, Cores::Across), (4, Cores::Auto)] {
            let problems: Vec<Problem> = texts
                .iter()
                .map(|t| Problem::new(t.clone(), t.parse().unwrap(), None))
                .collect();
            let options = Options {
                workers,
                cores,
                ..Options::default()
            };
            let search = SearchOptions::default();
            let answers: Vec<(String, bool)> =
                prove(problems, &options, &search, &Limits::default())
                    .map(|a| {
                        let proved = matches!(a.outcome.unwrap().verdict, Verdict::Proved(_));
                        (a.name, proved)
                    })
                    .collect();
            let expected: Vec<(String, bool)> = texts
                .iter()
                .enumerate()
                .map(|(i, t)| (t.clone(), i % 3 != 1))
                .collect();
            assert_eq!(answers, expected);
        }
    }

    /// Across the sequents, the batch's bound decides how many searches
    /// run at once at the bound of each; within, the one search, or the
    /// race of two that share one account, holds at most all of it.
    #[test]
    fn the_batch_bound_shares_out_the_memory() {
        let options = Options {
            workers: 16,
            total_memory_bytes: Some(5 << 30),
            ..Options::default()
        };
        let search = SearchOptions::default().with_jobs(4);
        let limits = Limits::default().with_memory_bytes(Some(1 << 30));
        let across = options.plan(false, &search, &limits);
        assert_eq!(
            (across.workers, across.limits.memory_bytes),
            (5, Some(1 << 30))
        );
        assert_eq!(across.search.jobs, Jobs::Count(1));
        let within = Options {
            total_memory_bytes: Some(1 << 30),
            ..options.clone()
        }
        .plan(true, &search, &limits);
        assert_eq!(
            (within.workers, within.limits.memory_bytes),
            (1, Some(1 << 30))
        );
        // Without a bound the workers are what was asked, at most as many
        // as the options take.
        let unbounded = options.with_workers(100_000).with_total_memory_bytes(None);
        let plan = unbounded.plan(false, &search, &Limits::UNBOUNDED);
        assert_eq!(plan.workers, SearchOptions::MAX_JOBS);
    }

    /// Cancelled results end the searches in flight and those not begun,
    /// on one worker and on several.
    #[test]
    fn cancelled_results_stop_their_searches() {
        // 2⁴² splits that no count cuts under weakening, which no search
        // gets through.
        let literals: Vec<String> = (0..40).map(|i| format!("x{i}")).collect();
        let text = format!(
            "|- p * q, 0 * (~p par ~p), 0 * (~q par ~q), {}",
            literals.join(", ")
        );
        let sequent: Sequent = text.parse().unwrap();
        for workers in [1, 2] {
            let problems: Vec<Problem> = (0..4)
                .map(|i| Problem::new(i.to_string(), sequent.clone(), None))
                .collect();
            let options = Options::default()
                .with_mode(Mode::CLASSICAL.with_affine())
                .with_workers(workers)
                .with_cores(Cores::Across);
            let results = prove(
                problems,
                &options,
                &SearchOptions::default(),
                &Limits::default(),
            );
            results.cancel();
            for answer in results {
                let verdict = answer.outcome.unwrap().verdict;
                assert!(
                    matches!(verdict, Verdict::Unknown(Reason::Stopped)),
                    "{verdict:?}"
                );
            }
        }
    }

    /// Workers whose stack cannot be had leave the batch to the caller's
    /// thread: a recursion limit read from a file can ask for terabytes of
    /// stack, which must not panic a batch of two workers.
    #[test]
    fn workers_that_cannot_start_leave_the_batch_here() {
        let sequent: Sequent = "|- a, ~a".parse().unwrap();
        let problems: Vec<Problem> = (0..3)
            .map(|i| Problem::new(i.to_string(), sequent.clone(), None))
            .collect();
        let options = Options::default().with_workers(2).with_cores(Cores::Across);
        let limits = Limits::default().with_recursion_depth(u32::MAX);
        for answer in prove(problems, &options, &SearchOptions::default(), &limits) {
            let verdict = answer.outcome.unwrap().verdict;
            assert!(matches!(verdict, Verdict::Proved(_)), "{verdict:?}");
        }
        // Reading ahead takes no more problems than workers can run.
        let options = Options::default()
            .with_workers(usize::MAX)
            .with_cores(Cores::Auto);
        let endless =
            std::iter::repeat_with(move || Problem::new("p".to_owned(), sequent.clone(), None));
        let first = prove(
            endless,
            &options,
            &SearchOptions::default(),
            &Limits::default(),
        )
        .next();
        assert!(matches!(
            first.unwrap().outcome.unwrap().verdict,
            Verdict::Proved(_)
        ));
    }

    /// A client that sends the next problem only once it has the answer
    /// to the last is answered: a worker that waits on the stream holds
    /// the queue, and the iterator gives each answer out without it. And
    /// no worker takes a problem more than its window ahead of the first
    /// answer not yet given out.
    #[cfg(feature = "parallel")]
    #[test]
    fn a_stream_is_answered_question_by_question() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::mpsc::channel;
        let (sender, received) = channel();
        std::thread::spawn(move || {
            let (answered, answers) = channel::<usize>();
            let questions = (0..20usize).inspect(move |&i| {
                if i > 0 {
                    // The answer to the last question first.
                    assert_eq!(answers.recv().unwrap(), i - 1);
                }
            });
            let options = Options::default().with_workers(4).with_cores(Cores::Across);
            let results = run(
                questions,
                &options,
                &SearchOptions::default(),
                &Limits::default(),
                |i, _, _| i,
            );
            for answer in results {
                let _ = answered.send(answer);
            }
            sender.send(()).unwrap();
        });
        assert!(
            received
                .recv_timeout(std::time::Duration::from_secs(20))
                .is_ok()
        );

        let taken = std::sync::Arc::new(AtomicUsize::new(0));
        let counted = taken.clone();
        let problems = (0..1_000usize).inspect(move |_| {
            counted.fetch_add(1, Ordering::Relaxed);
        });
        let options = Options::default().with_workers(2).with_cores(Cores::Across);
        let mut results = run(
            problems,
            &options,
            &SearchOptions::default(),
            &Limits::default(),
            |i, _, _| {
                std::thread::sleep(std::time::Duration::from_millis(1));
                i
            },
        );
        assert_eq!(results.next(), Some(0));
        std::thread::sleep(std::time::Duration::from_millis(50));
        let window = 1 + workers::AHEAD * 2;
        assert!(taken.load(Ordering::Relaxed) <= window, "{taken:?}");
    }

    /// A panic in the work is resumed at its problem's place, after the
    /// results before it, however many problems follow it: the other
    /// workers stop taking problems, so the batch never waits for good.
    #[test]
    fn a_panic_ends_the_batch_at_its_place() {
        let (sender, received) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let options = Options::default().with_workers(2).with_cores(Cores::Across);
            let mut results = run(
                0..100usize,
                &options,
                &SearchOptions::default(),
                &Limits::default(),
                |i, _, _| {
                    assert_ne!(i, 5, "the work panics on problem 5");
                    i
                },
            );
            let before: Vec<usize> = results.by_ref().take(5).collect();
            let panicked =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| results.next())).is_err();
            sender.send((before, panicked)).unwrap();
        });
        let answer = received.recv_timeout(std::time::Duration::from_secs(20));
        assert_eq!(answer, Ok(((0..5).collect(), true)));
    }

    /// A panic of the problems themselves, on a worker, ends the batch at
    /// its place too: the results before it, then the panic. Workers that
    /// went on past it would move the later results up a place.
    #[cfg(feature = "parallel")]
    #[test]
    fn a_panic_of_the_problems_ends_the_batch_at_its_place() {
        let (sender, received) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let options = Options::default().with_workers(2).with_cores(Cores::Across);
            let problems = (0..100usize).inspect(|&i| assert_ne!(i, 5, "the problems panic at 5"));
            let mut results = run(
                problems,
                &options,
                &SearchOptions::default(),
                &Limits::default(),
                |i, _, _| i,
            );
            let before: Vec<usize> = results.by_ref().take(5).collect();
            let panicked =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| results.next())).is_err();
            sender.send((before, panicked)).unwrap();
        });
        let answer = received.recv_timeout(std::time::Duration::from_secs(20));
        assert_eq!(answer, Ok(((0..5).collect(), true)));
    }

    /// Dropping the results ends the batch, however long its queue: the
    /// cancel is raised, so the work in flight stops, the workers end and
    /// let the problems go, and no worker took a problem beyond its window.
    #[cfg(feature = "parallel")]
    #[test]
    fn dropped_results_end_the_batch() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::mpsc::{RecvTimeoutError, channel};
        let taken = Arc::new(AtomicUsize::new(0));
        let counted = taken.clone();
        // Dropped with the problems, when the last worker has ended.
        let (gone, problems_kept) = channel::<()>();
        let problems = (0..1_000usize).inspect(move |_| {
            let _ = &gone;
            counted.fetch_add(1, Ordering::Relaxed);
        });
        let workers = 2;
        let options = Options::default()
            .with_workers(workers)
            .with_cores(Cores::Across);
        let mut results = run(
            problems,
            &options,
            &SearchOptions::default(),
            &Limits::default(),
            |i, _, cancel: &Cancel| {
                // Every problem but the first waits for the cancel.
                while i > 0 && !cancel.is_cancelled() {
                    std::thread::sleep(std::time::Duration::from_millis(1));
                }
                i
            },
        );
        let cancel = results.canceller();
        assert_eq!(results.next(), Some(0));
        drop(results);
        assert!(cancel.is_cancelled());
        assert_eq!(
            problems_kept.recv_timeout(std::time::Duration::from_secs(20)),
            Err(RecvTimeoutError::Disconnected)
        );
        let window = 1 + workers::AHEAD * workers;
        assert!(taken.load(Ordering::Relaxed) <= window, "{taken:?}");
    }
}