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