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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//! Comparing two versions of a design (REQUIREMENTS.md section 8): given
//! `old` and `new` models sharing the same signatures and fields, find a
//! minimal shrunk instance or trace allowed by one and forbidden by the
//! other, or confirm they agree up to the chosen scope.

use crate::model::{Model, model_error};
use crate::report::{RESULT_VERSION, Report};
use crate::solve::{Options, Verdict};
use elinvar_logic::{
    Decl, Error, Expr, ExprKind, Formula, FormulaKind, IntExpr, IntExprKind, Quantifier, Relation,
    TemporalOp, Variable,
};
use serde::Serialize;
use std::collections::BTreeMap;
use std::fmt;

/// How `new` differs from `old` up to the searched scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DiffVerdict {
    /// Every case up to the scope allowed by one is allowed by the other.
    Equivalent,
    /// `new` forbids at least one case `old` allows, and allows nothing extra.
    Tightened,
    /// `new` allows at least one case `old` forbids, and forbids nothing `old` allows.
    Loosened,
    /// Each model allows at least one case the other forbids.
    Diverged,
    /// One of the checks ran out of budget.
    Unknown,
    /// `diff --of`: the two models together allow no case, so there is
    /// nothing to compare the functions on. The rules are wrong, not the
    /// functions equal (DESIGN.md section 7.6).
    Vacuous,
}

impl fmt::Display for DiffVerdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            DiffVerdict::Equivalent => "equivalent",
            DiffVerdict::Tightened => "tightened",
            DiffVerdict::Loosened => "loosened",
            DiffVerdict::Diverged => "diverged",
            DiffVerdict::Unknown => "unknown",
            DiffVerdict::Vacuous => "vacuous",
        };
        f.write_str(s)
    }
}

/// The result of comparing two models ([`diff_models`]).
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use]
pub struct DiffReport {
    /// The schema version.
    pub elinvar: u32,
    /// How `new` differs from `old`, or `None` when there are errors.
    pub verdict: Option<DiffVerdict>,
    /// A minimal case allowed by `old` and forbidden by `new`, if any.
    pub only_in_old: Option<Report>,
    /// A minimal case allowed by `new` and forbidden by `old`, if any.
    pub only_in_new: Option<Report>,
    /// Errors preventing the comparison (for example, mismatched signatures).
    pub errors: Vec<Error>,
    /// Plain-text summary made from the fields above.
    pub story: String,
}

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

fn diff_error(message: String) -> Error {
    model_error("model.diff_mismatch", message)
}

fn relation_map(model: &Model) -> BTreeMap<String, Relation> {
    model
        .relations()
        .into_iter()
        .map(|r| (r.name().to_string(), r))
        .collect()
}

fn check_compatible(old: &Model, new: &Model) -> Vec<Error> {
    let old_map = relation_map(old);
    let new_map = relation_map(new);
    let mut errors = Vec::new();
    for (name, r_old) in &old_map {
        match new_map.get(name) {
            None => errors.push(diff_error(format!(
                "`{name}` is declared in the old model but missing from the new model"
            ))),
            Some(r_new) => {
                if r_old.arity() != r_new.arity() {
                    errors.push(diff_error(format!(
                        "`{name}` has arity {} in the old model and {} in the new model",
                        r_old.arity(),
                        r_new.arity()
                    )));
                }
                if r_old.is_changing() != r_new.is_changing() {
                    errors.push(diff_error(format!(
                        "`{name}` changes in one model and is fixed in the other"
                    )));
                }
            }
        }
    }
    for name in new_map.keys() {
        if !old_map.contains_key(name) {
            errors.push(diff_error(format!(
                "`{name}` is declared in the new model but missing from the old model"
            )));
        }
    }
    errors
}

fn rebind_expr(e: &Expr, target: &BTreeMap<String, Relation>) -> Expr {
    match e.kind() {
        ExprKind::Relation(r) => match target.get(r.name()) {
            Some(mapped) => Expr::relation(mapped),
            None => e.clone(),
        },
        ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => e.clone(),
        ExprKind::Binary(op, a, b) => {
            rebind_expr(a, target).apply_binary(*op, &rebind_expr(b, target))
        }
        ExprKind::Unary(op, a) => rebind_expr(a, target).apply_unary(*op),
        ExprKind::Prime(a) => rebind_expr(a, target).prime(),
        ExprKind::Comprehension(decls, body) => {
            let ds = decls
                .iter()
                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
                .collect();
            Expr::comprehension(ds, &rebind_formula(body, target))
        }
        ExprKind::IfThenElse(c, a, b) => Expr::if_then_else(
            &rebind_formula(c, target),
            &rebind_expr(a, target),
            &rebind_expr(b, target),
        ),
        ExprKind::IntToSet(v) => rebind_int(v, target).to_set(),
    }
}

fn rebind_int(v: &IntExpr, target: &BTreeMap<String, Relation>) -> IntExpr {
    match v.kind() {
        IntExprKind::Constant(_) => v.clone(),
        IntExprKind::Count(e) => rebind_expr(e, target).count(),
        IntExprKind::Sum(e) => rebind_expr(e, target).sum(),
        IntExprKind::Binary(op, a, b) => rebind_int(a, target).apply(*op, &rebind_int(b, target)),
        IntExprKind::Negate(a) => rebind_int(a, target).negate(),
        IntExprKind::IfThenElse(c, a, b) => IntExpr::if_then_else(
            &rebind_formula(c, target),
            &rebind_int(a, target),
            &rebind_int(b, target),
        ),
        IntExprKind::SumOver(decls, body) => {
            let ds = decls
                .iter()
                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
                .collect();
            IntExpr::sum_over(ds, &rebind_int(body, target))
        }
    }
}

fn rebind_formula(f: &Formula, target: &BTreeMap<String, Relation>) -> Formula {
    match f.kind() {
        FormulaKind::Constant(_) => f.clone(),
        FormulaKind::Subset(a, b) => rebind_expr(a, target).is_in(&rebind_expr(b, target)),
        FormulaKind::Equal(a, b) => rebind_expr(a, target).equals(&rebind_expr(b, target)),
        FormulaKind::Multiplicity(m, a) => rebind_expr(a, target).apply_multiplicity(*m),
        FormulaKind::Not(g) => rebind_formula(g, target).not(),
        FormulaKind::And(fs) => Formula::and_all(
            fs.iter()
                .map(|g| rebind_formula(g, target))
                .collect::<Vec<_>>(),
        ),
        FormulaKind::Or(fs) => Formula::or_all(
            fs.iter()
                .map(|g| rebind_formula(g, target))
                .collect::<Vec<_>>(),
        ),
        FormulaKind::Implies(a, b) => rebind_formula(a, target).implies(&rebind_formula(b, target)),
        FormulaKind::Iff(a, b) => rebind_formula(a, target).iff(&rebind_formula(b, target)),
        FormulaKind::Quantified(q, decls, body) => {
            let ds = decls
                .iter()
                .map(|d| Decl::with(&d.var, d.mult, &rebind_expr(&d.expr, target)))
                .collect();
            Formula::quantified(*q, ds, &rebind_formula(body, target))
        }
        FormulaKind::Temporal(op, g) => rebind_formula(g, target).temporal(*op),
        FormulaKind::TemporalBinary(op, a, b) => {
            rebind_formula(a, target).temporal_binary(*op, &rebind_formula(b, target))
        }
        FormulaKind::IntCompare(op, a, b) => {
            rebind_int(a, target).compare_with(*op, &rebind_int(b, target))
        }
    }
}

fn diff_story(r: &DiffReport, scope: Option<usize>, steps: Option<usize>) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    if !r.errors.is_empty() {
        for e in &r.errors {
            let _ = writeln!(out, "error[{}]: {}", e.code, e.message);
            if !e.fix.is_empty() {
                let _ = writeln!(out, "  fix: {}", e.fix);
            }
        }
        return out;
    }
    let verdict = r.verdict.unwrap_or(DiffVerdict::Unknown);
    let _ = writeln!(out, "diff: {verdict}");
    if let Some(old_rep) = &r.only_in_old
        && old_rep.verdict == Some(Verdict::Counterexample)
    {
        let _ = writeln!(out, "\nallowed by old, forbidden by new:");
        out.push_str(&old_rep.story);
    }
    if let Some(new_rep) = &r.only_in_new
        && new_rep.verdict == Some(Verdict::Counterexample)
    {
        let _ = writeln!(out, "\nallowed by new, forbidden by old:");
        out.push_str(&new_rep.story);
    }
    if verdict == DiffVerdict::Equivalent {
        match (scope, steps) {
            (Some(sc), Some(st)) => {
                let _ = writeln!(
                    out,
                    "  both designs allow the same cases up to scope {sc}, {st} steps."
                );
            }
            (Some(sc), None) => {
                let _ = writeln!(out, "  both designs allow the same cases up to scope {sc}.");
            }
            _ => {
                let _ = writeln!(
                    out,
                    "  both designs allow the same cases up to the searched scope."
                );
            }
        }
    }
    out
}

/// Compares two models sharing the same signatures and fields, up to `scope`
/// and `options`, returning a [`DiffReport`] with shrunk witnesses for any
/// cases allowed by one model and forbidden by the other.
pub fn diff_models(old: &Model, new: &Model, scope: usize, options: &Options) -> DiffReport {
    diff_models_with_bitwidth(old, new, scope, elinvar_logic::DEFAULT_BITWIDTH, options)
}

/// Like [`diff_models`], using `bitwidth` for bounded `Int` atoms on both
/// sides (used, for example, when comparing two imported SQL schemas whose
/// integer literals need more than 4 bits).
pub fn diff_models_with_bitwidth(
    old: &Model,
    new: &Model,
    scope: usize,
    bitwidth: u32,
    options: &Options,
) -> DiffReport {
    let errors = check_compatible(old, new);
    if !errors.is_empty() {
        let mut r = DiffReport {
            elinvar: RESULT_VERSION,
            verdict: None,
            only_in_old: None,
            only_in_new: None,
            errors,
            story: String::new(),
        };
        r.story = diff_story(&r, None, None);
        return r;
    }
    let old_map = relation_map(old);
    let new_map = relation_map(new);
    let has_changing = old.relations().iter().any(Relation::is_changing)
        || new.relations().iter().any(Relation::is_changing);
    let searched_steps = has_changing.then_some(options.steps);
    let new_in_old = diff_facts_assertion(old, new, &old_map, options.slicing);
    let old_in_new = diff_facts_assertion(new, old, &new_map, options.slicing);

    // W25: both sides are independent read-only checks; run in parallel and
    // combine in deterministic `(OnlyInOld, OnlyInNew)` order (AGENTS.md law 16).
    let (rep_old, rep_new) = std::thread::scope(|s| {
        let h_old = s.spawn(|| {
            check_diff_side(
                old,
                new,
                &old_map,
                &new_in_old,
                "OnlyInOld",
                scope,
                bitwidth,
                options,
            )
        });
        let rep_new = check_diff_side(
            new,
            old,
            &new_map,
            &old_in_new,
            "OnlyInNew",
            scope,
            bitwidth,
            options,
        );
        let rep_old = match h_old.join() {
            Ok(r) => r,
            Err(_) => check_diff_side(
                old,
                new,
                &old_map,
                &new_in_old,
                "OnlyInOld",
                scope,
                bitwidth,
                options,
            ),
        };
        (rep_old, rep_new)
    });

    let mut errors = Vec::new();
    errors.extend(rep_old.errors.iter().cloned());
    errors.extend(rep_new.errors.iter().cloned());
    if !errors.is_empty() {
        let mut r = DiffReport {
            elinvar: RESULT_VERSION,
            verdict: None,
            only_in_old: Some(rep_old),
            only_in_new: Some(rep_new),
            errors,
            story: String::new(),
        };
        r.story = diff_story(&r, Some(scope), searched_steps);
        return r;
    }

    let verdict = match (rep_old.verdict, rep_new.verdict) {
        (Some(Verdict::Unknown), _) | (_, Some(Verdict::Unknown)) => DiffVerdict::Unknown,
        (Some(Verdict::Counterexample), Some(Verdict::Counterexample)) => DiffVerdict::Diverged,
        (Some(Verdict::Counterexample), _) => DiffVerdict::Tightened,
        (_, Some(Verdict::Counterexample)) => DiffVerdict::Loosened,
        _ => DiffVerdict::Equivalent,
    };

    let mut r = DiffReport {
        elinvar: RESULT_VERSION,
        verdict: Some(verdict),
        only_in_old: Some(rep_old),
        only_in_new: Some(rep_new),
        errors: Vec::new(),
        story: String::new(),
    };
    r.story = diff_story(&r, Some(scope), searched_steps);
    r
}

/// Compares the tuples returned by a function expression `old_expr` in `old`
/// against `new_expr` in `new` over cases allowed by both models (W10).
///
/// - `Tightened`: `new_expr` drops tuples `old_expr` returns (`only_in_old`).
/// - `Loosened`: `new_expr` gains tuples `old_expr` lacks (`only_in_new`).
/// - `Diverged`: `new_expr` both loses and gains tuples.
/// - `Equivalent`: both functions return the same tuples in every shared case.
pub fn diff_functions(
    old: &Model,
    old_expr: &Expr,
    new: &Model,
    new_expr: &Expr,
    scope: usize,
    bitwidth: u32,
    options: &Options,
) -> DiffReport {
    let errors = check_compatible(old, new);
    if !errors.is_empty() {
        let mut r = DiffReport {
            elinvar: RESULT_VERSION,
            verdict: None,
            only_in_old: None,
            only_in_new: None,
            errors,
            story: String::new(),
        };
        r.story = diff_story(&r, None, None);
        return r;
    }
    let old_map = relation_map(old);
    let new_facts_in_old = rebind_formula(&new.all_facts(), &old_map);
    let new_expr_in_old = rebind_expr(new_expr, &old_map);

    let mut both = old.clone();
    both.fact_named("new_model_facts", new_facts_in_old);

    let has_changing = old.relations().iter().any(Relation::is_changing);
    let lost_prop = if has_changing {
        old_expr.is_in(&new_expr_in_old).always()
    } else {
        old_expr.is_in(&new_expr_in_old)
    };
    let gained_prop = if has_changing {
        new_expr_in_old.is_in(old_expr).always()
    } else {
        new_expr_in_old.is_in(old_expr)
    };

    let (rep_old, rep_new) = std::thread::scope(|s| {
        let h_old = s.spawn(|| {
            both.check(&lost_prop)
                .named("LostTuples")
                .scope(scope)
                .bitwidth(bitwidth)
                .options(*options)
                .without_holds_warnings()
                .report()
        });
        let rep_new = both
            .check(&gained_prop)
            .named("GainedTuples")
            .scope(scope)
            .bitwidth(bitwidth)
            .options(*options)
            .without_holds_warnings()
            .report();
        let rep_old = match h_old.join() {
            Ok(r) => r,
            Err(_) => both
                .check(&lost_prop)
                .named("LostTuples")
                .scope(scope)
                .bitwidth(bitwidth)
                .options(*options)
                .without_holds_warnings()
                .report(),
        };
        (rep_old, rep_new)
    });

    let mut errors = Vec::new();
    errors.extend(rep_old.errors.iter().cloned());
    errors.extend(rep_new.errors.iter().cloned());
    if !errors.is_empty() {
        let mut r = DiffReport {
            elinvar: RESULT_VERSION,
            verdict: None,
            only_in_old: Some(rep_old),
            only_in_new: Some(rep_new),
            errors,
            story: String::new(),
        };
        r.story = diff_story(&r, Some(scope), has_changing.then_some(options.steps));
        return r;
    }

    let verdict = match (rep_old.verdict, rep_new.verdict) {
        (Some(Verdict::Unknown), _) | (_, Some(Verdict::Unknown)) => DiffVerdict::Unknown,
        (Some(Verdict::Counterexample), Some(Verdict::Counterexample)) => DiffVerdict::Diverged,
        (Some(Verdict::Counterexample), _) => DiffVerdict::Tightened,
        (_, Some(Verdict::Counterexample)) => DiffVerdict::Loosened,
        // Both checks share the facts of both models: when those allow no
        // case, "the same tuples" would claim more than is known (law 14).
        (Some(Verdict::Vacuous), _) | (_, Some(Verdict::Vacuous)) => DiffVerdict::Vacuous,
        _ => DiffVerdict::Equivalent,
    };

    let eval_diff = |rep: &Report, diff_e: &Expr| -> Option<String> {
        if let Some(inst) = &rep.instance {
            return elinvar_logic::evaluate_expr(inst, diff_e)
                .ok()
                .filter(|ts| !ts.is_empty())
                .map(|ts| format!("{ts}"));
        }
        if let Some(tr) = &rep.trace {
            let trace =
                elinvar_logic::Trace::new(tr.fixed.clone(), tr.states.clone(), tr.loop_to).ok()?;
            let k = rep.broken_at.unwrap_or(0);
            return elinvar_logic::evaluate_trace_expr_at(&trace, diff_e, k)
                .ok()
                .filter(|ts| !ts.is_empty())
                .map(|ts| format!("{ts}"));
        }
        None
    };

    let mut story = String::new();
    use std::fmt::Write as _;
    let _ = writeln!(story, "diff: {verdict}");
    if rep_old.verdict == Some(Verdict::Counterexample) {
        let lost = eval_diff(&rep_old, &old_expr.difference(&new_expr_in_old)).unwrap_or_default();
        let _ = writeln!(story, "\ntuples lost by new: {lost}");
        story.push_str(&rep_old.story);
    }
    if rep_new.verdict == Some(Verdict::Counterexample) {
        let gained = eval_diff(&rep_new, &new_expr_in_old.difference(old_expr)).unwrap_or_default();
        let _ = writeln!(story, "\ntuples gained by new: {gained}");
        story.push_str(&rep_new.story);
    }
    if verdict == DiffVerdict::Vacuous {
        let _ = writeln!(
            story,
            "  the two models together allow no case up to scope {scope}, so their functions \
             cannot be compared: the rules contradict each other."
        );
    }
    if verdict == DiffVerdict::Equivalent {
        if has_changing {
            let _ = writeln!(
                story,
                "  both functions return the same tuples up to scope {scope}, {} steps.",
                options.steps
            );
        } else {
            let _ = writeln!(
                story,
                "  both functions return the same tuples up to scope {scope}."
            );
        }
    }

    DiffReport {
        elinvar: RESULT_VERSION,
        verdict: Some(verdict),
        only_in_old: Some(rep_old),
        only_in_new: Some(rep_new),
        errors: Vec::new(),
        story,
    }
}

/// Runs one side of `diff` (`OnlyInOld` or `OnlyInNew`).
///
/// - When the reduced diff assertion is trivially `true`, checks 1-state
///   non-vacuity first so a pure tightening on a large temporal schema does
///   not unroll every untouched table just to confirm `Holds` (B23).
/// - When both models are any-state transition systems (no initial-state-only
///   facts on changing relations, e.g. SQL diff `--from-any`), applies the
///   exact One-step Transition Diff Reduction (W25): replaces `assumed`'s
///   transition disjunction with `always (AssumedOnly or Stutter)` so COI
///   slices away every untouched table and trigger, and referees any found
///   counterexample against the FULL unreduced models (AGENTS.md law 13).
#[allow(clippy::too_many_arguments)]
fn check_diff_side(
    assumed: &Model,
    target: &Model,
    assumed_map: &BTreeMap<String, Relation>,
    assertion: &Formula,
    name: &str,
    scope: usize,
    bitwidth: u32,
    options: &Options,
) -> Report {
    let reduced = if options.slicing {
        reduce_assumed_for_any_state_diff(assumed, target, assumed_map, options.steps)
    } else {
        None
    };

    let run_at_scope = |try_scope: usize| -> Report {
        if matches!(assertion.kind(), FormulaKind::Constant(true)) && options.steps > 1 {
            let mut fast = *options;
            fast.steps = 1;
            let mut cmd = assumed
                .check(assertion)
                .named(name)
                .scope(try_scope)
                .bitwidth(bitwidth)
                .options(fast)
                .without_holds_warnings();
            if let Some((ref red_facts, _)) = reduced {
                cmd = cmd.with_override_model_facts(red_facts.clone());
            }
            let rep = cmd.report();
            if rep.verdict == Some(Verdict::Holds) {
                return rep;
            }
        }

        if let Some((ref reduced_facts, eff_steps)) = reduced {
            let mut red_opts = *options;
            red_opts.steps = eff_steps;
            let rep = assumed
                .check(assertion)
                .named(name)
                .scope(try_scope)
                .bitwidth(bitwidth)
                .options(red_opts)
                .with_override_model_facts(reduced_facts.clone())
                .without_holds_warnings()
                .report();
            // Law 13: referee any counterexample against the FULL unreduced models.
            let verified = match rep.verdict {
                Some(Verdict::Counterexample) => {
                    let target_rebound = rebind_formula(&target.all_facts(), assumed_map);
                    let full_check = assumed.all_facts().and(&target_rebound.not());
                    if let Some(tr_rep) = &rep.trace {
                        elinvar_logic::Trace::new(
                            tr_rep.fixed.clone(),
                            tr_rep.states.clone(),
                            tr_rep.loop_to,
                        )
                        .ok()
                        .is_some_and(|tr| {
                            elinvar_logic::evaluate_trace(&tr, &full_check) == Ok(true)
                        })
                    } else if let Some(inst) = &rep.instance {
                        elinvar_logic::evaluate(inst, &full_check) == Ok(true)
                    } else {
                        false
                    }
                }
                Some(Verdict::Holds | Verdict::Vacuous | Verdict::Unknown) => true,
                _ => false,
            };
            if verified {
                return rep;
            }
        }

        assumed
            .check(assertion)
            .named(name)
            .scope(try_scope)
            .bitwidth(bitwidth)
            .options(*options)
            .without_holds_warnings()
            .report()
    };

    // W25: when searching for a counterexample at scope >= 2, probe smaller
    // scopes (1, then 2 if scope >= 3) first. A verified counterexample at a
    // smaller scope is already a valid minimal witness at `scope`, avoiding
    // large full-scope SAT solves when a 1- or 2-row witness exists.
    // `Holds` is only ever returned after searching the full `scope`.
    if !matches!(assertion.kind(), FormulaKind::Constant(true)) && scope >= 2 {
        let probes: &[usize] = if scope >= 3 { &[1, 2] } else { &[1] };
        for &probe_scope in probes {
            let rep = run_at_scope(probe_scope);
            if rep.verdict == Some(Verdict::Counterexample) {
                return rep;
            }
        }
    }

    run_at_scope(scope)
}

/// Exact One-step Transition Diff Reduction for any-state models (W25):
/// when neither `assumed` nor `target` has initial-state-only facts on
/// changing relations and every temporal fact is either a state invariant
/// (`always P` with non-temporal `P`) or a 1-step transition disjunction
/// containing a pure stutter arm, any trace satisfying `assumed ∧ ¬target`
/// either violates a state invariant at some state `s_i` (witnessed by
/// stuttering on `s_i`) or takes an arm in `AssumedOnly` at some step
/// `s_i -> s_{i+1}` (witnessed by `s_i -> s_{i+1} -> s_{i+1}`).
/// Therefore replacing `assumed`'s transition disjunction with
/// `always (AssumedOnly ∨ Stutter)` is equisatisfiable with `assumed ∧ ¬target`
/// and allows COI to slice away every unchanged table and trigger.
fn reduce_assumed_for_any_state_diff(
    assumed: &Model,
    target: &Model,
    assumed_map: &BTreeMap<String, Relation>,
    requested_steps: usize,
) -> Option<(Formula, usize)> {
    let all_rels = assumed.relations();
    if !all_rels.iter().any(Relation::is_changing) {
        return None;
    }
    let mut a_conjs = Vec::new();
    split_and_diff(&assumed.all_facts(), &mut a_conjs);
    let target_rebound = rebind_formula(&target.all_facts(), assumed_map);
    let mut t_conjs = Vec::new();
    split_and_diff(&target_rebound, &mut t_conjs);

    // Check that `target` has no initial-state-only facts on changing relations
    // and no multi-step temporal facts, and collect its single transition disjunction.
    let mut target_trans: Option<Vec<Formula>> = None;
    for tc in &t_conjs {
        if !tc.is_temporal() {
            if formula_mentions_changing_diff(tc) {
                return None;
            }
        } else if let FormulaKind::Temporal(TemporalOp::Always, inner) = tc.kind() {
            if !inner.is_temporal() {
                continue;
            }
            if !is_one_step_diff(inner) {
                return None;
            }
            let arms = extract_always_or_arms(tc)?;
            if target_trans.is_some() {
                return None;
            }
            target_trans = Some(arms);
        } else {
            return None;
        }
    }
    let target_arms = target_trans?;

    // Same check on `assumed`, locating its single transition disjunction.
    let mut assumed_trans_idx: Option<usize> = None;
    let mut assumed_arms: Option<Vec<Formula>> = None;
    for (idx, ac) in a_conjs.iter().enumerate() {
        if !ac.is_temporal() {
            if formula_mentions_changing_diff(ac) {
                return None;
            }
        } else if let FormulaKind::Temporal(TemporalOp::Always, inner) = ac.kind() {
            if !inner.is_temporal() {
                continue;
            }
            if !is_one_step_diff(inner) {
                return None;
            }
            let arms = extract_always_or_arms(ac)?;
            if assumed_trans_idx.is_some() {
                return None;
            }
            assumed_trans_idx = Some(idx);
            assumed_arms = Some(arms);
        } else {
            return None;
        }
    }
    let trans_idx = assumed_trans_idx?;
    let assumed_arms = assumed_arms?;

    let mut stutter_arm: Option<Formula> = None;
    let mut assumed_only = Vec::new();
    let mut dropped_count = 0usize;
    for a in &assumed_arms {
        let exact_in_target = target_arms.iter().any(|t| formula_alpha_eq(a, t, &[]));
        if exact_in_target {
            if is_pure_stutter_arm_diff(a, &all_rels) && stutter_arm.is_none() {
                stutter_arm = Some(a.clone());
            } else {
                dropped_count += 1;
            }
        } else if target_arms.iter().any(|t| arm_syntactically_implies(a, t)) {
            dropped_count += 1;
        } else {
            assumed_only.push(a.clone());
        }
    }
    // Require a shared pure stutter arm on both sides and at least one dropped arm.
    let stutter = stutter_arm?;
    if dropped_count == 0 {
        return None;
    }

    let eff_steps = if assumed_only.is_empty() {
        1
    } else {
        requested_steps.clamp(1, 2)
    };
    let mut kept_arms = assumed_only;
    kept_arms.push(stutter);
    a_conjs[trans_idx] = Formula::or_all(kept_arms).always();
    Some((Formula::and_all(a_conjs), eff_steps))
}

fn expr_mentions_changing_diff(e: &Expr) -> bool {
    match e.kind() {
        ExprKind::Relation(r) => r.is_changing(),
        ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
        ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr_mentions_changing_diff(a),
        ExprKind::Binary(_, a, b) => {
            expr_mentions_changing_diff(a) || expr_mentions_changing_diff(b)
        }
        ExprKind::Comprehension(ds, body) => {
            ds.iter().any(|d| expr_mentions_changing_diff(&d.expr))
                || formula_mentions_changing_diff(body)
        }
        ExprKind::IfThenElse(c, a, b) => {
            formula_mentions_changing_diff(c)
                || expr_mentions_changing_diff(a)
                || expr_mentions_changing_diff(b)
        }
        ExprKind::IntToSet(i) => int_mentions_changing_diff(i),
    }
}

fn int_mentions_changing_diff(i: &IntExpr) -> bool {
    match i.kind() {
        IntExprKind::Constant(_) => false,
        IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_mentions_changing_diff(e),
        IntExprKind::Binary(_, a, b) => {
            int_mentions_changing_diff(a) || int_mentions_changing_diff(b)
        }
        IntExprKind::Negate(a) => int_mentions_changing_diff(a),
        IntExprKind::IfThenElse(c, a, b) => {
            formula_mentions_changing_diff(c)
                || int_mentions_changing_diff(a)
                || int_mentions_changing_diff(b)
        }
        IntExprKind::SumOver(ds, body) => {
            ds.iter().any(|d| expr_mentions_changing_diff(&d.expr))
                || int_mentions_changing_diff(body)
        }
    }
}

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

/// Returns true when `f` contains no temporal operators (`always`, `eventually`,
/// `after`, `until`, etc.) and at most single-prime expressions `e'` (no `e''`).
fn is_one_step_diff(f: &Formula) -> bool {
    fn expr_ok(e: &Expr, in_prime: bool) -> bool {
        match e.kind() {
            ExprKind::Relation(_)
            | ExprKind::Variable(_)
            | ExprKind::None
            | ExprKind::Univ
            | ExprKind::Iden => true,
            ExprKind::Prime(a) => !in_prime && expr_ok(a, true),
            ExprKind::Unary(_, a) => expr_ok(a, in_prime),
            ExprKind::Binary(_, a, b) => expr_ok(a, in_prime) && expr_ok(b, in_prime),
            ExprKind::Comprehension(ds, body) => {
                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && form_ok(body, in_prime)
            }
            ExprKind::IfThenElse(c, a, b) => {
                form_ok(c, in_prime) && expr_ok(a, in_prime) && expr_ok(b, in_prime)
            }
            ExprKind::IntToSet(i) => int_ok(i, in_prime),
        }
    }
    fn int_ok(i: &IntExpr, in_prime: bool) -> bool {
        match i.kind() {
            IntExprKind::Constant(_) => true,
            IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_ok(e, in_prime),
            IntExprKind::Binary(_, a, b) => int_ok(a, in_prime) && int_ok(b, in_prime),
            IntExprKind::Negate(a) => int_ok(a, in_prime),
            IntExprKind::IfThenElse(c, a, b) => {
                form_ok(c, in_prime) && int_ok(a, in_prime) && int_ok(b, in_prime)
            }
            IntExprKind::SumOver(ds, body) => {
                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && int_ok(body, in_prime)
            }
        }
    }
    fn form_ok(f: &Formula, in_prime: bool) -> bool {
        match f.kind() {
            FormulaKind::Constant(_) => true,
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
                expr_ok(a, in_prime) && expr_ok(b, in_prime)
            }
            FormulaKind::Multiplicity(_, a) => expr_ok(a, in_prime),
            FormulaKind::Not(g) => form_ok(g, in_prime),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(|g| form_ok(g, in_prime)),
            FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
                form_ok(a, in_prime) && form_ok(b, in_prime)
            }
            FormulaKind::Quantified(_, ds, body) => {
                ds.iter().all(|d| expr_ok(&d.expr, in_prime)) && form_ok(body, in_prime)
            }
            FormulaKind::IntCompare(_, a, b) => int_ok(a, in_prime) && int_ok(b, in_prime),
            FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
        }
    }
    form_ok(f, false)
}

fn is_pure_stutter_arm_diff(arm: &Formula, all_rels: &[Relation]) -> bool {
    let mut conjs = Vec::new();
    split_and_diff(arm, &mut conjs);
    if conjs.is_empty() {
        return false;
    }
    let mut framed = std::collections::BTreeSet::new();
    for c in &conjs {
        let FormulaKind::Equal(a, b) = c.kind() else {
            return false;
        };
        let matched = match (a.kind(), b.kind()) {
            (ExprKind::Prime(p), ExprKind::Relation(r))
            | (ExprKind::Relation(r), ExprKind::Prime(p)) => {
                matches!(p.kind(), ExprKind::Relation(r2) if r2 == r)
            }
            _ => false,
        };
        if !matched {
            return false;
        }
        if let ExprKind::Relation(r) = b.kind() {
            framed.insert(r.name().to_string());
        } else if let ExprKind::Relation(r) = a.kind() {
            framed.insert(r.name().to_string());
        }
    }
    all_rels
        .iter()
        .filter(|r| r.is_changing())
        .all(|r| framed.contains(r.name()))
}

/// Builds a logically equivalent assertion for checking `assumed => target`
/// (with `target` rebound into `assumed`'s relations) that omits facts and
/// untouched transition arms shared identically by both models, so
/// `coi::try_check_coi` slices away untouched tables automatically (B23).
fn diff_facts_assertion(
    assumed: &Model,
    target: &Model,
    assumed_map: &BTreeMap<String, Relation>,
    reduce: bool,
) -> Formula {
    let mut assumed_conjuncts = Vec::new();
    split_and_diff(&assumed.all_facts(), &mut assumed_conjuncts);

    // A `one` set is exact through the bounds, which differ between the two
    // sides; say it as a fact so a side without it is compared against it.
    let mut target_facts = vec![target.all_facts()];
    target_facts.extend(target.one_set_facts());
    let target_rebound = rebind_formula(&Formula::and_all(target_facts), assumed_map);
    let mut target_conjuncts = Vec::new();
    split_and_diff(&target_rebound, &mut target_conjuncts);

    // Collect `always (arm_1 or ...)` transition conjuncts from `assumed`.
    let assumed_transitions: Vec<Vec<Formula>> = assumed_conjuncts
        .iter()
        .filter_map(extract_always_or_arms)
        .collect();

    let mut diff_conjuncts = Vec::new();
    for tc in target_conjuncts {
        // Any conjunct already present identically in `assumed` is guaranteed true.
        if assumed_conjuncts
            .iter()
            .any(|ac| formula_alpha_eq(ac, &tc, &[]))
        {
            continue;
        }
        if reduce
            && let Some(target_arms) = extract_always_or_arms(&tc)
            && let Some(reduced) = reduce_transition_diff(&assumed_transitions, &target_arms)
        {
            if !matches!(reduced.kind(), FormulaKind::Constant(true)) {
                diff_conjuncts.push(reduced);
            }
            continue;
        }
        diff_conjuncts.push(tc);
    }

    if diff_conjuncts.is_empty() {
        Formula::truth()
    } else {
        Formula::and_all(diff_conjuncts)
    }
}

fn split_and_diff(f: &Formula, out: &mut Vec<Formula>) {
    match f.kind() {
        FormulaKind::And(fs) => {
            for sub in fs {
                split_and_diff(sub, out);
            }
        }
        FormulaKind::Constant(true) => {}
        _ => out.push(f.clone()),
    }
}

fn split_or_diff(f: &Formula, out: &mut Vec<Formula>) {
    match f.kind() {
        FormulaKind::Or(fs) => {
            for sub in fs {
                split_or_diff(sub, out);
            }
        }
        _ => out.push(f.clone()),
    }
}

fn extract_always_or_arms(f: &Formula) -> Option<Vec<Formula>> {
    let FormulaKind::Temporal(TemporalOp::Always, body) = f.kind() else {
        return None;
    };
    let mut arms = Vec::new();
    split_or_diff(body, &mut arms);
    if arms.len() >= 2 { Some(arms) } else { None }
}

/// Reduces `always (assumed_arms) => always (target_arms)` using pure
/// propositional frame stripping (B23):
/// - If `assumed_only` is empty, `assumed => target` is tautologically true.
/// - Otherwise, let `s` be a closed conjunctive arm shared by both sides (such
///   as `nothing`), `C` the conjuncts of `s` implied by every arm in
///   `assumed_only`, and `L = s \ C`. Any shared arm implying `L` is dropped,
///   and `C` is stripped from all remaining arms so only changed tables and
///   their dependencies remain in the assertion.
fn reduce_transition_diff(
    assumed_transitions: &[Vec<Formula>],
    target_arms: &[Formula],
) -> Option<Formula> {
    // Pick the assumed transition sharing the most arms with `target_arms`.
    let assumed_arms = assumed_transitions.iter().max_by_key(|a_arms| {
        a_arms
            .iter()
            .filter(|a| target_arms.iter().any(|t| formula_alpha_eq(a, t, &[])))
            .count()
    })?;

    let mut shared = Vec::new();
    let mut assumed_only = Vec::new();
    for a in assumed_arms {
        if target_arms.iter().any(|t| formula_alpha_eq(a, t, &[])) {
            shared.push(a.clone());
        } else if target_arms.iter().any(|t| arm_syntactically_implies(a, t)) {
            // `a` syntactically implies an arm of `target_arms` (e.g. a tightened
            // trigger with extra guard conjuncts), so `a` can never violate `target`.
        } else {
            assumed_only.push(a.clone());
        }
    }
    if assumed_only.is_empty() {
        return Some(Formula::truth());
    }
    let target_only: Vec<Formula> = target_arms
        .iter()
        .filter(|t| !assumed_arms.iter().any(|a| formula_alpha_eq(a, t, &[])))
        .cloned()
        .collect();

    let assumed_only_closed: Vec<Vec<Formula>> =
        assumed_only.iter().map(arm_closed_conjuncts).collect();

    // Find a shared closed conjunctive arm (typically `nothing` / stutter) that
    // shares the most closed conjuncts with every arm in `assumed_only`.
    let mut best_stutter: Option<(usize, Vec<Formula>, Vec<Formula>)> = None;
    for (idx, s) in shared.iter().enumerate() {
        if matches!(s.kind(), FormulaKind::Quantified(Quantifier::Some, _, _)) {
            continue;
        }
        let mut s_conjs = Vec::new();
        split_and_diff(s, &mut s_conjs);
        if s_conjs.is_empty() || s_conjs.iter().any(formula_has_free_vars) {
            continue;
        }
        let mut common = Vec::new();
        let mut local = Vec::new();
        for c in s_conjs {
            let in_all = assumed_only_closed
                .iter()
                .all(|ac| ac.iter().any(|x| formula_alpha_eq(x, &c, &[])));
            if in_all {
                common.push(c);
            } else {
                local.push(c);
            }
        }
        if common.is_empty() {
            continue;
        }
        let better = match &best_stutter {
            None => true,
            Some((_, prev_common, _)) => common.len() > prev_common.len(),
        };
        if better {
            best_stutter = Some((idx, common, local));
        }
    }

    let (stutter_idx, common, local) = best_stutter?;
    if local.is_empty() {
        // Every conjunct of the shared arm `s` is already implied by every
        // `assumed_only` arm, so `assumed => target` is tautologically true.
        return Some(Formula::truth());
    }

    let mut reduced_arms = Vec::new();
    reduced_arms.push(Formula::and_all(local.clone()));

    for (idx, s) in shared.iter().enumerate() {
        if idx == stutter_idx {
            continue;
        }
        let s_closed = arm_closed_conjuncts(s);
        let implies_local = local
            .iter()
            .all(|l| s_closed.iter().any(|c| formula_alpha_eq(c, l, &[])));
        if implies_local {
            // `s => local`, so `local` already covers every transition matching `s`.
            continue;
        }
        reduced_arms.push(strip_closed_conjuncts(s, &common));
    }

    for b in &target_only {
        reduced_arms.push(strip_closed_conjuncts(b, &common));
    }

    Some(Formula::or_all(reduced_arms).always())
}

fn arm_closed_conjuncts(arm: &Formula) -> Vec<Formula> {
    fn visit(f: &Formula, bound: &mut Vec<Variable>, out: &mut Vec<Formula>) {
        match f.kind() {
            FormulaKind::And(fs) => {
                for sub in fs {
                    visit(sub, bound, out);
                }
            }
            FormulaKind::Quantified(Quantifier::Some, decls, body) => {
                let saved = bound.len();
                for d in decls {
                    bound.push(d.var.clone());
                }
                visit(body, bound, out);
                bound.truncate(saved);
            }
            FormulaKind::Constant(true) => {}
            _ => {
                if !formula_uses_any_var(f, bound) {
                    out.push(f.clone());
                }
            }
        }
    }
    let mut out = Vec::new();
    let mut bound = Vec::new();
    visit(arm, &mut bound, &mut out);
    out
}

fn strip_closed_conjuncts(arm: &Formula, to_strip: &[Formula]) -> Formula {
    fn visit(f: &Formula, bound: &mut Vec<Variable>, to_strip: &[Formula]) -> Formula {
        match f.kind() {
            FormulaKind::And(fs) => {
                let kept: Vec<Formula> = fs
                    .iter()
                    .map(|sub| visit(sub, bound, to_strip))
                    .filter(|g| !matches!(g.kind(), FormulaKind::Constant(true)))
                    .collect();
                if kept.is_empty() {
                    Formula::truth()
                } else {
                    Formula::and_all(kept)
                }
            }
            FormulaKind::Quantified(Quantifier::Some, decls, body) => {
                let saved = bound.len();
                for d in decls {
                    bound.push(d.var.clone());
                }
                let new_body = visit(body, bound, to_strip);
                bound.truncate(saved);
                Formula::quantified(Quantifier::Some, decls.clone(), &new_body)
            }
            _ => {
                if !formula_uses_any_var(f, bound)
                    && to_strip.iter().any(|s| formula_alpha_eq(f, s, &[]))
                {
                    Formula::truth()
                } else {
                    f.clone()
                }
            }
        }
    }
    let mut bound = Vec::new();
    visit(arm, &mut bound, to_strip)
}

fn formula_has_free_vars(f: &Formula) -> bool {
    fn visit_f(f: &Formula, bound: &mut Vec<Variable>) -> bool {
        match f.kind() {
            FormulaKind::Constant(_) => false,
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
                visit_e(a, bound) || visit_e(b, bound)
            }
            FormulaKind::Multiplicity(_, e) => visit_e(e, bound),
            FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => visit_f(a, bound),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(|g| visit_f(g, bound)),
            FormulaKind::Implies(a, b)
            | FormulaKind::Iff(a, b)
            | FormulaKind::TemporalBinary(_, a, b) => visit_f(a, bound) || visit_f(b, bound),
            FormulaKind::Quantified(_, decls, body) => {
                let saved = bound.len();
                for d in decls {
                    if visit_e(&d.expr, bound) {
                        bound.truncate(saved);
                        return true;
                    }
                    bound.push(d.var.clone());
                }
                let res = visit_f(body, bound);
                bound.truncate(saved);
                res
            }
            FormulaKind::IntCompare(_, a, b) => visit_i(a, bound) || visit_i(b, bound),
        }
    }
    fn visit_e(e: &Expr, bound: &mut Vec<Variable>) -> bool {
        match e.kind() {
            ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
            ExprKind::Variable(v) => !bound.contains(v),
            ExprKind::Unary(_, a) | ExprKind::Prime(a) => visit_e(a, bound),
            ExprKind::Binary(_, a, b) => visit_e(a, bound) || visit_e(b, bound),
            ExprKind::Comprehension(decls, body) => {
                let saved = bound.len();
                for d in decls {
                    if visit_e(&d.expr, bound) {
                        bound.truncate(saved);
                        return true;
                    }
                    bound.push(d.var.clone());
                }
                let res = visit_f(body, bound);
                bound.truncate(saved);
                res
            }
            ExprKind::IfThenElse(c, a, b) => {
                visit_f(c, bound) || visit_e(a, bound) || visit_e(b, bound)
            }
            ExprKind::IntToSet(i) => visit_i(i, bound),
        }
    }
    fn visit_i(i: &IntExpr, bound: &mut Vec<Variable>) -> bool {
        match i.kind() {
            IntExprKind::Constant(_) => false,
            IntExprKind::Count(e) | IntExprKind::Sum(e) => visit_e(e, bound),
            IntExprKind::Binary(_, a, b) => visit_i(a, bound) || visit_i(b, bound),
            IntExprKind::Negate(a) => visit_i(a, bound),
            IntExprKind::IfThenElse(c, a, b) => {
                visit_f(c, bound) || visit_i(a, bound) || visit_i(b, bound)
            }
            IntExprKind::SumOver(decls, body) => {
                let saved = bound.len();
                for d in decls {
                    if visit_e(&d.expr, bound) {
                        bound.truncate(saved);
                        return true;
                    }
                    bound.push(d.var.clone());
                }
                let res = visit_i(body, bound);
                bound.truncate(saved);
                res
            }
        }
    }
    visit_f(f, &mut Vec::new())
}

fn formula_uses_any_var(f: &Formula, vars: &[Variable]) -> bool {
    if vars.is_empty() {
        return false;
    }
    fn visit_f(f: &Formula, vars: &[Variable]) -> bool {
        match f.kind() {
            FormulaKind::Constant(_) => false,
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
                visit_e(a, vars) || visit_e(b, vars)
            }
            FormulaKind::Multiplicity(_, e) => visit_e(e, vars),
            FormulaKind::Not(a) | FormulaKind::Temporal(_, a) => visit_f(a, vars),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(|g| visit_f(g, vars)),
            FormulaKind::Implies(a, b)
            | FormulaKind::Iff(a, b)
            | FormulaKind::TemporalBinary(_, a, b) => visit_f(a, vars) || visit_f(b, vars),
            FormulaKind::Quantified(_, decls, body) => {
                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_f(body, vars)
            }
            FormulaKind::IntCompare(_, a, b) => visit_i(a, vars) || visit_i(b, vars),
        }
    }
    fn visit_e(e: &Expr, vars: &[Variable]) -> bool {
        match e.kind() {
            ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
            ExprKind::Variable(v) => vars.contains(v),
            ExprKind::Unary(_, a) | ExprKind::Prime(a) => visit_e(a, vars),
            ExprKind::Binary(_, a, b) => visit_e(a, vars) || visit_e(b, vars),
            ExprKind::Comprehension(decls, body) => {
                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_f(body, vars)
            }
            ExprKind::IfThenElse(c, a, b) => {
                visit_f(c, vars) || visit_e(a, vars) || visit_e(b, vars)
            }
            ExprKind::IntToSet(i) => visit_i(i, vars),
        }
    }
    fn visit_i(i: &IntExpr, vars: &[Variable]) -> bool {
        match i.kind() {
            IntExprKind::Constant(_) => false,
            IntExprKind::Count(e) | IntExprKind::Sum(e) => visit_e(e, vars),
            IntExprKind::Binary(_, a, b) => visit_i(a, vars) || visit_i(b, vars),
            IntExprKind::Negate(a) => visit_i(a, vars),
            IntExprKind::IfThenElse(c, a, b) => {
                visit_f(c, vars) || visit_i(a, vars) || visit_i(b, vars)
            }
            IntExprKind::SumOver(decls, body) => {
                decls.iter().any(|d| visit_e(&d.expr, vars)) || visit_i(body, vars)
            }
        }
    }
    visit_f(f, vars)
}

/// Returns true when transition arm `a` syntactically implies arm `t`
/// (e.g. `some r: T | G1 and G2` implies `some r: T | G1`, W25).
fn arm_syntactically_implies(a: &Formula, t: &Formula) -> bool {
    if formula_alpha_eq(a, t, &[]) {
        return true;
    }
    match (a.kind(), t.kind()) {
        (
            FormulaKind::Quantified(Quantifier::Some, da, ba),
            FormulaKind::Quantified(Quantifier::Some, dt, bt),
        ) if da.len() == dt.len() => {
            let mut env = Vec::with_capacity(da.len());
            for (xa, xt) in da.iter().zip(dt.iter()) {
                if xa.mult != xt.mult || !expr_alpha_eq(&xa.expr, &xt.expr, &env) {
                    return false;
                }
                env.push((xa.var.clone(), xt.var.clone()));
            }
            let mut a_conjs = Vec::new();
            let mut t_conjs = Vec::new();
            split_and_diff(ba, &mut a_conjs);
            split_and_diff(bt, &mut t_conjs);
            t_conjs
                .iter()
                .all(|tc| a_conjs.iter().any(|ac| formula_alpha_eq(ac, tc, &env)))
        }
        _ => {
            let mut a_conjs = Vec::new();
            let mut t_conjs = Vec::new();
            split_and_diff(a, &mut a_conjs);
            split_and_diff(t, &mut t_conjs);
            !t_conjs.is_empty()
                && t_conjs
                    .iter()
                    .all(|tc| a_conjs.iter().any(|ac| formula_alpha_eq(ac, tc, &[])))
        }
    }
}

fn formula_alpha_eq(a: &Formula, b: &Formula, env: &[(Variable, Variable)]) -> bool {
    match (a.kind(), b.kind()) {
        (FormulaKind::Constant(x), FormulaKind::Constant(y)) => x == y,
        (FormulaKind::Subset(a1, a2), FormulaKind::Subset(b1, b2))
        | (FormulaKind::Equal(a1, a2), FormulaKind::Equal(b1, b2)) => {
            expr_alpha_eq(a1, b1, env) && expr_alpha_eq(a2, b2, env)
        }
        (FormulaKind::Multiplicity(m1, e1), FormulaKind::Multiplicity(m2, e2)) => {
            m1 == m2 && expr_alpha_eq(e1, e2, env)
        }
        (FormulaKind::Not(f1), FormulaKind::Not(f2)) => formula_alpha_eq(f1, f2, env),
        (FormulaKind::And(fs1), FormulaKind::And(fs2))
        | (FormulaKind::Or(fs1), FormulaKind::Or(fs2)) => {
            fs1.len() == fs2.len()
                && fs1
                    .iter()
                    .zip(fs2.iter())
                    .all(|(x, y)| formula_alpha_eq(x, y, env))
        }
        (FormulaKind::Implies(a1, a2), FormulaKind::Implies(b1, b2))
        | (FormulaKind::Iff(a1, a2), FormulaKind::Iff(b1, b2)) => {
            formula_alpha_eq(a1, b1, env) && formula_alpha_eq(a2, b2, env)
        }
        (FormulaKind::Quantified(q1, d1, b1), FormulaKind::Quantified(q2, d2, b2)) => {
            if q1 != q2 || d1.len() != d2.len() {
                return false;
            }
            let mut next_env = env.to_vec();
            for (x, y) in d1.iter().zip(d2.iter()) {
                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
                    return false;
                }
                next_env.push((x.var.clone(), y.var.clone()));
            }
            formula_alpha_eq(b1, b2, &next_env)
        }
        (FormulaKind::Temporal(op1, f1), FormulaKind::Temporal(op2, f2)) => {
            op1 == op2 && formula_alpha_eq(f1, f2, env)
        }
        (FormulaKind::TemporalBinary(op1, a1, a2), FormulaKind::TemporalBinary(op2, b1, b2)) => {
            op1 == op2 && formula_alpha_eq(a1, b1, env) && formula_alpha_eq(a2, b2, env)
        }
        (FormulaKind::IntCompare(op1, a1, a2), FormulaKind::IntCompare(op2, b1, b2)) => {
            op1 == op2 && int_alpha_eq(a1, b1, env) && int_alpha_eq(a2, b2, env)
        }
        _ => false,
    }
}

fn expr_alpha_eq(a: &Expr, b: &Expr, env: &[(Variable, Variable)]) -> bool {
    match (a.kind(), b.kind()) {
        (ExprKind::Relation(r1), ExprKind::Relation(r2)) => r1 == r2,
        (ExprKind::Variable(v1), ExprKind::Variable(v2)) => {
            for (x, y) in env.iter().rev() {
                if x == v1 || y == v2 {
                    return x == v1 && y == v2;
                }
            }
            v1 == v2
        }
        (ExprKind::None, ExprKind::None)
        | (ExprKind::Univ, ExprKind::Univ)
        | (ExprKind::Iden, ExprKind::Iden) => true,
        (ExprKind::Unary(op1, e1), ExprKind::Unary(op2, e2)) => {
            op1 == op2 && expr_alpha_eq(e1, e2, env)
        }
        (ExprKind::Binary(op1, a1, a2), ExprKind::Binary(op2, b1, b2)) => {
            op1 == op2 && expr_alpha_eq(a1, b1, env) && expr_alpha_eq(a2, b2, env)
        }
        (ExprKind::Prime(e1), ExprKind::Prime(e2)) => expr_alpha_eq(e1, e2, env),
        (ExprKind::Comprehension(d1, b1), ExprKind::Comprehension(d2, b2)) => {
            if d1.len() != d2.len() {
                return false;
            }
            let mut next_env = env.to_vec();
            for (x, y) in d1.iter().zip(d2.iter()) {
                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
                    return false;
                }
                next_env.push((x.var.clone(), y.var.clone()));
            }
            formula_alpha_eq(b1, b2, &next_env)
        }
        (ExprKind::IfThenElse(c1, t1, e1), ExprKind::IfThenElse(c2, t2, e2)) => {
            formula_alpha_eq(c1, c2, env)
                && expr_alpha_eq(t1, t2, env)
                && expr_alpha_eq(e1, e2, env)
        }
        (ExprKind::IntToSet(i1), ExprKind::IntToSet(i2)) => int_alpha_eq(i1, i2, env),
        _ => false,
    }
}

fn int_alpha_eq(a: &IntExpr, b: &IntExpr, env: &[(Variable, Variable)]) -> bool {
    match (a.kind(), b.kind()) {
        (IntExprKind::Constant(x), IntExprKind::Constant(y)) => x == y,
        (IntExprKind::Count(e1), IntExprKind::Count(e2))
        | (IntExprKind::Sum(e1), IntExprKind::Sum(e2)) => expr_alpha_eq(e1, e2, env),
        (IntExprKind::Binary(op1, a1, a2), IntExprKind::Binary(op2, b1, b2)) => {
            op1 == op2 && int_alpha_eq(a1, b1, env) && int_alpha_eq(a2, b2, env)
        }
        (IntExprKind::Negate(i1), IntExprKind::Negate(i2)) => int_alpha_eq(i1, i2, env),
        (IntExprKind::IfThenElse(c1, t1, e1), IntExprKind::IfThenElse(c2, t2, e2)) => {
            formula_alpha_eq(c1, c2, env) && int_alpha_eq(t1, t2, env) && int_alpha_eq(e1, e2, env)
        }
        (IntExprKind::SumOver(d1, b1), IntExprKind::SumOver(d2, b2)) => {
            if d1.len() != d2.len() {
                return false;
            }
            let mut next_env = env.to_vec();
            for (x, y) in d1.iter().zip(d2.iter()) {
                if x.mult != y.mult || !expr_alpha_eq(&x.expr, &y.expr, &next_env) {
                    return false;
                }
                next_env.push((x.var.clone(), y.var.clone()));
            }
            int_alpha_eq(b1, b2, &next_env)
        }
        _ => false,
    }
}