Skip to main content

bitwright/prove/
sat.rs

1//! A conflict-driven clause-learning SAT solver: two watched literals with blockers, VSIDS
2//! decisions with phase saving, first-UIP learning with recursive minimization, Luby restarts,
3//! and a learned-clause database reduced by literal block distance. Every learned clause is a
4//! reverse-unit-propagation (RUP) consequence of the clauses before it, so the solver can log
5//! a DRUP proof (additions and deletions) that [`super::drup`] checks independently.
6//!
7//! Written from the published descriptions of these techniques (Marques-Silva and Sakallah's
8//! GRASP learning, Moskewicz et al.'s watched literals and VSIDS, Eén and Sörensson's MiniSat
9//! paper, Audemard and Simon's LBD, Wetzler, Heule and Hunt's DRAT format), not from any
10//! solver's code.
11
12/// A variable, from 0.
13pub type Var = u32;
14
15/// A literal: `2·var` for the positive one, `2·var + 1` for the negative.
16#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Lit(pub u32);
18
19impl Lit {
20    /// The positive literal of `v`.
21    pub fn pos(v: Var) -> Lit {
22        Lit(v << 1)
23    }
24    /// The negative literal of `v`.
25    pub fn neg(v: Var) -> Lit {
26        Lit((v << 1) | 1)
27    }
28    /// `v` if `positive`, else `¬v`.
29    pub fn new(v: Var, positive: bool) -> Lit {
30        Lit((v << 1) | u32::from(!positive))
31    }
32    /// The variable.
33    pub fn var(self) -> Var {
34        self.0 >> 1
35    }
36    /// Whether the literal is negative.
37    pub fn is_neg(self) -> bool {
38        self.0 & 1 == 1
39    }
40    /// DIMACS form: `var + 1`, negated if negative.
41    pub fn dimacs(self) -> i64 {
42        let v = i64::from(self.var()) + 1;
43        if self.is_neg() { -v } else { v }
44    }
45}
46
47impl core::ops::Not for Lit {
48    type Output = Lit;
49    fn not(self) -> Lit {
50        Lit(self.0 ^ 1)
51    }
52}
53
54/// A step of a DRUP proof.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub enum Step {
57    /// A clause added (implied by reverse unit propagation).
58    Add(Vec<Lit>),
59    /// A clause deleted.
60    Delete(Vec<Lit>),
61}
62
63/// The answer of [`Solver::solve`].
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum Answer {
66    /// Satisfiable: the value of every variable.
67    Sat(Vec<bool>),
68    /// Unsatisfiable (with a proof, when logging was on).
69    Unsat,
70    /// A limit was reached: another call goes on from here.
71    Unknown,
72}
73
74/// A SAT search behind a circuit that grows ([`Incremental`](super::Incremental)): bitwright's
75/// own [`Solver`], or another one a host links in (CaDiCaL, through the `bitwright-cadical`
76/// crate). Variables are numbered from 0 in the order they are made. A backend can be sent to
77/// another thread, so that what holds one can.
78pub trait Backend: core::fmt::Debug + Send {
79    /// A new variable.
80    fn new_var(&mut self) -> Var;
81
82    /// Adds a clause.
83    fn add_clause(&mut self, lits: &[Lit]);
84
85    /// Adds a clause, with two of its literals to watch first if the search can use the
86    /// hint. The default ignores it.
87    fn add_clause_watching(&mut self, lits: &[Lit], watches: [Lit; 2]) {
88        let _ = watches;
89        self.add_clause(lits);
90    }
91
92    /// Whether the clauses and `assumptions` hold together, within `limits` of search
93    /// counted from this call (a search that counts otherwise honours them as it can). The
94    /// assumptions are of this call only; what the search learned stays.
95    fn solve_assuming(&mut self, assumptions: &[Lit], limits: Limits) -> Answer;
96
97    /// After `solve_assuming` answered `Unsat`: assumptions of that call that conflict with
98    /// the clauses (none when the clauses alone are contradictory).
99    fn failed_assumptions(&self) -> Vec<Lit>;
100
101    /// Conflicts of every search so far.
102    fn conflicts(&self) -> u64;
103
104    /// Propagations of every search so far (0 from a search that does not count them).
105    fn propagations(&self) -> u64;
106
107    /// Whether [`conflicts`](Self::conflicts) is an exact count of search conflicts (`false`
108    /// for a backend that does not expose its conflict counter).
109    fn exact_conflicts(&self) -> bool {
110        true
111    }
112}
113
114impl Backend for Solver {
115    fn new_var(&mut self) -> Var {
116        Solver::new_var(self)
117    }
118
119    fn add_clause(&mut self, lits: &[Lit]) {
120        Solver::add_clause(self, lits);
121    }
122
123    fn add_clause_watching(&mut self, lits: &[Lit], watches: [Lit; 2]) {
124        Solver::add_clause_watching(self, lits, watches);
125    }
126
127    fn solve_assuming(&mut self, assumptions: &[Lit], limits: Limits) -> Answer {
128        Solver::solve_assuming(self, assumptions, limits)
129    }
130
131    fn failed_assumptions(&self) -> Vec<Lit> {
132        self.failed.clone()
133    }
134
135    fn conflicts(&self) -> u64 {
136        self.conflicts
137    }
138
139    fn propagations(&self) -> u64 {
140        self.propagations
141    }
142}
143
144impl<B: Backend + ?Sized> Backend for Box<B> {
145    fn new_var(&mut self) -> Var {
146        (**self).new_var()
147    }
148
149    fn add_clause(&mut self, lits: &[Lit]) {
150        (**self).add_clause(lits);
151    }
152
153    fn add_clause_watching(&mut self, lits: &[Lit], watches: [Lit; 2]) {
154        (**self).add_clause_watching(lits, watches);
155    }
156
157    fn solve_assuming(&mut self, assumptions: &[Lit], limits: Limits) -> Answer {
158        (**self).solve_assuming(assumptions, limits)
159    }
160
161    fn failed_assumptions(&self) -> Vec<Lit> {
162        (**self).failed_assumptions()
163    }
164
165    fn conflicts(&self) -> u64 {
166        (**self).conflicts()
167    }
168
169    fn propagations(&self) -> u64 {
170        (**self).propagations()
171    }
172
173    fn exact_conflicts(&self) -> bool {
174        (**self).exact_conflicts()
175    }
176}
177
178/// The most work one call of [`Solver::solve_within`] may do, counted from the call's start.
179/// Both counters are deterministic: the same clauses and limits give the same answer.
180#[derive(Copy, Clone, Debug, PartialEq, Eq)]
181pub struct Limits {
182    /// Conflicts.
183    pub conflicts: u64,
184    /// Propagations (literals propagated), which track the time a call takes more closely than
185    /// conflicts do: each conflict costs more propagation on a larger formula.
186    pub propagations: u64,
187}
188
189impl Limits {
190    /// At most `conflicts` conflicts, and any number of propagations.
191    pub fn conflicts(conflicts: u64) -> Limits {
192        Limits {
193            conflicts,
194            propagations: u64::MAX,
195        }
196    }
197}
198
199#[derive(Copy, Clone, PartialEq, Eq, Debug)]
200enum Value {
201    True,
202    False,
203    Unset,
204}
205
206/// A clause: its literals are `arena[start..start + len]`, the two watched ones first.
207#[derive(Copy, Clone)]
208struct Clause {
209    start: u32,
210    len: u32,
211    lbd: u32,
212    activity: f32,
213    learnt: bool,
214    deleted: bool,
215}
216
217#[derive(Copy, Clone)]
218struct Watch {
219    clause: u32,
220    /// A literal of the clause: when it is true, the clause is (for a binary clause, the other
221    /// literal, which the watched one's falsity implies).
222    blocker: Lit,
223}
224
225/// A CDCL solver. Clauses are added, then [`solve`](Self::solve) is called; a call that ends
226/// on its limits keeps the search where it stopped, so the next call goes on from there, and
227/// calls of `a` then `b` conflicts do exactly what one call of `a + b` would. Adding a clause
228/// after a call starts the search again from the top level, keeping what was learned.
229pub struct Solver {
230    clauses: Vec<Clause>,
231    /// Every clause's literals, one after another.
232    arena: Vec<Lit>,
233    /// Reused while normalizing incoming clauses; never retained as a clause's storage.
234    clause_buffer: Vec<Lit>,
235    /// Literals of deleted clauses still in the arena.
236    wasted: usize,
237    /// Clauses of three or more literals, under the negation of each watched literal.
238    watches: Vec<Vec<Watch>>,
239    /// Binary clauses, likewise (the other literal as the blocker).
240    bins: Vec<Vec<Watch>>,
241    values: Vec<Value>,
242    level: Vec<u32>,
243    reason: Vec<Option<u32>>,
244    trail: Vec<Lit>,
245    trail_lim: Vec<usize>,
246    qhead: usize,
247    activity: Vec<f64>,
248    var_inc: f64,
249    cla_inc: f32,
250    heap: Heap,
251    phase: Vec<bool>,
252    seen: Vec<u8>,
253    /// The formula is already contradictory (an empty clause, or a top-level conflict).
254    unsat: bool,
255    /// After [`solve_assuming`](Self::solve_assuming) answered `Unsat`: assumptions that are
256    /// contradictory with the clauses (none when the clauses alone are).
257    failed: Vec<Lit>,
258    proof: Option<Vec<Step>>,
259    /// Restarts so far (the index into the Luby sequence).
260    restarts: u32,
261    /// Conflicts since the last restart.
262    here: u64,
263    /// When to reduce the learned clauses next (in conflicts).
264    next_reduce: u64,
265    /// Learned clauses not deleted.
266    learnts: usize,
267    /// Indices of live learned clauses in `clauses` (so `reduce` and rescaling skip problem CNF).
268    learnt_ids: Vec<u32>,
269    /// Reusable scratch for conflict analysis and LBD stamping.
270    analyze_learnt: Vec<Lit>,
271    analyze_clear: Vec<Lit>,
272    analyze_stack: Vec<Lit>,
273    lbd_seen: Vec<u32>,
274    lbd_stamp: u32,
275    /// Lemmas offered by preprocessing as RUP consequences that unit propagation did not
276    /// confirm, so they were not added.
277    pub(super) rejected_lemmas: u64,
278    /// Clauses learned so far, units included (kept or since deleted).
279    pub lemmas: u64,
280    /// Conflicts so far.
281    pub conflicts: u64,
282    /// Decisions so far.
283    pub decisions: u64,
284    /// Propagations so far.
285    pub propagations: u64,
286}
287
288impl core::fmt::Debug for Solver {
289    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
290        f.debug_struct("Solver")
291            .field("vars", &self.values.len())
292            .field("clauses", &self.clauses.len())
293            .field("conflicts", &self.conflicts)
294            .field("decisions", &self.decisions)
295            .finish()
296    }
297}
298
299impl Default for Solver {
300    fn default() -> Self {
301        Solver::new()
302    }
303}
304
305impl Solver {
306    /// An empty solver.
307    pub fn new() -> Solver {
308        Solver {
309            clauses: Vec::new(),
310            arena: Vec::new(),
311            clause_buffer: Vec::new(),
312            wasted: 0,
313            watches: Vec::new(),
314            bins: Vec::new(),
315            values: Vec::new(),
316            level: Vec::new(),
317            reason: Vec::new(),
318            trail: Vec::new(),
319            trail_lim: Vec::new(),
320            qhead: 0,
321            activity: Vec::new(),
322            var_inc: 1.0,
323            cla_inc: 1.0,
324            heap: Heap::default(),
325            phase: Vec::new(),
326            seen: Vec::new(),
327            unsat: false,
328            failed: Vec::new(),
329            proof: None,
330            restarts: 0,
331            here: 0,
332            next_reduce: 2000,
333            learnts: 0,
334            learnt_ids: Vec::new(),
335            analyze_learnt: Vec::new(),
336            analyze_clear: Vec::new(),
337            analyze_stack: Vec::new(),
338            lbd_seen: Vec::new(),
339            lbd_stamp: 0,
340            rejected_lemmas: 0,
341            lemmas: 0,
342            conflicts: 0,
343            decisions: 0,
344            propagations: 0,
345        }
346    }
347
348    /// Records a DRUP proof of every learned and deleted clause.
349    pub fn log_proof(&mut self) {
350        self.proof = Some(Vec::new());
351    }
352
353    /// The proof logged so far (see [`log_proof`](Self::log_proof)).
354    pub fn take_proof(&mut self) -> Option<Vec<Step>> {
355        self.proof.take()
356    }
357
358    /// The number of variables.
359    pub fn num_vars(&self) -> u32 {
360        self.values.len() as u32
361    }
362
363    /// The number of clauses kept, learned ones included (units are assignments, not
364    /// clauses).
365    pub fn num_clauses(&self) -> usize {
366        self.clauses.iter().filter(|c| !c.deleted).count()
367    }
368
369    /// The number of learned clauses kept.
370    pub fn num_learnts(&self) -> usize {
371        self.learnts
372    }
373
374    /// The number of variables assigned with no decision made: fixed by the clauses and the
375    /// units learned, whatever the search does next.
376    pub fn num_fixed(&self) -> usize {
377        self.trail_lim.first().copied().unwrap_or(self.trail.len())
378    }
379
380    /// A new variable.
381    pub fn new_var(&mut self) -> Var {
382        let v = self.values.len() as u32;
383        self.values.push(Value::Unset);
384        self.level.push(0);
385        self.reason.push(None);
386        self.activity.push(0.0);
387        self.phase.push(false);
388        self.seen.push(0);
389        self.watches.push(Vec::new());
390        self.watches.push(Vec::new());
391        self.bins.push(Vec::new());
392        self.bins.push(Vec::new());
393        self.heap.insert(v, &self.activity);
394        v
395    }
396
397    fn value(&self, l: Lit) -> Value {
398        match self.values[l.var() as usize] {
399            Value::Unset => Value::Unset,
400            v => {
401                if (v == Value::True) != l.is_neg() {
402                    Value::True
403                } else {
404                    Value::False
405                }
406            }
407        }
408    }
409
410    pub(super) fn prefer_selector(&mut self, l: Lit) {
411        self.activity[l.var() as usize] = 0.5;
412        self.phase[l.var() as usize] = l.is_neg();
413        self.heap.decrease(l.var(), &self.activity);
414    }
415
416    fn lits(&self, c: u32) -> &[Lit] {
417        let c = self.clauses[c as usize];
418        &self.arena[c.start as usize..(c.start + c.len) as usize]
419    }
420
421    /// Adds a clause (the search goes back to the top level first). Returns `false` when the
422    /// formula is now known unsatisfiable.
423    pub fn add_clause(&mut self, lits: &[Lit]) -> bool {
424        self.add_incoming_clause(lits, false, None)
425    }
426
427    /// Initial watches for an encoding clause may follow its gate's roles instead of the
428    /// numeric variable order. Normalization and proof premises remain unchanged.
429    pub(super) fn add_clause_watching(&mut self, lits: &[Lit], watches: [Lit; 2]) -> bool {
430        self.add_incoming_clause(lits, false, Some(watches))
431    }
432
433    /// A RUP consequence established by native preprocessing, logged as a proof step rather
434    /// than admitted as an additional premise. Binary consequences are retained glue clauses.
435    /// The claim is checked first, by the solver's own unit propagation: a lemma it does not
436    /// confirm is dropped (and counted), so a mistake in the preprocessing that offers it can
437    /// cost a deduction but never decide a question wrongly, with or without a certificate.
438    pub(super) fn add_rup_clause(&mut self, lits: &[Lit]) -> bool {
439        if self.unsat {
440            return false;
441        }
442        if !self.follows_by_propagation(lits) {
443            self.rejected_lemmas += 1;
444            return !self.unsat;
445        }
446        if self.unsat {
447            return false;
448        }
449        if let Some(proof) = &mut self.proof {
450            proof.push(Step::Add(lits.to_vec()));
451        }
452        self.add_incoming_clause(lits, true, None)
453    }
454
455    /// Whether `lits` follows from the clauses by reverse unit propagation: at the top level,
456    /// with every literal of it false, propagation meets a conflict. (A conflict at the top
457    /// level alone makes the formula unsatisfiable, which is recorded.)
458    fn follows_by_propagation(&mut self, lits: &[Lit]) -> bool {
459        self.cancel_until(0);
460        for &l in lits {
461            while l.var() >= self.num_vars() {
462                self.new_var();
463            }
464        }
465        if self.propagate().is_some() {
466            self.unsat = true;
467            if let Some(p) = &mut self.proof {
468                p.push(Step::Add(Vec::new()));
469            }
470            return true;
471        }
472        if lits.iter().any(|&l| self.value(l) == Value::True) {
473            return true;
474        }
475        let mark = self.trail.len();
476        self.trail_lim.push(mark);
477        let mut conflict = false;
478        for &l in lits {
479            match self.value(l) {
480                Value::Unset => self.assign(!l, None),
481                Value::False => {}
482                // A tautology: its negation is contradictory.
483                Value::True => {
484                    conflict = true;
485                    break;
486                }
487            }
488        }
489        if !conflict {
490            conflict = self.propagate().is_some();
491        }
492        // Undone without a trace: the phases the search saved stay as they were.
493        let saved: Vec<(usize, bool)> = self.trail[mark..]
494            .iter()
495            .map(|l| (l.var() as usize, self.phase[l.var() as usize]))
496            .collect();
497        self.cancel_until(0);
498        for (v, phase) in saved {
499            self.phase[v] = phase;
500        }
501        conflict
502    }
503
504    #[cfg(test)]
505    pub(super) fn proof_steps(&self) -> Option<&[Step]> {
506        self.proof.as_deref()
507    }
508
509    fn add_incoming_clause(
510        &mut self,
511        lits: &[Lit],
512        learnt: bool,
513        watches: Option<[Lit; 2]>,
514    ) -> bool {
515        if self.unsat {
516            return false;
517        }
518        let mut buffer = core::mem::take(&mut self.clause_buffer);
519        buffer.clear();
520        buffer.extend_from_slice(lits);
521        let result = self.add_buffered_clause(&mut buffer, learnt, watches);
522        self.clause_buffer = buffer;
523        result
524    }
525
526    fn add_buffered_clause(
527        &mut self,
528        c: &mut Vec<Lit>,
529        learnt: bool,
530        watches: Option<[Lit; 2]>,
531    ) -> bool {
532        self.cancel_until(0);
533        c.sort_unstable();
534        c.dedup();
535        // A tautology is always true.
536        if c.windows(2).any(|w| w[0].var() == w[1].var()) {
537            return true;
538        }
539        for &l in c.iter() {
540            while l.var() >= self.num_vars() {
541                self.new_var();
542            }
543        }
544        // Literals false at level 0 are dropped (the propagation that made them false is a
545        // RUP step, so the shorter clause is too); a true one satisfies the clause.
546        if c.iter().any(|&l| self.value(l) == Value::True) {
547            return true;
548        }
549        let original_len = c.len();
550        c.retain(|&l| self.value(l) != Value::False);
551        if (c.len() != original_len || original_len == 0)
552            && let Some(p) = &mut self.proof
553        {
554            p.push(Step::Add(c.clone()));
555        }
556        match c.len() {
557            0 => {
558                self.unsat = true;
559                false
560            }
561            1 => {
562                self.assign(c[0], None);
563                if self.propagate().is_some() {
564                    self.unsat = true;
565                    if let Some(p) = &mut self.proof {
566                        p.push(Step::Add(Vec::new()));
567                    }
568                    return false;
569                }
570                true
571            }
572            _ => {
573                if let Some(watches) = watches {
574                    let mut selected = 0;
575                    for wanted in watches {
576                        if let Some(i) = c[selected..].iter().position(|&l| l == wanted) {
577                            c.swap(selected, selected + i);
578                            selected += 1;
579                        }
580                    }
581                }
582                self.attach(c, learnt, if learnt { 2 } else { 0 });
583                true
584            }
585        }
586    }
587
588    fn attach(&mut self, lits: &[Lit], learnt: bool, lbd: u32) -> u32 {
589        let idx = self.clauses.len() as u32;
590        let list = if lits.len() == 2 {
591            &mut self.bins
592        } else {
593            &mut self.watches
594        };
595        list[(!lits[0]).0 as usize].push(Watch {
596            clause: idx,
597            blocker: lits[1],
598        });
599        list[(!lits[1]).0 as usize].push(Watch {
600            clause: idx,
601            blocker: lits[0],
602        });
603        self.clauses.push(Clause {
604            start: self.arena.len() as u32,
605            len: lits.len() as u32,
606            lbd,
607            activity: 0.0,
608            learnt,
609            deleted: false,
610        });
611        self.arena.extend_from_slice(lits);
612        if learnt {
613            self.learnts += 1;
614            self.learnt_ids.push(idx);
615        }
616        idx
617    }
618
619    fn decision_level(&self) -> u32 {
620        self.trail_lim.len() as u32
621    }
622
623    fn assign(&mut self, l: Lit, reason: Option<u32>) {
624        let v = l.var() as usize;
625        self.values[v] = if l.is_neg() {
626            Value::False
627        } else {
628            Value::True
629        };
630        self.level[v] = self.decision_level();
631        self.reason[v] = reason;
632        self.trail.push(l);
633    }
634
635    /// Unit propagation from `qhead`: the conflicting clause, if any.
636    fn propagate(&mut self) -> Option<u32> {
637        self.propagate_until(u64::MAX)
638    }
639
640    /// Complete each literal's watch list before pausing, leaving the remaining trail queued.
641    fn propagate_until(&mut self, stop: u64) -> Option<u32> {
642        while self.qhead < self.trail.len() && self.propagations < stop {
643            let p = self.trail[self.qhead];
644            self.qhead += 1;
645            self.propagations += 1;
646            // Binary clauses with ¬p: the other literal holds.
647            let pi = p.0 as usize;
648            for k in 0..self.bins[pi].len() {
649                let w = self.bins[pi][k];
650                match self.value(w.blocker) {
651                    Value::True => {}
652                    Value::Unset => self.assign(w.blocker, Some(w.clause)),
653                    Value::False => {
654                        self.qhead = self.trail.len();
655                        return Some(w.clause);
656                    }
657                }
658            }
659            // Longer clauses watching ¬p (watched under the literal that became false).
660            let mut ws = core::mem::take(&mut self.watches[pi]);
661            let false_lit = !p;
662            let mut i = 0;
663            let mut j = 0;
664            let mut conflict = None;
665            while i < ws.len() {
666                let w = ws[i];
667                i += 1;
668                if self.value(w.blocker) == Value::True {
669                    ws[j] = w;
670                    j += 1;
671                    continue;
672                }
673                let c = self.clauses[w.clause as usize];
674                if c.deleted {
675                    continue;
676                }
677                let (s, e) = (c.start as usize, (c.start + c.len) as usize);
678                // Make the second literal the false one.
679                if self.arena[s] == false_lit {
680                    self.arena.swap(s, s + 1);
681                }
682                let first = self.arena[s];
683                let kept = Watch {
684                    clause: w.clause,
685                    blocker: first,
686                };
687                if first != w.blocker && self.value(first) == Value::True {
688                    ws[j] = kept;
689                    j += 1;
690                    continue;
691                }
692                // Look for a new literal to watch.
693                let mut found = false;
694                for k in s + 2..e {
695                    let l = self.arena[k];
696                    if self.value(l) != Value::False {
697                        self.arena.swap(s + 1, k);
698                        self.watches[(!l).0 as usize].push(kept);
699                        found = true;
700                        break;
701                    }
702                }
703                if found {
704                    continue;
705                }
706                ws[j] = kept;
707                j += 1;
708                if self.value(first) == Value::False {
709                    conflict = Some(w.clause);
710                    self.qhead = self.trail.len();
711                    while i < ws.len() {
712                        ws[j] = ws[i];
713                        i += 1;
714                        j += 1;
715                    }
716                } else {
717                    self.assign(first, Some(w.clause));
718                }
719            }
720            ws.truncate(j);
721            self.watches[pi] = ws;
722            if conflict.is_some() {
723                return conflict;
724            }
725        }
726        None
727    }
728
729    fn bump_var(&mut self, v: Var) {
730        let a = &mut self.activity[v as usize];
731        *a += self.var_inc;
732        if *a > 1e100 {
733            for x in &mut self.activity {
734                *x *= 1e-100;
735            }
736            self.var_inc *= 1e-100;
737        }
738        self.heap.decrease(v, &self.activity);
739    }
740
741    fn bump_clause(&mut self, c: u32) {
742        let cl = &mut self.clauses[c as usize];
743        cl.activity += self.cla_inc;
744        if cl.activity > 1e20 {
745            for &i in &self.learnt_ids {
746                self.clauses[i as usize].activity *= 1e-20;
747            }
748            self.cla_inc *= 1e-20;
749        }
750    }
751
752    /// Makes `l` the first literal of clause `c` (a reason clause, whose implied literal is
753    /// `l`).
754    fn implied_first(&mut self, c: u32, l: Lit) {
755        let cl = self.clauses[c as usize];
756        let s = cl.start as usize;
757        if self.arena[s] != l {
758            let k = self.arena[s..s + cl.len as usize]
759                .iter()
760                .position(|&x| x == l)
761                .unwrap_or(0);
762            self.arena.swap(s, s + k);
763        }
764    }
765
766    /// First-UIP conflict analysis: the learned clause (asserting literal first), the level to
767    /// go back to, and its literal block distance.
768    fn analyze(&mut self, confl: u32) -> (Vec<Lit>, u32, u32) {
769        let mut learnt = core::mem::take(&mut self.analyze_learnt);
770        learnt.clear();
771        learnt.push(Lit(0));
772        let mut path = 0;
773        let mut p: Option<Lit> = None;
774        let mut idx = self.trail.len();
775        let mut confl = Some(confl);
776        loop {
777            let c = confl.expect("a reason for every implied literal");
778            let cl = self.clauses[c as usize];
779            if cl.learnt {
780                self.bump_clause(c);
781            }
782            // A reason's first literal is the implied one (`p`), skipped.
783            let s = cl.start as usize + usize::from(p.is_some());
784            for k in s..(cl.start + cl.len) as usize {
785                let q = self.arena[k];
786                let v = q.var() as usize;
787                if self.seen[v] == 0 && self.level[v] > 0 {
788                    self.bump_var(q.var());
789                    self.seen[v] = 1;
790                    if self.level[v] >= self.decision_level() {
791                        path += 1;
792                    } else {
793                        learnt.push(q);
794                    }
795                }
796            }
797            // The next literal of the trail marked seen.
798            loop {
799                idx -= 1;
800                if self.seen[self.trail[idx].var() as usize] != 0 {
801                    break;
802                }
803            }
804            let l = self.trail[idx];
805            p = Some(l);
806            confl = self.reason[l.var() as usize];
807            self.seen[l.var() as usize] = 0;
808            path -= 1;
809            if path == 0 {
810                break;
811            }
812            if let Some(c) = confl {
813                self.implied_first(c, l);
814            }
815        }
816        learnt[0] = !p.expect("a UIP");
817        // Recursive minimization: drop literals implied by the others.
818        let abstract_levels = learnt[1..].iter().fold(0u32, |acc, l| {
819            acc | (1 << (self.level[l.var() as usize] & 31))
820        });
821        let mut kept = Vec::with_capacity(learnt.len());
822        kept.push(learnt[0]);
823        let mut to_clear = core::mem::take(&mut self.analyze_clear);
824        to_clear.clear();
825        to_clear.extend_from_slice(&learnt);
826        for &l in &learnt[1..] {
827            if self.reason[l.var() as usize].is_none()
828                || !self.redundant(l, abstract_levels, &mut to_clear)
829            {
830                kept.push(l);
831            }
832        }
833        for &l in &to_clear {
834            self.seen[l.var() as usize] = 0;
835        }
836        self.analyze_learnt = learnt;
837        self.analyze_clear = to_clear;
838        // The backtrack level: the highest level among the rest, that literal second.
839        let mut bt = 0;
840        if kept.len() > 1 {
841            let mut max_i = 1;
842            for i in 2..kept.len() {
843                if self.level[kept[i].var() as usize] > self.level[kept[max_i].var() as usize] {
844                    max_i = i;
845                }
846            }
847            kept.swap(1, max_i);
848            bt = self.level[kept[1].var() as usize];
849        }
850        let need_levels = self.decision_level() as usize + 1;
851        if self.lbd_seen.len() < need_levels {
852            self.lbd_seen.resize(need_levels, 0);
853        }
854        self.lbd_stamp = self.lbd_stamp.wrapping_add(1);
855        if self.lbd_stamp == 0 {
856            self.lbd_seen.fill(0);
857            self.lbd_stamp = 1;
858        }
859        let stamp = self.lbd_stamp;
860        let mut lbd = 0u32;
861        for &l in &kept {
862            let lv = self.level[l.var() as usize] as usize;
863            if self.lbd_seen[lv] != stamp {
864                self.lbd_seen[lv] = stamp;
865                lbd += 1;
866            }
867        }
868        (kept, bt, lbd)
869    }
870
871    /// Whether `l` (in the learned clause) is implied by the clause's other literals, through
872    /// the reasons of the literals it depends on.
873    fn redundant(&mut self, l: Lit, abstract_levels: u32, to_clear: &mut Vec<Lit>) -> bool {
874        let mut stack = core::mem::take(&mut self.analyze_stack);
875        stack.clear();
876        stack.push(l);
877        let top = to_clear.len();
878        while let Some(p) = stack.pop() {
879            let Some(c) = self.reason[p.var() as usize] else {
880                self.analyze_stack = stack;
881                return false;
882            };
883            let cl = self.clauses[c as usize];
884            for k in cl.start as usize..(cl.start + cl.len) as usize {
885                let q = self.arena[k];
886                let v = q.var() as usize;
887                if q.var() == p.var() || self.seen[v] != 0 || self.level[v] == 0 {
888                    continue;
889                }
890                if self.reason[v].is_some() && (abstract_levels >> (self.level[v] & 31)) & 1 == 1 {
891                    self.seen[v] = 1;
892                    stack.push(q);
893                    to_clear.push(q);
894                } else {
895                    for x in to_clear.drain(top..) {
896                        self.seen[x.var() as usize] = 0;
897                    }
898                    self.analyze_stack = stack;
899                    return false;
900                }
901            }
902        }
903        self.analyze_stack = stack;
904        true
905    }
906
907    fn cancel_until(&mut self, level: u32) {
908        if self.decision_level() <= level {
909            return;
910        }
911        let lim = self.trail_lim[level as usize];
912        for i in (lim..self.trail.len()).rev() {
913            let l = self.trail[i];
914            let v = l.var() as usize;
915            self.phase[v] = !l.is_neg();
916            self.values[v] = Value::Unset;
917            self.reason[v] = None;
918            if !self.heap.contains(l.var()) {
919                self.heap.insert(l.var(), &self.activity);
920            }
921        }
922        self.trail.truncate(lim);
923        self.trail_lim.truncate(level as usize);
924        self.qhead = lim;
925    }
926
927    /// The decision levels a restart can keep (van der Tak, Ramos and Heule, "Reusing the
928    /// Assignment Trail in CDCL Solvers", 2011): a prefix whose decisions have no lower
929    /// priority than variables a restart would free. Root assignments remain fixed;
930    /// implications in a discarded suffix become candidates too. Keeping an eligible
931    /// prefix avoids rebuilding its propagated literals, which on a large circuit is most
932    /// of a restart's cost.
933    fn reusable_levels(&mut self) -> u32 {
934        // The next decision: the most active unassigned variable (assigned ones leave the
935        // heap, and come back when unassigned).
936        let next = loop {
937            match self.heap.top() {
938                // Propagation has completed and every variable is assigned: keep the
939                // completed model instead of undoing and rebuilding it at a restart.
940                None => return self.decision_level(),
941                Some(v) if self.values[v as usize] == Value::Unset => break v,
942                Some(_) => {
943                    self.heap.pop(&self.activity);
944                }
945            }
946        };
947        let mut competing = self.activity[next as usize];
948        let mut keep = self.decision_level();
949        let mut end = self.trail.len();
950        // A fresh restart can also choose variables that are currently implied. Build
951        // the maximum priority of the suffix that would become unassigned, excluding
952        // the root assignments and the implications of already retained decisions.
953        for level in (0..self.trail_lim.len()).rev() {
954            let start = self.trail_lim[level];
955            for literal in &self.trail[start..end] {
956                competing = competing.max(self.activity[literal.var() as usize]);
957            }
958            let decision = self.trail[start].var();
959            if self.activity[decision as usize] < competing {
960                keep = level as u32;
961            }
962            end = start;
963        }
964        keep
965    }
966
967    fn pick(&mut self) -> Option<Lit> {
968        while let Some(v) = self.heap.pop(&self.activity) {
969            if self.values[v as usize] == Value::Unset {
970                return Some(Lit::new(v, self.phase[v as usize]));
971            }
972        }
973        None
974    }
975
976    /// Halves the learned clauses, keeping the glue clauses (LBD ≤ 2) and reasons.
977    fn reduce(&mut self) {
978        let mut idx: Vec<u32> = self
979            .learnt_ids
980            .iter()
981            .copied()
982            .filter(|&i| {
983                let c = &self.clauses[i as usize];
984                !c.deleted && c.lbd > 2 && c.len > 2
985            })
986            .collect();
987        idx.sort_by(|&a, &b| {
988            let (ca, cb) = (&self.clauses[a as usize], &self.clauses[b as usize]);
989            cb.lbd.cmp(&ca.lbd).then(
990                ca.activity
991                    .partial_cmp(&cb.activity)
992                    .unwrap_or(core::cmp::Ordering::Equal),
993            )
994        });
995        let locked = |s: &Solver, c: u32| {
996            let l = s.arena[s.clauses[c as usize].start as usize];
997            s.value(l) == Value::True && s.reason[l.var() as usize] == Some(c)
998        };
999        for &c in idx.iter().take(idx.len() / 2) {
1000            if locked(self, c) {
1001                continue;
1002            }
1003            self.clauses[c as usize].deleted = true;
1004            self.learnts -= 1;
1005            self.wasted += self.clauses[c as usize].len as usize;
1006            if self.proof.is_some() {
1007                let lits = self.lits(c).to_vec();
1008                if let Some(p) = &mut self.proof {
1009                    p.push(Step::Delete(lits));
1010                }
1011            }
1012        }
1013        self.learnt_ids
1014            .retain(|&i| !self.clauses[i as usize].deleted);
1015        if self.wasted * 4 > self.arena.len() {
1016            self.collect();
1017        }
1018    }
1019
1020    /// Drops the deleted clauses: the arena is compacted, the clauses renumbered, and every
1021    /// watch and reason follows.
1022    fn collect(&mut self) {
1023        let mut map = vec![u32::MAX; self.clauses.len()];
1024        let mut arena = Vec::with_capacity(self.arena.len() - self.wasted);
1025        let mut kept = 0usize;
1026        for (i, m) in map.iter_mut().enumerate() {
1027            let c = self.clauses[i];
1028            if c.deleted {
1029                continue;
1030            }
1031            *m = kept as u32;
1032            let start = arena.len() as u32;
1033            arena.extend_from_slice(&self.arena[c.start as usize..(c.start + c.len) as usize]);
1034            self.clauses[kept] = Clause { start, ..c };
1035            kept += 1;
1036        }
1037        self.clauses.truncate(kept);
1038        self.arena = arena;
1039        self.wasted = 0;
1040        self.learnt_ids.retain_mut(|i| {
1041            *i = map[*i as usize];
1042            *i != u32::MAX
1043        });
1044        for ws in self.watches.iter_mut().chain(self.bins.iter_mut()) {
1045            ws.retain_mut(|w| {
1046                w.clause = map[w.clause as usize];
1047                w.clause != u32::MAX
1048            });
1049        }
1050        for r in self.reason.iter_mut().flatten() {
1051            *r = map[*r as usize];
1052        }
1053    }
1054
1055    /// Solves within `max_conflicts` conflicts (see [`solve_within`](Self::solve_within)).
1056    pub fn solve(&mut self, max_conflicts: u64) -> Answer {
1057        self.solve_within(Limits::conflicts(max_conflicts))
1058    }
1059
1060    /// Solves within `limits`, counted from this call. On [`Answer::Unknown`] the search stays
1061    /// where it stopped: the next call goes on from there. A zero allowance pauses an
1062    /// undecided search without work; a contradiction already established is still returned.
1063    pub fn solve_within(&mut self, limits: Limits) -> Answer {
1064        if self.unsat {
1065            return Answer::Unsat;
1066        }
1067        if limits.conflicts == 0 || limits.propagations == 0 {
1068            return Answer::Unknown;
1069        }
1070        let (c0, p0) = (self.conflicts, self.propagations);
1071        let propagation_stop = p0.saturating_add(limits.propagations);
1072        loop {
1073            if let Some(confl) = self.propagate_until(propagation_stop) {
1074                if !self.learn(confl) {
1075                    return Answer::Unsat;
1076                }
1077                if self.conflicts - c0 >= limits.conflicts
1078                    || self.propagations - p0 >= limits.propagations
1079                {
1080                    return Answer::Unknown;
1081                }
1082            } else {
1083                if self.propagations - p0 >= limits.propagations {
1084                    return Answer::Unknown;
1085                }
1086                if self.here >= luby(self.restarts) * 100 {
1087                    self.restarts += 1;
1088                    self.here = 0;
1089                    let keep = self.reusable_levels();
1090                    self.cancel_until(keep);
1091                    continue;
1092                }
1093                let Some(d) = self.pick() else {
1094                    let model = self.values.iter().map(|&v| v == Value::True).collect();
1095                    self.cancel_until(0);
1096                    return Answer::Sat(model);
1097                };
1098                self.decisions += 1;
1099                self.trail_lim.push(self.trail.len());
1100                self.assign(d, None);
1101            }
1102        }
1103    }
1104
1105    /// Learns from the conflict `confl`: the first-UIP clause, logged, kept and asserted after
1106    /// backjumping. `false` when the conflict is at the top level: the formula is
1107    /// unsatisfiable, which is recorded.
1108    fn learn(&mut self, confl: u32) -> bool {
1109        self.conflicts += 1;
1110        self.here += 1;
1111        if self.decision_level() == 0 {
1112            self.unsat = true;
1113            if let Some(p) = &mut self.proof {
1114                p.push(Step::Add(Vec::new()));
1115            }
1116            return false;
1117        }
1118        let (learnt, bt, lbd) = self.analyze(confl);
1119        self.lemmas += 1;
1120        self.cancel_until(bt);
1121        if let Some(p) = &mut self.proof {
1122            p.push(Step::Add(learnt.clone()));
1123        }
1124        if learnt.len() == 1 {
1125            self.assign(learnt[0], None);
1126        } else {
1127            let c = self.attach(&learnt, true, lbd);
1128            self.bump_clause(c);
1129            self.assign(learnt[0], Some(c));
1130        }
1131        self.var_inc /= 0.95;
1132        self.cla_inc /= 0.999;
1133        if self.conflicts >= self.next_reduce {
1134            self.next_reduce = self.conflicts + 2000 + 300 * (self.conflicts / 2000);
1135            self.reduce();
1136        }
1137        true
1138    }
1139
1140    /// Solves under `assumptions`, decided first and in order, within `limits` counted from
1141    /// this call. [`Answer::Unsat`] when the clauses and the assumptions together are
1142    /// contradictory; the clauses alone are then still satisfiable unless
1143    /// [`is_unsat`](Self::is_unsat) says so. Assumptions are decisions, so every clause
1144    /// learned on the way follows from the clauses alone: it is logged and kept, and once the
1145    /// answer is `Unsat` the negation of the assumptions follows from them by unit propagation
1146    /// ([`add_rup_clause`](Self::add_rup_clause) accepts it). The search starts at the top
1147    /// level and ends there: unlike [`solve_within`](Self::solve_within), an unfinished call
1148    /// is not resumed.
1149    pub(super) fn solve_assuming(&mut self, assumptions: &[Lit], limits: Limits) -> Answer {
1150        self.failed.clear();
1151        if self.unsat {
1152            return Answer::Unsat;
1153        }
1154        if limits.conflicts == 0 || limits.propagations == 0 {
1155            return Answer::Unknown;
1156        }
1157        for &l in assumptions {
1158            while l.var() >= self.num_vars() {
1159                self.new_var();
1160            }
1161        }
1162        self.cancel_until(0);
1163        let (c0, p0) = (self.conflicts, self.propagations);
1164        let propagation_stop = p0.saturating_add(limits.propagations);
1165        let answer = loop {
1166            if let Some(confl) = self.propagate_until(propagation_stop) {
1167                if !self.learn(confl) {
1168                    break Answer::Unsat;
1169                }
1170                if self.conflicts - c0 >= limits.conflicts
1171                    || self.propagations - p0 >= limits.propagations
1172                {
1173                    break Answer::Unknown;
1174                }
1175                continue;
1176            }
1177            if self.propagations - p0 >= limits.propagations {
1178                break Answer::Unknown;
1179            }
1180            if self.here >= luby(self.restarts) * 100 {
1181                self.restarts += 1;
1182                self.here = 0;
1183                self.cancel_until(0);
1184                continue;
1185            }
1186            let level = self.decision_level() as usize;
1187            let d = if let Some(&a) = assumptions.get(level) {
1188                match self.value(a) {
1189                    // Already true: an empty level keeps levels and assumptions aligned.
1190                    Value::True => {
1191                        self.trail_lim.push(self.trail.len());
1192                        continue;
1193                    }
1194                    // Falsified by the assumptions before it (and the clauses).
1195                    Value::False => {
1196                        self.analyze_final(a);
1197                        break Answer::Unsat;
1198                    }
1199                    Value::Unset => a,
1200                }
1201            } else {
1202                match self.pick() {
1203                    Some(d) => d,
1204                    None => {
1205                        break Answer::Sat(self.values.iter().map(|&v| v == Value::True).collect());
1206                    }
1207                }
1208            };
1209            self.decisions += 1;
1210            self.trail_lim.push(self.trail.len());
1211            self.assign(d, None);
1212        };
1213        self.cancel_until(0);
1214        answer
1215    }
1216
1217    /// `a`, an assumption found false at its turn, and the assumptions decided before it
1218    /// that its falsity follows from: walked back along the reasons from `a`'s variable to
1219    /// the decisions, which under assumptions are assumptions.
1220    fn analyze_final(&mut self, a: Lit) {
1221        self.failed.push(a);
1222        let Some(&start) = self.trail_lim.first() else {
1223            // False at the top level: by the clauses alone, whatever else is assumed.
1224            return;
1225        };
1226        self.seen[a.var() as usize] = 1;
1227        for i in (start..self.trail.len()).rev() {
1228            let l = self.trail[i];
1229            let v = l.var() as usize;
1230            if self.seen[v] == 0 {
1231                continue;
1232            }
1233            self.seen[v] = 0;
1234            match self.reason[v] {
1235                None => {
1236                    if l != a {
1237                        self.failed.push(l);
1238                    }
1239                }
1240                Some(c) => {
1241                    for k in 0..self.lits(c).len() {
1242                        let q = self.lits(c)[k].var() as usize;
1243                        // (Not the implied literal itself: it is done, and a mark left on
1244                        // it would outlive this walk.)
1245                        if q != v && self.level[q] > 0 {
1246                            self.seen[q] = 1;
1247                        }
1248                    }
1249                }
1250            }
1251        }
1252        self.seen[a.var() as usize] = 0;
1253    }
1254
1255    /// Whether the clauses are known to be contradictory.
1256    pub(super) fn is_unsat(&self) -> bool {
1257        self.unsat
1258    }
1259
1260    /// Adds `clauses` proved by another solver over a subset of these clauses (in the same
1261    /// variables): `justification`'s additions, that proof's steps, are logged first. Each of
1262    /// them followed by unit propagation from the other solver's clauses and the additions
1263    /// before it, so it does from this solver's, a superset (its deletions are dropped: a
1264    /// clause kept longer only helps propagation). `false` when the formula is now known
1265    /// unsatisfiable.
1266    pub(super) fn import(&mut self, justification: Vec<Step>, clauses: &[Vec<Lit>]) -> bool {
1267        if let Some(p) = &mut self.proof {
1268            p.extend(
1269                justification
1270                    .into_iter()
1271                    .filter(|s| matches!(s, Step::Add(_))),
1272            );
1273        }
1274        for c in clauses {
1275            for &l in c {
1276                while l.var() >= self.num_vars() {
1277                    self.new_var();
1278                }
1279            }
1280            if !self.add_incoming_clause(c, true, None) {
1281                return false;
1282            }
1283        }
1284        !self.unsat
1285    }
1286}
1287
1288/// The Luby sequence 1, 1, 2, 1, 1, 2, 4, ... (restart `i`'s length in units).
1289fn luby(i: u32) -> u64 {
1290    let mut size = 1u64;
1291    let mut seq = 0u32;
1292    let x = u64::from(i);
1293    while size < x + 1 {
1294        seq += 1;
1295        size = 2 * size + 1;
1296    }
1297    let mut x = x;
1298    while size - 1 != x {
1299        size = (size - 1) >> 1;
1300        seq -= 1;
1301        x %= size;
1302    }
1303    1 << seq
1304}
1305
1306/// A binary max-heap of variables by activity.
1307#[derive(Default)]
1308struct Heap {
1309    heap: Vec<Var>,
1310    index: Vec<i64>,
1311}
1312
1313impl Heap {
1314    fn contains(&self, v: Var) -> bool {
1315        self.index.get(v as usize).is_some_and(|&i| i >= 0)
1316    }
1317
1318    fn insert(&mut self, v: Var, act: &[f64]) {
1319        while self.index.len() <= v as usize {
1320            self.index.push(-1);
1321        }
1322        if self.contains(v) {
1323            return;
1324        }
1325        self.index[v as usize] = self.heap.len() as i64;
1326        self.heap.push(v);
1327        self.up(self.heap.len() - 1, act);
1328    }
1329
1330    fn decrease(&mut self, v: Var, act: &[f64]) {
1331        if let Some(&i) = self.index.get(v as usize)
1332            && i >= 0
1333        {
1334            self.up(i as usize, act);
1335        }
1336    }
1337
1338    fn top(&self) -> Option<Var> {
1339        self.heap.first().copied()
1340    }
1341
1342    fn pop(&mut self, act: &[f64]) -> Option<Var> {
1343        let top = *self.heap.first()?;
1344        let last = self.heap.pop()?;
1345        self.index[top as usize] = -1;
1346        if !self.heap.is_empty() {
1347            self.heap[0] = last;
1348            self.index[last as usize] = 0;
1349            self.down(0, act);
1350        }
1351        Some(top)
1352    }
1353
1354    fn up(&mut self, mut i: usize, act: &[f64]) {
1355        let v = self.heap[i];
1356        while i > 0 {
1357            let parent = (i - 1) / 2;
1358            if act[self.heap[parent] as usize] >= act[v as usize] {
1359                break;
1360            }
1361            self.heap[i] = self.heap[parent];
1362            self.index[self.heap[i] as usize] = i as i64;
1363            i = parent;
1364        }
1365        self.heap[i] = v;
1366        self.index[v as usize] = i as i64;
1367    }
1368
1369    fn down(&mut self, mut i: usize, act: &[f64]) {
1370        let v = self.heap[i];
1371        loop {
1372            let l = 2 * i + 1;
1373            if l >= self.heap.len() {
1374                break;
1375            }
1376            let r = l + 1;
1377            let c =
1378                if r < self.heap.len() && act[self.heap[r] as usize] > act[self.heap[l] as usize] {
1379                    r
1380                } else {
1381                    l
1382                };
1383            if act[self.heap[c] as usize] <= act[v as usize] {
1384                break;
1385            }
1386            self.heap[i] = self.heap[c];
1387            self.index[self.heap[i] as usize] = i as i64;
1388            i = c;
1389        }
1390        self.heap[i] = v;
1391        self.index[v as usize] = i as i64;
1392    }
1393}
1394
1395#[cfg(test)]
1396mod lemma_tests {
1397    use super::*;
1398
1399    #[test]
1400    fn a_lemma_is_added_only_when_propagation_confirms_it() {
1401        let mut s = Solver::new();
1402        s.log_proof();
1403        let (a, b, c) = (s.new_var(), s.new_var(), s.new_var());
1404        // a = b and b = c.
1405        for (x, y) in [(a, b), (b, c)] {
1406            assert!(s.add_clause(&[Lit::neg(x), Lit::pos(y)]));
1407            assert!(s.add_clause(&[Lit::pos(x), Lit::neg(y)]));
1408        }
1409        // a = c follows by unit propagation: kept, and logged as a proof step.
1410        assert!(s.add_rup_clause(&[Lit::neg(a), Lit::pos(c)]));
1411        assert_eq!(s.rejected_lemmas, 0);
1412        let logged = s.proof_steps().unwrap().len();
1413        // a != c does not follow (and is false): dropped, not logged, the formula intact.
1414        assert!(s.add_rup_clause(&[Lit::neg(a), Lit::neg(c)]));
1415        assert_eq!(s.rejected_lemmas, 1);
1416        assert_eq!(s.proof_steps().unwrap().len(), logged);
1417        assert!(s.add_clause(&[Lit::pos(a)]));
1418        assert!(matches!(s.solve(1000), Answer::Sat(_)));
1419    }
1420
1421    #[test]
1422    fn a_tautology_or_a_satisfied_lemma_follows() {
1423        let mut s = Solver::new();
1424        let (a, b) = (s.new_var(), s.new_var());
1425        assert!(s.add_clause(&[Lit::pos(a)]));
1426        assert!(s.add_rup_clause(&[Lit::pos(b), Lit::neg(b)]));
1427        assert!(s.add_rup_clause(&[Lit::pos(a), Lit::pos(b)]));
1428        assert_eq!(s.rejected_lemmas, 0);
1429    }
1430}
1431
1432#[cfg(test)]
1433mod restart_tests {
1434    use super::*;
1435
1436    fn priority(s: &mut Solver, v: Var, value: f64) {
1437        s.activity[v as usize] = value;
1438        s.heap.decrease(v, &s.activity);
1439    }
1440
1441    fn decide(s: &mut Solver, v: Var) {
1442        s.trail_lim.push(s.trail.len());
1443        s.assign(Lit::pos(v), None);
1444        assert!(s.propagate_until(u64::MAX).is_none());
1445    }
1446
1447    #[test]
1448    fn a_higher_priority_implication_prevents_retaining_its_decision() {
1449        let mut s = Solver::new();
1450        let root = s.new_var();
1451        let decision = s.new_var();
1452        let implied = s.new_var();
1453        let unset = s.new_var();
1454        assert!(s.add_clause(&[Lit::pos(root)]));
1455        assert!(s.add_clause(&[Lit::neg(decision), Lit::pos(implied)]));
1456        for (v, p) in [
1457            (root, 1000.0),
1458            (decision, 10.0),
1459            (implied, 20.0),
1460            (unset, 1.0),
1461        ] {
1462            priority(&mut s, v, p);
1463        }
1464        decide(&mut s, decision);
1465        assert_eq!(s.values[implied as usize], Value::True);
1466        let keep = s.reusable_levels();
1467        assert_eq!(keep, 0);
1468        s.cancel_until(keep);
1469        assert_eq!(s.pick().unwrap().var(), implied);
1470        assert_eq!(s.values[root as usize], Value::True);
1471    }
1472
1473    #[test]
1474    fn the_restart_keeps_earlier_levels_but_reconsiders_later_implications() {
1475        let mut s = Solver::new();
1476        let first = s.new_var();
1477        let second = s.new_var();
1478        let implied = s.new_var();
1479        let unset = s.new_var();
1480        assert!(s.add_clause(&[Lit::neg(second), Lit::pos(implied)]));
1481        for (v, p) in [(first, 30.0), (second, 20.0), (implied, 25.0), (unset, 1.0)] {
1482            priority(&mut s, v, p);
1483        }
1484        decide(&mut s, first);
1485        decide(&mut s, second);
1486        let keep = s.reusable_levels();
1487        assert_eq!(keep, 1);
1488        s.cancel_until(keep);
1489        assert_eq!(s.values[first as usize], Value::True);
1490        assert_eq!(s.values[second as usize], Value::Unset);
1491        assert_eq!(s.pick().unwrap().var(), implied);
1492    }
1493
1494    #[test]
1495    fn root_priorities_do_not_force_a_restart_of_reusable_levels() {
1496        let mut s = Solver::new();
1497        let root = s.new_var();
1498        let decision = s.new_var();
1499        let implied = s.new_var();
1500        let unset = s.new_var();
1501        assert!(s.add_clause(&[Lit::pos(root)]));
1502        assert!(s.add_clause(&[Lit::neg(decision), Lit::pos(implied)]));
1503        for (v, p) in [
1504            (root, 1000.0),
1505            (decision, 20.0),
1506            (implied, 10.0),
1507            (unset, 1.0),
1508        ] {
1509            priority(&mut s, v, p);
1510        }
1511        decide(&mut s, decision);
1512        assert_eq!(s.reusable_levels(), 1);
1513    }
1514
1515    #[test]
1516    fn a_completed_model_is_returned_without_rebuilding_its_trail() {
1517        let mut s = Solver::new();
1518        let decision = s.new_var();
1519        let implied = s.new_var();
1520        assert!(s.add_clause(&[Lit::neg(decision), Lit::pos(implied)]));
1521        decide(&mut s, decision);
1522        s.here = 100;
1523        assert_eq!(s.reusable_levels(), 1);
1524        let before = s.decisions;
1525        assert_eq!(s.solve(1), Answer::Sat(vec![true, true]));
1526        assert_eq!(s.decisions, before);
1527    }
1528}