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        let mut spent = 0u64;
633        let mut fully = true;
634        // LOGIC.md 14.3: shrinking is bounded by conflicts only, never by
635        // the command's time budget, so the same model and scope give the
636        // same instance however fast the machine (AGENTS.md law 17).
637        let left = |spent: u64| Budget::conflicts(SHRINK_CONFLICTS.saturating_sub(spent).max(1));
638        let target_verdict = if self.is_check {
639            Verdict::Counterexample
640        } else {
641            Verdict::Found
642        };
643        let sets = cmd.top_sizes();
644        let can_fast_skip_unused = !formula_mentions_univ_or_iden(&cmd.facts_for(None))
645            && !formula_mentions_univ_or_iden(&cmd.formula);
646        'sets: for (set, _, start, exact) in sets {
647            if exact {
648                continue;
649            }
650            let mut k = start;
651            if can_fast_skip_unused
652                && start > 0
653                && used_atoms_for_top_set(&cmd, &best, &set, start) == 0
654            {
655                // W25: `best` already uses 0 atoms of `set` and no formula
656                // mentions `univ`/`iden`, so shrinking `set` to 0 needs no SAT call.
657                cmd = cmd.with_scope(&set, 0);
658                continue 'sets;
659            }
660            while k > 0 {
661                let budget = left(spent);
662                let mut trial = cmd.with_scope(&set, k - 1);
663                trial.options = trial.options.budget(budget);
664                match trial.solve_with(&mut *make_solver) {
665                    Ok(out) => {
666                        spent += out.stats.conflicts;
667                        if out.verdict == target_verdict {
668                            best = out;
669                            cmd = trial;
670                            k -= 1;
671                        } else if out.verdict == Verdict::Unknown {
672                            fully = false;
673                            break 'sets;
674                        } else {
675                            break;
676                        }
677                    }
678                    Err(_) => break,
679                }
680                if spent >= SHRINK_CONFLICTS {
681                    fully = false;
682                    break 'sets;
683                }
684            }
685        }
686        if fully && let Ok(bounds) = cmd.bounds() {
687            let full_facts = cmd.facts_for(Some(&bounds));
688            let tuple_formula = if self.is_check {
689                full_facts.and(&self.formula.not())
690            } else {
691                full_facts.and(&self.formula)
692            };
693            let (states, loop_to) = best
694                .trace
695                .as_ref()
696                .map_or((1, 0), |t| (t.states().len(), t.loop_to()));
697            // W27: on a 1-state stuttering trace, transition arms with a pure
698            // stutter step hold automatically, and static `SqlDateFn` total
699            // functions have fixed cardinality that cannot be shrunk. Drop the
700            // transition disjunction and lock `SqlDateFn` to `best`'s values
701            // during tuple shrinking, while still refereeing against the FULL
702            // `tuple_formula` (AGENTS.md law 13).
703            let (shrink_bounds, shrink_formula) = crate::coi::prepare_tuple_shrink(
704                &bounds,
705                &full_facts,
706                &self.formula,
707                self.is_check,
708                states,
709                loop_to,
710                best.instance.as_ref(),
711                best.trace.as_ref(),
712            )
713            .unwrap_or_else(|| (bounds.clone(), tuple_formula.clone()));
714            let budget = SHRINK_CONFLICTS.saturating_sub(spent);
715            match shrink_tuples(
716                &bounds,
717                &tuple_formula,
718                &shrink_bounds,
719                &shrink_formula,
720                states,
721                loop_to,
722                budget,
723                Box::new(make_solver()),
724            ) {
725                Some((next, used, finished)) => {
726                    spent += used;
727                    fully = finished;
728                    match next {
729                        Next::Instance(i) => best.instance = Some(i),
730                        Next::Trace(t) => {
731                            best.labels = self.model.labels_with(&t, &self.extra_step_labels);
732                            best.trace = Some(t);
733                        }
734                        Next::Done | Next::Unknown => {}
735                    }
736                }
737                // `best` is an instance of these bounds, so no instance at
738                // all means the budget ran out before the first one: the
739                // tuples were not shrunk (AGENTS.md law 14).
740                None => fully = false,
741            }
742        }
743        best.stats.conflicts += spent;
744        let sizes = Sizes(
745            cmd.top_sizes()
746                .into_iter()
747                .map(|(_, name, k, _)| (name, k))
748                .collect(),
749        );
750        (best, sizes, fully)
751    }
752
753    /// Runs the check and returns if it holds; otherwise panics with the
754    /// story as the message (LOGIC.md 14.4, R26).
755    #[track_caller]
756    pub fn assert_holds(&self) {
757        let report = self.report();
758        if !matches!(report.verdict, Some(Verdict::Holds | Verdict::Proved)) {
759            panic!("{}", report.story);
760        }
761    }
762}
763
764/// B10: maps atoms belonging uniquely to a singleton sub-signature (such as an
765/// `enum` constant `Learner = {Role0}` or a `one sig Admin extends User {}`)
766/// to that signature's name so stories show `Learner` instead of `Role0`.
767fn singleton_aliases(instance: &Instance) -> BTreeMap<String, String> {
768    let mut counts: BTreeMap<String, Vec<String>> = BTreeMap::new();
769    for (r, t) in instance.entries() {
770        if r.arity() != 1
771            || r.name().starts_with('$')
772            || is_ordering_relation(r.name())
773            || (r.name().contains("_chk_")
774                && (r.name().contains("_val") || r.name().contains("_ord")))
775        {
776            continue;
777        }
778        if t.len() != 1 {
779            continue;
780        }
781        let Some(tup) = t.iter().next() else { continue };
782        let Some(&atom) = tup.names().first() else {
783            continue;
784        };
785        // Skip a top-level set whose single atom is already named `{Set}0`.
786        if let Some(rest) = atom.strip_prefix(r.name())
787            && !rest.is_empty()
788            && rest.bytes().all(|b| b.is_ascii_digit())
789        {
790            continue;
791        }
792        // Skip integer atoms (e.g. `0`, `1`).
793        if atom.parse::<i64>().is_ok() {
794            continue;
795        }
796        counts
797            .entry(atom.to_string())
798            .or_default()
799            .push(r.name().to_string());
800    }
801    let mut aliases = BTreeMap::new();
802    for (atom, names) in counts {
803        if names.len() == 1 {
804            aliases.insert(atom, names.into_iter().next().expect("len is 1"));
805        }
806    }
807    aliases
808}
809
810fn display_atom<'a>(atom: &'a str, aliases: &'a BTreeMap<String, String>) -> &'a str {
811    aliases.get(atom).map(String::as_str).unwrap_or(atom)
812}
813
814fn tuples_text(t: &TupleSet, aliases: &BTreeMap<String, String>) -> String {
815    let parts: Vec<String> = t
816        .iter()
817        .map(|x| {
818            x.names()
819                .iter()
820                .map(|a| display_atom(a, aliases))
821                .collect::<Vec<_>>()
822                .join(" -> ")
823        })
824        .collect();
825    format!("{{{}}}", parts.join(", "))
826}
827
828fn is_ordering_relation(name: &str) -> bool {
829    name == "first" || name == "next" || name.ends_with("/first") || name.ends_with("/next")
830}
831
832fn instance_lines(
833    out: &mut String,
834    instance: &Instance,
835    indent: &str,
836    brief: bool,
837    aliases: &BTreeMap<String, String>,
838) {
839    let mut empty_names: Vec<&str> = Vec::new();
840    let mut order_lines: Vec<(&str, &TupleSet)> = Vec::new();
841    for (r, t) in instance.entries() {
842        if let Some(name) = r.name().strip_prefix('$') {
843            let atoms: 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            let _ = writeln!(out, "{indent}witness {name} = {}", atoms.join(", "));
854        } else if is_ordering_relation(r.name()) {
855            if !brief && !t.is_empty() {
856                order_lines.push((r.name(), t));
857            }
858        } else if t.is_empty() {
859            if !brief {
860                empty_names.push(r.name());
861            }
862        } else {
863            // Omit redundant `Learner = {Learner}` lines once `Role0` is aliased to `Learner`.
864            if r.arity() == 1
865                && t.len() == 1
866                && let Some(tup) = t.iter().next()
867                && let Some(&atom) = tup.names().first()
868                && aliases.get(atom).map(String::as_str) == Some(r.name())
869            {
870                continue;
871            }
872            let _ = writeln!(out, "{indent}{} = {}", r.name(), tuples_text(t, aliases));
873        }
874    }
875    if !order_lines.is_empty() {
876        let parts: Vec<String> = order_lines
877            .into_iter()
878            .map(|(n, t)| format!("{n} = {}", tuples_text(t, aliases)))
879            .collect();
880        let _ = writeln!(out, "{indent}order: {}", parts.join("; "));
881    }
882    if !empty_names.is_empty() {
883        let _ = writeln!(out, "{indent}empty: {}", empty_names.join(", "));
884    }
885}
886
887fn sizes_text(sizes: &Sizes) -> String {
888    sizes
889        .0
890        .iter()
891        .map(|(k, v)| format!("{k}: {v}"))
892        .collect::<Vec<_>>()
893        .join(", ")
894}
895
896/// LOGIC.md 14.2: the text of a result, made from its data.
897pub fn story(r: &Report) -> String {
898    format_story(r, false)
899}
900
901/// A brief version of [`story`] that omits empty relations and library
902/// ordering relations (`first`, `next`), showing only signatures and fields
903/// that hold atoms or tuples.
904pub fn story_brief(r: &Report) -> String {
905    format_story(r, true)
906}
907
908fn format_story(r: &Report, brief: bool) -> String {
909    let mut out = String::new();
910    let title = if r.name.is_empty() {
911        r.command.to_string()
912    } else {
913        format!("{} {}", r.command, r.name)
914    };
915    if !r.errors.is_empty() {
916        let _ = writeln!(out, "{title}: ERRORS");
917        for e in &r.errors {
918            let place = e
919                .place
920                .as_ref()
921                .map(|p| format!("{p}: "))
922                .unwrap_or_default();
923            let _ = writeln!(out, "  {place}error[{}]: {}", e.code, e.message);
924            let _ = writeln!(out, "    fix: {}", e.fix);
925        }
926        return out;
927    }
928    let searched = format!("searched every case up to {}", sizes_text(&r.scope));
929    let expect_tag = match (r.expect, r.expect_met) {
930        (Some(e), Some(true)) => format!(" [expect {e}: met]"),
931        (Some(e), Some(false)) => format!(" [expect {e}: NOT MET]"),
932        (Some(e), None) => format!(" [expect {e}: unknown]"),
933        _ => String::new(),
934    };
935    match r.verdict {
936        Some(Verdict::Holds) => {
937            let _ = writeln!(out, "{title}: holds{expect_tag}");
938            let _ = writeln!(out, "  {searched}; a larger case might still break it.");
939            if let Some(n) = &r.note {
940                let _ = writeln!(out, "  note: {n}");
941            }
942            if let Some(core) = &r.core {
943                let used = if core.used.is_empty() {
944                    "(none: assertion holds from bounds alone)".to_string()
945                } else {
946                    core.used.join(", ")
947                };
948                let _ = writeln!(out, "  used rules: {used}");
949                if !core.unused.is_empty() {
950                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
951                }
952            }
953        }
954        Some(Verdict::Proved) => {
955            let _ = writeln!(out, "{title}: PROVED{expect_tag}");
956            let scope_only: Vec<(String, usize)> = r
957                .scope
958                .0
959                .iter()
960                .filter(|(k, _)| k != "steps")
961                .cloned()
962                .collect();
963            let scope_text = sizes_text(&Sizes(scope_only));
964            let reason = r
965                .note
966                .as_deref()
967                .unwrap_or("proved for any number of steps by induction");
968            let _ = writeln!(out, "  {reason}, for all cases up to {scope_text}.");
969            if let Some(core) = &r.core {
970                let used = if core.used.is_empty() {
971                    "(none: assertion holds from bounds alone)".to_string()
972                } else {
973                    core.used.join(", ")
974                };
975                let _ = writeln!(out, "  used rules: {used}");
976                if !core.unused.is_empty() {
977                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
978                }
979            }
980        }
981        Some(Verdict::Vacuous) => {
982            let _ = writeln!(out, "{title}: VACUOUS{expect_tag}");
983            let _ = writeln!(
984                out,
985                "  the rules allow no case at all up to {}, so nothing can break the promise.",
986                sizes_text(&r.scope)
987            );
988            if let Some(n) = &r.note {
989                let _ = writeln!(out, "  note: {n}");
990            }
991            if let Some(core) = &r.core
992                && !core.used.is_empty()
993            {
994                let _ = writeln!(out, "  conflicting rules: {}", core.used.join(", "));
995            }
996        }
997        Some(Verdict::None) => {
998            let _ = writeln!(out, "{title}: no instance{expect_tag}");
999            let _ = writeln!(out, "  {searched}.");
1000            if let Some(core) = &r.core {
1001                if let Some(n) = &r.note {
1002                    let _ = writeln!(out, "  note: {n}");
1003                }
1004                let used = if core.used.is_empty() {
1005                    "(none: the run's own constraint allows no case)".to_string()
1006                } else {
1007                    core.used.join(", ")
1008                };
1009                let _ = writeln!(out, "  used rules: {used}");
1010                if !core.unused.is_empty() {
1011                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
1012                }
1013            }
1014        }
1015        Some(Verdict::Unknown) | None => {
1016            let _ = writeln!(out, "{title}: UNKNOWN{expect_tag}");
1017            if let Some(n) = &r.note {
1018                let _ = writeln!(out, "  {n}");
1019            }
1020        }
1021        Some(Verdict::Found) | Some(Verdict::Counterexample) => {
1022            let word = if r.verdict == Some(Verdict::Found) {
1023                "found"
1024            } else {
1025                "COUNTEREXAMPLE"
1026            };
1027            let (prep, size) = match &r.shrunk_to {
1028                Some(s) => ("with", s),
1029                None => ("in scope", &r.scope),
1030            };
1031            match &r.trace {
1032                None => {
1033                    let _ = writeln!(
1034                        out,
1035                        "{title}: {word} {prep} {}{expect_tag}",
1036                        sizes_text(size)
1037                    );
1038                    if let Some(i) = &r.instance {
1039                        let aliases = singleton_aliases(i);
1040                        instance_lines(&mut out, i, "  ", brief, &aliases);
1041                    }
1042                }
1043                Some(t) => {
1044                    let aliases = singleton_aliases(&t.fixed);
1045                    let _ = writeln!(
1046                        out,
1047                        "{title}: {word} in {} states, {prep} {}{expect_tag}",
1048                        t.states.len(),
1049                        sizes_text(size)
1050                    );
1051                    let _ = writeln!(out, "  start");
1052                    instance_lines(&mut out, &t.fixed, "    ", brief, &aliases);
1053                    if let Some(s0) = t.states.first() {
1054                        for (r, ts) in s0.entries().filter(|(_, ts)| !ts.is_empty()) {
1055                            let _ =
1056                                writeln!(out, "    {} = {}", r.name(), tuples_text(ts, &aliases));
1057                        }
1058                    }
1059                    for s in &t.steps {
1060                        // A model without actions has no names for its steps;
1061                        // "nothing" is said only when nothing changes.
1062                        let action = match &s.action {
1063                            Some(a) if s.args.is_empty() => format!("  {a}"),
1064                            Some(a) => {
1065                                let args: Vec<&str> =
1066                                    s.args.iter().map(|x| display_atom(x, &aliases)).collect();
1067                                format!("  {a}({})", args.join(", "))
1068                            }
1069                            None if s.changes.is_empty() => "  nothing changes".to_string(),
1070                            None => String::new(),
1071                        };
1072                        let changes: Vec<String> = s
1073                            .changes
1074                            .iter()
1075                            .map(|c| {
1076                                let mut parts = Vec::new();
1077                                if !c.gained.is_empty() {
1078                                    parts.push(format!(
1079                                        "{} gains {}",
1080                                        c.relation,
1081                                        tuples_text(&c.gained, &aliases)
1082                                    ));
1083                                }
1084                                if !c.lost.is_empty() {
1085                                    parts.push(format!(
1086                                        "{} loses {}",
1087                                        c.relation,
1088                                        tuples_text(&c.lost, &aliases)
1089                                    ));
1090                                }
1091                                parts.join(", ")
1092                            })
1093                            .collect();
1094                        let loops = if s.to <= s.step {
1095                            format!(", back to state {}", s.to)
1096                        } else {
1097                            String::new()
1098                        };
1099                        let _ = writeln!(
1100                            out,
1101                            "  step {}{action}{}{loops}",
1102                            s.step + 1,
1103                            if changes.is_empty() {
1104                                String::new()
1105                            } else {
1106                                format!("  {}", changes.join("; "))
1107                            }
1108                        );
1109                    }
1110                    if let Some(k) = r.broken_at {
1111                        let who = if r.broken_witness.is_empty() {
1112                            String::new()
1113                        } else {
1114                            let pairs: Vec<String> = r
1115                                .broken_witness
1116                                .iter()
1117                                .map(|(v, a)| format!("{v} = {}", display_atom(a, &aliases)))
1118                                .collect();
1119                            format!(" (for {})", pairs.join(", "))
1120                        };
1121                        let _ =
1122                            writeln!(out, "  broken at state {k}, as step {} begins{who}", k + 1);
1123                    }
1124                }
1125            }
1126            if r.verdict == Some(Verdict::Counterexample) {
1127                let _ = writeln!(out, "  {searched}.");
1128                if !r.fully_shrunk {
1129                    let _ = writeln!(out, "  (not fully shrunk: shrinking ran out of its budget)");
1130                }
1131            }
1132        }
1133    }
1134    for w in &r.warnings {
1135        let place = w
1136            .place
1137            .as_ref()
1138            .map(|p| format!("{p}: "))
1139            .unwrap_or_default();
1140        let _ = writeln!(out, "  {place}warning[{}]: {}", w.code, w.message);
1141        let _ = writeln!(out, "    fix: {}", w.fix);
1142    }
1143    out
1144}
1145
1146fn expr_mentions_univ_or_iden(e: &elinvar_logic::Expr) -> bool {
1147    use elinvar_logic::ExprKind as K;
1148    match e.kind() {
1149        K::Univ | K::Iden => true,
1150        K::Relation(_) | K::Variable(_) | K::None => false,
1151        K::Unary(_, a) | K::Prime(a) => expr_mentions_univ_or_iden(a),
1152        K::Binary(_, a, b) => expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b),
1153        K::Comprehension(ds, body) => {
1154            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1155                || formula_mentions_univ_or_iden(body)
1156        }
1157        K::IfThenElse(c, a, b) => {
1158            formula_mentions_univ_or_iden(c)
1159                || expr_mentions_univ_or_iden(a)
1160                || expr_mentions_univ_or_iden(b)
1161        }
1162        K::IntToSet(i) => int_mentions_univ_or_iden(i),
1163    }
1164}
1165
1166fn int_mentions_univ_or_iden(i: &elinvar_logic::IntExpr) -> bool {
1167    use elinvar_logic::IntExprKind as K;
1168    match i.kind() {
1169        K::Constant(_) => false,
1170        K::Count(e) | K::Sum(e) => expr_mentions_univ_or_iden(e),
1171        K::Binary(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
1172        K::Negate(a) => int_mentions_univ_or_iden(a),
1173        K::IfThenElse(c, a, b) => {
1174            formula_mentions_univ_or_iden(c)
1175                || int_mentions_univ_or_iden(a)
1176                || int_mentions_univ_or_iden(b)
1177        }
1178        K::SumOver(ds, body) => {
1179            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1180                || int_mentions_univ_or_iden(body)
1181        }
1182    }
1183}
1184
1185fn formula_mentions_univ_or_iden(f: &elinvar_logic::Formula) -> bool {
1186    use elinvar_logic::FormulaKind as K;
1187    match f.kind() {
1188        K::Constant(_) => false,
1189        K::Subset(a, b) | K::Equal(a, b) => {
1190            expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b)
1191        }
1192        K::Multiplicity(_, a) => expr_mentions_univ_or_iden(a),
1193        K::Not(g) | K::Temporal(_, g) => formula_mentions_univ_or_iden(g),
1194        K::And(fs) | K::Or(fs) => fs.iter().any(formula_mentions_univ_or_iden),
1195        K::Implies(a, b) | K::Iff(a, b) | K::TemporalBinary(_, a, b) => {
1196            formula_mentions_univ_or_iden(a) || formula_mentions_univ_or_iden(b)
1197        }
1198        K::Quantified(_, ds, body) => {
1199            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
1200                || formula_mentions_univ_or_iden(body)
1201        }
1202        K::IntCompare(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
1203    }
1204}
1205
1206/// Counts how many distinct atoms from top-level set `set`'s upper bound
1207/// actually appear in any relation tuple of `best` (W25).
1208fn used_atoms_for_top_set(
1209    cmd: &Command<'_>,
1210    best: &Outcome,
1211    set: &elinvar_logic::Expr,
1212    fallback: usize,
1213) -> usize {
1214    let elinvar_logic::ExprKind::Relation(set_rel) = set.kind() else {
1215        return fallback;
1216    };
1217    let Ok(bounds) = cmd.bounds() else {
1218        return fallback;
1219    };
1220    let Some(up) = bounds.upper(set_rel) else {
1221        return fallback;
1222    };
1223    let bu = bounds.universe();
1224    let pool_names: std::collections::BTreeSet<&str> = up
1225        .indices()
1226        .filter_map(|idx| bu.atom(idx as usize))
1227        .collect();
1228    if pool_names.is_empty() {
1229        return 0;
1230    }
1231    let mut used_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1232    let mut scan_inst = |inst: &elinvar_logic::Instance| {
1233        let u = inst.universe();
1234        let n = u.size() as u64;
1235        if n == 0 {
1236            return;
1237        }
1238        for (rel, ts) in inst.entries() {
1239            let arity = rel.arity();
1240            for mut idx in ts.indices() {
1241                for _ in 0..arity {
1242                    let a = (idx % n) as usize;
1243                    if let Some(name) = u.atom(a)
1244                        && let Some(&pname) = pool_names.get(name)
1245                    {
1246                        used_names.insert(pname);
1247                    }
1248                    idx /= n;
1249                }
1250            }
1251        }
1252    };
1253    if let Some(inst) = &best.instance {
1254        scan_inst(inst);
1255    } else if let Some(tr) = &best.trace {
1256        scan_inst(tr.fixed());
1257        for st in tr.states() {
1258            scan_inst(st);
1259        }
1260    } else {
1261        return fallback;
1262    }
1263    used_names.len()
1264}