Skip to main content

elinvar_engine/
report.rs

1//! Results as data, stories, shrinking, and `assert_holds` (LOGIC.md
2//! section 14, R24 to R26, R31).
3
4use crate::model::Command;
5use crate::sat::{Budget, Cdcl, Solver};
6use crate::solve::{HoldsCore, Next, Outcome, Stats, StepLabel, Verdict, shrink_tuples};
7use elinvar_logic::{
8    Error, Formula, FormulaKind, Instance, Quantifier, TemporalOp, Trace, TupleSet, Variable,
9    evaluate_trace_at, evaluate_trace_expr_at,
10};
11use serde::Serialize;
12use serde::ser::{SerializeMap, Serializer};
13use std::collections::BTreeMap;
14use std::fmt::Write as _;
15
16/// The version of the result's JSON schema (LOGIC.md 14.1).
17pub const RESULT_VERSION: u32 = 1;
18
19/// The JSON Schema of the result, version 1 (LOGIC.md 14.1).
20/// `cargo x generate` writes it to `docs/schema/result-v1.json`.
21pub const RESULT_SCHEMA: &str = r##"{
22  "$schema": "https://json-schema.org/draft/2020-12/schema",
23  "$id": "https://github.com/rustborg/elinvar/docs/schema/result-v1.json",
24  "title": "Elinvar result, version 1",
25  "description": "The result of a run or check command (LOGIC.md section 14.1).",
26  "type": "object",
27  "required": ["elinvar", "command", "name", "verdict", "scope", "shrunk_to", "fully_shrunk",
28               "instance", "trace", "broken_at", "note", "errors", "stats", "story"],
29  "additionalProperties": false,
30  "properties": {
31    "elinvar": { "const": 1 },
32    "command": { "enum": ["run", "check"] },
33    "name": { "type": "string" },
34    "verdict": {
35      "description": "null when there are errors",
36      "enum": ["found", "none", "counterexample", "holds", "proved", "vacuous", "unknown", null]
37    },
38    "scope": { "$ref": "#/$defs/sizes" },
39    "shrunk_to": { "oneOf": [{ "$ref": "#/$defs/sizes" }, { "type": "null" }] },
40    "fully_shrunk": { "type": "boolean" },
41    "instance": { "oneOf": [{ "$ref": "#/$defs/instance" }, { "type": "null" }] },
42    "trace": { "oneOf": [{ "$ref": "#/$defs/trace" }, { "type": "null" }] },
43    "broken_at": { "type": ["integer", "null"], "minimum": 0 },
44    "broken_witness": {
45      "description": "for a broken always-all promise, the variable bindings at broken_at that falsify the body",
46      "type": "array",
47      "items": {
48        "type": "array",
49        "prefixItems": [{ "type": "string" }, { "type": "string" }],
50        "minItems": 2,
51        "maxItems": 2
52      }
53    },
54    "expect": { "type": "integer", "minimum": 0 },
55    "expect_met": { "type": ["boolean", "null"] },
56    "note": { "type": ["string", "null"] },
57    "errors": { "type": "array", "items": { "$ref": "#/$defs/error" } },
58    "warnings": { "type": "array", "items": { "$ref": "#/$defs/error" } },
59    "stats": {
60      "type": "object",
61      "required": ["primary_variables", "gates", "conflicts"],
62      "additionalProperties": false,
63      "properties": {
64        "primary_variables": { "type": "integer", "minimum": 0 },
65        "gates": { "type": "integer", "minimum": 0 },
66        "conflicts": { "type": "integer", "minimum": 0 }
67      }
68    },
69    "core": {
70      "description": "when --explain is requested on a holds or vacuous check, the minimal subset of rules that suffices to rule out counterexamples; on a run with no instance, the minimal subset that, with the run's constraint, allows no instance",
71      "type": "object",
72      "required": ["used", "unused"],
73      "additionalProperties": false,
74      "properties": {
75        "used": { "type": "array", "items": { "type": "string" } },
76        "unused": { "type": "array", "items": { "type": "string" } }
77      }
78    },
79    "story": { "type": "string" }
80  },
81  "$defs": {
82    "sizes": {
83      "description": "atoms per top-level set, in declaration order, and steps for a model with changing relations",
84      "type": "object",
85      "additionalProperties": { "type": "integer", "minimum": 0 }
86    },
87    "tuples": {
88      "type": "array",
89      "items": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
90    },
91    "instance": {
92      "type": "object",
93      "required": ["atoms", "relations"],
94      "additionalProperties": false,
95      "properties": {
96        "atoms": { "type": "array", "items": { "type": "string" } },
97        "bitwidth": {
98          "description": "the bitwidth of the integers, present only with integer atoms (LOGIC.md 16.1)",
99          "type": "integer", "minimum": 1, "maximum": 32
100        },
101        "ints": {
102          "description": "each integer atom's integer, by atom name; present only with integer atoms",
103          "type": "object",
104          "additionalProperties": { "type": "integer" }
105        },
106        "relations": {
107          "type": "array",
108          "items": {
109            "type": "object",
110            "required": ["name", "arity", "tuples"],
111            "additionalProperties": false,
112            "properties": {
113              "name": { "type": "string" },
114              "arity": { "type": "integer", "minimum": 1 },
115              "tuples": { "$ref": "#/$defs/tuples" }
116            }
117          }
118        }
119      }
120    },
121    "trace": {
122      "type": "object",
123      "required": ["fixed", "states", "loop_to", "steps"],
124      "additionalProperties": false,
125      "properties": {
126        "fixed": { "$ref": "#/$defs/instance" },
127        "states": { "type": "array", "items": { "$ref": "#/$defs/instance" }, "minItems": 1 },
128        "loop_to": { "type": "integer", "minimum": 0 },
129        "steps": {
130          "type": "array",
131          "items": {
132            "type": "object",
133            "required": ["step", "to", "action", "args", "changes"],
134            "additionalProperties": false,
135            "properties": {
136              "step": { "type": "integer", "minimum": 0 },
137              "to": { "type": "integer", "minimum": 0 },
138              "action": { "type": ["string", "null"] },
139              "args": { "type": "array", "items": { "type": "string" } },
140              "changes": {
141                "type": "array",
142                "items": {
143                  "type": "object",
144                  "required": ["relation", "gained", "lost"],
145                  "additionalProperties": false,
146                  "properties": {
147                    "relation": { "type": "string" },
148                    "gained": { "$ref": "#/$defs/tuples" },
149                    "lost": { "$ref": "#/$defs/tuples" }
150                  }
151                }
152              }
153            }
154          }
155        }
156      }
157    },
158    "error": {
159      "type": "object",
160      "required": ["code", "message", "fix", "place"],
161      "additionalProperties": false,
162      "properties": {
163        "code": { "type": "string", "pattern": "^[a-z]+\\.[a-z_]+$" },
164        "message": { "type": "string" },
165        "fix": { "type": "string" },
166        "place": {
167          "oneOf": [
168            {
169              "type": "object",
170              "required": ["file", "line", "column"],
171              "additionalProperties": false,
172              "properties": {
173                "file": { "type": "string" },
174                "line": { "type": "integer", "minimum": 1 },
175                "column": { "type": "integer", "minimum": 1 }
176              }
177            },
178            { "type": "null" }
179          ]
180        }
181      }
182    }
183  }
184}
185"##;
186
187/// The default budget of shrinking, in conflicts over all its solves
188/// (LOGIC.md 14.3).
189pub const SHRINK_CONFLICTS: u64 = 1_000_000;
190
191/// Sizes by name, in declaration order, written as a JSON object.
192#[derive(Clone, Debug, Default, PartialEq, Eq)]
193pub struct Sizes(pub Vec<(String, usize)>);
194
195impl Serialize for Sizes {
196    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
197        let mut map = s.serialize_map(Some(self.0.len()))?;
198        for (k, v) in &self.0 {
199            map.serialize_entry(k, v)?;
200        }
201        map.end()
202    }
203}
204
205/// What a changing relation gains and loses in one step.
206#[derive(Clone, Debug, Serialize)]
207#[non_exhaustive]
208pub struct Change {
209    /// The relation.
210    pub relation: String,
211    /// The tuples it gains.
212    pub gained: TupleSet,
213    /// The tuples it loses.
214    pub lost: TupleSet,
215}
216
217/// One step of a trace: out of state `step`, to the next state or, for the
218/// last, back to the loop target.
219#[derive(Clone, Debug, Serialize)]
220#[non_exhaustive]
221pub struct StepReport {
222    /// The state the step leaves.
223    pub step: usize,
224    /// The state it reaches.
225    pub to: usize,
226    /// The action, or `None` when nothing changed.
227    pub action: Option<String>,
228    /// The action's arguments.
229    pub args: Vec<String>,
230    /// What each changing relation gains and loses.
231    pub changes: Vec<Change>,
232}
233
234/// A trace as the result gives it.
235#[derive(Clone, Debug, Serialize)]
236#[non_exhaustive]
237pub struct TraceReport {
238    /// The fixed relations.
239    pub fixed: Instance,
240    /// The states.
241    pub states: Vec<Instance>,
242    /// The state the last one loops back to.
243    pub loop_to: usize,
244    /// One per state.
245    pub steps: Vec<StepReport>,
246}
247
248/// The result of a command (LOGIC.md 14.1).
249#[derive(Clone, Debug, Serialize)]
250#[non_exhaustive]
251#[must_use]
252pub struct Report {
253    /// The schema version.
254    pub elinvar: u32,
255    /// `run` or `check`.
256    pub command: &'static str,
257    /// The command's name.
258    pub name: String,
259    /// The verdict; `None` when there are errors.
260    pub verdict: Option<Verdict>,
261    /// The scope searched.
262    pub scope: Sizes,
263    /// For a counterexample, the scope it was shrunk to.
264    pub shrunk_to: Option<Sizes>,
265    /// Whether shrinking finished within its budget.
266    pub fully_shrunk: bool,
267    /// The instance, without changing relations.
268    pub instance: Option<Instance>,
269    /// The trace, with changing relations.
270    pub trace: Option<TraceReport>,
271    /// For a counterexample to `always P`, the first state where `P` fails.
272    pub broken_at: Option<usize>,
273    /// For a counterexample to `always all x: S | ...`, the first variable
274    /// bindings `(name, atom)` at `broken_at` that falsify the body (W9).
275    #[serde(default, skip_serializing_if = "Vec::is_empty")]
276    pub broken_witness: Vec<(String, String)>,
277    /// The command's `expect 0` or `expect 1` annotation when present (W16).
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub expect: Option<u64>,
280    /// Whether the verdict met `expect` (`None` when `unknown` or no `expect`).
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub expect_met: Option<bool>,
283    /// For `unknown`, which budget ran out and what is known.
284    pub note: Option<String>,
285    /// Every error.
286    pub errors: Vec<Error>,
287    /// Non-fatal warnings about the model or command (such as wrapped integer
288    /// literals or step predicates leaving changing relations unconstrained).
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub warnings: Vec<Error>,
291    /// Statistics.
292    pub stats: Stats,
293    /// When requested on a `holds` or `vacuous` check, or a `run` with no
294    /// instance, which named rules formed the minimal unsatisfiable core
295    /// (REQUIREMENTS.md section 8).
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub core: Option<HoldsCore>,
298    /// The text, made from the fields above.
299    pub story: String,
300}
301
302impl std::fmt::Display for Report {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        f.write_str(&self.story)
305    }
306}
307
308fn difference(a: &TupleSet, b: &TupleSet) -> TupleSet {
309    let mut out = TupleSet::empty(a.universe(), a.arity())
310        .expect("a tuple set's own arity and universe are valid");
311    for i in a.indices().filter(|&i| !b.contains_index(i)) {
312        out.insert_index(i)
313            .expect("an index of a tuple set is an index of its arity");
314    }
315    out
316}
317
318pub(crate) fn trace_report(trace: &Trace, labels: &[StepLabel]) -> TraceReport {
319    let states = trace.states();
320    let steps = (0..states.len())
321        .map(|k| {
322            let to = if k + 1 < states.len() {
323                k + 1
324            } else {
325                trace.loop_to()
326            };
327            let changes = states[k]
328                .entries()
329                .filter_map(|(r, now)| {
330                    let next = states[to].get(r)?;
331                    let gained = difference(next, now);
332                    let lost = difference(now, next);
333                    (!gained.is_empty() || !lost.is_empty()).then(|| Change {
334                        relation: r.name().to_string(),
335                        gained,
336                        lost,
337                    })
338                })
339                .collect();
340            let label = labels.get(k);
341            StepReport {
342                step: k,
343                to,
344                action: label.and_then(|l| l.action.clone()),
345                args: label.map(|l| l.args.clone()).unwrap_or_default(),
346                changes,
347            }
348        })
349        .collect();
350    TraceReport {
351        fixed: trace.fixed().clone(),
352        states: states.to_vec(),
353        loop_to: trace.loop_to(),
354        steps,
355    }
356}
357
358/// LOGIC.md 14.1: the first state where `P` fails, for `always P`, a
359/// single-formula block holding it, or `A implies always P`, plus any
360/// universal quantifier witness bindings at that state (W9).
361fn broken_at_with_witness(
362    assertion: &Formula,
363    trace: &Trace,
364) -> (Option<usize>, Vec<(String, String)>) {
365    let mut a = assertion;
366    loop {
367        match a.kind() {
368            FormulaKind::And(fs) if fs.len() == 1 => a = &fs[0],
369            FormulaKind::Implies(_, rhs) => a = rhs,
370            _ => break,
371        }
372    }
373    let FormulaKind::Temporal(TemporalOp::Always, p) = a.kind() else {
374        return (None, Vec::new());
375    };
376    let Some(k) =
377        (0..trace.states().len()).find(|&k| evaluate_trace_at(trace, p, k, &[]) == Ok(false))
378    else {
379        return (None, Vec::new());
380    };
381    let witness = find_all_witness(p, trace, k);
382    (Some(k), witness)
383}
384
385/// W9: finds the first tuple of variable assignments falsifying `all x1: e1, ... | body`
386/// at state `k` of `trace`.
387fn find_all_witness(formula: &Formula, trace: &Trace, k: usize) -> Vec<(String, String)> {
388    let mut cur = formula;
389    let mut vars: Vec<Variable> = Vec::new();
390    let mut ranges = Vec::new();
391    loop {
392        match cur.kind() {
393            FormulaKind::And(fs) if fs.len() == 1 => cur = &fs[0],
394            FormulaKind::Quantified(Quantifier::All, decls, body) => {
395                for d in decls {
396                    if d.expr.arity() != Some(1) {
397                        return Vec::new();
398                    }
399                    vars.push(d.var.clone());
400                    ranges.push(d.expr.clone());
401                }
402                cur = body;
403            }
404            _ => break,
405        }
406    }
407    if vars.is_empty() {
408        return Vec::new();
409    }
410    let mut domains: Vec<Vec<usize>> = Vec::with_capacity(ranges.len());
411    for r in &ranges {
412        let Ok(ts) = evaluate_trace_expr_at(trace, r, k) else {
413            return Vec::new();
414        };
415        let atoms: Vec<usize> = ts.indices().map(|i| i as usize).collect();
416        if atoms.is_empty() {
417            return Vec::new();
418        }
419        domains.push(atoms);
420    }
421    let total: usize = domains
422        .iter()
423        .try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
424        .unwrap_or(0);
425    if total == 0 || total > 4096 {
426        return Vec::new();
427    }
428    for code in 0..total {
429        let mut atoms = vec![0usize; domains.len()];
430        let mut c = code;
431        for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
432            *slot = dom[c % dom.len()];
433            c /= dom.len();
434        }
435        let bindings: Vec<(Variable, usize)> =
436            vars.iter().cloned().zip(atoms.iter().copied()).collect();
437        if evaluate_trace_at(trace, cur, k, &bindings) == Ok(false) {
438            return vars
439                .iter()
440                .zip(atoms)
441                .map(|(v, idx)| {
442                    let atom = trace
443                        .universe()
444                        .atom(idx)
445                        .expect("atom index from trace universe")
446                        .to_string();
447                    (v.name().to_string(), atom)
448                })
449                .collect();
450        }
451    }
452    Vec::new()
453}
454
455fn check_expect_met(expect: Option<u64>, verdict: Option<Verdict>) -> Option<bool> {
456    let e = expect?;
457    let v = verdict?;
458    match v {
459        Verdict::Unknown => None,
460        Verdict::Found | Verdict::Counterexample => Some(e >= 1),
461        Verdict::Holds | Verdict::Proved | Verdict::Vacuous | Verdict::None => Some(e == 0),
462    }
463}
464
465impl Report {
466    /// The result of a command that could not run: its errors, and no
467    /// verdict (LOGIC.md 14.1).
468    pub fn of_errors(command: &'static str, name: &str, errors: Vec<Error>) -> Report {
469        let mut report = Report::empty(command, name.to_string(), Sizes::default());
470        report.errors = errors;
471        report.story = story(&report);
472        report
473    }
474
475    /// A result with nothing found yet and no story.
476    fn empty(command: &'static str, name: String, scope: Sizes) -> Report {
477        Report {
478            elinvar: RESULT_VERSION,
479            command,
480            name,
481            verdict: None,
482            scope,
483            shrunk_to: None,
484            fully_shrunk: true,
485            instance: None,
486            trace: None,
487            broken_at: None,
488            broken_witness: Vec::new(),
489            expect: None,
490            expect_met: None,
491            note: None,
492            errors: Vec::new(),
493            warnings: Vec::new(),
494            stats: Stats::default(),
495            core: None,
496            story: String::new(),
497        }
498    }
499}
500
501impl Command<'_> {
502    fn scope_sizes(&self) -> Sizes {
503        let mut sizes: Vec<(String, usize)> = self
504            .top_sizes()
505            .into_iter()
506            .map(|(_, name, k, _)| (name, k))
507            .collect();
508        if self.model.has_changing() {
509            sizes.push(("steps".to_string(), self.options.steps));
510        }
511        Sizes(sizes)
512    }
513
514    /// Runs the command with the default solver and returns its result,
515    /// errors included as data.
516    pub fn report(&self) -> Report {
517        self.report_with(Cdcl::new)
518    }
519
520    /// Runs the command and shrinks any counterexample using a solver built
521    /// by `make_solver` (R9, DESIGN.md section 7.4). Every instance or trace
522    /// returned is still refereed by `elinvar-logic`.
523    pub fn report_with<S, F>(&self, mut make_solver: F) -> Report
524    where
525        S: Solver + 'static,
526        F: FnMut() -> S,
527    {
528        let mut report = Report::empty(
529            if self.is_check { "check" } else { "run" },
530            self.name.clone(),
531            self.scope_sizes(),
532        );
533        report.warnings = self.warnings.clone();
534        report.expect = self.expect;
535        match self.solve_with(&mut make_solver) {
536            Err(errors) => report.errors = errors,
537            Ok(out) => {
538                let out = if self.shrink
539                    && matches!(out.verdict, Verdict::Counterexample | Verdict::Found)
540                {
541                    let (out, shrunk_to, fully) = self.shrink_with(out, &mut make_solver);
542                    report.shrunk_to = Some(shrunk_to);
543                    report.fully_shrunk = fully;
544                    out
545                } else {
546                    out
547                };
548                report.verdict = Some(out.verdict);
549                report.expect_met = check_expect_met(report.expect, report.verdict);
550                report.note = out.note.clone();
551                report.stats = out.stats;
552                report.instance = out.instance.clone();
553                if self.is_check
554                    && !self.skip_holds_warnings
555                    && matches!(out.verdict, Verdict::Holds | Verdict::Proved)
556                {
557                    report
558                        .warnings
559                        .extend(self.holds_warnings(&mut make_solver));
560                }
561                if let Some(trace) = &out.trace {
562                    if self.is_check {
563                        let (at, witness) = broken_at_with_witness(&self.formula, trace);
564                        report.broken_at = at;
565                        report.broken_witness = witness;
566                    }
567                    report.trace = Some(trace_report(trace, &out.labels));
568                }
569            }
570        }
571        report.story = story(&report);
572        report
573    }
574
575    /// Runs the command and, when a `check` concludes `holds`, `proved`, or
576    /// `vacuous`, or a `run` finds no instance, also extracts the minimal
577    /// unsatisfiable core of named rules that established it (REQUIREMENTS.md
578    /// section 8, B13, B14). The command's conflict budget covers both the
579    /// solve and the core extraction.
580    pub fn report_explained(&self) -> Report {
581        let mut report = self.report();
582        let total_budget = self
583            .options
584            .budget
585            .conflicts
586            .unwrap_or(crate::solve::DEFAULT_CONFLICTS);
587        let mut remaining = total_budget.saturating_sub(report.stats.conflicts);
588        let res = match report.verdict {
589            Some(Verdict::Vacuous) => self.explain_vacuous_budgeted(&mut remaining).ok(),
590            Some(Verdict::Holds | Verdict::Proved) => {
591                self.explain_assertion_budgeted(&mut remaining).ok()
592            }
593            Some(Verdict::None) => match self.explain_no_instance_budgeted(&mut remaining) {
594                Ok((res, alone)) => {
595                    if alone && !matches!(res, crate::solve::CoreResult::NotUnsat) {
596                        report.note = Some(
597                            "the rules allow no case at all, whatever the run asks".to_string(),
598                        );
599                    }
600                    Some(res)
601                }
602                Err(_) => None,
603            },
604            _ => None,
605        };
606        match res {
607            Some(crate::solve::CoreResult::Complete(core)) => {
608                report.core = Some(core);
609                report.story = story(&report);
610            }
611            Some(crate::solve::CoreResult::Incomplete { core, note }) => {
612                report.core = core;
613                report.note = Some(match report.note.take() {
614                    Some(prev) => format!("{prev}; {note}"),
615                    None => note,
616                });
617                report.story = story(&report);
618            }
619            Some(crate::solve::CoreResult::NotUnsat) | None => {}
620        }
621        report
622    }
623
624    /// LOGIC.md 14.3: fewer atoms, then fewer tuples.
625    fn shrink_with<S, F>(&self, found: Outcome, make_solver: &mut F) -> (Outcome, Sizes, bool)
626    where
627        S: Solver + 'static,
628        F: FnMut() -> S,
629    {
630        let mut best = found;
631        let mut cmd = self.clone();
632        // LOGIC.md 14.3: fewer states come before fewer atoms, so atom
633        // shrinking never needs to search traces longer than `best`.
634        if let Some(trace) = &best.trace {
635            cmd.options.steps = cmd.options.steps.min(trace.states().len());
636        }
637        let mut spent = 0u64;
638        let mut fully = true;
639        // LOGIC.md 14.3: shrinking is bounded by conflicts only, never by
640        // the command's time budget, so the same model and scope give the
641        // same instance however fast the machine (AGENTS.md law 17).
642        let left = |spent: u64| Budget::conflicts(SHRINK_CONFLICTS.saturating_sub(spent).max(1));
643        let target_verdict = if self.is_check {
644            Verdict::Counterexample
645        } else {
646            Verdict::Found
647        };
648        let sets = cmd.top_sizes();
649        let can_fast_skip_unused = !formula_mentions_univ_or_iden(&cmd.facts_for(None))
650            && !formula_mentions_univ_or_iden(&cmd.formula);
651        'sets: for (set, _, start, exact) in sets {
652            if exact {
653                continue;
654            }
655            let mut k = start;
656            if can_fast_skip_unused && start > 0 {
657                let used = used_atoms_for_top_set(&cmd, &best, &set, start);
658                if used == 0 {
659                    // W25: `best` already uses 0 atoms of `set` and no formula
660                    // mentions `univ`/`iden`, so shrinking `set` to 0 needs no SAT call.
661                    cmd = cmd.with_scope(&set, 0);
662                    continue 'sets;
663                }
664                if used + 1 < k {
665                    // Jump directly to the number of atoms `best` actually uses
666                    // before stepping down one by one (deterministic; falls back
667                    // to `k - 1` if `used` is unexpectedly UNSAT).
668                    let budget = left(spent);
669                    let mut trial = cmd.with_scope(&set, used);
670                    trial.options = trial.options.budget(budget);
671                    if let Ok(out) = trial.solve_with(&mut *make_solver) {
672                        spent += out.stats.conflicts;
673                        if out.verdict == target_verdict {
674                            best = out;
675                            cmd = trial;
676                            k = used;
677                        } else if out.verdict == Verdict::Unknown {
678                            fully = false;
679                            break 'sets;
680                        }
681                    }
682                    if spent >= SHRINK_CONFLICTS {
683                        fully = false;
684                        break 'sets;
685                    }
686                }
687            }
688            while k > 0 {
689                let budget = left(spent);
690                let mut trial = cmd.with_scope(&set, k - 1);
691                trial.options = trial.options.budget(budget);
692                match trial.solve_with(&mut *make_solver) {
693                    Ok(out) => {
694                        spent += out.stats.conflicts;
695                        if out.verdict == target_verdict {
696                            best = out;
697                            cmd = trial;
698                            k -= 1;
699                        } else if out.verdict == Verdict::Unknown {
700                            fully = false;
701                            break 'sets;
702                        } else {
703                            break;
704                        }
705                    }
706                    Err(_) => break,
707                }
708                if spent >= SHRINK_CONFLICTS {
709                    fully = false;
710                    break 'sets;
711                }
712            }
713        }
714        if fully && let Ok(bounds) = cmd.bounds() {
715            let full_facts = cmd.facts_for(Some(&bounds));
716            let tuple_formula = if self.is_check {
717                full_facts.and(&self.formula.not())
718            } else {
719                full_facts.and(&self.formula)
720            };
721            let (states, loop_to) = best
722                .trace
723                .as_ref()
724                .map_or((1, 0), |t| (t.states().len(), t.loop_to()));
725            // W27: on a 1-state stuttering trace, transition arms with a pure
726            // stutter step hold automatically, and static `SqlDateFn` total
727            // functions have fixed cardinality that cannot be shrunk. Drop the
728            // transition disjunction and lock `SqlDateFn` to `best`'s values
729            // during tuple shrinking, while still refereeing against the FULL
730            // `tuple_formula` (AGENTS.md law 13).
731            let (shrink_bounds, shrink_formula) = crate::coi::prepare_tuple_shrink(
732                &bounds,
733                &full_facts,
734                &self.formula,
735                self.is_check,
736                states,
737                loop_to,
738                best.instance.as_ref(),
739                best.trace.as_ref(),
740            )
741            .unwrap_or_else(|| (bounds.clone(), tuple_formula.clone()));
742            let budget = SHRINK_CONFLICTS.saturating_sub(spent);
743            match shrink_tuples(
744                &bounds,
745                &tuple_formula,
746                &shrink_bounds,
747                &shrink_formula,
748                states,
749                loop_to,
750                budget,
751                Box::new(make_solver()),
752            ) {
753                Some((next, used, finished)) => {
754                    spent += used;
755                    fully = finished;
756                    match next {
757                        Next::Instance(i) => best.instance = Some(i),
758                        Next::Trace(t) => {
759                            best.labels = self.model.labels_with(&t, &self.extra_step_labels);
760                            best.trace = Some(t);
761                        }
762                        Next::Done | Next::Unknown => {}
763                    }
764                }
765                // `best` is an instance of these bounds, so no instance at
766                // all means the budget ran out before the first one: the
767                // tuples were not shrunk (AGENTS.md law 14).
768                None => fully = false,
769            }
770        }
771        best.stats.conflicts += spent;
772        let sizes = Sizes(
773            cmd.top_sizes()
774                .into_iter()
775                .map(|(_, name, k, _)| (name, k))
776                .collect(),
777        );
778        (best, sizes, fully)
779    }
780
781    /// Runs the check and returns if it holds; otherwise panics with the
782    /// story as the message (LOGIC.md 14.4, R26).
783    #[track_caller]
784    pub fn assert_holds(&self) {
785        let report = self.report();
786        if !matches!(report.verdict, Some(Verdict::Holds | Verdict::Proved)) {
787            panic!("{}", report.story);
788        }
789    }
790}
791
792/// B10: maps atoms belonging uniquely to a singleton sub-signature (such as an
793/// `enum` constant `Learner = {Role0}` or a `one sig Admin extends User {}`)
794/// to that signature's name so stories show `Learner` instead of `Role0`.
795fn singleton_aliases(instance: &Instance) -> BTreeMap<String, String> {
796    let mut counts: BTreeMap<String, Vec<String>> = BTreeMap::new();
797    for (r, t) in instance.entries() {
798        if r.arity() != 1
799            || r.name().starts_with('$')
800            || is_ordering_relation(r.name())
801            || (r.name().contains("_chk_")
802                && (r.name().contains("_val") || r.name().contains("_ord")))
803        {
804            continue;
805        }
806        if t.len() != 1 {
807            continue;
808        }
809        let Some(tup) = t.iter().next() else { continue };
810        let Some(&atom) = tup.names().first() else {
811            continue;
812        };
813        // Skip a top-level set whose single atom is already named `{Set}0`.
814        if let Some(rest) = atom.strip_prefix(r.name())
815            && !rest.is_empty()
816            && rest.bytes().all(|b| b.is_ascii_digit())
817        {
818            continue;
819        }
820        // Skip integer atoms (e.g. `0`, `1`).
821        if atom.parse::<i64>().is_ok() {
822            continue;
823        }
824        counts
825            .entry(atom.to_string())
826            .or_default()
827            .push(r.name().to_string());
828    }
829    let mut aliases = BTreeMap::new();
830    for (atom, names) in counts {
831        if names.len() == 1 {
832            aliases.insert(atom, names.into_iter().next().expect("len is 1"));
833        }
834    }
835    aliases
836}
837
838fn display_atom<'a>(atom: &'a str, aliases: &'a BTreeMap<String, String>) -> &'a str {
839    aliases.get(atom).map(String::as_str).unwrap_or(atom)
840}
841
842fn tuples_text(t: &TupleSet, aliases: &BTreeMap<String, String>) -> String {
843    let parts: Vec<String> = t
844        .iter()
845        .map(|x| {
846            x.names()
847                .iter()
848                .map(|a| display_atom(a, aliases))
849                .collect::<Vec<_>>()
850                .join(" -> ")
851        })
852        .collect();
853    format!("{{{}}}", parts.join(", "))
854}
855
856fn is_ordering_relation(name: &str) -> bool {
857    name == "first" || name == "next" || name.ends_with("/first") || name.ends_with("/next")
858}
859
860fn instance_lines(
861    out: &mut String,
862    instance: &Instance,
863    indent: &str,
864    brief: bool,
865    aliases: &BTreeMap<String, String>,
866) {
867    let mut empty_names: Vec<&str> = Vec::new();
868    let mut order_lines: Vec<(&str, &TupleSet)> = Vec::new();
869    for (r, t) in instance.entries() {
870        if let Some(name) = r.name().strip_prefix('$') {
871            let atoms: Vec<String> = t
872                .iter()
873                .map(|x| {
874                    x.names()
875                        .iter()
876                        .map(|a| display_atom(a, aliases))
877                        .collect::<Vec<_>>()
878                        .join(" -> ")
879                })
880                .collect();
881            let _ = writeln!(out, "{indent}witness {name} = {}", atoms.join(", "));
882        } else if is_ordering_relation(r.name()) {
883            if !brief && !t.is_empty() {
884                order_lines.push((r.name(), t));
885            }
886        } else if t.is_empty() {
887            if !brief {
888                empty_names.push(r.name());
889            }
890        } else {
891            // Omit redundant `Learner = {Learner}` lines once `Role0` is aliased to `Learner`.
892            if r.arity() == 1
893                && t.len() == 1
894                && let Some(tup) = t.iter().next()
895                && let Some(&atom) = tup.names().first()
896                && aliases.get(atom).map(String::as_str) == Some(r.name())
897            {
898                continue;
899            }
900            let _ = writeln!(out, "{indent}{} = {}", r.name(), tuples_text(t, aliases));
901        }
902    }
903    if !order_lines.is_empty() {
904        let parts: Vec<String> = order_lines
905            .into_iter()
906            .map(|(n, t)| format!("{n} = {}", tuples_text(t, aliases)))
907            .collect();
908        let _ = writeln!(out, "{indent}order: {}", parts.join("; "));
909    }
910    if !empty_names.is_empty() {
911        let _ = writeln!(out, "{indent}empty: {}", empty_names.join(", "));
912    }
913}
914
915fn sizes_text(sizes: &Sizes) -> String {
916    sizes
917        .0
918        .iter()
919        .map(|(k, v)| format!("{k}: {v}"))
920        .collect::<Vec<_>>()
921        .join(", ")
922}
923
924/// LOGIC.md 14.2: the text of a result, made from its data.
925pub fn story(r: &Report) -> String {
926    format_story(r, false)
927}
928
929/// A brief version of [`story`] that omits empty relations and library
930/// ordering relations (`first`, `next`), showing only signatures and fields
931/// that hold atoms or tuples.
932pub fn story_brief(r: &Report) -> String {
933    format_story(r, true)
934}
935
936fn format_story(r: &Report, brief: bool) -> String {
937    let mut out = String::new();
938    let title = if r.name.is_empty() {
939        r.command.to_string()
940    } else {
941        format!("{} {}", r.command, r.name)
942    };
943    if !r.errors.is_empty() {
944        let _ = writeln!(out, "{title}: ERRORS");
945        for e in &r.errors {
946            let place = e
947                .place
948                .as_ref()
949                .map(|p| format!("{p}: "))
950                .unwrap_or_default();
951            let _ = writeln!(out, "  {place}error[{}]: {}", e.code, e.message);
952            let _ = writeln!(out, "    fix: {}", e.fix);
953        }
954        return out;
955    }
956    let searched = format!("searched every case up to {}", sizes_text(&r.scope));
957    let expect_tag = match (r.expect, r.expect_met) {
958        (Some(e), Some(true)) => format!(" [expect {e}: met]"),
959        (Some(e), Some(false)) => format!(" [expect {e}: NOT MET]"),
960        (Some(e), None) => format!(" [expect {e}: unknown]"),
961        _ => String::new(),
962    };
963    match r.verdict {
964        Some(Verdict::Holds) => {
965            let _ = writeln!(out, "{title}: holds{expect_tag}");
966            let _ = writeln!(out, "  {searched}; a larger case might still break it.");
967            if let Some(n) = &r.note {
968                let _ = writeln!(out, "  note: {n}");
969            }
970            if let Some(core) = &r.core {
971                let used = if core.used.is_empty() {
972                    "(none: assertion holds from bounds alone)".to_string()
973                } else {
974                    core.used.join(", ")
975                };
976                let _ = writeln!(out, "  used rules: {used}");
977                if !core.unused.is_empty() {
978                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
979                }
980            }
981        }
982        Some(Verdict::Proved) => {
983            let _ = writeln!(out, "{title}: PROVED{expect_tag}");
984            let scope_only: Vec<(String, usize)> = r
985                .scope
986                .0
987                .iter()
988                .filter(|(k, _)| k != "steps")
989                .cloned()
990                .collect();
991            let scope_text = sizes_text(&Sizes(scope_only));
992            let reason = r
993                .note
994                .as_deref()
995                .unwrap_or("proved for any number of steps by induction");
996            let _ = writeln!(out, "  {reason}, for all cases up to {scope_text}.");
997            if let Some(core) = &r.core {
998                let used = if core.used.is_empty() {
999                    "(none: assertion holds from bounds alone)".to_string()
1000                } else {
1001                    core.used.join(", ")
1002                };
1003                let _ = writeln!(out, "  used rules: {used}");
1004                if !core.unused.is_empty() {
1005                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
1006                }
1007            }
1008        }
1009        Some(Verdict::Vacuous) => {
1010            let _ = writeln!(out, "{title}: VACUOUS{expect_tag}");
1011            let _ = writeln!(
1012                out,
1013                "  the rules allow no case at all up to {}, so nothing can break the promise.",
1014                sizes_text(&r.scope)
1015            );
1016            if let Some(n) = &r.note {
1017                let _ = writeln!(out, "  note: {n}");
1018            }
1019            if let Some(core) = &r.core
1020                && !core.used.is_empty()
1021            {
1022                let _ = writeln!(out, "  conflicting rules: {}", core.used.join(", "));
1023            }
1024        }
1025        Some(Verdict::None) => {
1026            let _ = writeln!(out, "{title}: no instance{expect_tag}");
1027            let _ = writeln!(out, "  {searched}.");
1028            if let Some(core) = &r.core {
1029                if let Some(n) = &r.note {
1030                    let _ = writeln!(out, "  note: {n}");
1031                }
1032                let used = if core.used.is_empty() {
1033                    "(none: the run's own constraint allows no case)".to_string()
1034                } else {
1035                    core.used.join(", ")
1036                };
1037                let _ = writeln!(out, "  used rules: {used}");
1038                if !core.unused.is_empty() {
1039                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
1040                }
1041            }
1042        }
1043        Some(Verdict::Unknown) | None => {
1044            let _ = writeln!(out, "{title}: UNKNOWN{expect_tag}");
1045            if let Some(n) = &r.note {
1046                let _ = writeln!(out, "  {n}");
1047            }
1048        }
1049        Some(Verdict::Found) | Some(Verdict::Counterexample) => {
1050            let word = if r.verdict == Some(Verdict::Found) {
1051                "found"
1052            } else {
1053                "COUNTEREXAMPLE"
1054            };
1055            let (prep, size) = match &r.shrunk_to {
1056                Some(s) => ("with", s),
1057                None => ("in scope", &r.scope),
1058            };
1059            match &r.trace {
1060                None => {
1061                    let _ = writeln!(
1062                        out,
1063                        "{title}: {word} {prep} {}{expect_tag}",
1064                        sizes_text(size)
1065                    );
1066                    if let Some(i) = &r.instance {
1067                        let aliases = singleton_aliases(i);
1068                        instance_lines(&mut out, i, "  ", brief, &aliases);
1069                    }
1070                }
1071                Some(t) => {
1072                    let aliases = singleton_aliases(&t.fixed);
1073                    let _ = writeln!(
1074                        out,
1075                        "{title}: {word} in {} states, {prep} {}{expect_tag}",
1076                        t.states.len(),
1077                        sizes_text(size)
1078                    );
1079                    let _ = writeln!(out, "  start");
1080                    instance_lines(&mut out, &t.fixed, "    ", brief, &aliases);
1081                    if let Some(s0) = t.states.first() {
1082                        for (r, ts) in s0.entries().filter(|(_, ts)| !ts.is_empty()) {
1083                            let _ =
1084                                writeln!(out, "    {} = {}", r.name(), tuples_text(ts, &aliases));
1085                        }
1086                    }
1087                    for s in &t.steps {
1088                        // A model without actions has no names for its steps;
1089                        // "nothing" is said only when nothing changes.
1090                        let action = match &s.action {
1091                            Some(a) if s.args.is_empty() => format!("  {a}"),
1092                            Some(a) => {
1093                                let args: Vec<&str> =
1094                                    s.args.iter().map(|x| display_atom(x, &aliases)).collect();
1095                                format!("  {a}({})", args.join(", "))
1096                            }
1097                            None if s.changes.is_empty() => "  nothing changes".to_string(),
1098                            None => String::new(),
1099                        };
1100                        let changes: Vec<String> = s
1101                            .changes
1102                            .iter()
1103                            .map(|c| {
1104                                let mut parts = Vec::new();
1105                                if !c.gained.is_empty() {
1106                                    parts.push(format!(
1107                                        "{} gains {}",
1108                                        c.relation,
1109                                        tuples_text(&c.gained, &aliases)
1110                                    ));
1111                                }
1112                                if !c.lost.is_empty() {
1113                                    parts.push(format!(
1114                                        "{} loses {}",
1115                                        c.relation,
1116                                        tuples_text(&c.lost, &aliases)
1117                                    ));
1118                                }
1119                                parts.join(", ")
1120                            })
1121                            .collect();
1122                        let loops = if s.to <= s.step {
1123                            format!(", back to state {}", s.to)
1124                        } else {
1125                            String::new()
1126                        };
1127                        let _ = writeln!(
1128                            out,
1129                            "  step {}{action}{}{loops}",
1130                            s.step + 1,
1131                            if changes.is_empty() {
1132                                String::new()
1133                            } else {
1134                                format!("  {}", changes.join("; "))
1135                            }
1136                        );
1137                    }
1138                    if let Some(k) = r.broken_at {
1139                        let who = if r.broken_witness.is_empty() {
1140                            String::new()
1141                        } else {
1142                            let pairs: Vec<String> = r
1143                                .broken_witness
1144                                .iter()
1145                                .map(|(v, a)| format!("{v} = {}", display_atom(a, &aliases)))
1146                                .collect();
1147                            format!(" (for {})", pairs.join(", "))
1148                        };
1149                        let _ =
1150                            writeln!(out, "  broken at state {k}, as step {} begins{who}", k + 1);
1151                    }
1152                }
1153            }
1154            if r.verdict == Some(Verdict::Counterexample) {
1155                let _ = writeln!(out, "  {searched}.");
1156                if !r.fully_shrunk {
1157                    let _ = writeln!(out, "  (not fully shrunk: shrinking ran out of its budget)");
1158                }
1159            }
1160        }
1161    }
1162    for w in &r.warnings {
1163        let place = w
1164            .place
1165            .as_ref()
1166            .map(|p| format!("{p}: "))
1167            .unwrap_or_default();
1168        let _ = writeln!(out, "  {place}warning[{}]: {}", w.code, w.message);
1169        let _ = writeln!(out, "    fix: {}", w.fix);
1170    }
1171    out
1172}
1173
1174fn expr_mentions_univ_or_iden(e: &elinvar_logic::Expr) -> bool {
1175    use elinvar_logic::ExprKind as K;
1176    match e.kind() {
1177        K::Univ | K::Iden => true,
1178        K::Relation(_) | K::Variable(_) | K::None => false,
1179        K::Unary(_, a) | K::Prime(a) => expr_mentions_univ_or_iden(a),
1180        K::Binary(_, a, b) => expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b),
1181        K::Comprehension(ds, body) => {
1182            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1183                || formula_mentions_univ_or_iden(body)
1184        }
1185        K::IfThenElse(c, a, b) => {
1186            formula_mentions_univ_or_iden(c)
1187                || expr_mentions_univ_or_iden(a)
1188                || expr_mentions_univ_or_iden(b)
1189        }
1190        K::IntToSet(i) => int_mentions_univ_or_iden(i),
1191    }
1192}
1193
1194fn int_mentions_univ_or_iden(i: &elinvar_logic::IntExpr) -> bool {
1195    use elinvar_logic::IntExprKind as K;
1196    match i.kind() {
1197        K::Constant(_) => false,
1198        K::Count(e) | K::Sum(e) => expr_mentions_univ_or_iden(e),
1199        K::Binary(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
1200        K::Negate(a) => int_mentions_univ_or_iden(a),
1201        K::IfThenElse(c, a, b) => {
1202            formula_mentions_univ_or_iden(c)
1203                || int_mentions_univ_or_iden(a)
1204                || int_mentions_univ_or_iden(b)
1205        }
1206        K::SumOver(ds, body) => {
1207            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1208                || int_mentions_univ_or_iden(body)
1209        }
1210    }
1211}
1212
1213fn formula_mentions_univ_or_iden(f: &elinvar_logic::Formula) -> bool {
1214    use elinvar_logic::FormulaKind as K;
1215    match f.kind() {
1216        K::Constant(_) => false,
1217        K::Subset(a, b) | K::Equal(a, b) => {
1218            expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b)
1219        }
1220        K::Multiplicity(_, a) => expr_mentions_univ_or_iden(a),
1221        K::Not(g) | K::Temporal(_, g) => formula_mentions_univ_or_iden(g),
1222        K::And(fs) | K::Or(fs) => fs.iter().any(formula_mentions_univ_or_iden),
1223        K::Implies(a, b) | K::Iff(a, b) | K::TemporalBinary(_, a, b) => {
1224            formula_mentions_univ_or_iden(a) || formula_mentions_univ_or_iden(b)
1225        }
1226        K::Quantified(_, ds, body) => {
1227            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1228                || formula_mentions_univ_or_iden(body)
1229        }
1230        K::IntCompare(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
1231    }
1232}
1233
1234/// Counts how many distinct atoms from top-level set `set`'s upper bound
1235/// actually appear in any relation tuple of `best` (W25).
1236fn used_atoms_for_top_set(
1237    cmd: &Command<'_>,
1238    best: &Outcome,
1239    set: &elinvar_logic::Expr,
1240    fallback: usize,
1241) -> usize {
1242    let elinvar_logic::ExprKind::Relation(set_rel) = set.kind() else {
1243        return fallback;
1244    };
1245    let Ok(bounds) = cmd.bounds() else {
1246        return fallback;
1247    };
1248    let Some(up) = bounds.upper(set_rel) else {
1249        return fallback;
1250    };
1251    let bu = bounds.universe();
1252    let pool_names: std::collections::BTreeSet<&str> = up
1253        .indices()
1254        .filter_map(|idx| bu.atom(idx as usize))
1255        .collect();
1256    if pool_names.is_empty() {
1257        return 0;
1258    }
1259    let mut used_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1260    let mut scan_inst = |inst: &elinvar_logic::Instance| {
1261        let u = inst.universe();
1262        let n = u.size() as u64;
1263        if n == 0 {
1264            return;
1265        }
1266        for (rel, ts) in inst.entries() {
1267            let arity = rel.arity();
1268            for mut idx in ts.indices() {
1269                for _ in 0..arity {
1270                    let a = (idx % n) as usize;
1271                    if let Some(name) = u.atom(a)
1272                        && let Some(&pname) = pool_names.get(name)
1273                    {
1274                        used_names.insert(pname);
1275                    }
1276                    idx /= n;
1277                }
1278            }
1279        }
1280    };
1281    if let Some(inst) = &best.instance {
1282        scan_inst(inst);
1283    } else if let Some(tr) = &best.trace {
1284        scan_inst(tr.fixed());
1285        for st in tr.states() {
1286            scan_inst(st);
1287        }
1288    } else {
1289        return fallback;
1290    }
1291    used_names.len()
1292}