elinvar-engine 0.1.0

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
//! Results as data, stories, shrinking, and `assert_holds` (LOGIC.md
//! section 14, R24 to R26, R31).

use crate::model::Command;
use crate::sat::{Budget, Cdcl, Solver};
use crate::solve::{HoldsCore, Next, Outcome, Stats, StepLabel, Verdict, shrink_tuples};
use elinvar_logic::{
    Error, Formula, FormulaKind, Instance, Quantifier, TemporalOp, Trace, TupleSet, Variable,
    evaluate_trace_at, evaluate_trace_expr_at,
};
use serde::Serialize;
use serde::ser::{SerializeMap, Serializer};
use std::collections::BTreeMap;
use std::fmt::Write as _;

/// The version of the result's JSON schema (LOGIC.md 14.1).
pub const RESULT_VERSION: u32 = 1;

/// The JSON Schema of the result, version 1 (LOGIC.md 14.1).
/// `cargo x generate` writes it to `docs/schema/result-v1.json`.
pub const RESULT_SCHEMA: &str = r##"{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://github.com/rustborg/elinvar/docs/schema/result-v1.json",
  "title": "Elinvar result, version 1",
  "description": "The result of a run or check command (LOGIC.md section 14.1).",
  "type": "object",
  "required": ["elinvar", "command", "name", "verdict", "scope", "shrunk_to", "fully_shrunk",
               "instance", "trace", "broken_at", "note", "errors", "stats", "story"],
  "additionalProperties": false,
  "properties": {
    "elinvar": { "const": 1 },
    "command": { "enum": ["run", "check"] },
    "name": { "type": "string" },
    "verdict": {
      "description": "null when there are errors",
      "enum": ["found", "none", "counterexample", "holds", "proved", "vacuous", "unknown", null]
    },
    "scope": { "$ref": "#/$defs/sizes" },
    "shrunk_to": { "oneOf": [{ "$ref": "#/$defs/sizes" }, { "type": "null" }] },
    "fully_shrunk": { "type": "boolean" },
    "instance": { "oneOf": [{ "$ref": "#/$defs/instance" }, { "type": "null" }] },
    "trace": { "oneOf": [{ "$ref": "#/$defs/trace" }, { "type": "null" }] },
    "broken_at": { "type": ["integer", "null"], "minimum": 0 },
    "broken_witness": {
      "description": "for a broken always-all promise, the variable bindings at broken_at that falsify the body",
      "type": "array",
      "items": {
        "type": "array",
        "prefixItems": [{ "type": "string" }, { "type": "string" }],
        "minItems": 2,
        "maxItems": 2
      }
    },
    "expect": { "type": "integer", "minimum": 0 },
    "expect_met": { "type": ["boolean", "null"] },
    "note": { "type": ["string", "null"] },
    "errors": { "type": "array", "items": { "$ref": "#/$defs/error" } },
    "warnings": { "type": "array", "items": { "$ref": "#/$defs/error" } },
    "stats": {
      "type": "object",
      "required": ["primary_variables", "gates", "conflicts"],
      "additionalProperties": false,
      "properties": {
        "primary_variables": { "type": "integer", "minimum": 0 },
        "gates": { "type": "integer", "minimum": 0 },
        "conflicts": { "type": "integer", "minimum": 0 }
      }
    },
    "core": {
      "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",
      "type": "object",
      "required": ["used", "unused"],
      "additionalProperties": false,
      "properties": {
        "used": { "type": "array", "items": { "type": "string" } },
        "unused": { "type": "array", "items": { "type": "string" } }
      }
    },
    "story": { "type": "string" }
  },
  "$defs": {
    "sizes": {
      "description": "atoms per top-level set, in declaration order, and steps for a model with changing relations",
      "type": "object",
      "additionalProperties": { "type": "integer", "minimum": 0 }
    },
    "tuples": {
      "type": "array",
      "items": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
    },
    "instance": {
      "type": "object",
      "required": ["atoms", "relations"],
      "additionalProperties": false,
      "properties": {
        "atoms": { "type": "array", "items": { "type": "string" } },
        "bitwidth": {
          "description": "the bitwidth of the integers, present only with integer atoms (LOGIC.md 16.1)",
          "type": "integer", "minimum": 1, "maximum": 32
        },
        "ints": {
          "description": "each integer atom's integer, by atom name; present only with integer atoms",
          "type": "object",
          "additionalProperties": { "type": "integer" }
        },
        "relations": {
          "type": "array",
          "items": {
            "type": "object",
            "required": ["name", "arity", "tuples"],
            "additionalProperties": false,
            "properties": {
              "name": { "type": "string" },
              "arity": { "type": "integer", "minimum": 1 },
              "tuples": { "$ref": "#/$defs/tuples" }
            }
          }
        }
      }
    },
    "trace": {
      "type": "object",
      "required": ["fixed", "states", "loop_to", "steps"],
      "additionalProperties": false,
      "properties": {
        "fixed": { "$ref": "#/$defs/instance" },
        "states": { "type": "array", "items": { "$ref": "#/$defs/instance" }, "minItems": 1 },
        "loop_to": { "type": "integer", "minimum": 0 },
        "steps": {
          "type": "array",
          "items": {
            "type": "object",
            "required": ["step", "to", "action", "args", "changes"],
            "additionalProperties": false,
            "properties": {
              "step": { "type": "integer", "minimum": 0 },
              "to": { "type": "integer", "minimum": 0 },
              "action": { "type": ["string", "null"] },
              "args": { "type": "array", "items": { "type": "string" } },
              "changes": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": ["relation", "gained", "lost"],
                  "additionalProperties": false,
                  "properties": {
                    "relation": { "type": "string" },
                    "gained": { "$ref": "#/$defs/tuples" },
                    "lost": { "$ref": "#/$defs/tuples" }
                  }
                }
              }
            }
          }
        }
      }
    },
    "error": {
      "type": "object",
      "required": ["code", "message", "fix", "place"],
      "additionalProperties": false,
      "properties": {
        "code": { "type": "string", "pattern": "^[a-z]+\\.[a-z_]+$" },
        "message": { "type": "string" },
        "fix": { "type": "string" },
        "place": {
          "oneOf": [
            {
              "type": "object",
              "required": ["file", "line", "column"],
              "additionalProperties": false,
              "properties": {
                "file": { "type": "string" },
                "line": { "type": "integer", "minimum": 1 },
                "column": { "type": "integer", "minimum": 1 }
              }
            },
            { "type": "null" }
          ]
        }
      }
    }
  }
}
"##;

/// The default budget of shrinking, in conflicts over all its solves
/// (LOGIC.md 14.3).
pub const SHRINK_CONFLICTS: u64 = 1_000_000;

/// Sizes by name, in declaration order, written as a JSON object.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sizes(pub Vec<(String, usize)>);

impl Serialize for Sizes {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut map = s.serialize_map(Some(self.0.len()))?;
        for (k, v) in &self.0 {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}

/// What a changing relation gains and loses in one step.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct Change {
    /// The relation.
    pub relation: String,
    /// The tuples it gains.
    pub gained: TupleSet,
    /// The tuples it loses.
    pub lost: TupleSet,
}

/// One step of a trace: out of state `step`, to the next state or, for the
/// last, back to the loop target.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct StepReport {
    /// The state the step leaves.
    pub step: usize,
    /// The state it reaches.
    pub to: usize,
    /// The action, or `None` when nothing changed.
    pub action: Option<String>,
    /// The action's arguments.
    pub args: Vec<String>,
    /// What each changing relation gains and loses.
    pub changes: Vec<Change>,
}

/// A trace as the result gives it.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct TraceReport {
    /// The fixed relations.
    pub fixed: Instance,
    /// The states.
    pub states: Vec<Instance>,
    /// The state the last one loops back to.
    pub loop_to: usize,
    /// One per state.
    pub steps: Vec<StepReport>,
}

/// The result of a command (LOGIC.md 14.1).
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use]
pub struct Report {
    /// The schema version.
    pub elinvar: u32,
    /// `run` or `check`.
    pub command: &'static str,
    /// The command's name.
    pub name: String,
    /// The verdict; `None` when there are errors.
    pub verdict: Option<Verdict>,
    /// The scope searched.
    pub scope: Sizes,
    /// For a counterexample, the scope it was shrunk to.
    pub shrunk_to: Option<Sizes>,
    /// Whether shrinking finished within its budget.
    pub fully_shrunk: bool,
    /// The instance, without changing relations.
    pub instance: Option<Instance>,
    /// The trace, with changing relations.
    pub trace: Option<TraceReport>,
    /// For a counterexample to `always P`, the first state where `P` fails.
    pub broken_at: Option<usize>,
    /// For a counterexample to `always all x: S | ...`, the first variable
    /// bindings `(name, atom)` at `broken_at` that falsify the body (W9).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub broken_witness: Vec<(String, String)>,
    /// The command's `expect 0` or `expect 1` annotation when present (W16).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect: Option<u64>,
    /// Whether the verdict met `expect` (`None` when `unknown` or no `expect`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect_met: Option<bool>,
    /// For `unknown`, which budget ran out and what is known.
    pub note: Option<String>,
    /// Every error.
    pub errors: Vec<Error>,
    /// Non-fatal warnings about the model or command (such as wrapped integer
    /// literals or step predicates leaving changing relations unconstrained).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<Error>,
    /// Statistics.
    pub stats: Stats,
    /// When requested on a `holds` or `vacuous` check, or a `run` with no
    /// instance, which named rules formed the minimal unsatisfiable core
    /// (REQUIREMENTS.md section 8).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub core: Option<HoldsCore>,
    /// The text, made from the fields above.
    pub story: String,
}

impl std::fmt::Display for Report {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.story)
    }
}

fn difference(a: &TupleSet, b: &TupleSet) -> TupleSet {
    let mut out = TupleSet::empty(a.universe(), a.arity())
        .expect("a tuple set's own arity and universe are valid");
    for i in a.indices().filter(|&i| !b.contains_index(i)) {
        out.insert_index(i)
            .expect("an index of a tuple set is an index of its arity");
    }
    out
}

pub(crate) fn trace_report(trace: &Trace, labels: &[StepLabel]) -> TraceReport {
    let states = trace.states();
    let steps = (0..states.len())
        .map(|k| {
            let to = if k + 1 < states.len() {
                k + 1
            } else {
                trace.loop_to()
            };
            let changes = states[k]
                .entries()
                .filter_map(|(r, now)| {
                    let next = states[to].get(r)?;
                    let gained = difference(next, now);
                    let lost = difference(now, next);
                    (!gained.is_empty() || !lost.is_empty()).then(|| Change {
                        relation: r.name().to_string(),
                        gained,
                        lost,
                    })
                })
                .collect();
            let label = labels.get(k);
            StepReport {
                step: k,
                to,
                action: label.and_then(|l| l.action.clone()),
                args: label.map(|l| l.args.clone()).unwrap_or_default(),
                changes,
            }
        })
        .collect();
    TraceReport {
        fixed: trace.fixed().clone(),
        states: states.to_vec(),
        loop_to: trace.loop_to(),
        steps,
    }
}

/// LOGIC.md 14.1: the first state where `P` fails, for `always P`, a
/// single-formula block holding it, or `A implies always P`, plus any
/// universal quantifier witness bindings at that state (W9).
fn broken_at_with_witness(
    assertion: &Formula,
    trace: &Trace,
) -> (Option<usize>, Vec<(String, String)>) {
    let mut a = assertion;
    loop {
        match a.kind() {
            FormulaKind::And(fs) if fs.len() == 1 => a = &fs[0],
            FormulaKind::Implies(_, rhs) => a = rhs,
            _ => break,
        }
    }
    let FormulaKind::Temporal(TemporalOp::Always, p) = a.kind() else {
        return (None, Vec::new());
    };
    let Some(k) =
        (0..trace.states().len()).find(|&k| evaluate_trace_at(trace, p, k, &[]) == Ok(false))
    else {
        return (None, Vec::new());
    };
    let witness = find_all_witness(p, trace, k);
    (Some(k), witness)
}

/// W9: finds the first tuple of variable assignments falsifying `all x1: e1, ... | body`
/// at state `k` of `trace`.
fn find_all_witness(formula: &Formula, trace: &Trace, k: usize) -> Vec<(String, String)> {
    let mut cur = formula;
    let mut vars: Vec<Variable> = Vec::new();
    let mut ranges = Vec::new();
    loop {
        match cur.kind() {
            FormulaKind::And(fs) if fs.len() == 1 => cur = &fs[0],
            FormulaKind::Quantified(Quantifier::All, decls, body) => {
                for d in decls {
                    if d.expr.arity() != Some(1) {
                        return Vec::new();
                    }
                    vars.push(d.var.clone());
                    ranges.push(d.expr.clone());
                }
                cur = body;
            }
            _ => break,
        }
    }
    if vars.is_empty() {
        return Vec::new();
    }
    let mut domains: Vec<Vec<usize>> = Vec::with_capacity(ranges.len());
    for r in &ranges {
        let Ok(ts) = evaluate_trace_expr_at(trace, r, k) else {
            return Vec::new();
        };
        let atoms: Vec<usize> = ts.indices().map(|i| i as usize).collect();
        if atoms.is_empty() {
            return Vec::new();
        }
        domains.push(atoms);
    }
    let total: usize = domains
        .iter()
        .try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
        .unwrap_or(0);
    if total == 0 || total > 4096 {
        return Vec::new();
    }
    for code in 0..total {
        let mut atoms = vec![0usize; domains.len()];
        let mut c = code;
        for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
            *slot = dom[c % dom.len()];
            c /= dom.len();
        }
        let bindings: Vec<(Variable, usize)> =
            vars.iter().cloned().zip(atoms.iter().copied()).collect();
        if evaluate_trace_at(trace, cur, k, &bindings) == Ok(false) {
            return vars
                .iter()
                .zip(atoms)
                .map(|(v, idx)| {
                    let atom = trace
                        .universe()
                        .atom(idx)
                        .expect("atom index from trace universe")
                        .to_string();
                    (v.name().to_string(), atom)
                })
                .collect();
        }
    }
    Vec::new()
}

fn check_expect_met(expect: Option<u64>, verdict: Option<Verdict>) -> Option<bool> {
    let e = expect?;
    let v = verdict?;
    match v {
        Verdict::Unknown => None,
        Verdict::Found | Verdict::Counterexample => Some(e >= 1),
        Verdict::Holds | Verdict::Proved | Verdict::Vacuous | Verdict::None => Some(e == 0),
    }
}

impl Report {
    /// The result of a command that could not run: its errors, and no
    /// verdict (LOGIC.md 14.1).
    pub fn of_errors(command: &'static str, name: &str, errors: Vec<Error>) -> Report {
        let mut report = Report::empty(command, name.to_string(), Sizes::default());
        report.errors = errors;
        report.story = story(&report);
        report
    }

    /// A result with nothing found yet and no story.
    fn empty(command: &'static str, name: String, scope: Sizes) -> Report {
        Report {
            elinvar: RESULT_VERSION,
            command,
            name,
            verdict: None,
            scope,
            shrunk_to: None,
            fully_shrunk: true,
            instance: None,
            trace: None,
            broken_at: None,
            broken_witness: Vec::new(),
            expect: None,
            expect_met: None,
            note: None,
            errors: Vec::new(),
            warnings: Vec::new(),
            stats: Stats::default(),
            core: None,
            story: String::new(),
        }
    }
}

impl Command<'_> {
    fn scope_sizes(&self) -> Sizes {
        let mut sizes: Vec<(String, usize)> = self
            .top_sizes()
            .into_iter()
            .map(|(_, name, k, _)| (name, k))
            .collect();
        if self.model.has_changing() {
            sizes.push(("steps".to_string(), self.options.steps));
        }
        Sizes(sizes)
    }

    /// Runs the command with the default solver and returns its result,
    /// errors included as data.
    pub fn report(&self) -> Report {
        self.report_with(Cdcl::new)
    }

    /// Runs the command and shrinks any counterexample using a solver built
    /// by `make_solver` (R9, DESIGN.md section 7.4). Every instance or trace
    /// returned is still refereed by `elinvar-logic`.
    pub fn report_with<S, F>(&self, mut make_solver: F) -> Report
    where
        S: Solver + 'static,
        F: FnMut() -> S,
    {
        let mut report = Report::empty(
            if self.is_check { "check" } else { "run" },
            self.name.clone(),
            self.scope_sizes(),
        );
        report.warnings = self.warnings.clone();
        report.expect = self.expect;
        match self.solve_with(&mut make_solver) {
            Err(errors) => report.errors = errors,
            Ok(out) => {
                let out = if self.shrink
                    && matches!(out.verdict, Verdict::Counterexample | Verdict::Found)
                {
                    let (out, shrunk_to, fully) = self.shrink_with(out, &mut make_solver);
                    report.shrunk_to = Some(shrunk_to);
                    report.fully_shrunk = fully;
                    out
                } else {
                    out
                };
                report.verdict = Some(out.verdict);
                report.expect_met = check_expect_met(report.expect, report.verdict);
                report.note = out.note.clone();
                report.stats = out.stats;
                report.instance = out.instance.clone();
                if self.is_check
                    && !self.skip_holds_warnings
                    && matches!(out.verdict, Verdict::Holds | Verdict::Proved)
                {
                    report
                        .warnings
                        .extend(self.holds_warnings(&mut make_solver));
                }
                if let Some(trace) = &out.trace {
                    if self.is_check {
                        let (at, witness) = broken_at_with_witness(&self.formula, trace);
                        report.broken_at = at;
                        report.broken_witness = witness;
                    }
                    report.trace = Some(trace_report(trace, &out.labels));
                }
            }
        }
        report.story = story(&report);
        report
    }

    /// Runs the command and, when a `check` concludes `holds`, `proved`, or
    /// `vacuous`, or a `run` finds no instance, also extracts the minimal
    /// unsatisfiable core of named rules that established it (REQUIREMENTS.md
    /// section 8, B13, B14). The command's conflict budget covers both the
    /// solve and the core extraction.
    pub fn report_explained(&self) -> Report {
        let mut report = self.report();
        let total_budget = self
            .options
            .budget
            .conflicts
            .unwrap_or(crate::solve::DEFAULT_CONFLICTS);
        let mut remaining = total_budget.saturating_sub(report.stats.conflicts);
        let res = match report.verdict {
            Some(Verdict::Vacuous) => self.explain_vacuous_budgeted(&mut remaining).ok(),
            Some(Verdict::Holds | Verdict::Proved) => {
                self.explain_assertion_budgeted(&mut remaining).ok()
            }
            Some(Verdict::None) => match self.explain_no_instance_budgeted(&mut remaining) {
                Ok((res, alone)) => {
                    if alone && !matches!(res, crate::solve::CoreResult::NotUnsat) {
                        report.note = Some(
                            "the rules allow no case at all, whatever the run asks".to_string(),
                        );
                    }
                    Some(res)
                }
                Err(_) => None,
            },
            _ => None,
        };
        match res {
            Some(crate::solve::CoreResult::Complete(core)) => {
                report.core = Some(core);
                report.story = story(&report);
            }
            Some(crate::solve::CoreResult::Incomplete { core, note }) => {
                report.core = core;
                report.note = Some(match report.note.take() {
                    Some(prev) => format!("{prev}; {note}"),
                    None => note,
                });
                report.story = story(&report);
            }
            Some(crate::solve::CoreResult::NotUnsat) | None => {}
        }
        report
    }

    /// LOGIC.md 14.3: fewer atoms, then fewer tuples.
    fn shrink_with<S, F>(&self, found: Outcome, make_solver: &mut F) -> (Outcome, Sizes, bool)
    where
        S: Solver + 'static,
        F: FnMut() -> S,
    {
        let mut best = found;
        let mut cmd = self.clone();
        let mut spent = 0u64;
        let mut fully = true;
        // LOGIC.md 14.3: shrinking is bounded by conflicts only, never by
        // the command's time budget, so the same model and scope give the
        // same instance however fast the machine (AGENTS.md law 17).
        let left = |spent: u64| Budget::conflicts(SHRINK_CONFLICTS.saturating_sub(spent).max(1));
        let target_verdict = if self.is_check {
            Verdict::Counterexample
        } else {
            Verdict::Found
        };
        let sets = cmd.top_sizes();
        let can_fast_skip_unused = !formula_mentions_univ_or_iden(&cmd.facts_for(None))
            && !formula_mentions_univ_or_iden(&cmd.formula);
        'sets: for (set, _, start, exact) in sets {
            if exact {
                continue;
            }
            let mut k = start;
            if can_fast_skip_unused
                && start > 0
                && used_atoms_for_top_set(&cmd, &best, &set, start) == 0
            {
                // W25: `best` already uses 0 atoms of `set` and no formula
                // mentions `univ`/`iden`, so shrinking `set` to 0 needs no SAT call.
                cmd = cmd.with_scope(&set, 0);
                continue 'sets;
            }
            while k > 0 {
                let budget = left(spent);
                let mut trial = cmd.with_scope(&set, k - 1);
                trial.options = trial.options.budget(budget);
                match trial.solve_with(&mut *make_solver) {
                    Ok(out) => {
                        spent += out.stats.conflicts;
                        if out.verdict == target_verdict {
                            best = out;
                            cmd = trial;
                            k -= 1;
                        } else if out.verdict == Verdict::Unknown {
                            fully = false;
                            break 'sets;
                        } else {
                            break;
                        }
                    }
                    Err(_) => break,
                }
                if spent >= SHRINK_CONFLICTS {
                    fully = false;
                    break 'sets;
                }
            }
        }
        if fully && let Ok(bounds) = cmd.bounds() {
            let full_facts = cmd.facts_for(Some(&bounds));
            let tuple_formula = if self.is_check {
                full_facts.and(&self.formula.not())
            } else {
                full_facts.and(&self.formula)
            };
            let (states, loop_to) = best
                .trace
                .as_ref()
                .map_or((1, 0), |t| (t.states().len(), t.loop_to()));
            // W27: on a 1-state stuttering trace, transition arms with a pure
            // stutter step hold automatically, and static `SqlDateFn` total
            // functions have fixed cardinality that cannot be shrunk. Drop the
            // transition disjunction and lock `SqlDateFn` to `best`'s values
            // during tuple shrinking, while still refereeing against the FULL
            // `tuple_formula` (AGENTS.md law 13).
            let (shrink_bounds, shrink_formula) = crate::coi::prepare_tuple_shrink(
                &bounds,
                &full_facts,
                &self.formula,
                self.is_check,
                states,
                loop_to,
                best.instance.as_ref(),
                best.trace.as_ref(),
            )
            .unwrap_or_else(|| (bounds.clone(), tuple_formula.clone()));
            let budget = SHRINK_CONFLICTS.saturating_sub(spent);
            match shrink_tuples(
                &bounds,
                &tuple_formula,
                &shrink_bounds,
                &shrink_formula,
                states,
                loop_to,
                budget,
                Box::new(make_solver()),
            ) {
                Some((next, used, finished)) => {
                    spent += used;
                    fully = finished;
                    match next {
                        Next::Instance(i) => best.instance = Some(i),
                        Next::Trace(t) => {
                            best.labels = self.model.labels_with(&t, &self.extra_step_labels);
                            best.trace = Some(t);
                        }
                        Next::Done | Next::Unknown => {}
                    }
                }
                // `best` is an instance of these bounds, so no instance at
                // all means the budget ran out before the first one: the
                // tuples were not shrunk (AGENTS.md law 14).
                None => fully = false,
            }
        }
        best.stats.conflicts += spent;
        let sizes = Sizes(
            cmd.top_sizes()
                .into_iter()
                .map(|(_, name, k, _)| (name, k))
                .collect(),
        );
        (best, sizes, fully)
    }

    /// Runs the check and returns if it holds; otherwise panics with the
    /// story as the message (LOGIC.md 14.4, R26).
    #[track_caller]
    pub fn assert_holds(&self) {
        let report = self.report();
        if !matches!(report.verdict, Some(Verdict::Holds | Verdict::Proved)) {
            panic!("{}", report.story);
        }
    }
}

/// B10: maps atoms belonging uniquely to a singleton sub-signature (such as an
/// `enum` constant `Learner = {Role0}` or a `one sig Admin extends User {}`)
/// to that signature's name so stories show `Learner` instead of `Role0`.
fn singleton_aliases(instance: &Instance) -> BTreeMap<String, String> {
    let mut counts: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (r, t) in instance.entries() {
        if r.arity() != 1
            || r.name().starts_with('$')
            || is_ordering_relation(r.name())
            || (r.name().contains("_chk_")
                && (r.name().contains("_val") || r.name().contains("_ord")))
        {
            continue;
        }
        if t.len() != 1 {
            continue;
        }
        let Some(tup) = t.iter().next() else { continue };
        let Some(&atom) = tup.names().first() else {
            continue;
        };
        // Skip a top-level set whose single atom is already named `{Set}0`.
        if let Some(rest) = atom.strip_prefix(r.name())
            && !rest.is_empty()
            && rest.bytes().all(|b| b.is_ascii_digit())
        {
            continue;
        }
        // Skip integer atoms (e.g. `0`, `1`).
        if atom.parse::<i64>().is_ok() {
            continue;
        }
        counts
            .entry(atom.to_string())
            .or_default()
            .push(r.name().to_string());
    }
    let mut aliases = BTreeMap::new();
    for (atom, names) in counts {
        if names.len() == 1 {
            aliases.insert(atom, names.into_iter().next().expect("len is 1"));
        }
    }
    aliases
}

fn display_atom<'a>(atom: &'a str, aliases: &'a BTreeMap<String, String>) -> &'a str {
    aliases.get(atom).map(String::as_str).unwrap_or(atom)
}

fn tuples_text(t: &TupleSet, aliases: &BTreeMap<String, String>) -> String {
    let parts: Vec<String> = t
        .iter()
        .map(|x| {
            x.names()
                .iter()
                .map(|a| display_atom(a, aliases))
                .collect::<Vec<_>>()
                .join(" -> ")
        })
        .collect();
    format!("{{{}}}", parts.join(", "))
}

fn is_ordering_relation(name: &str) -> bool {
    name == "first" || name == "next" || name.ends_with("/first") || name.ends_with("/next")
}

fn instance_lines(
    out: &mut String,
    instance: &Instance,
    indent: &str,
    brief: bool,
    aliases: &BTreeMap<String, String>,
) {
    let mut empty_names: Vec<&str> = Vec::new();
    let mut order_lines: Vec<(&str, &TupleSet)> = Vec::new();
    for (r, t) in instance.entries() {
        if let Some(name) = r.name().strip_prefix('$') {
            let atoms: Vec<String> = t
                .iter()
                .map(|x| {
                    x.names()
                        .iter()
                        .map(|a| display_atom(a, aliases))
                        .collect::<Vec<_>>()
                        .join(" -> ")
                })
                .collect();
            let _ = writeln!(out, "{indent}witness {name} = {}", atoms.join(", "));
        } else if is_ordering_relation(r.name()) {
            if !brief && !t.is_empty() {
                order_lines.push((r.name(), t));
            }
        } else if t.is_empty() {
            if !brief {
                empty_names.push(r.name());
            }
        } else {
            // Omit redundant `Learner = {Learner}` lines once `Role0` is aliased to `Learner`.
            if r.arity() == 1
                && t.len() == 1
                && let Some(tup) = t.iter().next()
                && let Some(&atom) = tup.names().first()
                && aliases.get(atom).map(String::as_str) == Some(r.name())
            {
                continue;
            }
            let _ = writeln!(out, "{indent}{} = {}", r.name(), tuples_text(t, aliases));
        }
    }
    if !order_lines.is_empty() {
        let parts: Vec<String> = order_lines
            .into_iter()
            .map(|(n, t)| format!("{n} = {}", tuples_text(t, aliases)))
            .collect();
        let _ = writeln!(out, "{indent}order: {}", parts.join("; "));
    }
    if !empty_names.is_empty() {
        let _ = writeln!(out, "{indent}empty: {}", empty_names.join(", "));
    }
}

fn sizes_text(sizes: &Sizes) -> String {
    sizes
        .0
        .iter()
        .map(|(k, v)| format!("{k}: {v}"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// LOGIC.md 14.2: the text of a result, made from its data.
pub fn story(r: &Report) -> String {
    format_story(r, false)
}

/// A brief version of [`story`] that omits empty relations and library
/// ordering relations (`first`, `next`), showing only signatures and fields
/// that hold atoms or tuples.
pub fn story_brief(r: &Report) -> String {
    format_story(r, true)
}

fn format_story(r: &Report, brief: bool) -> String {
    let mut out = String::new();
    let title = if r.name.is_empty() {
        r.command.to_string()
    } else {
        format!("{} {}", r.command, r.name)
    };
    if !r.errors.is_empty() {
        let _ = writeln!(out, "{title}: ERRORS");
        for e in &r.errors {
            let place = e
                .place
                .as_ref()
                .map(|p| format!("{p}: "))
                .unwrap_or_default();
            let _ = writeln!(out, "  {place}error[{}]: {}", e.code, e.message);
            let _ = writeln!(out, "    fix: {}", e.fix);
        }
        return out;
    }
    let searched = format!("searched every case up to {}", sizes_text(&r.scope));
    let expect_tag = match (r.expect, r.expect_met) {
        (Some(e), Some(true)) => format!(" [expect {e}: met]"),
        (Some(e), Some(false)) => format!(" [expect {e}: NOT MET]"),
        (Some(e), None) => format!(" [expect {e}: unknown]"),
        _ => String::new(),
    };
    match r.verdict {
        Some(Verdict::Holds) => {
            let _ = writeln!(out, "{title}: holds{expect_tag}");
            let _ = writeln!(out, "  {searched}; a larger case might still break it.");
            if let Some(n) = &r.note {
                let _ = writeln!(out, "  note: {n}");
            }
            if let Some(core) = &r.core {
                let used = if core.used.is_empty() {
                    "(none: assertion holds from bounds alone)".to_string()
                } else {
                    core.used.join(", ")
                };
                let _ = writeln!(out, "  used rules: {used}");
                if !core.unused.is_empty() {
                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
                }
            }
        }
        Some(Verdict::Proved) => {
            let _ = writeln!(out, "{title}: PROVED{expect_tag}");
            let scope_only: Vec<(String, usize)> = r
                .scope
                .0
                .iter()
                .filter(|(k, _)| k != "steps")
                .cloned()
                .collect();
            let scope_text = sizes_text(&Sizes(scope_only));
            let reason = r
                .note
                .as_deref()
                .unwrap_or("proved for any number of steps by induction");
            let _ = writeln!(out, "  {reason}, for all cases up to {scope_text}.");
            if let Some(core) = &r.core {
                let used = if core.used.is_empty() {
                    "(none: assertion holds from bounds alone)".to_string()
                } else {
                    core.used.join(", ")
                };
                let _ = writeln!(out, "  used rules: {used}");
                if !core.unused.is_empty() {
                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
                }
            }
        }
        Some(Verdict::Vacuous) => {
            let _ = writeln!(out, "{title}: VACUOUS{expect_tag}");
            let _ = writeln!(
                out,
                "  the rules allow no case at all up to {}, so nothing can break the promise.",
                sizes_text(&r.scope)
            );
            if let Some(n) = &r.note {
                let _ = writeln!(out, "  note: {n}");
            }
            if let Some(core) = &r.core
                && !core.used.is_empty()
            {
                let _ = writeln!(out, "  conflicting rules: {}", core.used.join(", "));
            }
        }
        Some(Verdict::None) => {
            let _ = writeln!(out, "{title}: no instance{expect_tag}");
            let _ = writeln!(out, "  {searched}.");
            if let Some(core) = &r.core {
                if let Some(n) = &r.note {
                    let _ = writeln!(out, "  note: {n}");
                }
                let used = if core.used.is_empty() {
                    "(none: the run's own constraint allows no case)".to_string()
                } else {
                    core.used.join(", ")
                };
                let _ = writeln!(out, "  used rules: {used}");
                if !core.unused.is_empty() {
                    let _ = writeln!(out, "  unused rules: {}", core.unused.join(", "));
                }
            }
        }
        Some(Verdict::Unknown) | None => {
            let _ = writeln!(out, "{title}: UNKNOWN{expect_tag}");
            if let Some(n) = &r.note {
                let _ = writeln!(out, "  {n}");
            }
        }
        Some(Verdict::Found) | Some(Verdict::Counterexample) => {
            let word = if r.verdict == Some(Verdict::Found) {
                "found"
            } else {
                "COUNTEREXAMPLE"
            };
            let (prep, size) = match &r.shrunk_to {
                Some(s) => ("with", s),
                None => ("in scope", &r.scope),
            };
            match &r.trace {
                None => {
                    let _ = writeln!(
                        out,
                        "{title}: {word} {prep} {}{expect_tag}",
                        sizes_text(size)
                    );
                    if let Some(i) = &r.instance {
                        let aliases = singleton_aliases(i);
                        instance_lines(&mut out, i, "  ", brief, &aliases);
                    }
                }
                Some(t) => {
                    let aliases = singleton_aliases(&t.fixed);
                    let _ = writeln!(
                        out,
                        "{title}: {word} in {} states, {prep} {}{expect_tag}",
                        t.states.len(),
                        sizes_text(size)
                    );
                    let _ = writeln!(out, "  start");
                    instance_lines(&mut out, &t.fixed, "    ", brief, &aliases);
                    if let Some(s0) = t.states.first() {
                        for (r, ts) in s0.entries().filter(|(_, ts)| !ts.is_empty()) {
                            let _ =
                                writeln!(out, "    {} = {}", r.name(), tuples_text(ts, &aliases));
                        }
                    }
                    for s in &t.steps {
                        // A model without actions has no names for its steps;
                        // "nothing" is said only when nothing changes.
                        let action = match &s.action {
                            Some(a) if s.args.is_empty() => format!("  {a}"),
                            Some(a) => {
                                let args: Vec<&str> =
                                    s.args.iter().map(|x| display_atom(x, &aliases)).collect();
                                format!("  {a}({})", args.join(", "))
                            }
                            None if s.changes.is_empty() => "  nothing changes".to_string(),
                            None => String::new(),
                        };
                        let changes: Vec<String> = s
                            .changes
                            .iter()
                            .map(|c| {
                                let mut parts = Vec::new();
                                if !c.gained.is_empty() {
                                    parts.push(format!(
                                        "{} gains {}",
                                        c.relation,
                                        tuples_text(&c.gained, &aliases)
                                    ));
                                }
                                if !c.lost.is_empty() {
                                    parts.push(format!(
                                        "{} loses {}",
                                        c.relation,
                                        tuples_text(&c.lost, &aliases)
                                    ));
                                }
                                parts.join(", ")
                            })
                            .collect();
                        let loops = if s.to <= s.step {
                            format!(", back to state {}", s.to)
                        } else {
                            String::new()
                        };
                        let _ = writeln!(
                            out,
                            "  step {}{action}{}{loops}",
                            s.step + 1,
                            if changes.is_empty() {
                                String::new()
                            } else {
                                format!("  {}", changes.join("; "))
                            }
                        );
                    }
                    if let Some(k) = r.broken_at {
                        let who = if r.broken_witness.is_empty() {
                            String::new()
                        } else {
                            let pairs: Vec<String> = r
                                .broken_witness
                                .iter()
                                .map(|(v, a)| format!("{v} = {}", display_atom(a, &aliases)))
                                .collect();
                            format!(" (for {})", pairs.join(", "))
                        };
                        let _ =
                            writeln!(out, "  broken at state {k}, as step {} begins{who}", k + 1);
                    }
                }
            }
            if r.verdict == Some(Verdict::Counterexample) {
                let _ = writeln!(out, "  {searched}.");
                if !r.fully_shrunk {
                    let _ = writeln!(out, "  (not fully shrunk: shrinking ran out of its budget)");
                }
            }
        }
    }
    for w in &r.warnings {
        let place = w
            .place
            .as_ref()
            .map(|p| format!("{p}: "))
            .unwrap_or_default();
        let _ = writeln!(out, "  {place}warning[{}]: {}", w.code, w.message);
        let _ = writeln!(out, "    fix: {}", w.fix);
    }
    out
}

fn expr_mentions_univ_or_iden(e: &elinvar_logic::Expr) -> bool {
    use elinvar_logic::ExprKind as K;
    match e.kind() {
        K::Univ | K::Iden => true,
        K::Relation(_) | K::Variable(_) | K::None => false,
        K::Unary(_, a) | K::Prime(a) => expr_mentions_univ_or_iden(a),
        K::Binary(_, a, b) => expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b),
        K::Comprehension(ds, body) => {
            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
                || formula_mentions_univ_or_iden(body)
        }
        K::IfThenElse(c, a, b) => {
            formula_mentions_univ_or_iden(c)
                || expr_mentions_univ_or_iden(a)
                || expr_mentions_univ_or_iden(b)
        }
        K::IntToSet(i) => int_mentions_univ_or_iden(i),
    }
}

fn int_mentions_univ_or_iden(i: &elinvar_logic::IntExpr) -> bool {
    use elinvar_logic::IntExprKind as K;
    match i.kind() {
        K::Constant(_) => false,
        K::Count(e) | K::Sum(e) => expr_mentions_univ_or_iden(e),
        K::Binary(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
        K::Negate(a) => int_mentions_univ_or_iden(a),
        K::IfThenElse(c, a, b) => {
            formula_mentions_univ_or_iden(c)
                || int_mentions_univ_or_iden(a)
                || int_mentions_univ_or_iden(b)
        }
        K::SumOver(ds, body) => {
            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
                || int_mentions_univ_or_iden(body)
        }
    }
}

fn formula_mentions_univ_or_iden(f: &elinvar_logic::Formula) -> bool {
    use elinvar_logic::FormulaKind as K;
    match f.kind() {
        K::Constant(_) => false,
        K::Subset(a, b) | K::Equal(a, b) => {
            expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b)
        }
        K::Multiplicity(_, a) => expr_mentions_univ_or_iden(a),
        K::Not(g) | K::Temporal(_, g) => formula_mentions_univ_or_iden(g),
        K::And(fs) | K::Or(fs) => fs.iter().any(formula_mentions_univ_or_iden),
        K::Implies(a, b) | K::Iff(a, b) | K::TemporalBinary(_, a, b) => {
            formula_mentions_univ_or_iden(a) || formula_mentions_univ_or_iden(b)
        }
        K::Quantified(_, ds, body) => {
            ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
                || formula_mentions_univ_or_iden(body)
        }
        K::IntCompare(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
    }
}

/// Counts how many distinct atoms from top-level set `set`'s upper bound
/// actually appear in any relation tuple of `best` (W25).
fn used_atoms_for_top_set(
    cmd: &Command<'_>,
    best: &Outcome,
    set: &elinvar_logic::Expr,
    fallback: usize,
) -> usize {
    let elinvar_logic::ExprKind::Relation(set_rel) = set.kind() else {
        return fallback;
    };
    let Ok(bounds) = cmd.bounds() else {
        return fallback;
    };
    let Some(up) = bounds.upper(set_rel) else {
        return fallback;
    };
    let bu = bounds.universe();
    let pool_names: std::collections::BTreeSet<&str> = up
        .indices()
        .filter_map(|idx| bu.atom(idx as usize))
        .collect();
    if pool_names.is_empty() {
        return 0;
    }
    let mut used_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
    let mut scan_inst = |inst: &elinvar_logic::Instance| {
        let u = inst.universe();
        let n = u.size() as u64;
        if n == 0 {
            return;
        }
        for (rel, ts) in inst.entries() {
            let arity = rel.arity();
            for mut idx in ts.indices() {
                for _ in 0..arity {
                    let a = (idx % n) as usize;
                    if let Some(name) = u.atom(a)
                        && let Some(&pname) = pool_names.get(name)
                    {
                        used_names.insert(pname);
                    }
                    idx /= n;
                }
            }
        }
    };
    if let Some(inst) = &best.instance {
        scan_inst(inst);
    } else if let Some(tr) = &best.trace {
        scan_inst(tr.fixed());
        for st in tr.states() {
            scan_inst(st);
        }
    } else {
        return fallback;
    }
    used_names.len()
}