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;
171const NO_REASON: u32 = u32::MAX;
172const DEAD_CLAUSE: u32 = u32::MAX;
173const BIN_FLAG: u32 = 1 << 31;
174const CREF_MASK: u32 = !BIN_FLAG;
175
176/// A clause watching a literal, with another of its literals: when that
177/// one is true the clause is satisfied and need not be visited.
178/// Packed into 8 bytes: the high bit of `cref_and_bin` marks a binary clause,
179/// and the lower 31 bits hold the arena offset.
180#[derive(Clone, Copy)]
181struct Watcher {
182    cref_and_bin: u32,
183    blocker: Lit,
184}
185
186impl Watcher {
187    #[inline]
188    fn new(cref: usize, blocker: Lit, binary: bool) -> Watcher {
189        debug_assert!(cref <= CREF_MASK as usize);
190        Watcher {
191            cref_and_bin: (cref as u32) | if binary { BIN_FLAG } else { 0 },
192            blocker,
193        }
194    }
195
196    #[inline]
197    fn cref(self) -> usize {
198        (self.cref_and_bin & CREF_MASK) as usize
199    }
200
201    #[inline]
202    fn is_binary(self) -> bool {
203        (self.cref_and_bin & BIN_FLAG) != 0
204    }
205}
206
207#[inline]
208fn value_of(values: &[u8], l: Lit) -> u8 {
209    let v = values[l.var().0 as usize];
210    if v == UNDEF {
211        UNDEF
212    } else {
213        v ^ (l.is_negative() as u8)
214    }
215}
216
217enum Search {
218    Sat,
219    Unsat,
220    Unknown,
221    Restart,
222}
223
224/// Elinvar's own conflict-driven solver.
225pub struct Cdcl {
226    ok: bool,
227    arena: Vec<Lit>,
228    /// The number of clauses in the arena.
229    clause_count: usize,
230    learnts: usize,
231    max_learnts: f64,
232    /// Buffers reused by clause minimization, conflict analysis, and clause addition.
233    stack: Vec<Lit>,
234    to_clear: Vec<Lit>,
235    learnt_buf: Vec<Lit>,
236    clause_buf: Vec<Lit>,
237    /// For each literal, the clauses watching it: visited when it becomes
238    /// false.
239    watches: Vec<Vec<Watcher>>,
240    values: Vec<u8>,
241    level: Vec<u32>,
242    reason: Vec<u32>,
243    phase: Vec<bool>,
244    activity: Vec<f64>,
245    var_inc: f64,
246    heap: Heap,
247    trail: Vec<Lit>,
248    trail_lim: Vec<usize>,
249    qhead: usize,
250    seen: Vec<bool>,
251    /// Reusable stamp table for computing learnt-clause LBD without allocating.
252    lbd_mark: Vec<u32>,
253    lbd_stamp: u32,
254    model: Vec<bool>,
255    /// Subset of the last solve's assumptions that derived `Unsat`.
256    conflict: Vec<Lit>,
257    restarts: u32,
258    /// Which limit stopped the last solve when it returned `Solved::Unknown`.
259    last_unknown: Option<BudgetExhausted>,
260    /// Conflicts over the solver's life, for statistics.
261    pub total_conflicts: u64,
262}
263
264impl Default for Cdcl {
265    fn default() -> Cdcl {
266        Cdcl::new()
267    }
268}
269
270impl Cdcl {
271    /// An empty solver.
272    pub fn new() -> Cdcl {
273        Cdcl {
274            ok: true,
275            arena: Vec::new(),
276            clause_count: 0,
277            learnts: 0,
278            max_learnts: 0.0,
279            stack: Vec::new(),
280            to_clear: Vec::new(),
281            learnt_buf: Vec::new(),
282            clause_buf: Vec::new(),
283            watches: Vec::new(),
284            values: Vec::new(),
285            level: Vec::new(),
286            reason: Vec::new(),
287            phase: Vec::new(),
288            activity: Vec::new(),
289            var_inc: 1.0,
290            heap: Heap::default(),
291            trail: Vec::new(),
292            trail_lim: Vec::new(),
293            qhead: 0,
294            seen: Vec::new(),
295            lbd_mark: Vec::new(),
296            lbd_stamp: 0,
297            model: Vec::new(),
298            conflict: Vec::new(),
299            restarts: 0,
300            last_unknown: None,
301            total_conflicts: 0,
302        }
303    }
304
305    /// The number of variables.
306    pub fn num_vars(&self) -> usize {
307        self.values.len()
308    }
309
310    fn lit_value(&self, l: Lit) -> u8 {
311        value_of(&self.values, l)
312    }
313
314    fn decision_level(&self) -> usize {
315        self.trail_lim.len()
316    }
317
318    #[inline]
319    fn enqueue(&mut self, l: Lit, reason: u32) {
320        let v = l.var().0 as usize;
321        debug_assert_eq!(self.values[v], UNDEF);
322        self.values[v] = if l.is_negative() { FALSE } else { TRUE };
323        self.level[v] = self.decision_level() as u32;
324        self.reason[v] = reason;
325        self.trail.push(l);
326    }
327
328    fn cancel_until(&mut self, level: usize) {
329        if self.decision_level() <= level {
330            return;
331        }
332        let start = self.trail_lim[level];
333        for i in (start..self.trail.len()).rev() {
334            let l = self.trail[i];
335            let v = l.var().0 as usize;
336            self.phase[v] = !l.is_negative();
337            self.values[v] = UNDEF;
338            self.reason[v] = NO_REASON;
339            self.heap.insert(v as u32, &self.activity);
340        }
341        self.trail.truncate(start);
342        self.trail_lim.truncate(level);
343        self.qhead = self.qhead.min(start);
344    }
345
346    /// Puts a clause in the arena; its offset.
347    fn push_clause(&mut self, lits: &[Lit], learnt: bool, lbd: u32) -> usize {
348        let cref = self.arena.len();
349        assert!(
350            cref <= CREF_MASK as usize,
351            "clause arena exceeded 2^31 literals"
352        );
353        self.arena.push(Lit(lits.len() as u32));
354        self.arena.push(Lit(lbd << 1 | u32::from(learnt)));
355        self.arena.extend_from_slice(lits);
356        self.clause_count += 1;
357        cref
358    }
359
360    #[inline]
361    fn clause_len(&self, cref: usize) -> usize {
362        self.arena[cref].0 as usize
363    }
364
365    #[inline]
366    fn lits(&self, cref: usize) -> &[Lit] {
367        &self.arena[cref + HEADER..cref + HEADER + self.clause_len(cref)]
368    }
369
370    fn attach(&mut self, cref: usize) {
371        let c = self.lits(cref);
372        let (a, b) = (c[0], c[1]);
373        let binary = c.len() == 2;
374        self.watches[a.index()].push(Watcher::new(cref, b, binary));
375        self.watches[b.index()].push(Watcher::new(cref, a, binary));
376    }
377
378    /// Unit propagation. Returns a conflicting clause, if any.
379    fn propagate(&mut self) -> Option<usize> {
380        while self.qhead < self.trail.len() {
381            let p = self.trail[self.qhead];
382            self.qhead += 1;
383            let false_lit = !p;
384            let mut ws = std::mem::take(&mut self.watches[false_lit.index()]);
385            let (mut i, mut j) = (0, 0);
386            let mut conflict = None;
387            while i < ws.len() {
388                let w = ws[i];
389                i += 1;
390                let blocker = value_of(&self.values, w.blocker);
391                if blocker == TRUE {
392                    ws[j] = w;
393                    j += 1;
394                    continue;
395                }
396                let cref = w.cref();
397                if w.is_binary() {
398                    ws[j] = w;
399                    j += 1;
400                    if blocker == FALSE {
401                        conflict = Some(cref);
402                        let rem = ws.len() - i;
403                        ws.copy_within(i.., j);
404                        j += rem;
405                        break;
406                    } else {
407                        // Analysis reads a reason's implied literal first.
408                        let lits = &mut self.arena[cref + HEADER..cref + HEADER + 2];
409                        if lits[0] != w.blocker {
410                            lits.swap(0, 1);
411                        }
412                        self.enqueue(w.blocker, cref as u32);
413                    }
414                    continue;
415                }
416                let len = self.arena[cref].0 as usize;
417                let lits = &mut self.arena[cref + HEADER..cref + HEADER + len];
418                if lits[0] == false_lit {
419                    lits.swap(0, 1);
420                }
421                let first = lits[0];
422                let kept = Watcher::new(cref, first, false);
423                if first != w.blocker && value_of(&self.values, first) == TRUE {
424                    ws[j] = kept;
425                    j += 1;
426                    continue;
427                }
428                let mut moved = false;
429                for k in 2..lits.len() {
430                    if value_of(&self.values, lits[k]) != FALSE {
431                        lits.swap(1, k);
432                        self.watches[lits[1].index()].push(kept);
433                        moved = true;
434                        break;
435                    }
436                }
437                if moved {
438                    continue;
439                }
440                ws[j] = kept;
441                j += 1;
442                if value_of(&self.values, first) == FALSE {
443                    conflict = Some(cref);
444                    let rem = ws.len() - i;
445                    ws.copy_within(i.., j);
446                    j += rem;
447                    break;
448                } else {
449                    self.enqueue(first, cref as u32);
450                }
451            }
452            ws.truncate(j);
453            self.watches[false_lit.index()] = ws;
454            if conflict.is_some() {
455                self.qhead = self.trail.len();
456                return conflict;
457            }
458        }
459        None
460    }
461
462    fn bump(&mut self, v: usize) {
463        self.activity[v] += self.var_inc;
464        if self.activity[v] > 1e100 {
465            crate::simd::scale_f64(&mut self.activity, 1e-100);
466            self.var_inc *= 1e-100;
467        }
468        self.heap.increased(v as u32, &self.activity);
469    }
470
471    /// First-UIP conflict analysis. Populates `self.learnt_buf` with the learnt
472    /// clause (asserting literal first) and returns the level to go back to.
473    fn analyze(&mut self, mut confl: usize) -> usize {
474        let mut learnt = std::mem::take(&mut self.learnt_buf);
475        learnt.clear();
476        learnt.push(Lit(0));
477        let mut path = 0usize;
478        let mut p: Option<Lit> = None;
479        let mut index = self.trail.len();
480        loop {
481            let start = usize::from(p.is_some());
482            for k in start..self.clause_len(confl) {
483                let q = self.arena[confl + HEADER + k];
484                let v = q.var().0 as usize;
485                if !self.seen[v] && self.level[v] > 0 {
486                    self.bump(v);
487                    self.seen[v] = true;
488                    if self.level[v] as usize >= self.decision_level() {
489                        path += 1;
490                    } else {
491                        learnt.push(q);
492                    }
493                }
494            }
495            loop {
496                index -= 1;
497                if self.seen[self.trail[index].var().0 as usize] {
498                    break;
499                }
500            }
501            let l = self.trail[index];
502            let v = l.var().0 as usize;
503            self.seen[v] = false;
504            path -= 1;
505            p = Some(l);
506            if path == 0 {
507                break;
508            }
509            let r = self.reason[v];
510            debug_assert_ne!(
511                r, NO_REASON,
512                "a literal at the conflict level with a seen successor has a reason"
513            );
514            confl = r as usize;
515        }
516        learnt[0] = !p.expect("analysis visits at least one literal");
517        self.minimize(&mut learnt);
518        self.minimize_binary(&mut learnt);
519        let mut back = 0;
520        if learnt.len() > 1 {
521            let mut max_i = 1;
522            for i in 2..learnt.len() {
523                if self.level[learnt[i].var().0 as usize]
524                    > self.level[learnt[max_i].var().0 as usize]
525                {
526                    max_i = i;
527                }
528            }
529            learnt.swap(1, max_i);
530            back = self.level[learnt[1].var().0 as usize] as usize;
531        }
532        self.learnt_buf = learnt;
533        back
534    }
535
536    fn abstract_level(&self, v: usize) -> u32 {
537        1 << (self.level[v] & 31)
538    }
539
540    /// Recursive minimization, as MiniSat does it: drops each literal of the
541    /// learnt clause that the others imply through reasons. Clears `seen`.
542    fn minimize(&mut self, learnt: &mut Vec<Lit>) {
543        let mut levels = 0u32;
544        for l in &learnt[1..] {
545            levels |= self.abstract_level(l.var().0 as usize);
546        }
547        let mut to_clear = std::mem::take(&mut self.to_clear);
548        to_clear.clear();
549        to_clear.extend_from_slice(learnt);
550        let mut j = 1;
551        for i in 1..learnt.len() {
552            let l = learnt[i];
553            let v = l.var().0 as usize;
554            if self.reason[v] == NO_REASON || !self.redundant(l, levels, &mut to_clear) {
555                learnt[j] = l;
556                j += 1;
557            }
558        }
559        learnt.truncate(j);
560        for l in &to_clear {
561            self.seen[l.var().0 as usize] = false;
562        }
563        self.to_clear = to_clear;
564    }
565
566    /// Binary-clause resolution minimization (Sorensson & Biere): if a binary
567    /// clause `(learnt[0] or b)` exists in the database and `!b` is in
568    /// `learnt[1..]`, resolving the two eliminates `!b` from `learnt`.
569    fn minimize_binary(&self, learnt: &mut Vec<Lit>) {
570        if learnt.len() <= 2 || learnt.len() > 30 {
571            return;
572        }
573        let first = learnt[0];
574        let ws = &self.watches[first.index()];
575        for &w in ws {
576            if !w.is_binary() {
577                continue;
578            }
579            let target = !w.blocker;
580            if let Some(pos) = learnt[1..].iter().position(|&l| l == target) {
581                learnt.swap_remove(pos + 1);
582                if learnt.len() <= 2 {
583                    break;
584                }
585            }
586        }
587    }
588
589    fn redundant(&mut self, p: Lit, levels: u32, to_clear: &mut Vec<Lit>) -> bool {
590        let mut stack = std::mem::take(&mut self.stack);
591        stack.clear();
592        stack.push(p);
593        let top = to_clear.len();
594        while let Some(q) = stack.pop() {
595            let r = self.reason[q.var().0 as usize];
596            debug_assert_ne!(r, NO_REASON, "only literals with a reason are pushed");
597            let c = r as usize;
598            for k in 1..self.clause_len(c) {
599                let l = self.arena[c + HEADER + k];
600                let v = l.var().0 as usize;
601                if !self.seen[v] && self.level[v] > 0 {
602                    if self.reason[v] != NO_REASON && self.abstract_level(v) & levels != 0 {
603                        self.seen[v] = true;
604                        stack.push(l);
605                        to_clear.push(l);
606                    } else {
607                        for t in &to_clear[top..] {
608                            self.seen[t.var().0 as usize] = false;
609                        }
610                        to_clear.truncate(top);
611                        self.stack = stack;
612                        return false;
613                    }
614                }
615            }
616        }
617        self.stack = stack;
618        true
619    }
620
621    fn pick_branch(&mut self) -> Option<Lit> {
622        while let Some(v) = self.heap.pop(&self.activity) {
623            if self.values[v as usize] == UNDEF {
624                return Some(Lit::new(Var(v), self.phase[v as usize]));
625            }
626        }
627        None
628    }
629
630    /// Drops half the learnt clauses with an LBD above 2, worst LBD first,
631    /// then longest, then oldest, at level 0.
632    fn reduce(&mut self) {
633        debug_assert_eq!(self.decision_level(), 0);
634        // Offsets grow with age, so ordering by offset is oldest first.
635        let mut learnt: Vec<(u32, usize, usize)> = Vec::new();
636        let mut c = 0;
637        while c < self.arena.len() {
638            let (len, flags) = (self.clause_len(c), self.arena[c + 1].0);
639            if flags & 1 == 1 && len > 2 && flags >> 1 > 2 {
640                learnt.push((flags >> 1, len, c));
641            }
642            c += HEADER + len;
643        }
644        learnt.sort_unstable();
645        let dropped = learnt.len() - learnt.len() / 2;
646        for &(_, _, c) in &learnt[learnt.len() / 2..] {
647            self.arena[c + 1] = Lit(DEAD_CLAUSE);
648        }
649        let old = std::mem::take(&mut self.arena);
650        self.arena = Vec::with_capacity(old.len());
651        self.clause_count = 0;
652        let mut c = 0;
653        while c < old.len() {
654            let len = old[c].0 as usize;
655            if old[c + 1].0 != DEAD_CLAUSE {
656                self.arena.extend_from_slice(&old[c..c + HEADER + len]);
657                self.clause_count += 1;
658            }
659            c += HEADER + len;
660        }
661        self.learnts -= dropped;
662        for w in &mut self.watches {
663            w.clear();
664        }
665        self.reason.fill(NO_REASON);
666        // Attach binary clauses first so unit propagation resolves all binary
667        // implications and conflicts before scanning longer clauses.
668        let mut c = 0;
669        while c < self.arena.len() {
670            let len = self.clause_len(c);
671            if len == 2 {
672                self.attach(c);
673            }
674            c += HEADER + len;
675        }
676        let mut c = 0;
677        while c < self.arena.len() {
678            let len = self.clause_len(c);
679            if len > 2 {
680                self.attach(c);
681            }
682            c += HEADER + len;
683        }
684        // A watch rebuilt on a literal already false at level 0 is only
685        // safe once that literal is propagated again.
686        self.qhead = 0;
687        if self.propagate().is_some() {
688            self.ok = false;
689            return;
690        }
691        self.probe();
692        if !self.ok {
693            return;
694        }
695        self.vivify();
696    }
697
698    /// Deterministic level-0 failed-literal probing: for unassigned variables
699    /// with binary watches, temporarily assume each polarity; a conflict proves
700    /// the opposite literal at level 0.
701    fn probe(&mut self) {
702        debug_assert_eq!(self.decision_level(), 0);
703        const MAX_PROBES: usize = 128;
704        let mut probed = 0usize;
705        for v in 0..self.values.len() {
706            if probed >= MAX_PROBES || !self.ok {
707                break;
708            }
709            if self.values[v] != UNDEF {
710                continue;
711            }
712            let pos = Lit::positive(Var(v as u32));
713            let neg = !pos;
714            let has_bin = self.watches[pos.index()]
715                .first()
716                .is_some_and(|w| w.is_binary())
717                || self.watches[neg.index()]
718                    .first()
719                    .is_some_and(|w| w.is_binary());
720            if !has_bin {
721                continue;
722            }
723            probed += 1;
724            for lit in [pos, neg] {
725                if self.values[v] != UNDEF {
726                    break;
727                }
728                self.trail_lim.push(self.trail.len());
729                self.enqueue(lit, NO_REASON);
730                let failed = self.propagate().is_some();
731                self.cancel_until(0);
732                if failed {
733                    self.enqueue(!lit, NO_REASON);
734                    if self.propagate().is_some() {
735                        self.ok = false;
736                        return;
737                    }
738                    break;
739                }
740            }
741        }
742    }
743
744    /// Unit propagation that skips a single clause `ignore` (used only during
745    /// clause vivification so normal `propagate` has no extra branch).
746    fn propagate_ignoring(&mut self, ignore: usize) -> Option<usize> {
747        while self.qhead < self.trail.len() {
748            let p = self.trail[self.qhead];
749            self.qhead += 1;
750            let false_lit = !p;
751            let mut ws = std::mem::take(&mut self.watches[false_lit.index()]);
752            let (mut i, mut j) = (0, 0);
753            let mut conflict = None;
754            while i < ws.len() {
755                let w = ws[i];
756                i += 1;
757                let cref = w.cref();
758                if cref == ignore {
759                    ws[j] = w;
760                    j += 1;
761                    continue;
762                }
763                let blocker = value_of(&self.values, w.blocker);
764                if blocker == TRUE {
765                    ws[j] = w;
766                    j += 1;
767                    continue;
768                }
769                if w.is_binary() {
770                    ws[j] = w;
771                    j += 1;
772                    if blocker == FALSE {
773                        conflict = Some(cref);
774                        let rem = ws.len() - i;
775                        ws.copy_within(i.., j);
776                        j += rem;
777                        break;
778                    } else {
779                        let lits = &mut self.arena[cref + HEADER..cref + HEADER + 2];
780                        if lits[0] != w.blocker {
781                            lits.swap(0, 1);
782                        }
783                        self.enqueue(w.blocker, cref as u32);
784                    }
785                    continue;
786                }
787                let len = self.arena[cref].0 as usize;
788                let lits = &mut self.arena[cref + HEADER..cref + HEADER + len];
789                if lits[0] == false_lit {
790                    lits.swap(0, 1);
791                }
792                let first = lits[0];
793                let kept = Watcher::new(cref, first, false);
794                if first != w.blocker && value_of(&self.values, first) == TRUE {
795                    ws[j] = kept;
796                    j += 1;
797                    continue;
798                }
799                let mut moved = false;
800                for k in 2..lits.len() {
801                    if value_of(&self.values, lits[k]) != FALSE {
802                        lits.swap(1, k);
803                        self.watches[lits[1].index()].push(kept);
804                        moved = true;
805                        break;
806                    }
807                }
808                if moved {
809                    continue;
810                }
811                ws[j] = kept;
812                j += 1;
813                if value_of(&self.values, first) == FALSE {
814                    conflict = Some(cref);
815                    let rem = ws.len() - i;
816                    ws.copy_within(i.., j);
817                    j += rem;
818                    break;
819                } else {
820                    self.enqueue(first, cref as u32);
821                }
822            }
823            ws.truncate(j);
824            self.watches[false_lit.index()] = ws;
825            if conflict.is_some() {
826                self.qhead = self.trail.len();
827                return conflict;
828            }
829        }
830        None
831    }
832
833    /// Shortens high-quality learnt clauses (LBD <= 4, len >= 3) at level 0
834    /// by temporarily assuming the negation of each literal and checking
835    /// whether remaining literals are already implied or conflicting.
836    fn vivify(&mut self) {
837        debug_assert_eq!(self.decision_level(), 0);
838        const MAX_CANDIDATES: usize = 128;
839        let mut candidates: Vec<(u32, usize)> = Vec::new();
840        let mut c = 0;
841        while c < self.arena.len() {
842            let len = self.clause_len(c);
843            let flags = self.arena[c + 1].0;
844            if (flags & 1) == 1 && len >= 3 && (flags >> 1) <= 4 {
845                candidates.push((flags >> 1, c));
846            }
847            c += HEADER + len;
848        }
849        // Best LBD first, then oldest (lowest offset): deterministic.
850        candidates.sort_unstable();
851        candidates.truncate(MAX_CANDIDATES);
852        let mut lits = Vec::new();
853        let mut kept = Vec::new();
854        for (old_lbd, cref) in candidates {
855            if !self.ok {
856                return;
857            }
858            let len = self.clause_len(cref);
859            lits.clear();
860            lits.extend_from_slice(&self.arena[cref + HEADER..cref + HEADER + len]);
861            if lits.iter().any(|&l| self.lit_value(l) == TRUE) {
862                continue;
863            }
864            kept.clear();
865            for &l in &lits {
866                match self.lit_value(l) {
867                    TRUE => {
868                        kept.push(l);
869                        break;
870                    }
871                    FALSE => {}
872                    _ => {
873                        kept.push(l);
874                        self.trail_lim.push(self.trail.len());
875                        self.enqueue(!l, NO_REASON);
876                        if self.propagate_ignoring(cref).is_some() {
877                            break;
878                        }
879                    }
880                }
881            }
882            self.cancel_until(0);
883            if kept.len() < lits.len() {
884                match kept.len() {
885                    0 => {
886                        self.ok = false;
887                        return;
888                    }
889                    1 => {
890                        if self.lit_value(kept[0]) == FALSE {
891                            self.ok = false;
892                            return;
893                        }
894                        if self.lit_value(kept[0]) == UNDEF {
895                            self.enqueue(kept[0], NO_REASON);
896                            if self.propagate().is_some() {
897                                self.ok = false;
898                                return;
899                            }
900                        }
901                    }
902                    _ => {
903                        // Demote the subsumed longer clause so the next `reduce`
904                        // evicts it first.
905                        self.arena[cref + 1] = Lit(((u32::MAX >> 2) << 1) | 1);
906                        let new_lbd = old_lbd.min(kept.len() as u32);
907                        let new_cref = self.push_clause(&kept, true, new_lbd);
908                        self.learnts += 1;
909                        self.attach(new_cref);
910                    }
911                }
912            }
913        }
914    }
915
916    fn compute_lbd(&mut self, lits: &[Lit]) -> u32 {
917        self.lbd_stamp = self.lbd_stamp.wrapping_add(1);
918        if self.lbd_stamp == 0 {
919            self.lbd_mark.fill(0);
920            self.lbd_stamp = 1;
921        }
922        let stamp = self.lbd_stamp;
923        let mut count = 0u32;
924        for &l in lits {
925            let lvl = self.level[l.var().0 as usize] as usize;
926            if lvl >= self.lbd_mark.len() {
927                self.lbd_mark.resize(lvl + 1, 0);
928            }
929            if self.lbd_mark[lvl] != stamp {
930                self.lbd_mark[lvl] = stamp;
931                count += 1;
932            }
933        }
934        count
935    }
936
937    /// Traces a falsified assumption `a` (where `!a` is currently true on the
938    /// trail) back through the implication graph to the subset of `assumptions`
939    /// that implied `!a`.
940    fn analyze_final(&mut self, a: Lit, assumptions: &[Lit]) {
941        self.conflict.clear();
942        let mut core = vec![a];
943        if self.decision_level() == 0 {
944            self.conflict = core;
945            return;
946        }
947        let p = !a;
948        let pv = p.var().0 as usize;
949        if self.level[pv] > 0 {
950            self.seen[pv] = true;
951            let mut marked = vec![pv];
952            let stop = self.trail_lim[0];
953            for i in (stop..self.trail.len()).rev() {
954                let lit = self.trail[i];
955                let x = lit.var().0 as usize;
956                if !self.seen[x] {
957                    continue;
958                }
959                match self.reason[x] {
960                    NO_REASON => core.push(lit),
961                    r => {
962                        let cref = r as usize;
963                        let start = cref + HEADER;
964                        let end = start + self.clause_len(cref);
965                        for j in start..end {
966                            let q = self.arena[j];
967                            let qv = q.var().0 as usize;
968                            if qv != x && self.level[qv] > 0 && !self.seen[qv] {
969                                self.seen[qv] = true;
970                                marked.push(qv);
971                            }
972                        }
973                    }
974                }
975            }
976            for v in marked {
977                self.seen[v] = false;
978            }
979        }
980        // Keep assumption order and drop duplicates: each core literal is
981        // taken once, by its first assumption.
982        let mut core: std::collections::BTreeSet<Lit> = core.into_iter().collect();
983        for &assump in assumptions {
984            if core.remove(&assump) {
985                self.conflict.push(assump);
986            }
987        }
988    }
989
990    fn search(
991        &mut self,
992        limit: u64,
993        assumptions: &[Lit],
994        budget: &Budget,
995        spent: &mut u64,
996        start: Instant,
997    ) -> Search {
998        if budget.time.is_some_and(|t| start.elapsed() >= t) {
999            self.last_unknown = Some(BudgetExhausted::Time);
1000            return Search::Unknown;
1001        }
1002        let mut conflicts = 0u64;
1003        loop {
1004            if let Some(confl) = self.propagate() {
1005                conflicts += 1;
1006                *spent += 1;
1007                self.total_conflicts += 1;
1008                if self.decision_level() == 0 {
1009                    self.ok = false;
1010                    self.conflict.clear();
1011                    return Search::Unsat;
1012                }
1013                let back = self.analyze(confl);
1014                self.cancel_until(back);
1015                if self.learnt_buf.len() == 1 {
1016                    let unit = self.learnt_buf[0];
1017                    self.enqueue(unit, NO_REASON);
1018                } else {
1019                    let learnt = std::mem::take(&mut self.learnt_buf);
1020                    let first = learnt[0];
1021                    let lbd = self.compute_lbd(&learnt);
1022                    let cref = self.push_clause(&learnt, true, lbd);
1023                    self.learnt_buf = learnt;
1024                    self.learnts += 1;
1025                    self.attach(cref);
1026                    self.enqueue(first, cref as u32);
1027                }
1028                self.var_inc /= 0.95;
1029                if budget.conflicts.is_some_and(|c| *spent >= c) {
1030                    self.last_unknown = Some(BudgetExhausted::Conflicts);
1031                    return Search::Unknown;
1032                }
1033                if budget
1034                    .time
1035                    .is_some_and(|t| (*spent & 15) == 0 && start.elapsed() >= t)
1036                {
1037                    self.last_unknown = Some(BudgetExhausted::Time);
1038                    return Search::Unknown;
1039                }
1040            } else {
1041                if conflicts >= limit {
1042                    self.cancel_until(0);
1043                    return Search::Restart;
1044                }
1045                let mut next = None;
1046                while self.decision_level() < assumptions.len() {
1047                    let a = assumptions[self.decision_level()];
1048                    match self.lit_value(a) {
1049                        TRUE => self.trail_lim.push(self.trail.len()),
1050                        FALSE => {
1051                            self.analyze_final(a, assumptions);
1052                            return Search::Unsat;
1053                        }
1054                        _ => {
1055                            next = Some(a);
1056                            break;
1057                        }
1058                    }
1059                }
1060                let next = match next {
1061                    Some(a) => a,
1062                    None => match self.pick_branch() {
1063                        Some(l) => l,
1064                        None => return Search::Sat,
1065                    },
1066                };
1067                self.trail_lim.push(self.trail.len());
1068                self.enqueue(next, NO_REASON);
1069            }
1070        }
1071    }
1072}
1073
1074/// The Luby sequence 1, 1, 2, 1, 1, 2, 4, ...: element `x`, from 0.
1075fn luby(mut x: u32) -> u64 {
1076    let mut size = 1u64;
1077    let mut seq = 0u32;
1078    while size < u64::from(x) + 1 {
1079        seq += 1;
1080        size = 2 * size + 1;
1081    }
1082    while size - 1 != u64::from(x) {
1083        size = (size - 1) >> 1;
1084        seq -= 1;
1085        x %= size as u32;
1086    }
1087    1u64 << seq
1088}
1089
1090impl Solver for Cdcl {
1091    fn new_var(&mut self) -> Var {
1092        let v = self.values.len() as u32;
1093        self.values.push(UNDEF);
1094        self.level.push(0);
1095        self.reason.push(NO_REASON);
1096        self.phase.push(false);
1097        self.activity.push(0.0);
1098        self.seen.push(false);
1099        self.watches.push(Vec::new());
1100        self.watches.push(Vec::new());
1101        self.heap.insert(v, &self.activity);
1102        Var(v)
1103    }
1104
1105    fn add_clause(&mut self, clause: &[Lit]) {
1106        if !self.ok {
1107            return;
1108        }
1109        self.cancel_until(0);
1110        let mut lits = std::mem::take(&mut self.clause_buf);
1111        lits.clear();
1112        lits.extend_from_slice(clause);
1113        lits.sort_unstable();
1114        lits.dedup();
1115        let mut kept = 0usize;
1116        for i in 0..lits.len() {
1117            let l = lits[i];
1118            if i + 1 < lits.len() && lits[i + 1] == !l {
1119                self.clause_buf = lits;
1120                return; // a tautology: l and not l, adjacent after sorting
1121            }
1122            match self.lit_value(l) {
1123                TRUE => {
1124                    self.clause_buf = lits;
1125                    return;
1126                }
1127                FALSE => {}
1128                _ => {
1129                    lits[kept] = l;
1130                    kept += 1;
1131                }
1132            }
1133        }
1134        lits.truncate(kept);
1135        match lits.len() {
1136            0 => self.ok = false,
1137            1 => {
1138                let unit = lits[0];
1139                self.clause_buf = lits;
1140                self.enqueue(unit, NO_REASON);
1141                if self.propagate().is_some() {
1142                    self.ok = false;
1143                }
1144                return;
1145            }
1146            _ => {
1147                let cref = self.push_clause(&lits, false, 0);
1148                self.clause_buf = lits;
1149                self.attach(cref);
1150                return;
1151            }
1152        }
1153        self.clause_buf = lits;
1154    }
1155
1156    fn solve(&mut self, assumptions: &[Lit], budget: &Budget) -> Solved {
1157        self.model.clear();
1158        self.conflict.clear();
1159        self.last_unknown = None;
1160        if !self.ok {
1161            return Solved::Unsat;
1162        }
1163        if budget.time.is_some_and(|t| t.is_zero()) {
1164            self.last_unknown = Some(BudgetExhausted::Time);
1165            return Solved::Unknown;
1166        }
1167        self.cancel_until(0);
1168        let start = Instant::now();
1169        if self.max_learnts == 0.0 {
1170            self.max_learnts = (self.clause_count as f64 / 3.0).max(1000.0);
1171        }
1172        let mut spent = 0u64;
1173        let result = loop {
1174            let limit = luby(self.restarts) * 100;
1175            match self.search(limit, assumptions, budget, &mut spent, start) {
1176                Search::Sat => {
1177                    self.model = self.values.iter().map(|&v| v == TRUE).collect();
1178                    break Solved::Sat;
1179                }
1180                Search::Unsat => break Solved::Unsat,
1181                Search::Unknown => break Solved::Unknown,
1182                Search::Restart => {
1183                    self.restarts += 1;
1184                    if self.learnts as f64 > self.max_learnts {
1185                        self.reduce();
1186                        if !self.ok {
1187                            break Solved::Unsat;
1188                        }
1189                        self.max_learnts *= 1.1;
1190                    }
1191                }
1192            }
1193        };
1194        self.cancel_until(0);
1195        result
1196    }
1197
1198    fn value(&self, var: Var) -> bool {
1199        self.model.get(var.0 as usize).copied().unwrap_or(false)
1200    }
1201
1202    fn conflicts(&self) -> u64 {
1203        self.total_conflicts
1204    }
1205
1206    fn unsat_core(&self) -> Vec<Lit> {
1207        self.conflict.clone()
1208    }
1209
1210    fn unknown_reason(&self) -> Option<BudgetExhausted> {
1211        self.last_unknown
1212    }
1213}
1214
1215const NOT_IN_HEAP: u32 = u32::MAX;
1216
1217/// A binary heap of variables, highest activity first, the lower variable
1218/// first on a tie.
1219#[derive(Default)]
1220struct Heap {
1221    heap: Vec<u32>,
1222    position: Vec<u32>,
1223}
1224
1225impl Heap {
1226    #[inline]
1227    fn before(a: u32, b: u32, activity: &[f64]) -> bool {
1228        let (x, y) = (activity[a as usize], activity[b as usize]);
1229        x > y || (x == y && a < b)
1230    }
1231
1232    fn insert(&mut self, v: u32, activity: &[f64]) {
1233        if self.position.len() <= v as usize {
1234            self.position.resize(v as usize + 1, NOT_IN_HEAP);
1235        }
1236        if self.position[v as usize] != NOT_IN_HEAP {
1237            return;
1238        }
1239        self.heap.push(v);
1240        let i = self.heap.len() - 1;
1241        self.position[v as usize] = i as u32;
1242        self.up(i, activity);
1243    }
1244
1245    fn increased(&mut self, v: u32, activity: &[f64]) {
1246        if let Some(&pos) = self.position.get(v as usize)
1247            && pos != NOT_IN_HEAP
1248        {
1249            self.up(pos as usize, activity);
1250        }
1251    }
1252
1253    fn pop(&mut self, activity: &[f64]) -> Option<u32> {
1254        if self.heap.is_empty() {
1255            return None;
1256        }
1257        let top = self.heap[0];
1258        let last = self.heap.pop().expect("the heap is not empty");
1259        self.position[top as usize] = NOT_IN_HEAP;
1260        if !self.heap.is_empty() {
1261            self.heap[0] = last;
1262            self.position[last as usize] = 0;
1263            self.down(0, activity);
1264        }
1265        Some(top)
1266    }
1267
1268    fn up(&mut self, mut i: usize, activity: &[f64]) {
1269        let v = self.heap[i];
1270        while i > 0 {
1271            let parent = (i - 1) / 2;
1272            if !Heap::before(v, self.heap[parent], activity) {
1273                break;
1274            }
1275            self.heap[i] = self.heap[parent];
1276            self.position[self.heap[i] as usize] = i as u32;
1277            i = parent;
1278        }
1279        self.heap[i] = v;
1280        self.position[v as usize] = i as u32;
1281    }
1282
1283    fn down(&mut self, mut i: usize, activity: &[f64]) {
1284        let v = self.heap[i];
1285        loop {
1286            let left = 2 * i + 1;
1287            if left >= self.heap.len() {
1288                break;
1289            }
1290            let right = left + 1;
1291            let child = if right < self.heap.len()
1292                && Heap::before(self.heap[right], self.heap[left], activity)
1293            {
1294                right
1295            } else {
1296                left
1297            };
1298            if !Heap::before(self.heap[child], v, activity) {
1299                break;
1300            }
1301            self.heap[i] = self.heap[child];
1302            self.position[self.heap[i] as usize] = i as u32;
1303            i = child;
1304        }
1305        self.heap[i] = v;
1306        self.position[v as usize] = i as u32;
1307    }
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312    use super::*;
1313
1314    fn lits(s: &mut Cdcl, n: usize) -> Vec<Var> {
1315        (0..n).map(|_| s.new_var()).collect()
1316    }
1317
1318    #[test]
1319    fn luby_sequence() {
1320        let got: Vec<u64> = (0..15).map(luby).collect();
1321        assert_eq!(got, [1, 1, 2, 1, 1, 2, 4, 1, 1, 2, 1, 1, 2, 4, 8]);
1322    }
1323
1324    #[test]
1325    fn simple_sat_and_unsat() {
1326        let mut s = Cdcl::new();
1327        let v = lits(&mut s, 2);
1328        let (a, b) = (Lit::positive(v[0]), Lit::positive(v[1]));
1329        s.add_clause(&[a, b]);
1330        s.add_clause(&[!a, b]);
1331        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Sat);
1332        assert!(s.value(v[1]));
1333        assert_eq!(s.solve(&[!b], &Budget::unlimited()), Solved::Unsat);
1334        // Assumptions do not stick.
1335        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Sat);
1336        s.add_clause(&[!b]);
1337        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat);
1338    }
1339
1340    /// The pigeonhole principle: n + 1 pigeons do not fit in n holes.
1341    fn pigeons(s: &mut Cdcl, holes: usize) {
1342        let pigeons = holes + 1;
1343        let p: Vec<Vec<Var>> = (0..pigeons).map(|_| lits(s, holes)).collect();
1344        for row in &p {
1345            let clause: Vec<Lit> = row.iter().map(|&v| Lit::positive(v)).collect();
1346            s.add_clause(&clause);
1347        }
1348        for h in 0..holes {
1349            for (i, a) in p.iter().enumerate() {
1350                for b in &p[i + 1..] {
1351                    s.add_clause(&[Lit::negative(a[h]), Lit::negative(b[h])]);
1352                }
1353            }
1354        }
1355    }
1356
1357    #[test]
1358    fn pigeonhole_is_unsat() {
1359        for holes in 1..=6 {
1360            let mut s = Cdcl::new();
1361            pigeons(&mut s, holes);
1362            assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat, "{holes}");
1363        }
1364    }
1365
1366    #[test]
1367    fn budget_gives_unknown_and_leaves_the_solver_usable() {
1368        let mut s = Cdcl::new();
1369        pigeons(&mut s, 8);
1370        assert_eq!(s.solve(&[], &Budget::conflicts(10)), Solved::Unknown);
1371        assert_eq!(s.solve(&[], &Budget::unlimited()), Solved::Unsat);
1372    }
1373
1374    /// Every model of a small formula, by blocking clauses, against brute
1375    /// force.
1376    #[test]
1377    fn enumerates_every_model() {
1378        // (a or b) and (not a or c) and (not b or not c) over a, b, c.
1379        let clauses: [&[(usize, bool)]; 3] = [
1380            &[(0, true), (1, true)],
1381            &[(0, false), (2, true)],
1382            &[(1, false), (2, false)],
1383        ];
1384        let mut brute = 0;
1385        for m in 0..8u32 {
1386            let val = |i: usize| (m >> i) & 1 == 1;
1387            if clauses
1388                .iter()
1389                .all(|c| c.iter().any(|&(i, pos)| val(i) == pos))
1390            {
1391                brute += 1;
1392            }
1393        }
1394        let mut s = Cdcl::new();
1395        let v = lits(&mut s, 3);
1396        for c in clauses {
1397            let c: Vec<Lit> = c.iter().map(|&(i, pos)| Lit::new(v[i], pos)).collect();
1398            s.add_clause(&c);
1399        }
1400        let mut found = 0;
1401        while s.solve(&[], &Budget::unlimited()) == Solved::Sat {
1402            found += 1;
1403            let block: Vec<Lit> = v.iter().map(|&x| Lit::new(x, !s.value(x))).collect();
1404            s.add_clause(&block);
1405        }
1406        assert_eq!(found, brute);
1407    }
1408
1409    #[test]
1410    fn unsat_core_extracts_conflicting_assumptions() {
1411        let mut s = Cdcl::new();
1412        let v = lits(&mut s, 5);
1413        // v0 -> v1, v1 -> !v2; v3 and v4 are unrelated.
1414        s.add_clause(&[Lit::negative(v[0]), Lit::positive(v[1])]);
1415        s.add_clause(&[Lit::negative(v[1]), Lit::negative(v[2])]);
1416        let assumptions = [
1417            Lit::positive(v[3]),
1418            Lit::positive(v[0]),
1419            Lit::positive(v[4]),
1420            Lit::positive(v[2]),
1421        ];
1422        assert_eq!(s.solve(&assumptions, &Budget::unlimited()), Solved::Unsat);
1423        let core = s.unsat_core();
1424        assert_eq!(core, vec![Lit::positive(v[0]), Lit::positive(v[2])]);
1425        // Confirm the extracted core alone is unsatisfiable.
1426        assert_eq!(s.solve(&core, &Budget::unlimited()), Solved::Unsat);
1427
1428        // Directly contradictory assumptions.
1429        let dup = [
1430            Lit::positive(v[3]),
1431            Lit::positive(v[4]),
1432            Lit::negative(v[4]),
1433        ];
1434        assert_eq!(s.solve(&dup, &Budget::unlimited()), Solved::Unsat);
1435        let core = s.unsat_core();
1436        assert_eq!(core, vec![Lit::positive(v[4]), Lit::negative(v[4])]);
1437
1438        // An assumption given twice is in the core once, in assumption order.
1439        let twice = [
1440            Lit::positive(v[0]),
1441            Lit::positive(v[0]),
1442            Lit::positive(v[2]),
1443        ];
1444        assert_eq!(s.solve(&twice, &Budget::unlimited()), Solved::Unsat);
1445        assert_eq!(
1446            s.unsat_core(),
1447            vec![Lit::positive(v[0]), Lit::positive(v[2])]
1448        );
1449    }
1450
1451    #[test]
1452    fn unknown_reason_distinguishes_conflicts_from_time() {
1453        // Pigeonhole 5 into 4 takes many conflicts.
1454        let mut s = Cdcl::new();
1455        let vars: Vec<Vec<Var>> = (0..5)
1456            .map(|_| (0..4).map(|_| s.new_var()).collect())
1457            .collect();
1458        for row in &vars {
1459            let clause: Vec<Lit> = row.iter().map(|&v| Lit::positive(v)).collect();
1460            s.add_clause(&clause);
1461        }
1462        for (p1, r1) in vars.iter().enumerate() {
1463            for r2 in &vars[(p1 + 1)..] {
1464                for (&a, &b) in r1.iter().zip(r2.iter()) {
1465                    s.add_clause(&[Lit::negative(a), Lit::negative(b)]);
1466                }
1467            }
1468        }
1469        let b_time = Budget::conflicts(1_000_000).with_time(Duration::ZERO);
1470        assert_eq!(s.solve(&[], &b_time), Solved::Unknown);
1471        assert_eq!(s.unknown_reason(), Some(BudgetExhausted::Time));
1472
1473        let b_confl = Budget::conflicts(2).with_time(Duration::from_secs(60));
1474        assert_eq!(s.solve(&[], &b_confl), Solved::Unknown);
1475        assert_eq!(s.unknown_reason(), Some(BudgetExhausted::Conflicts));
1476    }
1477}
1478
1479#[cfg(kani)]
1480mod kani_proofs {
1481    use super::*;
1482
1483    #[kani::proof]
1484    fn kani_lit_and_watcher_roundtrip() {
1485        let v: u32 = kani::any();
1486        kani::assume(v < (1 << 20));
1487        let val: bool = kani::any();
1488        let lit = Lit::new(Var(v), val);
1489        assert_eq!(lit.var(), Var(v));
1490        assert_eq!(!lit.is_negative(), val);
1491        assert_eq!(!(!lit), lit);
1492
1493        let cref: usize = kani::any();
1494        kani::assume(cref <= CREF_MASK as usize);
1495        let binary: bool = kani::any();
1496        let w = Watcher::new(cref, lit, binary);
1497        assert_eq!(w.cref(), cref);
1498        assert_eq!(w.is_binary(), binary);
1499        assert_eq!(w.blocker, lit);
1500    }
1501
1502    #[kani::proof]
1503    #[kani::unwind(6)]
1504    fn kani_heap_order_and_invariants() {
1505        let a0: u8 = kani::any();
1506        let a1: u8 = kani::any();
1507        let a2: u8 = kani::any();
1508        let act = [f64::from(a0), f64::from(a1), f64::from(a2)];
1509        let mut h = Heap::default();
1510        h.insert(0, &act);
1511        h.insert(1, &act);
1512        h.insert(2, &act);
1513        let first = h.pop(&act).expect("3 items");
1514        let second = h.pop(&act).expect("2 items");
1515        let third = h.pop(&act).expect("1 item");
1516        assert!(h.pop(&act).is_none());
1517        // Strict deterministic order: highest activity first, lowest var on tie.
1518        assert!(Heap::before(first, second, &act));
1519        assert!(Heap::before(second, third, &act));
1520        assert!(first != second && second != third && first != third);
1521    }
1522}