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