Skip to main content

logicaffeine_proof/
cdcl.rs

1//! A conflict-driven clause-learning (CDCL) SAT core — the modern competition-grade
2//! engine, built to the lineage that made SAT practical: two-watched-literal unit
3//! propagation (Moskewicz et al., *Chaff*, 2001), first-UIP conflict analysis with
4//! learned clauses and non-chronological backtracking (Marques-Silva & Sakallah,
5//! *GRASP*, 1996), VSIDS-style activity decisions, and Luby restarts (Luby et al.,
6//! 1993). The clean reference implementation it follows is Eén & Sörensson's *MiniSat*
7//! (2003).
8//!
9//! This module is the propositional substrate of a **DPLL(T)** engine (Nieuwenhuis,
10//! Oliveras & Tinelli, JACM 2006): theory propagators (an AllDifferent GAC filter for
11//! grid categories, EUF, LIA, …) plug in through [`Theory`], and every learned clause is
12//! a resolvent the solver can log as a **DRAT/LRAT** proof step (Wetzler/Heule/Hunt,
13//! 2014; Cruz-Filipe et al., 2017) for a downstream linear checker.
14//!
15//! It is deliberately self-contained and value-typed (`Var = u32`, `Lit` a packed
16//! sign+index) so it can be exercised against a brute-force oracle in isolation before
17//! it is wired to the grid encoder — a SAT core is only as good as its cross-checks.
18
19use std::collections::{HashSet, VecDeque};
20
21/// A propositional variable: an index `0..num_vars`.
22pub type Var = u32;
23
24/// A literal: a variable plus a sign, packed as `var << 1 | negated`. Packing keeps the
25/// watch lists and the trail cache-dense, the way every fast solver stores them.
26#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
27pub struct Lit(u32);
28
29impl Lit {
30    /// The positive literal `+v`.
31    #[inline]
32    pub fn pos(v: Var) -> Lit {
33        Lit(v << 1)
34    }
35    /// The negative literal `¬v`.
36    #[inline]
37    pub fn neg(v: Var) -> Lit {
38        Lit((v << 1) | 1)
39    }
40    /// Build from a variable and a sign (`true` ⇒ positive).
41    #[inline]
42    pub fn new(v: Var, positive: bool) -> Lit {
43        if positive {
44            Lit::pos(v)
45        } else {
46            Lit::neg(v)
47        }
48    }
49    /// The underlying variable.
50    #[inline]
51    pub fn var(self) -> Var {
52        self.0 >> 1
53    }
54    /// Whether this is a positive literal.
55    #[inline]
56    pub fn is_positive(self) -> bool {
57        self.0 & 1 == 0
58    }
59    /// The complementary literal.
60    #[inline]
61    pub fn negated(self) -> Lit {
62        Lit(self.0 ^ 1)
63    }
64    /// The dense index for watch/seen arrays (`2*var + sign`).
65    #[inline]
66    fn index(self) -> usize {
67        self.0 as usize
68    }
69}
70
71/// A three-valued assignment cell.
72#[derive(Clone, Copy, PartialEq, Eq, Debug)]
73enum Val {
74    True,
75    False,
76    Unset,
77}
78
79/// Reason a variable was assigned, for the implication graph that conflict analysis
80/// walks. `Decision` is a branching guess; `Clause(ci)` means clause `ci` became unit
81/// and forced this literal (its other literals are all false, earlier on the trail).
82#[derive(Clone, Copy, Debug)]
83enum Reason {
84    Decision,
85    Clause(usize),
86}
87
88/// A watch-list entry: the clause being watched plus a *blocking literal* — one of the clause's
89/// other literals, cached inline. If the blocker is already true the clause is satisfied, so
90/// propagation skips it without dereferencing the clause at all (the cache-miss saver from
91/// Chaff/MiniSat). Purely an optimization: the verdict is unaffected.
92#[derive(Clone, Copy, Debug)]
93struct Watcher {
94    clause: usize,
95    blocker: Lit,
96    /// Whether the watched clause is binary. For a binary clause the blocker *is* the only other
97    /// literal, so when it is not already true the clause is immediately unit-or-conflict — decided
98    /// with no clause dereference at all (the implicit-binary trick from Kissat/CaDiCaL). Kept in sync
99    /// by watch (re)creation: strengthening always `unwatch`+`rewatch`es, and `reduce_db` rebuilds all
100    /// watches, so a binary flag is never stale against clause contents.
101    binary: bool,
102}
103
104/// The verdict of [`Solver::solve`].
105#[derive(Clone, PartialEq, Eq, Debug)]
106pub enum SolveResult {
107    /// Satisfiable, with a full model over `0..num_vars` (`true`/`false` per variable).
108    Sat(Vec<bool>),
109    /// Unsatisfiable.
110    Unsat,
111}
112
113/// The outcome of a conflict-budgeted solve: a verdict, or budget exhaustion (with the learned
114/// clauses left available for symmetric amplification).
115#[derive(Clone, PartialEq, Eq, Debug)]
116pub enum BudgetedResult {
117    /// Satisfiable, with a full model.
118    Sat(Vec<bool>),
119    /// Unsatisfiable (proven within budget).
120    Unsat,
121    /// The conflict budget was exhausted before a verdict; [`Solver::learned`] holds the clauses
122    /// derived so far.
123    Budget,
124}
125
126/// A learned clause logged for proof reconstruction. Each is a resolvent derivable from
127/// the formula by reverse unit propagation — the unit of a DRAT/LRAT proof. With proof tracing
128/// on ([`Solver::set_lrat`]) it carries its LRAT step: its id and the ids of the clauses that,
129/// in order, each become unit under its negation until the last conflicts.
130#[derive(Clone, Debug)]
131pub struct LearnedClause {
132    pub lits: Vec<Lit>,
133    pub id: u64,
134    pub hints: Vec<u64>,
135}
136
137/// A theory propagator (the DPLL(T) seam). The SAT core calls [`Theory::propagate`] at
138/// each fixpoint of Boolean propagation; a theory returns a fresh clause to add (an
139/// explanation/conflict) or `None` if it has nothing to say. AllDifferent GAC, EUF, and
140/// LIA all implement this without the core knowing the theory.
141pub trait Theory {
142    /// Given the solver's current `trail` (assigned literals in assignment order), return a clause
143    /// that is theory-entailed and currently unit or falsified (so the core will propagate or
144    /// conflict on it), or `None` at a theory fixpoint. The trail is passed in order — and shrinks
145    /// on backtrack — so an incremental theory can sync forward/undo against it (LIFO). The returned
146    /// clauses MUST each be a sound consequence of the theory. Returning the whole batch of forced
147    /// clauses at once (rather than one per call) lets an incremental theory amortise its work over
148    /// one pass instead of rescanning per implication. An empty vec means "theory fixpoint".
149    fn propagate(&mut self, trail: &[Lit]) -> Vec<Vec<Lit>>;
150}
151
152/// Glucose restart-policy constants (Audemard & Simon, 2012). `LBD_WINDOW` recent conflicts feed
153/// the fast average; `TRAIL_WINDOW` recent trail lengths feed the blocking average. A restart fires
154/// when `fast_lbd_avg * RESTART_K > global_lbd_avg`; it is *blocked* when the trail at conflict
155/// exceeds `BLOCK_R ×` the recent average (and at least `BLOCK_MIN_CONFLICTS` have passed).
156const LBD_WINDOW: usize = 50;
157const TRAIL_WINDOW: usize = 5000;
158const RESTART_K: f64 = 0.8;
159const BLOCK_R: f64 = 1.4;
160const BLOCK_MIN_CONFLICTS: u64 = 10_000;
161
162/// Adaptive restart phase length: the first phase spans `ADAPT_PHASE_BASE` conflicts, and each
163/// switch multiplies it by `PHASE_GROWTH`. The base is large enough that a small instance solves
164/// entirely inside the first (aggressive Glucose) phase — keeping Glucose's wins there — while a
165/// long search alternates into calm Luby phases that help SAT and Luby-favouring instances.
166const ADAPT_PHASE_BASE: u64 = 5000;
167const PHASE_GROWTH: f64 = 2.0;
168
169/// The restart heuristic. Glucose's dynamic LBD policy restarts when recent learned-clause quality
170/// (literal-block distance) degrades relative to the global average, and *blocks* a restart when
171/// the trail is unusually long — a sign the search is closing in on a model. Luby is the classic
172/// universal sequence (Luby et al., 1993). Adaptive alternates the two in geometrically growing
173/// phases (the CaDiCaL/Kissat "stabilizing / non-stabilizing" idea): aggressive Glucose restarts to
174/// EXPLORE, then calm Luby restarts to let phase-saving EXPLOIT and dig toward a model — capturing
175/// the strength of each and avoiding the per-instance losses of either alone. The choice is a pure
176/// search-ORDER heuristic: it never changes a verdict.
177#[derive(Clone, Copy, PartialEq, Eq, Debug)]
178pub enum RestartMode {
179    /// Alternate Glucose (non-stabilizing) and Luby (stabilizing) phases — the default.
180    Adaptive,
181    /// Dynamic LBD restarts with blocking — the Glucose lever.
182    Glucose,
183    /// The Luby universal restart sequence.
184    Luby,
185}
186
187/// The CDCL solver.
188pub struct Solver {
189    num_vars: usize,
190    /// All clauses (original + learned); a clause is a `Vec<Lit>`.
191    clauses: Vec<Vec<Lit>>,
192    /// Watch lists: for each literal, the [`Watcher`]s on it. Two-watched-literal scheme — a
193    /// clause is visited only when one of its two watched literals is falsified, and even then is
194    /// skipped without a dereference when its cached blocking literal is already true.
195    watches: Vec<Vec<Watcher>>,
196    /// Per-variable value.
197    value: Vec<Val>,
198    /// Per-variable decision level.
199    level: Vec<u32>,
200    /// Per-variable reason.
201    reason: Vec<Reason>,
202    /// The assignment trail (literals in assignment order).
203    trail: Vec<Lit>,
204    /// Index into `trail` where each decision level begins.
205    trail_lim: Vec<usize>,
206    /// Head of the propagation queue (index into `trail`).
207    qhead: usize,
208    /// VSIDS activities and the bump/decay.
209    activity: Vec<f64>,
210    var_inc: f64,
211    /// Phase saving: the last value each variable held before being unset by a backjump. A
212    /// decision reuses it, so the search sticks to assignments that previously propagated far —
213    /// the standard ~2-3× win on structured SAT. Purely a heuristic: it changes search ORDER,
214    /// never completeness, so verdicts are unaffected.
215    saved_phase: Vec<bool>,
216    /// Learned clauses, logged for proof output.
217    learned_log: Vec<LearnedClause>,
218    /// Scratch `seen` markers for conflict analysis (indexed by var).
219    seen: Vec<bool>,
220    /// Reusable redundancy memo for learned-clause minimization (indexed by var): `0` unknown, `1`
221    /// redundant, `2` not — solver-resident so `minimize` never allocates a per-conflict `HashMap`.
222    min_cache: Vec<u8>,
223    /// The vars whose `min_cache` entry was set this minimization, so only those are reset (not the
224    /// whole array) — the sparse-clear list that keeps minimization allocation-free.
225    min_touched: Vec<Var>,
226    /// Per-decision-level stamps for computing a learned clause's LBD without a per-conflict `Vec`
227    /// allocation or sort: a level is counted once when its stamp differs from the current generation.
228    lbd_stamp: Vec<u32>,
229    /// The current LBD-stamp generation, bumped once per conflict (wraps only after 2³² conflicts).
230    lbd_gen: u32,
231    /// Set once an empty clause is added — the formula is then trivially unsatisfiable.
232    empty_clause: bool,
233    /// Number of clauses present when the solve began (the original formula); clauses at
234    /// indices `>= n_original` are learned. Lets a downstream checker read the original
235    /// clauses without a separate copy.
236    n_original: usize,
237    /// Total conflicts encountered during the solve — the standard measure of search work,
238    /// the lever symmetry breaking is meant to collapse. Pure observability; never read by the
239    /// search itself, so it cannot change a verdict.
240    conflicts: u64,
241    /// Total decisions (branchings) — search work. Pure observability; never read by the search.
242    decisions: u64,
243    /// Total literals propagated by BCP (one per trail literal processed) — throughput work.
244    propagations: u64,
245    /// Total restarts performed — observability for the restart policy.
246    restarts: u64,
247    /// Per clause, whether the solver learned it (else it was added): what an incremental solve, whose added clauses
248    /// come between its learned ones, deletes from.
249    learned_flag: Vec<bool>,
250    /// How many clauses of the database are learned ones.
251    learned_live: usize,
252    /// Each clause's id: the caller's for a clause added with one, else the next free one.
253    clause_ids: Vec<u64>,
254    next_id: u64,
255    /// Whether each learned clause, and each refutation, records its LRAT hints.
256    lrat: bool,
257    /// The hints [`Solver::analyze`] found for the clause about to be learned.
258    pending_hints: Vec<u64>,
259    /// The hints of the last unsatisfiable solve's conclusion: the negation of its assumptions, or the empty clause.
260    unsat_hints: Vec<u64>,
261    /// The hints that derive the empty clause, once the formula has been found unsatisfiable at level 0.
262    empty_hints: Vec<u64>,
263    /// Per variable, its place on the trail while assigned.
264    trail_pos: Vec<u32>,
265    /// Per-clause LBD (literal-block distance, Audemard & Simon 2009): the number of distinct
266    /// decision levels among a learned clause's literals. Low LBD ("glue") clauses are the most
267    /// reusable; high-LBD clauses are the deletion candidates. Originals carry `u32::MAX`.
268    lbd: Vec<u32>,
269    /// Whether to periodically delete high-LBD learned clauses, keeping the database compact (the
270    /// Glucose lever). Verdict-invariant — deletion only removes redundant learned clauses; the
271    /// original formula and all locked/glue clauses are kept. Toggleable for A/B benchmarking.
272    reduce_enabled: bool,
273    /// The live-learned-clause count that triggers a reduction; grows after each reduction.
274    reduce_limit: usize,
275    /// If `Some`, decisions are restricted to variables flagged `true` (the rest are left to theory
276    /// propagation). DPLL(XOR) sets this to the non-pivot variables so search ranges only over the
277    /// GF(2) kernel; `None` means branch on any variable (ordinary CDCL).
278    decision_mask: Option<Vec<bool>>,
279    /// VSIDS order heap (MiniSat-style indexed binary max-heap): the next decision is the highest-
280    /// activity unassigned variable in O(log n), replacing the old O(n) activity scan — the dominant
281    /// throughput lever at scale. `heap_pos[v]` is v's index in `heap`, or -1 when absent.
282    heap: Vec<Var>,
283    heap_pos: Vec<i32>,
284    /// The restart heuristic in force (default [`RestartMode::Glucose`]).
285    restart_mode: RestartMode,
286    /// Glucose fast window: the LBDs of the most recent `LBD_WINDOW` conflicts, with their running
287    /// sum, for the dynamic restart trigger.
288    lbd_fast: VecDeque<u32>,
289    lbd_fast_sum: u64,
290    /// Sum of every conflict's LBD over the whole solve — the global average's numerator (its
291    /// denominator is `conflicts`).
292    lbd_global_sum: u64,
293    /// Glucose blocking window: the trail lengths at the most recent `TRAIL_WINDOW` conflicts, with
294    /// their running sum, for the blocking-restart "we look close to a model" test.
295    trail_fast: VecDeque<usize>,
296    trail_fast_sum: u64,
297    /// Restarts suppressed by the blocking heuristic. Pure observability.
298    blocked_restarts: u64,
299    /// Learned clauses strengthened by vivification. Pure observability.
300    vivifications: u64,
301    /// Units derived by failed-literal probing. Pure observability.
302    probes: u64,
303    /// Learned clauses deleted or strengthened by subsumption / self-subsuming resolution. Pure
304    /// observability.
305    subsumptions: u64,
306    /// Whether to run the level-0 inprocessing schedule (probe + vivify + rephase) between
307    /// restarts during a long search. Default on; toggleable for A/B benchmarking. Verdict-invariant
308    /// either way.
309    inprocess_enabled: bool,
310    /// Conflicts between inprocessing rounds (default [`INPROCESS_INTERVAL`]). Tunable for
311    /// benchmarking and tests.
312    inprocess_interval: u64,
313    /// Whether probing is still worth running this solve. Set false after a probing round derives no
314    /// unit — on most instances probing finds nothing, so it would otherwise be pure overhead. Reset
315    /// at each top-level solve.
316    probe_active: bool,
317    /// Restart bookkeeping, solver-resident so the adaptive phase machinery can reset it cleanly:
318    /// conflicts since the last restart, the current Luby limit, and the Luby step index.
319    csr: u64,
320    restart_limit: u64,
321    restart_no: u64,
322    /// Adaptive restart phase: `stabilizing` = the calm (Luby) phase vs the aggressive (Glucose)
323    /// phase; `phase_start` is the conflict count when the current phase began; `phase_len` is its
324    /// length, grown by [`PHASE_GROWTH`] each switch.
325    stabilizing: bool,
326    phase_start: u64,
327    phase_len: u64,
328}
329
330/// Conflicts before the FIRST inprocessing round — high enough that short searches never inprocess
331/// (their churn can cost more than it saves), so the schedule engages only on the genuinely long
332/// solves where it pays off. Measured: at 2000 a couple of short random instances regress; at 6000
333/// every tested instance is regression-free while the long-search wins (PHP, gt18, hard random)
334/// are kept. Subsequent rounds back off by [`INPROCESS_GROWTH`].
335const INPROCESS_INTERVAL: u64 = 6000;
336/// Per-round caps so an inprocessing pass stays cheap relative to search.
337const PROBE_BUDGET: usize = 256;
338const VIVIFY_BUDGET: usize = 400;
339const SUBSUME_BUDGET: usize = 600;
340/// Each inprocessing round multiplies the conflicts-until-next-round by this factor, so a long
341/// search inprocesses often early then rarely — bounding total inprocessing cost (and the churn it
342/// can cost on instances where it does not pay off).
343const INPROCESS_GROWTH: f64 = 1.5;
344
345impl Solver {
346    /// A fresh solver over `num_vars` variables and no clauses.
347    pub fn new(num_vars: usize) -> Self {
348        Solver {
349            num_vars,
350            clauses: Vec::new(),
351            watches: vec![Vec::new(); num_vars * 2],
352            value: vec![Val::Unset; num_vars],
353            level: vec![0; num_vars],
354            reason: vec![Reason::Decision; num_vars],
355            trail: Vec::new(),
356            trail_lim: Vec::new(),
357            qhead: 0,
358            activity: vec![0.0; num_vars],
359            var_inc: 1.0,
360            saved_phase: vec![false; num_vars],
361            learned_log: Vec::new(),
362            seen: vec![false; num_vars],
363            min_cache: vec![0u8; num_vars],
364            min_touched: Vec::new(),
365            lbd_stamp: vec![0u32; num_vars + 1],
366            lbd_gen: 0,
367            empty_clause: false,
368            n_original: 0,
369            conflicts: 0,
370            decisions: 0,
371            propagations: 0,
372            restarts: 0,
373            lbd: Vec::new(),
374            learned_flag: Vec::new(),
375            learned_live: 0,
376            clause_ids: Vec::new(),
377            next_id: 1,
378            lrat: false,
379            pending_hints: Vec::new(),
380            unsat_hints: Vec::new(),
381            empty_hints: Vec::new(),
382            trail_pos: vec![0; num_vars],
383            reduce_enabled: true,
384            reduce_limit: 2000,
385            decision_mask: None,
386            heap: (0..num_vars as Var).collect(),
387            heap_pos: (0..num_vars as i32).collect(),
388            restart_mode: RestartMode::Adaptive,
389            lbd_fast: VecDeque::with_capacity(LBD_WINDOW + 1),
390            lbd_fast_sum: 0,
391            lbd_global_sum: 0,
392            trail_fast: VecDeque::with_capacity(TRAIL_WINDOW + 1),
393            trail_fast_sum: 0,
394            blocked_restarts: 0,
395            vivifications: 0,
396            probes: 0,
397            subsumptions: 0,
398            inprocess_enabled: true,
399            inprocess_interval: INPROCESS_INTERVAL,
400            probe_active: true,
401            csr: 0,
402            restart_limit: luby(1) * 100,
403            restart_no: 1,
404            stabilizing: false,
405            phase_start: 0,
406            phase_len: ADAPT_PHASE_BASE,
407        }
408    }
409
410    /// Run one subsumption + self-subsuming-resolution round over the learned clauses (Phase 4
411    /// inprocessing). Returns `false` if it proves the formula UNSAT. Verdict-invariant.
412    pub fn subsume(&mut self) -> bool {
413        self.subsume_round(0)
414    }
415
416    /// Learned clauses deleted or strengthened by subsumption during this solver's life.
417    pub fn subsumptions(&self) -> u64 {
418        self.subsumptions
419    }
420
421    /// Enable or disable the between-restart inprocessing schedule (default on). For A/B
422    /// benchmarking; verdict-invariant either way.
423    pub fn set_inprocess(&mut self, on: bool) {
424        self.inprocess_enabled = on;
425    }
426
427    /// Set the conflict interval between inprocessing rounds (default `INPROCESS_INTERVAL`).
428    /// Tuning / test knob; verdict-invariant.
429    pub fn set_inprocess_interval(&mut self, conflicts: u64) {
430        self.inprocess_interval = conflicts.max(1);
431    }
432
433    /// Run one vivification round over the learned clauses, strengthening each shortenable clause
434    /// in place (Phase 2 inprocessing). Returns `false` if vivification proves the formula UNSAT.
435    /// Verdict-invariant; intended to be scheduled at decision level 0 between restarts.
436    pub fn vivify(&mut self) -> bool {
437        self.vivify_round(0)
438    }
439
440    /// Learned clauses strengthened by vivification during this solver's life. Pure observability.
441    pub fn vivifications(&self) -> u64 {
442        self.vivifications
443    }
444
445    /// Run one failed-literal probing round (Phase 3 inprocessing): try each phase of each free
446    /// variable as a level-0 assumption; if propagation conflicts, the opposite literal is a forced
447    /// unit, learned permanently. Returns `false` if probing proves the formula UNSAT.
448    /// Verdict-invariant; scheduled at decision level 0.
449    pub fn probe(&mut self) -> bool {
450        self.probe_round(0)
451    }
452
453    /// Units derived by failed-literal probing during this solver's life. Pure observability.
454    pub fn probes(&self) -> u64 {
455        self.probes
456    }
457
458    /// Select the restart heuristic (default [`RestartMode::Glucose`]). Search-order only — a
459    /// verdict is unaffected, so this is for A/B tuning.
460    pub fn set_restart_mode(&mut self, mode: RestartMode) {
461        self.restart_mode = mode;
462    }
463
464    /// The restart heuristic in force.
465    pub fn restart_mode(&self) -> RestartMode {
466        self.restart_mode
467    }
468
469    /// Restarts suppressed by Glucose blocking during the last solve.
470    pub fn blocked_restarts(&self) -> u64 {
471        self.blocked_restarts
472    }
473
474    /// Record a conflict's LBD and the trail length at the moment of conflict, updating the Glucose
475    /// fast and blocking windows. If the trail was much longer than the recent average, empty the
476    /// fast LBD window — that defers the next dynamic restart (the blocking heuristic: a long trail
477    /// means a promising branch). Pure heuristic state; never affects a verdict. Call once per
478    /// conflict, before `conflicts` is incremented.
479    fn note_conflict(&mut self, lbd: u32, trail_at_conflict: usize) {
480        self.lbd_global_sum += u64::from(lbd);
481        self.lbd_fast.push_back(lbd);
482        self.lbd_fast_sum += u64::from(lbd);
483        if self.lbd_fast.len() > LBD_WINDOW {
484            self.lbd_fast_sum -= u64::from(self.lbd_fast.pop_front().unwrap());
485        }
486        self.trail_fast.push_back(trail_at_conflict);
487        self.trail_fast_sum += trail_at_conflict as u64;
488        if self.trail_fast.len() > TRAIL_WINDOW {
489            self.trail_fast_sum -= self.trail_fast.pop_front().unwrap() as u64;
490        }
491        if self.conflicts >= BLOCK_MIN_CONFLICTS
492            && self.lbd_fast.len() >= LBD_WINDOW
493            && (trail_at_conflict as f64)
494                > BLOCK_R * (self.trail_fast_sum as f64 / self.trail_fast.len() as f64)
495        {
496            self.lbd_fast.clear();
497            self.lbd_fast_sum = 0;
498            self.blocked_restarts += 1;
499        }
500    }
501
502    /// The Glucose dynamic-restart trigger: the fast-window LBD average has degraded past
503    /// `RESTART_K ×` the global average. Fires only once the fast window is full (and is emptied by
504    /// blocking, which is how a block suppresses the next restart).
505    fn glucose_should_restart(&self) -> bool {
506        if self.lbd_fast.len() < LBD_WINDOW || self.conflicts == 0 {
507            return false;
508        }
509        let fast = self.lbd_fast_sum as f64 / self.lbd_fast.len() as f64;
510        let global = self.lbd_global_sum as f64 / self.conflicts as f64;
511        fast * RESTART_K > global
512    }
513
514    /// Reset all restart bookkeeping for a fresh top-level solve (Luby counter, Glucose windows, and
515    /// the adaptive phase, which starts in the aggressive Glucose phase).
516    fn reset_restart_state(&mut self) {
517        self.csr = 0;
518        self.restart_limit = luby(1) * 100;
519        self.restart_no = 1;
520        self.stabilizing = false;
521        self.phase_start = self.conflicts;
522        self.phase_len = ADAPT_PHASE_BASE;
523        self.lbd_fast.clear();
524        self.lbd_fast_sum = 0;
525    }
526
527    /// In Adaptive mode, switch between the aggressive (Glucose) and calm (Luby) phases once the
528    /// current phase's conflict budget is spent, growing the next phase and resetting both policies'
529    /// trigger state so neither carries a stale signal across the boundary. No-op in fixed modes.
530    fn advance_restart_phase(&mut self) {
531        if self.restart_mode != RestartMode::Adaptive {
532            return;
533        }
534        if self.conflicts - self.phase_start >= self.phase_len {
535            self.stabilizing = !self.stabilizing;
536            self.phase_start = self.conflicts;
537            self.phase_len = ((self.phase_len as f64) * PHASE_GROWTH) as u64;
538            self.csr = 0;
539            self.restart_no = 1;
540            self.restart_limit = luby(1) * 100;
541            self.lbd_fast.clear();
542            self.lbd_fast_sum = 0;
543        }
544    }
545
546    /// Whether to restart now, per the active policy. Adaptive consults Glucose in its aggressive
547    /// phase and Luby in its calm (stabilizing) phase.
548    fn want_restart(&self) -> bool {
549        match self.restart_mode {
550            RestartMode::Glucose => self.glucose_should_restart(),
551            RestartMode::Luby => self.csr >= self.restart_limit,
552            RestartMode::Adaptive => {
553                if self.stabilizing {
554                    self.csr >= self.restart_limit
555                } else {
556                    self.glucose_should_restart()
557                }
558            }
559        }
560    }
561
562    /// Perform a restart: jump to level 0, advance the Luby counter, and reset the Glucose fast
563    /// window so the next trigger measures freshly.
564    fn do_restart(&mut self) {
565        self.backtrack_to(0);
566        self.csr = 0;
567        self.restarts += 1;
568        self.restart_no += 1;
569        self.restart_limit = luby(self.restart_no) * 100;
570        self.lbd_fast.clear();
571        self.lbd_fast_sum = 0;
572    }
573
574    /// Restrict branching to `vars` (DPLL(XOR): the engine's non-pivot variables; the theory forces
575    /// the rest). A model is still complete because theory propagation assigns every excluded
576    /// variable before all decision variables are exhausted.
577    /// Grow the solver by `k` fresh variables, numbered after those it has, and return the first one's number: each
578    /// unassigned and unconstrained, a decision variable unless a decision set restricts them (one then joins it by
579    /// [`Solver::add_decision_vars`]). A user that encodes a formula a part at a time numbers its variables densely
580    /// as it goes, so a solver is as large as what it was asked.
581    pub fn add_vars(&mut self, k: usize) -> usize {
582        let first = self.num_vars;
583        let n = first + k;
584        self.num_vars = n;
585        self.watches.resize(n * 2, Vec::new());
586        self.value.resize(n, Val::Unset);
587        self.level.resize(n, 0);
588        self.reason.resize(n, Reason::Decision);
589        self.activity.resize(n, 0.0);
590        self.saved_phase.resize(n, false);
591        self.seen.resize(n, false);
592        self.min_cache.resize(n, 0);
593        self.lbd_stamp.resize(n + 1, 0);
594        self.trail_pos.resize(n, 0);
595        self.heap_pos.resize(n, -1);
596        match self.decision_mask.as_mut() {
597            Some(mask) => mask.resize(n, false),
598            None => {
599                for v in first..n {
600                    self.heap_insert(v as Var);
601                }
602            }
603        }
604        first
605    }
606
607    /// Add `vars` to the variables decisions fall on, beside those already there: an incremental user grows the set as
608    /// it adds the clauses that constrain them. Without a set yet, every variable is one already. Out-of-range and
609    /// repeated variables are ignored.
610    pub fn add_decision_vars(&mut self, vars: &[usize]) {
611        let Some(mask) = self.decision_mask.as_mut() else { return };
612        let mut joined: Vec<usize> = Vec::new();
613        for &v in vars {
614            if v < self.num_vars && !mask[v] {
615                mask[v] = true;
616                joined.push(v);
617            }
618        }
619        for v in joined {
620            if self.value[v] == Val::Unset {
621                self.heap_insert(v as Var);
622            }
623        }
624    }
625
626    pub fn set_decision_vars(&mut self, vars: &[usize]) {
627        let mut mask = vec![false; self.num_vars];
628        for &v in vars {
629            if v < self.num_vars {
630                mask[v] = true;
631            }
632        }
633        self.decision_mask = Some(mask);
634        // Rebuild the order heap to hold only the decision candidates.
635        self.heap.clear();
636        self.heap_pos = vec![-1; self.num_vars];
637        for &v in vars {
638            if v < self.num_vars && self.heap_pos[v] < 0 {
639                self.heap_pos[v] = self.heap.len() as i32;
640                self.heap.push(v as Var);
641            }
642        }
643        for i in (0..self.heap.len() / 2).rev() {
644            self.sift_down(i);
645        }
646    }
647
648    // --- VSIDS order heap (indexed binary max-heap on `activity`) ---
649
650    fn heap_swap(&mut self, i: usize, j: usize) {
651        self.heap.swap(i, j);
652        self.heap_pos[self.heap[i] as usize] = i as i32;
653        self.heap_pos[self.heap[j] as usize] = j as i32;
654    }
655
656    fn sift_up(&mut self, mut i: usize) {
657        while i > 0 {
658            let p = (i - 1) / 2;
659            if self.activity[self.heap[i] as usize] > self.activity[self.heap[p] as usize] {
660                self.heap_swap(i, p);
661                i = p;
662            } else {
663                break;
664            }
665        }
666    }
667
668    fn sift_down(&mut self, mut i: usize) {
669        let n = self.heap.len();
670        loop {
671            let (l, r) = (2 * i + 1, 2 * i + 2);
672            let mut m = i;
673            if l < n && self.activity[self.heap[l] as usize] > self.activity[self.heap[m] as usize]
674            {
675                m = l;
676            }
677            if r < n && self.activity[self.heap[r] as usize] > self.activity[self.heap[m] as usize]
678            {
679                m = r;
680            }
681            if m == i {
682                break;
683            }
684            self.heap_swap(i, m);
685            i = m;
686        }
687    }
688
689    /// Insert `v` (idempotent: a no-op if already present).
690    fn heap_insert(&mut self, v: Var) {
691        if self.heap_pos[v as usize] >= 0 {
692            return;
693        }
694        let i = self.heap.len();
695        self.heap.push(v);
696        self.heap_pos[v as usize] = i as i32;
697        self.sift_up(i);
698    }
699
700    /// Remove and return the highest-activity variable, or `None` if empty.
701    fn heap_pop(&mut self) -> Option<Var> {
702        if self.heap.is_empty() {
703            return None;
704        }
705        let top = self.heap[0];
706        self.heap_pos[top as usize] = -1;
707        let last = self.heap.pop().unwrap();
708        if !self.heap.is_empty() {
709            self.heap[0] = last;
710            self.heap_pos[last as usize] = 0;
711            self.sift_down(0);
712        }
713        Some(top)
714    }
715
716    /// Restore the heap after `v`'s activity rose (it can only move toward the root).
717    fn heap_increase(&mut self, v: Var) {
718        let i = self.heap_pos[v as usize];
719        if i >= 0 {
720            self.sift_up(i as usize);
721        }
722    }
723
724    /// Total conflicts during the last solve — the search-work metric.
725    pub fn conflicts(&self) -> u64 {
726        self.conflicts
727    }
728
729    /// Total decisions during the last solve.
730    pub fn decisions(&self) -> u64 {
731        self.decisions
732    }
733
734    /// Total BCP propagations during the last solve — the throughput metric.
735    pub fn propagations(&self) -> u64 {
736        self.propagations
737    }
738
739    /// Total restarts during the last solve.
740    pub fn restarts(&self) -> u64 {
741        self.restarts
742    }
743
744    /// Enable or disable LBD-based learned-clause deletion (default on). For A/B benchmarking.
745    pub fn set_reduce(&mut self, on: bool) {
746        self.reduce_enabled = on;
747    }
748
749    /// Set the live-learned-clause count that triggers a reduction (tuning / stress-testing).
750    pub fn set_reduce_limit(&mut self, limit: usize) {
751        self.reduce_limit = limit.max(1);
752    }
753
754    /// Seed the saved-phase polarities (the order decisions try first) from an external assignment.
755    /// Purely a search-order hint — it never changes which models exist, so it cannot affect the
756    /// verdict — but starting decisions on, e.g., a GF(2)-consistent assignment lets the hybrid XOR
757    /// route begin on the linear system's solution manifold and only repair the residual clauses.
758    pub fn set_initial_phase(&mut self, phases: &[bool]) {
759        for (v, &p) in phases.iter().enumerate().take(self.num_vars) {
760            self.saved_phase[v] = p;
761        }
762    }
763
764    /// The number of learned clauses currently live in the database (originals excluded).
765    pub fn live_learned(&self) -> usize {
766        self.clauses.len().saturating_sub(self.n_original)
767    }
768
769    /// The learned clauses produced during the last solve (the DRAT/LRAT proof skeleton).
770    pub fn learned(&self) -> &[LearnedClause] {
771        &self.learned_log
772    }
773
774    /// The learned clauses since the last take, moved out: a caller that keeps its own proof log takes each once, so
775    /// the solver does not hold every one for its whole life.
776    pub fn take_learned(&mut self) -> Vec<LearnedClause> {
777        std::mem::take(&mut self.learned_log)
778    }
779
780    /// The ids of the clauses the database holds. A hint a later solve gives names one of these or a clause it learned
781    /// since, so a proof log may forget whatever none of them rests on.
782    pub fn live_ids(&self) -> &[u64] {
783        &self.clause_ids
784    }
785
786    /// The ORIGINAL clauses (those present before solving), borrowed in place — so a RUP
787    /// checker can replay over them without copying the clause set.
788    pub fn original_clauses(&self) -> &[Vec<Lit>] {
789        &self.clauses[..self.n_original]
790    }
791
792    /// Add a clause. An empty clause makes the formula trivially unsatisfiable; a unit
793    /// clause is enqueued as a top-level fact. Between incremental solves the search is
794    /// dropped first and the clause read against the level-0 facts: its literals not yet
795    /// false lead, so the two it watches are ones that can still become false; one left is a
796    /// fact enqueued now, none left makes the formula unsatisfiable.
797    pub fn add_clause(&mut self, lits: Vec<Lit>) {
798        let id = self.next_id;
799        self.add_clause_with_id(lits, id);
800    }
801
802    /// [`Solver::add_clause`] with the id the clause's hints name it by chosen by the caller, above every id before it.
803    /// A tautology is dropped and its id left unused.
804    pub fn add_clause_with_id(&mut self, mut lits: Vec<Lit>, id: u64) {
805        self.next_id = self.next_id.max(id + 1);
806        // Dedup and drop a clause that is already a tautology (`v ∨ ¬v`).
807        lits.sort_by_key(|l| l.0);
808        lits.dedup();
809        for w in lits.windows(2) {
810            if w[0].var() == w[1].var() {
811                // contains both polarities of some var → tautology, skip
812                return;
813            }
814        }
815        self.backtrack_to(0);
816        if lits.len() >= 2 {
817            lits.sort_by_key(|&l| self.lit_false(l));
818            let open = lits.iter().filter(|&&l| !self.lit_false(l)).count();
819            if open <= 1 {
820                let ci = self.store(lits.clone(), false, id, Vec::new());
821                match lits.first() {
822                    Some(&l) if open == 1 && self.val_of(l) == Val::Unset => self.enqueue(l, Reason::Clause(ci)),
823                    Some(&l) if open == 1 && self.lit_true(l) => {}
824                    _ => self.found_empty(ci),
825                }
826                return;
827            }
828        }
829        self.store(lits, false, id, Vec::new());
830    }
831
832    /// Number the clauses the solver makes from `id` on (when that is above every id it has used): a caller that gives
833    /// its own clauses ids from another range keeps the two apart.
834    pub fn set_next_clause_id(&mut self, id: u64) {
835        self.next_id = self.next_id.max(id);
836    }
837
838    /// The next clause id, taken: one a caller gives a clause it derives itself.
839    pub fn next_clause_id(&mut self) -> u64 {
840        self.next_id += 1;
841        self.next_id - 1
842    }
843
844    /// Record LRAT hints: each learned clause's, and each refutation's (see [`Solver::unsat_hints`]). For pure CNF
845    /// solving: inprocessing, which strengthens clauses without a chain, is turned off, and a theory's clauses carry
846    /// none.
847    pub fn set_lrat(&mut self, on: bool) {
848        self.lrat = on;
849        if on {
850            self.inprocess_enabled = false;
851        }
852    }
853
854    /// After an unsatisfiable solve under assumptions, with tracing on: the hints of the clause of the assumptions'
855    /// negations (the empty clause's when the formula itself is unsatisfiable), each id in order a clause that is unit
856    /// under that clause's negation, the last conflicting.
857    pub fn unsat_hints(&self) -> &[u64] {
858        &self.unsat_hints
859    }
860
861    /// The trail-ordered reasons (by clause index) of every variable that `vars` lean on: each of them and, through its
862    /// reason, every variable that reason's other literals hold, stopping at decisions and at level-0 facts, each of
863    /// which its unit clause stands for ([`Solver::unit_of`]).
864    fn cone(&mut self, vars: impl IntoIterator<Item = Var>) -> Vec<usize> {
865        let mut stack: Vec<Var> = vars.into_iter().collect();
866        let mut visited: HashSet<Var> = HashSet::new();
867        let mut found: Vec<(u32, usize)> = Vec::new();
868        while let Some(v) = stack.pop() {
869            if !visited.insert(v) || self.value[v as usize] == Val::Unset {
870                continue;
871            }
872            if self.level[v as usize] == 0 {
873                if let Some(ci) = self.unit_of(v) {
874                    found.push((self.trail_pos[v as usize], ci));
875                }
876                continue;
877            }
878            if let Reason::Clause(ci) = self.reason[v as usize] {
879                found.push((self.trail_pos[v as usize], ci));
880                stack.extend(self.clauses[ci].iter().map(|l| l.var()).filter(|&w| w != v));
881            }
882        }
883        found.sort_unstable();
884        found.into_iter().map(|(_, ci)| ci).collect()
885    }
886
887    /// The database index of the unit clause of the level-0 fact on `v`, derived the first time a chain needs it: the
888    /// units of its reason's other literals (each false at level 0), then the reason. It is logged as a learned clause
889    /// and kept as a permanent one, `v`'s reason from then on, so a later chain names the fact by one hint and not by
890    /// everything level 0 derived it from. `None` for a fact with no reason.
891    fn unit_of(&mut self, v: Var) -> Option<usize> {
892        let long = |s: &Solver, w: Var| matches!(s.reason[w as usize], Reason::Clause(ci) if s.clauses[ci].len() > 1);
893        let mut stack: Vec<(Var, bool)> = vec![(v, false)];
894        while let Some((u, ready)) = stack.pop() {
895            let Reason::Clause(ci) = self.reason[u as usize] else { continue };
896            if self.clauses[ci].len() == 1 {
897                continue;
898            }
899            if !ready {
900                stack.push((u, true));
901                for k in 0..self.clauses[ci].len() {
902                    let w = self.clauses[ci][k].var();
903                    if w != u && long(self, w) {
904                        stack.push((w, false));
905                    }
906                }
907                continue;
908            }
909            let mut hints: Vec<u64> = Vec::with_capacity(self.clauses[ci].len());
910            for l in &self.clauses[ci] {
911                if let (true, Reason::Clause(cj)) = (l.var() != u, self.reason[l.var() as usize]) {
912                    hints.push(self.clause_ids[cj]);
913                }
914            }
915            hints.push(self.clause_ids[ci]);
916            let fact = Lit::new(u, self.value[u as usize] == Val::True);
917            let id = self.next_clause_id();
918            self.learned_log.push(LearnedClause { lits: vec![fact], id, hints });
919            let unit = self.store(vec![fact], false, id, Vec::new());
920            self.reason[u as usize] = Reason::Clause(unit);
921        }
922        match self.reason[v as usize] {
923            Reason::Clause(ci) => Some(ci),
924            Reason::Decision => None,
925        }
926    }
927
928    /// [`Solver::cone`]'s clause ids.
929    fn cone_hints(&mut self, vars: impl IntoIterator<Item = Var>) -> Vec<u64> {
930        self.cone(vars).into_iter().map(|ci| self.clause_ids[ci]).collect()
931    }
932
933    /// The hints of `clause` from `reasons` (clause indices in trail order): replayed under its negation, each reason
934    /// a unit is kept, one already satisfied is dropped, and the first that conflicts ends the chain. The negation of
935    /// a set of assumptions can contradict a level-0 fact before the reason the solver found it by.
936    fn replayed(&self, clause: &[Lit], reasons: &[usize]) -> Vec<u64> {
937        let mut assign: std::collections::HashMap<Var, bool> = clause.iter().map(|l| (l.var(), !l.is_positive())).collect();
938        let truth = |assign: &std::collections::HashMap<Var, bool>, l: Lit| assign.get(&l.var()).map(|&v| v == l.is_positive());
939        let mut hints = Vec::new();
940        for &ci in reasons {
941            let mut open: Option<Lit> = None;
942            let mut satisfied = false;
943            let mut several = false;
944            for &l in &self.clauses[ci] {
945                match truth(&assign, l) {
946                    Some(true) => satisfied = true,
947                    Some(false) => {}
948                    None if open.is_none() || open == Some(l) => open = Some(l),
949                    None => several = true,
950                }
951            }
952            if satisfied {
953                continue;
954            }
955            hints.push(self.clause_ids[ci]);
956            match open {
957                None => return hints,
958                Some(_) if several => return reasons.iter().map(|&ci| self.clause_ids[ci]).collect(),
959                Some(u) => {
960                    assign.insert(u.var(), u.is_positive());
961                }
962            }
963        }
964        hints
965    }
966
967    /// The formula is unsatisfiable at level 0, clause `ci` false there: the empty clause's hints are the units of its
968    /// literals' level-0 facts, then it.
969    fn found_empty(&mut self, ci: usize) {
970        self.empty_clause = true;
971        if self.lrat && self.empty_hints.is_empty() {
972            let vars: Vec<Var> = self.clauses[ci].iter().map(|l| l.var()).collect();
973            let mut hints = self.cone_hints(vars);
974            hints.push(self.clause_ids[ci]);
975            self.empty_hints = hints;
976        }
977    }
978
979    /// Internal: register a clause under the next free id and set up its two watches. `learned`
980    /// clauses are also logged, with the hints [`Solver::analyze`] left. Returns the clause index.
981    fn add_clause_raw(&mut self, lits: Vec<Lit>, learned: bool) -> usize {
982        let id = self.next_clause_id();
983        let hints = if learned { std::mem::take(&mut self.pending_hints) } else { Vec::new() };
984        self.store(lits, learned, id, hints)
985    }
986
987    /// Register a clause with its id and hints and set up its two watches.
988    fn store(&mut self, lits: Vec<Lit>, learned: bool, id: u64, hints: Vec<u64>) -> usize {
989        let ci = self.clauses.len();
990        self.clause_ids.push(id);
991        // Keep the per-clause LBD vector aligned with `clauses` (grows by exactly one here).
992        // Originals/units default to `u32::MAX` (never deleted); the caller overwrites a learned
993        // clause's slot with its real LBD.
994        self.lbd.push(u32::MAX);
995        self.learned_flag.push(learned);
996        self.learned_live += learned as usize;
997        if learned {
998            self.learned_log.push(LearnedClause { lits: lits.clone(), id, hints });
999        }
1000        if lits.is_empty() {
1001            self.clauses.push(lits);
1002            self.found_empty(ci);
1003            return ci;
1004        }
1005        if lits.len() == 1 {
1006            let l = lits[0];
1007            self.clauses.push(lits);
1008            // A unit clause forces its literal. If it is already FALSE on the trail, the
1009            // formula is unsatisfiable (a top-level conflict); if already true, nothing to
1010            // do; else enqueue it.
1011            match self.val_of(l) {
1012                Val::True => {}
1013                Val::False => self.found_empty(ci),
1014                Val::Unset => self.enqueue(l, Reason::Clause(ci)),
1015            }
1016            return ci;
1017        }
1018        // Watch the first two literals, each blocked by the other.
1019        let (w0, w1) = (lits[0], lits[1]);
1020        let bin = lits.len() == 2;
1021        self.watches[w0.index()].push(Watcher {
1022            clause: ci,
1023            blocker: w1,
1024            binary: bin,
1025        });
1026        self.watches[w1.index()].push(Watcher {
1027            clause: ci,
1028            blocker: w0,
1029            binary: bin,
1030        });
1031        self.clauses.push(lits);
1032        ci
1033    }
1034
1035    #[inline]
1036    fn val_of(&self, l: Lit) -> Val {
1037        match self.value[l.var() as usize] {
1038            Val::Unset => Val::Unset,
1039            v => {
1040                if l.is_positive() {
1041                    v
1042                } else {
1043                    match v {
1044                        Val::True => Val::False,
1045                        Val::False => Val::True,
1046                        Val::Unset => Val::Unset,
1047                    }
1048                }
1049            }
1050        }
1051    }
1052
1053    #[inline]
1054    fn lit_true(&self, l: Lit) -> bool {
1055        self.val_of(l) == Val::True
1056    }
1057    #[inline]
1058    fn lit_false(&self, l: Lit) -> bool {
1059        self.val_of(l) == Val::False
1060    }
1061
1062    /// Assign `l` true with the given reason, push it on the trail. Assumes `l` is currently
1063    /// unset (callers check).
1064    fn enqueue(&mut self, l: Lit, r: Reason) {
1065        let v = l.var() as usize;
1066        self.value[v] = if l.is_positive() {
1067            Val::True
1068        } else {
1069            Val::False
1070        };
1071        self.level[v] = self.trail_lim.len() as u32;
1072        self.reason[v] = r;
1073        self.trail_pos[v] = self.trail.len() as u32;
1074        self.trail.push(l);
1075    }
1076
1077    /// Two-watched-literal unit propagation. Returns the index of a conflicting clause, or
1078    /// `None` at a Boolean fixpoint.
1079    fn propagate(&mut self) -> Option<usize> {
1080        while self.qhead < self.trail.len() {
1081            let p = self.trail[self.qhead];
1082            self.qhead += 1;
1083            self.propagations += 1;
1084            // Clauses watching ¬p may have become unit/false.
1085            let false_lit = p.negated();
1086            let mut wi = 0;
1087            // Take the watch list out to satisfy the borrow checker; we rebuild it.
1088            let mut watchers = std::mem::take(&mut self.watches[false_lit.index()]);
1089            'next_clause: while wi < watchers.len() {
1090                // Blocking literal: if it is already true, the clause is satisfied — skip it
1091                // without dereferencing the clause (the cache-miss saver).
1092                if self.lit_true(watchers[wi].blocker) {
1093                    wi += 1;
1094                    continue;
1095                }
1096                // Binary clause: the blocker is the *only* other literal and it is not true, so the
1097                // clause is immediately unit (blocker unassigned) or a conflict (blocker false) — with
1098                // no clause dereference at all. The bulk of a mature learned database is binary, so this
1099                // is a real BCP win, and it is exact.
1100                if watchers[wi].binary {
1101                    let other = watchers[wi].blocker;
1102                    let ci = watchers[wi].clause;
1103                    if self.lit_false(other) {
1104                        self.watches[false_lit.index()] = watchers;
1105                        return Some(ci);
1106                    }
1107                    self.enqueue(other, Reason::Clause(ci));
1108                    wi += 1;
1109                    continue;
1110                }
1111                let ci = watchers[wi].clause;
1112                let clause_len = self.clauses[ci].len();
1113                // Ensure the watched literal we keep is in slot 0/1; make slot 1 = false_lit.
1114                if self.clauses[ci][0] == false_lit {
1115                    self.clauses[ci].swap(0, 1);
1116                }
1117                // Slot 0 is the other watched literal; refresh it as this watch's blocker.
1118                let other = self.clauses[ci][0];
1119                watchers[wi].blocker = other;
1120                // If it is already satisfied, the clause is fine — keep watching false_lit.
1121                if self.lit_true(other) {
1122                    wi += 1;
1123                    continue;
1124                }
1125                // Look for a new, non-false literal to watch (slots 2..).
1126                for k in 2..clause_len {
1127                    let lk = self.clauses[ci][k];
1128                    if !self.lit_false(lk) {
1129                        // Move lk into slot 1, watch it (blocked by `other`), drop this watch.
1130                        self.clauses[ci].swap(1, k);
1131                        // This path only fires for clauses with a third literal to move to, so the
1132                        // clause is never binary here (`clause_len >= 3`).
1133                        self.watches[lk.index()].push(Watcher {
1134                            clause: ci,
1135                            blocker: other,
1136                            binary: clause_len == 2,
1137                        });
1138                        watchers.swap_remove(wi);
1139                        continue 'next_clause;
1140                    }
1141                }
1142                // No new watch: clause is unit on `other` or conflicting.
1143                if self.lit_false(other) {
1144                    // Conflict: restore the rest of this watch list and report.
1145                    self.watches[false_lit.index()] = watchers;
1146                    return Some(ci);
1147                }
1148                // Unit: propagate `other`.
1149                self.enqueue(other, Reason::Clause(ci));
1150                wi += 1;
1151            }
1152            self.watches[false_lit.index()] = watchers;
1153        }
1154        None
1155    }
1156
1157    /// First-UIP conflict analysis (GRASP/MiniSat). Walks the implication graph back from
1158    /// the conflicting clause to the first unique implication point at the current level,
1159    /// producing a learned clause and the level to backjump to.
1160    fn analyze(&mut self, conflict: usize) -> (Vec<Lit>, u32, u32) {
1161        let decision_level = self.trail_lim.len() as u32;
1162        let mut learned: Vec<Lit> = vec![Lit::pos(0)]; // slot 0 reserved for the UIP
1163        let mut counter = 0usize; // unresolved literals at the current level
1164        let mut p: Option<Lit> = None;
1165        let mut trail_idx = self.trail.len();
1166        let mut clause = conflict;
1167        // With tracing: the variables whose reasons the resolution used.
1168        let mut resolved: Vec<Var> = Vec::new();
1169
1170        loop {
1171            // Resolve with `clause` (its literals are all false; for the conflict clause, and for
1172            // each antecedent reason clause thereafter). Index rather than clone the clause: copying
1173            // each `Lit` out ends the immutable borrow before we `bump`/mark, so the hot 1UIP loop
1174            // never allocates — the way a production solver walks reason clauses.
1175            for k in 0..self.clauses[clause].len() {
1176                let q = self.clauses[clause][k];
1177                if Some(q) == p {
1178                    continue; // skip the pivot we just resolved on
1179                }
1180                let v = q.var() as usize;
1181                if !self.seen[v] && self.level[v] > 0 {
1182                    self.bump(q.var());
1183                    self.seen[v] = true;
1184                    if self.level[v] == decision_level {
1185                        counter += 1;
1186                    } else {
1187                        learned.push(q);
1188                    }
1189                }
1190            }
1191            // Pick the next literal to resolve: the most recent seen literal on the trail.
1192            loop {
1193                trail_idx -= 1;
1194                let l = self.trail[trail_idx];
1195                if self.seen[l.var() as usize] {
1196                    p = Some(l);
1197                    break;
1198                }
1199            }
1200            let pv = p.unwrap().var() as usize;
1201            self.seen[pv] = false;
1202            counter -= 1;
1203            if counter == 0 {
1204                break;
1205            }
1206            clause = match self.reason[pv] {
1207                Reason::Clause(ci) => ci,
1208                Reason::Decision => unreachable!("UIP reached a decision before counter hit 0"),
1209            };
1210            if self.lrat {
1211                resolved.push(pv as Var);
1212            }
1213        }
1214        // The asserting literal is ¬p (p is the UIP, currently true).
1215        learned[0] = p.unwrap().negated();
1216        // Clear the `seen` marks left on the non-UIP learned literals.
1217        for &l in &learned[1..] {
1218            self.seen[l.var() as usize] = false;
1219        }
1220        // Recursive minimization: drop any learned literal whose reason is already covered by the
1221        // rest of the clause. Strictly strengthens the (still-implied) clause, shrinking its size
1222        // and LBD — verdict-invariant.
1223        let redundant = self.minimize(&mut learned);
1224        if self.lrat {
1225            // The chain: under the clause's negation, the reasons of the resolved and the minimized-away variables and
1226            // of every level-0 fact a clause among them leans on, in trail order, then the conflict.
1227            let mut used: Vec<Var> = resolved;
1228            used.extend(redundant);
1229            let mut zero: Vec<Var> = self.clauses[conflict].iter().map(|l| l.var()).filter(|&v| self.level[v as usize] == 0).collect();
1230            for &v in &used {
1231                if let Reason::Clause(ci) = self.reason[v as usize] {
1232                    zero.extend(self.clauses[ci].iter().map(|l| l.var()).filter(|&w| self.level[w as usize] == 0));
1233                }
1234            }
1235            let mut ordered: Vec<(u32, u64)> = used
1236                .iter()
1237                .filter_map(|&v| match self.reason[v as usize] {
1238                    Reason::Clause(ci) => Some((self.trail_pos[v as usize], self.clause_ids[ci])),
1239                    Reason::Decision => None,
1240                })
1241                .collect();
1242            let level0 = self.cone_hints(zero);
1243            ordered.sort_unstable();
1244            ordered.dedup();
1245            let mut hints = level0;
1246            hints.extend(ordered.into_iter().map(|(_, id)| id));
1247            hints.push(self.clause_ids[conflict]);
1248            self.pending_hints = hints;
1249        }
1250        // Move the highest-decision-level literal into slot 1. The two-watched-literal invariant
1251        // requires the second watch to be the most recently falsified literal (the backjump
1252        // level); otherwise the learned clause can be falsified later without the watch firing.
1253        let mut backjump = 0u32;
1254        let mut max_idx = 1usize;
1255        for i in 1..learned.len() {
1256            let lv = self.level[learned[i].var() as usize];
1257            if lv > backjump {
1258                backjump = lv;
1259                max_idx = i;
1260            }
1261        }
1262        if learned.len() >= 2 {
1263            learned.swap(1, max_idx);
1264        }
1265        // LBD (distinct decision levels among the learned literals) via generation-stamped counting —
1266        // no per-conflict Vec allocation or sort. Each level is counted once per conflict.
1267        self.lbd_gen = self.lbd_gen.wrapping_add(1);
1268        if self.lbd_gen == 0 {
1269            // Generation wrapped after 2³² conflicts — reset the stamps once and restart at 1.
1270            for s in self.lbd_stamp.iter_mut() {
1271                *s = 0;
1272            }
1273            self.lbd_gen = 1;
1274        }
1275        let mut lbd = 0u32;
1276        for &l in learned.iter() {
1277            let lev = self.level[l.var() as usize] as usize;
1278            if self.lbd_stamp[lev] != self.lbd_gen {
1279                self.lbd_stamp[lev] = self.lbd_gen;
1280                lbd += 1;
1281            }
1282        }
1283        (learned, backjump, lbd)
1284    }
1285
1286    /// Recursive learned-clause minimization (Sörensson & Biere, 2009). A non-asserting literal is
1287    /// dropped if its reason clause's other literals are all already in the learned clause, are
1288    /// level-0 facts, or are themselves removable — meaning the literal is redundant. The result is
1289    /// a sub-clause still implied by the formula, so it is verdict-invariant; it just yields
1290    /// shorter, lower-LBD clauses that propagate and delete better.
1291    /// Drop the learned literals implied by the rest; the variables found redundant, whose reasons the shortened clause
1292    /// leans on.
1293    fn minimize(&mut self, learned: &mut Vec<Lit>) -> Vec<Var> {
1294        // Mark every learned literal in the shared `seen` array — the in-clause test, no per-conflict
1295        // HashSet — and borrow the reusable memo/touch buffers out of `self` so `lit_redundant` can
1296        // read `self` immutably while writing them (no per-conflict HashMap).
1297        for &l in learned.iter() {
1298            self.seen[l.var() as usize] = true;
1299        }
1300        let mut cache = std::mem::take(&mut self.min_cache);
1301        let mut touched = std::mem::take(&mut self.min_touched);
1302        // Pass 1: fill the memo (`cache[var] == 1` ⟺ that literal is redundant), with `seen` intact.
1303        for i in 1..learned.len() {
1304            let _ = self.lit_redundant(learned[i], &mut cache, &mut touched, 0);
1305        }
1306        // Clear `seen` off the full (not-yet-compacted) learned clause — the next analyze starts clean.
1307        for &l in learned.iter() {
1308            self.seen[l.var() as usize] = false;
1309        }
1310        // Pass 2: drop the redundant literals.
1311        let mut j = 1;
1312        for i in 1..learned.len() {
1313            let l = learned[i];
1314            if cache[l.var() as usize] != 1 {
1315                learned[j] = l;
1316                j += 1;
1317            }
1318        }
1319        learned.truncate(j);
1320        let redundant: Vec<Var> = if self.lrat { touched.iter().copied().filter(|&v| cache[v as usize] == 1).collect() } else { Vec::new() };
1321        // Sparse-reset the memo and hand the buffers back to `self` for the next conflict.
1322        for &v in &touched {
1323            cache[v as usize] = 0;
1324        }
1325        touched.clear();
1326        self.min_cache = cache;
1327        self.min_touched = touched;
1328        redundant
1329    }
1330
1331    fn lit_redundant(
1332        &self,
1333        lit: Lit,
1334        cache: &mut [u8],
1335        touched: &mut Vec<Var>,
1336        depth: u32,
1337    ) -> bool {
1338        let v = lit.var();
1339        match cache[v as usize] {
1340            1 => return true,
1341            2 => return false,
1342            _ => {}
1343        }
1344        // Bound the recursion: a deep implication chain could otherwise overflow the stack. Not
1345        // minimizing a literal is always sound, so we conservatively report "not redundant" past the
1346        // limit — and do NOT cache that cutoff, which is not the true answer.
1347        if depth >= 48 {
1348            return false;
1349        }
1350        let result = match self.reason[v as usize] {
1351            // A decision literal anchors its level; it is never redundant.
1352            Reason::Decision => false,
1353            // No clone: the reason clause and the recursive call are both immutable borrows of `self`.
1354            // `seen[qv]` is the in-learned-clause test (marked by `minimize`).
1355            Reason::Clause(ci) => self.clauses[ci].iter().all(|&q| {
1356                let qv = q.var();
1357                qv == v
1358                    || self.level[qv as usize] == 0
1359                    || self.seen[qv as usize]
1360                    || self.lit_redundant(q, cache, touched, depth + 1)
1361            }),
1362        };
1363        cache[v as usize] = if result { 1 } else { 2 };
1364        touched.push(v);
1365        result
1366    }
1367
1368    fn bump(&mut self, v: Var) {
1369        self.activity[v as usize] += self.var_inc;
1370        if self.activity[v as usize] > 1e100 {
1371            // Rescale all activities; relative order (hence the heap) is preserved.
1372            for a in self.activity.iter_mut() {
1373                *a *= 1e-100;
1374            }
1375            self.var_inc *= 1e-100;
1376        }
1377        self.heap_increase(v);
1378    }
1379
1380    fn decay(&mut self) {
1381        self.var_inc /= 0.95;
1382    }
1383
1384    /// Undo assignments down to (but not including) `level`.
1385    fn backtrack_to(&mut self, level: u32) {
1386        if self.trail_lim.len() as u32 <= level {
1387            return;
1388        }
1389        let target = self.trail_lim[level as usize];
1390        while self.trail.len() > target {
1391            let l = self.trail.pop().unwrap();
1392            let v = l.var() as usize;
1393            // Remember the polarity this variable held, so the next decision on it reuses it.
1394            self.saved_phase[v] = self.value[v] == Val::True;
1395            self.value[v] = Val::Unset;
1396            // Return the now-unassigned variable to the order heap (if it's a decision candidate).
1397            if self.heap_pos[v] < 0 && self.decision_mask.as_ref().is_none_or(|m| m[v]) {
1398                self.heap_insert(v as Var);
1399            }
1400        }
1401        self.qhead = target;
1402        self.trail_lim.truncate(level as usize);
1403    }
1404
1405    /// Delete the high-LBD half of the (deletable) learned clauses and compact the database.
1406    ///
1407    /// Soundness/verdict-invariance: only learned clauses are ever removed, and never a **locked**
1408    /// clause (a current reason on the trail), a **glue** clause (LBD ≤ 2), or a unit/binary. A
1409    /// learned clause is a resolvent already implied by the formula, so dropping it cannot change
1410    /// satisfiability. Surviving clauses keep their two watched literals (slots 0/1) unchanged, so
1411    /// the two-watched-literal invariant is preserved — we only renumber and rebuild the watch
1412    /// lists. The full proof trace (`learned_log`) is untouched, so a downstream RUP/PR check still
1413    /// replays every learned clause.
1414    /// [`Solver::reduce_db`] for an incremental solve: the learned clauses wherever they lie, every added clause kept.
1415    fn reduce_learned(&mut self) {
1416        let n = self.clauses.len();
1417        let mut locked = vec![false; n];
1418        for &l in &self.trail {
1419            if let Reason::Clause(ci) = self.reason[l.var() as usize] {
1420                locked[ci] = true;
1421            }
1422        }
1423        let mut cand: Vec<usize> =
1424            (0..n).filter(|&ci| self.learned_flag[ci] && !locked[ci] && self.lbd[ci] > 2 && self.clauses[ci].len() > 2).collect();
1425        if cand.is_empty() {
1426            return;
1427        }
1428        cand.sort_by(|&a, &b| self.lbd[b].cmp(&self.lbd[a]));
1429        let drop_n = cand.len() / 2;
1430        let delete: std::collections::HashSet<usize> = cand.into_iter().take(drop_n).collect();
1431        self.compact(&delete);
1432    }
1433
1434    fn reduce_db(&mut self) {
1435        let n = self.clauses.len();
1436        // A clause currently justifying a trail literal must not be deleted.
1437        let mut locked = vec![false; n];
1438        for &l in &self.trail {
1439            if let Reason::Clause(ci) = self.reason[l.var() as usize] {
1440                locked[ci] = true;
1441            }
1442        }
1443        // Deletion candidates: learned, unlocked, non-glue, length > 2.
1444        let mut cand: Vec<usize> = (self.n_original..n)
1445            .filter(|&ci| !locked[ci] && self.lbd[ci] > 2 && self.clauses[ci].len() > 2)
1446            .collect();
1447        if cand.is_empty() {
1448            return;
1449        }
1450        cand.sort_by(|&a, &b| self.lbd[b].cmp(&self.lbd[a])); // worst (highest LBD) first
1451        let drop_n = cand.len() / 2;
1452        let delete: std::collections::HashSet<usize> = cand.into_iter().take(drop_n).collect();
1453        self.compact(&delete);
1454    }
1455
1456    /// Rebuild the clause database keeping every clause NOT in `delete`, renumbering reasons and
1457    /// rebuilding watch lists from each survivor's (unchanged) first two literals. Originals stay
1458    /// first — so `n_original` / `original_clauses()` remain valid — provided `delete` holds only
1459    /// learned indices, and no deleted clause is a current reason (locked). Shared by LBD reduction
1460    /// and subsumption.
1461    fn compact(&mut self, delete: &std::collections::HashSet<usize>) {
1462        if delete.is_empty() {
1463            return;
1464        }
1465        let n = self.clauses.len();
1466        let survivors: Vec<usize> = (0..n).filter(|ci| !delete.contains(ci)).collect();
1467        let mut remap = vec![usize::MAX; n];
1468        for (new, &old) in survivors.iter().enumerate() {
1469            remap[old] = new;
1470        }
1471        let new_clauses: Vec<Vec<Lit>> = survivors
1472            .iter()
1473            .map(|&ci| self.clauses[ci].clone())
1474            .collect();
1475        let new_lbd: Vec<u32> = survivors.iter().map(|&ci| self.lbd[ci]).collect();
1476        let new_flag: Vec<bool> = survivors.iter().map(|&ci| self.learned_flag[ci]).collect();
1477        let new_ids: Vec<u64> = survivors.iter().map(|&ci| self.clause_ids[ci]).collect();
1478        for v in 0..self.num_vars {
1479            if let Reason::Clause(ci) = self.reason[v] {
1480                if remap[ci] != usize::MAX {
1481                    self.reason[v] = Reason::Clause(remap[ci]);
1482                }
1483            }
1484        }
1485        self.clauses = new_clauses;
1486        self.lbd = new_lbd;
1487        self.learned_live = new_flag.iter().filter(|&&f| f).count();
1488        self.learned_flag = new_flag;
1489        self.clause_ids = new_ids;
1490        for w in self.watches.iter_mut() {
1491            w.clear();
1492        }
1493        for (ci, c) in self.clauses.iter().enumerate() {
1494            if c.len() >= 2 {
1495                let (l0, l1) = (c[0], c[1]);
1496                let bin = c.len() == 2;
1497                self.watches[l0.index()].push(Watcher {
1498                    clause: ci,
1499                    blocker: l1,
1500                    binary: bin,
1501                });
1502                self.watches[l1.index()].push(Watcher {
1503                    clause: ci,
1504                    blocker: l0,
1505                    binary: bin,
1506                });
1507            }
1508        }
1509    }
1510
1511    /// Lift the two watchers of clause `ci` from the watch lists (its watched literals are, by
1512    /// invariant, `clauses[ci][0..2]`). Used to EXCLUDE a clause from propagation while it is being
1513    /// vivified, so the strengthened clause is implied by `F \ {C}` — the soundness key.
1514    fn unwatch(&mut self, ci: usize) {
1515        if self.clauses[ci].len() < 2 {
1516            return;
1517        }
1518        let (a, b) = (self.clauses[ci][0].index(), self.clauses[ci][1].index());
1519        if let Some(p) = self.watches[a].iter().position(|w| w.clause == ci) {
1520            self.watches[a].swap_remove(p);
1521        }
1522        if let Some(p) = self.watches[b].iter().position(|w| w.clause == ci) {
1523            self.watches[b].swap_remove(p);
1524        }
1525    }
1526
1527    /// Re-establish watches on `clauses[ci]`'s current first two literals (the inverse of
1528    /// [`Self::unwatch`], after a possible literal rewrite).
1529    fn rewatch(&mut self, ci: usize) {
1530        if self.clauses[ci].len() < 2 {
1531            return;
1532        }
1533        let (l0, l1) = (self.clauses[ci][0], self.clauses[ci][1]);
1534        let bin = self.clauses[ci].len() == 2;
1535        self.watches[l0.index()].push(Watcher {
1536            clause: ci,
1537            blocker: l1,
1538            binary: bin,
1539        });
1540        self.watches[l1.index()].push(Watcher {
1541            clause: ci,
1542            blocker: l0,
1543            binary: bin,
1544        });
1545    }
1546
1547    /// Vivify the clause at `ci` (asymmetric branching; Piette, Hamadi & Saïs 2008). Must be called
1548    /// at decision level 0 with the top-level fixpoint reached and `ci` already un-watched. Pushes
1549    /// trial decisions `¬lᵢ` for the clause's literals in order, propagating against `F \ {C}`:
1550    ///
1551    /// - `lᵢ` already FALSE ⇒ `F\{C} ⊨ ¬lᵢ` under the assumed prefix ⇒ `lᵢ` is redundant — drop it.
1552    /// - `lᵢ` already TRUE  ⇒ `F\{C} ⊨ (kept ∨ lᵢ)` ⇒ that prefix subsumes C — strengthen to it.
1553    /// - propagating `¬lᵢ` CONFLICTS ⇒ `F\{C} ⊨ kept` ⇒ strengthen to the prefix `kept`.
1554    ///
1555    /// Returns the strengthened literal set if C can be shortened (a strict, still-implied subset),
1556    /// else `None`. Leaves the trail back at level 0; the clause is left un-watched for the caller to
1557    /// rewatch or replace. Because the result is implied by `F \ {C}` and is `⊆ C`, replacing C with
1558    /// it preserves every model and the new clause is a valid RUP/DRAT addition.
1559    fn vivify_clause(&mut self, ci: usize) -> Option<Vec<Lit>> {
1560        let c = self.clauses[ci].clone();
1561        let mut kept: Vec<Lit> = Vec::with_capacity(c.len());
1562        let mut shortened = false;
1563        for &l in &c {
1564            match self.val_of(l) {
1565                Val::False => shortened = true, // redundant literal — drop it
1566                Val::True => {
1567                    kept.push(l);
1568                    shortened = kept.len() < c.len();
1569                    break;
1570                }
1571                Val::Unset => {
1572                    kept.push(l);
1573                    self.trail_lim.push(self.trail.len());
1574                    self.enqueue(l.negated(), Reason::Decision);
1575                    if self.propagate().is_some() {
1576                        shortened = kept.len() < c.len();
1577                        break;
1578                    }
1579                }
1580            }
1581        }
1582        self.backtrack_to(0);
1583        if shortened && !kept.is_empty() {
1584            Some(kept)
1585        } else {
1586            None
1587        }
1588    }
1589
1590    /// One vivification round over the learned clauses (Phase 2 inprocessing). Strengthens each
1591    /// shortenable learned clause in place, appending the result to the proof log as a valid RUP
1592    /// addition. Must be invoked at decision level 0. Returns `false` if a clause vivifies down to a
1593    /// unit that conflicts (or to empty) — i.e. the formula is proven UNSAT. Verdict-invariant: only
1594    /// replaces a learned clause with an equally- or more-constraining clause implied by the rest of
1595    /// the formula. A `budget` of 0 means "every learned clause".
1596    fn vivify_round(&mut self, budget: usize) -> bool {
1597        self.backtrack_to(0);
1598        if self.propagate().is_some() {
1599            return false; // level-0 conflict ⇒ UNSAT
1600        }
1601        let n = self.clauses.len();
1602        let cap = if budget == 0 { usize::MAX } else { budget };
1603        let mut done = 0usize;
1604        for ci in self.n_original..n {
1605            if done >= cap {
1606                break;
1607            }
1608            if self.clauses[ci].len() < 2 {
1609                continue; // units/empties: nothing to strengthen
1610            }
1611            done += 1;
1612            self.unwatch(ci);
1613            match self.vivify_clause(ci) {
1614                None => self.rewatch(ci),
1615                Some(kept) => {
1616                    self.vivifications += 1;
1617                    self.learned_log.push(LearnedClause { lits: kept.clone(), id: 0, hints: Vec::new() });
1618                    if kept.is_empty() {
1619                        self.empty_clause = true;
1620                        self.clauses[ci] = kept;
1621                        return false;
1622                    }
1623                    if kept.len() == 1 {
1624                        let u = kept[0];
1625                        self.clauses[ci] = kept;
1626                        match self.val_of(u) {
1627                            Val::False => {
1628                                self.empty_clause = true;
1629                                return false;
1630                            }
1631                            Val::Unset => self.enqueue(u, Reason::Clause(ci)),
1632                            Val::True => {}
1633                        }
1634                        if self.propagate().is_some() {
1635                            return false;
1636                        }
1637                        continue;
1638                    }
1639                    self.lbd[ci] = self.clause_lbd(&kept);
1640                    self.clauses[ci] = kept;
1641                    self.rewatch(ci);
1642                }
1643            }
1644        }
1645        true
1646    }
1647
1648    /// One failed-literal probing round. For each free variable `v` (a decision candidate), assume
1649    /// each phase as a fresh decision and propagate against the whole formula: if `F ∧ probe`
1650    /// conflicts at level 0, then `F ⊨ ¬probe`, so `¬probe` is added as a permanent unit (a valid
1651    /// RUP step) and propagated. Returns `false` if a derived unit conflicts — the formula is UNSAT.
1652    /// Verdict-invariant. A `budget` of 0 means "every variable".
1653    fn probe_round(&mut self, budget: usize) -> bool {
1654        self.backtrack_to(0);
1655        if self.propagate().is_some() {
1656            return false; // level-0 conflict ⇒ UNSAT
1657        }
1658        let cap = if budget == 0 { usize::MAX } else { budget };
1659        let mut done = 0usize;
1660        for v in 0..self.num_vars as Var {
1661            if done >= cap {
1662                break;
1663            }
1664            if self.value[v as usize] != Val::Unset {
1665                continue; // already a level-0 fact
1666            }
1667            if self.decision_mask.as_ref().is_some_and(|m| !m[v as usize]) {
1668                continue; // not a decision candidate
1669            }
1670            done += 1;
1671            for probe in [Lit::pos(v), Lit::neg(v)] {
1672                if self.value[v as usize] != Val::Unset {
1673                    break; // fixed by the other phase's probe
1674                }
1675                self.trail_lim.push(self.trail.len());
1676                self.enqueue(probe, Reason::Decision);
1677                let conflict = self.propagate().is_some();
1678                self.backtrack_to(0);
1679                if conflict {
1680                    // F ∧ probe is UNSAT ⇒ ¬probe is forced; learn it as a unit (RUP) and apply it.
1681                    self.probes += 1;
1682                    self.add_clause_raw(vec![probe.negated()], true);
1683                    if self.empty_clause || self.propagate().is_some() {
1684                        return false;
1685                    }
1686                }
1687            }
1688        }
1689        true
1690    }
1691
1692    /// One subsumption + self-subsuming-resolution round over the LEARNED clauses. A learned clause
1693    /// subsumed by any clause is deleted; a learned clause that self-subsumes against another
1694    /// (exactly one literal resolves away) is strengthened. Only learned, unlocked clauses are
1695    /// removed/strengthened — originals (and the RUP certificate, and `n_original`) stay valid.
1696    /// Verdict-invariant: a deleted clause is entailed by its subsumer (and subsumption is
1697    /// transitive, so soundness survives even if the subsumer is itself later removed), and a
1698    /// strengthened clause is a sound resolvent (logged as RUP). Returns `false` if a strengthening
1699    /// derives the empty clause. `budget` of 0 means "every learned clause".
1700    fn subsume_round(&mut self, budget: usize) -> bool {
1701        self.backtrack_to(0);
1702        if self.propagate().is_some() {
1703            return false;
1704        }
1705        let n = self.clauses.len();
1706        if n <= self.n_original {
1707            return true;
1708        }
1709        let code = |l: Lit| l.var() * 2 + u32::from(!l.is_positive());
1710        let mut coded: Vec<Vec<u32>> = Vec::with_capacity(n);
1711        let mut sigs: Vec<u64> = Vec::with_capacity(n);
1712        for c in &self.clauses {
1713            let mut v: Vec<u32> = c.iter().map(|&l| code(l)).collect();
1714            v.sort_unstable();
1715            v.dedup();
1716            sigs.push(c.iter().fold(0u64, |s, l| s | (1u64 << (l.var() % 64))));
1717            coded.push(v);
1718        }
1719        let mut occ: Vec<Vec<usize>> = vec![Vec::new(); self.num_vars];
1720        for (ci, cc) in coded.iter().enumerate() {
1721            for &x in cc {
1722                occ[(x / 2) as usize].push(ci);
1723            }
1724        }
1725        let mut locked = vec![false; n];
1726        for &l in &self.trail {
1727            if let Reason::Clause(ci) = self.reason[l.var() as usize] {
1728                if ci < n {
1729                    locked[ci] = true;
1730                }
1731            }
1732        }
1733        let mut delete: std::collections::HashSet<usize> = std::collections::HashSet::new();
1734        let mut strengthen: Vec<(usize, u32)> = Vec::new();
1735        let cap = if budget == 0 { usize::MAX } else { budget };
1736        let mut done = 0usize;
1737        for di in self.n_original..n {
1738            if done >= cap {
1739                break;
1740            }
1741            if coded[di].len() < 2 || delete.contains(&di) {
1742                continue;
1743            }
1744            done += 1;
1745            let rare = *coded[di]
1746                .iter()
1747                .min_by_key(|&&x| occ[(x / 2) as usize].len())
1748                .unwrap();
1749            let mut tried = 0;
1750            for &ci in &occ[(rare / 2) as usize] {
1751                if ci == di || delete.contains(&ci) {
1752                    continue;
1753                }
1754                tried += 1;
1755                if tried > 96 {
1756                    break;
1757                }
1758                if coded[ci].len() > coded[di].len() || (sigs[ci] & !sigs[di]) != 0 {
1759                    continue;
1760                }
1761                match self_subsumes(&coded[ci], &coded[di]) {
1762                    Sub::Subsumes => {
1763                        if !locked[di] {
1764                            delete.insert(di);
1765                        }
1766                        break;
1767                    }
1768                    Sub::Strengthen(pivot) => {
1769                        strengthen.push((di, pivot));
1770                        break;
1771                    }
1772                    Sub::No => {}
1773                }
1774            }
1775        }
1776        for (di, drop_code) in strengthen {
1777            if delete.contains(&di) {
1778                continue;
1779            }
1780            self.unwatch(di);
1781            let new: Vec<Lit> = self.clauses[di]
1782                .iter()
1783                .copied()
1784                .filter(|&l| code(l) != drop_code)
1785                .collect();
1786            self.subsumptions += 1;
1787            self.learned_log.push(LearnedClause { lits: new.clone(), id: 0, hints: Vec::new() });
1788            if new.is_empty() {
1789                self.empty_clause = true;
1790                self.clauses[di] = new;
1791                return false;
1792            }
1793            if new.len() == 1 {
1794                let u = new[0];
1795                self.clauses[di] = new;
1796                match self.val_of(u) {
1797                    Val::False => {
1798                        self.empty_clause = true;
1799                        return false;
1800                    }
1801                    Val::Unset => self.enqueue(u, Reason::Clause(di)),
1802                    Val::True => {}
1803                }
1804                if self.propagate().is_some() {
1805                    return false;
1806                }
1807            } else {
1808                self.lbd[di] = self.clause_lbd(&new);
1809                self.clauses[di] = new;
1810                self.rewatch(di);
1811            }
1812        }
1813        self.subsumptions += delete.len() as u64;
1814        self.compact(&delete);
1815        true
1816    }
1817
1818    /// Rotate the saved-phase strategy (rephasing). Decisions reuse `saved_phase`; periodically
1819    /// overwriting it — invert, all-false, all-true, then leave the search's own saved phases — kicks
1820    /// the search out of a basin without changing completeness. Pure heuristic; verdict-invariant.
1821    fn rephase(&mut self, round: u64) {
1822        match round % 4 {
1823            0 => {
1824                for p in self.saved_phase.iter_mut() {
1825                    *p = !*p;
1826                }
1827            }
1828            1 => self.saved_phase.iter_mut().for_each(|p| *p = false),
1829            2 => self.saved_phase.iter_mut().for_each(|p| *p = true),
1830            _ => {}
1831        }
1832    }
1833
1834    /// Run one level-0 inprocessing round: failed-literal probing (only while it keeps paying off),
1835    /// then subsumption + self-subsuming resolution, then learned-clause vivification, then a
1836    /// rephase. Returns `false` if it proves the formula UNSAT. Must be called at decision level 0
1837    /// (the scheduler calls it right after a restart). Verdict-invariant.
1838    fn inprocess(&mut self, round: u64) -> bool {
1839        if self.probe_active {
1840            let before = self.probes;
1841            if !self.probe_round(PROBE_BUDGET) {
1842                return false;
1843            }
1844            // Most instances yield no failed literals; once a round finds none, stop probing this
1845            // solve so it is not pure overhead.
1846            if self.probes == before {
1847                self.probe_active = false;
1848            }
1849        }
1850        if !self.subsume_round(SUBSUME_BUDGET) {
1851            return false;
1852        }
1853        if !self.vivify_round(VIVIFY_BUDGET) {
1854            return false;
1855        }
1856        self.rephase(round);
1857        true
1858    }
1859
1860    /// The decision literal for `v`: its saved phase (false-first on the first ever decision).
1861    fn decision_lit(&self, v: Var) -> Lit {
1862        if self.saved_phase[v as usize] {
1863            Lit::pos(v)
1864        } else {
1865            Lit::neg(v)
1866        }
1867    }
1868
1869    /// Pick the highest-activity unassigned decision variable in O(log n) via the order heap,
1870    /// discarding popped variables that are already assigned (lazy deletion). `None` once every
1871    /// decision candidate is assigned. Backtracking re-inserts unassigned candidates, so the heap is
1872    /// never missing a candidate when a decision is actually needed.
1873    fn pick_branch(&mut self) -> Option<Var> {
1874        loop {
1875            let v = self.heap_pop()?;
1876            if self.value[v as usize] == Val::Unset {
1877                return Some(v);
1878            }
1879        }
1880    }
1881
1882    /// The Literal-Block-Distance of a clause: the number of distinct decision levels among its
1883    /// literals (Audemard & Simon, 2009). Low LBD ⇒ "glue" ⇒ kept across reductions.
1884    fn clause_lbd(&self, lits: &[Lit]) -> u32 {
1885        let mut levels: Vec<u32> = lits.iter().map(|l| self.level[l.var() as usize]).collect();
1886        levels.sort_unstable();
1887        levels.dedup();
1888        levels.len() as u32
1889    }
1890
1891    /// The conflict aftermath shared by Boolean and theory conflicts: derive the 1-UIP asserting
1892    /// clause from conflicting clause `ci`, backjump, learn + enqueue it, then run the decay /
1893    /// reduce-DB / restart bookkeeping. Returns `true` when the conflict is at decision level 0 — the
1894    /// formula is UNSAT.
1895    fn after_conflict(&mut self, ci: usize) -> bool {
1896        if self.trail_lim.is_empty() {
1897            return true; // conflict at level 0
1898        }
1899        let trail_at_conflict = self.trail.len();
1900        let (learned, backjump, lbd) = self.analyze(ci);
1901        self.note_conflict(lbd, trail_at_conflict);
1902        self.backtrack_to(backjump);
1903        let asserting = learned[0];
1904        let unit = learned.len() == 1;
1905        let new_ci = self.add_clause_raw(learned, true);
1906        self.lbd[new_ci] = lbd;
1907        if !unit {
1908            self.enqueue(asserting, Reason::Clause(new_ci));
1909        }
1910        self.decay();
1911        self.conflicts += 1;
1912        self.csr += 1;
1913        if self.reduce_enabled && self.live_learned() >= self.reduce_limit {
1914            self.reduce_db();
1915            self.reduce_limit += 500;
1916        }
1917        self.advance_restart_phase();
1918        if self.want_restart() {
1919            self.do_restart();
1920        }
1921        false
1922    }
1923
1924    /// Solve, optionally under a list of theory propagators (DPLL(T)). Returns a model or
1925    /// `Unsat`. The learned-clause log is available afterwards via [`Solver::learned`].
1926    pub fn solve(&mut self) -> SolveResult {
1927        self.solve_with(&mut [])
1928    }
1929
1930    /// Solve but give up after `max_conflicts` conflicts, returning [`BudgetedResult::Budget`] with
1931    /// the learned clauses ([`Self::learned`]) intact — the hook dynamic symmetry breaking needs to
1932    /// interleave bounded search with symmetric clause amplification. A `max_conflicts` of 0 means
1933    /// unlimited (equivalent to [`Self::solve`]).
1934    pub fn solve_budgeted(&mut self, max_conflicts: u64) -> BudgetedResult {
1935        // Mark which clauses are original so DB reduction never deletes them (the omission that
1936        // would otherwise let reduction drop the formula itself and report a bogus SAT).
1937        self.n_original = self.clauses.len();
1938        if self.empty_clause {
1939            return BudgetedResult::Unsat;
1940        }
1941        if self.propagate().is_some() {
1942            return BudgetedResult::Unsat;
1943        }
1944        self.reset_restart_state();
1945        let start = self.conflicts;
1946        loop {
1947            if let Some(ci) = self.propagate() {
1948                if self.trail_lim.is_empty() {
1949                    return BudgetedResult::Unsat;
1950                }
1951                let trail_at_conflict = self.trail.len();
1952                let (learned, backjump, lbd) = self.analyze(ci);
1953                self.note_conflict(lbd, trail_at_conflict);
1954                self.backtrack_to(backjump);
1955                let asserting = learned[0];
1956                let unit = learned.len() == 1;
1957                let new_ci = self.add_clause_raw(learned, true);
1958                self.lbd[new_ci] = lbd;
1959                if !unit {
1960                    self.enqueue(asserting, Reason::Clause(new_ci));
1961                }
1962                self.decay();
1963                self.conflicts += 1;
1964                self.csr += 1;
1965                if max_conflicts != 0 && self.conflicts - start >= max_conflicts {
1966                    self.backtrack_to(0);
1967                    return BudgetedResult::Budget;
1968                }
1969                if self.reduce_enabled && self.live_learned() >= self.reduce_limit {
1970                    self.reduce_db();
1971                    self.reduce_limit += 500;
1972                }
1973                self.advance_restart_phase();
1974                if self.want_restart() {
1975                    self.do_restart();
1976                }
1977                continue;
1978            }
1979            match self.pick_branch() {
1980                None => {
1981                    let model = (0..self.num_vars)
1982                        .map(|v| self.value[v] == Val::True)
1983                        .collect();
1984                    return BudgetedResult::Sat(model);
1985                }
1986                Some(v) => {
1987                    self.trail_lim.push(self.trail.len());
1988                    self.decisions += 1;
1989                    self.enqueue(self.decision_lit(v), Reason::Decision);
1990                }
1991            }
1992        }
1993    }
1994
1995    /// Solve with theory propagators. Each is consulted at every Boolean fixpoint; a
1996    /// returned clause is added to the formula (and may immediately propagate or conflict).
1997    pub fn solve_with(&mut self, theories: &mut [Box<dyn Theory>]) -> SolveResult {
1998        self.n_original = self.clauses.len();
1999        if self.empty_clause {
2000            return SolveResult::Unsat;
2001        }
2002        // Top-level propagation of any unit clauses already enqueued.
2003        if self.propagate().is_some() {
2004            return SolveResult::Unsat;
2005        }
2006        self.reset_restart_state();
2007        let mut last_inprocess = 0u64;
2008        let mut inprocess_rounds = 0u64;
2009        let mut inprocess_gap = self.inprocess_interval;
2010        self.probe_active = true; // re-arm probing for this solve
2011
2012        loop {
2013            let conflict = self.propagate();
2014            if let Some(ci) = conflict {
2015                let restarts_before = self.restarts;
2016                if self.after_conflict(ci) {
2017                    return SolveResult::Unsat;
2018                }
2019                // A restart just returned us to level 0 — the safe point to inprocess. Gated by a
2020                // GROWING gap so only long searches pay, and less and less as the search runs on
2021                // (bounding churn). probe + subsume + vivify + rephase, all verdict-invariant; a
2022                // `false` return means inprocessing proved UNSAT.
2023                if self.inprocess_enabled
2024                    && theories.is_empty()
2025                    && self.restarts > restarts_before
2026                    && self.conflicts - last_inprocess >= inprocess_gap
2027                {
2028                    last_inprocess = self.conflicts;
2029                    if !self.inprocess(inprocess_rounds) {
2030                        return SolveResult::Unsat;
2031                    }
2032                    inprocess_rounds += 1;
2033                    inprocess_gap = ((inprocess_gap as f64) * INPROCESS_GROWTH) as u64;
2034                }
2035                continue;
2036            }
2037            // Boolean fixpoint — consult theories before branching. Every clause a theory hands back
2038            // is a globally-valid no-good (a logical consequence of the formula), so we CARRY it into
2039            // the learned database: a contradiction found by one strategy holds in every model, and a
2040            // carried clause prunes that branch for the rest of the search. A theory conflict (all
2041            // literals false) drives a 1-UIP backjump exactly like a Boolean conflict — sound because
2042            // we consult at EVERY fixpoint, so the inconsistency is caught at the level of its last
2043            // contributing assignment and the carried clause has a current-level literal. A theory
2044            // propagation (one literal still free) is enqueued with the carried clause as its reason,
2045            // so later conflict analysis resolves through the theory's reasoning.
2046            let mut theory_acted = false;
2047            for ti in 0..theories.len() {
2048                let implied = theories[ti].propagate(&self.trail);
2049                if implied.is_empty() {
2050                    continue;
2051                }
2052                // A theory conflict takes priority: carry it and run conflict analysis.
2053                if let Some(conf) = implied
2054                    .iter()
2055                    .find(|c| c.iter().all(|&l| self.lit_false(l)))
2056                {
2057                    if conf.is_empty() {
2058                        return SolveResult::Unsat; // an unconditional contradiction (0 = 1)
2059                    }
2060                    let lbd = self.clause_lbd(conf);
2061                    let ci = self.add_clause_raw(conf.clone(), true);
2062                    self.lbd[ci] = lbd;
2063                    if self.after_conflict(ci) {
2064                        return SolveResult::Unsat;
2065                    }
2066                    theory_acted = true;
2067                    break;
2068                }
2069                // Otherwise carry every implied unit, enqueueing its one free literal.
2070                for c in &implied {
2071                    if c.iter().any(|&l| self.lit_true(l)) {
2072                        continue; // already satisfied — stale
2073                    }
2074                    let free: Vec<usize> = (0..c.len())
2075                        .filter(|&i| self.val_of(c[i]) == Val::Unset)
2076                        .collect();
2077                    if free.len() != 1 {
2078                        continue; // not a clean unit propagation — skip defensively
2079                    }
2080                    let mut lits = c.clone();
2081                    lits.swap(0, free[0]);
2082                    if lits.len() > 1 {
2083                        // Watch the highest-level false literal alongside the implied one.
2084                        let mut best = 1;
2085                        let mut best_lv = 0u32;
2086                        for i in 1..lits.len() {
2087                            let lv = self.level[lits[i].var() as usize];
2088                            if lv >= best_lv {
2089                                best_lv = lv;
2090                                best = i;
2091                            }
2092                        }
2093                        lits.swap(1, best);
2094                    }
2095                    let implied_lit = lits[0];
2096                    let multi = lits.len() > 1;
2097                    let lbd = self.clause_lbd(&lits);
2098                    let ci = self.add_clause_raw(lits, true);
2099                    self.lbd[ci] = lbd;
2100                    if multi {
2101                        // A unit clause was already enqueued by add_clause_raw's unit path.
2102                        self.enqueue(implied_lit, Reason::Clause(ci));
2103                    }
2104                    theory_acted = true;
2105                }
2106                if theory_acted {
2107                    break;
2108                }
2109            }
2110            if theory_acted {
2111                continue;
2112            }
2113            // Decide.
2114            match self.pick_branch() {
2115                None => {
2116                    // Full assignment → SAT.
2117                    let model = (0..self.num_vars)
2118                        .map(|v| self.value[v] == Val::True)
2119                        .collect();
2120                    return SolveResult::Sat(model);
2121                }
2122                Some(v) => {
2123                    self.trail_lim.push(self.trail.len());
2124                    // Phase saving: reuse the variable's last polarity (false-first initially).
2125                    self.decisions += 1;
2126                    self.enqueue(self.decision_lit(v), Reason::Decision);
2127                }
2128            }
2129        }
2130    }
2131
2132    /// Solve under temporary `assumptions` (literals forced true for THIS query only),
2133    /// reusing every clause learned so far. The permanent clause database is untouched, so a
2134    /// later call with different assumptions may well be satisfiable — successive queries on
2135    /// the same solver (e.g. BMC at increasing depths) amortise learning. This is the
2136    /// incremental-SAT (IPASIR) pattern. `Unsat` here means "unsatisfiable UNDER these
2137    /// assumptions".
2138    ///
2139    /// Soundness of reuse: conflict analysis keeps decision-level literals (assumptions are
2140    /// decisions) and drops level-0 facts, so each learned clause is a consequence of the
2141    /// PERMANENT clauses alone — valid no matter which assumptions a future query makes.
2142    ///
2143    /// Restarts follow the Luby sequence (100 conflicts a unit) and drop the search to level 0:
2144    /// the next decisions place the assumptions again, so they stay the bottom levels.
2145    /// (Does not touch `n_original`; do not mix with [`Solver::original_clauses`]/RUP on the
2146    /// same solver.)
2147    pub fn solve_under_assumptions(&mut self, assumptions: &[Lit]) -> SolveResult {
2148        match self.solve_under_assumptions_budgeted(assumptions, 0) {
2149            BudgetedResult::Sat(model) => SolveResult::Sat(model),
2150            BudgetedResult::Unsat => SolveResult::Unsat,
2151            BudgetedResult::Budget => unreachable!("a solve without a budget runs to a verdict"),
2152        }
2153    }
2154
2155    /// [`Solver::solve_under_assumptions`] within `max_conflicts` conflicts (0: no limit), `Budget` when they run out
2156    /// with the search dropped and every learned clause kept. On `Unsat`, the clause of the assumptions' negations is
2157    /// RUP from the clauses added and [`Solver::learned`] so far. Learned clauses are deleted, the added ones never,
2158    /// whatever their order: a long run of queries keeps its database in bounds.
2159    pub fn solve_under_assumptions_budgeted(&mut self, assumptions: &[Lit], max_conflicts: u64) -> BudgetedResult {
2160        // Drop any prior search state, keeping level-0 facts and all learned clauses.
2161        self.backtrack_to(0);
2162        if self.empty_clause {
2163            self.unsat_hints = self.empty_hints.clone();
2164            return BudgetedResult::Unsat;
2165        }
2166        // Level-0 propagation: if the permanent formula is already unsatisfiable, no
2167        // assumption can rescue it — and it stays unsat for every future query, so latch the
2168        // permanent-unsat flag (this also guarantees a clean state on the next call, which a
2169        // no-op `backtrack_to(0)` over an empty `trail_lim` would otherwise inherit dirty).
2170        if let Some(ci) = self.propagate() {
2171            self.found_empty(ci);
2172            self.unsat_hints = self.empty_hints.clone();
2173            return BudgetedResult::Unsat;
2174        }
2175        let mut spent = 0u64;
2176        let (mut since_restart, mut restart_no) = (0u64, 1u64);
2177        loop {
2178            if let Some(ci) = self.propagate() {
2179                if self.trail_lim.is_empty() {
2180                    // A conflict with no decisions: the formula is unsatisfiable.
2181                    self.found_empty(ci);
2182                    self.unsat_hints = self.empty_hints.clone();
2183                    return BudgetedResult::Unsat;
2184                }
2185                let (learned, backjump, lbd) = self.analyze(ci);
2186                self.backtrack_to(backjump);
2187                let asserting = learned[0];
2188                let unit = learned.len() == 1;
2189                let new_ci = self.add_clause_raw(learned, true);
2190                self.lbd[new_ci] = lbd;
2191                if !unit {
2192                    self.enqueue(asserting, Reason::Clause(new_ci));
2193                }
2194                self.decay();
2195                self.conflicts += 1;
2196                spent += 1;
2197                if self.reduce_enabled && self.learned_live >= self.reduce_limit {
2198                    self.reduce_learned();
2199                    self.reduce_limit += 500;
2200                }
2201                if max_conflicts > 0 && spent >= max_conflicts {
2202                    self.backtrack_to(0);
2203                    return BudgetedResult::Budget;
2204                }
2205                since_restart += 1;
2206                if since_restart >= luby(restart_no) * 100 {
2207                    self.backtrack_to(0);
2208                    self.restarts += 1;
2209                    since_restart = 0;
2210                    restart_no += 1;
2211                }
2212                continue;
2213            }
2214            // Decide: place the first not-yet-satisfied assumption (so the search always
2215            // explores under the full assumption set, even after a backjump unset some).
2216            let mut decided = false;
2217            for &a in assumptions {
2218                match self.val_of(a) {
2219                    // The assumption is forced false ⇒ no model under the assumptions: the chain is the cone
2220                    // of its negation back to the assumptions before it.
2221                    Val::False => {
2222                        if self.lrat {
2223                            let negated: Vec<Lit> = assumptions.iter().map(|x| x.negated()).collect();
2224                            let reasons = self.cone([a.var()]);
2225                            self.unsat_hints = self.replayed(&negated, &reasons);
2226                        }
2227                        return BudgetedResult::Unsat;
2228                    }
2229                    Val::True => {}
2230                    Val::Unset => {
2231                        self.trail_lim.push(self.trail.len());
2232                        self.enqueue(a, Reason::Decision);
2233                        decided = true;
2234                        break;
2235                    }
2236                }
2237            }
2238            if decided {
2239                continue;
2240            }
2241            // All assumptions hold — branch on the remaining variables.
2242            match self.pick_branch() {
2243                None => {
2244                    let model = (0..self.num_vars)
2245                        .map(|v| self.value[v] == Val::True)
2246                        .collect();
2247                    return BudgetedResult::Sat(model);
2248                }
2249                Some(v) => {
2250                    self.trail_lim.push(self.trail.len());
2251                    self.decisions += 1;
2252                    self.enqueue(self.decision_lit(v), Reason::Decision);
2253                }
2254            }
2255        }
2256    }
2257}
2258
2259/// The Luby restart sequence `1,1,2,1,1,2,4,1,…` (Luby, Sinclair & Zuckerman, 1993) —
2260/// the optimal universal restart schedule.
2261/// The outcome of testing clause `C` (as sorted `(var,sign)` codes) against clause `D`.
2262enum Sub {
2263    /// `C ⊆ D` — `C` subsumes `D`, so `D` is redundant.
2264    Subsumes,
2265    /// `C` self-subsumes `D` on one literal: all of `C` is in `D` except a single literal whose
2266    /// negation is in `D`. `D` can drop that negated literal (the carried code). Resolution + the
2267    /// resulting subsumption.
2268    Strengthen(u32),
2269    /// No subsumption relationship.
2270    No,
2271}
2272
2273/// Classify `c` against `d` (both sorted, deduped `(var,sign)` code vectors). A code's sign bit is
2274/// the low bit, so `code ^ 1` is the opposite-polarity literal.
2275fn self_subsumes(c: &[u32], d: &[u32]) -> Sub {
2276    let mut pivot: Option<u32> = None;
2277    for &x in c {
2278        if d.binary_search(&x).is_ok() {
2279            continue; // x ∈ D
2280        }
2281        if d.binary_search(&(x ^ 1)).is_ok() {
2282            if pivot.is_some() {
2283                return Sub::No; // a second flipped literal ⇒ not (self-)subsuming
2284            }
2285            pivot = Some(x ^ 1);
2286        } else {
2287            return Sub::No; // x neither in D nor its negation ⇒ C ⊄ D
2288        }
2289    }
2290    match pivot {
2291        None => Sub::Subsumes,
2292        Some(p) => Sub::Strengthen(p),
2293    }
2294}
2295
2296fn luby(mut i: u64) -> u64 {
2297    // 1-indexed Luby.
2298    let mut k = 1u32;
2299    loop {
2300        let span = (1u64 << k) - 1;
2301        if i == span {
2302            return 1u64 << (k - 1);
2303        }
2304        if i < span {
2305            i -= (1u64 << (k - 1)) - 1;
2306            k = 1;
2307            continue;
2308        }
2309        k += 1;
2310    }
2311}
2312
2313#[cfg(test)]
2314#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/cdcl/tests.rs"]
2315mod tests;