verif 0.2.0

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
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
//! Differential testing for modular verification.
//!
//! Two soundness holes in the call rule were found by accident, by writing a test
//! that asserted the wrong thing and noticing the engine agreed. That is not a method.
//! This file is the method: generate programs containing calls, verify them with the
//! engine, and *interpret them concretely*, then demand that a proof never outruns
//! reality.
//!
//! The property is one direction, and it is the direction that matters:
//!
//! > if the engine reports the caller verified, then no concrete execution in a
//! > bounded enumeration violates the postcondition.
//!
//! The other direction — a failure must have a real counterexample — is checked where
//! it is cheap, but it cannot be complete, because a failure may come from a bound the
//! enumeration does not reach. Soundness is the property that, if broken, lets a
//! verifier certify a bug, so it is the one tested exhaustively.
//!
//! Three families live here, each aimed at a class of mistake that had already occurred:
//!
//! 1. **Callers**, where the frame rule can be wrong about what a callee writes and what
//!    the caller is told about it.
//! 2. **Loops containing calls**, where the loop rules and the call rule meet, and where
//!    a termination claim can outrun its variant.
//! 3. **Obligation pressure**, where a program has more side obligations than the report
//!    can hold. This one found the worst defect in the crate: obligations past the cap
//!    were dropped silently, so a program could report `Total` while a failing `LoopExit`
//!    sat in the part that did not fit.
//!
//! A generator cannot invent the *shape* of a mistake it was not told about, so each
//! family is biased towards a shape that had already gone wrong.

use verif::smt::{self, var, Var};
use verif::wp::{self, Proc, Stmt};

// ---------------------------------------------------------------------------
// A tiny deterministic generator, so a failure can be re-run.
// ---------------------------------------------------------------------------

struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Rng {
        // Never zero: xorshift has a fixed point there.
        Rng(seed | 1)
    }

    fn next(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }

    fn flip(&mut self) -> bool {
        self.below(2) == 1
    }
}

// ---------------------------------------------------------------------------
// A concrete interpreter for the statement language.
// ---------------------------------------------------------------------------

/// A concrete machine state: variable index to value.
type State = std::collections::BTreeMap<u32, u64>;

/// Why a concrete run stopped without reaching the end.
#[derive(Debug, PartialEq, Eq)]
enum Stopped {
    /// An `assume` was false, or a variable was read before being written.
    Blocked,
    /// An `assert` was false: a real violation of the program's own specification.
    Failed,
    /// A loop ran longer than the interpreter's bound. The run is inconclusive.
    TooLong,
}

/// How the interpreter treats a call.
///
/// [`CallMode::SkipCalls`] exists only for `the_property_has_teeth`: it is a
/// deliberately wrong semantics, used to show that the differential property *can*
/// fail. A check that has never been observed to fail is not evidence of anything.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CallMode {
    /// Execute calls for real.
    Real,
    /// Treat every call as a no-op.
    SkipCalls,
}

/// Run `s` to completion, or say why it did not finish.
///
/// The interpreter is deliberately small: it covers the fragment the generator
/// produces, and returns [`Stopped::TooLong`] rather than guessing when it does not
/// understand something. A verdict of "inconclusive" is not a verdict, and the
/// harness below treats it as such.
fn exec(s: &Stmt<'_>, state: &mut State, mode: CallMode) -> Result<(), Stopped> {
    const LOOP_LIMIT: u32 = 64;
    match s {
        Stmt::Skip => Ok(()),
        Stmt::Assign { var, expr } => {
            let v = lookup(state, *expr).ok_or(Stopped::Blocked)?;
            state.insert(smt::index(*var), v);
            Ok(())
        }
        Stmt::AssignMany { binds } => {
            // Read every right-hand side in the old state, then write.
            let mut vals = Vec::new();
            for (_, expr) in binds.iter() {
                vals.push(lookup(state, *expr).ok_or(Stopped::Blocked)?);
            }
            for ((var, _), v) in binds.iter().zip(vals) {
                state.insert(smt::index(*var), v);
            }
            Ok(())
        }
        Stmt::Assume(c) => match lookup_pred(state, *c) {
            Some(true) => Ok(()),
            _ => Err(Stopped::Blocked),
        },
        Stmt::Assert(c) => match lookup_pred(state, *c) {
            Some(true) => Ok(()),
            Some(false) => Err(Stopped::Failed),
            None => Err(Stopped::Blocked),
        },
        Stmt::Seq { first, second } => {
            exec(first, state, mode)?;
            exec(second, state, mode)
        }
        Stmt::If { cond, then_, else_ } => match lookup_pred(state, *cond) {
            Some(true) => exec(then_, state, mode),
            Some(false) => exec(else_, state, mode),
            None => Err(Stopped::Blocked),
        },
        Stmt::While { cond, body, .. } => {
            let mut n = 0;
            loop {
                match lookup_pred(state, *cond) {
                    Some(true) => {}
                    Some(false) => return Ok(()),
                    None => return Err(Stopped::Blocked),
                }
                if n >= LOOP_LIMIT {
                    return Err(Stopped::TooLong);
                }
                exec(body, state, mode)?;
                n += 1;
            }
        }
        Stmt::Call { proc_, actuals, writes } => {
            if mode == CallMode::SkipCalls {
                return Ok(());
            }
            // Bind the callee's parameters from the caller's arguments.
            let mut callee: State = State::new();
            for (global, local) in actuals.iter() {
                if let Some(v) = state.get(&smt::index(*local)) {
                    callee.insert(smt::index(*global), *v);
                }
            }
            // A caller that violates the precondition is a caller bug; the engine is
            // supposed to have caught it, so this is "blocked" from the callee's side.
            match lookup_pred(&callee, proc_.requires) {
                Some(true) => {}
                _ => return Err(Stopped::Blocked),
            }
            exec(proc_.body, &mut callee, mode)?;
            // Write the callee's frame back through the rename.
            for w in writes.iter() {
                if let Some((_, local)) = actuals.iter().find(|(g, _)| g == w) {
                    if let Some(v) = callee.get(&smt::index(*w)) {
                        state.insert(smt::index(*local), *v);
                    }
                }
            }
            Ok(())
        }
    }
}

fn lookup(state: &State, t: Var) -> Option<u64> {
    smt::evaluate(t, |i| state.get(&i).copied())
}

fn lookup_pred(state: &State, p: smt::Pred) -> Option<bool> {
    smt::evaluate_pred(p, |i| state.get(&i).copied())
}

// ---------------------------------------------------------------------------
// The generator.
// ---------------------------------------------------------------------------

/// A random expression over `x` and small constants.
fn rand_expr(rng: &mut Rng, x: Var, depth: u32) -> Var {
    let choices = if depth == 0 { 4 } else { 7 };
    match rng.below(choices) {
        0 => x,
        1 => smt::word(rng.below(8), 8),
        2 => x + smt::word(1 + rng.below(3), 8),
        3 => x * smt::word(2, 8),
        4 => smt::band(x, smt::word(rng.below(256), 8)),
        5 => smt::bor(x, smt::word(rng.below(256), 8)),
        _ => {
            let l = rand_expr(rng, x, depth - 1);
            let r = rand_expr(rng, x, depth - 1);
            l + r
        }
    }
}

/// Build one case, verify it, and check the proof against concrete execution.
///
/// Returns `true` when the engine verified the caller, so the caller can count how
/// often the interesting case was reached.
fn run_case(seed: u64, case_no: u32) -> bool {
    let mut rng = Rng::new(seed);

    // The callee: `rr := f(x)`, and sometimes a second write to `sc` — either
    // directly, or through a *nested call* to a helper. The nested shape matters: the
    // frame has to propagate through two levels of rename, and that is exactly where
    // an under-declared frame could hide one level up.
    let use_helper = rng.flip();
    let writes_scratch = rng.flip();
    let x = smt::var(8);
    let rr = smt::var(8);
    let sc = smt::var(8);
    let f_expr = rand_expr(&mut rng, x, 2);
    let g_expr = rand_expr(&mut rng, x, 1);

    let write_rr = Stmt::Assign { var: rr, expr: f_expr };
    let write_sc = Stmt::Assign { var: sc, expr: g_expr };

    // A helper that writes `hr := hx + 1`, wired so its result lands in `sc`.
    let hx = smt::var(8);
    let hr = smt::var(8);
    let helper_body = Stmt::Assign { var: hr, expr: hx + 1u32 };
    let helper = Proc {
        name: "helper",
        requires: smt::truth(true),
        ensures: smt::eq(hr, hx + 1u32),
        body: &helper_body,
    };
    let h_actuals = vec![(hx, x), (hr, sc)];
    let h_writes = vec![hr];
    let helper_call = Stmt::Call { proc_: &helper, actuals: &h_actuals, writes: &h_writes };
    // `sc` is written either way when the helper is used.
    let sc_is_written = writes_scratch || use_helper;

    let callee_body = if use_helper {
        Stmt::Seq { first: &helper_call, second: &write_rr }
    } else if writes_scratch {
        Stmt::Seq { first: &write_rr, second: &write_sc }
    } else {
        Stmt::Seq { first: &write_rr, second: &Stmt::Skip }
    };
    let callee = Proc {
        name: "callee",
        // A precondition that is always satisfiable, so the caller's obligation is
        // discharged for every input and the interesting failures come from the frame.
        requires: smt::truth(true),
        ensures: smt::eq(rr, f_expr),
        body: &callee_body,
    };
    // The callee must verify, or nothing downstream is meaningful.
    // The helper must verify too, since the callee assumes its contract.
    assert!(
        wp::verify_proc(&helper).is_verified(),
        "case {}: the helper must verify",
        case_no
    );
    let callee_report = wp::verify_proc(&callee);
    assert!(
        callee_report.is_verified(),
        "case {}: the callee itself must verify: {:?}",
        case_no,
        callee_report.first_failure()
    );

    // The caller. `input` is free; `t` receives the result; `b` is seeded so a
    // postcondition about it is meaningful.
    let input = smt::var(8);
    let t = smt::var(8);
    let b = smt::var(8);

    // The rename. `sc` is mapped only sometimes, which is how an unmodelled call is
    // produced; and `rr` is mapped onto `input` sometimes, which is the aliasing that
    // must be rejected.
    let alias_result = rng.below(4) == 0;
    let result_target = if alias_result { input } else { t };
    let mut actuals = vec![(x, input), (rr, result_target)];
    let map_scratch = sc_is_written && rng.flip();
    if map_scratch {
        actuals.push((sc, b));
    }

    // The declared frame: correct, generous, or a lie. The lie is the case that used
    // to make the engine prove a falsehood.
    let declared: Vec<Var> = match rng.below(4) {
        0 => vec![rr],          // correct when there is no scratch
        1 => vec![rr, sc],      // generous
        2 => vec![rr, sc, x],   // over-declared
        _ => Vec::new(),        // a lie
    };

    let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &declared };

    // Seed both `b` and the result target *before* the call. Seeding the result is
    // what gives the havoc rule something to get wrong: if the engine lets the
    // pre-call value of a written variable masquerade as its post-call value, then a
    // postcondition like `t == 0x55` verifies even though the call overwrote `t`.
    // Without this seeding the harness could not see that bug at all.
    let seed_b = Stmt::Assign { var: b, expr: smt::word(0x07, 8) };
    let seed_value = 0x55u64;
    // Seeding the input would constrain the enumeration, so skip it when the result
    // was renamed onto the input.
    let seed_result = !alias_result;
    let seed_t = Stmt::Assign { var: result_target, expr: smt::word(seed_value, 8) };
    let prog = if seed_result {
        Stmt::Seq {
            first: &seed_b,
            second: &Stmt::Seq { first: &seed_t, second: &call },
        }
    } else {
        Stmt::Seq { first: &seed_b, second: &call }
    };

    // The postcondition: about the result, about `b`, about a value the call should
    // have destroyed, or trivially true. The last two are the ones the two soundness
    // holes used to get wrong.
    let result_in_caller = smt::substitute_word(f_expr, &[(x, input)]);
    let post = match rng.below(5) {
        0 => smt::eq(result_target, result_in_caller),
        1 => smt::ule_const(result_target, 0xff),
        2 => smt::eq_const(b, 0x07),
        // "the call left the result alone" -- false, and the havoc rule must make it
        // unprovable.
        3 if seed_result => smt::eq_const(result_target, seed_value),
        _ => smt::truth(true),
    };

    let report = wp::verify(&prog, smt::truth(true), post);
    let verified = report.is_verified();

    // The property: a proof must not outrun reality.
    if verified {
        for v in 0..=255u64 {
            let mut state = State::new();
            state.insert(smt::index(input), v);
            match exec(&prog, &mut state, CallMode::Real) {
                Ok(()) => {
                    let holds = lookup_pred(&state, post);
                    assert!(
                        holds != Some(false),
                        "case {} (seed {}): the engine VERIFIED but input {} violates the \
                         postcondition",
                        case_no,
                        seed,
                        v
                    );
                }
                Err(Stopped::Failed) => panic!(
                    "case {} (seed {}): engine VERIFIED but input {} fails an assertion",
                    case_no, seed, v
                ),
                // Inconclusive runs are not counterexamples.
                Err(Stopped::Blocked) | Err(Stopped::TooLong) => {}
            }
        }
    } else {
        // The cheap half of completeness: a report that is not verified must have a
        // failure to point at.
        assert!(
            report.first_failure().is_some(),
            "case {}: a report that is not verified must have a failure",
            case_no
        );
    }
    verified
}

#[test]
fn a_proof_never_outruns_concrete_execution() {
    // 60 generated cases. Each one is verified with the engine and then executed
    // concretely for every one of the 256 inputs, and a verification that disagrees
    // with any execution fails the test with the case and the input that broke it.
    let mut verified_count = 0;
    for i in 0..300u64 {
        let seed = 0x9E37_79B9_7F4A_7C15u64.wrapping_mul(i + 1);
        if smt::with_fresh(|| run_case(seed, i as u32)) {
            verified_count += 1;
        }
    }
    // Non-vacuity: if the generator stopped producing verifiable callers, the check
    // above would pass while testing nothing.
    assert!(
        verified_count > 30,
        "the generator produced only {} verifiable callers, so the check is nearly vacuous",
        verified_count
    );
}

#[test]
fn the_harness_catches_a_deliberately_broken_frame_rule() {
    // The harness is only worth having if it would have caught the hole it was written
    // for. This reproduces that hole by hand — an under-declared frame — and shows the
    // concrete side sees the violation, which is the evidence the harness relies on.
    // If this stops holding, the harness has gone blind.
    smt::with_fresh(|| {
        let x = smt::var(8);
        let rr = smt::var(8);
        let sc = smt::var(8);
        let a1 = Stmt::Assign { var: sc, expr: x + x };
        let a2 = Stmt::Assign { var: rr, expr: sc };
        let body = Stmt::Seq { first: &a1, second: &a2 };
        let callee = Proc {
            name: "dbl",
            requires: smt::truth(true),
            ensures: smt::eq(rr, x + x),
            body: &body,
        };

        let input = smt::var(8);
        let t = smt::var(8);
        let b = smt::var(8);
        let actuals = vec![(x, input), (rr, t), (sc, b)];
        let lie: Vec<Var> = Vec::new();

        // The frame check rejects the lie, so the engine will not verify. That is the
        // fix; what this test adds is that the concrete side *would* have disagreed.
        assert!(!Stmt::frame(&callee, &actuals, &lie));

        // Run the callee concretely and show the violation is real: with input 3, `b`
        // ends up 6, not the 7 it started at.
        let seed_b = Stmt::Assign { var: b, expr: smt::word(7, 8) };
        let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &lie };
        let prog = Stmt::Seq { first: &seed_b, second: &call };
        let mut state = State::new();
        state.insert(smt::index(input), 3);
        // The interpreter writes only the *declared* frame, so `b` is left alone and
        // the postcondition would appear to hold. That is the unsoundness, reproduced:
        // the declared frame is not what the machine does.
        exec(&prog, &mut state, CallMode::Real).expect("the run completes");
        assert_eq!(state.get(&smt::index(b)).copied(), Some(7));

        // The real machine overwrites `b` with 6. The engine used to agree with the
        // wrong one.
        let real_b = 3u64 + 3;
        assert_ne!(real_b, 7);
        assert_eq!(real_b, 6);
    });
}

#[test]
fn the_property_has_teeth() {
    // A check that has never been observed to fail is not evidence of anything. So:
    // here is a case the engine verifies, and here is the *same* case under a
    // deliberately wrong semantics for calls, where the check fires. That is the
    // detection the real harness depends on, exercised on purpose.
    smt::with_fresh(|| {
        let x = smt::var(8);
        let rr = smt::var(8);
        // The callee returns a constant, so the postcondition below does not depend on
        // the input. My first version used `rr := x + 1` and asserted `t == 1`, which
        // is simply false; the engine produced the counterexample immediately.
        let body = Stmt::Assign { var: rr, expr: smt::word(1, 8) };
        let f = Proc {
            name: "f",
            requires: smt::truth(true),
            ensures: smt::eq_const(rr, 1),
            body: &body,
        };
        let input = smt::var(8);
        let t = smt::var(8);
        let actuals = vec![(x, input), (rr, t)];
        let declared = vec![rr];
        let call = Stmt::Call { proc_: &f, actuals: &actuals, writes: &declared };
        let seed_t = Stmt::Assign { var: t, expr: smt::word(0, 8) };
        let prog = Stmt::Seq { first: &seed_t, second: &call };
        // "t is 1 after the call" -- true exactly when the call is executed.
        let post = smt::eq_const(t, 1);

        let report = wp::verify(&prog, smt::truth(true), post);
        assert!(report.is_verified(), "{:?}", report.first_failure());

        // Real semantics: every input agrees with the proof.
        for v in 0..=255u64 {
            let mut st = State::new();
            st.insert(smt::index(input), v);
            exec(&prog, &mut st, CallMode::Real).expect("the run completes");
            assert_eq!(st.get(&smt::index(t)).copied(), Some(1));
        }

        // Deliberately wrong semantics: the call is a no-op, so `t` stays 0 and the
        // postcondition is false. The harness's check must fire for every input.
        let mut caught = 0;
        for v in 0..=255u64 {
            let mut st = State::new();
            st.insert(smt::index(input), v);
            exec(&prog, &mut st, CallMode::SkipCalls).expect("the run completes");
            if lookup_pred(&st, post) == Some(false) {
                caught += 1;
            }
        }
        assert_eq!(
            caught, 256,
            "the broken semantics must be caught for every input, or the harness is blind"
        );
    });
}

// ---------------------------------------------------------------------------
// Loops containing calls.
//
// This is where the loop rules and the call rule meet, and it is the region where a
// mistake is most expensive: a wrong invariant, a wrong variant, or a frame that does
// not survive an iteration. The generator builds
//
//   callee: rr := x + 1
//   c := <free input>; a := c; k := 0
//   while k < n { tmp := callee(a); a := tmp; k := k + 1 }
//   assert a == c + n
//
// with the contract, the frame, the invariant and the variant each varied. The
// postcondition is exact, so the invariant `k <= n && a == c + k` is what carries the
// proof, and it is preserved only because the callee's postcondition pins its result.
// ---------------------------------------------------------------------------

/// Build and check one loop-with-a-call case. Returns `(verified, termination_proved)`.
fn run_loop_case(seed: u64, case_no: u32) -> (bool, bool) {
    let mut rng = Rng::new(seed);

    // 1..=3 iterations, so the loop terminates and the enumeration stays exhaustive.
    let n = 1 + rng.below(3);
    let exact_contract = rng.below(4) != 0;
    let lie_frame = rng.below(4) == 0;
    let wrong_variant = rng.below(4) == 0;
    // A body that never advances the counter, so the loop diverges. `variant: None`
    // then leaves a *partially* correct proof: the invariant is trivially preserved and
    // the exit condition is vacuous, yet the loop never terminates. That is the case
    // that makes the termination check non-vacuous.
    let diverges = rng.below(8) == 0;

    // The callee.
    let x = smt::var(8);
    let rr = smt::var(8);
    let callee_body = Stmt::Assign { var: rr, expr: x + 1u32 };
    let callee_ensures = if exact_contract {
        smt::eq(rr, x + 1u32)
    } else {
        // Still true, but it does not pin the result when `x` is at the top of its
        // range -- so the loop invariant cannot be preserved from it.
        smt::implies(smt::ult_const(x, 255), smt::eq(rr, x + 1u32))
    };
    let callee = Proc {
        name: "inc",
        requires: smt::truth(true),
        ensures: callee_ensures,
        body: &callee_body,
    };
    assert!(
        wp::verify_proc(&callee).is_verified(),
        "case {}: the callee must verify on its own",
        case_no
    );

    // The caller.
    let c = smt::var(8); // the free input, read-only across the call
    let a = smt::var(8); // the accumulator
    let k = smt::var(3); // the counter, wider than nothing but small
    let tmp = smt::var(8); // the callee's result, then copied back

    let actuals = vec![(x, a), (rr, tmp)];
    let declared: Vec<Var> = if lie_frame { Vec::new() } else { vec![rr] };
    let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &declared };

    let advance = Stmt::Assign { var: k, expr: k + 1u32 };
    let copy_back = Stmt::Assign { var: a, expr: tmp };
    let loop_body = if diverges {
        // The call still happens, so the call rules are exercised; only the counter
        // fails to advance.
        Stmt::Seq { first: &call, second: &copy_back }
    } else {
        Stmt::Seq {
            first: &call,
            second: &Stmt::Seq { first: &copy_back, second: &advance },
        }
    };

    let inv = smt::and(
        smt::ule_const(k, n),
        smt::eq(a, c + smt::truncate(k, 8)),
    );
    let variant = if diverges || wrong_variant {
        // A measure that does not decrease, or none at all.
        Some(k)
    } else {
        Some(smt::sub(smt::word(n, 3), k))
    };
    let loop_ = Stmt::While {
        cond: smt::ult_const(k, n),
        invariant: inv,
        variant,
        body: &loop_body,
    };

    let init_k = Stmt::Assign { var: k, expr: smt::word(0, 3) };
    let init_a = Stmt::Assign { var: a, expr: c };
    let prologue = Stmt::Seq { first: &init_k, second: &init_a };
    let prog = Stmt::Seq { first: &prologue, second: &loop_ };

    let post = smt::eq(a, c + smt::word(n, 8));
    let report = wp::verify(&prog, smt::truth(true), post);
    let verified = report.is_verified();
    // The raw termination claim, read the way a caller who skipped `is_verified` would
    // read it. This is deliberately *not* `establishes()`: the defect this check exists
    // for is a `Total` claim on a report that failed, and `establishes()` would fold
    // that failure into `Nothing` and hide it. Two invariants, checked for every input:
    //
    //   verified  => no violating execution
    //   raw_total => no divergent execution
    //
    // The second is what makes the variant rule observable. It has to be checked
    // outside the `verified` branch, because a variant that fails to discharge leaves
    // the report unverified — and that is exactly when the old code claimed `Total`.
    let raw_total = report.correctness() == wp::Correctness::Total;
    let total = report.establishes() == wp::Established::Total;

    if !verified {
        assert!(
            report.first_failure().is_some(),
            "case {}: a report that is not verified must have a failure",
            case_no
        );
    }

    for v in 0..=255u64 {
        let mut state = State::new();
        state.insert(smt::index(c), v);
        match exec(&prog, &mut state, CallMode::Real) {
            Ok(()) => {
                if verified {
                    let holds = lookup_pred(&state, post);
                    assert!(
                        holds != Some(false),
                        "case {} (seed {}): VERIFIED but input {} violates the \
                         postcondition",
                        case_no,
                        seed,
                        v
                    );
                }
            }
            Err(Stopped::Failed) => assert!(
                !verified,
                "case {} (seed {}): VERIFIED but input {} fails an assertion",
                case_no, seed, v
            ),
            Err(Stopped::TooLong) => {
                // A report that claims termination must not diverge concretely. Note
                // this fires for an *unverified* report too, which is the whole point:
                // a variant that does not decrease is exactly the case that leaves the
                // report unverified while still claiming progress.
                assert!(
                    !raw_total,
                    "case {} (seed {}): the report claims TERMINATION but input {} \
                     diverged. `correctness()` said Total for a loop whose variant was \
                     never proved to decrease.",
                    case_no, seed, v
                );
            }
            Err(Stopped::Blocked) => {}
        }
    }

    (verified, total)
}

#[test]
fn a_loop_with_a_call_never_proves_a_false_postcondition() {
    let mut verified = 0;
    let mut total = 0;
    for i in 0..300u64 {
        let seed = 0xD1B5_4A32_D192_ED03u64.wrapping_mul(i + 1);
        let (v, t) = smt::with_fresh(|| run_loop_case(seed, i as u32));
        if v {
            verified += 1;
        }
        if t {
            total += 1;
        }
    }
    // Non-vacuity, in both directions: some cases must verify, and some must carry a
    // termination proof, or the loop side of the harness is checking nothing.
    assert!(
        verified > 20,
        "only {} of 300 loop cases verified, so the check is nearly vacuous",
        verified
    );
    assert!(
        total > 10,
        "only {} of 300 loop cases proved termination, so the variant rule is barely \
         exercised",
        total
    );
}

#[test]
fn a_total_claim_is_not_made_for_a_divergent_loop() {
    // The termination rule, isolated. A loop whose counter never advances diverges, so
    // no variant can exist: the engine may report the loop *partially* correct — the
    // invariant is preserved and the exit condition is vacuous — but it must not claim
    // termination. Without this, a `Total` verdict would be worth nothing.
    smt::with_fresh(|| {
        let k = smt::var(3);
        let a = smt::var(8);
        let c = smt::var(8);
        // The body does not touch `k`, so `while k < 3` never exits.
        let body = Stmt::Skip;
        let inv = smt::and(smt::ule_const(k, 3), smt::eq(a, c));
        let loop_ = Stmt::While {
            cond: smt::ult_const(k, 3),
            invariant: inv,
            // No variant: only partial correctness is claimed.
            variant: None,
            body: &body,
        };
        let init_k = Stmt::Assign { var: k, expr: smt::word(0, 3) };
        let init_a = Stmt::Assign { var: a, expr: c };
        let prog = Stmt::Seq {
            first: &init_k,
            second: &Stmt::Seq { first: &init_a, second: &loop_ },
        };

        let report = wp::verify(&prog, smt::truth(true), smt::eq(a, c));
        assert!(report.is_verified(), "{:?}", report.first_failure());
        assert!(
            !report.terminates(),
            "a divergent loop must not be reported as terminating"
        );
        assert_eq!(report.correctness(), wp::Correctness::Partial);
        assert_eq!(report.establishes(), wp::Established::Partial);

        // And concretely it really does diverge, so the `Partial` verdict is honest.
        let mut state = State::new();
        state.insert(smt::index(c), 7);
        assert_eq!(
            exec(&prog, &mut state, CallMode::Real),
            Err(Stopped::TooLong),
            "the loop must not terminate concretely"
        );

        // Supplying a measure that cannot decrease turns the claim into a failure.
        let bad = Stmt::While {
            cond: smt::ult_const(k, 3),
            invariant: inv,
            variant: Some(k),
            body: &body,
        };
        let prog2 = Stmt::Seq {
            first: &init_k,
            second: &Stmt::Seq { first: &init_a, second: &bad },
        };
        let report2 = wp::verify(&prog2, smt::truth(true), smt::eq(a, c));
        let (ob, _) = report2
            .first_failure()
            .expect("a non-decreasing measure must fail");
        assert_eq!(ob.rule, wp::Rule::LoopVariant);
    });
}

// ---------------------------------------------------------------------------
// Obligation pressure: more side obligations than the report can hold.
//
// The worst defect in the crate. `push` dropped obligations once the buffer was full, so
// a program could report `verified` — and `Total` — while a failing `LoopExit` sat in the
// part that did not fit. Nothing about the call rule or the loop rule was wrong; the
// report was simply claiming more than it had checked.
//
// This family makes the class catchable by machine: build a loop whose exit obligation
// fails, pad the program with assertions so the obligation count crosses the cap, and
// demand that a report which says `verified` is never contradicted by execution.
// ---------------------------------------------------------------------------

/// Build a program whose `LoopExit` fails, padded with `padding` assertions, and check
/// the property. Returns whether the engine verified it.
///
/// The postcondition is `100 <= i` while the loop exits at `i == 10`, so the exit
/// obligation is genuinely false. Preservation holds, so `LoopExit` is the only
/// obligation that can report it — which is what makes the cap dangerous.
fn run_padded_case(padding: u32, case_no: u32) -> bool {
    smt::with_fresh(|| {
        let i = smt::var(8);
        let init: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Assign {
            var: i,
            expr: smt::word(0, 8),
        }));
        let step: &'static Stmt<'static> =
            Box::leak(Box::new(Stmt::Assign { var: i, expr: i + 1u32 }));
        let loop_: &'static Stmt<'static> = Box::leak(Box::new(Stmt::While {
            cond: smt::ult_const(i, 10),
            invariant: smt::ule_const(i, 10),
            variant: None,
            body: step,
        }));
        let core: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Seq {
            first: init,
            second: loop_,
        }));

        // Padding after the loop, so a right-to-left walk fills the buffer before it
        // reaches the loop.
        let mut node = core;
        for _ in 0..padding {
            let leaf: &'static Stmt<'static> =
                Box::leak(Box::new(Stmt::Assert(smt::truth(true))));
            node = Box::leak(Box::new(Stmt::Seq { first: node, second: leaf }));
        }

        let post = smt::not(smt::ult_const(i, 100));
        let report = wp::verify(node, smt::truth(true), post);
        let verified = report.is_verified();

        if verified {
            // If the report claims verification, execution must agree. This is where the
            // old code failed: the failing exit obligation was dropped, so the report
            // verified, and the postcondition was false for every input.
            let mut state = State::new();
            let outcome = exec(node, &mut state, CallMode::Real);
            assert!(
                outcome != Ok(()),
                "case {} (padding {}): VERIFIED but the program runs to completion and \
                 the postcondition is false",
                case_no,
                padding
            );
            let holds = lookup_pred(&state, post);
            assert!(
                holds != Some(false),
                "case {} (padding {}): VERIFIED but the postcondition is false on \
                 completion",
                case_no,
                padding
            );
        }
        verified
    })
}

#[test]
fn obligation_pressure_never_produces_a_false_verification() {
    // Padding from 0 to well past the cap, so the boundary is crossed in both
    // directions. Nothing here should ever verify, because the exit obligation is false
    // for every input — and with the cap handled honestly, nothing does.
    let mut verified = 0;
    for padding in 0..28u32 {
        if run_padded_case(padding, padding) {
            verified += 1;
        }
    }
    assert_eq!(
        verified, 0,
        "no padding may turn a failing program into a verified one, but {} did",
        verified
    );
}

#[test]
fn crossing_the_cap_is_observable() {
    // The boundary itself, so the test above cannot pass by the padding being
    // ineffective. Below the cap the failure is the loop's; at and above it the failure
    // is the overflow, and the rule named changes.
    smt::with_fresh(|| {
        let i = smt::var(8);
        let init: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Assign {
            var: i,
            expr: smt::word(0, 8),
        }));
        let step: &'static Stmt<'static> =
            Box::leak(Box::new(Stmt::Assign { var: i, expr: i + 1u32 }));
        let loop_: &'static Stmt<'static> = Box::leak(Box::new(Stmt::While {
            cond: smt::ult_const(i, 10),
            invariant: smt::ule_const(i, 10),
            variant: None,
            body: step,
        }));
        let core: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Seq {
            first: init,
            second: loop_,
        }));
        let post = smt::not(smt::ult_const(i, 100));

        // No padding: the loop's own obligations fit, and `LoopExit` is what fails.
        let report = wp::verify(core, smt::truth(true), post);
        let (ob, _) = report.first_failure().expect("the exit obligation fails");
        assert_eq!(ob.rule, wp::Rule::LoopExit);

        // Enough padding to overrun: now the report names the overflow instead, and
        // stops claiming to have checked the loop at all.
        let mut node = core;
        for _ in 0..wp::MAX_OBLIGATIONS {
            let leaf: &'static Stmt<'static> =
                Box::leak(Box::new(Stmt::Assert(smt::truth(true))));
            node = Box::leak(Box::new(Stmt::Seq { first: node, second: leaf }));
        }
        let report = wp::verify(node, smt::truth(true), post);
        let (ob, _) = report.first_failure().expect("the overflow must be reported");
        assert_eq!(ob.rule, wp::Rule::ObligationOverflow);
        assert!(!report.is_verified());
        assert_eq!(report.establishes(), wp::Established::Nothing);
    });
}

// ---------------------------------------------------------------------------
// Memory: the fourth family, and the first module without a harness.
//
// The call and loop rules were covered above; the memory rules were not. They are the
// most algebraic part of the crate -- an ite-chain read, a simultaneous binding list for
// a store, a frame lemma derived by pushing one through the other, and a guarded
// quantifier for a prefix property -- and every one of them is a place where the symbolic
// form could disagree with what an array actually does.
//
// The check is a direct comparison against a concrete array over an enumerable state
// space. A program is a sequence of stores, one of which writes at a *symbolic* address,
// and the postcondition is a fact about the resulting cells. The engine's verdict on
// `wp(post, program)` is compared with the array obtained by running the same operations:
//
//   Valid      => no sampled (initial array, address) may violate the postcondition
//   not Valid  => some sampled input must violate it, and the search must find one
//
// Both directions are checkable because the state space is small and closed: four 8-bit
// cells plus the address, and the program mentions nothing else. Initial values are drawn
// from a set that includes every literal the program and the postcondition use, so the
// sample is biased towards the interactions that can expose a disagreement.
// ---------------------------------------------------------------------------

const MEM_VALS: [u8; 6] = [0, 1, 2, 3, 7, 200];

/// One operation on a four-cell memory. Addresses are concrete cell indices except in
/// [`Op::StoreAtSymbolic`], which uses the program's symbolic address input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    /// `m[addr] := val`
    StoreConst { addr: usize, val: u8 },
    /// `m[dst] := m[src]`
    StoreCopy { dst: usize, src: usize },
    /// `t := m[x]; m[x] := m[y]; m[y] := t`
    SwapCells { x: usize, y: usize },
    /// `m[a] := m[src]`, where `a` is the program's symbolic address.
    StoreAtSymbolic { src: usize },
}

/// The postcondition to check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Post {
    /// `m[i] == m[j]`
    EqCells(usize, usize),
    /// `m[i] == c`
    EqConst(usize, u8),
    /// every cell below the symbolic address equals `c`
    BelowConst(u8),
}

fn mem_pick_cell(rng: &mut Rng) -> usize {
    rng.below(4) as usize
}

fn mem_pick_val(rng: &mut Rng) -> u8 {
    MEM_VALS[rng.below(6) as usize]
}

fn gen_ops(rng: &mut Rng, len: usize) -> Vec<Op> {
    let mut ops = Vec::with_capacity(len);
    for _ in 0..len {
        let which = rng.below(4);
        let op = match which {
            0 => Op::StoreConst {
                addr: mem_pick_cell(rng),
                val: mem_pick_val(rng),
            },
            1 => Op::StoreCopy {
                dst: mem_pick_cell(rng),
                src: mem_pick_cell(rng),
            },
            2 => Op::SwapCells {
                x: mem_pick_cell(rng),
                y: mem_pick_cell(rng),
            },
            _ => Op::StoreAtSymbolic {
                src: mem_pick_cell(rng),
            },
        };
        ops.push(op);
    }
    ops
}

fn gen_post(rng: &mut Rng) -> Post {
    match rng.below(3) {
        0 => Post::EqCells(mem_pick_cell(rng), mem_pick_cell(rng)),
        1 => Post::EqConst(mem_pick_cell(rng), mem_pick_val(rng)),
        _ => Post::BelowConst(mem_pick_val(rng)),
    }
}

/// The concrete array after `ops`, with `a` as the symbolic address and `init` the start.
fn exec_ops(ops: &[Op], a: usize, init: [u8; 4]) -> [u8; 4] {
    let mut m = init;
    for op in ops {
        match *op {
            Op::StoreConst { addr, val } => m[addr] = val,
            Op::StoreCopy { dst, src } => m[dst] = m[src],
            // The symbolic program does this in three steps through a temporary; on an
            // array the same effect is a swap.
            Op::SwapCells { x, y } => m.swap(x, y),
            Op::StoreAtSymbolic { src } => m[a] = m[src],
        }
    }
    m
}

fn eval_post(post: Post, a: usize, m: [u8; 4]) -> bool {
    match post {
        Post::EqCells(i, j) => m[i] == m[j],
        Post::EqConst(i, c) => m[i] == c,
        Post::BelowConst(c) => (0..a).all(|k| m[k] == c),
    }
}

/// Build the symbolic program for `ops`. `a` is the symbolic address variable.
fn build_mem_program(
    ops: &[Op],
    a: Var,
    m: &verif::mem::Mem<'_>,
) -> &'static Stmt<'static> {
    fn binds_of(b: &[(Var, Var)]) -> &'static [(Var, Var)] {
        Box::leak(b.to_vec().into_boxed_slice())
    }
    let mut stmts: Vec<&'static Stmt<'static>> = Vec::new();
    let const_addr = |c: usize| smt::word(c as u64, 2);
    for op in ops {
        match *op {
            Op::StoreConst { addr, val } => {
                let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
                let n = m.store_binds(const_addr(addr), smt::word(val as u64, 8), &mut b);
                stmts.push(Box::leak(Box::new(Stmt::AssignMany {
                    binds: binds_of(&b[..n]),
                })));
            }
            Op::StoreCopy { dst, src } => {
                let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
                let n = m.store_binds(const_addr(dst), m.read_const(src), &mut b);
                stmts.push(Box::leak(Box::new(Stmt::AssignMany {
                    binds: binds_of(&b[..n]),
                })));
            }
            Op::SwapCells { x, y } => {
                let t = smt::var(8);
                stmts.push(Box::leak(Box::new(Stmt::Assign {
                    var: t,
                    expr: m.read_const(x),
                })));
                let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
                let n = m.store_binds(const_addr(x), m.read_const(y), &mut b);
                stmts.push(Box::leak(Box::new(Stmt::AssignMany {
                    binds: binds_of(&b[..n]),
                })));
                let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
                let n = m.store_binds(const_addr(y), t, &mut b);
                stmts.push(Box::leak(Box::new(Stmt::AssignMany {
                    binds: binds_of(&b[..n]),
                })));
            }
            Op::StoreAtSymbolic { src } => {
                let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
                let n = m.store_binds(a, m.read_const(src), &mut b);
                stmts.push(Box::leak(Box::new(Stmt::AssignMany {
                    binds: binds_of(&b[..n]),
                })));
            }
        }
    }
    let mut node: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
    while let Some(s) = stmts.pop() {
        node = Box::leak(Box::new(Stmt::Seq { first: s, second: node }));
    }
    node
}

/// Every initial array the sample considers.
fn sample_arrays() -> Vec<[u8; 4]> {
    let mut out = Vec::new();
    for a in MEM_VALS {
        for b in MEM_VALS {
            for c in MEM_VALS {
                for d in MEM_VALS {
                    out.push([a, b, c, d]);
                }
            }
        }
    }
    out
}

/// Count the sampled (array, address) pairs that violate `post` after `ops`.
fn count_violations(ops: &[Op], post: Post, arrays: &[[u8; 4]]) -> usize {
    let mut violations = 0;
    for init in arrays {
        for a in 0..4usize {
            if !eval_post(post, a, exec_ops(ops, a, *init)) {
                violations += 1;
            }
        }
    }
    violations
}

#[test]
fn a_memory_proof_never_outruns_the_array() {
    let arrays = sample_arrays();
    let mut verified_cases = 0;
    let mut falsified_cases = 0;
    // Coverage counters. "The generator covers the interesting shapes" is exactly the kind
    // of claim this project exists to distrust, so the shapes are counted and asserted
    // rather than argued. A future edit that quietly stopped emitting the symbolic-address
    // store would leave a family that still passes and still proves nothing about it.
    let mut symbolic_store_ops = 0;
    let mut swap_ops = 0;
    let mut below_posts = 0;

    for seed in 0..400u64 {
        let mut rng = Rng::new(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
        let len = 1 + rng.below(4) as usize;
        let ops = gen_ops(&mut rng, len);
        let post = gen_post(&mut rng);
        symbolic_store_ops += ops
            .iter()
            .filter(|o| matches!(o, Op::StoreAtSymbolic { .. }))
            .count();
        swap_ops += ops.iter().filter(|o| matches!(o, Op::SwapCells { .. })).count();
        if matches!(post, Post::BelowConst(_)) {
            below_posts += 1;
        }

        let verdict = smt::with_fresh(|| {
            let mut buf = [Var::SENTINEL; 4];
            let n = verif::mem::declare(2, 8, &mut buf);
            let m = verif::mem::Mem::new(&buf[..n], 8);
            let a = var(2);
            // The quantifier bound needs a width that can hold `len`, which is one more
            // than the address width; see `Mem::check_addr_width`.
            let bound = var(3);
            let prog = build_mem_program(&ops, a, &m);
            let symbolic_post = match post {
                Post::EqCells(i, j) => smt::eq(m.read_const(i), m.read_const(j)),
                Post::EqConst(i, c) => smt::eq(m.read_const(i), smt::word(c as u64, 8)),
                Post::BelowConst(c) => {
                    m.forall_below(bound, |v| smt::eq(v, smt::word(c as u64, 8)))
                }
            };
            smt::prove(wp::wp(symbolic_post, prog))
        });

        let violations = count_violations(&ops, post, &arrays);

        if verdict.is_proved() {
            verified_cases += 1;
            assert_eq!(
                violations, 0,
                "seed {}: VERIFIED but {} sampled (array, address) pairs violate {:?} \
                 after {:?}",
                seed, violations, post, ops
            );
        } else {
            assert!(
                violations > 0,
                "seed {}: verdict {:?} is not a proof, yet no sampled input violates {:?} \
                 after {:?}",
                seed, verdict, post, ops
            );
            falsified_cases += 1;
        }
    }

    // Non-vacuity in both directions: the sample must contain programs the engine proves
    // and programs it refutes, or the comparison above checks nothing.
    assert!(
        verified_cases > 0,
        "no case was proved; the memory family is vacuous"
    );
    assert!(
        falsified_cases > 0,
        "no case was refuted; the memory family cannot detect a bad rule"
    );
    // The shapes that exercise the non-trivial rules must actually appear.
    assert!(
        symbolic_store_ops > 0,
        "no store at a symbolic address was generated; the ite-chain read and the frame \
         rule are not being exercised"
    );
    assert!(
        swap_ops > 0,
        "no swap was generated; the simultaneous-binding path is not being exercised"
    );
    assert!(
        below_posts > 0,
        "no `forall_below` postcondition was generated; the guarded quantifier is not \
         being exercised"
    );
    eprintln!(
        "memory family: {} proved, {} refuted; {} symbolic stores, {} swaps, {} below-posts",
        verified_cases, falsified_cases, symbolic_store_ops, swap_ops, below_posts
    );
}

#[test]
fn the_memory_family_has_teeth() {
    // A deliberately wrong store rule must be caught, or the family above proves nothing.
    //
    // My first attempt at this used a store that kept the destination's own value, which
    // is the identity -- the engine honestly reported "not proved" and nothing was caught,
    // because a rule that proves *too little* is not a soundness bug. The dangerous
    // direction is a rule that proves *too much*: here, a store that writes `val` to
    // every cell and ignores the address. That makes `m[1] == 5` provable after
    // `m[0] := 5`, which is false on any array whose cell 1 did not start at 5.
    let arrays = sample_arrays();
    let addr = 0usize;
    let other = 1usize;
    let val = 5u8;

    let ops = [Op::StoreConst { addr, val }];
    let post = Post::EqConst(other, val);

    let verdict = smt::with_fresh(|| {
        let mut buf = [Var::SENTINEL; 4];
        let n = verif::mem::declare(2, 8, &mut buf);
        let m = verif::mem::Mem::new(&buf[..n], 8);

        // The broken rule: every cell becomes `val`, the address is ignored.
        let binds: &'static [(Var, Var)] = Box::leak(
            m.cells()
                .iter()
                .map(|c| (*c, smt::word(val as u64, 8)))
                .collect::<Vec<_>>()
                .into_boxed_slice(),
        );
        let prog = Stmt::AssignMany { binds };
        let symbolic_post = smt::eq(m.read_const(other), smt::word(val as u64, 8));
        smt::prove(wp::wp(symbolic_post, &prog))
    });

    let violations = count_violations(&ops, post, &arrays);
    assert!(
        verdict.is_proved(),
        "the broken rule was expected to prove the false postcondition, but gave {:?}",
        verdict
    );
    assert!(
        violations > 0,
        "the broken rule proved a postcondition that no sampled array violates; the \
         teeth test is not exercising the disagreement it claims to"
    );
}

// ---------------------------------------------------------------------------
// Memory, positive side: programs that *should* verify.
//
// The random family above is dominated by refutations -- 362 of 400 -- because a randomly
// chosen postcondition is rarely true unless the program forces it. Refutation is a test of
// *strength*: a weak rule proves too much, so it fails to refute. Soundness is tested by
// the other direction, and the random family gives only 38 proved cases to test it with.
// That is thin, and the thinness is structural, not bad luck.
//
// So this family is biased the other way. Each case is a template that is *correct by
// construction*, aimed at one of the four non-trivial rules:
//
//   StoreReadSymbolic  the ite-chain read: read back what was just stored, at a symbolic
//                      address, for every address.
//   StoreFrameSymbolic the frame rule: a store at one address leaves another alone.
//   FillBelow          the guarded quantifier: fill a prefix, then `forall_below` it.
//   Swap               simultaneous bindings: an exchange through a temporary.
//   Copy               the read/write composition: a cell equals the source it was copied
//                      from, using a snapshot for the old value.
//
// Every case must satisfy two things at once: the engine must *prove* it, and no concrete
// array may violate it. A template that fails to prove is a false negative -- not a
// soundness bug, but worth knowing. A template that proves while an array violates it is a
// soundness bug, and that is the case this family exists to catch.
//
// Each template also gets a mutated twin: the same program with the postcondition changed so
// it is false. The mutation must *not* be proved. Without that, a template that the engine
// proved for the wrong reason -- say, because the goal collapsed to `true` -- would look
// like a success.
// ---------------------------------------------------------------------------

/// A program that should verify, plus what it should do to a concrete array.
#[derive(Debug, Clone, Copy)]
enum Pos {
    /// `m[a] := v; assert m[a] == v`
    StoreReadSymbolic { val: u8 },
    /// `old := m[at]; m[a] := v; assert a != at => m[at] == old`
    StoreFrameSymbolic { val: u8, at: usize },
    /// fill cells `0..n` with `v`, then `assert forall k < n { m[k] == v }`
    FillBelow { n: usize, val: u8 },
    /// `t := m[x]; m[x] := m[y]; m[y] := t; assert m[x] == old m[y] && m[y] == old m[x]`
    Swap { x: usize, y: usize },
    /// `m[dst] := m[src]; assert m[dst] == old m[src]`
    Copy { dst: usize, src: usize },
}

fn pos_templates() -> Vec<Pos> {
    let mut out = Vec::new();
    for val in MEM_VALS {
        out.push(Pos::StoreReadSymbolic { val });
        for at in 0..4usize {
            out.push(Pos::StoreFrameSymbolic { val, at });
        }
        for n in 0..=4usize {
            out.push(Pos::FillBelow { n, val });
        }
    }
    for x in 0..4usize {
        for y in 0..4usize {
            out.push(Pos::Swap { x, y });
            for src in 0..4usize {
                out.push(Pos::Copy { dst: x, src });
            }
        }
    }
    out
}

fn pos_seq(stmts: Vec<&'static Stmt<'static>>) -> &'static Stmt<'static> {
    let mut node: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
    for s in stmts.into_iter().rev() {
        node = Box::leak(Box::new(Stmt::Seq { first: s, second: node }));
    }
    node
}

fn pos_store(
    m: &verif::mem::Mem<'_>,
    addr: Var,
    val: Var,
) -> &'static Stmt<'static> {
    let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
    let n = m.store_binds(addr, val, &mut b);
    let binds: &'static [(Var, Var)] = Box::leak(b[..n].to_vec().into_boxed_slice());
    Box::leak(Box::new(Stmt::AssignMany { binds }))
}

fn pos_assign(v: Var, e: Var) -> &'static Stmt<'static> {
    Box::leak(Box::new(Stmt::Assign { var: v, expr: e }))
}

/// Build the symbolic program and postcondition for `p`, and the precondition under which
/// the postcondition is expected to hold. `mutate` replaces the postcondition with a false
/// one, for the teeth check.
fn build_pos(
    p: Pos,
    m: &verif::mem::Mem<'_>,
    a: Var,
    bound: Var,
    mutate: bool,
) -> (smt::Pred, &'static Stmt<'static>, smt::Pred) {
    let caddr = |c: usize| smt::word(c as u64, 2);
    let w8 = |v: u8| smt::word(v as u64, 8);
    match p {
        Pos::StoreReadSymbolic { val } => {
            let prog = pos_store(m, a, w8(val));
            let post = if mutate {
                smt::eq(m.read(a), w8(val.wrapping_add(1)))
            } else {
                smt::eq(m.read(a), w8(val))
            };
            (smt::truth(true), pos_seq(vec![prog]), post)
        }
        Pos::StoreFrameSymbolic { val, at } => {
            let old = var(8);
            let save = pos_assign(old, m.read_const(at));
            let store = pos_store(m, a, w8(val));
            let post = smt::implies(
                smt::not(smt::eq(a, caddr(at))),
                smt::eq(m.read_const(at), if mutate { w8(val) } else { old }),
            );
            (smt::truth(true), pos_seq(vec![save, store]), post)
        }
        Pos::FillBelow { n, val } => {
            let mut stmts = Vec::new();
            for k in 0..n {
                stmts.push(pos_store(m, caddr(k), w8(val)));
            }
            let post = m.forall_below(
                bound,
                |c| {
                    smt::eq(
                        c,
                        if mutate { w8(val.wrapping_add(1)) } else { w8(val) },
                    )
                },
            );
            // The bound must be the fill count, or the quantifier ranges over cells that
            // were never written. It needs to hold `len`, so it is wider than the address.
            (smt::eq_const(bound, n as u64), pos_seq(stmts), post)
        }
        Pos::Swap { x, y } => {
            let t = var(8);
            let oi = var(8);
            let oj = var(8);
            let save_x = pos_assign(oi, m.read_const(x));
            let save_y = pos_assign(oj, m.read_const(y));
            let save_t = pos_assign(t, oi);
            let wr_x = pos_store(m, caddr(x), oj);
            let wr_y = pos_store(m, caddr(y), t);
            let (e0, e1) = if mutate {
                (w8(0), w8(0))
            } else {
                (oj, oi)
            };
            let post = smt::and(
                smt::eq(m.read_const(x), e0),
                smt::eq(m.read_const(y), e1),
            );
            (smt::truth(true), pos_seq(vec![save_x, save_y, save_t, wr_x, wr_y]), post)
        }
        Pos::Copy { dst, src } => {
            let old = var(8);
            let save = pos_assign(old, m.read_const(src));
            let store = pos_store(m, caddr(dst), m.read_const(src));
            let post = smt::eq(
                m.read_const(dst),
                if mutate { w8(0) } else { old },
            );
            (smt::truth(true), pos_seq(vec![save, store]), post)
        }
    }
}

/// Check a template concretely: does every sampled array satisfy the expected effect?
fn pos_concrete_ok(p: Pos, arrays: &[[u8; 4]]) -> bool {
    for init in arrays {
        let mut m = *init;
        let ok = match p {
            Pos::StoreReadSymbolic { val } => {
                // For every address the store lands on, reading it back gives `val`.
                (0..4usize).all(|addr| {
                    let mut mm = m;
                    mm[addr] = val;
                    mm[addr] == val
                })
            }
            Pos::StoreFrameSymbolic { val, at } => (0..4usize).all(|addr| {
                let mut mm = m;
                let old = mm[at];
                mm[addr] = val;
                addr == at || mm[at] == old
            }),
            Pos::FillBelow { n, val } => {
                for slot in m.iter_mut().take(n) {
                    *slot = val;
                }
                m.iter().take(n).all(|cell| *cell == val)
            }
            Pos::Swap { x, y } => {
                let (ox, oy) = (m[x], m[y]);
                m.swap(x, y);
                m[x] == oy && m[y] == ox
            }
            Pos::Copy { dst, src } => {
                let old = m[src];
                m[dst] = old;
                m[dst] == old
            }
        };
        if !ok {
            return false;
        }
    }
    true
}

#[test]
fn memory_programs_that_should_verify_do_verify() {
    let arrays = sample_arrays();
    let mut proved = 0usize;
    let mut mutations_refuted = 0usize;

    for p in pos_templates() {
        let concrete_ok = pos_concrete_ok(p, &arrays);
        assert!(
            concrete_ok,
            "template {:?} violates its own postcondition on a concrete array; the template \
             is wrong, not the engine",
            p
        );

        let verdict = smt::with_fresh(|| {
            let mut buf = [Var::SENTINEL; 4];
            let n = verif::mem::declare(2, 8, &mut buf);
            let m = verif::mem::Mem::new(&buf[..n], 8);
            let a = var(2);
            let bound = var(3);
            let (pre, prog, post) = build_pos(p, &m, a, bound, false);
            smt::prove_implies(pre, wp::wp(post, prog))
        });
        assert!(
            verdict.is_proved(),
            "template {:?} should verify but the engine gave {:?}",
            p,
            verdict
        );
        proved += 1;

        // The mutated twin must not be proved, or the proof above is insensitive.
        //
        // The one exception is `FillBelow { n: 0 }`, and it is a legitimate one: filling
        // zero cells and then asserting "every cell below 0 is v" is *genuinely* true, so
        // changing `v` cannot make it false. That is a vacuously true boundary case, not a
        // hole -- unlike the narrow bound, where vacuity came from an unsatisfiable
        // precondition that looked satisfiable. Excluding it here keeps the mutation count
        // meaningful instead of padding it with a case that cannot be refuted.
        let vacuously_true = matches!(p, Pos::FillBelow { n: 0, .. });
        let mutated = smt::with_fresh(|| {
            let mut buf = [Var::SENTINEL; 4];
            let n = verif::mem::declare(2, 8, &mut buf);
            let m = verif::mem::Mem::new(&buf[..n], 8);
            let a = var(2);
            let bound = var(3);
            let (pre, prog, post) = build_pos(p, &m, a, bound, true);
            smt::prove_implies(pre, wp::wp(post, prog))
        });
        if vacuously_true {
            assert!(
                mutated.is_proved(),
                "{:?} is vacuously true and its mutation should also prove",
                p
            );
        } else {
            assert!(
                !mutated.is_proved(),
                "the mutated postcondition of {:?} was proved, so the template's proof is                  insensitive to the postcondition",
                p
            );
            mutations_refuted += 1;
        }
    }

    assert!(proved > 100, "expected many templates to verify, got {}", proved);
    assert!(
        mutations_refuted > 100,
        "expected nearly every mutated template to be refuted, got {}; a template whose \
         mutation survives is proving nothing",
        mutations_refuted
    );
    eprintln!(
        "memory positive family: {} templates proved, {} mutations refuted",
        proved, mutations_refuted
    );
}

// ---------------------------------------------------------------------------
// Assertions inside and after branches.
//
// The claim an assertion makes is about the states that *reach* it, and two defects in a
// row got that wrong in opposite directions. An assertion inside a branch was checked
// against every input, so a correct program was refused; an assertion after a branch was
// checked as if the branch were absent, also a refusal. Neither was caught by the soundness
// families above, and that is the point: a verifier that refuses too much never certifies a
// bug, so over-refusal is invisible to a one-directional soundness test.
//
// This family pins the claim on both sides:
//
// > the engine verifies the program if and only if no concrete execution reaches a failed
// > assertion.
//
// The left-to-right direction is soundness (the fix must not admit a real failure); the
// right-to-left direction is the guard against over-refusal that the two fixes had to
// satisfy. A generator cannot invent the shape of a mistake it was not told about, so the
// shapes here are exactly the ones that had gone wrong: asserts under a guard, asserts
// under the negated guard, asserts after a branch, and writes between a guard and an
// assertion inside the branch.
// ---------------------------------------------------------------------------

/// A word expression, as a description that can be built in any arena.
#[derive(Clone, Copy, Debug)]
enum EDesc {
    X,
    K(u64),
    AddK(u64),
    MaskK(u64),
}

/// A predicate description.
#[derive(Clone, Debug)]
enum PDesc {
    EqK(u64),
    LtK(u64),
    Not(Box<PDesc>),
    Or(Box<PDesc>, Box<PDesc>),
}

/// A program description.
#[derive(Clone, Debug)]
enum SDesc {
    Assign(EDesc),
    Assert(PDesc),
    If(PDesc, Vec<SDesc>, Vec<SDesc>),
}

fn gen_edesc(rng: &mut Rng) -> EDesc {
    match rng.below(4) {
        0 => EDesc::X,
        1 => EDesc::K(rng.below(4)),
        2 => EDesc::AddK(1 + rng.below(2)),
        _ => EDesc::MaskK(rng.below(8)),
    }
}

fn gen_pdesc(rng: &mut Rng, depth: u32) -> PDesc {
    if depth == 0 || rng.below(3) == 0 {
        return if rng.below(2) == 0 {
            PDesc::EqK(rng.below(4))
        } else {
            PDesc::LtK(rng.below(4))
        };
    }
    match rng.below(3) {
        0 => PDesc::Not(Box::new(gen_pdesc(rng, depth - 1))),
        _ => {
            let a = gen_pdesc(rng, depth - 1);
            let b = gen_pdesc(rng, depth - 1);
            PDesc::Or(Box::new(a), Box::new(b))
        }
    }
}

fn gen_sdesc(rng: &mut Rng, depth: u32, n: usize) -> Vec<SDesc> {
    let mut out = Vec::with_capacity(n);
    for _ in 0..n {
        let which = rng.below(if depth > 0 { 3 } else { 2 });
        let s = match which {
            0 => SDesc::Assign(gen_edesc(rng)),
            1 => SDesc::Assert(gen_pdesc(rng, 1)),
            _ => {
                let c = gen_pdesc(rng, 1);
                let (nt, ne) = (rng.below(3) as usize, rng.below(3) as usize);
                let t = gen_sdesc(rng, depth - 1, nt);
                let e = gen_sdesc(rng, depth - 1, ne);
                SDesc::If(c, t, e)
            }
        };
        out.push(s);
    }
    out
}

/// A built program, with terms that live in the arena current when it was built.
enum Step {
    Assign(Var),
    Assert(smt::Pred),
    If(smt::Pred, Vec<Step>, Vec<Step>),
}

fn build_step(d: &SDesc, x: Var) -> Step {
    match d {
        SDesc::Assign(e) => Step::Assign(match e {
            EDesc::X => x,
            EDesc::K(k) => smt::word(*k, 8),
            EDesc::AddK(k) => smt::add(x, smt::word(*k, 8)),
            EDesc::MaskK(k) => smt::band(x, smt::word(*k, 8)),
        }),
        SDesc::Assert(p) => Step::Assert(build_pdesc(p, x)),
        SDesc::If(c, t, e) => Step::If(
            build_pdesc(c, x),
            t.iter().map(|s| build_step(s, x)).collect(),
            e.iter().map(|s| build_step(s, x)).collect(),
        ),
    }
}

fn build_pdesc(d: &PDesc, x: Var) -> smt::Pred {
    match d {
        PDesc::EqK(k) => x.eq_val(*k),
        PDesc::LtK(k) => x.lt_val(*k),
        PDesc::Not(p) => smt::not(build_pdesc(p, x)),
        PDesc::Or(a, b) => smt::or(build_pdesc(a, x), build_pdesc(b, x)),
    }
}

fn build_program(steps: &[SDesc], x: Var) -> &'static Stmt<'static> {
    let built: Vec<Step> = steps.iter().map(|d| build_step(d, x)).collect();
    leaked_seq(&built, x)
}

fn leaked_seq(steps: &[Step], x: Var) -> &'static Stmt<'static> {
    let mut seq: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
    for s in steps.iter().rev() {
        let one: &'static Stmt<'static> = match s {
            Step::Assign(e) => Box::leak(Box::new(Stmt::Assign { var: x, expr: *e })),
            Step::Assert(p) => Box::leak(Box::new(Stmt::Assert(*p))),
            Step::If(c, t, e) => Box::leak(Box::new(Stmt::If {
                cond: *c,
                then_: leaked_seq(t, x),
                else_: leaked_seq(e, x),
            })),
        };
        seq = Box::leak(Box::new(Stmt::Seq { first: one, second: seq }));
    }
    seq
}

/// Execute the built program on one concrete input, `false` if an assertion fails.
///
/// The state is threaded by `&mut` through the branches. Passing it by value instead
/// loses every assignment made inside an `if`, which makes the interpreter disagree with
/// the engine about a program the engine is right about -- so the differential property
/// fails on a correct program and sends you looking for a soundness hole that is not
/// there. That happened: it cost an afternoon. The `&mut` is the fix.
fn run_steps(steps: &[Step], x: u64) -> bool {
    let mut x = x;
    run_steps_mut(steps, &mut x)
}

fn run_steps_mut(steps: &[Step], x: &mut u64) -> bool {
    for s in steps {
        match s {
            Step::Assign(e) => {
                let cur = *x;
                if let Some(v) = smt::evaluate(*e, |_| Some(cur)) {
                    *x = v;
                }
            }
            Step::Assert(p) => {
                let cur = *x;
                if smt::evaluate_pred(*p, |_| Some(cur)) != Some(true) {
                    return false;
                }
            }
            Step::If(c, t, e) => {
                let cur = *x;
                let take_then = smt::evaluate_pred(*c, |_| Some(cur)) == Some(true);
                if !run_steps_mut(if take_then { t } else { e }, x) {
                    return false;
                }
            }
        }
    }
    true
}

#[test]
fn an_assertion_claim_matches_concrete_execution_both_ways() {
    let mut rng = Rng::new(0xa55e_2718_1337_0001);
    let mut verified = 0u32;
    let mut refused = 0u32;
    for case in 0..500u32 {
        let n = 1 + rng.below(4) as usize;
        let desc = gen_sdesc(&mut rng, 2, n);
        smt::with_fresh(|| {
            let x = var(8);
            let steps: Vec<Step> = desc.iter().map(|d| build_step(d, x)).collect();
            let any_failure = (0..=255u64).any(|v| !run_steps(&steps, v));
            let prog = build_program(&desc, x);
            let is_verified = wp::verify(prog, smt::truth(true), smt::truth(true)).is_verified();

            // Soundness: a proof must not outrun reality.
            assert!(
                !(is_verified && any_failure),
                "case {}: the engine verified a program whose assertion fails on a real input",
                case
            );
            // And no over-refusal: if every input is fine, the engine must say so. This is
            // the direction the guard-context fixes had to establish, and the one a
            // one-directional soundness test cannot see.
            assert!(
                !(!is_verified && !any_failure),
                "case {}: every concrete run is fine but the engine refused the program",
                case
            );
            if is_verified {
                verified += 1;
            } else {
                refused += 1;
            }
        });
    }
    assert!(verified > 20, "expected some programs to verify, got {}", verified);
    assert!(refused > 20, "expected some programs to be refused, got {}", refused);
    eprintln!("assertion family: {} verified, {} refused", verified, refused);
}