Skip to main content

elinvar_engine/
sat.rs

1//! The solver trait and Elinvar's own conflict-driven solver (LOGIC.md
2//! section 12.8, DESIGN.md section 7.4).
3//!
4//! The solver follows the shape of MiniSat: two watched literals per
5//! clause, learning from the first unique implication point, variable
6//! activity, phase saving, and Luby restarts. It is deterministic: ties in
7//! activity go to the lower variable, the first value tried is false, and
8//! nothing is random. Time is read only to stop when a time budget runs out
9//! (AGENTS.md law 17).
10
11use std::time::{Duration, Instant};
12
13/// A variable of the solver, numbered from 0.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct Var(pub u32);
16
17/// A variable or its negation.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct Lit(u32);
20
21impl Lit {
22    /// The variable, true.
23    pub fn positive(v: Var) -> Lit {
24        Lit(v.0 * 2)
25    }
26
27    /// The variable, false.
28    pub fn negative(v: Var) -> Lit {
29        Lit(v.0 * 2 + 1)
30    }
31
32    /// `positive(v)` if `value`, else `negative(v)`.
33    pub fn new(v: Var, value: bool) -> Lit {
34        if value {
35            Lit::positive(v)
36        } else {
37            Lit::negative(v)
38        }
39    }
40
41    /// The variable.
42    pub fn var(self) -> Var {
43        Var(self.0 / 2)
44    }
45
46    /// Whether this is the negation of the variable.
47    pub fn is_negative(self) -> bool {
48        self.0 & 1 == 1
49    }
50
51    fn index(self) -> usize {
52        self.0 as usize
53    }
54}
55
56impl std::ops::Not for Lit {
57    type Output = Lit;
58    fn not(self) -> Lit {
59        Lit(self.0 ^ 1)
60    }
61}
62
63/// The result of a solve.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum Solved {
66    /// The clauses and the assumptions have a model.
67    Sat,
68    /// They have none.
69    Unsat,
70    /// The budget ran out first.
71    Unknown,
72}
73
74/// Which limit of a [`Budget`] ended a solve as [`Solved::Unknown`] (N26).
75#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
76#[serde(rename_all = "snake_case")]
77#[non_exhaustive]
78pub enum BudgetExhausted {
79    /// The conflict limit was reached.
80    Conflicts,
81    /// The wall-clock time limit was reached.
82    Time,
83}
84
85/// How much a solve may spend. `None` means no limit of that kind.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
87#[non_exhaustive]
88pub struct Budget {
89    /// The number of conflicts.
90    pub conflicts: Option<u64>,
91    /// Wall-clock time. Running out can only turn an answer into unknown.
92    pub time: Option<Duration>,
93}
94
95impl Budget {
96    /// No limit.
97    pub fn unlimited() -> Budget {
98        Budget::default()
99    }
100
101    /// A limit on conflicts.
102    pub fn conflicts(n: u64) -> Budget {
103        Budget {
104            conflicts: Some(n),
105            time: None,
106        }
107    }
108
109    /// The same budget with a time limit too.
110    #[must_use]
111    pub fn with_time(mut self, time: Duration) -> Budget {
112        self.time = Some(time);
113        self
114    }
115}
116
117/// A SAT solver: the one public trait without two implementations, because
118/// R9 asks for it (AGENTS.md law 25).
119///
120/// ```
121/// use elinvar_engine::sat::{Budget, Cdcl, Lit, Solved, Solver};
122///
123/// let mut solver = Cdcl::new();
124/// let a = solver.new_var();
125/// let b = solver.new_var();
126/// solver.add_clause(&[Lit::positive(a), Lit::positive(b)]);
127/// solver.add_clause(&[Lit::negative(a)]);
128/// assert_eq!(solver.solve(&[], &Budget::conflicts(100)), Solved::Sat);
129/// assert!(!solver.value(a));
130/// assert!(solver.value(b));
131/// ```
132pub trait Solver {
133    /// A new variable.
134    fn new_var(&mut self) -> Var;
135    /// Adds a clause: at least one of its literals is true.
136    fn add_clause(&mut self, clause: &[Lit]);
137    /// Solves under assumptions. `Unknown` when the budget runs out.
138    fn solve(&mut self, assumptions: &[Lit], budget: &Budget) -> Solved;
139    /// The value of a variable in the model, after `Solved::Sat`.
140    fn value(&self, var: Var) -> bool;
141    /// Total conflicts spent by this solver, for statistics. Returns `0`
142    /// when a solver does not report conflict counts.
143    fn conflicts(&self) -> u64 {
144        0
145    }
146    /// After `Solved::Unsat`, a subset of the assumptions passed to `solve`
147    /// whose conjunction with the clauses is unsatisfiable. Returns an empty
148    /// vector when the clauses alone are unsatisfiable or when a solver does
149    /// not extract cores.
150    fn unsat_core(&self) -> Vec<Lit> {
151        Vec::new()
152    }
153    /// After `Solved::Unknown`, which limit of the [`Budget`] ended the search,
154    /// if the solver tracks it (N26).
155    fn unknown_reason(&self) -> Option<BudgetExhausted> {
156        None
157    }
158}
159
160const TRUE: u8 = 1;
161const FALSE: u8 = 0;
162const UNDEF: u8 = 2;
163
164/// Clauses live one after another in one arena, as in MiniSat, so that
165/// visiting one reads one place in memory: at a clause's offset its length,
166/// then its LBD shifted left by one with whether it is learnt in the low
167/// bit, then its literals. A learnt clause's LBD is the number of distinct
168/// decision levels among its literals when it was learnt; lower is more
169/// useful.
170const HEADER: usize = 2;
171
172/// A clause watching a literal, with another of its literals: when that
173/// one is true the clause is satisfied and need not be visited.
174#[derive(Clone, Copy)]
175struct Watcher {
176    cref: usize,
177    blocker: Lit,
178    /// A clause of two literals: the blocker is the other one, so the
179    /// clause itself is read only when it propagates.
180    binary: bool,
181}
182
183fn value_of(values: &[u8], l: Lit) -> u8 {
184    let v = values[l.var().0 as usize];
185    if v == UNDEF {
186        UNDEF
187    } else {
188        v ^ (l.is_negative() as u8)
189    }
190}
191
192enum Search {
193    Sat,
194    Unsat,
195    Unknown,
196    Restart,
197}
198
199/// Elinvar's own conflict-driven solver.
200pub struct Cdcl {
201    ok: bool,
202    arena: Vec<Lit>,
203    /// The number of clauses in the arena.
204    clause_count: usize,
205    learnts: usize,
206    max_learnts: f64,
207    /// Buffers reused by clause minimization.
208    stack: Vec<Lit>,
209    to_clear: Vec<Lit>,
210    /// For each literal, the clauses watching it: visited when it becomes
211    /// false.
212    watches: Vec<Vec<Watcher>>,
213    values: Vec<u8>,
214    level: Vec<u32>,
215    reason: Vec<Option<usize>>,
216    phase: Vec<bool>,
217    activity: Vec<f64>,
218    var_inc: f64,
219    heap: Heap,
220    trail: Vec<Lit>,
221    trail_lim: Vec<usize>,
222    qhead: usize,
223    seen: Vec<bool>,
224    /// Reusable stamp table for computing learnt-clause LBD without allocating.
225    lbd_mark: Vec<u32>,
226    lbd_stamp: u32,
227    model: Vec<bool>,
228    /// Subset of the last solve's assumptions that derived `Unsat`.
229    conflict: Vec<Lit>,
230    restarts: u32,
231    /// Which limit stopped the last solve when it returned `Solved::Unknown`.
232    last_unknown: Option<BudgetExhausted>,
233    /// Conflicts over the solver's life, for statistics.
234    pub total_conflicts: u64,
235}
236
237impl Default for Cdcl {
238    fn default() -> Cdcl {
239        Cdcl::new()
240    }
241}
242
243impl Cdcl {
244    /// An empty solver.
245    pub fn new() -> Cdcl {
246        Cdcl {
247            ok: true,
248            arena: Vec::new(),
249            clause_count: 0,
250            learnts: 0,
251            max_learnts: 0.0,
252            stack: Vec::new(),
253            to_clear: Vec::new(),
254            watches: Vec::new(),
255            values: Vec::new(),
256            level: Vec::new(),
257            reason: Vec::new(),
258            phase: Vec::new(),
259            activity: Vec::new(),
260            var_inc: 1.0,
261            heap: Heap::default(),
262            trail: Vec::new(),
263            trail_lim: Vec::new(),
264            qhead: 0,
265            seen: Vec::new(),
266            lbd_mark: Vec::new(),
267            lbd_stamp: 0,
268            model: Vec::new(),
269            conflict: Vec::new(),
270            restarts: 0,
271            last_unknown: None,
272            total_conflicts: 0,
273        }
274    }
275
276    /// The number of variables.
277    pub fn num_vars(&self) -> usize {
278        self.values.len()
279    }
280
281    fn lit_value(&self, l: Lit) -> u8 {
282        value_of(&self.values, l)
283    }
284
285    fn decision_level(&self) -> usize {
286        self.trail_lim.len()
287    }
288
289    fn enqueue(&mut self, l: Lit, reason: Option<usize>) {
290        let v = l.var().0 as usize;
291        debug_assert_eq!(self.values[v], UNDEF);
292        self.values[v] = if l.is_negative() { FALSE } else { TRUE };
293        self.level[v] = self.decision_level() as u32;
294        self.reason[v] = reason;
295        self.trail.push(l);
296    }
297
298    fn cancel_until(&mut self, level: usize) {
299        if self.decision_level() <= level {
300            return;
301        }
302        let start = self.trail_lim[level];
303        for i in (start..self.trail.len()).rev() {
304            let l = self.trail[i];
305            let v = l.var().0 as usize;
306            self.phase[v] = !l.is_negative();
307            self.values[v] = UNDEF;
308            self.reason[v] = None;
309            self.heap.insert(v as u32, &self.activity);
310        }
311        self.trail.truncate(start);
312        self.trail_lim.truncate(level);
313        self.qhead = self.qhead.min(start);
314    }
315
316    /// Puts a clause in the arena; its offset.
317    fn push_clause(&mut self, lits: &[Lit], learnt: bool, lbd: u32) -> usize {
318        let cref = self.arena.len();
319        self.arena.push(Lit(lits.len() as u32));
320        self.arena.push(Lit(lbd << 1 | u32::from(learnt)));
321        self.arena.extend_from_slice(lits);
322        self.clause_count += 1;
323        cref
324    }
325
326    fn clause_len(&self, cref: usize) -> usize {
327        self.arena[cref].0 as usize
328    }
329
330    fn lits(&self, cref: usize) -> &[Lit] {
331        &self.arena[cref + HEADER..cref + HEADER + self.clause_len(cref)]
332    }
333
334    fn attach(&mut self, cref: usize) {
335        let c = self.lits(cref);
336        let (a, b) = (c[0], c[1]);
337        let binary = c.len() == 2;
338        self.watches[a.index()].push(Watcher {
339            cref,
340            blocker: b,
341            binary,
342        });
343        self.watches[b.index()].push(Watcher {
344            cref,
345            blocker: a,
346            binary,
347        });
348    }
349
350    /// Unit propagation. Returns a conflicting clause, if any.
351    fn propagate(&mut self) -> Option<usize> {
352        while self.qhead < self.trail.len() {
353            let p = self.trail[self.qhead];
354            self.qhead += 1;
355            let false_lit = !p;
356            let mut ws = std::mem::take(&mut self.watches[false_lit.index()]);
357            let (mut i, mut j) = (0, 0);
358            let mut conflict = None;
359            while i < ws.len() {
360                let w = ws[i];
361                i += 1;
362                let blocker = value_of(&self.values, w.blocker);
363                if blocker == TRUE {
364                    ws[j] = w;
365                    j += 1;
366                    continue;
367                }
368                if w.binary {
369                    ws[j] = w;
370                    j += 1;
371                    if blocker == FALSE {
372                        conflict = Some(w.cref);
373                        while i < ws.len() {
374                            ws[j] = ws[i];
375                            j += 1;
376                            i += 1;
377                        }
378                    } else {
379                        // Analysis reads a reason's implied literal first.
380                        let lits = &mut self.arena[w.cref + HEADER..w.cref + HEADER + 2];
381                        if lits[0] != w.blocker {
382                            lits.swap(0, 1);
383                        }
384                        self.enqueue(w.blocker, Some(w.cref));
385                    }
386                    continue;
387                }
388                let len = self.arena[w.cref].0 as usize;
389                let lits = &mut self.arena[w.cref + HEADER..w.cref + HEADER + len];
390                if lits[0] == false_lit {
391                    lits.swap(0, 1);
392                }
393                let first = lits[0];
394                let kept = Watcher {
395                    cref: w.cref,
396                    blocker: first,
397                    binary: false,
398                };
399                if first != w.blocker && value_of(&self.values, first) == TRUE {
400                    ws[j] = kept;
401                    j += 1;
402                    continue;
403                }
404                let mut moved = false;
405                for k in 2..lits.len() {
406                    if value_of(&self.values, lits[k]) != FALSE {
407                        lits.swap(1, k);
408                        self.watches[lits[1].index()].push(kept);
409                        moved = true;
410                        break;
411                    }
412                }
413                if moved {
414                    continue;
415                }
416                ws[j] = kept;
417                j += 1;
418                if value_of(&self.values, first) == FALSE {
419                    conflict = Some(w.cref);
420                    while i < ws.len() {
421                        ws[j] = ws[i];
422                        j += 1;
423                        i += 1;
424                    }
425                } else {
426                    self.enqueue(first, Some(w.cref));
427                }
428            }
429            ws.truncate(j);
430            self.watches[false_lit.index()] = ws;
431            if conflict.is_some() {
432                self.qhead = self.trail.len();
433                return conflict;
434            }
435        }
436        None
437    }
438
439    fn bump(&mut self, v: usize) {
440        self.activity[v] += self.var_inc;
441        if self.activity[v] > 1e100 {
442            for a in &mut self.activity {
443                *a *= 1e-100;
444            }
445            self.var_inc *= 1e-100;
446        }
447        self.heap.increased(v as u32, &self.activity);
448    }
449
450    /// First-UIP conflict analysis. Returns the learnt clause, its
451    /// asserting literal first, and the level to go back to.
452    fn analyze(&mut self, mut confl: usize) -> (Vec<Lit>, usize) {
453        let mut learnt = vec![Lit(0)];
454        let mut path = 0usize;
455        let mut p: Option<Lit> = None;
456        let mut index = self.trail.len();
457        loop {
458            let start = usize::from(p.is_some());
459            for k in start..self.clause_len(confl) {
460                let q = self.arena[confl + HEADER + k];
461                let v = q.var().0 as usize;
462                if !self.seen[v] && self.level[v] > 0 {
463                    self.bump(v);
464                    self.seen[v] = true;
465                    if self.level[v] as usize >= self.decision_level() {
466                        path += 1;
467                    } else {
468                        learnt.push(q);
469                    }
470                }
471            }
472            loop {
473                index -= 1;
474                if self.seen[self.trail[index].var().0 as usize] {
475                    break;
476                }
477            }
478            let l = self.trail[index];
479            let v = l.var().0 as usize;
480            self.seen[v] = false;
481            path -= 1;
482            p = Some(l);
483            if path == 0 {
484                break;
485            }
486            confl = self.reason[v]
487                .expect("a literal at the conflict level with a seen successor has a reason");
488        }
489        learnt[0] = !p.expect("analysis visits at least one literal");
490        self.minimize(&mut learnt);
491        let mut back = 0;
492        if learnt.len() > 1 {
493            let mut max_i = 1;
494            for i in 2..learnt.len() {
495                if self.level[learnt[i].var().0 as usize]
496                    > self.level[learnt[max_i].var().0 as usize]
497                {
498                    max_i = i;
499                }
500            }
501            learnt.swap(1, max_i);
502            back = self.level[learnt[1].var().0 as usize] as usize;
503        }
504        (learnt, back)
505    }
506
507    fn abstract_level(&self, v: usize) -> u32 {
508        1 << (self.level[v] & 31)
509    }
510
511    /// Recursive minimization, as MiniSat does it: drops each literal of the
512    /// learnt clause that the others imply through reasons. Clears `seen`.
513    fn minimize(&mut self, learnt: &mut Vec<Lit>) {
514        let mut levels = 0u32;
515        for l in &learnt[1..] {
516            levels |= self.abstract_level(l.var().0 as usize);
517        }
518        let mut to_clear = std::mem::take(&mut self.to_clear);
519        to_clear.clear();
520        to_clear.extend_from_slice(learnt);
521        let mut j = 1;
522        for i in 1..learnt.len() {
523            let l = learnt[i];
524            let v = l.var().0 as usize;
525            if self.reason[v].is_none() || !self.redundant(l, levels, &mut to_clear) {
526                learnt[j] = l;
527                j += 1;
528            }
529        }
530        learnt.truncate(j);
531        for l in &to_clear {
532            self.seen[l.var().0 as usize] = false;
533        }
534        self.to_clear = to_clear;
535    }
536
537    fn redundant(&mut self, p: Lit, levels: u32, to_clear: &mut Vec<Lit>) -> bool {
538        let mut stack = std::mem::take(&mut self.stack);
539        stack.clear();
540        stack.push(p);
541        let top = to_clear.len();
542        while let Some(q) = stack.pop() {
543            let c =
544                self.reason[q.var().0 as usize].expect("only literals with a reason are pushed");
545            for k in 1..self.clause_len(c) {
546                let l = self.arena[c + HEADER + k];
547                let v = l.var().0 as usize;
548                if !self.seen[v] && self.level[v] > 0 {
549                    if self.reason[v].is_some() && self.abstract_level(v) & levels != 0 {
550                        self.seen[v] = true;
551                        stack.push(l);
552                        to_clear.push(l);
553                    } else {
554                        for t in &to_clear[top..] {
555                            self.seen[t.var().0 as usize] = false;
556                        }
557                        to_clear.truncate(top);
558                        self.stack = stack;
559                        return false;
560                    }
561                }
562            }
563        }
564        self.stack = stack;
565        true
566    }
567
568    fn pick_branch(&mut self) -> Option<Lit> {
569        while let Some(v) = self.heap.pop(&self.activity) {
570            if self.values[v as usize] == UNDEF {
571                return Some(Lit::new(Var(v), self.phase[v as usize]));
572            }
573        }
574        None
575    }
576
577    /// Drops half the learnt clauses with an LBD above 2, worst LBD first,
578    /// then longest, then oldest, at level 0.
579    fn reduce(&mut self) {
580        debug_assert_eq!(self.decision_level(), 0);
581        // Offsets grow with age, so ordering by offset is oldest first.
582        let mut learnt: Vec<(u32, usize, usize)> = Vec::new();
583        let mut c = 0;
584        while c < self.arena.len() {
585            let (len, flags) = (self.clause_len(c), self.arena[c + 1].0);
586            if flags & 1 == 1 && len > 2 && flags >> 1 > 2 {
587                learnt.push((flags >> 1, len, c));
588            }
589            c += HEADER + len;
590        }
591        learnt.sort_unstable();
592        let drop: std::collections::BTreeSet<usize> = learnt[learnt.len() / 2..]
593            .iter()
594            .map(|&(_, _, c)| c)
595            .collect();
596        let old = std::mem::take(&mut self.arena);
597        self.arena = Vec::with_capacity(old.len());
598        self.clause_count = 0;
599        let mut c = 0;
600        while c < old.len() {
601            let len = old[c].0 as usize;
602            if !drop.contains(&c) {
603                self.arena.extend_from_slice(&old[c..c + HEADER + len]);
604                self.clause_count += 1;
605            }
606            c += HEADER + len;
607        }
608        self.learnts -= drop.len();
609        for w in &mut self.watches {
610            w.clear();
611        }
612        self.reason.fill(None);
613        let mut c = 0;
614        while c < self.arena.len() {
615            self.attach(c);
616            c += HEADER + self.clause_len(c);
617        }
618        // A watch rebuilt on a literal already false at level 0 is only
619        // safe once that literal is propagated again.
620        self.qhead = 0;
621    }
622
623    fn compute_lbd(&mut self, lits: &[Lit]) -> u32 {
624        self.lbd_stamp = self.lbd_stamp.wrapping_add(1);
625        if self.lbd_stamp == 0 {
626            self.lbd_mark.fill(0);
627            self.lbd_stamp = 1;
628        }
629        let stamp = self.lbd_stamp;
630        let mut count = 0u32;
631        for &l in lits {
632            let lvl = self.level[l.var().0 as usize] as usize;
633            if lvl >= self.lbd_mark.len() {
634                self.lbd_mark.resize(lvl + 1, 0);
635            }
636            if self.lbd_mark[lvl] != stamp {
637                self.lbd_mark[lvl] = stamp;
638                count += 1;
639            }
640        }
641        count
642    }
643
644    /// Traces a falsified assumption `a` (where `!a` is currently true on the
645    /// trail) back through the implication graph to the subset of `assumptions`
646    /// that implied `!a`.
647    fn analyze_final(&mut self, a: Lit, assumptions: &[Lit]) {
648        self.conflict.clear();
649        let mut core = vec![a];
650        if self.decision_level() == 0 {
651            self.conflict = core;
652            return;
653        }
654        let p = !a;
655        let pv = p.var().0 as usize;
656        if self.level[pv] > 0 {
657            self.seen[pv] = true;
658            let mut marked = vec![pv];
659            let stop = self.trail_lim[0];
660            for i in (stop..self.trail.len()).rev() {
661                let lit = self.trail[i];
662                let x = lit.var().0 as usize;
663                if !self.seen[x] {
664                    continue;
665                }
666                match self.reason[x] {
667                    None => core.push(lit),
668                    Some(cref) => {
669                        let start = cref + HEADER;
670                        let end = start + self.clause_len(cref);
671                        for j in start..end {
672                            let q = self.arena[j];
673                            let qv = q.var().0 as usize;
674                            if qv != x && self.level[qv] > 0 && !self.seen[qv] {
675                                self.seen[qv] = true;
676                                marked.push(qv);
677                            }
678                        }
679                    }
680                }
681            }
682            for v in marked {
683                self.seen[v] = false;
684            }
685        }
686        // Keep assumption order and drop duplicates: each core literal is
687        // taken once, by its first assumption.
688        let mut core: std::collections::BTreeSet<Lit> = core.into_iter().collect();
689        for &assump in assumptions {
690            if core.remove(&assump) {
691                self.conflict.push(assump);
692            }
693        }
694    }
695
696    fn search(
697        &mut self,
698        limit: u64,
699        assumptions: &[Lit],
700        budget: &Budget,
701        spent: &mut u64,
702        start: Instant,
703    ) -> Search {
704        if budget.time.is_some_and(|t| start.elapsed() >= t) {
705            self.last_unknown = Some(BudgetExhausted::Time);
706            return Search::Unknown;
707        }
708        let mut conflicts = 0u64;
709        loop {
710            if let Some(confl) = self.propagate() {
711                conflicts += 1;
712                *spent += 1;
713                self.total_conflicts += 1;
714                if self.decision_level() == 0 {
715                    self.ok = false;
716                    self.conflict.clear();
717                    return Search::Unsat;
718                }
719                let (learnt, back) = self.analyze(confl);
720                self.cancel_until(back);
721                if learnt.len() == 1 {
722                    self.enqueue(learnt[0], None);
723                } else {
724                    let first = learnt[0];
725                    let lbd = self.compute_lbd(&learnt);
726                    let cref = self.push_clause(&learnt, true, lbd);
727                    self.learnts += 1;
728                    self.attach(cref);
729                    self.enqueue(first, Some(cref));
730                }
731                self.var_inc /= 0.95;
732                if budget.conflicts.is_some_and(|c| *spent >= c) {
733                    self.last_unknown = Some(BudgetExhausted::Conflicts);
734                    return Search::Unknown;
735                }
736                if budget
737                    .time
738                    .is_some_and(|t| (*spent & 15) == 0 && start.elapsed() >= t)
739                {
740                    self.last_unknown = Some(BudgetExhausted::Time);
741                    return Search::Unknown;
742                }
743            } else {
744                if conflicts >= limit {
745                    self.cancel_until(0);
746                    return Search::Restart;
747                }
748                let mut next = None;
749                while self.decision_level() < assumptions.len() {
750                    let a = assumptions[self.decision_level()];
751                    match self.lit_value(a) {
752                        TRUE => self.trail_lim.push(self.trail.len()),
753                        FALSE => {
754                            self.analyze_final(a, assumptions);
755                            return Search::Unsat;
756                        }
757                        _ => {
758                            next = Some(a);
759                            break;
760                        }
761                    }
762                }
763                let next = match next {
764                    Some(a) => a,
765                    None => match self.pick_branch() {
766                        Some(l) => l,
767                        None => return Search::Sat,
768                    },
769                };
770                self.trail_lim.push(self.trail.len());
771                self.enqueue(next, None);
772            }
773        }
774    }
775}
776
777/// The Luby sequence 1, 1, 2, 1, 1, 2, 4, ...: element `x`, from 0.
778fn luby(mut x: u32) -> u64 {
779    let mut size = 1u64;
780    let mut seq = 0u32;
781    while size < u64::from(x) + 1 {
782        seq += 1;
783        size = 2 * size + 1;
784    }
785    while size - 1 != u64::from(x) {
786        size = (size - 1) >> 1;
787        seq -= 1;
788        x %= size as u32;
789    }
790    1u64 << seq
791}
792
793impl Solver for Cdcl {
794    fn new_var(&mut self) -> Var {
795        let v = self.values.len() as u32;
796        self.values.push(UNDEF);
797        self.level.push(0);
798        self.reason.push(None);
799        self.phase.push(false);
800        self.activity.push(0.0);
801        self.seen.push(false);
802        self.watches.push(Vec::new());
803        self.watches.push(Vec::new());
804        self.heap.insert(v, &self.activity);
805        Var(v)
806    }
807
808    fn add_clause(&mut self, clause: &[Lit]) {
809        if !self.ok {
810            return;
811        }
812        self.cancel_until(0);
813        let mut lits = clause.to_vec();
814        lits.sort_unstable();
815        lits.dedup();
816        let mut kept = Vec::with_capacity(lits.len());
817        for (i, &l) in lits.iter().enumerate() {
818            if i + 1 < lits.len() && lits[i + 1] == !l {
819                return; // a tautology: l and not l, adjacent after sorting
820            }
821            match self.lit_value(l) {
822                TRUE => return,
823                FALSE => {}
824                _ => kept.push(l),
825            }
826        }
827        match kept.len() {
828            0 => self.ok = false,
829            1 => {
830                self.enqueue(kept[0], None);
831                if self.propagate().is_some() {
832                    self.ok = false;
833                }
834            }
835            _ => {
836                let cref = self.push_clause(&kept, false, 0);
837                self.attach(cref);
838            }
839        }
840    }
841
842    fn solve(&mut self, assumptions: &[Lit], budget: &Budget) -> Solved {
843        self.model.clear();
844        self.conflict.clear();
845        self.last_unknown = None;
846        if !self.ok {
847            return Solved::Unsat;
848        }
849        if budget.time.is_some_and(|t| t.is_zero()) {
850            self.last_unknown = Some(BudgetExhausted::Time);
851            return Solved::Unknown;
852        }
853        self.cancel_until(0);
854        let start = Instant::now();
855        if self.max_learnts == 0.0 {
856            self.max_learnts = (self.clause_count as f64 / 3.0).max(1000.0);
857        }
858        let mut spent = 0u64;
859        let result = loop {
860            let limit = luby(self.restarts) * 100;
861            match self.search(limit, assumptions, budget, &mut spent, start) {
862                Search::Sat => {
863                    self.model = self.values.iter().map(|&v| v == TRUE).collect();
864                    break Solved::Sat;
865                }
866                Search::Unsat => break Solved::Unsat,
867                Search::Unknown => break Solved::Unknown,
868                Search::Restart => {
869                    self.restarts += 1;
870                    if self.learnts as f64 > self.max_learnts {
871                        self.reduce();
872                        self.max_learnts *= 1.1;
873                    }
874                }
875            }
876        };
877        self.cancel_until(0);
878        result
879    }
880
881    fn value(&self, var: Var) -> bool {
882        self.model.get(var.0 as usize).copied().unwrap_or(false)
883    }
884
885    fn conflicts(&self) -> u64 {
886        self.total_conflicts
887    }
888
889    fn unsat_core(&self) -> Vec<Lit> {
890        self.conflict.clone()
891    }
892
893    fn unknown_reason(&self) -> Option<BudgetExhausted> {
894        self.last_unknown
895    }
896}
897
898/// A binary heap of variables, highest activity first, the lower variable
899/// first on a tie.
900#[derive(Default)]
901struct Heap {
902    heap: Vec<u32>,
903    position: Vec<Option<usize>>,
904}
905
906impl Heap {
907    fn before(a: u32, b: u32, activity: &[f64]) -> bool {
908        let (x, y) = (activity[a as usize], activity[b as usize]);
909        x > y || (x == y && a < b)
910    }
911
912    fn insert(&mut self, v: u32, activity: &[f64]) {
913        if self.position.len() <= v as usize {
914            self.position.resize(v as usize + 1, None);
915        }
916        if self.position[v as usize].is_some() {
917            return;
918        }
919        self.heap.push(v);
920        let i = self.heap.len() - 1;
921        self.position[v as usize] = Some(i);
922        self.up(i, activity);
923    }
924
925    fn increased(&mut self, v: u32, activity: &[f64]) {
926        if let Some(i) = self.position.get(v as usize).copied().flatten() {
927            self.up(i, activity);
928        }
929    }
930
931    fn pop(&mut self, activity: &[f64]) -> Option<u32> {
932        if self.heap.is_empty() {
933            return None;
934        }
935        let top = self.heap[0];
936        let last = self.heap.pop().expect("the heap is not empty");
937        self.position[top as usize] = None;
938        if !self.heap.is_empty() {
939            self.heap[0] = last;
940            self.position[last as usize] = Some(0);
941            self.down(0, activity);
942        }
943        Some(top)
944    }
945
946    fn up(&mut self, mut i: usize, activity: &[f64]) {
947        let v = self.heap[i];
948        while i > 0 {
949            let parent = (i - 1) / 2;
950            if !Heap::before(v, self.heap[parent], activity) {
951                break;
952            }
953            self.heap[i] = self.heap[parent];
954            self.position[self.heap[i] as usize] = Some(i);
955            i = parent;
956        }
957        self.heap[i] = v;
958        self.position[v as usize] = Some(i);
959    }
960
961    fn down(&mut self, mut i: usize, activity: &[f64]) {
962        let v = self.heap[i];
963        loop {
964            let left = 2 * i + 1;
965            if left >= self.heap.len() {
966                break;
967            }
968            let right = left + 1;
969            let child = if right < self.heap.len()
970                && Heap::before(self.heap[right], self.heap[left], activity)
971            {
972                right
973            } else {
974                left
975            };
976            if !Heap::before(self.heap[child], v, activity) {
977                break;
978            }
979            self.heap[i] = self.heap[child];
980            self.position[self.heap[i] as usize] = Some(i);
981            i = child;
982        }
983        self.heap[i] = v;
984        self.position[v as usize] = Some(i);
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991
992    fn lits(s: &mut Cdcl, n: usize) -> Vec<Var> {
993        (0..n).map(|_| s.new_var()).collect()
994    }
995
996    #[test]
997    fn luby_sequence() {
998        let got: Vec<u64> = (0..15).map(luby).collect();
999        assert_eq!(got, [1, 1, 2, 1, 1, 2, 4, 1, 1, 2, 1, 1, 2, 4, 8]);
1000    }
1001
1002    #[test]
1003    fn simple_sat_and_unsat() {
1004        let mut s = Cdcl::new();
1005        let v = lits(&mut s, 2);
1006        let (a, b) = (Lit::positive(v[0]), Lit::positive(v[1]));
1007        s.add_clause(&[a, b]);
1008        s.add_clause(&[!a, b]);
1009        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Sat);
1010        assert!(s.value(v[1]));
1011        assert_eq!(s.solve(&[!b], &Budget::unlimited()), Solved::Unsat);
1012        // Assumptions do not stick.
1013        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Sat);
1014        s.add_clause(&[!b]);
1015        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat);
1016    }
1017
1018    /// The pigeonhole principle: n + 1 pigeons do not fit in n holes.
1019    fn pigeons(s: &mut Cdcl, holes: usize) {
1020        let pigeons = holes + 1;
1021        let p: Vec<Vec<Var>> = (0..pigeons).map(|_| lits(s, holes)).collect();
1022        for row in &p {
1023            let clause: Vec<Lit> = row.iter().map(|&v| Lit::positive(v)).collect();
1024            s.add_clause(&clause);
1025        }
1026        for h in 0..holes {
1027            for (i, a) in p.iter().enumerate() {
1028                for b in &p[i + 1..] {
1029                    s.add_clause(&[Lit::negative(a[h]), Lit::negative(b[h])]);
1030                }
1031            }
1032        }
1033    }
1034
1035    #[test]
1036    fn pigeonhole_is_unsat() {
1037        for holes in 1..=6 {
1038            let mut s = Cdcl::new();
1039            pigeons(&mut s, holes);
1040            assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat, "{holes}");
1041        }
1042    }
1043
1044    #[test]
1045    fn budget_gives_unknown_and_leaves_the_solver_usable() {
1046        let mut s = Cdcl::new();
1047        pigeons(&mut s, 8);
1048        assert_eq!(s.solve(&[], &Budget::conflicts(10)), Solved::Unknown);
1049        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat);
1050    }
1051
1052    /// Every model of a small formula, by blocking clauses, against brute
1053    /// force.
1054    #[test]
1055    fn enumerates_every_model() {
1056        // (a or b) and (not a or c) and (not b or not c) over a, b, c.
1057        let clauses: [&[(usize, bool)]; 3] = [
1058            &[(0, true), (1, true)],
1059            &[(0, false), (2, true)],
1060            &[(1, false), (2, false)],
1061        ];
1062        let mut brute = 0;
1063        for m in 0..8u32 {
1064            let val = |i: usize| (m >> i) & 1 == 1;
1065            if clauses
1066                .iter()
1067                .all(|c| c.iter().any(|&(i, pos)| val(i) == pos))
1068            {
1069                brute += 1;
1070            }
1071        }
1072        let mut s = Cdcl::new();
1073        let v = lits(&mut s, 3);
1074        for c in clauses {
1075            let c: Vec<Lit> = c.iter().map(|&(i, pos)| Lit::new(v[i], pos)).collect();
1076            s.add_clause(&c);
1077        }
1078        let mut found = 0;
1079        while s.solve(&[], &Budget::unlimited()) == Solved::Sat {
1080            found += 1;
1081            let block: Vec<Lit> = v.iter().map(|&x| Lit::new(x, !s.value(x))).collect();
1082            s.add_clause(&block);
1083        }
1084        assert_eq!(found, brute);
1085    }
1086
1087    #[test]
1088    fn unsat_core_extracts_conflicting_assumptions() {
1089        let mut s = Cdcl::new();
1090        let v = lits(&mut s, 5);
1091        // v0 -> v1, v1 -> !v2; v3 and v4 are unrelated.
1092        s.add_clause(&[Lit::negative(v[0]), Lit::positive(v[1])]);
1093        s.add_clause(&[Lit::negative(v[1]), Lit::negative(v[2])]);
1094        let assumptions = [
1095            Lit::positive(v[3]),
1096            Lit::positive(v[0]),
1097            Lit::positive(v[4]),
1098            Lit::positive(v[2]),
1099        ];
1100        assert_eq!(s.solve(&assumptions, &Budget::unlimited()), Solved::Unsat);
1101        let core = s.unsat_core();
1102        assert_eq!(core, vec![Lit::positive(v[0]), Lit::positive(v[2])]);
1103        // Confirm the extracted core alone is unsatisfiable.
1104        assert_eq!(s.solve(&core, &Budget::unlimited()), Solved::Unsat);
1105
1106        // Directly contradictory assumptions.
1107        let dup = [
1108            Lit::positive(v[3]),
1109            Lit::positive(v[4]),
1110            Lit::negative(v[4]),
1111        ];
1112        assert_eq!(s.solve(&dup, &Budget::unlimited()), Solved::Unsat);
1113        let core = s.unsat_core();
1114        assert_eq!(core, vec![Lit::positive(v[4]), Lit::negative(v[4])]);
1115
1116        // An assumption given twice is in the core once, in assumption order.
1117        let twice = [
1118            Lit::positive(v[0]),
1119            Lit::positive(v[0]),
1120            Lit::positive(v[2]),
1121        ];
1122        assert_eq!(s.solve(&twice, &Budget::unlimited()), Solved::Unsat);
1123        assert_eq!(
1124            s.unsat_core(),
1125            vec![Lit::positive(v[0]), Lit::positive(v[2])]
1126        );
1127    }
1128
1129    #[test]
1130    fn unknown_reason_distinguishes_conflicts_from_time() {
1131        // Pigeonhole 5 into 4 takes many conflicts.
1132        let mut s = Cdcl::new();
1133        let vars: Vec<Vec<Var>> = (0..5)
1134            .map(|_| (0..4).map(|_| s.new_var()).collect())
1135            .collect();
1136        for row in &vars {
1137            let clause: Vec<Lit> = row.iter().map(|&v| Lit::positive(v)).collect();
1138            s.add_clause(&clause);
1139        }
1140        for (p1, r1) in vars.iter().enumerate() {
1141            for r2 in &vars[(p1 + 1)..] {
1142                for (&a, &b) in r1.iter().zip(r2.iter()) {
1143                    s.add_clause(&[Lit::negative(a), Lit::negative(b)]);
1144                }
1145            }
1146        }
1147        let b_time = Budget::conflicts(1_000_000).with_time(Duration::ZERO);
1148        assert_eq!(s.solve(&[], &b_time), Solved::Unknown);
1149        assert_eq!(s.unknown_reason(), Some(BudgetExhausted::Time));
1150
1151        let b_confl = Budget::conflicts(2).with_time(Duration::from_secs(60));
1152        assert_eq!(s.solve(&[], &b_confl), Solved::Unknown);
1153        assert_eq!(s.unknown_reason(), Some(BudgetExhausted::Conflicts));
1154    }
1155}