dive-trace 0.1.0

TLA+ counterexample trace format and independent trace validation
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
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
//! The checks.
//!
//! Every check evaluates a predicate of the model over *given* states with
//! the dive-eval evaluator (`Model::eval`): `Init` as a state predicate on the
//! first state, the next-state relation as an action predicate on each pair
//! of states. Private register-dependent Init delegates to an independent
//! single-candidate operation from empty slots. Whether a state has a
//! successor (a deadlock ending, `ENABLED`, fairness) is the dive-eval
//! evaluator's `ENABLED` search ([`crate::enabled`]).
//!
//! **Random draws.** Borrowed/warmed-model replay refuses them by name
//! ([`RANDOM_UNSUPPORTED`]). Fresh native finite sessions can independently
//! prove bounded `RandomElement` support by rebinding the entire source runtime
//! per alternative. No producer RNG position or cached answer supplies proof.
//! Register reads and writes are also refused ([`REGISTERS_UNSUPPORTED`]):
//! the evaluator may retain values written by off-trace checker evaluations.
//!
//! **Runtime names.** Under TLC's value or exploration order, strings and
//! model values compare by the order in which they were first encountered.
//! Names interned when the model was bound have the same order as in TLC.
//! If decoding the trace or any check interned a name after that
//! ([`Model::has_runtime_names`]), the validator cannot know where TLC
//! placed it, and the result, valid or invalid, becomes
//! [`RUNTIME_NAMES_UNSUPPORTED`].

use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};

use dive_eval::{AssumptionOutcome, ErrorClass, EvalError, Host, HostError, St, StateRef};
use dive_ir::StdOp;
use dive_model::{Model, Pred};
use dive_value::{Ctx, Value};

use crate::format::Ending;
use crate::trace::Trace;

/// Which check failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Check {
    /// The trace's shape: empty, a variable missing or extra, a value that
    /// does not read.
    Shape,
    /// The claimed length differs from the number of states.
    Length,
    /// An `ASSUME` of the specification does not hold.
    Assumption,
    /// The first state does not satisfy the initial predicate.
    Init,
    /// A step does not satisfy the next-state relation.
    Next,
    /// A step's label names an action that does not hold on it.
    Label,
    /// A state that must be in the model violates a `CONSTRAINT`.
    Constraint,
    /// A step that must be in the model violates an `ACTION_CONSTRAINT`.
    ActionConstraint,
    /// An invariant fails before the end, so the search would have stopped
    /// there (or, at the end, an invariant listed before the claimed one
    /// fails).
    Invariant,
    /// An implied initial predicate fails on the first state.
    ImpliedInit,
    /// An action property fails on a step before the end.
    ImpliedAction,
    /// The claimed ending does not hold: the invariant or property is not
    /// violated, or the model has no such invariant or property.
    Ending,
    /// A temporal conjunct of the behavior specification is false.
    Fairness,
    /// A claimed temporal property holds, or a violated property was omitted.
    Temporal,
}

impl Check {
    /// A stable name for reports.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Shape => "shape",
            Self::Length => "length",
            Self::Assumption => "assumption",
            Self::Init => "init",
            Self::Next => "next",
            Self::Label => "label",
            Self::Constraint => "constraint",
            Self::ActionConstraint => "action-constraint",
            Self::Invariant => "invariant",
            Self::ImpliedInit => "implied-init",
            Self::ImpliedAction => "implied-action",
            Self::Ending => "ending",
            Self::Fairness => "fairness",
            Self::Temporal => "temporal",
        }
    }
}

/// The first check a trace fails.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failure {
    /// The state (0-based) the check is about; for a step, the state it
    /// leads to.
    pub state: usize,
    /// The check.
    pub check: Check,
    /// What failed, precisely enough to file as a bug.
    pub detail: String,
}

/// The validator's verdict.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Validation {
    /// Every check passed: the trace is a behavior of the specification and
    /// ends as claimed.
    Valid,
    /// A check failed.
    Invalid(Failure),
    /// Every check that could be made passed, but part of the claim cannot
    /// be checked independently. The text names it. Never a verdict.
    Unsupported(String),
}

impl Validation {
    /// Whether the trace validated.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        matches!(self, Self::Valid)
    }

    /// `valid`, `invalid` or `unsupported`.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Valid => "valid",
            Self::Invalid(_) => "invalid",
            Self::Unsupported(_) => "unsupported",
        }
    }
}

/// The verdict with what the validator noticed along the way.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Report {
    /// The verdict.
    pub validation: Validation,
    /// Remarks: labels that could not be checked, how a TLC document was
    /// read. They never change the verdict.
    pub notes: Vec<String>,
    /// The number of states in the trace.
    pub length: usize,
}

/// Actual progress before cooperative validation interruption.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidationProgress {
    /// Completed checks in this validation invocation, not exploration work.
    pub checks_passed: u64,
    /// Zero-based supplied state position, when known.
    pub state: Option<usize>,
    /// The check that was interrupted, when known.
    pub check: Option<Check>,
}

/// A controlled validation did not produce a validation report.
///
/// The driver interprets the opaque evaluator interruption. This crate knows
/// neither resource budgets nor the authority that requested interruption.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValidationRunError {
    /// A typed host interruption, never an invalid or unsupported trace.
    Interrupted {
        /// Original evaluator transport, retaining its opaque owner identity.
        error: EvalError,
        /// Actual progress in this invocation.
        progress: ValidationProgress,
    },
    /// Allocation or evaluator resource exhaustion; no validation verdict exists.
    ResourceLimit {
        /// Original resource error, not a semantic capability refusal.
        error: EvalError,
        /// Actual progress before validation could not complete.
        progress: ValidationProgress,
    },
    /// An internal evaluator failure aborted validation, rather than refuting it.
    EvaluationFailure {
        /// Original internal evaluator error.
        error: EvalError,
        /// Work completed before the failure.
        progress: ValidationProgress,
    },
    /// The fresh source binder reported an intrinsic internal binding failure.
    BindingFailure {
        /// Original typed binding error; never parsed from its display text.
        error: dive_model::BindError,
        /// Progress before a private runtime could be constructed.
        progress: ValidationProgress,
    },
    /// The isolated validation thread could not run or did not return.
    ThreadFailure(String),
    /// Another thread owns the evaluator's control registration.
    ControlConflict(dive_eval::HostControlConflict),
}

impl std::fmt::Display for ValidationRunError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Interrupted { error, .. }
            | Self::ResourceLimit { error, .. }
            | Self::EvaluationFailure { error, .. } => error.fmt(f),
            Self::BindingFailure { error, .. } => error.fmt(f),
            Self::ThreadFailure(message) => f.write_str(message),
            Self::ControlConflict(error) => error.fmt(f),
        }
    }
}
impl std::error::Error for ValidationRunError {}

/// The reason given for a deadlock ending whose `ENABLED` cannot be decided.
pub const DEADLOCK_UNSUPPORTED: &str = "deadlock: ENABLED of the next-state relation could not be decided on the last state; every other check passed";

/// The reason given when the trace or a check created a name after the
/// model was bound, under an order where names compare by encounter.
pub const RUNTIME_NAMES_UNSUPPORTED: &str = "runtime string encounter order: decoding the trace or checking it created a string or model value that was not interned when the model was bound, and its order relative to other names depends on evaluations outside the trace";

/// The reason given when a check draws a random value.
pub const RANDOM_UNSUPPORTED: &str = "a random draw: the value depends on the checking run's stream position, which only the successor generator determines, so the independent validator cannot check it";

/// The reason given when a check accesses search-dependent TLC registers.
pub const REGISTERS_UNSUPPORTED: &str = "TLCGet/TLCSet registers: their contents depend on evaluations outside the trace, so the independent validator cannot read or write them";

/// Composition outside independent replay's pure, complete, deterministic-tail slice.
pub const COMPOSITION_UNSUPPORTED: &str = "action composition: independent replay requires TLA mode, pure finite complete intermediates and at most one complete tail successor";

/// What stopped a run early.
pub(crate) enum Stop {
    Invalid(Failure),
    Unsupported(String),
    Interrupted {
        error: EvalError,
        state: Option<usize>,
        check: Option<Check>,
    },
    ControlConflict(dive_eval::HostControlConflict),
}

impl Stop {
    fn at(self, state: Option<usize>, check: Check) -> Self {
        match self {
            Self::Interrupted { error, .. } => Self::Interrupted {
                error,
                state,
                check: Some(check),
            },
            other => other,
        }
    }
}

impl From<Stop> for Validation {
    fn from(s: Stop) -> Self {
        match s {
            Stop::Invalid(f) => Self::Invalid(f),
            Stop::Unsupported(u) => Self::Unsupported(u),
            Stop::Interrupted { .. } => Self::Unsupported(
                "the caller interrupted validation; use validate_controlled for typed transport"
                    .into(),
            ),
            Stop::ControlConflict(error) => Self::Unsupported(error.to_string()),
        }
    }
}

/// What the end of the trace must show.
enum Goal {
    Invariant(usize),
    InvariantError(usize, String),
    ImpliedInit(usize),
    ImpliedAction(usize),
    Deadlock,
    Behavior,
    Liveness(&'static str),
    ErrorEnd(&'static str),
    TemporalStateError,
    NextStateError,
}

/// One validation run. `passed` counts the checks passed, in order: the
/// TLC reader uses it to compare interpretations of a lossy document.
enum AssumptionControl {
    Unit,
    Cooperative,
}

/// Which finite operation a trusted caller selected; never read from a document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FiniteScope {
    /// An ordinary checking word: a deadlock has no successor.
    Behavior,
    /// A sampled finite behavior whose every row passed the safety checks.
    Sample,
    /// A simulation deadlock: no successor satisfies the model's constraints.
    SampledDeadlock,
}

pub(crate) struct Run<'a> {
    model: &'a Model,
    host: Arc<TraceHost>,
    /// The host installed before the run, restored after it.
    inner: Option<Arc<dyn Host>>,
    pub(crate) passed: u64,
    pub(crate) notes: BTreeSet<String>,
    private_init: bool,
    pub(crate) init_incomplete: bool,
    endpoint_prepared: bool,
    endpoint_exception: Option<(EvalError, Option<usize>, Check)>,
    control: Option<Arc<dyn dive_eval::HostControl>>,
    /// Finite-mode replay keeps its existing control during ASSUME checks.
    assumption_control: AssumptionControl,
    /// Trusted operation selection, never read from a serialized document.
    finite_scope: FiniteScope,
}

impl<'a> Run<'a> {
    pub(crate) fn new(model: &'a Model) -> Self {
        let inner = model.evaluator.host();
        let host = Arc::new(TraceHost {
            level: AtomicI64::new(0),
            inner: inner.clone(),
            drew: Mutex::new(None),
            any: AtomicBool::new(false),
            registers: AtomicBool::new(false),
            composition: AtomicBool::new(false),
            register_used: AtomicBool::new(false),
            startup: AtomicBool::new(false),
            next_error: AtomicBool::new(false),
            effect: Mutex::new(None),
            private: false,
            run_config: Mutex::new(None),
            cache_domain: next_cache_domain(),
            choices: None,
            predicate_init: AtomicBool::new(false),
            predicate_next: AtomicBool::new(false),
            inputs: None,
        });
        model.evaluator.set_host(host.clone());
        Self {
            model,
            host,
            inner,
            passed: 0,
            notes: BTreeSet::new(),
            private_init: false,
            init_incomplete: false,
            endpoint_prepared: false,
            endpoint_exception: None,
            control: None,
            assumption_control: AssumptionControl::Unit,
            finite_scope: FiniteScope::Behavior,
        }
    }

    pub(crate) fn private(model: &'a Model, host: Arc<TraceHost>, initial: bool) -> Self {
        let inner = model.evaluator.replace_host(Some(host.clone()));
        let notes = if host.inputs.is_some() {
            BTreeSet::from(["External inputs are explicit assumptions. Fresh source replay verifies their ordered use; it does not authenticate past host contents.".into()])
        } else {
            BTreeSet::new()
        };
        Self {
            model,
            host,
            inner,
            passed: 0,
            notes,
            private_init: initial,
            init_incomplete: false,
            endpoint_prepared: false,
            endpoint_exception: None,
            control: None,
            assumption_control: AssumptionControl::Unit,
            finite_scope: FiniteScope::Behavior,
        }
    }

    /// Validates `trace`.
    // Plain document/session callers have a closed result type. Controlled
    // callers bypass this conversion through validate_result, including label,
    // ENABLED/fairness and final refusal handling.
    pub(crate) fn validate(&mut self, trace: &Trace) -> Validation {
        self.validate_result(trace).unwrap_or_else(Validation::from)
    }

    fn validate_result(&mut self, trace: &Trace) -> Result<Validation, Stop> {
        let v = match self.run(trace) {
            Ok(None) => Validation::Valid,
            Ok(Some(why)) => Validation::Unsupported(why),
            Err(stop @ (Stop::Interrupted { .. } | Stop::ControlConflict(_))) => return Err(stop),
            Err(stop) => stop.into(),
        };
        let v = self.refusal().map_or(v, Validation::Unsupported);
        if v == Validation::Valid {
            self.poll(None, None)?;
        }
        Ok(v)
    }

    fn poll(&self, state: Option<usize>, check: Option<Check>) -> Result<(), Stop> {
        if let Some(control) = &self.control {
            control.check().map_err(|interrupted| Stop::Interrupted {
                error: EvalError::interrupted(interrupted),
                state,
                check,
            })?;
        }
        Ok(())
    }

    /// Why the run's verdict cannot stand, whatever it is: a check drew a
    /// random value, accessed registers, or a name was created after binding.
    pub(crate) fn refusal(&self) -> Option<String> {
        if let Some(feature) = self.model.evaluator.external_input_refusal() {
            return Some(feature);
        }
        if self.host.inputs.is_none() && !self.model.evaluator.options().host_access.is_empty() {
            return Some(
                "external inputs require a fresh Session with explicit recorded assumptions".into(),
            );
        }
        if let Some(error) = self
            .host
            .inputs
            .as_ref()
            .and_then(|inputs| inputs.failure())
        {
            return Some(error.message);
        }
        if let Some(reason) = self
            .host
            .choices
            .as_ref()
            .and_then(|choices| choices.refusal())
        {
            return Some(reason);
        }
        if let Some(effect) = self
            .host
            .effect
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
        {
            return Some(effect);
        }
        if self.host.any.load(Ordering::Relaxed) {
            let op = self
                .host
                .drew
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .map_or_else(|| "a random operator".to_owned(), StdOp::qualified_name);
            return Some(format!("{op}: {RANDOM_UNSUPPORTED}"));
        }
        if self.host.registers.load(Ordering::Relaxed) {
            return Some(REGISTERS_UNSUPPORTED.to_owned());
        }
        if self.host.composition.load(Ordering::Relaxed) {
            return Some(COMPOSITION_UNSUPPORTED.to_owned());
        }
        self.model
            .has_runtime_names()
            .then(|| RUNTIME_NAMES_UNSUPPORTED.to_owned())
    }

    #[allow(
        clippy::too_many_lines,
        reason = "every trace check, in the order the search makes them"
    )]
    fn run(&mut self, trace: &Trace) -> Result<Option<String>, Stop> {
        self.poll(None, None)?;
        let m = self.model;
        if matches!(
            trace.ending,
            Ending::TemporalStateError { .. }
                | Ending::TemporalSourceError { .. }
                | Ending::NextStateError { .. }
                | Ending::ViewSourceError { .. }
                | Ending::CandidateStateError { .. }
                | Ending::PartialNext { .. }
                | Ending::PartialInit { .. }
        ) && (!self.host.private || !self.endpoint_prepared)
        {
            return Err(Stop::Unsupported(
                "temporal error endpoint requires a privately reconstructed source session".into(),
            ));
        }
        let n = trace.states.len();
        if n == 0 {
            return Err(invalid(0, Check::Shape, "the trace has no states"));
        }
        if trace.labels.len() != n {
            return Err(invalid(
                0,
                Check::Shape,
                "the trace has a label list of the wrong length",
            ));
        }
        if let Some(len) = trace.length
            && len != n
        {
            return Err(invalid(
                n - 1,
                Check::Length,
                format!("the trace claims {len} states but has {n}"),
            ));
        }
        let vars = m.ir.vars().len();
        for (k, s) in trace.states.iter().enumerate() {
            if k.is_multiple_of(1024) {
                self.poll(Some(k), Some(Check::Shape))?;
            }
            if s.len() != vars || s.iter().any(Option::is_none) {
                return Err(invalid(
                    k,
                    Check::Shape,
                    "the state does not assign every variable",
                ));
            }
            crate::trace::validate_state_names(m, s).map_err(Stop::Unsupported)?;
        }
        let named_lasso = !trace.properties.is_empty();
        if named_lasso {
            self.host.startup.store(false, Ordering::Relaxed);
            self.prepare_periodic(&trace.ending, &trace.properties)?;
            self.host
                .startup
                .store(self.private_init, Ordering::Relaxed);
        }
        self.assumptions()?;
        if self.private_init {
            self.host
                .startup
                .store(self.private_init, Ordering::Relaxed);
        }
        // The candidate endpoint separately regenerates the final row on a
        // fresh terminal runtime. Ordinary checks apply to its source prefix;
        // shape/name/length checks above still cover the entire supplied word.
        let last = if matches!(trace.ending, Ending::CandidateStateError { .. }) {
            n.checked_sub(2).ok_or_else(|| {
                invalid(
                    0,
                    Check::Shape,
                    "candidate error requires a complete source prefix and terminal row",
                )
            })?
        } else {
            n - 1
        };
        let goal = self.goal(&trace.ending, last)?;
        let terminal_before_exclusion = matches!(
            goal,
            Goal::Invariant(_)
                | Goal::InvariantError(..)
                | Goal::ImpliedInit(_)
                | Goal::ImpliedAction(_)
        );
        let behavior =
            matches!(goal, Goal::Behavior) && matches!(self.finite_scope, FiniteScope::Behavior);
        for k in 0..=last {
            if k.is_multiple_of(1024) {
                self.poll(Some(k), None)?;
            }
            if let Some(choices) = &self.host.choices {
                choices.prefer(&trace.states[k]);
            }
            let here = St::state(trace.states[k].clone());
            let step =
                (k > 0).then(|| St::action(trace.states[k - 1].clone(), trace.states[k].clone()));
            match &step {
                None => {
                    // Init uses startup level 0; generated-state predicates
                    // keep the separate Clear context in `here` (level 1).
                    if self.private_init {
                        // Ordered source construction and finite native choices
                        // cannot share startup register authority. The existing
                        // direct scalar domain-membership proof remains a fast path.
                        self.host.startup.store(false, Ordering::Relaxed);
                        let operation = if self.host.register_used.load(Ordering::Relaxed) {
                            self.host.startup.store(true, Ordering::Relaxed);
                            crate::initial::check(m, &trace.states[0], self.control.as_deref())
                        } else {
                            match crate::initial::random_check(m, &trace.states[0]) {
                                Ok(Some(member)) => Ok(Some(member)),
                                Ok(None) => crate::initial::check(
                                    m,
                                    &trace.states[0],
                                    self.control.as_deref(),
                                ),
                                Err(error) => Err(error),
                            }
                        };
                        let member = match operation {
                            Ok(Some(member)) => member,
                            Ok(None) => {
                                self.init_incomplete = !self
                                    .host
                                    .choices
                                    .as_ref()
                                    .is_some_and(|choices| choices.drew());
                                let error = EvalError::unsupported(crate::initial::UNSUPPORTED);
                                return Err(self.evaluation_refusal(&error, Some(0), Check::Init));
                            }
                            Err(error) => {
                                if error.class() == ErrorClass::Eval {
                                    return Err(Stop::Unsupported(format!(
                                        "independent Init source evaluation fails: {error}"
                                    )));
                                }
                                return Err(self.evaluation_refusal(&error, Some(0), Check::Init));
                            }
                        };
                        if !member {
                            return Err(invalid(
                                0,
                                Check::Init,
                                "the first state is outside the independent Init relation",
                            ));
                        }
                        self.passed += 1;
                    } else {
                        self.host.predicate_init.store(true, Ordering::Relaxed);
                        let initial = St::initial(trace.states[0].clone());
                        for init in &m.init {
                            self.require(&init.pred, &initial, 0, Check::Init, || {
                                format!(
                                    "the initial predicate {} is false in the first state",
                                    m.location(&init.pred)
                                )
                            })?;
                        }
                    }
                    self.host.startup.store(false, Ordering::Relaxed);
                    self.host.predicate_init.store(false, Ordering::Relaxed);
                }
                Some(step) => {
                    if !(named_lasso && trace.states[k - 1] == trace.states[k]) {
                        // Otherwise the implicit full-state stuttering closure.
                        self.next(step, k, "the step into this state")?;
                    }
                    if let Some(label) = &trace.labels[k] {
                        self.label(&label.name, step, k)?;
                    }
                }
            }
            if behavior {
                continue;
            }
            let is_last = k == last;
            let constrained_step = step
                .as_ref()
                .filter(|_| !(named_lasso && trace.states[k - 1] == trace.states[k]));
            self.constraints(
                &here,
                constrained_step,
                k,
                is_last && terminal_before_exclusion,
            )?;
            match (&goal, is_last) {
                (Goal::Invariant(i), true) => {
                    self.claimed(&m.invariants, *i, &here, k, Check::Invariant, "invariant")?;
                }
                (Goal::InvariantError(i, ec), true) => {
                    self.invariant_error(*i, ec, &here, k)?;
                    // An invariant evaluation error decides before implied
                    // properties or later invariants are checked.
                    return Ok(None);
                }
                _ => {
                    for inv in &m.invariants {
                        self.require(&inv.pred, &here, k, Check::Invariant, || {
                            format!("invariant {} is false here, so the search would have stopped at this state", inv.name)
                        })?;
                    }
                }
            }
            match (&goal, &step, is_last) {
                (Goal::Invariant(_), _, true) => {}
                (Goal::ImpliedInit(i), None, _) => {
                    self.claimed(
                        &m.implied_inits,
                        *i,
                        &here,
                        k,
                        Check::ImpliedInit,
                        "property",
                    )?;
                }
                (Goal::ImpliedAction(i), Some(step), true) => {
                    self.claimed(
                        &m.implied_actions,
                        *i,
                        step,
                        k,
                        Check::ImpliedAction,
                        "property",
                    )?;
                }
                (_, None, _) => {
                    for p in &m.implied_inits {
                        self.require(&p.pred, &here, k, Check::ImpliedInit, || {
                            format!("property {} is false in the first state", p.name)
                        })?;
                    }
                }
                (_, Some(step), _) => {
                    for p in &m.implied_actions {
                        self.require(&p.pred, step, k, Check::ImpliedAction, || {
                            format!("action property {} is false on this step, so the search would have stopped here", p.name)
                        })?;
                    }
                }
            }
        }
        if named_lasso {
            self.periodic_end(trace)?;
            return Ok(None);
        }
        if let Ending::Lasso { back_to } = trace.ending {
            if m.view.is_some() {
                // TLC closes the loop on the VIEW's value, not the state's:
                // the last state's successor only has the same view as the
                // state it loops to (Examples' MCDistributedReplicatedLog).
                self.notes.insert("VIEW: TLC's loop closes on the view, not the state; the loop step is not checked".to_owned());
            } else {
                let step = St::action(trace.states[last].clone(), trace.states[back_to].clone());
                let what = format!(
                    "the loop from the last state back to state {} (numbered from 1)",
                    back_to + 1
                );
                self.next(&step, last, &what)?;
            }
        }
        Ok(match goal {
            Goal::Deadlock
                if self.finite_scope == FiniteScope::SampledDeadlock
                    && !(m.constraints.is_empty() && m.action_constraints.is_empty()) =>
            {
                return self.sampled_deadlock(&trace.states[last], last);
            }
            Goal::Deadlock => {
                if let Some(next) = &m.next {
                    match crate::enabled::enabled(m, next, None, &trace.states[last]) {
                        Ok(false) => None,
                        Ok(true) => {
                            return Err(invalid(
                                last,
                                Check::Ending,
                                "the claimed deadlock has a successor",
                            ));
                        }
                        Err(e) => {
                            if let crate::enabled::EnabledError::Interrupted(error) = e {
                                return Err(refused(&error).at(Some(last), Check::Ending));
                            }
                            self.notes.insert(e.to_string());
                            Some(DEADLOCK_UNSUPPORTED.to_owned())
                        }
                    }
                } else {
                    Some(DEADLOCK_UNSUPPORTED.to_owned())
                }
            }
            // The fallible entrypoint separately reconstructs the program
            // before this path validation and replays it afterward.
            Goal::TemporalStateError
            | Goal::Invariant(_)
            | Goal::InvariantError(..)
            | Goal::ImpliedInit(_)
            | Goal::ImpliedAction(_)
            | Goal::Behavior
            | Goal::NextStateError => None,
            Goal::Liveness(why) | Goal::ErrorEnd(why) => Some(why.to_owned()),
        })
    }

    pub(crate) fn prepare_periodic(
        &mut self,
        ending: &Ending,
        properties: &[String],
    ) -> Result<(), Stop> {
        if !matches!(ending, Ending::Lasso { .. } | Ending::Stuttering) {
            return Err(invalid(
                0,
                Check::Ending,
                "temporal property names require a periodic ending",
            ));
        }
        if self.model.view.is_some()
            || self.model.symmetry_reduction.is_some()
            || (self.model.symmetry.is_some() && !self.model.unreduced_symmetry_liveness())
        {
            return Err(Stop::Unsupported(
                "periodic validation under VIEW or SYMMETRY needs concrete closing-state evidence"
                    .into(),
            ));
        }
        let mut names = BTreeSet::new();
        let mut declared = BTreeSet::new();
        if self
            .model
            .property_claims()
            .iter()
            .any(|p| !declared.insert(&p.name))
        {
            return Err(Stop::Unsupported(
                "split temporal properties with ambiguous repeated names".into(),
            ));
        }
        let mut previous = None;
        for name in properties {
            if name.is_empty() || !names.insert(name) {
                return Err(invalid(
                    0,
                    Check::Ending,
                    "empty or repeated temporal property name",
                ));
            }
            let Some(index) = self
                .model
                .property_claims()
                .iter()
                .position(|p| p.name == *name)
            else {
                return Err(invalid(
                    0,
                    Check::Ending,
                    format!("the model has no temporal property named `{name}`"),
                ));
            };
            if previous.is_some_and(|prior| index <= prior) {
                return Err(invalid(
                    0,
                    Check::Ending,
                    "temporal property names are not in configured order",
                ));
            }
            previous = Some(index);
        }
        let check = |pred: &Pred| {
            crate::temporal::check_periodic_context(self.model, pred).map_err(|error| match error {
                crate::temporal::TemporalError::Interrupted(error) => refused(&error),
                other => Stop::Unsupported(other.to_string()),
            })
        };
        for init in &self.model.init {
            check(&init.pred)?;
        }
        if let Some(next) = &self.model.next {
            check(next)?;
        }
        for p in self
            .model
            .constraints
            .iter()
            .chain(&self.model.action_constraints)
            .chain(&self.model.invariants)
            .chain(&self.model.implied_inits)
            .chain(&self.model.implied_actions)
        {
            check(&p.pred)?;
        }
        for &d in &self.model.assumptions {
            check(&Pred::new(
                self.model.ir.def(d).body,
                self.model.evaluator.scope(d).map_err(|error| {
                    if error.class() == ErrorClass::Interrupted {
                        refused(&error).at(None, Check::Assumption)
                    } else {
                        Stop::Unsupported(error.to_string())
                    }
                })?,
            ))?;
        }
        Ok(())
    }

    fn periodic_end(&mut self, trace: &Trace) -> Result<(), Stop> {
        let last = trace.states.len() - 1;
        let back = match trace.ending {
            Ending::Lasso { back_to } => back_to,
            Ending::Stuttering => last,
            _ => return Err(Stop::Unsupported("internal nonperiodic ending".into())),
        };
        let stutter = trace.states[last] == trace.states[back];
        let step = St::action(trace.states[last].clone(), trace.states[back].clone());
        if !stutter {
            self.next(&step, last, "the closing step")?;
            for c in &self.model.action_constraints {
                self.require(&c.pred, &step, last, Check::ActionConstraint, || {
                    format!("ACTION_CONSTRAINT {} is false on the closing step", c.name)
                })?;
            }
        }
        for p in &self.model.implied_actions {
            self.require(&p.pred, &step, last, Check::ImpliedAction, || {
                format!("action property {} is false on the closing step", p.name)
            })?;
        }
        for p in &self.model.temporals {
            if !self.temporal_truth(&p.pred, trace, back)? {
                return Err(invalid(
                    0,
                    Check::Fairness,
                    format!(
                        "behavior temporal conjunct {} is false on this word",
                        p.name
                    ),
                ));
            }
            self.passed += 1;
        }
        for p in self.model.property_claims() {
            let holds = self.temporal_truth(&p.pred, trace, back)?;
            let claimed = trace.properties.contains(&p.name);
            if claimed && holds {
                return Err(invalid(
                    0,
                    Check::Temporal,
                    format!("temporal property {} holds on this word", p.name),
                ));
            }
            if !claimed && !holds {
                return Err(invalid(
                    0,
                    Check::Temporal,
                    format!("violated temporal property {} was omitted", p.name),
                ));
            }
            self.passed += 1;
        }
        Ok(())
    }

    fn temporal_truth(&self, pred: &Pred, trace: &Trace, back: usize) -> Result<bool, Stop> {
        use crate::temporal::TemporalError;
        match crate::temporal::evaluate_lasso(self.model, pred, &trace.states, back) {
            Ok(values) => values
                .first()
                .copied()
                .ok_or_else(|| Stop::Unsupported("internal empty temporal truth vector".into())),
            Err(TemporalError::Invalid(detail)) => Err(invalid(0, Check::Temporal, detail)),
            Err(TemporalError::Unsupported(detail)) => Err(Stop::Unsupported(detail)),
            Err(TemporalError::Interrupted(error)) => {
                Err(refused(&error).at(None, Check::Temporal))
            }
        }
    }

    fn goal(&self, ending: &Ending, last: usize) -> Result<Goal, Stop> {
        let m = self.model;
        let find =
            |list: &[dive_model::Named], name: &str| list.iter().position(|n| n.name == name);
        Ok(match ending {
            Ending::Invariant(name) => Goal::Invariant(find(&m.invariants, name).ok_or_else(|| {
                invalid(last, Check::Ending, format!("the model has no invariant named `{name}`"))
            })?),
            Ending::InvariantError { name, ec } => Goal::InvariantError(
                find(&m.invariants, name).ok_or_else(|| {
                    invalid(last, Check::Ending, format!("the model has no invariant named `{name}`"))
                })?,
                ec.clone(),
            ),
            Ending::Property(name) if last == 0 => {
                Goal::ImpliedInit(find(&m.implied_inits, name).ok_or_else(|| {
                    invalid(
                        last,
                        Check::Ending,
                        format!("the model has no implied initial predicate named `{name}`, and a one-state trace cannot violate an action property"),
                    )
                })?)
            }
            Ending::Property(name) => Goal::ImpliedAction(find(&m.implied_actions, name).ok_or_else(|| {
                invalid(last, Check::Ending, format!("the model has no action property named `{name}`"))
            })?),
            Ending::Deadlock => {
                if !m.settings.check_deadlock {
                    return Err(invalid(
                        last,
                        Check::Ending,
                        "the model does not check for deadlock (CHECK_DEADLOCK FALSE or -deadlock)",
                    ));
                }
                Goal::Deadlock
            }
            Ending::Behavior => Goal::Behavior,
            Ending::TemporalStateError { .. } => Goal::TemporalStateError,
            Ending::NextStateError { .. } | Ending::TemporalSourceError { .. }
                | Ending::ViewSourceError { .. }
                    | Ending::CandidateStateError { .. } | Ending::PartialNext { .. } | Ending::PartialInit { .. } => Goal::NextStateError,
            Ending::Lasso { back_to } => {
                if *back_to > last {
                    return Err(invalid(last, Check::Shape, format!("the lasso loops back to state {back_to}, past the end")));
                }
                Goal::Liveness("liveness: the steps and the loop back (unless noted) were checked, but named temporal-property claims are missing")
            }
            Ending::Stuttering => Goal::Liveness("liveness: the steps were checked, but named temporal-property claims are missing"),
            Ending::Assertion | Ending::Error { .. } => Goal::ErrorEnd("an error while expanding the last state: the steps were checked, but re-raising the error needs the successor generator, which the independent validator does not have"),
        })
    }

    fn assumptions(&mut self) -> Result<(), Stop> {
        // Binding and ASSUME remain explicit uninterruptible units. This
        // thread-owned frame restores control on every return/unwind without
        // disabling another evaluator or any worker's installed capability.
        let _assumptions = if self.control.is_some()
            && !self.endpoint_prepared
            && matches!(self.assumption_control, AssumptionControl::Unit)
        {
            Some(
                self.model
                    .evaluator
                    .host_control(None)
                    .map_err(Stop::ControlConflict)?,
            )
        } else {
            None
        };
        match self.model.check_assumptions() {
            AssumptionOutcome::AllTrue => {
                self.passed += 1;
                Ok(())
            }
            AssumptionOutcome::False { message, .. } => Err(invalid(0, Check::Assumption, message)),
            AssumptionOutcome::Error { error, message, .. } => match error.class() {
                ErrorClass::Eval => Err(invalid(0, Check::Assumption, message)),
                _ => Err(self.evaluation_refusal(&error, None, Check::Assumption)),
            },
        }
    }

    fn next(&mut self, step: &St, k: usize, what: &str) -> Result<(), Stop> {
        let m = self.model;
        let Some(next) = &m.next else {
            return Err(invalid(
                k,
                Check::Next,
                "the model has no next-state relation, so a trace has one state",
            ));
        };
        if let Some(choices) = &self.host.choices
            && m.ir
                .node(next.expr)
                .effects
                .intersects(dive_ir::Effects::IMPURE.union(dive_ir::Effects::OPEN))
        {
            let (StateRef::Vals(source), StateRef::Vals(target)) = (&step.s0, &step.s1) else {
                return Err(Stop::Unsupported(
                    "independent random Next needs complete source/target rows".into(),
                ));
            };
            self.host
                .level
                .store(i64::try_from(k).unwrap_or(i64::MAX), Ordering::Relaxed);
            match crate::initial::next(m, source, target, choices) {
                Ok(Some(true)) => {
                    self.passed += 1;
                    return Ok(());
                }
                Ok(Some(false)) => {
                    return Err(invalid(
                        k,
                        Check::Next,
                        "the step is outside the independent ordered Next relation",
                    ));
                }
                Ok(None) => {}
                Err(error) => return Err(self.evaluation_refusal(&error, Some(k), Check::Next)),
            }
        }
        // Structural decline happens before evaluation. This older predicate
        // path may retain different action LET/argument caches, so it may not
        // grant random support after the independent operation declined.
        self.host.predicate_next.store(true, Ordering::Relaxed);
        let result = self.require(next, step, k, Check::Next, || {
            format!(
                "{what} does not satisfy the next-state relation {}",
                m.location(next)
            )
        });
        self.host.predicate_next.store(false, Ordering::Relaxed);
        result
    }

    /// The label's definition must hold on the step, if it can be checked.
    /// TLC labels a step with the definition its action was split from, and
    /// that action implies the definition's body.
    fn label(&mut self, name: &str, step: &St, k: usize) -> Result<(), Stop> {
        let m = self.model;
        let ev = &m.evaluator;
        let Some(d) = m.ir.root_def(name) else {
            self.notes.insert(format!(
                "label `{name}` names no definition of the root module; not checked"
            ));
            return Ok(());
        };
        let d = ev.redirected(d);
        if !m.ir.def(d).params.is_empty() || ev.is_value_override(d) {
            self.notes.insert(format!(
                "label `{name}` names an operator with parameters; not checked"
            ));
            return Ok(());
        }
        let r = ev.eval_def(d, step);
        match r {
            Ok(Value::Bool(true)) => {
                self.passed += 1;
                Ok(())
            }
            Ok(Value::Bool(false)) => Err(invalid(
                k,
                Check::Label,
                format!("the step is labelled `{name}`, but `{name}` is false on it"),
            )),
            Err(error)
                if matches!(error.class(), ErrorClass::ResourceLimit | ErrorClass::Bug)
                    && self.endpoint_prepared =>
            {
                Err(self.evaluation_refusal(&error, Some(k), Check::Label))
            }
            Err(error) if error.class() == ErrorClass::Interrupted => {
                Err(refused(&error).at(Some(k), Check::Label))
            }
            _ => {
                self.notes.insert(format!(
                    "label `{name}` could not be evaluated on its own; not checked"
                ));
                Ok(())
            }
        }
    }

    /// The claimed invariant or property: those listed before it hold, it
    /// does not.
    fn claimed(
        &mut self,
        list: &[dive_model::Named],
        i: usize,
        st: &St,
        k: usize,
        check: Check,
        what: &str,
    ) -> Result<(), Stop> {
        for earlier in &list[..i] {
            self.require(&earlier.pred, st, k, check, || {
                format!("{what} {} is also false here and comes first in the configuration, so it would be reported instead of {}", earlier.name, list[i].name)
            })?;
        }
        let p = &list[i];
        if self.holds(&p.pred, st, k, check)? {
            return Err(invalid(
                k,
                Check::Ending,
                format!(
                    "{what} {} holds at the end of the trace, so the trace does not violate it",
                    p.name
                ),
            ));
        }
        self.passed += 1;
        Ok(())
    }

    fn require(
        &mut self,
        pred: &Pred,
        st: &St,
        k: usize,
        check: Check,
        detail: impl FnOnce() -> String,
    ) -> Result<(), Stop> {
        if self.holds(pred, st, k, check)? {
            self.passed += 1;
            Ok(())
        } else {
            Err(invalid(k, check, detail()))
        }
    }

    /// The named final invariant raises the claimed underlying error. All
    /// earlier invariants still have to hold, in configuration order.
    fn invariant_error(&mut self, i: usize, ec: &str, st: &St, k: usize) -> Result<(), Stop> {
        let m = self.model;
        for earlier in &m.invariants[..i] {
            self.require(&earlier.pred, st, k, Check::Invariant, || {
                format!(
                    "invariant {} comes before {}, so it would decide first",
                    earlier.name, m.invariants[i].name
                )
            })?;
        }
        let named = &m.invariants[i];
        self.host
            .level
            .store(i64::try_from(k + 1).unwrap_or(i64::MAX), Ordering::Relaxed);
        let actual = match m.eval(&named.pred, st) {
            Err(error) if error.class() == ErrorClass::Eval => error.ec(),
            Err(error) => return Err(self.evaluation_refusal(&error, Some(k), Check::Invariant)),
            // Checking an invariant requires a boolean, so a non-boolean
            // result independently establishes TLC_EXPECTED_VALUE.
            Ok(value) if !matches!(value, Value::Bool(_)) => dive_eval::Ec::ExpectedValue,
            Ok(_) => {
                return Err(invalid(
                    k,
                    Check::Ending,
                    format!(
                        "invariant {} does not raise the claimed evaluation error",
                        named.name
                    ),
                ));
            }
        };
        if actual.name() != ec {
            return Err(invalid(
                k,
                Check::Ending,
                format!(
                    "invariant {} raises {}, not the claimed {ec}",
                    named.name,
                    actual.name()
                ),
            ));
        }
        self.passed += 1;
        Ok(())
    }

    // TLC first evaluates model constraints, stopping at their first false
    // result, then still checks invariants and implied properties on an excluded
    // candidate. A false constraint is admissible only for the last state of a
    // named, independently checked safety ending. An error while evaluating a
    // constraint decides earlier and must never be skipped, even for invariants.
    fn constraints(
        &mut self,
        here: &St,
        step: Option<&St>,
        state: usize,
        allow_excluded: bool,
    ) -> Result<(), Stop> {
        for constraint in &self.model.constraints {
            if !self.holds(&constraint.pred, here, state, Check::Constraint)? {
                return if allow_excluded {
                    Ok(())
                } else {
                    Err(invalid(
                        state,
                        Check::Constraint,
                        format!(
                            "CONSTRAINT {} is false; only a checked terminal invariant or property may lie outside the model",
                            constraint.name,
                        ),
                    ))
                };
            }
        }
        if let Some(step) = step {
            for constraint in &self.model.action_constraints {
                if !self.holds(&constraint.pred, step, state, Check::ActionConstraint)? {
                    return if allow_excluded {
                        Ok(())
                    } else {
                        Err(invalid(
                            state,
                            Check::ActionConstraint,
                            format!(
                                "ACTION_CONSTRAINT {} is false; only a checked terminal invariant or property may lie outside the model",
                                constraint.name,
                            ),
                        ))
                    };
                }
            }
        }
        Ok(())
    }

    /// A simulation deadlock. TLC's simulator keeps only the successors that
    /// satisfy every `CONSTRAINT` and then every `ACTION_CONSTRAINT`, stopping
    /// at the first false one (`SimulationWorker.addElement`, `isInModel` and
    /// `isInActions`), and reports a deadlock when none is kept. Every
    /// successor of the last state is regenerated here; the claim stands only
    /// if each one falls outside the model. Constraints see the successor's
    /// level, action constraints and generation the last state's.
    fn sampled_deadlock(
        &mut self,
        state: &crate::State,
        last: usize,
    ) -> Result<Option<String>, Stop> {
        let m = self.model;
        if m.next.is_none() || m.actions.is_empty() {
            return Ok(Some(DEADLOCK_UNSUPPORTED.to_owned()));
        }
        let source_level = last.saturating_add(1);
        let mut ordinal = 0u64;
        for action in &m.actions {
            self.poll(Some(last), Some(Check::Ending))?;
            let host = &self.host;
            host.set_replay_level(source_level);
            let mut found = None;
            let mut sink = |candidate: &dive_eval::next::Successor<'_>| {
                if !candidate.complete() {
                    found = Some(Found::Incomplete);
                    return dive_eval::next::Flow::Stop;
                }
                let successor: crate::State = candidate.state.iter().cloned().collect();
                let here = St::state(successor.clone());
                let step = St::action(state.clone(), successor);
                let decision = in_model(m, host, &here, &step, source_level);
                // Generation continues at the last state's level.
                host.set_replay_level(source_level);
                match decision {
                    Ok(false) => dive_eval::next::Flow::Continue,
                    Ok(true) => {
                        found = Some(Found::Inside);
                        dive_eval::next::Flow::Stop
                    }
                    Err(other) => {
                        found = Some(other);
                        dive_eval::next::Flow::Stop
                    }
                }
            };
            let outcome = m.evaluator.next_states(action, state, ordinal, &mut sink);
            match found {
                None => {}
                Some(Found::Inside) => {
                    return Err(invalid(
                        last,
                        Check::Ending,
                        "the claimed deadlock has a successor that satisfies every constraint",
                    ));
                }
                Some(Found::Incomplete) => {
                    return Err(invalid(
                        last,
                        Check::Ending,
                        "the claimed deadlock has a successor that does not assign every variable",
                    ));
                }
                Some(Found::NotBoolean(detail)) => {
                    return Err(invalid(last, Check::Ending, detail));
                }
                Some(Found::Error(e)) => {
                    return Err(match e.class() {
                        ErrorClass::Eval => invalid(
                            last,
                            Check::Ending,
                            format!(
                                "evaluating a constraint on a successor of the claimed deadlock fails: {}",
                                e.message()
                            ),
                        ),
                        _ => self.evaluation_refusal(&e, Some(last), Check::Ending),
                    });
                }
            }
            match outcome {
                Ok(o) => ordinal = ordinal.saturating_add(o.emitted),
                Err(e) => {
                    return Err(match e.error.class() {
                        ErrorClass::Eval => invalid(
                            last,
                            Check::Ending,
                            format!(
                                "generating a successor of the claimed deadlock fails: {}",
                                e.error.message()
                            ),
                        ),
                        _ => self.evaluation_refusal(&e.error, Some(last), Check::Ending),
                    });
                }
            }
        }
        if m.has_runtime_names() {
            return Ok(Some(crate::RUNTIME_NAMES_UNSUPPORTED.to_owned()));
        }
        self.notes.insert("Simulation deadlock: every successor of the last state lies outside the model's constraints, so TLC's simulator keeps none".to_owned());
        Ok(None)
    }

    fn evaluation_refusal(
        &mut self,
        error: &EvalError,
        state: Option<usize>,
        check: Check,
    ) -> Stop {
        // Plain finite validation keeps its closed report channel. The
        // fallible endpoint path retains original resource/bug transport separately
        // and intercepts it before constructing any ValidationReport.
        if self.endpoint_prepared
            && matches!(error.class(), ErrorClass::ResourceLimit | ErrorClass::Bug)
        {
            self.endpoint_exception = Some((error.clone(), state, check));
        }
        refused(error).at(state, check)
    }

    fn holds(&mut self, pred: &Pred, st: &St, k: usize, check: Check) -> Result<bool, Stop> {
        let m = self.model;
        // TLC's level of `s0`: state k (numbered from 0) is at level k + 1;
        // a step into state k is evaluated with the state before it as s0.
        let level = if matches!(st.s1, StateRef::Vals(_)) {
            k
        } else {
            k + 1
        };
        self.host
            .level
            .store(i64::try_from(level).unwrap_or(i64::MAX), Ordering::Relaxed);
        match m.eval(pred, st) {
            Ok(Value::Bool(b)) => Ok(b),
            Ok(v) => Err(invalid(
                k,
                check,
                format!(
                    "{} is not a boolean here: {}",
                    m.location(pred),
                    v.kind_name()
                ),
            )),
            Err(e) => match e.class() {
                ErrorClass::Eval => Err(invalid(
                    k,
                    check,
                    format!("evaluating {} fails: {}", m.location(pred), e.message()),
                )),
                _ => Err(self.evaluation_refusal(&e, Some(k), check)),
            },
        }
    }
}

/// What regenerating a claimed simulation deadlock's successors found.
enum Found {
    Inside,
    Incomplete,
    NotBoolean(String),
    Error(EvalError),
}

/// Whether a successor satisfies every `CONSTRAINT` and then every
/// `ACTION_CONSTRAINT`, stopping at the first false one, as TLC's simulator
/// does. `source_level` is the TLC level of the state it succeeds.
fn in_model(
    m: &Model,
    host: &TraceHost,
    here: &St,
    step: &St,
    source_level: usize,
) -> Result<bool, Found> {
    let truth = |pred: &Pred, st: &St| match m.eval(pred, st) {
        Ok(Value::Bool(b)) => Ok(b),
        Ok(v) => Err(Found::NotBoolean(format!(
            "{} is not a boolean on a successor of the claimed deadlock: {}",
            m.location(pred),
            v.kind_name()
        ))),
        Err(e) => Err(Found::Error(e)),
    };
    host.set_replay_level(source_level.saturating_add(1));
    for constraint in &m.constraints {
        if !truth(&constraint.pred, here)? {
            return Ok(false);
        }
    }
    host.set_replay_level(source_level);
    for constraint in &m.action_constraints {
        if !truth(&constraint.pred, step)? {
            return Ok(false);
        }
    }
    Ok(true)
}

fn invalid(state: usize, check: Check, detail: impl Into<String>) -> Stop {
    Stop::Invalid(Failure {
        state,
        check,
        detail: detail.into(),
    })
}

fn refused(e: &EvalError) -> Stop {
    if e.class() == ErrorClass::Interrupted {
        return Stop::Interrupted {
            error: e.clone(),
            state: None,
            check: None,
        };
    }
    Stop::Unsupported(match e.class() {
        ErrorClass::Unsupported => format!("the evaluator refuses: {}", e.message()),
        ErrorClass::ResourceLimit => format!("resource limit: {}", e.message()),
        _ => format!("internal evaluator error (a bug): {e}"),
    })
}

impl Drop for Run<'_> {
    fn drop(&mut self) {
        let _ = self.model.evaluator.replace_host(self.inner.take());
    }
}

/// What the validator provides of a checking run: the level of the state
/// being checked (`TLCGet("level")`, refusing it under a prime) and `TLCGet("config")` from the host the
/// model was bound with, if any. Registers and live counters depend on
/// evaluations outside the trace, so they are refused by name. Register
/// access and unproved random draws are remembered so the whole verdict is
/// refused, including when an optional label check swallowed an error. Fresh
/// finite sessions may instead install a bounded source-choice search.
#[derive(Debug)]
pub(crate) struct TraceHost {
    inputs: Option<Arc<dive_eval::inputs::InputReplay>>,
    level: AtomicI64,
    inner: Option<Arc<dyn Host>>,
    /// The first operator that drew.
    drew: Mutex<Option<StdOp>>,
    /// Whether any check drew.
    any: AtomicBool,
    /// Whether any check attempted a register read or write.
    pub(crate) registers: AtomicBool,
    /// Whether evaluation reached composition outside the bounded slice.
    composition: AtomicBool,
    pub(crate) register_used: AtomicBool,
    pub(crate) startup: AtomicBool,
    /// The narrow Next lane refuses output effects even during fresh startup.
    pub(crate) next_error: AtomicBool,
    effect: Mutex<Option<String>>,
    private: bool,
    pub(crate) run_config: Mutex<Option<dive_eval::RunConfig>>,
    /// This host's own expression cache domain: replay reuses lazy values it
    /// computed itself, as TLC's `LazyValue` does, but never values another
    /// consumer cached.
    cache_domain: u64,
    pub(crate) choices: Option<Arc<crate::choices::Search>>,
    predicate_init: AtomicBool,
    predicate_next: AtomicBool,
}

/// A cache domain no other replay host has used (0 is ordinary evaluation's).
pub(crate) fn next_cache_domain() -> u64 {
    static NEXT: AtomicU64 = AtomicU64::new(1);
    NEXT.fetch_add(1, Ordering::Relaxed)
}

impl TraceHost {
    #[cfg(test)]
    pub(crate) fn startup() -> Arc<Self> {
        Self::startup_context(None, None)
    }

    pub(crate) fn set_replay_level(&self, level: usize) {
        self.level
            .store(i64::try_from(level).unwrap_or(i64::MAX), Ordering::Relaxed);
    }
    pub(crate) fn startup_context(
        inputs: Option<Arc<dive_eval::inputs::InputReplay>>,
        choices: Option<Arc<crate::choices::Search>>,
    ) -> Arc<Self> {
        Arc::new(Self {
            inputs,
            level: AtomicI64::new(0),
            inner: None,
            drew: Mutex::new(None),
            any: AtomicBool::new(false),
            registers: AtomicBool::new(false),
            composition: AtomicBool::new(false),
            register_used: AtomicBool::new(false),
            startup: AtomicBool::new(true),
            next_error: AtomicBool::new(false),
            effect: Mutex::new(None),
            private: true,
            run_config: Mutex::new(None),
            cache_domain: next_cache_domain(),
            choices,
            predicate_init: AtomicBool::new(false),
            predicate_next: AtomicBool::new(false),
        })
    }

    pub(crate) fn finish_input_binding(&self, model: &Model) -> Result<(), String> {
        if let Some(feature) = model.evaluator.external_input_refusal() {
            return Err(feature);
        }
        self.inputs.as_ref().map_or(Ok(()), |inputs| {
            inputs.finish_binding().map_err(|error| error.message)
        })
    }

    fn private_host(&self) -> bool {
        self.private
    }

    fn refuse_effect(&self, feature: String) -> Result<(), HostError> {
        let mut effect = self.effect.lock().unwrap_or_else(PoisonError::into_inner);
        if effect.is_none() {
            *effect = Some(feature.clone());
        }
        Err(HostError {
            code: 0,
            message: feature,
        })
    }
}

impl Host for TraceHost {
    fn input(
        &self,
        request: &dive_eval::inputs::InputRequest,
    ) -> Option<Result<dive_eval::inputs::InputResponse, HostError>> {
        self.inputs.as_ref().map(|inputs| inputs.request(request))
    }

    fn check_random_in_enabled(&self) -> Result<(), HostError> {
        self.refuse_effect(
            "RandomElement/Randomization inside ENABLED is unsupported in independent replay"
                .into(),
        )
    }

    fn check_native_access(&self, op: StdOp) -> Result<(), HostError> {
        if self.inputs.is_some() && matches!(op, StdOp::IoUtilsIOEnv | StdOp::IoUtilsDeserialize) {
            return Ok(());
        }
        if op == StdOp::TlcRandomElement
            && let Some(choices) = &self.choices
        {
            if self.register_used.load(Ordering::Relaxed)
                || self.predicate_init.load(Ordering::Relaxed)
                || self.predicate_next.load(Ordering::Relaxed)
            {
                return Err(choices.refuse(
                    "random choice requires supported ordered Init/Next and a register-free replay prefix",
                ));
            }

            return Ok(());
        }
        if self.private_host()
            && matches!(
                op,
                StdOp::TlcRandomElement
                    | StdOp::RandomizationRandomSubset
                    | StdOp::RandomizationRandomSetOfSubsets
                    | StdOp::RandomizationRandomSubsetSet
            )
        {
            if !self.any.swap(true, Ordering::Relaxed) {
                *self.drew.lock().unwrap_or_else(PoisonError::into_inner) = Some(op);
            }
            return Err(HostError {
                code: 0,
                message: format!("{}: {RANDOM_UNSUPPORTED}", op.qualified_name()),
            });
        }
        if self.private_host()
            && op.impure()
            && !matches!(
                op,
                StdOp::TlcTLCGet | StdOp::TlcTLCSet | StdOp::TlcPrint | StdOp::TlcPrintT
            )
        {
            return self.refuse_effect(format!(
                "{}: private trace startup does not support this host effect",
                op.qualified_name()
            ));
        }
        Ok(())
    }

    fn print_output(&self, _text: &str) -> Result<bool, HostError> {
        if self.next_error.load(Ordering::Relaxed) {
            self.refuse_effect("Print/PrintT in Next error reconstruction".into())?;
        }
        // Reconstruct Print's value semantics without invoking any sink or
        // counting replay/startup reconstruction as producer output. The
        // evaluator still checks arguments and performs normal rendering.
        Ok(false)
    }

    fn check_tlc_access(&self, key: &str, write: bool) -> Result<(), HostError> {
        if self.private_host()
            && !(key.starts_with("s:")
                || !write && matches!(key, "config" | "level" | "all" | "all:named"))
        {
            return self.refuse_effect(format!(
                "TLC{}({key:?}): private trace startup does not support this host effect",
                if write { "Set" } else { "Get" }
            ));
        }
        Ok(())
    }
    fn check_register_access(&self) -> Result<(), HostError> {
        if let Some(choices) = &self.choices
            && choices.drew()
        {
            self.registers.store(true, Ordering::Relaxed);
            return Err(choices.refuse(REGISTERS_UNSUPPORTED));
        }
        self.register_used.store(true, Ordering::Relaxed);
        if self.startup.load(Ordering::Relaxed) {
            return Ok(());
        }
        self.registers.store(true, Ordering::Relaxed);
        Err(HostError {
            code: 0,
            message: REGISTERS_UNSUPPORTED.to_owned(),
        })
    }

    fn check_action_composition(&self) -> Result<(), HostError> {
        self.composition.store(true, Ordering::Relaxed);
        Err(HostError {
            code: 0,
            message: COMPOSITION_UNSUPPORTED.to_owned(),
        })
    }

    fn requires_bounded_action_composition(&self) -> bool {
        true
    }

    fn check_bounded_action_composition(&self) -> Result<(), HostError> {
        let result = self
            .inner
            .as_ref()
            .map_or(Ok(()), |host| host.check_bounded_action_composition());
        if result.is_err() {
            self.composition.store(true, Ordering::Relaxed);
        }
        result
    }

    fn expression_cache_domain(&self) -> u64 {
        self.cache_domain
    }

    fn random(&self, op: StdOp, args: &[Value], ctx: Ctx) -> Option<Result<Value, HostError>> {
        if let Some(choices) = &self.choices {
            return Some(choices.random(op, args, ctx));
        }
        if !self.any.swap(true, Ordering::Relaxed) {
            *self.drew.lock().unwrap_or_else(PoisonError::into_inner) = Some(op);
        }
        None
    }

    fn level(&self) -> Option<i64> {
        Some(self.level.load(Ordering::Relaxed))
    }

    /// Replay tracks only the level of the state being checked, so a primed
    /// `TLCGet("level")` (the successor's level in TLC) refuses the whole
    /// verdict, even where a label check swallowed the error.
    fn successor_level(&self) -> Result<i64, HostError> {
        self.refuse_effect(dive_eval::PRIMED_LEVEL_UNSUPPORTED.to_owned())
            .map(|()| 0)
    }

    fn config(&self) -> Option<dive_eval::RunConfig> {
        self.run_config
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
            .or_else(|| self.inner.as_ref().and_then(|h| h.config()))
    }
}

/// Validates a trace already read against `model`. Random draws are refused
/// by name ([`RANDOM_UNSUPPORTED`]).
#[must_use]
pub fn validate(model: &Model, trace: &Trace) -> Report {
    let admitted = model.validate_context().and_then(|()| {
        for &def in &model.assumptions {
            model.evaluator.scope(def)?;
        }
        Ok(())
    });
    if let Err(error) = admitted {
        return Report {
            validation: Validation::Unsupported(error.to_string()),
            notes: Vec::new(),
            length: trace.logical_length(),
        };
    }
    let mut run = Run::new(model);
    let validation = run.validate(trace);
    Report {
        validation,
        notes: std::mem::take(&mut run.notes).into_iter().collect(),
        length: trace.logical_length(),
    }
}

/// Validates supplied states with a generic cooperative host capability.
///
/// Interruption is returned outside [`Validation`]: it is neither an invalid
/// trace nor an unsupported feature. Only the owning driver can interpret its
/// opaque identity. Binding, `ASSUME`, quiet value units and pure bulk/native
/// work retain their interruption limitations. Supplied deferred values may
/// retain a different evaluator, whose work this control does not govern.
/// This does not control TLC JSON
/// interpretation or private [`crate::Session`] reconstruction.
///
/// ```
/// # fn run(model: &dive_model::Model, trace: &dive_trace::Trace,
/// #        control: std::sync::Arc<dyn dive_eval::HostControl>)
/// #        -> Result<dive_trace::Report, dive_trace::ValidationRunError> {
/// dive_trace::validate_controlled(model, trace, control)
/// # }
/// ```
///
/// # Errors
/// Typed host interruption with actual validation progress, or a conflicting
/// control registration owned by another thread. Ordinary invalid/unsupported
/// trace reports remain ordinary reports.
pub fn validate_controlled(
    model: &Model,
    trace: &Trace,
    control: Arc<dyn dive_eval::HostControl>,
) -> Result<Report, ValidationRunError> {
    let _scope = model
        .evaluator
        .host_control(Some(control.clone()))
        .map_err(ValidationRunError::ControlConflict)?;
    let admitted = model.validate_context().and_then(|()| {
        for &def in &model.assumptions {
            model.evaluator.scope(def)?;
        }
        Ok(())
    });
    if let Err(error) = admitted {
        if error.class() == ErrorClass::Interrupted {
            return Err(ValidationRunError::Interrupted {
                error,
                progress: ValidationProgress {
                    checks_passed: 0,
                    state: None,
                    check: None,
                },
            });
        }
        return Ok(Report {
            validation: Validation::Unsupported(error.to_string()),
            notes: Vec::new(),
            length: trace.logical_length(),
        });
    }
    let mut run = Run::new(model);
    run.control = Some(control);
    controlled_report(&mut run, trace)
}

#[allow(
    clippy::too_many_lines,
    reason = "finite validation and independent endpoint phases share one fallible report boundary"
)]
fn controlled_report(run: &mut Run<'_>, trace: &Trace) -> Result<Report, ValidationRunError> {
    let endpoint = if matches!(trace.ending, Ending::TemporalStateError { .. }) {
        if !run.host.private {
            return Ok(Report {
                validation: Validation::Unsupported(
                    "temporal error endpoint requires a privately reconstructed source session"
                        .into(),
                ),
                notes: Vec::new(),
                length: trace.logical_length(),
            });
        }
        if !trace.properties.is_empty() {
            return Ok(Report {
                validation: Validation::Invalid(Failure {
                    state: 0,
                    check: Check::Shape,
                    detail: "finite error endpoints cannot claim temporal properties".into(),
                }),
                notes: Vec::new(),
                length: trace.logical_length(),
            });
        }
        match crate::row_demand::prepare(run.model, &trace.states, run.control.as_deref()) {
            Ok(program) => {
                run.endpoint_prepared = true;
                Some(program)
            }
            Err(error) => return endpoint_refusal(run, trace, error, None),
        }
    } else {
        None
    };
    let result = run.validate_result(trace);
    let mut validation = controlled_result(run, result)?;
    if validation == Validation::Valid
        && let Some(program) = endpoint
    {
        let Some(last) = trace.states.len().checked_sub(1) else {
            return Ok(Report {
                validation: Validation::Invalid(Failure {
                    state: 0,
                    check: Check::Shape,
                    detail: "endpoint has no state".into(),
                }),
                notes: Vec::new(),
                length: 0,
            });
        };
        let Ending::TemporalStateError { ec, endpoint } = &trace.ending else {
            return Ok(Report {
                validation: Validation::Unsupported("missing endpoint ending".into()),
                notes: Vec::new(),
                length: trace.logical_length(),
            });
        };
        match program.replay(
            run.model,
            &trace.states[last],
            ec,
            endpoint,
            run.control.as_deref(),
        ) {
            Ok(Ok(())) => {}
            Ok(Err(detail)) => {
                validation = Validation::Invalid(Failure {
                    state: last,
                    check: Check::Ending,
                    detail,
                });
            }
            Err(error) => return endpoint_refusal(run, trace, error, Some(last)),
        }
        if let Some(control) = &run.control {
            control
                .check()
                .map_err(|error| ValidationRunError::Interrupted {
                    error: EvalError::interrupted(error),
                    progress: progress(run, Some(last)),
                })?;
        }
    }
    if let Some(feature) = run.refusal() {
        validation = Validation::Unsupported(feature);
    }
    Ok(Report {
        validation,
        notes: std::mem::take(&mut run.notes).into_iter().collect(),
        length: trace.logical_length(),
    })
}

fn controlled_result(
    run: &mut Run<'_>,
    result: Result<Validation, Stop>,
) -> Result<Validation, ValidationRunError> {
    if let Some((error, state, check)) = run.endpoint_exception.take() {
        let progress = ValidationProgress {
            checks_passed: run.passed,
            state,
            check: Some(check),
        };
        return Err(if error.class() == ErrorClass::ResourceLimit {
            ValidationRunError::ResourceLimit { error, progress }
        } else {
            ValidationRunError::EvaluationFailure { error, progress }
        });
    }
    let validation = match result {
        Ok(validation) => validation,
        Err(Stop::Interrupted {
            error,
            state,
            check,
        }) => {
            return Err(ValidationRunError::Interrupted {
                error,
                progress: ValidationProgress {
                    checks_passed: run.passed,
                    state,
                    check,
                },
            });
        }
        Err(Stop::ControlConflict(error)) => {
            return Err(ValidationRunError::ControlConflict(error));
        }
        Err(other) => other.into(),
    };
    Ok(validation)
}

fn progress(run: &Run<'_>, state: Option<usize>) -> ValidationProgress {
    ValidationProgress {
        checks_passed: run.passed,
        state,
        check: Some(Check::Ending),
    }
}
fn endpoint_refusal(
    run: &Run<'_>,
    trace: &Trace,
    error: crate::row_demand::FormulaError,
    state: Option<usize>,
) -> Result<Report, ValidationRunError> {
    let feature = match error {
        crate::row_demand::FormulaError::Evaluation(error) => match error.class() {
            ErrorClass::Interrupted => {
                return Err(ValidationRunError::Interrupted {
                    error,
                    progress: progress(run, state),
                });
            }
            ErrorClass::ResourceLimit => {
                return Err(ValidationRunError::ResourceLimit {
                    error,
                    progress: progress(run, state),
                });
            }
            ErrorClass::Bug => {
                return Err(ValidationRunError::EvaluationFailure {
                    error,
                    progress: progress(run, state),
                });
            }
            _ => error.to_string(),
        },
        other => other.to_string(),
    };
    Ok(Report {
        validation: Validation::Unsupported(feature),
        notes: Vec::new(),
        length: trace.logical_length(),
    })
}

pub(crate) fn validate_private_controlled(
    model: &Model,
    host: Arc<TraceHost>,
    trace: &Trace,
    control: Option<Arc<dyn dive_eval::HostControl>>,
) -> Result<Report, ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|control| model.evaluator.host_control(Some(control.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host, false);
    run.control = control;
    controlled_report(&mut run, trace)
}

pub(crate) fn validate_finite_private_controlled(
    model: &Model,
    host: &Arc<TraceHost>,
    trace: &Trace,
    initial: bool,
    control: Option<Arc<dyn dive_eval::HostControl>>,
    scope: FiniteScope,
) -> Result<(Report, bool), ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|control| model.evaluator.host_control(Some(control.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host.clone(), initial);
    run.control = control;
    run.assumption_control = AssumptionControl::Cooperative;
    run.finite_scope = scope;
    let report = controlled_report(&mut run, trace)?;
    let retry = initial && run.init_incomplete && !host.register_used.load(Ordering::Relaxed);
    Ok((report, retry))
}

/// Internal prefix result: Session must separately replay the terminal event
/// on another freshly bound runtime before publishing a completed report.
pub(crate) fn validate_next_prefix_controlled(
    model: &Model,
    host: Arc<TraceHost>,
    trace: &Trace,
    control: Option<Arc<dyn dive_eval::HostControl>>,
) -> Result<(Report, u64), ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|control| model.evaluator.host_control(Some(control.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host, false);
    run.control = control;
    run.endpoint_prepared = true;
    let mut report = controlled_report(&mut run, trace)?;
    if report.validation == Validation::Valid
        && matches!(trace.ending, Ending::CandidateStateError { .. })
    {
        let last = trace.states.len() - 1;
        if let Some(label) = &trace.labels[last] {
            run.host.set_replay_level(last);
            let step = St::action(trace.states[last - 1].clone(), trace.states[last].clone());
            let result = run
                .label(&label.name, &step, last)
                .map(|()| Validation::Valid);
            report.validation = controlled_result(&mut run, result)?;
            report.notes.extend(std::mem::take(&mut run.notes));
        }
        report.length = trace.logical_length();
    }
    Ok((report, run.passed))
}

#[allow(
    clippy::too_many_lines,
    reason = "one typed control boundary dispatches independently replayed terminal sites"
)]
pub(crate) fn replay_next_controlled(
    model: &Model,
    host: Arc<TraceHost>,
    trace: &Trace,
    state: &crate::State,
    checks_passed: u64,
    control: Option<Arc<dyn dive_eval::HostControl>>,
) -> Result<Report, ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|control| model.evaluator.host_control(Some(control.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host, false);
    run.control = control;
    run.passed = checks_passed;
    let Some(last) = trace.states.len().checked_sub(1) else {
        return Ok(Report {
            validation: Validation::Invalid(Failure {
                state: 0,
                check: Check::Shape,
                detail: "Next endpoint has no state".into(),
            }),
            notes: Vec::new(),
            length: 0,
        });
    };
    run.poll(Some(last), Some(Check::Ending))
        .map_err(|stop| match stop {
            Stop::Interrupted { error, .. } => ValidationRunError::Interrupted {
                error,
                progress: progress(&run, Some(last)),
            },
            _ => ValidationRunError::EvaluationFailure {
                error: EvalError::bug("unexpected terminal replay poll outcome"),
                progress: progress(&run, Some(last)),
            },
        })?;
    run.host.level.store(
        i64::try_from(last.saturating_add(1)).unwrap_or(i64::MAX),
        Ordering::Relaxed,
    );
    let replay = match &trace.ending {
        Ending::ViewSourceError { ec, endpoint } => crate::ordered_prefix::view(
            model,
            trace,
            ec,
            endpoint,
            &run.host,
            run.control.as_deref(),
        ),
        Ending::CandidateStateError { ec, endpoint } => {
            let Some(source) = last
                .checked_sub(1)
                .and_then(|index| trace.states.get(index))
            else {
                return Ok(Report {
                    validation: Validation::Invalid(Failure {
                        state: last,
                        check: Check::Shape,
                        detail: "candidate error has no predecessor".into(),
                    }),
                    notes: Vec::new(),
                    length: trace.logical_length(),
                });
            };
            crate::candidate_error::replay(
                model,
                source,
                state,
                last,
                ec,
                endpoint,
                &run.host,
                run.control.as_deref(),
            )
        }
        Ending::TemporalSourceError { ec, endpoint } => crate::source_row::replay(
            model,
            state,
            last,
            ec,
            endpoint,
            &run.host,
            run.control.as_deref(),
        ),
        Ending::NextStateError { ec, endpoint } => crate::next_error::replay(
            model,
            state,
            last,
            ec,
            endpoint,
            &run.host,
            run.control.as_deref(),
        ),
        _ => Ok(Validation::Unsupported(
            "missing source terminal endpoint".into(),
        )),
    };
    let mut validation = replay.map_err(|error| match error.class() {
        ErrorClass::Interrupted => ValidationRunError::Interrupted {
            error,
            progress: progress(&run, Some(last)),
        },
        ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
            error,
            progress: progress(&run, Some(last)),
        },
        _ => ValidationRunError::EvaluationFailure {
            error,
            progress: progress(&run, Some(last)),
        },
    })?;
    if let Some(feature) = run.refusal() {
        validation = Validation::Unsupported(feature);
    }
    Ok(Report {
        validation,
        notes: Vec::new(),
        length: trace.logical_length(),
    })
}

pub(crate) fn replay_partial_controlled(
    model: &Model,
    host: Arc<TraceHost>,
    trace: &Trace,
    endpoint: &crate::PartialNextEndpoint,
    checks_passed: u64,
    control: Option<Arc<dyn dive_eval::HostControl>>,
) -> Result<Report, ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|control| model.evaluator.host_control(Some(control.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host, false);
    run.control = control;
    run.passed = checks_passed;
    let Some(last) = trace.states.len().checked_sub(1) else {
        return Ok(Report {
            validation: Validation::Invalid(Failure {
                state: 0,
                check: Check::Shape,
                detail: "Next endpoint has no state".into(),
            }),
            notes: Vec::new(),
            length: 0,
        });
    };
    run.poll(Some(last), Some(Check::Ending))
        .map_err(|stop| match stop {
            Stop::Interrupted { error, .. } => ValidationRunError::Interrupted {
                error,
                progress: progress(&run, Some(last)),
            },
            _ => ValidationRunError::EvaluationFailure {
                error: EvalError::bug("unexpected terminal replay poll outcome"),
                progress: progress(&run, Some(last)),
            },
        })?;
    run.host.level.store(
        i64::try_from(last.saturating_add(1)).unwrap_or(i64::MAX),
        Ordering::Relaxed,
    );
    let mut validation = crate::partial::replay(
        model,
        &trace.states[last],
        trace.states.len(),
        endpoint,
        &run.host,
        run.control.as_deref(),
    )
    .map_err(|error| match error.class() {
        ErrorClass::Interrupted => ValidationRunError::Interrupted {
            error,
            progress: progress(&run, Some(last)),
        },
        ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
            error,
            progress: progress(&run, Some(last)),
        },
        _ => ValidationRunError::EvaluationFailure {
            error,
            progress: progress(&run, Some(last)),
        },
    })?;
    if let Some(feature) = run.refusal() {
        validation = Validation::Unsupported(feature);
    }
    Ok(Report {
        validation,
        notes: Vec::new(),
        length: trace.states.len().saturating_add(1),
    })
}

pub(crate) fn replay_initial_partial_controlled(
    model: &Model,
    host: Arc<TraceHost>,
    endpoint: &crate::PartialStateEndpoint,
    control: Option<Arc<dyn dive_eval::HostControl>>,
) -> Result<Report, ValidationRunError> {
    let _scope = control
        .as_ref()
        .map(|c| model.evaluator.host_control(Some(c.clone())))
        .transpose()
        .map_err(ValidationRunError::ControlConflict)?;
    let mut run = Run::private(model, host, false);
    run.control = control;
    run.endpoint_prepared = true;
    run.host.set_replay_level(0);
    run.poll(None, Some(Check::Assumption))
        .map_err(|stop| match stop {
            Stop::Interrupted { error, .. } => ValidationRunError::Interrupted {
                error,
                progress: progress(&run, None),
            },
            _ => ValidationRunError::EvaluationFailure {
                error: EvalError::bug("unexpected Init partial control failure"),
                progress: progress(&run, None),
            },
        })?;
    let result = run.assumptions().map(|()| Validation::Valid);
    let mut validation = controlled_result(&mut run, result)?;
    if validation == Validation::Valid {
        let empty = Arc::from([]);
        validation = crate::partial::replay(
            model,
            &empty,
            0,
            endpoint,
            &run.host,
            run.control.as_deref(),
        )
        .map_err(|error| match error.class() {
            ErrorClass::Interrupted => ValidationRunError::Interrupted {
                error,
                progress: progress(&run, None),
            },
            ErrorClass::ResourceLimit => ValidationRunError::ResourceLimit {
                error,
                progress: progress(&run, None),
            },
            _ => ValidationRunError::EvaluationFailure {
                error,
                progress: progress(&run, None),
            },
        })?;
    }
    if let Some(feature) = run.refusal() {
        validation = Validation::Unsupported(feature);
    }
    if let Some(control) = &run.control {
        control
            .check()
            .map_err(|error| ValidationRunError::Interrupted {
                error: EvalError::interrupted(error),
                progress: progress(&run, None),
            })?;
    }
    Ok(Report {
        validation,
        notes: Vec::new(),
        length: 1,
    })
}

/// `report`, refused if a name was created after the model was bound
/// ([`RUNTIME_NAMES_UNSUPPORTED`]).
pub(crate) fn guard_runtime_names(model: &Model, mut report: Report) -> Report {
    if model.has_runtime_names() {
        report.validation = Validation::Unsupported(RUNTIME_NAMES_UNSUPPORTED.to_owned());
    }
    report
}

/// Negative controls: by-construction invalid edits of a valid
/// breadth-first counterexample must be rejected.
#[cfg(test)]
mod negative_controls {
    #![allow(clippy::expect_used, clippy::panic, reason = "test assertions")]

    use std::sync::Arc;

    use super::{
        Check, ErrorClass, Run, TraceHost, Validation, ValidationRunError, endpoint_refusal,
        validate,
    };
    use crate::{Ending, Trace, TraceDoc};

    const SPEC: &str = "---- MODULE Count ----\nEXTENDS Naturals\nVARIABLE x\n\
        Init == x = 0\nNext == x' = x + 1\nSmall == x < 3\nTiny == x < 5\n====\n";

    fn model() -> dive_model::Model {
        let analysis = dive_sema::analyze_source("Count.tla", SPEC, &dive_sema::Options::default());
        let ir = Arc::new(dive_ir::lower(&analysis).expect("lower"));
        let cfg = dive_config::parse("INIT Init\nNEXT Next\nINVARIANT Tiny Small\n")
            .into_config()
            .expect("cfg");
        dive_model::bind(ir, &cfg, &dive_model::BindOptions::tlc()).expect("bind")
    }

    fn trace(model: &dive_model::Model, xs: &[i64]) -> Trace {
        let states = xs.iter().map(|x| serde_json::json!({ "x": x })).collect();
        let doc = TraceDoc::behavior(states)
            .expect("states")
            .with_ending(Ending::Invariant("Small".to_owned()));
        Trace::decode(model, &doc).expect("decode")
    }

    fn rejected(model: &dive_model::Model, t: &Trace) -> Check {
        match validate(model, t).validation {
            Validation::Invalid(f) => f.check,
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn endpoint_allocation_failure_has_no_completed_validation_report() {
        let model = model();
        let trace = trace(&model, &[0, 1]);
        let host = TraceHost::startup();
        let run = Run::private(&model, host, false);
        let error = crate::row_demand::reserve(&mut Vec::<u64>::new(), usize::MAX)
            .expect_err("actual allocation capacity overflow");
        let error =
            endpoint_refusal(&run, &trace, error, Some(1)).expect_err("no report on exhaustion");
        assert!(
            matches!(error,ValidationRunError::ResourceLimit{error,progress} if error.class()==ErrorClass::ResourceLimit&&progress.state==Some(1)&&progress.check==Some(Check::Ending))
        );
    }

    #[test]
    fn edits_of_a_valid_counterexample_are_rejected() {
        let m = model();
        let original = trace(&m, &[0, 1, 2, 3]);
        assert_eq!(validate(&m, &original).validation, Validation::Valid);
        // A dropped middle state, a dropped initial state, swapped states
        // and a changed value are not steps of the specification.
        assert_eq!(rejected(&m, &trace(&m, &[0, 1, 3])), Check::Next);
        assert_eq!(rejected(&m, &trace(&m, &[1, 2, 3])), Check::Init);
        assert_eq!(rejected(&m, &trace(&m, &[0, 2, 1, 3])), Check::Next);
        assert_eq!(rejected(&m, &trace(&m, &[0, 1, 7, 3])), Check::Next);
        // Cut short, the claimed invariant holds at the end.
        assert_eq!(rejected(&m, &trace(&m, &[0, 1, 2])), Check::Ending);
        // Another invariant is not violated at the end.
        let mut claim = original.clone();
        claim.ending = Ending::Invariant("Tiny".to_owned());
        assert_eq!(rejected(&m, &claim), Check::Ending);
        // An invariant the model does not have.
        claim.ending = Ending::Invariant("Missing".to_owned());
        assert_eq!(rejected(&m, &claim), Check::Ending);
    }
}