elinvar-engine 0.1.1

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
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
//! `run`, `check`, verdicts, the next instance, and the referee (LOGIC.md
//! sections 12.1, 12.6, and 12.7).

use crate::circuit::{Bool, Circuit};
use crate::sat::{Budget, BudgetExhausted, Cdcl, Lit, Solved, Solver};
use crate::skolem::skolemize;
use crate::symmetry;
use crate::translate::{Primary, Shape, Translator};
use elinvar_logic::{
    Against, Bounds, Error, Expr, ExprKind, Formula, FormulaKind, Instance, IntExpr, IntExprKind,
    Relation, TemporalOp, Trace, TupleSet, check_formula, evaluate, evaluate_trace,
};
use serde::Serialize;
use std::fmt;
use std::time::{Duration, Instant};

/// How a search runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Options {
    /// Break symmetries (LOGIC.md 12.5). On by default; off for counting.
    pub symmetry_breaking: bool,
    /// The budget of each solve. There is always one (AGENTS.md law 22).
    pub budget: Budget,
    /// The most states a trace may have (LOGIC.md 13.4).
    pub steps: usize,
    /// The most entries the symmetry predicate compares per pair of atoms
    /// (LOGIC.md 12.5).
    pub predicate_length: usize,
    /// Try a smaller problem with the same verdict before the whole one
    /// (DESIGN.md section 7.9). On by default; off, every check is solved
    /// whole, which gives the reference answer slicing is compared with.
    pub slicing: bool,
    /// Forbid signed integer overflow (`noOverflow` in Alloy 6.2.0,
    /// `A4Options.java`): when true, any case whose integer arithmetic overflows
    /// the bitwidth is ruled out. Off by default, matching Alloy's default.
    pub no_overflow: bool,
}

/// Alloy's default limit on steps (`ScopeComputer.java`, `maxtrace`).
pub const DEFAULT_STEPS: usize = 10;

/// The default budget: generous and finite.
pub const DEFAULT_CONFLICTS: u64 = 10_000_000;

impl Default for Options {
    fn default() -> Options {
        Options {
            symmetry_breaking: true,
            budget: Budget::conflicts(DEFAULT_CONFLICTS),
            steps: DEFAULT_STEPS,
            predicate_length: symmetry::PREDICATE_LENGTH,
            slicing: true,
            no_overflow: false,
        }
    }
}

impl Options {
    /// The same options with symmetry breaking on or off.
    #[must_use]
    pub fn symmetry_breaking(mut self, on: bool) -> Options {
        self.symmetry_breaking = on;
        self
    }

    /// The same options with another length of the symmetry predicate.
    #[must_use]
    pub fn predicate_length(mut self, length: usize) -> Options {
        self.predicate_length = length;
        self
    }

    /// The same options with slicing on or off (DESIGN.md section 7.9).
    #[must_use]
    pub fn slicing(mut self, on: bool) -> Options {
        self.slicing = on;
        self
    }

    /// The same options with overflow prevention on or off (Alloy `noOverflow`).
    #[must_use]
    pub fn no_overflow(mut self, on: bool) -> Options {
        self.no_overflow = on;
        self
    }

    /// The same options with another limit on steps.
    #[must_use]
    pub fn steps(mut self, steps: usize) -> Options {
        self.steps = steps;
        self
    }

    /// The same options with another budget.
    #[must_use]
    pub fn budget(mut self, budget: Budget) -> Options {
        self.budget = budget;
        self
    }
}

/// What a search concluded (DESIGN.md section 7.6).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Verdict {
    /// `run`: an instance, refereed.
    Found,
    /// `run`: no instance within the bounds.
    None,
    /// `check`: an instance that breaks the assertion, refereed.
    Counterexample,
    /// `check`: no counterexample within the bounds, and the rules allow
    /// at least one case.
    Holds,
    /// `check`: proved for any number of steps within the scope by k-induction
    /// (N9), and the initial state is non-vacuous.
    Proved,
    /// `check`: no counterexample within the bounds, because the rules
    /// allow no case within them.
    Vacuous,
    /// The budget ran out.
    Unknown,
}

impl fmt::Display for Verdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Verdict::Found => "found",
            Verdict::None => "none",
            Verdict::Counterexample => "counterexample",
            Verdict::Holds => "holds",
            Verdict::Proved => "proved",
            Verdict::Vacuous => "vacuous",
            Verdict::Unknown => "unknown",
        };
        write!(f, "{s}")
    }
}

/// The size of a translation and the work of its solves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Stats {
    /// Primary variables.
    pub primary_variables: u32,
    /// Gates of the circuit.
    pub gates: usize,
    /// Conflicts over every solve.
    pub conflicts: u64,
}

/// What happened at one step of a trace (LOGIC.md 13.5): an action and
/// its arguments, or nothing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct StepLabel {
    /// The action, or `None` when nothing changed.
    pub action: Option<String>,
    /// The arguments, as atom names.
    pub args: Vec<String>,
}

/// The answer to `run` or `check`.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use]
pub struct Outcome {
    /// The verdict.
    pub verdict: Verdict,
    /// The instance, for `found` and `counterexample` without changing
    /// relations. It holds the user's relations, then the skolem relations
    /// that name witnesses.
    pub instance: Option<Instance>,
    /// The trace, for `found` and `counterexample` with changing relations.
    pub trace: Option<Trace>,
    /// For a trace of a model with actions, step `k` is the one out of
    /// state `k` (LOGIC.md 13.5).
    pub labels: Vec<StepLabel>,
    /// For `unknown`, what is known and which budget ran out.
    pub note: Option<String>,
    /// Statistics.
    pub stats: Stats,
}

impl fmt::Display for Outcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.verdict)?;
        if let Some(note) = &self.note {
            write!(f, " ({note})")?;
        }
        Ok(())
    }
}

/// What the next solve gave.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Next {
    /// An instance of a problem with no changing relation, refereed.
    Instance(Instance),
    /// A trace of a problem with changing relations, refereed.
    Trace(Trace),
    /// No more instances or traces.
    Done,
    /// The budget ran out.
    Unknown,
}

/// The search for one shape of trace: one circuit and one solver.
struct Search {
    bounds: Bounds,
    shape: Shape,
    circuit: Circuit,
    solver: Box<dyn Solver>,
    primaries: Vec<Primary>,
    loop_vars: Vec<Bool>,
    checked_sat: bool,
    cur_loop: usize,
    saved: Option<(Instance, Vec<Instance>, usize, Vec<Lit>)>,
    exhausted: bool,
    timed_out: bool,
}

impl Search {
    fn new(
        bounds: &Bounds,
        formula: &Formula,
        shape: Shape,
        options: &Options,
        mut solver: Box<dyn Solver>,
    ) -> Search {
        let deadline = options.budget.time.map(|t| Instant::now() + t);
        let expired = || deadline.is_some_and(|d| Instant::now() >= d);
        let mut circuit = Circuit::new();
        let mut timed_out = expired();
        let (root, primaries, loop_vars) = if timed_out {
            (Bool::FALSE, Vec::new(), Vec::new())
        } else {
            let (mut tr, primaries, loop_vars) = Translator::new(&mut circuit, bounds, shape);
            tr.set_deadline(deadline);
            tr.set_no_overflow(options.no_overflow);
            let mut root = tr.formula(formula);
            if tr.timed_out() || expired() {
                timed_out = true;
            }
            if !timed_out && options.no_overflow && root != Bool::FALSE {
                let of = tr.overflow_free();
                root = tr.circuit.and([root, of]);
            }
            if !timed_out && !loop_vars.is_empty() && root != Bool::FALSE {
                let lc = tr.loop_constraint();
                root = tr.circuit.and([root, lc]);
            }
            if !timed_out && options.symmetry_breaking && root != Bool::FALSE {
                let sbp =
                    symmetry::predicate(&mut tr, bounds, &primaries, options.predicate_length);
                root = tr.circuit.and([root, sbp]);
                if expired() {
                    timed_out = true;
                }
            }
            (root, primaries, loop_vars)
        };
        let satisfiable = if timed_out {
            false
        } else {
            circuit.assert(solver.as_mut(), root)
        };
        Search {
            bounds: bounds.clone(),
            shape,
            circuit,
            solver,
            primaries,
            loop_vars,
            checked_sat: false,
            cur_loop: 0,
            saved: None,
            exhausted: !satisfiable,
            timed_out,
        }
    }

    fn is_true(&self, b: Bool) -> bool {
        let l = self.circuit.lit(b);
        self.solver.value(l.var()) != l.is_negative()
    }

    fn block_clause(&self, loop_j: Option<usize>) -> Vec<Lit> {
        let mut block: Vec<Lit> = self
            .primaries
            .iter()
            .map(|p| {
                let l = self.circuit.lit(p.value);
                if self.is_true(p.value) { !l } else { l }
            })
            .collect();
        if let Some(j) = loop_j {
            block.push(!self.circuit.lit(self.loop_vars[j]));
        }
        block
    }

    /// The next model, read as `(fixed, states, loop_to)`, with the model
    /// ruled out afterwards (LOGIC.md 12.6 and 13.4). `None` when there are
    /// no more; `Err` when the budget ran out.
    fn next(&mut self, budget: &Budget) -> Result<Option<(Instance, Vec<Instance>, usize)>, ()> {
        if self.timed_out {
            return Err(());
        }
        if self.exhausted {
            return Ok(None);
        }
        if self.loop_vars.is_empty() {
            let j = self.shape.loop_to.unwrap_or(0);
            return match self.solver.solve(&[], budget) {
                Solved::Unsat => {
                    self.exhausted = true;
                    Ok(None)
                }
                Solved::Unknown => Err(()),
                Solved::Sat => {
                    let (fixed, states) = self.read();
                    let block = self.block_clause(None);
                    if block.is_empty() {
                        self.exhausted = true;
                    } else {
                        self.solver.add_clause(&block);
                    }
                    Ok(Some((fixed, states, j)))
                }
            };
        }
        // Variable-loop search: one solve rules out all `L` loop targets when
        // UNSAT; when SAT, find the earliest loop target `0..L` under
        // assumptions on the same solver.
        if !self.checked_sat {
            match self.solver.solve(&[], budget) {
                Solved::Unsat => {
                    self.exhausted = true;
                    return Ok(None);
                }
                Solved::Unknown => return Err(()),
                Solved::Sat => {
                    self.checked_sat = true;
                    let j = self
                        .loop_vars
                        .iter()
                        .position(|&lv| self.is_true(lv))
                        .expect("loop_constraint forces exactly one loop target true");
                    let (fixed, states) = self.read();
                    let block = self.block_clause(Some(j));
                    if j == 0 {
                        self.solver.add_clause(&block);
                        return Ok(Some((fixed, states, 0)));
                    }
                    self.saved = Some((fixed, states, j, block));
                }
            }
        }
        while self.cur_loop < self.loop_vars.len() {
            if self
                .saved
                .as_ref()
                .is_some_and(|(_, _, j, _)| *j == self.cur_loop)
            {
                let (fixed, states, j, block) = self.saved.take().expect("checked just above");
                self.solver.add_clause(&block);
                return Ok(Some((fixed, states, j)));
            }
            let lv = self.circuit.lit(self.loop_vars[self.cur_loop]);
            match self.solver.solve(&[lv], budget) {
                Solved::Sat => {
                    let (fixed, states) = self.read();
                    let block = self.block_clause(Some(self.cur_loop));
                    self.solver.add_clause(&block);
                    return Ok(Some((fixed, states, self.cur_loop)));
                }
                Solved::Unsat => self.cur_loop += 1,
                Solved::Unknown => return Err(()),
            }
        }
        self.exhausted = true;
        Ok(None)
    }

    /// A model under assumptions, without ruling it out afterwards.
    fn solve_assuming(
        &mut self,
        assumptions: &[Lit],
        budget: &Budget,
    ) -> Result<Option<(Instance, Vec<Instance>)>, ()> {
        Ok(self
            .solve_assuming_bits(assumptions, budget)?
            .map(|bits| self.read_from(&bits)))
    }

    /// A model under assumptions, returning only primary-variable booleans
    /// without constructing full `Instance`s (used during tuple shrinking).
    fn solve_assuming_bits(
        &mut self,
        assumptions: &[Lit],
        budget: &Budget,
    ) -> Result<Option<Vec<bool>>, ()> {
        if self.timed_out {
            return Err(());
        }
        if self.exhausted {
            return Ok(None);
        }
        match self.solver.solve(assumptions, budget) {
            Solved::Unsat => Ok(None),
            Solved::Unknown => Err(()),
            Solved::Sat => Ok(Some(
                self.primaries
                    .iter()
                    .map(|p| self.is_true(p.value))
                    .collect(),
            )),
        }
    }

    fn read(&self) -> (Instance, Vec<Instance>) {
        let bits: Vec<bool> = self
            .primaries
            .iter()
            .map(|p| self.is_true(p.value))
            .collect();
        self.read_from(&bits)
    }

    fn read_from(&self, bits: &[bool]) -> (Instance, Vec<Instance>) {
        let universe = self.bounds.universe();
        let mut fixed = Instance::new(universe);
        let mut states: Vec<Instance> = (0..self.shape.states)
            .map(|_| Instance::new(universe))
            .collect();
        // Each relation's set in each of its states (one for a static
        // relation, as `Translator::new` allocates them): the lower bound and
        // the true primaries.
        let mut sets: Vec<Vec<TupleSet>> = self
            .bounds
            .entries()
            .map(|(r, lower, _)| {
                let count = if r.is_changing() {
                    self.shape.states
                } else {
                    1
                };
                vec![lower.clone(); count]
            })
            .collect();
        for (p, &val) in self.primaries.iter().zip(bits) {
            if val {
                sets[p.relation][p.state]
                    .insert_index(p.tuple)
                    .expect("a primary variable's tuple is in its relation's upper bound");
            }
        }
        for (r, sets) in self.bounds.relations().zip(sets) {
            if r.is_changing() {
                for (instance, set) in states.iter_mut().zip(sets) {
                    instance
                        .set(r, set)
                        .expect("the bounds' relations are distinct and well formed");
                }
            } else {
                let set = sets
                    .into_iter()
                    .next()
                    .expect("a static relation has one set");
                fixed
                    .set(r, set)
                    .expect("the bounds' relations are distinct and well formed");
            }
        }
        (fixed, states)
    }
}

/// The trace shapes a search tries in turn (LOGIC.md 13.4): for a temporal
/// problem, one per number of states from 1 to `steps`, each with its loop
/// target left to the solver; otherwise one state looping to itself.
fn shapes(temporal: bool, steps: usize, depth: usize) -> Vec<Shape> {
    if temporal {
        (1..=steps.max(1))
            .map(|l| Shape::variable_loop(l, depth))
            .collect()
    } else {
        vec![Shape::single(depth)]
    }
}

struct Engine<'f> {
    user_bounds: Bounds,
    bounds: Bounds,
    formula: Formula,
    skolemized: Formula,
    options: Options,
    temporal: bool,
    shapes: Vec<Shape>,
    next_shape: usize,
    current: Option<Search>,
    make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
    /// The size of the latest search, and the conflicts of the searches
    /// already finished; `stats()` adds the current one's.
    stats: Stats,
    /// Shared wall-clock deadline across all trace shapes when `options.budget.time` is set.
    deadline: Option<Instant>,
    /// Which budget limit caused the last `Next::Unknown`, if known.
    last_unknown: Option<BudgetExhausted>,
}

impl<'f> Engine<'f> {
    fn new(
        bounds: &Bounds,
        formula: &Formula,
        options: &Options,
        make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
    ) -> Result<Engine<'f>, Vec<Error>> {
        let errors = check_formula(formula, Against::Bounds(bounds));
        if !errors.is_empty() {
            return Err(errors);
        }
        let sk = skolemize(formula, bounds);
        // LOGIC.md 12.2: what skolemization leaves over sets or relations
        // cannot be grounded.
        let remaining = higher_order(&sk.formula);
        if !remaining.is_empty() {
            return Err(remaining);
        }
        let temporal = bounds.relations().any(Relation::is_changing);
        let shapes = shapes(temporal, options.steps, formula.past_depth());
        let deadline = options.budget.time.map(|t| Instant::now() + t);
        Ok(Engine {
            user_bounds: bounds.clone(),
            bounds: sk.bounds,
            formula: formula.clone(),
            skolemized: sk.formula,
            options: *options,
            temporal,
            shapes,
            next_shape: 0,
            current: None,
            make_solver,
            stats: Stats::default(),
            deadline,
            last_unknown: None,
        })
    }

    fn stats(&self) -> Stats {
        let mut stats = self.stats;
        stats.conflicts += self.current.as_ref().map_or(0, |s| s.solver.conflicts());
        stats
    }

    fn unknown_reason(&self) -> Option<BudgetExhausted> {
        self.last_unknown
    }

    fn remaining_budget(&self) -> Option<Budget> {
        let mut b = self.options.budget;
        if let Some(deadline) = self.deadline {
            let rem = deadline.checked_duration_since(Instant::now())?;
            b.time = Some(rem);
        }
        Some(b)
    }

    fn next_instance(&mut self) -> Next {
        self.last_unknown = None;
        loop {
            let Some(budget) = self.remaining_budget() else {
                self.last_unknown = Some(BudgetExhausted::Time);
                return Next::Unknown;
            };
            if self.current.is_none() {
                let Some(&shape) = self.shapes.get(self.next_shape) else {
                    return Next::Done;
                };
                self.next_shape += 1;
                let solver = (self.make_solver)();
                let search =
                    Search::new(&self.bounds, &self.skolemized, shape, &self.options, solver);
                self.stats.primary_variables = search.primaries.len() as u32;
                self.stats.gates = search.circuit.gate_count();
                self.current = Some(search);
            }
            let search = self.current.as_mut().expect("set just above");
            match search.next(&budget) {
                Err(()) => {
                    self.last_unknown = search.solver.unknown_reason().or_else(|| {
                        if self.deadline.is_some_and(|d| Instant::now() >= d) {
                            Some(BudgetExhausted::Time)
                        } else {
                            None
                        }
                    });
                    return Next::Unknown;
                }
                Ok(None) => {
                    self.stats.conflicts += search.solver.conflicts();
                    self.current = None;
                }
                Ok(Some((fixed, states, loop_to))) => {
                    return if self.temporal {
                        let trace = Trace::new(fixed, states, loop_to)
                            .expect("a shape has states and a loop target among them");
                        self.referee_trace(&trace);
                        Next::Trace(trace)
                    } else {
                        self.referee(&fixed);
                        Next::Instance(fixed)
                    };
                }
            }
        }
    }

    fn referee(&self, instance: &Instance) {
        referee_instance(&self.user_bounds, &self.formula, &self.skolemized, instance);
    }

    fn referee_trace(&self, trace: &Trace) {
        referee_trace(&self.user_bounds, &self.formula, &self.skolemized, trace);
    }
}

/// A search for the instances, or traces, of one problem, one after
/// another. With changing relations, it tries the shapes of LOGIC.md 13.4
/// in order: by number of states, then by loop target.
///
/// ```
/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
/// use elinvar_engine::{Finder, Next, Options};
///
/// let u = Universe::new(["A", "B"]).unwrap();
/// let s = Relation::unary("S");
/// let mut b = Bounds::new(&u);
/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
///
/// let mut finder = Finder::new(&b, &Expr::relation(&s).some(), &Options::default()).unwrap();
/// let mut found = 0;
/// while let Next::Instance(_) = finder.next_instance() {
///     found += 1;
/// }
/// assert!(found >= 1);
/// ```
pub struct Finder(Engine<'static>);

impl Finder {
    /// Translates a problem: bounds and a formula with no free variables,
    /// using the default solver.
    ///
    /// Errors: every error of the formula against the bounds, together.
    pub fn new(
        bounds: &Bounds,
        formula: &Formula,
        options: &Options,
    ) -> Result<Finder, Vec<Error>> {
        Finder::with_solver(bounds, formula, options, Cdcl::new)
    }

    /// Translates a problem using a solver built by `make_solver` (R9,
    /// DESIGN.md section 7.4). Each trace shape asks for a fresh solver.
    /// Every returned instance or trace is still refereed by `elinvar-logic`.
    ///
    /// Errors: every error of the formula against the bounds, together.
    pub fn with_solver<S, F>(
        bounds: &Bounds,
        formula: &Formula,
        options: &Options,
        mut make_solver: F,
    ) -> Result<Finder, Vec<Error>>
    where
        S: Solver + 'static,
        F: FnMut() -> S + 'static,
    {
        let factory = Box::new(move || Box::new(make_solver()) as Box<dyn Solver>);
        Ok(Finder(Engine::new(bounds, formula, options, factory)?))
    }

    /// Statistics so far: the size of the last translation, and the
    /// conflicts of every solve.
    pub fn stats(&self) -> Stats {
        self.0.stats()
    }

    /// The next instance or trace, after ruling out those already given
    /// (LOGIC.md 12.6 and 13.4).
    pub fn next_instance(&mut self) -> Next {
        self.0.next_instance()
    }
}

/// Every quantifier over sets or relations left in a formula
/// (`logic.higher_order`), once per variable.
fn higher_order(f: &Formula) -> Vec<Error> {
    fn expr(e: &elinvar_logic::Expr, out: &mut Vec<Error>) {
        match e.kind() {
            ExprKind::Binary(_, a, b) => {
                expr(a, out);
                expr(b, out);
            }
            ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr(a, out),
            ExprKind::Comprehension(decls, body) => {
                for d in decls {
                    expr(&d.expr, out);
                }
                formula(body, out);
            }
            ExprKind::IfThenElse(c, a, b) => {
                formula(c, out);
                expr(a, out);
                expr(b, out);
            }
            ExprKind::IntToSet(v) => int(v, out),
            ExprKind::Relation(_)
            | ExprKind::Variable(_)
            | ExprKind::None
            | ExprKind::Univ
            | ExprKind::Iden => {}
        }
    }
    fn int(v: &elinvar_logic::IntExpr, out: &mut Vec<Error>) {
        use elinvar_logic::IntExprKind as K;
        match v.kind() {
            K::Constant(_) => {}
            K::Count(e) | K::Sum(e) => expr(e, out),
            K::Binary(_, a, b) => {
                int(a, out);
                int(b, out);
            }
            K::Negate(a) => int(a, out),
            K::IfThenElse(c, a, b) => {
                formula(c, out);
                int(a, out);
                int(b, out);
            }
            // A sum's declarations are of atoms, checked when it is built.
            K::SumOver(decls, body) => {
                for d in decls {
                    expr(&d.expr, out);
                }
                int(body, out);
            }
        }
    }
    fn formula(f: &Formula, out: &mut Vec<Error>) {
        match f.kind() {
            FormulaKind::Constant(_) => {}
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
                expr(a, out);
                expr(b, out);
            }
            FormulaKind::Multiplicity(_, a) => expr(a, out),
            FormulaKind::Not(g) | FormulaKind::Temporal(_, g) => formula(g, out),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => {
                for g in fs {
                    formula(g, out);
                }
            }
            FormulaKind::Implies(a, b)
            | FormulaKind::Iff(a, b)
            | FormulaKind::TemporalBinary(_, a, b) => {
                formula(a, out);
                formula(b, out);
            }
            FormulaKind::Quantified(_, decls, body) => {
                for d in decls {
                    expr(&d.expr, out);
                    if !d.is_first_order() {
                        let e = Error::new(
                            "logic.higher_order",
                            format!(
                                "`{}` ranges over sets or relations under a quantifier that \
                                 skolemization cannot remove",
                                d.var
                            ),
                        )
                        .at(f.place().clone());
                        if !out.contains(&e) {
                            out.push(e);
                        }
                    }
                }
                formula(body, out);
            }
            FormulaKind::IntCompare(_, a, b) => {
                int(a, out);
                int(b, out);
            }
        }
    }
    let mut out = Vec::new();
    formula(f, &mut out);
    out
}

/// LOGIC.md 12.7: within the bounds, and the formula as the user wrote it
/// is true. A failure is a bug in Elinvar (AGENTS.md law 13).
fn referee_instance(bounds: &Bounds, formula: &Formula, skolemized: &Formula, instance: &Instance) {
    assert!(
        bounds.admits(instance),
        "Elinvar bug: the solver returned an instance outside the bounds \
         (the referee's check of LOGIC.md 12.7). Please report it with the model."
    );
    let verdict = match evaluate(instance, formula) {
        // LOGIC.md 12.7: too large to enumerate as written; the witnesses
        // the instance names decide it.
        Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
            evaluate(instance, skolemized)
        }
        other => other,
    };
    if verdict != Ok(true) {
        panic!(
            "Elinvar bug: the solver returned an instance under which the formula \
             is {verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
             report it with the model."
        );
    }
}

fn referee_trace(bounds: &Bounds, formula: &Formula, skolemized: &Formula, trace: &Trace) {
    assert!(
        trace.within(bounds),
        "Elinvar bug: the solver returned a trace outside the bounds \
         (the referee's check of LOGIC.md 12.7). Please report it with the model."
    );
    let verdict = match evaluate_trace(trace, formula) {
        Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
            evaluate_trace(trace, skolemized)
        }
        other => other,
    };
    if verdict != Ok(true) {
        panic!(
            "Elinvar bug: the solver returned a trace on which the formula is \
             {verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
             report it with the model."
        );
    }
}

/// LOGIC.md 14.3, step 3: fewer tuples. Returns the smallest instance or
/// trace found, the conflicts spent, and whether shrinking finished within
/// `budget`. `None` if there is no instance of that shape, or the first
/// solve runs out of budget.
#[allow(clippy::too_many_arguments)]
pub(crate) fn shrink_tuples(
    full_bounds: &Bounds,
    full_formula: &Formula,
    shrink_bounds: &Bounds,
    shrink_formula: &Formula,
    states: usize,
    loop_to: usize,
    budget: u64,
    solver: Box<dyn Solver>,
) -> Option<(Next, u64, bool)> {
    let sk = skolemize(shrink_formula, shrink_bounds);
    let temporal = full_bounds.relations().any(Relation::is_changing);
    let depth = shrink_formula.past_depth();
    let shape = if temporal {
        Shape::new(states, loop_to, depth)
    } else {
        Shape::single(depth)
    };
    let off = Options::default().symmetry_breaking(false);
    let mut search = Search::new(&sk.bounds, &sk.formula, shape, &off, solver);
    let wrap = |(fixed, states): (Instance, Vec<Instance>)| {
        if temporal {
            let trace = Trace::new(fixed, states, loop_to)
                .expect("a shape has states and a loop target among them");
            referee_trace(full_bounds, full_formula, &sk.formula, &trace);
            Next::Trace(trace)
        } else {
            referee_instance(full_bounds, full_formula, &sk.formula, &fixed);
            Next::Instance(fixed)
        }
    };
    let spent = |s: &Search| s.solver.conflicts();
    // LOGIC.md 14.3: conflicts only, so the instance returned never depends
    // on time (AGENTS.md law 17).
    let left = |s: &Search| Budget::conflicts(budget.saturating_sub(spent(s)).max(1));
    let first_budget = left(&search);
    let Ok(Some(mut current)) = search.solve_assuming_bits(&[], &first_budget) else {
        return None;
    };
    let mut forced: Vec<Lit> = Vec::new();
    let mut finished = true;
    let total_primaries = search.primaries.len();
    let mut k = 0usize;
    let mut batch = Vec::with_capacity(4);
    while k < total_primaries {
        if !current[k] {
            k += 1;
            continue;
        }
        if spent(&search) >= budget {
            finished = false;
            break;
        }
        // Try removing up to 4 true primaries at once; if the batch is UNSAT,
        // fall back to testing them individually in number order.
        batch.clear();
        let mut scan = k;
        while scan < total_primaries && batch.len() < 4 {
            if current[scan] {
                batch.push(scan);
            }
            scan += 1;
        }
        if batch.len() >= 2 {
            let saved_len = forced.len();
            for &idx in &batch {
                forced.push(!search.circuit.lit(search.primaries[idx].value));
            }
            let step_budget = left(&search);
            match search.solve_assuming_bits(&forced, &step_budget) {
                Ok(Some(found)) => {
                    current = found;
                    k = scan;
                    continue;
                }
                Ok(None) => {
                    forced.truncate(saved_len);
                }
                Err(()) => {
                    forced.truncate(saved_len);
                    finished = false;
                    break;
                }
            }
        }
        for &idx in &batch {
            if !current[idx] {
                continue;
            }
            if spent(&search) >= budget {
                finished = false;
                break;
            }
            let step_budget = left(&search);
            forced.push(!search.circuit.lit(search.primaries[idx].value));
            match search.solve_assuming_bits(&forced, &step_budget) {
                Ok(Some(found)) => current = found,
                Ok(None) => {
                    forced.pop();
                }
                Err(()) => {
                    forced.pop();
                    finished = false;
                    break;
                }
            }
        }
        if !finished {
            break;
        }
        k = scan;
    }
    let used = spent(&search);
    Some((wrap(search.read_from(&current)), used, finished))
}

fn format_duration(d: Duration) -> String {
    let ms = d.as_millis();
    if ms == 0 {
        "0ms".to_string()
    } else if ms < 1000 {
        format!("{ms}ms")
    } else if ms.is_multiple_of(60_000) {
        format!("{}m", ms / 60_000)
    } else if ms.is_multiple_of(1000) {
        format!("{}s", ms / 1000)
    } else {
        format!("{:.2}s", d.as_secs_f64())
    }
}

fn unknown_note(budget: &Budget, reason: Option<BudgetExhausted>, known: &str) -> String {
    let which = match reason {
        Some(BudgetExhausted::Time) => match budget.time {
            Some(t) => format!("the time limit of {}", format_duration(t)),
            None => "the time limit".to_string(),
        },
        Some(BudgetExhausted::Conflicts) => match budget.conflicts {
            Some(c) => format!("the conflict budget of {c} conflicts"),
            None => "the conflict budget".to_string(),
        },
        None => match (budget.conflicts, budget.time) {
            (Some(c), Some(t)) => {
                format!("the budget of {c} conflicts or {}", format_duration(t))
            }
            (Some(c), None) => format!("the conflict budget of {c} conflicts"),
            (None, Some(t)) => format!("the time limit of {}", format_duration(t)),
            (None, None) => "the budget".to_string(),
        },
    };
    format!("{which} ran out; {known}")
}

impl Outcome {
    fn from_next(next: Next, found: Verdict, stats: Stats) -> Option<Outcome> {
        let (instance, trace) = match next {
            Next::Instance(i) => (Some(i), None),
            Next::Trace(t) => (None, Some(t)),
            Next::Done | Next::Unknown => return None,
        };
        Some(Outcome {
            verdict: found,
            instance,
            trace,
            labels: Vec::new(),
            note: None,
            stats,
        })
    }

    fn without(verdict: Verdict, note: Option<String>, stats: Stats) -> Outcome {
        Outcome {
            verdict,
            instance: None,
            trace: None,
            labels: Vec::new(),
            note,
            stats,
        }
    }
}

/// Looks for an instance of `formula` within `bounds`; with changing
/// relations, a trace of at most `options.steps` states.
///
/// ```
/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
/// use elinvar_engine::{Options, Verdict, run};
///
/// let u = Universe::new(["A", "B"]).unwrap();
/// let s = Relation::unary("S");
/// let mut b = Bounds::new(&u);
/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
///
/// let out = run(&b, &Expr::relation(&s).one(), &Options::default()).unwrap();
/// assert_eq!(out.verdict, Verdict::Found);
/// ```
pub fn run(bounds: &Bounds, formula: &Formula, options: &Options) -> Result<Outcome, Vec<Error>> {
    run_with_solver(bounds, formula, options, Cdcl::new)
}

/// Like [`run`], using a solver built by `make_solver` (R9, DESIGN.md
/// section 7.4). Every returned instance or trace is still refereed by
/// `elinvar-logic`.
pub fn run_with_solver<S, F>(
    bounds: &Bounds,
    formula: &Formula,
    options: &Options,
    mut make_solver: F,
) -> Result<Outcome, Vec<Error>>
where
    S: Solver + 'static,
    F: FnMut() -> S,
{
    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
    let mut finder = Engine::new(bounds, formula, options, factory)?;
    let next = finder.next_instance();
    let stats = finder.stats();
    Ok(match next {
        Next::Done => Outcome::without(Verdict::None, None, stats),
        Next::Unknown => Outcome::without(
            Verdict::Unknown,
            Some(unknown_note(
                &options.budget,
                finder.unknown_reason(),
                "nothing is known",
            )),
            stats,
        ),
        next => Outcome::from_next(next, Verdict::Found, stats).expect("an instance or a trace"),
    })
}

/// Looks for a counterexample to `assertion` under `rules` within
/// `bounds`; when there is none, tells `holds` from `vacuous` (LOGIC.md
/// 12.1 and 13.4).
///
/// ```
/// use elinvar_engine::logic::{Bounds, Expr, Relation, Universe};
/// use elinvar_engine::{Options, Verdict, check};
///
/// let u = Universe::new(["A", "B"]).unwrap();
/// let s = Relation::unary("S");
/// let mut b = Bounds::new(&u);
/// b.bound_upper(&s, u.all(1).unwrap()).unwrap();
/// let se = Expr::relation(&s);
///
/// let out = check(&b, &se.some(), &se.is_in(&Expr::univ()), &Options::default()).unwrap();
/// assert_eq!(out.verdict, Verdict::Holds);
///
/// let vacuous = check(&b, &se.some().and(&se.no()), &se.some(), &Options::default()).unwrap();
/// assert_eq!(vacuous.verdict, Verdict::Vacuous);
/// ```
pub fn check(
    bounds: &Bounds,
    rules: &Formula,
    assertion: &Formula,
    options: &Options,
) -> Result<Outcome, Vec<Error>> {
    check_with_solver(bounds, rules, assertion, options, Cdcl::new)
}

/// Like [`check`], using a solver built by `make_solver` (R9, DESIGN.md
/// section 7.4). Every returned instance or trace is still refereed by
/// `elinvar-logic`.
pub fn check_with_solver<S, F>(
    bounds: &Bounds,
    rules: &Formula,
    assertion: &Formula,
    options: &Options,
    mut make_solver: F,
) -> Result<Outcome, Vec<Error>>
where
    S: Solver + 'static,
    F: FnMut() -> S,
{
    let deadline = options.budget.time.map(|t| Instant::now() + t);
    let negated = rules.and(&assertion.not());
    let mut stats = {
        let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
        let mut finder = Engine::new(bounds, &negated, options, factory)?;
        let next = finder.next_instance();
        let stats = finder.stats();
        match next {
            Next::Done => stats,
            Next::Unknown => {
                return Ok(Outcome::without(
                    Verdict::Unknown,
                    Some(unknown_note(
                        &options.budget,
                        finder.unknown_reason(),
                        "nothing is known",
                    )),
                    stats,
                ));
            }
            next => {
                return Ok(Outcome::from_next(next, Verdict::Counterexample, stats)
                    .expect("an instance or a trace"));
            }
        }
    };
    let mut rules_opts = *options;
    if let Some(d) = deadline {
        let Some(rem) = d.checked_duration_since(Instant::now()) else {
            return Ok(Outcome::without(
                Verdict::Unknown,
                Some(unknown_note(
                    &options.budget,
                    Some(BudgetExhausted::Time),
                    "no counterexample exists within the bounds, and whether the rules allow any case is not settled",
                )),
                stats,
            ));
        };
        rules_opts.budget.time = Some(rem);
    }
    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
    let mut rules_only = Engine::new(bounds, rules, &rules_opts, factory)?;
    let next = rules_only.next_instance();
    stats.conflicts += rules_only.stats().conflicts;
    let (verdict, note) = match next {
        Next::Instance(_) | Next::Trace(_) => (Verdict::Holds, None),
        Next::Done => (Verdict::Vacuous, None),
        Next::Unknown => (
            Verdict::Unknown,
            Some(unknown_note(
                &options.budget,
                rules_only.unknown_reason(),
                "no counterexample exists within the bounds, and whether the rules allow any case is not settled",
            )),
        ),
    };
    Ok(Outcome::without(verdict, note, stats))
}

/// Solves `formula` on a single fixed-length path of `states` states (with a
/// self-loop on state `states - 1`, never read when `formula` has only bounded
/// `after` operators). Used by k-induction (N9) for exact base and step checks.
pub(crate) fn solve_fixed_states<S, F>(
    bounds: &Bounds,
    formula: &Formula,
    states: usize,
    options: &Options,
    mut make_solver: F,
) -> Result<(Next, Stats), Vec<Error>>
where
    S: Solver + 'static,
    F: FnMut() -> S,
{
    let errors = check_formula(formula, Against::Bounds(bounds));
    if !errors.is_empty() {
        return Err(errors);
    }
    let sk = skolemize(formula, bounds);
    let errors = higher_order(&sk.formula);
    if !errors.is_empty() {
        return Err(errors);
    }
    let temporal = bounds.relations().any(Relation::is_changing) || formula.is_temporal();
    let depth = 0;
    let loop_to = states.saturating_sub(1);
    let shape = if temporal {
        Shape::new(states.max(1), loop_to, depth)
    } else {
        Shape::single(depth)
    };
    let deadline = options.budget.time.map(|t| Instant::now() + t);
    let solver = Box::new(make_solver()) as Box<dyn Solver>;
    let mut search = Search::new(&sk.bounds, &sk.formula, shape, options, solver);
    let stats = |s: &Search| Stats {
        primary_variables: s.primaries.len() as u32,
        gates: s.circuit.gate_count(),
        conflicts: s.solver.conflicts(),
    };
    let mut eff_budget = options.budget;
    if let Some(d) = deadline {
        let Some(rem) = d.checked_duration_since(Instant::now()) else {
            return Ok((Next::Unknown, stats(&search)));
        };
        if rem.is_zero() {
            return Ok((Next::Unknown, stats(&search)));
        }
        eff_budget.time = Some(rem);
    }
    match search.solve_assuming(&[], &eff_budget) {
        Ok(Some((fixed, st))) => {
            let st_out = stats(&search);
            let next = if temporal {
                let trace = Trace::new(fixed, st, loop_to)
                    .expect("a shape has states and a loop target among them");
                referee_trace(bounds, formula, &sk.formula, &trace);
                Next::Trace(trace)
            } else {
                referee_instance(bounds, formula, &sk.formula, &fixed);
                Next::Instance(fixed)
            };
            Ok((next, st_out))
        }
        Ok(None) => Ok((Next::Done, stats(&search))),
        Err(()) => Ok((Next::Unknown, stats(&search))),
    }
}

/// The number of instances, or traces, of `formula` within `bounds`, by
/// the solver, up to `limit`. `None` if the budget ran out first. With
/// symmetry breaking off and no changing relations, this is the count brute
/// force gives (R18).
pub fn count(
    bounds: &Bounds,
    formula: &Formula,
    options: &Options,
    limit: u64,
) -> Result<Option<u64>, Vec<Error>> {
    count_with_solver(bounds, formula, options, limit, Cdcl::new)
}

/// Like [`count`], using a solver built by `make_solver` (R9, DESIGN.md
/// section 7.4).
pub fn count_with_solver<S, F>(
    bounds: &Bounds,
    formula: &Formula,
    options: &Options,
    limit: u64,
    mut make_solver: F,
) -> Result<Option<u64>, Vec<Error>>
where
    S: Solver + 'static,
    F: FnMut() -> S,
{
    let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
    let mut finder = Engine::new(bounds, formula, options, factory)?;
    let mut n = 0;
    while n < limit {
        match finder.next_instance() {
            Next::Instance(_) | Next::Trace(_) => n += 1,
            Next::Done => return Ok(Some(n)),
            Next::Unknown => return Ok(None),
        }
    }
    Ok(Some(n))
}

/// Which named rules were used to establish a `holds` or `vacuous` verdict
/// (REQUIREMENTS.md section 8). Dropping every rule in `unused` leaves the
/// check unsatisfiable; dropping any rule in `used` can break it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct HoldsCore {
    /// Rules in the minimal unsatisfiable core, in declaration order.
    pub used: Vec<String>,
    /// Rules not needed for this check within the scope, in declaration order.
    pub unused: Vec<String>,
}

impl fmt::Display for HoldsCore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "used rules: {}", self.used.join(", "))?;
        if !self.unused.is_empty() {
            write!(f, "; unused rules: {}", self.unused.join(", "))?;
        }
        Ok(())
    }
}

/// Result of budget-bounded core extraction (B13, B14).
pub(crate) enum CoreResult {
    /// Core minimization completed cleanly across all trace lengths.
    Complete(HoldsCore),
    /// The conflict budget ran out before core extraction or minimization finished.
    Incomplete {
        core: Option<HoldsCore>,
        note: String,
    },
    /// The negated assertion was satisfiable under the rules (not UNSAT).
    NotUnsat,
}

fn expr_is_state_only(e: &Expr) -> bool {
    match e.kind() {
        ExprKind::Relation(_)
        | ExprKind::Variable(_)
        | ExprKind::None
        | ExprKind::Univ
        | ExprKind::Iden => true,
        ExprKind::Prime(_) => false,
        ExprKind::Unary(_, a) => expr_is_state_only(a),
        ExprKind::Binary(_, a, b) => expr_is_state_only(a) && expr_is_state_only(b),
        ExprKind::IfThenElse(c, a, b) => {
            formula_is_state_only(c) && expr_is_state_only(a) && expr_is_state_only(b)
        }
        ExprKind::Comprehension(ds, body) => {
            ds.iter().all(|d| expr_is_state_only(&d.expr)) && formula_is_state_only(body)
        }
        ExprKind::IntToSet(n) => int_is_state_only(n),
    }
}

fn int_is_state_only(n: &IntExpr) -> bool {
    match n.kind() {
        IntExprKind::Constant(_) => true,
        IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_is_state_only(e),
        IntExprKind::Negate(a) => int_is_state_only(a),
        IntExprKind::Binary(_, a, b) => int_is_state_only(a) && int_is_state_only(b),
        IntExprKind::IfThenElse(c, a, b) => {
            formula_is_state_only(c) && int_is_state_only(a) && int_is_state_only(b)
        }
        IntExprKind::SumOver(ds, body) => {
            ds.iter().all(|d| expr_is_state_only(&d.expr)) && int_is_state_only(body)
        }
    }
}

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

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

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

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

fn unwrap_always_state_only(f: &Formula) -> Option<Formula> {
    let mut cur = f;
    while let FormulaKind::And(fs) = cur.kind()
        && fs.len() == 1
    {
        cur = &fs[0];
    }
    match cur.kind() {
        FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
            Some(inner.clone())
        }
        _ if formula_is_state_only(cur) => Some(cur.clone()),
        _ => None,
    }
}

/// If `f` holds identically at every state of any trace, returns its single-state
/// equivalent formula.
fn every_state_rule(f: &Formula) -> Option<Formula> {
    let mut cur = f;
    while let FormulaKind::And(fs) = cur.kind()
        && fs.len() == 1
    {
        cur = &fs[0];
    }
    match cur.kind() {
        FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
            Some(inner.clone())
        }
        FormulaKind::And(fs) => {
            let mut parts = Vec::with_capacity(fs.len());
            for g in fs {
                parts.push(every_state_rule(g)?);
            }
            Some(Formula::and_all(parts))
        }
        _ if formula_is_state_only(cur) && !formula_mentions_changing(cur) => Some(cur.clone()),
        _ => None,
    }
}

fn build_holds_core(rules: &[(String, Formula)], used_indices: &[usize]) -> HoldsCore {
    let mut used = Vec::new();
    let mut unused = Vec::new();
    for (i, (name, _)) in rules.iter().enumerate() {
        if used_indices.contains(&i) {
            if !used.contains(name) {
                used.push(name.clone());
            }
        } else if !used.contains(name) && !unused.contains(name) {
            unused.push(name.clone());
        }
    }
    unused.retain(|n| !used.contains(n));
    HoldsCore { used, unused }
}

fn solve_budgeted(
    solver: &mut Cdcl,
    assumptions: &[Lit],
    remaining: &mut u64,
    deadline: Option<std::time::Instant>,
) -> Solved {
    if *remaining == 0 {
        return Solved::Unknown;
    }
    let time = match deadline {
        Some(d) => {
            let Some(rem) = d.checked_duration_since(std::time::Instant::now()) else {
                return Solved::Unknown;
            };
            if rem.is_zero() {
                return Solved::Unknown;
            }
            Some(rem)
        }
        None => None,
    };
    let before = solver.conflicts();
    let budget = Budget {
        conflicts: Some(*remaining),
        time,
    };
    let res = solver.solve(assumptions, &budget);
    let spent = solver.conflicts().saturating_sub(before);
    *remaining = remaining.saturating_sub(spent);
    res
}

/// Budget-bounded minimal unsatisfiable core extraction (B13, B14):
/// tries cheap answers first (0 rules, then every-state static rules on 1 state),
/// then minimizes globally across all trace lengths under one shared budget.
pub(crate) fn explain_core_budgeted(
    bounds: &Bounds,
    rules: &[(String, Formula)],
    assertion: &Formula,
    options: &Options,
    remaining: &mut u64,
) -> Result<CoreResult, Vec<Error>> {
    let mut errors = check_formula(assertion, Against::Bounds(bounds));
    for (_, f) in rules {
        for e in check_formula(f, Against::Bounds(bounds)) {
            if !errors.contains(&e) {
                errors.push(e);
            }
        }
    }
    if !errors.is_empty() {
        return Err(errors);
    }
    // B69: share one wall-clock deadline across every core-extraction probe.
    let time_limit = options.budget.time.map(|d| std::time::Instant::now() + d);

    // Stage 0 & 1 (B14): for a state-only invariant `always P` (or static `P`),
    // check 0 rules and then every-state static rules on a single state first!
    // This answers tautologies and static-rule holds in milliseconds without
    // unrolling the trace or ever touching `fact Steps` (B13).
    if let Some(p) = unwrap_always_state_only(assertion) {
        let sk_p = skolemize(&p.not(), bounds);
        if higher_order(&sk_p.formula).is_empty() {
            // Stage 0: 0 rules on 1 state.
            let mut circuit0 = Circuit::new();
            let mut solver0 = Cdcl::new();
            let root0 = {
                let (mut tr, _, _) = Translator::new(&mut circuit0, &sk_p.bounds, Shape::single(0));
                tr.formula(&sk_p.formula)
            };
            if !circuit0.assert(&mut solver0, root0) {
                return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
            }
            match solve_budgeted(&mut solver0, &[], remaining, time_limit) {
                Solved::Unsat => {
                    return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
                }
                Solved::Unknown => {
                    return Ok(CoreResult::Incomplete {
                        core: None,
                        note: "core extraction did not finish within budget".to_string(),
                    });
                }
                Solved::Sat => {}
            }

            // Stage 1: every-state static rules only on 1 state.
            let static_pairs: Vec<(usize, Formula)> = rules
                .iter()
                .enumerate()
                .filter_map(|(i, (_, f))| every_state_rule(f).map(|sf| (i, sf)))
                .collect();
            if !static_pairs.is_empty() {
                if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
                    return Ok(CoreResult::Incomplete {
                        core: None,
                        note: "core extraction did not finish within budget".to_string(),
                    });
                }
                let mut cur_b = sk_p.bounds.clone();
                let mut sk_static = Vec::with_capacity(static_pairs.len());
                let mut static_ok = true;
                for (orig_i, sf) in &static_pairs {
                    let skr = skolemize(sf, &cur_b);
                    if !higher_order(&skr.formula).is_empty() {
                        static_ok = false;
                        break;
                    }
                    cur_b = skr.bounds;
                    sk_static.push((*orig_i, skr.formula));
                }
                if static_ok {
                    let mut circuit1 = Circuit::new();
                    let mut solver1 = Cdcl::new();
                    let (root1, rbs) = {
                        let (mut tr, _, _) =
                            Translator::new(&mut circuit1, &cur_b, Shape::single(0));
                        let r = tr.formula(&sk_p.formula);
                        let bs: Vec<Bool> = sk_static.iter().map(|(_, f)| tr.formula(f)).collect();
                        (r, bs)
                    };
                    if !circuit1.assert(&mut solver1, root1) {
                        return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
                    }
                    let mut lits = Vec::with_capacity(rbs.len());
                    for rb in rbs {
                        let act = Lit::positive(solver1.new_var());
                        circuit1.assert_if(&mut solver1, act, rb);
                        lits.push(act);
                    }
                    match solve_budgeted(&mut solver1, &lits, remaining, time_limit) {
                        Solved::Unsat => {
                            let init = solver1.unsat_core();
                            let mut core_pos: Vec<usize> = (0..lits.len())
                                .filter(|&k| init.contains(&lits[k]))
                                .collect();
                            let mut i = core_pos.len();
                            while i > 0 {
                                i -= 1;
                                let without: Vec<Lit> = core_pos
                                    .iter()
                                    .enumerate()
                                    .filter(|&(j, _)| j != i)
                                    .map(|(_, &k)| lits[k])
                                    .collect();
                                match solve_budgeted(&mut solver1, &without, remaining, time_limit)
                                {
                                    Solved::Unsat => {
                                        let refined = solver1.unsat_core();
                                        core_pos.retain(|&k| refined.contains(&lits[k]));
                                        i = i.min(core_pos.len());
                                    }
                                    Solved::Unknown => {
                                        let orig: Vec<usize> =
                                            core_pos.iter().map(|&k| sk_static[k].0).collect();
                                        return Ok(CoreResult::Incomplete {
                                            core: Some(build_holds_core(rules, &orig)),
                                            note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
                                        });
                                    }
                                    Solved::Sat => {}
                                }
                            }
                            let orig: Vec<usize> =
                                core_pos.iter().map(|&k| sk_static[k].0).collect();
                            return Ok(CoreResult::Complete(build_holds_core(rules, &orig)));
                        }
                        Solved::Unknown => {
                            return Ok(CoreResult::Incomplete {
                                core: None,
                                note: "core extraction did not finish within budget".to_string(),
                            });
                        }
                        Solved::Sat => {}
                    }
                }
            }
        }
    }

    // Stage 2: full temporal (or non-invariant) global MUS across all shapes.
    let sk_assert = skolemize(&assertion.not(), bounds);
    let mut ho = higher_order(&sk_assert.formula);
    let mut sk_rules = Vec::with_capacity(rules.len());
    let mut cur_bounds = sk_assert.bounds;
    for (_, f) in rules {
        let sk_r = skolemize(f, &cur_bounds);
        for e in higher_order(&sk_r.formula) {
            if !ho.contains(&e) {
                ho.push(e);
            }
        }
        cur_bounds = sk_r.bounds;
        sk_rules.push(sk_r.formula);
    }
    if !ho.is_empty() {
        return Err(ho);
    }
    let temporal = cur_bounds.relations().any(Relation::is_changing);
    let mut depth = sk_assert.formula.past_depth();
    for f in &sk_rules {
        depth = depth.max(f.past_depth());
    }
    // Check largest shapes first: they are the strongest filter for deletion probes.
    let mut shape_list = shapes(temporal, options.steps, depth);
    shape_list.reverse();

    let mut active_solvers: Vec<(Cdcl, Vec<Lit>)> = Vec::new();
    let mut union_mask = vec![false; rules.len()];
    for shape in shape_list {
        if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
            return Ok(CoreResult::Incomplete {
                core: None,
                note: "core extraction did not finish within budget".to_string(),
            });
        }
        let mut circuit = Circuit::new();
        let mut solver = Cdcl::new();
        let (root, rule_bools) = {
            let (mut tr, _, loop_vars) = Translator::new(&mut circuit, &cur_bounds, shape);
            let mut root = tr.formula(&sk_assert.formula);
            if !loop_vars.is_empty() && root != Bool::FALSE {
                let lc = tr.loop_constraint();
                root = tr.circuit.and([root, lc]);
            }
            let rbs: Vec<Bool> = sk_rules.iter().map(|f| tr.formula(f)).collect();
            (root, rbs)
        };
        if !circuit.assert(&mut solver, root) {
            continue;
        }
        let mut lits = Vec::with_capacity(rule_bools.len());
        for rb in rule_bools {
            let act = Lit::positive(solver.new_var());
            circuit.assert_if(&mut solver, act, rb);
            lits.push(act);
        }
        match solve_budgeted(&mut solver, &lits, remaining, time_limit) {
            Solved::Sat => return Ok(CoreResult::NotUnsat),
            Solved::Unknown => {
                return Ok(CoreResult::Incomplete {
                    core: None,
                    note: "core extraction did not finish within budget".to_string(),
                });
            }
            Solved::Unsat => {
                let init = solver.unsat_core();
                for (i, lit) in lits.iter().enumerate() {
                    if init.contains(lit) {
                        union_mask[i] = true;
                    }
                }
                active_solvers.push((solver, lits));
            }
        }
    }

    let mut core: Vec<usize> = (0..rules.len()).filter(|&i| union_mask[i]).collect();
    // B13: global deletion-based MUS across ALL shapes together, trying to drop
    // temporal transition rules first so unnecessary trace facts are always pruned.
    let mut trial_order: Vec<usize> = core
        .iter()
        .copied()
        .filter(|&i| every_state_rule(&rules[i].1).is_none())
        .rev()
        .collect();
    trial_order.extend(
        core.iter()
            .copied()
            .filter(|&i| every_state_rule(&rules[i].1).is_some())
            .rev(),
    );

    for cand in trial_order {
        if !core.contains(&cand) {
            continue;
        }
        let without_idx: Vec<usize> = core.iter().copied().filter(|&i| i != cand).collect();
        let mut all_unsat = true;
        for (solver, lits) in &mut active_solvers {
            let assumps: Vec<Lit> = without_idx.iter().map(|&i| lits[i]).collect();
            match solve_budgeted(solver, &assumps, remaining, time_limit) {
                Solved::Unsat => {}
                Solved::Sat => {
                    all_unsat = false;
                    break;
                }
                Solved::Unknown => {
                    return Ok(CoreResult::Incomplete {
                        core: Some(build_holds_core(rules, &core)),
                        note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
                    });
                }
            }
        }
        if all_unsat {
            core = without_idx;
        }
    }
    Ok(CoreResult::Complete(build_holds_core(rules, &core)))
}

/// Extracts a minimal subset of `rules` that suffices to rule out any
/// counterexample to `assertion` within `bounds` (REQUIREMENTS.md section 8).
///
/// Returns `Ok(None)` if a counterexample exists or the budget runs out.
/// Symmetry breaking is disabled during core extraction so the core reflects
/// only the named rules.
pub fn explain_core(
    bounds: &Bounds,
    rules: &[(String, Formula)],
    assertion: &Formula,
    options: &Options,
) -> Result<Option<HoldsCore>, Vec<Error>> {
    let mut remaining = options.budget.conflicts.unwrap_or(DEFAULT_CONFLICTS);
    match explain_core_budgeted(bounds, rules, assertion, options, &mut remaining)? {
        CoreResult::Complete(core) => Ok(Some(core)),
        CoreResult::Incomplete { .. } | CoreResult::NotUnsat => Ok(None),
    }
}

/// The tuple set of a relation by name in an instance, for tests and
/// renderings.
pub fn tuples_named<'a>(instance: &'a Instance, name: &str) -> Option<&'a TupleSet> {
    instance
        .entries()
        .find(|(r, _)| r.name() == name)
        .map(|(_, t)| t)
}

#[cfg(test)]
mod tests {
    use super::*;
    use elinvar_logic::{Expr, Universe};

    /// LOGIC.md 13.6: the worked examples, translated on the fixed shape
    /// shrinking uses, three states looping to state 1, with `s` pinned to
    /// `{}`, `{A}`, `{}`. Each holds there exactly when its value is true.
    #[test]
    fn worked_examples_on_a_fixed_loop() {
        let u = Universe::new(["A"]).expect("one atom is a universe");
        let r = Relation::changing("s", 1);
        let mut bounds = Bounds::new(&u);
        bounds
            .bound_upper(&r, u.all(1).expect("arity 1"))
            .expect("s is new");
        let s = Expr::relation(&r);
        let (some, none) = (s.some(), s.no());
        let pinned = none.and(&some.and(&none.after()).after());
        let cases: Vec<(Formula, bool)> = vec![
            (some.clone(), false),
            (some.after(), true),
            (some.eventually(), true),
            (some.always(), false),
            (some.eventually().always(), true),
            (some.always().eventually(), false),
            (none.until(&some), true),
            (some.releases(&none), false),
            (some.once(), false),
            (some.once().after(), true),
            (some.before().after().after(), true),
            (none.historically().eventually(), true),
            (some.implies(&none.before()).always(), true),
            (none.since(&some).after(), true),
            (some.triggered(&none), true),
            (s.prime().equals(&s), false),
            (s.prime().equals(&s).not().always(), true),
        ];
        for (f, want) in cases {
            for (g, holds) in [(f.clone(), want), (f.not(), !want)] {
                let full = pinned.and(&g);
                let found = shrink_tuples(
                    &bounds,
                    &full,
                    &bounds,
                    &full,
                    3,
                    1,
                    1_000_000,
                    Box::new(Cdcl::new()),
                );
                assert_eq!(found.is_some(), holds, "{g}");
            }
        }
    }
}