Skip to main content

elinvar_engine/
solve.rs

1//! `run`, `check`, verdicts, the next instance, and the referee (LOGIC.md
2//! sections 12.1, 12.6, and 12.7).
3
4use crate::circuit::{Bool, Circuit};
5use crate::sat::{Budget, BudgetExhausted, Cdcl, Lit, Solved, Solver};
6use crate::skolem::skolemize;
7use crate::symmetry;
8use crate::translate::{Primary, Shape, Translator};
9use elinvar_logic::{
10    Against, Bounds, Error, Expr, ExprKind, Formula, FormulaKind, Instance, IntExpr, IntExprKind,
11    Relation, TemporalOp, Trace, TupleSet, check_formula, evaluate, evaluate_trace,
12};
13use serde::Serialize;
14use std::fmt;
15use std::time::{Duration, Instant};
16
17/// How a search runs.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
19#[non_exhaustive]
20pub struct Options {
21    /// Break symmetries (LOGIC.md 12.5). On by default; off for counting.
22    pub symmetry_breaking: bool,
23    /// The budget of each solve. There is always one (AGENTS.md law 22).
24    pub budget: Budget,
25    /// The most states a trace may have (LOGIC.md 13.4).
26    pub steps: usize,
27    /// The most entries the symmetry predicate compares per pair of atoms
28    /// (LOGIC.md 12.5).
29    pub predicate_length: usize,
30    /// Try a smaller problem with the same verdict before the whole one
31    /// (DESIGN.md section 7.9). On by default; off, every check is solved
32    /// whole, which gives the reference answer slicing is compared with.
33    pub slicing: bool,
34    /// Forbid signed integer overflow (`noOverflow` in Alloy 6.2.0,
35    /// `A4Options.java`): when true, any case whose integer arithmetic overflows
36    /// the bitwidth is ruled out. Off by default, matching Alloy's default.
37    pub no_overflow: bool,
38}
39
40/// Alloy's default limit on steps (`ScopeComputer.java`, `maxtrace`).
41pub const DEFAULT_STEPS: usize = 10;
42
43/// The default budget: generous and finite.
44pub const DEFAULT_CONFLICTS: u64 = 10_000_000;
45
46impl Default for Options {
47    fn default() -> Options {
48        Options {
49            symmetry_breaking: true,
50            budget: Budget::conflicts(DEFAULT_CONFLICTS),
51            steps: DEFAULT_STEPS,
52            predicate_length: symmetry::PREDICATE_LENGTH,
53            slicing: true,
54            no_overflow: false,
55        }
56    }
57}
58
59impl Options {
60    /// The same options with symmetry breaking on or off.
61    #[must_use]
62    pub fn symmetry_breaking(mut self, on: bool) -> Options {
63        self.symmetry_breaking = on;
64        self
65    }
66
67    /// The same options with another length of the symmetry predicate.
68    #[must_use]
69    pub fn predicate_length(mut self, length: usize) -> Options {
70        self.predicate_length = length;
71        self
72    }
73
74    /// The same options with slicing on or off (DESIGN.md section 7.9).
75    #[must_use]
76    pub fn slicing(mut self, on: bool) -> Options {
77        self.slicing = on;
78        self
79    }
80
81    /// The same options with overflow prevention on or off (Alloy `noOverflow`).
82    #[must_use]
83    pub fn no_overflow(mut self, on: bool) -> Options {
84        self.no_overflow = on;
85        self
86    }
87
88    /// The same options with another limit on steps.
89    #[must_use]
90    pub fn steps(mut self, steps: usize) -> Options {
91        self.steps = steps;
92        self
93    }
94
95    /// The same options with another budget.
96    #[must_use]
97    pub fn budget(mut self, budget: Budget) -> Options {
98        self.budget = budget;
99        self
100    }
101}
102
103/// What a search concluded (DESIGN.md section 7.6).
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
105#[serde(rename_all = "snake_case")]
106#[non_exhaustive]
107pub enum Verdict {
108    /// `run`: an instance, refereed.
109    Found,
110    /// `run`: no instance within the bounds.
111    None,
112    /// `check`: an instance that breaks the assertion, refereed.
113    Counterexample,
114    /// `check`: no counterexample within the bounds, and the rules allow
115    /// at least one case.
116    Holds,
117    /// `check`: proved for any number of steps within the scope by k-induction
118    /// (N9), and the initial state is non-vacuous.
119    Proved,
120    /// `check`: no counterexample within the bounds, because the rules
121    /// allow no case within them.
122    Vacuous,
123    /// The budget ran out.
124    Unknown,
125}
126
127impl fmt::Display for Verdict {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let s = match self {
130            Verdict::Found => "found",
131            Verdict::None => "none",
132            Verdict::Counterexample => "counterexample",
133            Verdict::Holds => "holds",
134            Verdict::Proved => "proved",
135            Verdict::Vacuous => "vacuous",
136            Verdict::Unknown => "unknown",
137        };
138        write!(f, "{s}")
139    }
140}
141
142/// The size of a translation and the work of its solves.
143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
144#[non_exhaustive]
145pub struct Stats {
146    /// Primary variables.
147    pub primary_variables: u32,
148    /// Gates of the circuit.
149    pub gates: usize,
150    /// Conflicts over every solve.
151    pub conflicts: u64,
152}
153
154/// What happened at one step of a trace (LOGIC.md 13.5): an action and
155/// its arguments, or nothing.
156#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
157#[non_exhaustive]
158pub struct StepLabel {
159    /// The action, or `None` when nothing changed.
160    pub action: Option<String>,
161    /// The arguments, as atom names.
162    pub args: Vec<String>,
163}
164
165/// The answer to `run` or `check`.
166#[derive(Clone, Debug, Serialize)]
167#[non_exhaustive]
168#[must_use]
169pub struct Outcome {
170    /// The verdict.
171    pub verdict: Verdict,
172    /// The instance, for `found` and `counterexample` without changing
173    /// relations. It holds the user's relations, then the skolem relations
174    /// that name witnesses.
175    pub instance: Option<Instance>,
176    /// The trace, for `found` and `counterexample` with changing relations.
177    pub trace: Option<Trace>,
178    /// For a trace of a model with actions, step `k` is the one out of
179    /// state `k` (LOGIC.md 13.5).
180    pub labels: Vec<StepLabel>,
181    /// For `unknown`, what is known and which budget ran out.
182    pub note: Option<String>,
183    /// Statistics.
184    pub stats: Stats,
185}
186
187impl fmt::Display for Outcome {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(f, "{}", self.verdict)?;
190        if let Some(note) = &self.note {
191            write!(f, " ({note})")?;
192        }
193        Ok(())
194    }
195}
196
197/// What the next solve gave.
198#[derive(Clone, Debug)]
199#[non_exhaustive]
200pub enum Next {
201    /// An instance of a problem with no changing relation, refereed.
202    Instance(Instance),
203    /// A trace of a problem with changing relations, refereed.
204    Trace(Trace),
205    /// No more instances or traces.
206    Done,
207    /// The budget ran out.
208    Unknown,
209}
210
211/// The search for one shape of trace: one circuit and one solver.
212struct Search {
213    bounds: Bounds,
214    shape: Shape,
215    circuit: Circuit,
216    solver: Box<dyn Solver>,
217    primaries: Vec<Primary>,
218    loop_vars: Vec<Bool>,
219    checked_sat: bool,
220    cur_loop: usize,
221    saved: Option<(Instance, Vec<Instance>, usize, Vec<Lit>)>,
222    exhausted: bool,
223    timed_out: bool,
224}
225
226impl Search {
227    fn new(
228        bounds: &Bounds,
229        formula: &Formula,
230        shape: Shape,
231        options: &Options,
232        mut solver: Box<dyn Solver>,
233    ) -> Search {
234        let deadline = options.budget.time.map(|t| Instant::now() + t);
235        let expired = || deadline.is_some_and(|d| Instant::now() >= d);
236        let mut circuit = Circuit::new();
237        let mut timed_out = expired();
238        let (root, primaries, loop_vars) = if timed_out {
239            (Bool::FALSE, Vec::new(), Vec::new())
240        } else {
241            let (mut tr, primaries, loop_vars) = Translator::new(&mut circuit, bounds, shape);
242            tr.set_deadline(deadline);
243            tr.set_no_overflow(options.no_overflow);
244            let mut root = tr.formula(formula);
245            if tr.timed_out() || expired() {
246                timed_out = true;
247            }
248            if !timed_out && options.no_overflow && root != Bool::FALSE {
249                let of = tr.overflow_free();
250                root = tr.circuit.and([root, of]);
251            }
252            if !timed_out && !loop_vars.is_empty() && root != Bool::FALSE {
253                let lc = tr.loop_constraint();
254                root = tr.circuit.and([root, lc]);
255            }
256            if !timed_out && options.symmetry_breaking && root != Bool::FALSE {
257                let sbp =
258                    symmetry::predicate(&mut tr, bounds, &primaries, options.predicate_length);
259                root = tr.circuit.and([root, sbp]);
260                if expired() {
261                    timed_out = true;
262                }
263            }
264            (root, primaries, loop_vars)
265        };
266        let satisfiable = if timed_out {
267            false
268        } else {
269            circuit.assert(solver.as_mut(), root)
270        };
271        Search {
272            bounds: bounds.clone(),
273            shape,
274            circuit,
275            solver,
276            primaries,
277            loop_vars,
278            checked_sat: false,
279            cur_loop: 0,
280            saved: None,
281            exhausted: !satisfiable,
282            timed_out,
283        }
284    }
285
286    fn is_true(&self, b: Bool) -> bool {
287        let l = self.circuit.lit(b);
288        self.solver.value(l.var()) != l.is_negative()
289    }
290
291    fn block_clause(&self, loop_j: Option<usize>) -> Vec<Lit> {
292        let mut block: Vec<Lit> = self
293            .primaries
294            .iter()
295            .map(|p| {
296                let l = self.circuit.lit(p.value);
297                if self.is_true(p.value) { !l } else { l }
298            })
299            .collect();
300        if let Some(j) = loop_j {
301            block.push(!self.circuit.lit(self.loop_vars[j]));
302        }
303        block
304    }
305
306    /// The next model, read as `(fixed, states, loop_to)`, with the model
307    /// ruled out afterwards (LOGIC.md 12.6 and 13.4). `None` when there are
308    /// no more; `Err` when the budget ran out.
309    fn next(&mut self, budget: &Budget) -> Result<Option<(Instance, Vec<Instance>, usize)>, ()> {
310        if self.timed_out {
311            return Err(());
312        }
313        if self.exhausted {
314            return Ok(None);
315        }
316        if self.loop_vars.is_empty() {
317            let j = self.shape.loop_to.unwrap_or(0);
318            return match self.solver.solve(&[], budget) {
319                Solved::Unsat => {
320                    self.exhausted = true;
321                    Ok(None)
322                }
323                Solved::Unknown => Err(()),
324                Solved::Sat => {
325                    let (fixed, states) = self.read();
326                    let block = self.block_clause(None);
327                    if block.is_empty() {
328                        self.exhausted = true;
329                    } else {
330                        self.solver.add_clause(&block);
331                    }
332                    Ok(Some((fixed, states, j)))
333                }
334            };
335        }
336        // Variable-loop search: one solve rules out all `L` loop targets when
337        // UNSAT; when SAT, find the earliest loop target `0..L` under
338        // assumptions on the same solver.
339        if !self.checked_sat {
340            match self.solver.solve(&[], budget) {
341                Solved::Unsat => {
342                    self.exhausted = true;
343                    return Ok(None);
344                }
345                Solved::Unknown => return Err(()),
346                Solved::Sat => {
347                    self.checked_sat = true;
348                    let j = self
349                        .loop_vars
350                        .iter()
351                        .position(|&lv| self.is_true(lv))
352                        .expect("loop_constraint forces exactly one loop target true");
353                    let (fixed, states) = self.read();
354                    let block = self.block_clause(Some(j));
355                    if j == 0 {
356                        self.solver.add_clause(&block);
357                        return Ok(Some((fixed, states, 0)));
358                    }
359                    self.saved = Some((fixed, states, j, block));
360                }
361            }
362        }
363        while self.cur_loop < self.loop_vars.len() {
364            if self
365                .saved
366                .as_ref()
367                .is_some_and(|(_, _, j, _)| *j == self.cur_loop)
368            {
369                let (fixed, states, j, block) = self.saved.take().expect("checked just above");
370                self.solver.add_clause(&block);
371                return Ok(Some((fixed, states, j)));
372            }
373            let lv = self.circuit.lit(self.loop_vars[self.cur_loop]);
374            match self.solver.solve(&[lv], budget) {
375                Solved::Sat => {
376                    let (fixed, states) = self.read();
377                    let block = self.block_clause(Some(self.cur_loop));
378                    self.solver.add_clause(&block);
379                    return Ok(Some((fixed, states, self.cur_loop)));
380                }
381                Solved::Unsat => self.cur_loop += 1,
382                Solved::Unknown => return Err(()),
383            }
384        }
385        self.exhausted = true;
386        Ok(None)
387    }
388
389    /// A model under assumptions, without ruling it out afterwards.
390    fn solve_assuming(
391        &mut self,
392        assumptions: &[Lit],
393        budget: &Budget,
394    ) -> Result<Option<(Instance, Vec<Instance>)>, ()> {
395        Ok(self
396            .solve_assuming_bits(assumptions, budget)?
397            .map(|bits| self.read_from(&bits)))
398    }
399
400    /// A model under assumptions, returning only primary-variable booleans
401    /// without constructing full `Instance`s (used during tuple shrinking).
402    fn solve_assuming_bits(
403        &mut self,
404        assumptions: &[Lit],
405        budget: &Budget,
406    ) -> Result<Option<Vec<bool>>, ()> {
407        if self.timed_out {
408            return Err(());
409        }
410        if self.exhausted {
411            return Ok(None);
412        }
413        match self.solver.solve(assumptions, budget) {
414            Solved::Unsat => Ok(None),
415            Solved::Unknown => Err(()),
416            Solved::Sat => Ok(Some(
417                self.primaries
418                    .iter()
419                    .map(|p| self.is_true(p.value))
420                    .collect(),
421            )),
422        }
423    }
424
425    fn read(&self) -> (Instance, Vec<Instance>) {
426        let bits: Vec<bool> = self
427            .primaries
428            .iter()
429            .map(|p| self.is_true(p.value))
430            .collect();
431        self.read_from(&bits)
432    }
433
434    fn read_from(&self, bits: &[bool]) -> (Instance, Vec<Instance>) {
435        let universe = self.bounds.universe();
436        let mut fixed = Instance::new(universe);
437        let mut states: Vec<Instance> = (0..self.shape.states)
438            .map(|_| Instance::new(universe))
439            .collect();
440        // Each relation's set in each of its states (one for a static
441        // relation, as `Translator::new` allocates them): the lower bound and
442        // the true primaries.
443        let mut sets: Vec<Vec<TupleSet>> = self
444            .bounds
445            .entries()
446            .map(|(r, lower, _)| {
447                let count = if r.is_changing() {
448                    self.shape.states
449                } else {
450                    1
451                };
452                vec![lower.clone(); count]
453            })
454            .collect();
455        for (p, &val) in self.primaries.iter().zip(bits) {
456            if val {
457                sets[p.relation][p.state]
458                    .insert_index(p.tuple)
459                    .expect("a primary variable's tuple is in its relation's upper bound");
460            }
461        }
462        for (r, sets) in self.bounds.relations().zip(sets) {
463            if r.is_changing() {
464                for (instance, set) in states.iter_mut().zip(sets) {
465                    instance
466                        .set(r, set)
467                        .expect("the bounds' relations are distinct and well formed");
468                }
469            } else {
470                let set = sets
471                    .into_iter()
472                    .next()
473                    .expect("a static relation has one set");
474                fixed
475                    .set(r, set)
476                    .expect("the bounds' relations are distinct and well formed");
477            }
478        }
479        (fixed, states)
480    }
481}
482
483/// The trace shapes a search tries in turn (LOGIC.md 13.4): for a temporal
484/// problem, one per number of states from 1 to `steps`, each with its loop
485/// target left to the solver; otherwise one state looping to itself.
486fn shapes(temporal: bool, steps: usize, depth: usize) -> Vec<Shape> {
487    if temporal {
488        (1..=steps.max(1))
489            .map(|l| Shape::variable_loop(l, depth))
490            .collect()
491    } else {
492        vec![Shape::single(depth)]
493    }
494}
495
496struct Engine<'f> {
497    user_bounds: Bounds,
498    bounds: Bounds,
499    formula: Formula,
500    skolemized: Formula,
501    options: Options,
502    temporal: bool,
503    shapes: Vec<Shape>,
504    next_shape: usize,
505    current: Option<Search>,
506    make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
507    /// The size of the latest search, and the conflicts of the searches
508    /// already finished; `stats()` adds the current one's.
509    stats: Stats,
510    /// Shared wall-clock deadline across all trace shapes when `options.budget.time` is set.
511    deadline: Option<Instant>,
512    /// Which budget limit caused the last `Next::Unknown`, if known.
513    last_unknown: Option<BudgetExhausted>,
514}
515
516impl<'f> Engine<'f> {
517    fn new(
518        bounds: &Bounds,
519        formula: &Formula,
520        options: &Options,
521        make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
522    ) -> Result<Engine<'f>, Vec<Error>> {
523        let errors = check_formula(formula, Against::Bounds(bounds));
524        if !errors.is_empty() {
525            return Err(errors);
526        }
527        let sk = skolemize(formula, bounds);
528        // LOGIC.md 12.2: what skolemization leaves over sets or relations
529        // cannot be grounded.
530        let remaining = higher_order(&sk.formula);
531        if !remaining.is_empty() {
532            return Err(remaining);
533        }
534        let temporal = bounds.relations().any(Relation::is_changing);
535        let shapes = shapes(temporal, options.steps, formula.past_depth());
536        let deadline = options.budget.time.map(|t| Instant::now() + t);
537        Ok(Engine {
538            user_bounds: bounds.clone(),
539            bounds: sk.bounds,
540            formula: formula.clone(),
541            skolemized: sk.formula,
542            options: *options,
543            temporal,
544            shapes,
545            next_shape: 0,
546            current: None,
547            make_solver,
548            stats: Stats::default(),
549            deadline,
550            last_unknown: None,
551        })
552    }
553
554    fn stats(&self) -> Stats {
555        let mut stats = self.stats;
556        stats.conflicts += self.current.as_ref().map_or(0, |s| s.solver.conflicts());
557        stats
558    }
559
560    fn unknown_reason(&self) -> Option<BudgetExhausted> {
561        self.last_unknown
562    }
563
564    fn remaining_budget(&self) -> Option<Budget> {
565        let mut b = self.options.budget;
566        if let Some(deadline) = self.deadline {
567            let rem = deadline.checked_duration_since(Instant::now())?;
568            b.time = Some(rem);
569        }
570        Some(b)
571    }
572
573    fn next_instance(&mut self) -> Next {
574        self.last_unknown = None;
575        loop {
576            let Some(budget) = self.remaining_budget() else {
577                self.last_unknown = Some(BudgetExhausted::Time);
578                return Next::Unknown;
579            };
580            if self.current.is_none() {
581                let Some(&shape) = self.shapes.get(self.next_shape) else {
582                    return Next::Done;
583                };
584                self.next_shape += 1;
585                let solver = (self.make_solver)();
586                let search =
587                    Search::new(&self.bounds, &self.skolemized, shape, &self.options, solver);
588                self.stats.primary_variables = search.primaries.len() as u32;
589                self.stats.gates = search.circuit.gate_count();
590                self.current = Some(search);
591            }
592            let search = self.current.as_mut().expect("set just above");
593            match search.next(&budget) {
594                Err(()) => {
595                    self.last_unknown = search.solver.unknown_reason().or_else(|| {
596                        if self.deadline.is_some_and(|d| Instant::now() >= d) {
597                            Some(BudgetExhausted::Time)
598                        } else {
599                            None
600                        }
601                    });
602                    return Next::Unknown;
603                }
604                Ok(None) => {
605                    self.stats.conflicts += search.solver.conflicts();
606                    self.current = None;
607                }
608                Ok(Some((fixed, states, loop_to))) => {
609                    return if self.temporal {
610                        let trace = Trace::new(fixed, states, loop_to)
611                            .expect("a shape has states and a loop target among them");
612                        self.referee_trace(&trace);
613                        Next::Trace(trace)
614                    } else {
615                        self.referee(&fixed);
616                        Next::Instance(fixed)
617                    };
618                }
619            }
620        }
621    }
622
623    fn referee(&self, instance: &Instance) {
624        referee_instance(&self.user_bounds, &self.formula, &self.skolemized, instance);
625    }
626
627    fn referee_trace(&self, trace: &Trace) {
628        referee_trace(&self.user_bounds, &self.formula, &self.skolemized, trace);
629    }
630}
631
632/// A search for the instances, or traces, of one problem, one after
633/// another. With changing relations, it tries the shapes of LOGIC.md 13.4
634/// in order: by number of states, then by loop target.
635///
636/// ```
637/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
638/// use elinvar_engine::{Finder, Next, Options};
639///
640/// let u = Universe::new(["A", "B"]).unwrap();
641/// let s = Relation::unary("S");
642/// let mut b = Bounds::new(&u);
643/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
644///
645/// let mut finder = Finder::new(&b, &Expr::relation(&s).some(), &Options::default()).unwrap();
646/// let mut found = 0;
647/// while let Next::Instance(_) = finder.next_instance() {
648///     found += 1;
649/// }
650/// assert!(found >= 1);
651/// ```
652pub struct Finder(Engine<'static>);
653
654impl Finder {
655    /// Translates a problem: bounds and a formula with no free variables,
656    /// using the default solver.
657    ///
658    /// Errors: every error of the formula against the bounds, together.
659    pub fn new(
660        bounds: &Bounds,
661        formula: &Formula,
662        options: &Options,
663    ) -> Result<Finder, Vec<Error>> {
664        Finder::with_solver(bounds, formula, options, Cdcl::new)
665    }
666
667    /// Translates a problem using a solver built by `make_solver` (R9,
668    /// DESIGN.md section 7.4). Each trace shape asks for a fresh solver.
669    /// Every returned instance or trace is still refereed by `elinvar-logic`.
670    ///
671    /// Errors: every error of the formula against the bounds, together.
672    pub fn with_solver<S, F>(
673        bounds: &Bounds,
674        formula: &Formula,
675        options: &Options,
676        mut make_solver: F,
677    ) -> Result<Finder, Vec<Error>>
678    where
679        S: Solver + 'static,
680        F: FnMut() -> S + 'static,
681    {
682        let factory = Box::new(move || Box::new(make_solver()) as Box<dyn Solver>);
683        Ok(Finder(Engine::new(bounds, formula, options, factory)?))
684    }
685
686    /// Statistics so far: the size of the last translation, and the
687    /// conflicts of every solve.
688    pub fn stats(&self) -> Stats {
689        self.0.stats()
690    }
691
692    /// The next instance or trace, after ruling out those already given
693    /// (LOGIC.md 12.6 and 13.4).
694    pub fn next_instance(&mut self) -> Next {
695        self.0.next_instance()
696    }
697}
698
699/// Every quantifier over sets or relations left in a formula
700/// (`logic.higher_order`), once per variable.
701fn higher_order(f: &Formula) -> Vec<Error> {
702    fn expr(e: &elinvar_logic::Expr, out: &mut Vec<Error>) {
703        match e.kind() {
704            ExprKind::Binary(_, a, b) => {
705                expr(a, out);
706                expr(b, out);
707            }
708            ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr(a, out),
709            ExprKind::Comprehension(decls, body) => {
710                for d in decls {
711                    expr(&d.expr, out);
712                }
713                formula(body, out);
714            }
715            ExprKind::IfThenElse(c, a, b) => {
716                formula(c, out);
717                expr(a, out);
718                expr(b, out);
719            }
720            ExprKind::IntToSet(v) => int(v, out),
721            ExprKind::Relation(_)
722            | ExprKind::Variable(_)
723            | ExprKind::None
724            | ExprKind::Univ
725            | ExprKind::Iden => {}
726        }
727    }
728    fn int(v: &elinvar_logic::IntExpr, out: &mut Vec<Error>) {
729        use elinvar_logic::IntExprKind as K;
730        match v.kind() {
731            K::Constant(_) => {}
732            K::Count(e) | K::Sum(e) => expr(e, out),
733            K::Binary(_, a, b) => {
734                int(a, out);
735                int(b, out);
736            }
737            K::Negate(a) => int(a, out),
738            K::IfThenElse(c, a, b) => {
739                formula(c, out);
740                int(a, out);
741                int(b, out);
742            }
743            // A sum's declarations are of atoms, checked when it is built.
744            K::SumOver(decls, body) => {
745                for d in decls {
746                    expr(&d.expr, out);
747                }
748                int(body, out);
749            }
750        }
751    }
752    fn formula(f: &Formula, out: &mut Vec<Error>) {
753        match f.kind() {
754            FormulaKind::Constant(_) => {}
755            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
756                expr(a, out);
757                expr(b, out);
758            }
759            FormulaKind::Multiplicity(_, a) => expr(a, out),
760            FormulaKind::Not(g) | FormulaKind::Temporal(_, g) => formula(g, out),
761            FormulaKind::And(fs) | FormulaKind::Or(fs) => {
762                for g in fs {
763                    formula(g, out);
764                }
765            }
766            FormulaKind::Implies(a, b)
767            | FormulaKind::Iff(a, b)
768            | FormulaKind::TemporalBinary(_, a, b) => {
769                formula(a, out);
770                formula(b, out);
771            }
772            FormulaKind::Quantified(_, decls, body) => {
773                for d in decls {
774                    expr(&d.expr, out);
775                    if !d.is_first_order() {
776                        let e = Error::new(
777                            "logic.higher_order",
778                            format!(
779                                "`{}` ranges over sets or relations under a quantifier that \
780                                 skolemization cannot remove",
781                                d.var
782                            ),
783                        )
784                        .at(f.place().clone());
785                        if !out.contains(&e) {
786                            out.push(e);
787                        }
788                    }
789                }
790                formula(body, out);
791            }
792            FormulaKind::IntCompare(_, a, b) => {
793                int(a, out);
794                int(b, out);
795            }
796        }
797    }
798    let mut out = Vec::new();
799    formula(f, &mut out);
800    out
801}
802
803/// LOGIC.md 12.7: within the bounds, and the formula as the user wrote it
804/// is true. A failure is a bug in Elinvar (AGENTS.md law 13).
805fn referee_instance(bounds: &Bounds, formula: &Formula, skolemized: &Formula, instance: &Instance) {
806    assert!(
807        bounds.admits(instance),
808        "Elinvar bug: the solver returned an instance outside the bounds \
809         (the referee's check of LOGIC.md 12.7). Please report it with the model."
810    );
811    let verdict = match evaluate(instance, formula) {
812        // LOGIC.md 12.7: too large to enumerate as written; the witnesses
813        // the instance names decide it.
814        Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
815            evaluate(instance, skolemized)
816        }
817        other => other,
818    };
819    if verdict != Ok(true) {
820        panic!(
821            "Elinvar bug: the solver returned an instance under which the formula \
822             is {verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
823             report it with the model."
824        );
825    }
826}
827
828fn referee_trace(bounds: &Bounds, formula: &Formula, skolemized: &Formula, trace: &Trace) {
829    assert!(
830        trace.within(bounds),
831        "Elinvar bug: the solver returned a trace outside the bounds \
832         (the referee's check of LOGIC.md 12.7). Please report it with the model."
833    );
834    let verdict = match evaluate_trace(trace, formula) {
835        Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
836            evaluate_trace(trace, skolemized)
837        }
838        other => other,
839    };
840    if verdict != Ok(true) {
841        panic!(
842            "Elinvar bug: the solver returned a trace on which the formula is \
843             {verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
844             report it with the model."
845        );
846    }
847}
848
849/// LOGIC.md 14.3, step 3: fewer tuples. Returns the smallest instance or
850/// trace found, the conflicts spent, and whether shrinking finished within
851/// `budget`. `None` if there is no instance of that shape, or the first
852/// solve runs out of budget.
853#[allow(clippy::too_many_arguments)]
854pub(crate) fn shrink_tuples(
855    full_bounds: &Bounds,
856    full_formula: &Formula,
857    shrink_bounds: &Bounds,
858    shrink_formula: &Formula,
859    states: usize,
860    loop_to: usize,
861    budget: u64,
862    solver: Box<dyn Solver>,
863) -> Option<(Next, u64, bool)> {
864    let sk = skolemize(shrink_formula, shrink_bounds);
865    let temporal = full_bounds.relations().any(Relation::is_changing);
866    let depth = shrink_formula.past_depth();
867    let shape = if temporal {
868        Shape::new(states, loop_to, depth)
869    } else {
870        Shape::single(depth)
871    };
872    let off = Options::default().symmetry_breaking(false);
873    let mut search = Search::new(&sk.bounds, &sk.formula, shape, &off, solver);
874    let wrap = |(fixed, states): (Instance, Vec<Instance>)| {
875        if temporal {
876            let trace = Trace::new(fixed, states, loop_to)
877                .expect("a shape has states and a loop target among them");
878            referee_trace(full_bounds, full_formula, &sk.formula, &trace);
879            Next::Trace(trace)
880        } else {
881            referee_instance(full_bounds, full_formula, &sk.formula, &fixed);
882            Next::Instance(fixed)
883        }
884    };
885    let spent = |s: &Search| s.solver.conflicts();
886    // LOGIC.md 14.3: conflicts only, so the instance returned never depends
887    // on time (AGENTS.md law 17).
888    let left = |s: &Search| Budget::conflicts(budget.saturating_sub(spent(s)).max(1));
889    let first_budget = left(&search);
890    let Ok(Some(mut current)) = search.solve_assuming_bits(&[], &first_budget) else {
891        return None;
892    };
893    let mut forced: Vec<Lit> = Vec::new();
894    let mut finished = true;
895    let total_primaries = search.primaries.len();
896    let mut k = 0usize;
897    let mut batch = Vec::with_capacity(4);
898    while k < total_primaries {
899        if !current[k] {
900            k += 1;
901            continue;
902        }
903        if spent(&search) >= budget {
904            finished = false;
905            break;
906        }
907        // Try removing up to 4 true primaries at once; if the batch is UNSAT,
908        // fall back to testing them individually in number order.
909        batch.clear();
910        let mut scan = k;
911        while scan < total_primaries && batch.len() < 4 {
912            if current[scan] {
913                batch.push(scan);
914            }
915            scan += 1;
916        }
917        if batch.len() >= 2 {
918            let saved_len = forced.len();
919            for &idx in &batch {
920                forced.push(!search.circuit.lit(search.primaries[idx].value));
921            }
922            let step_budget = left(&search);
923            match search.solve_assuming_bits(&forced, &step_budget) {
924                Ok(Some(found)) => {
925                    current = found;
926                    k = scan;
927                    continue;
928                }
929                Ok(None) => {
930                    forced.truncate(saved_len);
931                }
932                Err(()) => {
933                    forced.truncate(saved_len);
934                    finished = false;
935                    break;
936                }
937            }
938        }
939        for &idx in &batch {
940            if !current[idx] {
941                continue;
942            }
943            if spent(&search) >= budget {
944                finished = false;
945                break;
946            }
947            let step_budget = left(&search);
948            forced.push(!search.circuit.lit(search.primaries[idx].value));
949            match search.solve_assuming_bits(&forced, &step_budget) {
950                Ok(Some(found)) => current = found,
951                Ok(None) => {
952                    forced.pop();
953                }
954                Err(()) => {
955                    forced.pop();
956                    finished = false;
957                    break;
958                }
959            }
960        }
961        if !finished {
962            break;
963        }
964        k = scan;
965    }
966    let used = spent(&search);
967    Some((wrap(search.read_from(&current)), used, finished))
968}
969
970fn format_duration(d: Duration) -> String {
971    let ms = d.as_millis();
972    if ms == 0 {
973        "0ms".to_string()
974    } else if ms < 1000 {
975        format!("{ms}ms")
976    } else if ms.is_multiple_of(60_000) {
977        format!("{}m", ms / 60_000)
978    } else if ms.is_multiple_of(1000) {
979        format!("{}s", ms / 1000)
980    } else {
981        format!("{:.2}s", d.as_secs_f64())
982    }
983}
984
985fn unknown_note(budget: &Budget, reason: Option<BudgetExhausted>, known: &str) -> String {
986    let which = match reason {
987        Some(BudgetExhausted::Time) => match budget.time {
988            Some(t) => format!("the time limit of {}", format_duration(t)),
989            None => "the time limit".to_string(),
990        },
991        Some(BudgetExhausted::Conflicts) => match budget.conflicts {
992            Some(c) => format!("the conflict budget of {c} conflicts"),
993            None => "the conflict budget".to_string(),
994        },
995        None => match (budget.conflicts, budget.time) {
996            (Some(c), Some(t)) => {
997                format!("the budget of {c} conflicts or {}", format_duration(t))
998            }
999            (Some(c), None) => format!("the conflict budget of {c} conflicts"),
1000            (None, Some(t)) => format!("the time limit of {}", format_duration(t)),
1001            (None, None) => "the budget".to_string(),
1002        },
1003    };
1004    format!("{which} ran out; {known}")
1005}
1006
1007impl Outcome {
1008    fn from_next(next: Next, found: Verdict, stats: Stats) -> Option<Outcome> {
1009        let (instance, trace) = match next {
1010            Next::Instance(i) => (Some(i), None),
1011            Next::Trace(t) => (None, Some(t)),
1012            Next::Done | Next::Unknown => return None,
1013        };
1014        Some(Outcome {
1015            verdict: found,
1016            instance,
1017            trace,
1018            labels: Vec::new(),
1019            note: None,
1020            stats,
1021        })
1022    }
1023
1024    fn without(verdict: Verdict, note: Option<String>, stats: Stats) -> Outcome {
1025        Outcome {
1026            verdict,
1027            instance: None,
1028            trace: None,
1029            labels: Vec::new(),
1030            note,
1031            stats,
1032        }
1033    }
1034}
1035
1036/// Looks for an instance of `formula` within `bounds`; with changing
1037/// relations, a trace of at most `options.steps` states.
1038///
1039/// ```
1040/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
1041/// use elinvar_engine::{Options, Verdict, run};
1042///
1043/// let u = Universe::new(["A", "B"]).unwrap();
1044/// let s = Relation::unary("S");
1045/// let mut b = Bounds::new(&u);
1046/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
1047///
1048/// let out = run(&b, &Expr::relation(&s).one(), &Options::default()).unwrap();
1049/// assert_eq!(out.verdict, Verdict::Found);
1050/// ```
1051pub fn run(bounds: &Bounds, formula: &Formula, options: &Options) -> Result<Outcome, Vec<Error>> {
1052    run_with_solver(bounds, formula, options, Cdcl::new)
1053}
1054
1055/// Like [`run`], using a solver built by `make_solver` (R9, DESIGN.md
1056/// section 7.4). Every returned instance or trace is still refereed by
1057/// `elinvar-logic`.
1058pub fn run_with_solver<S, F>(
1059    bounds: &Bounds,
1060    formula: &Formula,
1061    options: &Options,
1062    mut make_solver: F,
1063) -> Result<Outcome, Vec<Error>>
1064where
1065    S: Solver + 'static,
1066    F: FnMut() -> S,
1067{
1068    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
1069    let mut finder = Engine::new(bounds, formula, options, factory)?;
1070    let next = finder.next_instance();
1071    let stats = finder.stats();
1072    Ok(match next {
1073        Next::Done => Outcome::without(Verdict::None, None, stats),
1074        Next::Unknown => Outcome::without(
1075            Verdict::Unknown,
1076            Some(unknown_note(
1077                &options.budget,
1078                finder.unknown_reason(),
1079                "nothing is known",
1080            )),
1081            stats,
1082        ),
1083        next => Outcome::from_next(next, Verdict::Found, stats).expect("an instance or a trace"),
1084    })
1085}
1086
1087/// Looks for a counterexample to `assertion` under `rules` within
1088/// `bounds`; when there is none, tells `holds` from `vacuous` (LOGIC.md
1089/// 12.1 and 13.4).
1090///
1091/// ```
1092/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
1093/// use elinvar_engine::{Options, Verdict, check};
1094///
1095/// let u = Universe::new(["A", "B"]).unwrap();
1096/// let s = Relation::unary("S");
1097/// let mut b = Bounds::new(&u);
1098/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
1099/// let se = Expr::relation(&s);
1100///
1101/// let out = check(&b, &se.some(), &se.is_in(&Expr::univ()), &Options::default()).unwrap();
1102/// assert_eq!(out.verdict, Verdict::Holds);
1103///
1104/// let vacuous = check(&b, &se.some().and(&se.no()), &se.some(), &Options::default()).unwrap();
1105/// assert_eq!(vacuous.verdict, Verdict::Vacuous);
1106/// ```
1107pub fn check(
1108    bounds: &Bounds,
1109    rules: &Formula,
1110    assertion: &Formula,
1111    options: &Options,
1112) -> Result<Outcome, Vec<Error>> {
1113    check_with_solver(bounds, rules, assertion, options, Cdcl::new)
1114}
1115
1116/// Like [`check`], using a solver built by `make_solver` (R9, DESIGN.md
1117/// section 7.4). Every returned instance or trace is still refereed by
1118/// `elinvar-logic`.
1119pub fn check_with_solver<S, F>(
1120    bounds: &Bounds,
1121    rules: &Formula,
1122    assertion: &Formula,
1123    options: &Options,
1124    mut make_solver: F,
1125) -> Result<Outcome, Vec<Error>>
1126where
1127    S: Solver + 'static,
1128    F: FnMut() -> S,
1129{
1130    let deadline = options.budget.time.map(|t| Instant::now() + t);
1131    let negated = rules.and(&assertion.not());
1132    let mut stats = {
1133        let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
1134        let mut finder = Engine::new(bounds, &negated, options, factory)?;
1135        let next = finder.next_instance();
1136        let stats = finder.stats();
1137        match next {
1138            Next::Done => stats,
1139            Next::Unknown => {
1140                return Ok(Outcome::without(
1141                    Verdict::Unknown,
1142                    Some(unknown_note(
1143                        &options.budget,
1144                        finder.unknown_reason(),
1145                        "nothing is known",
1146                    )),
1147                    stats,
1148                ));
1149            }
1150            next => {
1151                return Ok(Outcome::from_next(next, Verdict::Counterexample, stats)
1152                    .expect("an instance or a trace"));
1153            }
1154        }
1155    };
1156    let mut rules_opts = *options;
1157    if let Some(d) = deadline {
1158        let Some(rem) = d.checked_duration_since(Instant::now()) else {
1159            return Ok(Outcome::without(
1160                Verdict::Unknown,
1161                Some(unknown_note(
1162                    &options.budget,
1163                    Some(BudgetExhausted::Time),
1164                    "no counterexample exists within the bounds, and whether the rules allow any case is not settled",
1165                )),
1166                stats,
1167            ));
1168        };
1169        rules_opts.budget.time = Some(rem);
1170    }
1171    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
1172    let mut rules_only = Engine::new(bounds, rules, &rules_opts, factory)?;
1173    let next = rules_only.next_instance();
1174    stats.conflicts += rules_only.stats().conflicts;
1175    let (verdict, note) = match next {
1176        Next::Instance(_) | Next::Trace(_) => (Verdict::Holds, None),
1177        Next::Done => (Verdict::Vacuous, None),
1178        Next::Unknown => (
1179            Verdict::Unknown,
1180            Some(unknown_note(
1181                &options.budget,
1182                rules_only.unknown_reason(),
1183                "no counterexample exists within the bounds, and whether the rules allow any case is not settled",
1184            )),
1185        ),
1186    };
1187    Ok(Outcome::without(verdict, note, stats))
1188}
1189
1190/// Solves `formula` on a single fixed-length path of `states` states (with a
1191/// self-loop on state `states - 1`, never read when `formula` has only bounded
1192/// `after` operators). Used by k-induction (N9) for exact base and step checks.
1193pub(crate) fn solve_fixed_states<S, F>(
1194    bounds: &Bounds,
1195    formula: &Formula,
1196    states: usize,
1197    options: &Options,
1198    mut make_solver: F,
1199) -> Result<(Next, Stats), Vec<Error>>
1200where
1201    S: Solver + 'static,
1202    F: FnMut() -> S,
1203{
1204    let errors = check_formula(formula, Against::Bounds(bounds));
1205    if !errors.is_empty() {
1206        return Err(errors);
1207    }
1208    let sk = skolemize(formula, bounds);
1209    let errors = higher_order(&sk.formula);
1210    if !errors.is_empty() {
1211        return Err(errors);
1212    }
1213    let temporal = bounds.relations().any(Relation::is_changing) || formula.is_temporal();
1214    let depth = 0;
1215    let loop_to = states.saturating_sub(1);
1216    let shape = if temporal {
1217        Shape::new(states.max(1), loop_to, depth)
1218    } else {
1219        Shape::single(depth)
1220    };
1221    let deadline = options.budget.time.map(|t| Instant::now() + t);
1222    let solver = Box::new(make_solver()) as Box<dyn Solver>;
1223    let mut search = Search::new(&sk.bounds, &sk.formula, shape, options, solver);
1224    let stats = |s: &Search| Stats {
1225        primary_variables: s.primaries.len() as u32,
1226        gates: s.circuit.gate_count(),
1227        conflicts: s.solver.conflicts(),
1228    };
1229    let mut eff_budget = options.budget;
1230    if let Some(d) = deadline {
1231        let Some(rem) = d.checked_duration_since(Instant::now()) else {
1232            return Ok((Next::Unknown, stats(&search)));
1233        };
1234        if rem.is_zero() {
1235            return Ok((Next::Unknown, stats(&search)));
1236        }
1237        eff_budget.time = Some(rem);
1238    }
1239    match search.solve_assuming(&[], &eff_budget) {
1240        Ok(Some((fixed, st))) => {
1241            let st_out = stats(&search);
1242            let next = if temporal {
1243                let trace = Trace::new(fixed, st, loop_to)
1244                    .expect("a shape has states and a loop target among them");
1245                referee_trace(bounds, formula, &sk.formula, &trace);
1246                Next::Trace(trace)
1247            } else {
1248                referee_instance(bounds, formula, &sk.formula, &fixed);
1249                Next::Instance(fixed)
1250            };
1251            Ok((next, st_out))
1252        }
1253        Ok(None) => Ok((Next::Done, stats(&search))),
1254        Err(()) => Ok((Next::Unknown, stats(&search))),
1255    }
1256}
1257
1258/// The number of instances, or traces, of `formula` within `bounds`, by
1259/// the solver, up to `limit`. `None` if the budget ran out first. With
1260/// symmetry breaking off and no changing relations, this is the count brute
1261/// force gives (R18).
1262pub fn count(
1263    bounds: &Bounds,
1264    formula: &Formula,
1265    options: &Options,
1266    limit: u64,
1267) -> Result<Option<u64>, Vec<Error>> {
1268    count_with_solver(bounds, formula, options, limit, Cdcl::new)
1269}
1270
1271/// Like [`count`], using a solver built by `make_solver` (R9, DESIGN.md
1272/// section 7.4).
1273pub fn count_with_solver<S, F>(
1274    bounds: &Bounds,
1275    formula: &Formula,
1276    options: &Options,
1277    limit: u64,
1278    mut make_solver: F,
1279) -> Result<Option<u64>, Vec<Error>>
1280where
1281    S: Solver + 'static,
1282    F: FnMut() -> S,
1283{
1284    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
1285    let mut finder = Engine::new(bounds, formula, options, factory)?;
1286    let mut n = 0;
1287    while n < limit {
1288        match finder.next_instance() {
1289            Next::Instance(_) | Next::Trace(_) => n += 1,
1290            Next::Done => return Ok(Some(n)),
1291            Next::Unknown => return Ok(None),
1292        }
1293    }
1294    Ok(Some(n))
1295}
1296
1297/// Which named rules were used to establish a `holds` or `vacuous` verdict
1298/// (REQUIREMENTS.md section 8). Dropping every rule in `unused` leaves the
1299/// check unsatisfiable; dropping any rule in `used` can break it.
1300#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1301#[non_exhaustive]
1302pub struct HoldsCore {
1303    /// Rules in the minimal unsatisfiable core, in declaration order.
1304    pub used: Vec<String>,
1305    /// Rules not needed for this check within the scope, in declaration order.
1306    pub unused: Vec<String>,
1307}
1308
1309impl fmt::Display for HoldsCore {
1310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1311        write!(f, "used rules: {}", self.used.join(", "))?;
1312        if !self.unused.is_empty() {
1313            write!(f, "; unused rules: {}", self.unused.join(", "))?;
1314        }
1315        Ok(())
1316    }
1317}
1318
1319/// Result of budget-bounded core extraction (B13, B14).
1320pub(crate) enum CoreResult {
1321    /// Core minimization completed cleanly across all trace lengths.
1322    Complete(HoldsCore),
1323    /// The conflict budget ran out before core extraction or minimization finished.
1324    Incomplete {
1325        core: Option<HoldsCore>,
1326        note: String,
1327    },
1328    /// The negated assertion was satisfiable under the rules (not UNSAT).
1329    NotUnsat,
1330}
1331
1332fn expr_is_state_only(e: &Expr) -> bool {
1333    match e.kind() {
1334        ExprKind::Relation(_)
1335        | ExprKind::Variable(_)
1336        | ExprKind::None
1337        | ExprKind::Univ
1338        | ExprKind::Iden => true,
1339        ExprKind::Prime(_) => false,
1340        ExprKind::Unary(_, a) => expr_is_state_only(a),
1341        ExprKind::Binary(_, a, b) => expr_is_state_only(a) && expr_is_state_only(b),
1342        ExprKind::IfThenElse(c, a, b) => {
1343            formula_is_state_only(c) && expr_is_state_only(a) && expr_is_state_only(b)
1344        }
1345        ExprKind::Comprehension(ds, body) => {
1346            ds.iter().all(|d| expr_is_state_only(&d.expr)) && formula_is_state_only(body)
1347        }
1348        ExprKind::IntToSet(n) => int_is_state_only(n),
1349    }
1350}
1351
1352fn int_is_state_only(n: &IntExpr) -> bool {
1353    match n.kind() {
1354        IntExprKind::Constant(_) => true,
1355        IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_is_state_only(e),
1356        IntExprKind::Negate(a) => int_is_state_only(a),
1357        IntExprKind::Binary(_, a, b) => int_is_state_only(a) && int_is_state_only(b),
1358        IntExprKind::IfThenElse(c, a, b) => {
1359            formula_is_state_only(c) && int_is_state_only(a) && int_is_state_only(b)
1360        }
1361        IntExprKind::SumOver(ds, body) => {
1362            ds.iter().all(|d| expr_is_state_only(&d.expr)) && int_is_state_only(body)
1363        }
1364    }
1365}
1366
1367fn formula_is_state_only(f: &Formula) -> bool {
1368    match f.kind() {
1369        FormulaKind::Constant(_) => true,
1370        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1371            expr_is_state_only(a) && expr_is_state_only(b)
1372        }
1373        FormulaKind::Multiplicity(_, a) => expr_is_state_only(a),
1374        FormulaKind::Not(g) => formula_is_state_only(g),
1375        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(formula_is_state_only),
1376        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
1377            formula_is_state_only(a) && formula_is_state_only(b)
1378        }
1379        FormulaKind::Quantified(_, ds, body) => {
1380            ds.iter().all(|d| expr_is_state_only(&d.expr)) && formula_is_state_only(body)
1381        }
1382        FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
1383        FormulaKind::IntCompare(_, a, b) => int_is_state_only(a) && int_is_state_only(b),
1384    }
1385}
1386
1387fn expr_mentions_changing(e: &Expr) -> bool {
1388    match e.kind() {
1389        ExprKind::Relation(r) => r.is_changing(),
1390        ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
1391        ExprKind::Prime(_) => true,
1392        ExprKind::Unary(_, a) => expr_mentions_changing(a),
1393        ExprKind::Binary(_, a, b) => expr_mentions_changing(a) || expr_mentions_changing(b),
1394        ExprKind::IfThenElse(c, a, b) => {
1395            formula_mentions_changing(c) || expr_mentions_changing(a) || expr_mentions_changing(b)
1396        }
1397        ExprKind::Comprehension(ds, body) => {
1398            ds.iter().any(|d| expr_mentions_changing(&d.expr)) || formula_mentions_changing(body)
1399        }
1400        ExprKind::IntToSet(n) => int_mentions_changing(n),
1401    }
1402}
1403
1404fn int_mentions_changing(n: &IntExpr) -> bool {
1405    match n.kind() {
1406        IntExprKind::Constant(_) => false,
1407        IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_mentions_changing(e),
1408        IntExprKind::Negate(a) => int_mentions_changing(a),
1409        IntExprKind::Binary(_, a, b) => int_mentions_changing(a) || int_mentions_changing(b),
1410        IntExprKind::IfThenElse(c, a, b) => {
1411            formula_mentions_changing(c) || int_mentions_changing(a) || int_mentions_changing(b)
1412        }
1413        IntExprKind::SumOver(ds, body) => {
1414            ds.iter().any(|d| expr_mentions_changing(&d.expr)) || int_mentions_changing(body)
1415        }
1416    }
1417}
1418
1419fn formula_mentions_changing(f: &Formula) -> bool {
1420    match f.kind() {
1421        FormulaKind::Constant(_) => false,
1422        FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
1423            expr_mentions_changing(a) || expr_mentions_changing(b)
1424        }
1425        FormulaKind::Multiplicity(_, a) => expr_mentions_changing(a),
1426        FormulaKind::Not(g) => formula_mentions_changing(g),
1427        FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(formula_mentions_changing),
1428        FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
1429            formula_mentions_changing(a) || formula_mentions_changing(b)
1430        }
1431        FormulaKind::Quantified(_, ds, body) => {
1432            ds.iter().any(|d| expr_mentions_changing(&d.expr)) || formula_mentions_changing(body)
1433        }
1434        FormulaKind::Temporal(_, g) => formula_mentions_changing(g),
1435        FormulaKind::TemporalBinary(_, a, b) => {
1436            formula_mentions_changing(a) || formula_mentions_changing(b)
1437        }
1438        FormulaKind::IntCompare(_, a, b) => int_mentions_changing(a) || int_mentions_changing(b),
1439    }
1440}
1441
1442fn unwrap_always_state_only(f: &Formula) -> Option<Formula> {
1443    let mut cur = f;
1444    while let FormulaKind::And(fs) = cur.kind()
1445        && fs.len() == 1
1446    {
1447        cur = &fs[0];
1448    }
1449    match cur.kind() {
1450        FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
1451            Some(inner.clone())
1452        }
1453        _ if formula_is_state_only(cur) => Some(cur.clone()),
1454        _ => None,
1455    }
1456}
1457
1458/// If `f` holds identically at every state of any trace, returns its single-state
1459/// equivalent formula.
1460fn every_state_rule(f: &Formula) -> Option<Formula> {
1461    let mut cur = f;
1462    while let FormulaKind::And(fs) = cur.kind()
1463        && fs.len() == 1
1464    {
1465        cur = &fs[0];
1466    }
1467    match cur.kind() {
1468        FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
1469            Some(inner.clone())
1470        }
1471        FormulaKind::And(fs) => {
1472            let mut parts = Vec::with_capacity(fs.len());
1473            for g in fs {
1474                parts.push(every_state_rule(g)?);
1475            }
1476            Some(Formula::and_all(parts))
1477        }
1478        _ if formula_is_state_only(cur) && !formula_mentions_changing(cur) => Some(cur.clone()),
1479        _ => None,
1480    }
1481}
1482
1483fn build_holds_core(rules: &[(String, Formula)], used_indices: &[usize]) -> HoldsCore {
1484    let mut used = Vec::new();
1485    let mut unused = Vec::new();
1486    for (i, (name, _)) in rules.iter().enumerate() {
1487        if used_indices.contains(&i) {
1488            if !used.contains(name) {
1489                used.push(name.clone());
1490            }
1491        } else if !used.contains(name) && !unused.contains(name) {
1492            unused.push(name.clone());
1493        }
1494    }
1495    unused.retain(|n| !used.contains(n));
1496    HoldsCore { used, unused }
1497}
1498
1499fn solve_budgeted(
1500    solver: &mut Cdcl,
1501    assumptions: &[Lit],
1502    remaining: &mut u64,
1503    deadline: Option<std::time::Instant>,
1504) -> Solved {
1505    if *remaining == 0 {
1506        return Solved::Unknown;
1507    }
1508    let time = match deadline {
1509        Some(d) => {
1510            let Some(rem) = d.checked_duration_since(std::time::Instant::now()) else {
1511                return Solved::Unknown;
1512            };
1513            if rem.is_zero() {
1514                return Solved::Unknown;
1515            }
1516            Some(rem)
1517        }
1518        None => None,
1519    };
1520    let before = solver.conflicts();
1521    let budget = Budget {
1522        conflicts: Some(*remaining),
1523        time,
1524    };
1525    let res = solver.solve(assumptions, &budget);
1526    let spent = solver.conflicts().saturating_sub(before);
1527    *remaining = remaining.saturating_sub(spent);
1528    res
1529}
1530
1531/// Budget-bounded minimal unsatisfiable core extraction (B13, B14):
1532/// tries cheap answers first (0 rules, then every-state static rules on 1 state),
1533/// then minimizes globally across all trace lengths under one shared budget.
1534pub(crate) fn explain_core_budgeted(
1535    bounds: &Bounds,
1536    rules: &[(String, Formula)],
1537    assertion: &Formula,
1538    options: &Options,
1539    remaining: &mut u64,
1540) -> Result<CoreResult, Vec<Error>> {
1541    let mut errors = check_formula(assertion, Against::Bounds(bounds));
1542    for (_, f) in rules {
1543        for e in check_formula(f, Against::Bounds(bounds)) {
1544            if !errors.contains(&e) {
1545                errors.push(e);
1546            }
1547        }
1548    }
1549    if !errors.is_empty() {
1550        return Err(errors);
1551    }
1552    // B69: share one wall-clock deadline across every core-extraction probe.
1553    let time_limit = options.budget.time.map(|d| std::time::Instant::now() + d);
1554
1555    // Stage 0 & 1 (B14): for a state-only invariant `always P` (or static `P`),
1556    // check 0 rules and then every-state static rules on a single state first!
1557    // This answers tautologies and static-rule holds in milliseconds without
1558    // unrolling the trace or ever touching `fact Steps` (B13).
1559    if let Some(p) = unwrap_always_state_only(assertion) {
1560        let sk_p = skolemize(&p.not(), bounds);
1561        if higher_order(&sk_p.formula).is_empty() {
1562            // Stage 0: 0 rules on 1 state.
1563            let mut circuit0 = Circuit::new();
1564            let mut solver0 = Cdcl::new();
1565            let root0 = {
1566                let (mut tr, _, _) = Translator::new(&mut circuit0, &sk_p.bounds, Shape::single(0));
1567                tr.formula(&sk_p.formula)
1568            };
1569            if !circuit0.assert(&mut solver0, root0) {
1570                return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
1571            }
1572            match solve_budgeted(&mut solver0, &[], remaining, time_limit) {
1573                Solved::Unsat => {
1574                    return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
1575                }
1576                Solved::Unknown => {
1577                    return Ok(CoreResult::Incomplete {
1578                        core: None,
1579                        note: "core extraction did not finish within budget".to_string(),
1580                    });
1581                }
1582                Solved::Sat => {}
1583            }
1584
1585            // Stage 1: every-state static rules only on 1 state.
1586            let static_pairs: Vec<(usize, Formula)> = rules
1587                .iter()
1588                .enumerate()
1589                .filter_map(|(i, (_, f))| every_state_rule(f).map(|sf| (i, sf)))
1590                .collect();
1591            if !static_pairs.is_empty() {
1592                if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
1593                    return Ok(CoreResult::Incomplete {
1594                        core: None,
1595                        note: "core extraction did not finish within budget".to_string(),
1596                    });
1597                }
1598                let mut cur_b = sk_p.bounds.clone();
1599                let mut sk_static = Vec::with_capacity(static_pairs.len());
1600                let mut static_ok = true;
1601                for (orig_i, sf) in &static_pairs {
1602                    let skr = skolemize(sf, &cur_b);
1603                    if !higher_order(&skr.formula).is_empty() {
1604                        static_ok = false;
1605                        break;
1606                    }
1607                    cur_b = skr.bounds;
1608                    sk_static.push((*orig_i, skr.formula));
1609                }
1610                if static_ok {
1611                    let mut circuit1 = Circuit::new();
1612                    let mut solver1 = Cdcl::new();
1613                    let (root1, rbs) = {
1614                        let (mut tr, _, _) =
1615                            Translator::new(&mut circuit1, &cur_b, Shape::single(0));
1616                        let r = tr.formula(&sk_p.formula);
1617                        let bs: Vec<Bool> = sk_static.iter().map(|(_, f)| tr.formula(f)).collect();
1618                        (r, bs)
1619                    };
1620                    if !circuit1.assert(&mut solver1, root1) {
1621                        return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
1622                    }
1623                    let mut lits = Vec::with_capacity(rbs.len());
1624                    for rb in rbs {
1625                        let act = Lit::positive(solver1.new_var());
1626                        circuit1.assert_if(&mut solver1, act, rb);
1627                        lits.push(act);
1628                    }
1629                    match solve_budgeted(&mut solver1, &lits, remaining, time_limit) {
1630                        Solved::Unsat => {
1631                            let init = solver1.unsat_core();
1632                            let mut core_pos: Vec<usize> = (0..lits.len())
1633                                .filter(|&k| init.contains(&lits[k]))
1634                                .collect();
1635                            let mut i = core_pos.len();
1636                            while i > 0 {
1637                                i -= 1;
1638                                let without: Vec<Lit> = core_pos
1639                                    .iter()
1640                                    .enumerate()
1641                                    .filter(|&(j, _)| j != i)
1642                                    .map(|(_, &k)| lits[k])
1643                                    .collect();
1644                                match solve_budgeted(&mut solver1, &without, remaining, time_limit)
1645                                {
1646                                    Solved::Unsat => {
1647                                        let refined = solver1.unsat_core();
1648                                        core_pos.retain(|&k| refined.contains(&lits[k]));
1649                                        i = i.min(core_pos.len());
1650                                    }
1651                                    Solved::Unknown => {
1652                                        let orig: Vec<usize> =
1653                                            core_pos.iter().map(|&k| sk_static[k].0).collect();
1654                                        return Ok(CoreResult::Incomplete {
1655                                            core: Some(build_holds_core(rules, &orig)),
1656                                            note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
1657                                        });
1658                                    }
1659                                    Solved::Sat => {}
1660                                }
1661                            }
1662                            let orig: Vec<usize> =
1663                                core_pos.iter().map(|&k| sk_static[k].0).collect();
1664                            return Ok(CoreResult::Complete(build_holds_core(rules, &orig)));
1665                        }
1666                        Solved::Unknown => {
1667                            return Ok(CoreResult::Incomplete {
1668                                core: None,
1669                                note: "core extraction did not finish within budget".to_string(),
1670                            });
1671                        }
1672                        Solved::Sat => {}
1673                    }
1674                }
1675            }
1676        }
1677    }
1678
1679    // Stage 2: full temporal (or non-invariant) global MUS across all shapes.
1680    let sk_assert = skolemize(&assertion.not(), bounds);
1681    let mut ho = higher_order(&sk_assert.formula);
1682    let mut sk_rules = Vec::with_capacity(rules.len());
1683    let mut cur_bounds = sk_assert.bounds;
1684    for (_, f) in rules {
1685        let sk_r = skolemize(f, &cur_bounds);
1686        for e in higher_order(&sk_r.formula) {
1687            if !ho.contains(&e) {
1688                ho.push(e);
1689            }
1690        }
1691        cur_bounds = sk_r.bounds;
1692        sk_rules.push(sk_r.formula);
1693    }
1694    if !ho.is_empty() {
1695        return Err(ho);
1696    }
1697    let temporal = cur_bounds.relations().any(Relation::is_changing);
1698    let mut depth = sk_assert.formula.past_depth();
1699    for f in &sk_rules {
1700        depth = depth.max(f.past_depth());
1701    }
1702    // Check largest shapes first: they are the strongest filter for deletion probes.
1703    let mut shape_list = shapes(temporal, options.steps, depth);
1704    shape_list.reverse();
1705
1706    let mut active_solvers: Vec<(Cdcl, Vec<Lit>)> = Vec::new();
1707    let mut union_mask = vec![false; rules.len()];
1708    for shape in shape_list {
1709        if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
1710            return Ok(CoreResult::Incomplete {
1711                core: None,
1712                note: "core extraction did not finish within budget".to_string(),
1713            });
1714        }
1715        let mut circuit = Circuit::new();
1716        let mut solver = Cdcl::new();
1717        let (root, rule_bools) = {
1718            let (mut tr, _, loop_vars) = Translator::new(&mut circuit, &cur_bounds, shape);
1719            let mut root = tr.formula(&sk_assert.formula);
1720            if !loop_vars.is_empty() && root != Bool::FALSE {
1721                let lc = tr.loop_constraint();
1722                root = tr.circuit.and([root, lc]);
1723            }
1724            let rbs: Vec<Bool> = sk_rules.iter().map(|f| tr.formula(f)).collect();
1725            (root, rbs)
1726        };
1727        if !circuit.assert(&mut solver, root) {
1728            continue;
1729        }
1730        let mut lits = Vec::with_capacity(rule_bools.len());
1731        for rb in rule_bools {
1732            let act = Lit::positive(solver.new_var());
1733            circuit.assert_if(&mut solver, act, rb);
1734            lits.push(act);
1735        }
1736        match solve_budgeted(&mut solver, &lits, remaining, time_limit) {
1737            Solved::Sat => return Ok(CoreResult::NotUnsat),
1738            Solved::Unknown => {
1739                return Ok(CoreResult::Incomplete {
1740                    core: None,
1741                    note: "core extraction did not finish within budget".to_string(),
1742                });
1743            }
1744            Solved::Unsat => {
1745                let init = solver.unsat_core();
1746                for (i, lit) in lits.iter().enumerate() {
1747                    if init.contains(lit) {
1748                        union_mask[i] = true;
1749                    }
1750                }
1751                active_solvers.push((solver, lits));
1752            }
1753        }
1754    }
1755
1756    let mut core: Vec<usize> = (0..rules.len()).filter(|&i| union_mask[i]).collect();
1757    // B13: global deletion-based MUS across ALL shapes together, trying to drop
1758    // temporal transition rules first so unnecessary trace facts are always pruned.
1759    let mut trial_order: Vec<usize> = core
1760        .iter()
1761        .copied()
1762        .filter(|&i| every_state_rule(&rules[i].1).is_none())
1763        .rev()
1764        .collect();
1765    trial_order.extend(
1766        core.iter()
1767            .copied()
1768            .filter(|&i| every_state_rule(&rules[i].1).is_some())
1769            .rev(),
1770    );
1771
1772    for cand in trial_order {
1773        if !core.contains(&cand) {
1774            continue;
1775        }
1776        let without_idx: Vec<usize> = core.iter().copied().filter(|&i| i != cand).collect();
1777        let mut all_unsat = true;
1778        for (solver, lits) in &mut active_solvers {
1779            let assumps: Vec<Lit> = without_idx.iter().map(|&i| lits[i]).collect();
1780            match solve_budgeted(solver, &assumps, remaining, time_limit) {
1781                Solved::Unsat => {}
1782                Solved::Sat => {
1783                    all_unsat = false;
1784                    break;
1785                }
1786                Solved::Unknown => {
1787                    return Ok(CoreResult::Incomplete {
1788                        core: Some(build_holds_core(rules, &core)),
1789                        note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
1790                    });
1791                }
1792            }
1793        }
1794        if all_unsat {
1795            core = without_idx;
1796        }
1797    }
1798    Ok(CoreResult::Complete(build_holds_core(rules, &core)))
1799}
1800
1801/// Extracts a minimal subset of `rules` that suffices to rule out any
1802/// counterexample to `assertion` within `bounds` (REQUIREMENTS.md section 8).
1803///
1804/// Returns `Ok(None)` if a counterexample exists or the budget runs out.
1805/// Symmetry breaking is disabled during core extraction so the core reflects
1806/// only the named rules.
1807pub fn explain_core(
1808    bounds: &Bounds,
1809    rules: &[(String, Formula)],
1810    assertion: &Formula,
1811    options: &Options,
1812) -> Result<Option<HoldsCore>, Vec<Error>> {
1813    let mut remaining = options.budget.conflicts.unwrap_or(DEFAULT_CONFLICTS);
1814    match explain_core_budgeted(bounds, rules, assertion, options, &mut remaining)? {
1815        CoreResult::Complete(core) => Ok(Some(core)),
1816        CoreResult::Incomplete { .. } | CoreResult::NotUnsat => Ok(None),
1817    }
1818}
1819
1820/// The tuple set of a relation by name in an instance, for tests and
1821/// renderings.
1822pub fn tuples_named<'a>(instance: &'a Instance, name: &str) -> Option<&'a TupleSet> {
1823    instance
1824        .entries()
1825        .find(|(r, _)| r.name() == name)
1826        .map(|(_, t)| t)
1827}
1828
1829#[cfg(test)]
1830mod tests {
1831    use super::*;
1832    use elinvar_logic::{Expr, Universe};
1833
1834    /// LOGIC.md 13.6: the worked examples, translated on the fixed shape
1835    /// shrinking uses, three states looping to state 1, with `s` pinned to
1836    /// `{}`, `{A}`, `{}`. Each holds there exactly when its value is true.
1837    #[test]
1838    fn worked_examples_on_a_fixed_loop() {
1839        let u = Universe::new(["A"]).expect("one atom is a universe");
1840        let r = Relation::changing("s", 1);
1841        let mut bounds = Bounds::new(&u);
1842        bounds
1843            .bound_upper(&r, u.all(1).expect("arity 1"))
1844            .expect("s is new");
1845        let s = Expr::relation(&r);
1846        let (some, none) = (s.some(), s.no());
1847        let pinned = none.and(&some.and(&none.after()).after());
1848        let cases: Vec<(Formula, bool)> = vec![
1849            (some.clone(), false),
1850            (some.after(), true),
1851            (some.eventually(), true),
1852            (some.always(), false),
1853            (some.eventually().always(), true),
1854            (some.always().eventually(), false),
1855            (none.until(&some), true),
1856            (some.releases(&none), false),
1857            (some.once(), false),
1858            (some.once().after(), true),
1859            (some.before().after().after(), true),
1860            (none.historically().eventually(), true),
1861            (some.implies(&none.before()).always(), true),
1862            (none.since(&some).after(), true),
1863            (some.triggered(&none), true),
1864            (s.prime().equals(&s), false),
1865            (s.prime().equals(&s).not().always(), true),
1866        ];
1867        for (f, want) in cases {
1868            for (g, holds) in [(f.clone(), want), (f.not(), !want)] {
1869                let full = pinned.and(&g);
1870                let found = shrink_tuples(
1871                    &bounds,
1872                    &full,
1873                    &bounds,
1874                    &full,
1875                    3,
1876                    1,
1877                    1_000_000,
1878                    Box::new(Cdcl::new()),
1879                );
1880                assert_eq!(found.is_some(), holds, "{g}");
1881            }
1882        }
1883    }
1884}