everystate 0.4.5

A lightning-fast TLA+ model checker (TLC-compatible, no Java needed)
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
//! Parallel breadth-first search (`-workers N`).
//!
//! Values, the syntax tree and the evaluator are single-threaded (`Rc`, `Cell`), so the workers share
//! nothing but bytes: every worker thread builds its own copy of the model, and states cross threads
//! in a serialized form (string and model-value ids are process-wide, see `intern`).
//!
//! The search stays level-synchronised and its result is the one of the sequential search, state for
//! state. One level at a time:
//!
//! 1. The workers take chunks of the level in increasing order. For every state they compute the
//!    successors, constraints and fingerprints exactly as the sequential loop does, look the
//!    fingerprints up in the fingerprint set (frozen while the workers run), and evaluate the
//!    invariants of every successor that may be new. They report, per state and in successor order,
//!    the candidates for new states.
//! 2. The main thread merges the reports in state order: the first occurrence of a fingerprint gets the
//!    next state id, as in the sequential search, so ids, parents, counts, depth and the state graph
//!    are identical to a one-worker run.
//!
//! Whatever is not this plain path is not handled here at all. When a worker meets a violation, an
//! error, a deadlock, or an operator whose effect depends on the order of exploration (Print, TLCSet,
//! TLCGet of a register or a statistic, RandomElement, I/O, a string that does not exist yet ...), it
//! reports the position of that state and stops; the workers never print, write or decide anything.
//! The level is merged up to that state and the sequential loop of `Checker::search` takes over from
//! exactly there: it re-expands the state and reports what it finds, with its own code. After an
//! order-dependent operator it finishes the level, so that every such effect happens in the sequential
//! order, and the next level goes to (fresh) workers again; the third time the search stays sequential
//! and says so.
//!
//! The candidates for initial states are dealt with in the same way (`Par::init`).
//!
//! States found by a parallel level exist as bytes only; `Checker::state_at` rebuilds one for a trace,
//! and `finish` rebuilds all of them when the state graph is going to be read (`-dump`, liveness).
//!
//! Test hooks (environment): EVERYSTATE_PAR_MIN, EVERYSTATE_PAR_CHUNK (see `cli::par_config`) and
//! EVERYSTATE_PAR_DEBUG (a summary of what the workers did, on standard error).
use crate::checker::{Checker, Events, FpSet, ParConfig, NO_PARENT};
use crate::codec::*;
use crate::eval::{set_stack_limit, StateData, StateRef};
use crate::host::Host;
use crate::intern::*;
use crate::model::{build_model, Model};
use crate::value::*;
use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::Hasher as StdHasher;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;


/// Consecutive states in serialized form: state `base + i` is `bytes[offs[i]..offs[i + 1]]`; or, in
/// numbered form (`nums`), the numbers of its variables' values (`Dict`), `nv` per state.
pub struct Batch {
    base: usize,
    offs: Vec<usize>,
    bytes: Vec<u8>,
    nums: Option<(usize, Vec<u32>)>,
}
impl Batch {
    fn new(base: usize) -> Batch {
        Batch { base, offs: vec![0], bytes: Vec::new(), nums: None }
    }
    fn numbered(base: usize, nv: usize) -> Batch {
        Batch { base, offs: vec![], bytes: Vec::new(), nums: Some((nv, Vec::new())) }
    }
    fn len(&self) -> usize {
        match &self.nums {
            Some((nv, r)) => r.len() / (*nv).max(1),
            None => self.offs.len() - 1,
        }
    }
    fn get(&self, i: usize) -> &[u8] {
        &self.bytes[self.offs[i]..self.offs[i + 1]]
    }
    /// The numbers of state `base + i` (numbered form).
    fn nums(&self, i: usize) -> Option<&[u32]> {
        self.nums.as_ref().map(|(nv, r)| &r[i * nv..(i + 1) * nv])
    }
}

/// Numbers for the values of variables, shared by the threads of a parallel search (id mode): a value
/// gets one the first time a thread sends it, and is kept as its encoding (`ser_var`). A state then
/// crosses threads as one number per variable, and a worker that has met a number knows its value by
/// it (`Nums`). Booleans and small integers are their own numbers (the immediate ids of `hashcons`).
pub struct Dict {
    shards: Box<[std::sync::Mutex<DictShard>]>,
}
#[derive(Default)]
struct DictShard {
    by_bytes: HashMap<Arc<[u8]>, u32, FxBuild>,
    bytes: Vec<Arc<[u8]>>,
}
const DICT_SHARDS: u32 = 64;
impl Dict {
    fn new() -> Dict {
        Dict { shards: (0..DICT_SHARDS).map(|_| Default::default()).collect() }
    }
    /// The number of the value encoded as `b` (`ser_var`).
    fn number(&self, b: &[u8]) -> u32 {
        let mut h = Fx(0);
        h.write(b);
        let k = (h.finish() >> 40) as u32 % DICT_SHARDS;
        let mut sh = self.shards[k as usize].lock().unwrap();
        if let Some(&x) = sh.by_bytes.get(b) {
            return x;
        }
        let i = sh.bytes.len() as u32;
        assert!(i < 1 << 24, "parallel search: more than 2^30 distinct values of variables");
        let x = i * DICT_SHARDS + k;
        let a: Arc<[u8]> = b.into();
        sh.bytes.push(a.clone());
        sh.by_bytes.insert(a, x);
        x
    }
    /// The encoding of the value numbered `x`.
    fn bytes(&self, x: u32) -> Arc<[u8]> {
        self.shards[(x % DICT_SHARDS) as usize].lock().unwrap().bytes[(x / DICT_SHARDS) as usize].clone()
    }
    /// Appends the encoding of the value numbered `x` (`ser_var`).
    fn encode(&self, x: u32, out: &mut Vec<u8>) {
        if crate::hashcons::is_immediate(x) {
            ser_var(&crate::hashcons::value(x), out, &mut vec![]);
        } else {
            out.extend_from_slice(&self.bytes(x));
        }
    }
    /// The value numbered `x`.
    fn value(&self, de: &mut De, x: u32) -> Value {
        if crate::hashcons::is_immediate(x) {
            return crate::hashcons::value(x);
        }
        let b = self.bytes(x);
        let mut pos = 0;
        let _len = get_u(&b, &mut pos);
        de.value(&b, &mut pos)
    }
}
/// The candidates of `out` from `mark` on that were written as encodings (`ser_state`), as numbers.
fn number_encodings(dict: &Dict, out: &mut ChunkOut, mark: (usize, usize, usize), nv: usize) {
    if out.bytes.len() == mark.1 {
        return;
    }
    let mut off = mark.1;
    for e in &out.ent[mark.0..] {
        if e.kind != CAND || e.len == 0 {
            continue;
        }
        let b = &out.bytes[off..off + e.len as usize];
        let mut pos = 0;
        for _ in 0..nv {
            let start = pos;
            let len = get_u(b, &mut pos) as usize;
            pos += len;
            out.nums.push(dict.number(&b[start..pos]));
        }
        off += e.len as usize;
    }
    out.bytes.truncate(mark.1);
}
/// A thread's side of `Dict`: the ids of the values it has met by number and back.
#[derive(Default)]
struct Nums {
    /// per shard, by index: the id + 1 (0: not met)
    ids: Vec<Vec<u32>>,
    /// by id: the number + 1 (0: not met)
    nums: Vec<u32>,
}
impl Nums {
    fn note(&mut self, x: u32, id: crate::hashcons::Id) {
        let (k, i) = ((x % DICT_SHARDS) as usize, (x / DICT_SHARDS) as usize);
        if self.ids.len() <= k {
            self.ids.resize(DICT_SHARDS as usize, vec![]);
        }
        if self.ids[k].len() <= i {
            self.ids[k].resize(i + 1, 0);
        }
        self.ids[k][i] = id + 1;
        let j = id as usize;
        if self.nums.len() <= j {
            self.nums.resize(j + 1, 0);
        }
        self.nums[j] = x + 1;
    }
    /// The id of the value numbered `x` on this thread (interning it); None when it cannot be interned.
    #[inline]
    fn id(&mut self, dict: &Dict, de: &mut De, x: u32) -> Option<crate::hashcons::Id> {
        if crate::hashcons::is_immediate(x) {
            return Some(x);
        }
        let (k, i) = ((x % DICT_SHARDS) as usize, (x / DICT_SHARDS) as usize);
        if let Some(&y) = self.ids.get(k).and_then(|v| v.get(i)) {
            if y != 0 {
                return Some(y - 1);
            }
        }
        let id = crate::hashcons::id(&dict.value(de, x))?;
        self.note(x, id);
        Some(id)
    }
    /// The number of the value with id `id` on this thread; None when it cannot be encoded.
    #[inline]
    fn num(&mut self, dict: &Dict, id: crate::hashcons::Id, tmp: &mut Vec<u8>, out: &mut Vec<u8>) -> Option<u32> {
        if crate::hashcons::is_immediate(id) {
            return Some(id);
        }
        if let Some(&y) = self.nums.get(id as usize) {
            if y != 0 {
                return Some(y - 1);
            }
        }
        out.clear();
        if !ser_var(&crate::hashcons::value(id), out, tmp) {
            return None;
        }
        let x = dict.number(out);
        self.note(x, id);
        Some(x)
    }
}

// ---------- the workers ----------
const CAND: u8 = 0; // not in the fingerprint set, first occurrence in this worker: carries the state
const DUP: u8 = 1; // seen earlier in this level by the same worker
const SEEN: u8 = 2; // in the fingerprint set (a state of an earlier level): `fp` holds its id

/// One successor that the merge has to know about.
struct Ent {
    fp: u64,
    act: u32,
    kind: u8,
    /// length of its serialized state in `ChunkOut::bytes` (0 = not sent)
    len: u32,
}
enum Event {
    /// a violation, an error or a deadlock: the sequential search reports it
    Check,
    /// the state cannot be expanded by a worker; the reason
    Fallback(String),
}
/// What a worker reports for the states `start .. start + done` of a level.
struct ChunkOut {
    start: usize,
    done: usize,
    /// what stopped the worker at state `start + done`
    event: Option<Event>,
    /// per state: generated successors, number of entries in `ent`
    src: Vec<(u64, u32)>,
    ent: Vec<Ent>,
    bytes: Vec<u8>,
    /// id mode: the candidates by group of the fingerprint set (see `Claim`), (fingerprint, entry), in
    /// order
    by_group: Vec<Vec<(u64, u32)>>,
    /// id mode: the candidates as numbers (`Dict`), `nv` per entry, instead of `bytes`
    nums: Vec<u32>,
}
/// Who found each fingerprint first in a level, as far as the workers can tell while they expand it
/// (id mode, `Par::level_ids`): fingerprint -> the smallest position (state of the level, successor)
/// it was found at so far. A worker that finds a fingerprint at a later position than one already
/// noted drops it: that is not the occurrence the sequential search meets first. (Only a shortcut: the
/// claim after the level decides; a fingerprint that finds no room here is a candidate.)
struct Firsts {
    keys: Box<[std::sync::atomic::AtomicU64]>,
    /// the complement of the earliest position (0: none yet; zeroed memory is a table with nothing in it)
    at: Box<[std::sync::atomic::AtomicU64]>,
    mask: usize,
}
/// How far `Firsts::first` looks for a fingerprint's slot (a table that full makes candidates).
const FIRSTS_PROBES: usize = 32;
impl Firsts {
    fn new(cap: usize) -> Firsts {
        Firsts { keys: crate::checker::zeroed_u64(cap), at: crate::checker::zeroed_u64(cap), mask: cap - 1 }
    }
    /// Notes that `fp` was found at `at`; false when it was found at an earlier position already.
    #[inline]
    fn first(&self, fp: u64, at: u64) -> bool {
        let k = if fp == 0 { 0x9E37_79B9_7F4A_7C15 } else { fp };
        let mut i = (k as usize) & self.mask;
        for _ in 0..FIRSTS_PROBES {
            let mut cur = self.keys[i].load(Ordering::Acquire);
            if cur == 0 {
                cur = match self.keys[i].compare_exchange(0, k, Ordering::AcqRel, Ordering::Acquire) {
                    Ok(_) => k,
                    Err(x) => x,
                };
            }
            if cur == k {
                return !at > self.at[i].fetch_max(!at, Ordering::AcqRel);
            }
            i = (i + 1) & self.mask;
        }
        true
    }
}

struct Job {
    /// the states are the candidates for initial states, not a level
    init: bool,
    /// id mode: who found each fingerprint first (see `Firsts`)
    firsts: Option<Firsts>,
    /// id mode: the numbers of values (states cross threads as numbers)
    dict: Option<Arc<Dict>>,
    /// what the sequential search measured of the step cache (see `Plans::adopt`)
    verdicts: Arc<[crate::compile::Verdict]>,
    frontier: Arc<Batch>,
    lvl: u32,
    chunk: usize,
    next: AtomicUsize,
    /// smallest position at which a worker stopped; states behind it are not expanded
    stop: AtomicUsize,
    fps: Arc<FpSet>,
}
enum ToWorker {
    Level(Arc<Job>),
    Claim(Arc<Claim>),
    Grow(Arc<Grow>),
    Exit,
}
/// The second half of a level in id mode (`Par::level_ids`): the candidates of every chunk go into the
/// fingerprint set, each worker taking the fingerprints of its groups of segments, in the order of the
/// level. The first of the level to insert a fingerprint is the one the sequential search finds first:
/// it is a new state (see `wins`); the others are not.
struct Claim {
    chunks: Vec<ChunkOut>,
    /// per chunk: how many of its entries count (the level ends at the first state a worker stopped at)
    upto: Vec<usize>,
    fps: Arc<FpSet>,
    next: AtomicUsize,
    /// per group: its new states (chunk, entry), stored once the group is done
    wins: Vec<std::sync::Mutex<Vec<(u32, u32)>>>,
}
/// The groups of segments of the fingerprint set that the workers claim fingerprints in: a fingerprint
/// belongs to group `FpSet::segment(fp) % CLAIM_GROUPS`. (More than workers: one slow worker delays the
/// end of the claim less.)
const CLAIM_GROUPS: usize = 16;
impl Claim {
    fn run(&self) {
        loop {
            let g = self.next.fetch_add(1, Ordering::Relaxed);
            if g >= CLAIM_GROUPS {
                return;
            }
            // (results are kept by the group and handed on once: threads writing one shared bitmap, or
            // one shared count, took longer than the inserts)
            let mut wins = vec![];
            for (ci, c) in self.chunks.iter().enumerate() {
                for &(fp, ei) in c.by_group[g].iter() {
                    if ei as usize >= self.upto[ci] {
                        break;
                    }
                    // (`Par::level_ids` made room for every candidate)
                    if self.fps.insert_owned(fp) {
                        wins.push((ci as u32, ei));
                    }
                }
            }
            self.fps.add_len(wins.len());
            *self.wins[g].lock().unwrap() = wins;
        }
    }
}
/// The fingerprint set moved to a larger one by the workers, a segment at a time (a fingerprint stays
/// in its segment whatever the size: see `FpSet`).
struct Grow {
    old: FpSet,
    new: FpSet,
    next: AtomicUsize,
}
impl Grow {
    fn run(&self) {
        loop {
            let s = self.next.fetch_add(1, Ordering::Relaxed);
            if s >= crate::checker::SEGMENTS {
                return;
            }
            self.new.refill_segment(&self.old, s);
        }
    }
}
/// EVERYSTATE_PAR_DEBUG: what one worker spent on levels and how many states it expanded, over all the
/// engines of a search. The main thread reports it when the search ends: a worker that wrote it as it
/// left could be cut off by the end of the process.
#[derive(Default)]
struct Busy {
    ns: std::sync::atomic::AtomicU64,
    states: std::sync::atomic::AtomicU64,
}
enum FromWorker {
    Ready(Result<(), String>),
    Chunk(ChunkOut),
    Done,
    /// a claim or a grow is done (on this worker's side)
    Finished,
}
#[derive(Clone, Copy)]
struct Flags {
    check_deadlock: bool,
    /// the merge needs every edge of the state graph (`-dump`, liveness)
    record: bool,
    /// ... and the successor states themselves (liveness under VIEW or SYMMETRY)
    keep_states: bool,
}

/// The host of a worker's evaluator: nothing may be read from or written to the outside by a worker.
struct GuardHost;
const IO: &str = "an operator that prints or does input/output";
impl Host for GuardHost {
    fn read_file(&self, path: &str) -> Result<Vec<u8>, String> {
        worker_impure(IO);
        Err(path.to_string())
    }
    fn write_file(&self, path: &str, _: &[u8]) -> Result<(), String> {
        worker_impure(IO);
        Err(path.to_string())
    }
    fn append_file(&self, path: &str, _: &[u8]) -> Result<(), String> {
        worker_impure(IO);
        Err(path.to_string())
    }
    fn exists(&self, _: &str) -> bool {
        worker_impure(IO);
        false
    }
    fn env(&self) -> Vec<(String, String)> {
        worker_impure(IO);
        vec![]
    }
    fn exec(&self, _: &[String], _: Option<&[(String, String)]>) -> Result<(i32, String, String), String> {
        worker_impure(IO);
        Err("not available".into())
    }
    fn print(&self, _: &str) {
        worker_impure(IO);
    }
    fn now_ms(&self) -> f64 {
        worker_impure("the clock");
        0.0
    }
}

/// The recipe by which a worker thread builds its own copy of the model: the configuration text and
/// the module sources the main thread read.
pub fn model_factory(root_name: String, cfg_text: String, sources: Vec<(String, String)>) -> Arc<dyn Fn() -> R<Model> + Send + Sync> {
    let sources = Arc::new(sources);
    Arc::new(move || {
        let cfg = crate::cfg::parse_config(&cfg_text)?;
        let src = sources.clone();
        let resolve: crate::modules::SourceResolver = Box::new(move |name: &str| src.iter().find(|(n, _)| n == name).map(|(_, t)| t.clone()));
        build_model(&root_name, resolve, &cfg, Rc::new(GuardHost))
    })
}

/// A level this large goes to the workers however long the search has run.
const BIG_LEVEL: usize = 512;
const STACK: usize = 1 << 30;
const UNSENDABLE: &str = "a state holds a value that cannot be passed between workers (a set defined by a predicate, or an operator)";

/// macOS: a thread of the default quality of service may run on an efficiency core, which takes about
/// twice as long; the level waits for its slowest worker.
#[cfg(target_os = "macos")]
fn prefer_fast_cores() {
    extern "C" {
        fn pthread_set_qos_class_self_np(class: u32, relative_priority: i32) -> i32;
    }
    const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21;
    // SAFETY: sets an attribute of the calling thread only
    unsafe {
        pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
    }
}
#[cfg(not(target_os = "macos"))]
fn prefer_fast_cores() {}

fn worker_main(factory: Arc<dyn Fn() -> R<Model> + Send + Sync>, flags: Flags, rx: Receiver<ToWorker>, tx: Sender<FromWorker>, busy: Arc<Busy>) {
    set_stack_limit(STACK - (64 << 20));
    set_worker(true);
    prefer_fast_cores();
    let model = match factory() {
        Ok(m) => m,
        Err(_) => {
            let _ = tx.send(FromWorker::Ready(Err("a worker could not load the specification".into())));
            return;
        }
    };
    let ck = Checker::new(&model, crate::checker::CheckOptions { check_deadlock: flags.check_deadlock, record_graph: false, lncheck: crate::checker::LnCheck::Final, par: None, store: None });
    if let Some(what) = take_impure() {
        let _ = tx.send(FromWorker::Ready(Err(format!("loading the specification uses {}", what))));
        return;
    }
    if tx.send(FromWorker::Ready(Ok(()))).is_err() {
        return;
    }
    let mut de = De::default();
    let mut succs: Vec<StateRef> = vec![];
    let mut acts: Vec<u32> = vec![];
    let mut scratch = Scratch::default();
    let mut sbuf: Vec<u8> = vec![];
    let nvars = model.vars.len();
    let idmode = ck.is_flat() && !flags.record && ck.caching();
    loop {
        let job = match rx.recv() {
            Ok(ToWorker::Level(job)) => job,
            Ok(ToWorker::Claim(c)) => {
                c.run();
                drop(c);
                if tx.send(FromWorker::Finished).is_err() {
                    return;
                }
                continue;
            }
            Ok(ToWorker::Grow(g)) => {
                g.run();
                drop(g);
                if tx.send(FromWorker::Finished).is_err() {
                    return;
                }
                continue;
            }
            _ => break,
        };
        ck.adopt(&job.verdicts);
        // fingerprints this worker has met in this level
        let mut local = FpSet::with_capacity(1 << 10);
        let t_job = std::time::Instant::now();
        {
            let fps = &*job.fps;
            let n = job.frontier.len();
            loop {
                let start = job.next.fetch_add(1, Ordering::Relaxed).saturating_mul(job.chunk);
                if start >= n || start > job.stop.load(Ordering::Relaxed) {
                    break;
                }
                let end = (start + job.chunk).min(n);
                let mut out = ChunkOut { start, done: 0, event: None, src: Vec::with_capacity(end - start), ent: vec![], bytes: vec![], by_group: if idmode { vec![vec![]; CLAIM_GROUPS] } else { vec![] }, nums: vec![] };
                for i in start..end {
                    if i > job.stop.load(Ordering::Relaxed) {
                        break;
                    }
                    // a numbered level: the ids by number (the values only if something needs them), or,
                    // with a value that cannot be interned, the encoding
                    let xs = job.frontier.nums(i);
                    let mut lazy = false;
                    if let Some(xs) = xs {
                        let dict = job.dict.as_ref().expect("a numbered level comes with its numbers");
                        scratch.cur.clear();
                        lazy = idmode && !job.init && xs.iter().all(|&x| scratch.nums.id(dict, &mut de, x).map(|id| scratch.cur.push(id)).is_some());
                        if !lazy {
                            scratch.cur.clear();
                            sbuf.clear();
                            for &x in xs {
                                dict.encode(x, &mut sbuf);
                            }
                        }
                    }
                    let sb: &[u8] = if xs.is_some() { &sbuf } else { job.frontier.get(i) };
                    let s = if lazy {
                        scratch.blank_state(nvars)
                    } else if idmode && !job.init {
                        scratch.enc.state(&mut de, sb, nvars, &mut scratch.cur)
                    } else {
                        de.state(sb, nvars)
                    };
                    let mark = (out.ent.len(), out.bytes.len(), out.nums.len());
                    let firsts = job.firsts.as_ref().map(|f| (f, i as u64));
                    let numbers = job.dict.as_deref().map(|d| (d, if lazy { xs } else { None }));
                    let mut event = if job.init { expand_init(&ck, &s, &mut local, &mut out) } else { expand(&ck, &s, sb, job.lvl, fps, &mut local, firsts, numbers, &mut de, &mut out, &mut succs, &mut acts, flags, &mut scratch) };
                    if let (Some(dict), None) = (&job.dict, &event) {
                        // (candidates found as values: their encodings to numbers)
                        number_encodings(dict, &mut out, mark, nvars);
                    }
                    // an order-dependent operator decides, whatever else happened to the evaluation
                    if let Some(what) = take_impure() {
                        event = Some(Event::Fallback(format!("the specification uses {}", what)));
                    }
                    if let Some(e) = event {
                        out.ent.truncate(mark.0);
                        out.bytes.truncate(mark.1);
                        out.nums.truncate(mark.2);
                        for g in out.by_group.iter_mut() {
                            while g.last().is_some_and(|x| x.1 as usize >= mark.0) {
                                g.pop();
                            }
                        }
                        ck.ev.extra_generated.set(0);
                        job.stop.fetch_min(i, Ordering::Relaxed);
                        out.event = Some(e);
                        break;
                    }
                    out.done += 1;
                }
                busy.states.fetch_add(out.done as u64, Ordering::Relaxed);
                if tx.send(FromWorker::Chunk(out)).is_err() {
                    return;
                }
            }
        }
        // (before `Done`: the main thread reads the counters after the last level)
        busy.ns.fetch_add(t_job.elapsed().as_nanos() as u64, Ordering::Relaxed);
        drop(job);
        if tx.send(FromWorker::Done).is_err() {
            return;
        }
    }
    if let Some(r) = ck.eval_report() {
        eprint!("{}: {}", std::thread::current().name().unwrap_or("worker"), r);
    }
    // the process is about to end or goes on without this thread: nothing here is worth tearing down
    std::mem::forget(ck);
    std::mem::forget(model);
}

/// Expands one state as the sequential loop does (same evaluations in the same order, same TLCGet("level")),
/// without its bookkeeping. Some(..) when the state has to go to the sequential search instead.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
fn expand(ck: &Checker, s: &StateRef, sb: &[u8], lvl: u32, fps: &FpSet, local: &mut FpSet, firsts: Option<(&Firsts, u64)>, numbers: Option<(&Dict, Option<&[u32]>)>, de: &mut De, out: &mut ChunkOut, succs: &mut Vec<StateRef>, acts: &mut Vec<u32>, flags: Flags, scratch: &mut Scratch) -> Option<Event> {
    let m = ck.model;
    let ev = ck.ev;
    let level = &ev.stats.level;
    level.set(lvl as i64);
    succs.clear();
    acts.clear();
    if ck.is_flat() && !flags.record {
        // As the sequential loop in flat mode: the successors are rows of a buffer, their fingerprints
        // are the parent's with the changed variables replaced, and a state is built (for the
        // invariants) only for a successor that may be new. There are no constraints and no action
        // properties in this mode.
        let nv = ck.model.vars.len();
        if !scratch.cur.is_empty() {
            return expand_ids(ck, s, sb, lvl, fps, local, firsts, numbers, de, out, flags, scratch);
        }
        scratch.rows.clear();
        if ck.successors_flat(s, &mut scratch.rows, acts).is_err() {
            return Some(Event::Check);
        }
        let extra = ev.extra_generated.replace(0);
        let first = out.ent.len();
        var_spans(sb, nv, &mut scratch.spans);
        if !acts.is_empty() && ck.parent_terms(s, &mut scratch.terms).is_err() {
            return Some(Event::Check);
        }
        for i in 0..acts.len() {
            let row = &scratch.rows[i * nv..(i + 1) * nv];
            level.set(lvl as i64 + 1);
            let fp = match ck.row_fingerprint(s, &scratch.terms, row) {
                Ok(fp) => fp,
                Err(_) => return Some(Event::Check),
            };
            let candidate = fps.get(fp).is_none() && local.put(fp, 0).is_none();
            if candidate {
                let mark = out.bytes.len();
                if !ser_row(row, s, sb, &scratch.spans, &mut out.bytes, &mut scratch.tmp) {
                    return Some(Event::Fallback(UNSENDABLE.into()));
                }
                if !out.by_group.is_empty() {
                    out.by_group[FpSet::segment(fp) % CLAIM_GROUPS].push((fp, out.ent.len() as u32));
                }
                out.ent.push(Ent { fp, act: acts[i], kind: CAND, len: (out.bytes.len() - mark) as u32 });
                if !m.invariants.is_empty() {
                    let t = StateData::new(row.to_vec());
                    for ii in 0..m.invariants.len() {
                        if !matches!(ck.eval_invariant(ii, &t), Ok(true)) {
                            return Some(Event::Check);
                        }
                    }
                }
            }
            level.set(lvl as i64);
        }
        if acts.is_empty() && flags.check_deadlock {
            return Some(Event::Check);
        }
        out.src.push((acts.len() as u64 + extra, (out.ent.len() - first) as u32));
        return None;
    }
    if ck.successors(s, succs, acts).is_err() {
        return Some(Event::Check);
    }
    let extra = ev.extra_generated.replace(0);
    let first = out.ent.len();
    var_spans(sb, ck.model.vars.len(), &mut scratch.spans);
    for i in 0..succs.len() {
        let t = &succs[i];
        let act = acts[i];
        let fp: R<Option<u64>> = (|| {
            level.set(lvl as i64 + 1);
            for c in &m.constraints {
                if !ck.eval_pred(c, t, None)? {
                    return Ok(None);
                }
            }
            level.set(lvl as i64);
            for c in &m.action_constraints {
                if !ck.eval_pred(c, s, Some(t))? {
                    level.set(lvl as i64 + 1);
                    return Ok(None);
                }
            }
            level.set(lvl as i64 + 1);
            Ok(Some(ck.fingerprint(t)?))
        })();
        let fp = match fp {
            Ok(fp) => fp,
            Err(_) => return Some(Event::Check),
        };
        let mut unseen = true;
        if let Some(fp) = fp {
            let (kind, word) = match fps.get(fp) {
                Some(id) => (SEEN, id as u64),
                None => match local.put(fp, 0) {
                    Some(_) => (DUP, fp),
                    None => (CAND, fp),
                },
            };
            unseen = kind == CAND;
            if kind == CAND || flags.record {
                let mark = out.bytes.len();
                if (kind == CAND || flags.keep_states) && !ser_successor(t, s, sb, &scratch.spans, &mut out.bytes, &mut scratch.tmp) {
                    return Some(Event::Fallback(UNSENDABLE.into()));
                }
                out.ent.push(Ent { fp: word, act, kind, len: (out.bytes.len() - mark) as u32 });
            }
        }
        if unseen {
            for ii in 0..m.invariants.len() {
                if !matches!(ck.eval_invariant(ii, t), Ok(true)) {
                    return Some(Event::Check);
                }
            }
        }
        level.set(lvl as i64);
        for p in &m.implied_actions {
            if !matches!(ck.eval_pred(p, s, Some(t)), Ok(true)) {
                return Some(Event::Check);
            }
        }
    }
    if succs.is_empty() && flags.check_deadlock {
        return Some(Event::Check);
    }
    out.src.push((succs.len() as u64 + extra, (out.ent.len() - first) as u32));
    None
}

/// `expand` in flat mode with the step cache: as the sequential search in id mode. The parent is interned
/// (and rebuilt from the canonical values, which the step cache compares by identity), its successors are
/// rows of ids, and a candidate is encoded from the parent's encoding and the values of the ids that
/// differ.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
fn expand_ids(ck: &Checker, s: &StateRef, sb: &[u8], lvl: u32, fps: &FpSet, local: &mut FpSet, firsts: Option<(&Firsts, u64)>, numbers: Option<(&Dict, Option<&[u32]>)>, de: &mut De, out: &mut ChunkOut, flags: Flags, scratch: &mut Scratch) -> Option<Event> {
    use crate::hashcons::NOT_INTERNED;
    let m = ck.model;
    let ev = ck.ev;
    let level = &ev.stats.level;
    let nv = m.vars.len();
    let cur = &mut scratch.cur;
    // (the parent's terms first: a successor found from the step cache gets its fingerprint from them,
    // and its row is built only if it is a candidate)
    let lazy = numbers.is_some_and(|(_, xs)| xs.is_some());
    let terms = if lazy { ck.id_terms(cur, &mut scratch.terms) } else { ck.parent_terms(s, &mut scratch.terms) };
    if terms.is_err() {
        return Some(Event::Check);
    }
    let fpx = scratch.terms.fp_ctx(fps);
    let ids_now: Vec<crate::hashcons::Id> = if lazy { cur.clone() } else { vec![] };
    let fill = || s.refill(|v| v.extend(ids_now.iter().map(|&x| crate::hashcons::value(x))));
    if ck.successors_ids(s, if lazy { Some(&fill) } else { None }, cur, &scratch.idrows, Some(&fpx)).is_err() {
        return Some(Event::Check);
    }
    let extra = ev.extra_generated.replace(0);
    let first = out.ent.len();
    let rows = scratch.idrows.borrow();
    let n = rows.len();
    if n > 0 {
        ck.id_fingerprints(s, cur, &scratch.terms, &rows, &mut scratch.fps);
        if numbers.is_none() {
            var_spans(sb, nv, &mut scratch.spans);
        }
    }
    // the parent's numbers (a bytes level: from its ids)
    if let (Some((dict, pn)), true) = (numbers, n > 0) {
        scratch.pnums.clear();
        match pn {
            Some(xs) => scratch.pnums.extend_from_slice(xs),
            None => {
                for &x in cur.iter() {
                    let y = if x < NOT_INTERNED {
                        scratch.nums.num(dict, x, &mut scratch.tmp, &mut scratch.tmp2)
                    } else {
                        scratch.tmp2.clear();
                        ser_var(&rows.value(x), &mut scratch.tmp2, &mut scratch.tmp).then(|| dict.number(&scratch.tmp2))
                    };
                    match y {
                        Some(y) => scratch.pnums.push(y),
                        None => return Some(Event::Fallback(UNSENDABLE.into())),
                    }
                }
            }
        }
    }
    level.set(lvl as i64 + 1);
    for i in 0..n {
        let fp = match scratch.fps[i] {
            Some(fp) => fp,
            None => return Some(Event::Check),
        };
        if fps.get(fp).is_some() {
            continue;
        }
        let first = match firsts {
            // (position: the state in the level, then the successor; past 2^24 successors, every one is a candidate)
            Some((f, at)) if i < 1 << 24 => f.first(fp, at << 24 | i as u64),
            Some(_) => true,
            None => local.put(fp, 0).is_none(),
        };
        if !first {
            continue;
        }
        let row: &[crate::hashcons::Id] = match rows.row(i, nv) {
            Some(row) => row,
            None => {
                let rc = rows.meta.recipe_of(i).expect("a successor without a row is a recipe");
                if !ck.build_recipe(rc, cur, &mut scratch.recipe_row) {
                    // (its changes do not apply after all: the sequential search finds out why)
                    return Some(Event::Check);
                }
                &scratch.recipe_row
            }
        };
        let mark = out.bytes.len();
        match numbers {
            Some((dict, _)) => {
                for k in 0..nv {
                    let x = row[k];
                    let y = if x == cur[k] {
                        Some(scratch.pnums[k])
                    } else if x < NOT_INTERNED {
                        scratch.nums.num(dict, x, &mut scratch.tmp, &mut scratch.tmp2)
                    } else {
                        scratch.tmp2.clear();
                        ser_var(&rows.value(x), &mut scratch.tmp2, &mut scratch.tmp).then(|| dict.number(&scratch.tmp2))
                    };
                    match y {
                        Some(y) => out.nums.push(y),
                        None => return Some(Event::Fallback(UNSENDABLE.into())),
                    }
                }
            }
            None => {
                for k in 0..nv {
                    let x = row[k];
                    if x == cur[k] {
                        out.bytes.extend_from_slice(&sb[scratch.spans[k].0..scratch.spans[k].1]);
                    } else if x < NOT_INTERNED {
                        if !scratch.enc.encode(x, &mut out.bytes, &mut scratch.tmp) {
                            return Some(Event::Fallback(UNSENDABLE.into()));
                        }
                    } else if !ser_var(&rows.value(x), &mut out.bytes, &mut scratch.tmp) {
                        return Some(Event::Fallback(UNSENDABLE.into()));
                    }
                }
            }
        }
        out.by_group[FpSet::segment(fp) % CLAIM_GROUPS].push((fp, out.ent.len() as u32));
        out.ent.push(Ent { fp, act: rows.meta.found[i].act, kind: CAND, len: (out.bytes.len() - mark) as u32 });
        if !m.invariants.is_empty() {
            let t = StateData::new(row.iter().map(|&x| rows.value(x)).collect());
            for ii in 0..m.invariants.len() {
                if !matches!(ck.eval_invariant(ii, &t), Ok(true)) {
                    return Some(Event::Check);
                }
            }
        }
    }
    let _ = de;
    level.set(lvl as i64);
    if n == 0 && flags.check_deadlock {
        return Some(Event::Check);
    }
    out.src.push((n as u64 + extra, (out.ent.len() - first) as u32));
    None
}

/// The same for a candidate initial state: constraints, fingerprint, invariants and implied initial
/// predicates, as in `Checker::compute_init`.
fn expand_init(ck: &Checker, s: &StateRef, local: &mut FpSet, out: &mut ChunkOut) -> Option<Event> {
    let m = ck.model;
    ck.ev.stats.level.set(1);
    let fp: R<Option<u64>> = (|| {
        for c in &m.constraints {
            if !ck.eval_pred(c, s, None)? {
                return Ok(None);
            }
        }
        Ok(Some(ck.fingerprint(s)?))
    })();
    let fp = match fp {
        Ok(fp) => fp,
        Err(_) => return Some(Event::Check),
    };
    let mut unseen = true;
    if let Some(fp) = fp {
        unseen = local.put(fp, 0).is_none();
        if unseen {
            // the merge takes the state itself from the level
            out.ent.push(Ent { fp, act: 0, kind: CAND, len: 0 });
        }
    }
    if unseen {
        for p in m.invariants.iter().chain(m.implied_inits.iter()) {
            if !matches!(ck.eval_pred(p, s, None), Ok(true)) {
                return Some(Event::Check);
            }
        }
    }
    out.src.push((1, (fp.is_some() && unseen) as u32));
    None
}

/// A worker's memo of the encodings of the values it interned, both ways: decoding a variable it has met
/// is a hash of its bytes, and encoding an id it has met is a copy.
#[derive(Default)]
struct Enc {
    arena: Vec<u8>,
    /// per id: where its variable encoding (length prefix included) is in `arena`; (0, 0) = not known
    by_id: Vec<(u32, u32)>,
    by_bytes: HashMap<Box<[u8]>, crate::hashcons::Id, FxBuild>,
}
impl Enc {
    fn note(&mut self, x: crate::hashcons::Id, bytes: &[u8]) {
        if crate::hashcons::is_immediate(x) {
            return;
        }
        let i = x as usize;
        if self.by_id.len() <= i {
            self.by_id.resize(i + 1, (0, 0));
        }
        if self.by_id[i].1 == 0 && self.arena.len() + bytes.len() < u32::MAX as usize {
            self.by_id[i] = (self.arena.len() as u32, bytes.len() as u32);
            self.arena.extend_from_slice(bytes);
        }
    }
    /// The state encoded in `b`, from canonical values; `cur` gets the ids of its variables
    /// (`NOT_INTERNED` for a value that cannot be interned).
    fn state(&mut self, de: &mut De, b: &[u8], nvars: usize, cur: &mut Vec<crate::hashcons::Id>) -> StateRef {
        use crate::hashcons::NOT_INTERNED;
        cur.clear();
        let mut vals = Vec::with_capacity(nvars);
        let mut pos = 0;
        for _ in 0..nvars {
            let start = pos;
            let len = get_u(b, &mut pos) as usize;
            let mut vpos = pos;
            pos += len;
            let span = &b[start..pos];
            if len <= 9 {
                // a scalar (or a small value): decoding it is cheaper than the memo
                let v = de.value(b, &mut vpos);
                match crate::hashcons::id(&v) {
                    Some(x) => {
                        cur.push(x);
                        vals.push(crate::hashcons::value(x));
                    }
                    None => {
                        cur.push(NOT_INTERNED);
                        vals.push(v);
                    }
                }
                continue;
            }
            if let Some(&x) = self.by_bytes.get(span) {
                cur.push(x);
                vals.push(crate::hashcons::value(x));
                continue;
            }
            let v = de.value(b, &mut vpos);
            match crate::hashcons::id(&v) {
                Some(x) => {
                    self.by_bytes.insert(span.into(), x);
                    self.note(x, span);
                    cur.push(x);
                    vals.push(crate::hashcons::value(x));
                }
                None => {
                    cur.push(NOT_INTERNED);
                    vals.push(v);
                }
            }
        }
        StateData::new(vals)
    }
    /// Appends the variable encoding of the value with id `x`; false when it cannot be encoded.
    fn encode(&mut self, x: crate::hashcons::Id, out: &mut Vec<u8>, tmp: &mut Vec<u8>) -> bool {
        if crate::hashcons::is_immediate(x) {
            return ser_var(&crate::hashcons::value(x), out, tmp);
        }
        if let Some(&(o, l)) = self.by_id.get(x as usize) {
            if l > 0 {
                out.extend_from_slice(&self.arena[o as usize..(o + l) as usize]);
                return true;
            }
        }
        let mark = out.len();
        if !ser_var(&crate::hashcons::value(x), out, tmp) {
            return false;
        }
        let bytes = out[mark..].to_vec();
        self.note(x, &bytes);
        true
    }
}

#[derive(Default)]
struct Scratch {
    enc: Enc,
    spans: Vec<(usize, usize)>,
    tmp: Vec<u8>,
    /// flat mode: the variables of the successors of the state being expanded, and its fingerprint terms
    rows: Vec<Value>,
    terms: crate::checker::ParentTerms,
    /// id mode: the ids of the parent, its successors, their fingerprints
    cur: Vec<crate::hashcons::Id>,
    idrows: RefCell<crate::stepcache::Rows>,
    fps: Vec<Option<u64>>,
    /// the row of a candidate noted as a recipe
    recipe_row: Vec<crate::hashcons::Id>,
    /// numbered levels: this thread's ids of numbers, the parent's numbers, an encoding, a blank state
    nums: Nums,
    pnums: Vec<u32>,
    tmp2: Vec<u8>,
    blank: Option<StateRef>,
}
impl Scratch {
    /// A state without values (filled when something needs them), reused unless something kept it.
    fn blank_state(&mut self, nv: usize) -> StateRef {
        match &self.blank {
            // (ours plus the evaluator's make two)
            Some(b) if Rc::strong_count(b) <= 2 => b.clone(),
            _ => {
                let b = StateData::blank(nv);
                self.blank = Some(b.clone());
                b
            }
        }
    }
}

struct Engine {
    /// the main thread's `Checker::verdicts`, set before each level
    verdicts: Arc<[crate::compile::Verdict]>,
    txs: Vec<Sender<ToWorker>>,
    rx: Receiver<FromWorker>,
    fps: Arc<FpSet>,
}
impl Engine {
    /// Starts the workers; they load the specification meanwhile (`wait_ready`).
    fn spawn(cfg: &ParConfig, flags: Flags, busy: &[Arc<Busy>]) -> Result<Engine, String> {
        let (tx, rx) = channel::<FromWorker>();
        let mut txs = vec![];
        for i in 0..cfg.workers {
            let (wtx, wrx) = channel::<ToWorker>();
            let (factory, tx, busy) = (cfg.factory.clone(), tx.clone(), busy[i].clone());
            let spawned = std::thread::Builder::new().name(format!("worker-{}", i + 1)).stack_size(STACK).spawn(move || worker_main(factory, flags, wrx, tx, busy));
            if spawned.is_err() {
                return Err("a worker thread could not be started".into());
            }
            txs.push(wtx);
        }
        drop(tx);
        Ok(Engine { verdicts: Arc::new([]), txs, rx, fps: Arc::new(FpSet::with_capacity(2)) })
    }
    /// Waits until every worker has loaded the specification.
    fn wait_ready(self) -> Result<Engine, String> {
        let mut failure = None;
        for _ in 0..self.txs.len() {
            match self.rx.recv() {
                Ok(FromWorker::Ready(Ok(()))) => {}
                Ok(FromWorker::Ready(Err(why))) => failure = Some(why),
                _ => failure = Some("a worker thread stopped unexpectedly".to_string()),
            }
        }
        match failure {
            Some(why) => Err(why), // dropping the engine tells the workers to leave
            None => Ok(self),
        }
    }
    /// Hands the workers a level (or the initial states); they report chunks, then `Done` each.
    fn start_job(&mut self, init: bool, frontier: Arc<Batch>, lvl: u32, chunk: usize) -> Arc<Job> {
        self.start_job_with(init, frontier, lvl, chunk, None, None)
    }
    fn start_job_with(&mut self, init: bool, frontier: Arc<Batch>, lvl: u32, chunk: usize, firsts: Option<Firsts>, dict: Option<Arc<Dict>>) -> Arc<Job> {
        let verdicts = self.verdicts.clone();
        let job = Arc::new(Job { init, firsts, dict, verdicts, frontier, lvl, chunk, next: AtomicUsize::new(0), stop: AtomicUsize::new(usize::MAX), fps: self.fps.clone() });
        for tx in &self.txs {
            tx.send(ToWorker::Level(job.clone())).expect("a worker thread stopped unexpectedly");
        }
        job
    }
    /// Has the workers run a claim (see `Claim`).
    fn claim(&mut self, c: Arc<Claim>) {
        for tx in &self.txs {
            tx.send(ToWorker::Claim(c.clone())).expect("a worker thread stopped unexpectedly");
        }
        drop(c);
        self.wait_finished();
    }
    fn wait_finished(&mut self) {
        let mut done = 0;
        while done < self.txs.len() {
            if let FromWorker::Finished = self.rx.recv().expect("a worker thread stopped unexpectedly") {
                done += 1;
            }
        }
    }
    /// Makes room in the fingerprint set for `more` fingerprints; the workers move a segmented set.
    fn make_room(&mut self, more: usize) {
        let fps = Arc::get_mut(&mut self.fps).expect("parallel search: the fingerprint set is still shared");
        while !fps.segmented() {
            fps.grow();
        }
        let mut cap = fps.capacity();
        while (fps.len() + more) * 2 >= cap {
            cap *= 2;
        }
        if cap == fps.capacity() {
            return;
        }
        let old = std::mem::replace(fps, FpSet::with_capacity(2));
        let new = old.empty_like(cap);
        let g = Arc::new(Grow { old, new, next: AtomicUsize::new(0) });
        for tx in &self.txs {
            tx.send(ToWorker::Grow(g.clone())).expect("a worker thread stopped unexpectedly");
        }
        self.wait_finished();
        let g = Arc::into_inner(g).expect("parallel search: a worker still holds the fingerprint set");
        *Arc::get_mut(&mut self.fps).expect("parallel search: the fingerprint set is still shared") = g.new;
    }
    /// Has the workers expand a level; the reports sorted by position, and where they stopped.
    fn run(&mut self, init: bool, frontier: Arc<Batch>, lvl: u32, chunk: usize) -> (Vec<ChunkOut>, usize) {
        self.run_with(init, frontier, lvl, chunk, None, None)
    }
    fn run_with(&mut self, init: bool, frontier: Arc<Batch>, lvl: u32, chunk: usize, firsts: Option<Firsts>, dict: Option<Arc<Dict>>) -> (Vec<ChunkOut>, usize) {
        let job = self.start_job_with(init, frontier, lvl, chunk, firsts, dict);
        let mut chunks = vec![];
        let mut done = 0;
        while done < self.txs.len() {
            match self.rx.recv().expect("a worker thread stopped unexpectedly") {
                FromWorker::Chunk(c) => chunks.push(c),
                FromWorker::Done => done += 1,
                FromWorker::Ready(_) | FromWorker::Finished => {}
            }
        }
        chunks.sort_by_key(|c| c.start);
        (chunks, job.stop.load(Ordering::Relaxed))
    }
}
impl Drop for Engine {
    fn drop(&mut self) {
        for tx in &self.txs {
            let _ = tx.send(ToWorker::Exit);
        }
    }
}

// ---------- the main thread ----------
/// Merges the first `upto` states of a chunk of the level starting at state `a`: new states get ids (in
/// order), their encodings go to `found`. `put` and `get` are the fingerprint set.
#[allow(clippy::too_many_arguments)]
fn merge_chunk(ck: &mut Checker, de: &RefCell<De>, c: &ChunkOut, upto: usize, a: usize, lvl: u32, record: bool, found: &mut Batch, put: &mut dyn FnMut(u64, u32) -> Option<u32>, get: &dyn Fn(u64) -> Option<u32>) {
    let mut at = At::default();
    for k in 0..upto {
        merge_state(ck, de, c, k, &mut at, a, lvl, record, found, put, get);
    }
}
/// Where the successors of the next state of a chunk start: in its entries, and in its encodings.
#[derive(Default)]
struct At {
    ent: usize,
    byte: usize,
}
/// `merge_chunk` for state `k` of the chunk alone, whose successors start `at` (which moves past them).
#[allow(clippy::too_many_arguments)]
#[inline]
fn merge_state(ck: &mut Checker, de: &RefCell<De>, c: &ChunkOut, k: usize, at: &mut At, a: usize, lvl: u32, record: bool, found: &mut Batch, put: &mut dyn FnMut(u64, u32) -> Option<u32>, get: &dyn Fn(u64) -> Option<u32>) {
    let nvars = ck.model.vars.len();
    let sid = a + c.start + k;
    let (generated, entries) = c.src[k];
    ck.generated += generated;
    let mut fresh = 0u32;
    for _ in 0..entries {
        let e = &c.ent[at.ent];
        at.ent += 1;
        let bytes = &c.bytes[at.byte..at.byte + e.len as usize];
        at.byte += e.len as usize;
        let id = match e.kind {
            CAND => {
                let nid = ck.states.len() as u32;
                match put(e.fp, nid) {
                    None => {
                        ck.states.push(ck.empty.clone());
                        ck.parent.push(sid as u32);
                        ck.level.push(lvl + 1);
                        ck.act.push(e.act as i32);
                        if record {
                            ck.succ.push(vec![]);
                            ck.succ_act.push(vec![]);
                            if let Some(ss) = &mut ck.succ_state {
                                ss.push(vec![]);
                            }
                        }
                        found.bytes.extend_from_slice(bytes);
                        found.offs.push(found.bytes.len());
                        fresh += 1;
                        nid
                    }
                    Some(ex) => ex,
                }
            }
            DUP => get(e.fp).expect("parallel search: a duplicate without its original"),
            _ => e.fp as u32,
        };
        if record {
            ck.succ[sid].push(id);
            ck.succ_act[sid].push(e.act);
            if let Some(ss) = &mut ck.succ_state {
                ss[sid].push(de.borrow_mut().state(bytes, nvars));
            }
        }
    }
    ck.outdeg.push(fresh);
}
/// `merge_chunk` into the checker's own fingerprint set.
#[allow(clippy::too_many_arguments)]
fn merge_chunk_seq(ck: &mut Checker, de: &RefCell<De>, c: &ChunkOut, upto: usize, a: usize, lvl: u32, record: bool, found: &mut Batch) {
    let mut fps = std::mem::replace(&mut ck.fps, FpSet::with_capacity(2));
    {
        let cell = RefCell::new(&mut fps);
        merge_chunk(ck, de, c, upto, a, lvl, record, found, &mut |fp, id| cell.borrow_mut().put(fp, id), &|fp| cell.borrow().get(fp));
    }
    ck.fps = fps;
}

/// The parallel side of a `Checker`.
pub struct Par {
    cfg: ParConfig,
    engine: Option<Engine>,
    /// workers started at the beginning of the search, not yet known to be ready
    starting: Option<Engine>,
    /// the states found by parallel levels, by ascending first id
    store: Vec<Arc<Batch>>,
    /// the states the last parallel level found: the next level, already serialized
    next: Option<Arc<Batch>>,
    de: RefCell<De>,
    /// the numbers of values for numbered levels (see `Dict`); it outlives the workers, as the levels do
    dict: Arc<Dict>,
    t0: f64,
    off: bool,
    /// how often a level went back to the sequential search because of an order-dependent operator
    strikes: u32,
    /// for EVERYSTATE_PAR_DEBUG: levels and states searched by the workers, and why they stopped
    stats: (u64, u64, Option<String>),
    /// milliseconds: before the first parallel level, in the workers, in the merge
    times: (f64, f64, f64),
    /// per worker, over all its engines (EVERYSTATE_PAR_DEBUG)
    busy: Vec<Arc<Busy>>,
}

/// Called once before the search loop.
fn flags_of(ck: &Checker) -> Flags {
    Flags { check_deadlock: ck.opts.check_deadlock, record: ck.opts.record_graph, keep_states: ck.succ_state.is_some() }
}
pub fn prepare(ck: &mut Checker) {
    if let Some(cfg) = ck.opts.par.clone() {
        if cfg.workers > 1 {
            let t0 = ck.t_start;
            // (the workers load the specification while the first levels are searched sequentially)
            let busy: Vec<Arc<Busy>> = (0..cfg.workers).map(|_| Arc::default()).collect();
            let starting = Engine::spawn(&cfg, flags_of(ck), &busy).ok();
            ck.par = Some(Box::new(Par { cfg, engine: None, starting, store: vec![], next: None, de: RefCell::new(De::default()), dict: Arc::new(Dict::new()), t0, off: false, strikes: 0, stats: (0, 0, None), times: (0.0, 0.0, 0.0), busy }));
            ck.level_end = ck.head;
        }
    }
}

/// Called with the candidates for initial states, before any of them is looked at. Returns how many of
/// them (from the first) the workers have dealt with; the sequential code goes on with the rest.
pub fn init(ck: &mut Checker, found: &[StateRef], events: &mut dyn Events) -> usize {
    match ck.par.take() {
        Some(mut par) => {
            let done = par.init(ck, found, events);
            ck.par = Some(par);
            done
        }
        None => 0,
    }
}

/// Called at the first state of every level. True when the level (or its beginning, up to a state the
/// sequential search has to look at) was searched by the workers; `ck.head` has moved accordingly.
pub fn level(ck: &mut Checker, events: &mut dyn Events) -> bool {
    let mut par = match ck.par.take() {
        Some(p) => p,
        None => {
            ck.level_end = usize::MAX;
            return false;
        }
    };
    let r = par.level(ck, events);
    if par.off {
        ck.level_end = usize::MAX;
    }
    ck.par = Some(par);
    r
}

/// Rebuilds the states before `upto` that exist in serialized form only (for a periodic liveness check).
pub fn materialize_upto(ck: &mut Checker, upto: usize) {
    if let Some(mut par) = ck.par.take() {
        par.materialize_upto(ck, upto);
        ck.par = Some(par);
    }
}

/// Called when the search is over: the workers leave, and the states are rebuilt when the caller will
/// read them all (`-dump`, liveness).
pub fn finish(ck: &mut Checker) {
    if let Some(mut par) = ck.par.take() {
        if std::env::var_os("EVERYSTATE_PAR_DEBUG").is_some() {
            // Linux: CPU time of this thread and of all threads, in ms (the workers are still alive)
            let cpu = |path: &std::path::Path| std::fs::read_to_string(path).ok().and_then(|t| t.split_whitespace().next().and_then(|x| x.parse::<f64>().ok())).unwrap_or(0.0) / 1e6;
            let main = cpu(std::path::Path::new("/proc/thread-self/schedstat"));
            let all: f64 = std::fs::read_dir("/proc/self/task").map(|d| d.flatten().map(|e| cpu(&e.path().join("schedstat"))).sum()).unwrap_or(0.0);
            eprintln!("par cpu: {:.0} ms main thread, {:.0} ms other threads", main, all - main);
            eprintln!("par: {} levels, {} of {} states expanded by workers, {} handed back{}", par.stats.0, par.stats.1, ck.head, par.strikes, par.stats.2.as_ref().map_or(String::new(), |w| format!("; stopped: {}", w)));
            eprintln!("par times: {:.0} ms before, {:.0} ms workers, {:.0} ms merge, {:.0} ms total", par.times.0, par.times.1, par.times.2, ck.ev.host.borrow().now_ms() - par.t0);
            if par.stats.0 > 0 {
                for b in &par.busy {
                    let (ns, n) = (b.ns.load(Ordering::Relaxed), b.states.load(Ordering::Relaxed));
                    eprintln!("par: worker: {:.1} ms on levels, {} states, {:.0} ns per state", ns as f64 / 1e6, n, ns as f64 / n.max(1) as f64);
                }
            }
        }
        par.engine = None;
        par.starting = None;
        if ck.opts.record_graph {
            par.materialize(ck, 0);
            par.store = vec![];
        }
        ck.par = Some(par);
    }
}

impl Par {
    /// State `i`, which the parallel search found.
    pub fn load(&self, i: usize, nvars: usize) -> StateRef {
        let k = self.store.partition_point(|b| b.base <= i) - 1;
        let b = &self.store[k];
        match b.nums(i - b.base) {
            Some(xs) => {
                let mut de = self.de.borrow_mut();
                StateData::new(xs.iter().map(|&x| self.dict.value(&mut de, x)).collect())
            }
            None => self.de.borrow_mut().state(b.get(i - b.base), nvars),
        }
    }
    /// Rebuilds the states from `from` on that exist in serialized form only.
    fn materialize(&mut self, ck: &mut Checker, from: usize) {
        for i in from..ck.states.len() {
            if Rc::ptr_eq(&ck.states[i], &ck.empty) {
                ck.states[i] = self.load(i, ck.model.vars.len());
            }
        }
    }
    /// Rebuilds the states before `upto` that exist in serialized form only.
    fn materialize_upto(&mut self, ck: &mut Checker, upto: usize) {
        for i in 0..upto {
            if Rc::ptr_eq(&ck.states[i], &ck.empty) {
                ck.states[i] = self.load(i, ck.model.vars.len());
            }
        }
    }
    /// `merge_chunk_seq`, one state at a time, with the checks of temporal properties that
    /// `Checker::search` makes between two states, on the checker as the one-thread search has it at
    /// that point. True when one of them ends the search: its result is in `ck.live_hit`, and the rest
    /// of the level is dropped.
    #[allow(clippy::too_many_arguments)]
    fn merge_checked(&mut self, ck: &mut Checker, events: &mut dyn Events, c: &ChunkOut, upto: usize, a: usize, lvl: u32, record: bool, found: &mut Batch) -> bool {
        let nvars = ck.model.vars.len();
        // the fingerprint set is out of the checker while a state is merged (as in `merge_chunk_seq`),
        // and back in it while a check runs
        let mut fps = std::mem::replace(&mut ck.fps, FpSet::with_capacity(2));
        let mut at = At::default();
        for k in 0..upto {
            let sid = a + c.start + k;
            if sid == ck.live_next {
                // A periodic liveness check is due before state `sid`. The states it reads are those
                // expanded so far, all of them from earlier merges.
                std::mem::swap(&mut ck.fps, &mut fps);
                ck.head = sid;
                ck.cur_level = if sid > a { lvl } else { ck.cur_level };
                if found.len() > 0 {
                    ck.depth = ck.depth.max(lvl + 1);
                }
                self.materialize_upto(ck, sid);
                ck.sync_stats();
                let hit = crate::liveness::periodic(ck, events);
                std::mem::swap(&mut ck.fps, &mut fps);
                if let Some(r) = hit {
                    ck.fps = fps;
                    self.stop_at_violation(ck, r, found, "liveness violation in a periodic check");
                    return true;
                }
            }
            {
                let cell = RefCell::new(&mut fps);
                merge_state(ck, &self.de, c, k, &mut at, a, lvl, record, found, &mut |fp, id| cell.borrow_mut().put(fp, id), &|fp| cell.borrow().get(fp));
            }
            if ck.onfly.is_some() {
                // State `sid` is expanded: does it complete a counterexample to a safety-shaped temporal
                // property? The check reads expanded states only, which are in the store or rebuilt.
                std::mem::swap(&mut ck.fps, &mut fps);
                ck.head = sid + 1;
                ck.cur_level = lvl;
                if found.len() > 0 {
                    ck.depth = ck.depth.max(lvl + 1);
                }
                ck.sync_stats();
                let hit = crate::liveness::expanded(ck, sid, &mut |ck, i| if Rc::ptr_eq(&ck.states[i], &ck.empty) { self.load(i, nvars) } else { ck.states[i].clone() });
                std::mem::swap(&mut ck.fps, &mut fps);
                if let Some(r) = hit {
                    ck.fps = fps;
                    self.stop_at_violation(ck, r, found, "violation of a temporal property during the search");
                    return true;
                }
            }
        }
        ck.fps = fps;
        false
    }
    /// A temporal property checked during the search is violated, and the search ends with `r`. The
    /// states found so far are kept: the counterexample may lead through them.
    fn stop_at_violation(&mut self, ck: &mut Checker, r: crate::checker::CheckResult, found: &mut Batch, why: &str) {
        ck.live_hit = Some(r);
        if found.len() > 0 {
            self.store.push(Arc::new(std::mem::replace(found, Batch::new(ck.states.len()))));
        }
        self.off = true;
        self.engine = None;
        self.next = None;
        self.stats.2 = Some(why.into());
    }
    /// From here on the search is sequential.
    fn give_up(&mut self, ck: &mut Checker, events: &mut dyn Events, why: &str) {
        self.off = true;
        self.engine = None;
        self.starting = None;
        self.next = None;
        self.materialize(ck, ck.head);
        self.stats.2 = Some(why.to_string());
        events.note(&format!("The search continues with 1 worker instead of {}: {}.", self.cfg.workers, why));
    }

    /// A worker met a state that only the sequential search may expand (an operator whose effect depends
    /// on the order of exploration, a value that cannot be passed on). The sequential search finishes
    /// this level from that state on, which keeps every such effect in its sequential order; the next
    /// level goes to the workers again. They are replaced, because the abandoned evaluation may have left
    /// something behind in their evaluators. The third time is the last.
    fn strike(&mut self, ck: &mut Checker, events: &mut dyn Events, why: &str) {
        self.strikes += 1;
        if self.strikes >= 3 {
            return self.give_up(ck, events, why);
        }
        self.engine = None;
        self.next = None;
        self.materialize(ck, ck.head);
    }

    /// Whether `n` states are worth handing to the workers; starts them when they are. (Starting them
    /// takes a few milliseconds; a level of `BIG_LEVEL` states takes longer than that on one thread.)
    fn ready(&mut self, ck: &mut Checker, events: &mut dyn Events, n: usize) -> bool {
        if !self.off && crate::eval::WORKERS.load(Ordering::Relaxed) < 2 {
            self.give_up(ck, events, "the specification reads TLCGet(\"config\")");
        }
        if self.off || n < self.cfg.min_frontier || !(self.cfg.eager || n >= BIG_LEVEL || ck.ev.host.borrow().now_ms() - self.t0 >= 50.0) {
            return false;
        }
        if self.engine.is_none() {
            let ts = ck.ev.host.borrow().now_ms();
            let started = match self.starting.take() {
                Some(e) => Ok(e),
                None => Engine::spawn(&self.cfg, flags_of(ck), &self.busy),
            }
            .and_then(Engine::wait_ready);
            if std::env::var_os("EVERYSTATE_PAR_DEBUG").is_some() {
                eprintln!("par: workers started in {:.1} ms, {:.1} ms after the search began", ck.ev.host.borrow().now_ms() - ts, ts - self.t0);
            }
            match started {
                Ok(e) => self.engine = Some(e),
                Err(why) => {
                    self.give_up(ck, events, &why);
                    return false;
                }
            }
        }
        self.engine.as_mut().unwrap().verdicts = ck.verdicts().into();
        true
    }
    fn chunk(&self, n: usize) -> usize {
        if self.cfg.chunk > 0 { self.cfg.chunk } else { (n / (self.cfg.workers * 8)).clamp(1, 256) }
    }

    fn init(&mut self, ck: &mut Checker, cands: &[StateRef], events: &mut dyn Events) -> usize {
        let n = cands.len();
        let nvars = ck.model.vars.len();
        if !self.ready(ck, events, n) {
            return 0;
        }
        let mut f = Batch::new(0);
        for s in cands {
            if !ser_state(s, nvars, &mut f.bytes) {
                self.give_up(ck, events, UNSENDABLE);
                return 0;
            }
            f.offs.push(f.bytes.len());
        }
        let frontier = Arc::new(f);
        let t1 = ck.ev.host.borrow().now_ms();
        if self.stats.0 == 0 && self.times.0 == 0.0 {
            self.times.0 = t1 - self.t0;
        }
        let chunk = self.chunk(n);
        let eng = self.engine.as_mut().unwrap();
        std::mem::swap(&mut ck.fps, Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared"));
        let (chunks, stop) = eng.run(true, frontier.clone(), 1, chunk);
        let eng = self.engine.as_mut().unwrap();
        std::mem::swap(&mut ck.fps, Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared"));
        let t2 = ck.ev.host.borrow().now_ms();
        self.times.1 += t2 - t1;
        let p = stop.min(n);
        let record = ck.opts.record_graph;
        let mut found = Batch::new(ck.states.len());
        let mut pos = 0;
        let mut event: Option<Event> = None;
        for c in chunks {
            if c.start + c.done == p && c.event.is_some() {
                event = c.event;
            }
            if c.start >= p {
                continue;
            }
            assert_eq!(c.start, pos, "parallel search: a part of the initial states is missing");
            let upto = c.done.min(p - c.start);
            let mut ei = 0;
            for k in 0..upto {
                ck.generated += 1;
                ck.init_generated += 1;
                if c.src[k].1 == 0 {
                    continue;
                }
                let e = &c.ent[ei];
                ei += 1;
                let nid = ck.states.len() as u32;
                if ck.fps.put(e.fp, nid).is_none() {
                    ck.states.push(ck.empty.clone());
                    ck.parent.push(NO_PARENT);
                    ck.level.push(1);
                    ck.act.push(-1);
                    ck.inits.push(nid);
                    if record {
                        ck.succ.push(vec![]);
                        ck.succ_act.push(vec![]);
                        if let Some(ss) = &mut ck.succ_state {
                            ss.push(vec![]);
                        }
                    }
                    ck.depth = ck.depth.max(1);
                    ck.init_distinct += 1;
                    found.bytes.extend_from_slice(frontier.get(c.start + k));
                    found.offs.push(found.bytes.len());
                }
            }
            pos += upto;
        }
        assert_eq!(pos, p, "parallel search: a part of the initial states is missing");
        self.stats.1 += p as u64;
        self.times.2 += ck.ev.host.borrow().now_ms() - t2;
        if found.len() > 0 {
            let found = Arc::new(found);
            self.store.push(found.clone());
            if p == n {
                self.next = Some(found);
            }
        }
        if p < n {
            match event {
                Some(Event::Fallback(why)) => self.strike(ck, events, &why),
                _ => {
                    self.off = true;
                    self.engine = None;
                    self.next = None;
                    self.materialize(ck, 0);
                    self.stats.2 = Some("violation or error".into());
                }
            }
        }
        p
    }

    /// A level whose workers find successors as ids (`expand_ids`), without the state graph. In two
    /// steps, both on the workers: they expand the level, each chunk's candidates for new states in
    /// state order; then they put the candidates into the fingerprint set, each worker the fingerprints
    /// of its own segments of the set (`Claim`), in the order of the level, so that the first occurrence
    /// of a fingerprint is the one the sequential search meets first. The main thread only numbers the
    /// new states in that order. (The ids kept in the set are not those of the states: nothing reads
    /// them without the state graph.)
    fn level_ids(&mut self, ck: &mut Checker, events: &mut dyn Events, frontier: Arc<Batch>, lvl: u32, chunk: usize, t1: f64) -> bool {
        let (a, n) = (frontier.base, frontier.len());
        let eng = self.engine.as_mut().unwrap();
        std::mem::swap(&mut ck.fps, Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared"));
        // (room for a few new fingerprints per state; more than that only makes candidates)
        let firsts = Firsts::new((4 * n).next_power_of_two().max(1 << 12));
        let (chunks, stop) = eng.run_with(false, frontier, lvl, chunk, Some(firsts), Some(self.dict.clone()));
        let t2 = ck.ev.host.borrow().now_ms();
        self.times.1 += t2 - t1;
        // the level ends at the first state a worker stopped at
        let p = stop.min(n);
        let mut event: Option<Event> = None;
        let mut upto = Vec::with_capacity(chunks.len());
        let mut states = Vec::with_capacity(chunks.len());
        let mut cands = 0;
        let mut pos = 0;
        for c in &chunks {
            if c.start + c.done == p && c.event.is_some() {
                event = c.event.as_ref().map(|e| match e {
                    Event::Check => Event::Check,
                    Event::Fallback(w) => Event::Fallback(w.clone()),
                });
            }
            let u = if c.start >= p { 0 } else { c.done.min(p - c.start) };
            if u > 0 {
                assert_eq!(c.start, pos, "parallel search: a part of the level is missing");
                pos += u;
            }
            let e = c.src[..u].iter().map(|x| x.1 as usize).sum::<usize>();
            cands += e;
            states.push(u);
            upto.push(e);
        }
        assert_eq!(pos, p, "parallel search: a part of the level is missing");
        eng.make_room(cands);
        let wins = (0..CLAIM_GROUPS).map(|_| Default::default()).collect();
        let claim = Arc::new(Claim { chunks, upto, fps: eng.fps.clone(), next: AtomicUsize::new(0), wins });
        let tb = ck.ev.host.borrow().now_ms();
        eng.claim(claim.clone());
        let tc = ck.ev.host.borrow().now_ms();
        let Claim { chunks, wins, fps: shared, .. } = Arc::into_inner(claim).expect("parallel search: a worker still holds the claim");
        // per chunk, one bit per entry: a new state
        let mut win: Vec<Vec<u64>> = chunks.iter().map(|c| vec![0; c.ent.len().div_ceil(64)]).collect();
        let mut news = 0;
        for w in wins {
            let w = w.into_inner().unwrap();
            news += w.len();
            for (ci, ei) in w {
                win[ci as usize][ei as usize / 64] |= 1 << (ei % 64);
            }
        }
        drop(shared);
        std::mem::swap(&mut ck.fps, Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared"));
        // the new states, numbered in the order of the level
        let nv = ck.model.vars.len();
        let mut found = Batch::numbered(ck.states.len(), nv);
        ck.states.reserve(news);
        ck.parent.reserve(news);
        ck.level.reserve(news);
        ck.act.reserve(news);
        ck.outdeg.reserve(p);
        let nums = &mut found.nums.as_mut().unwrap().1;
        nums.reserve(news * nv);
        for (ci, c) in chunks.iter().enumerate() {
            debug_assert!(c.bytes.is_empty(), "a numbered level has no encodings");
            let mut ei = 0;
            for k in 0..states[ci] {
                let sid = a + c.start + k;
                let (generated, entries) = c.src[k];
                ck.generated += generated;
                let mut fresh = 0u32;
                for _ in 0..entries {
                    let e = &c.ent[ei];
                    if win[ci][ei / 64] >> (ei % 64) & 1 == 1 {
                        ck.states.push(ck.empty.clone());
                        ck.parent.push(sid as u32);
                        ck.level.push(lvl + 1);
                        ck.act.push(e.act as i32);
                        nums.extend_from_slice(&c.nums[ei * nv..(ei + 1) * nv]);
                        fresh += 1;
                    }
                    ei += 1;
                }
                ck.outdeg.push(fresh);
            }
        }
        debug_assert!(NO_PARENT as usize > ck.states.len());
        if std::env::var_os("EVERYSTATE_PAR_DEBUG").is_some() {
            let td = ck.ev.host.borrow().now_ms();
            eprintln!("par: level {}: {} states, {} candidates, {} new; expand {:.1} ms, prepare {:.1} ms, claim {:.1} ms, number {:.1} ms", lvl, p, cands, found.len(), t2 - t1, tb - t2, tc - tb, td - tc);
        }
        ck.head = a + p;
        ck.cur_level = lvl;
        self.stats.0 += 1;
        self.stats.1 += p as u64;
        self.times.2 += ck.ev.host.borrow().now_ms() - t2;
        self.end_level(ck, events, found, p == n, event)
    }

    fn level(&mut self, ck: &mut Checker, events: &mut dyn Events) -> bool {
        let (a, b) = (ck.head, ck.states.len());
        let n = b - a;
        let nvars = ck.model.vars.len();
        if !self.ready(ck, events, n) {
            // this level is searched sequentially
            self.next = None;
            self.materialize(ck, a);
            return false;
        }
        let frontier = match self.next.take() {
            Some(f) if f.base == a && f.len() == n => f,
            _ => {
                let mut f = Batch::new(a);
                for i in a..b {
                    if !ser_state(&ck.states[i], nvars, &mut f.bytes) {
                        self.give_up(ck, events, UNSENDABLE);
                        return false;
                    }
                    f.offs.push(f.bytes.len());
                }
                Arc::new(f)
            }
        };
        let lvl = ck.level[a];
        let chunk = self.chunk(n);
        let t1 = ck.ev.host.borrow().now_ms();
        if self.stats.0 == 0 && self.times.0 == 0.0 {
            self.times.0 = t1 - self.t0;
        }
        if ck.is_flat() && !ck.opts.record_graph && ck.caching() && !ck.checks_during_search() {
            // (the workers find successors as ids: see `level_ids`, which records no graph and checks
            // nothing between two states; temporal properties record the graph anyway)
            return self.level_ids(ck, events, frontier, lvl, chunk, t1);
        }
        let eng = self.engine.as_mut().unwrap();
        // The workers read the fingerprint set while they run, and the chunks they finish are merged
        // meanwhile, in state order, into the same set (which has room for them; see `FpSet`). A chunk
        // is merged early only when it and every chunk before it are whole; the rest waits for the end
        // of the level, when it is known where the workers stopped. So does the rest of the level once
        // the set has no room left without growing, which it can do only when nobody reads it.
        let fps_now = Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared");
        std::mem::swap(&mut ck.fps, fps_now);
        let job = eng.start_job(false, frontier, lvl, chunk);
        let record = ck.opts.record_graph;
        let mut found = Batch::new(b);
        let mut pos = 0;
        let mut pending: std::collections::BTreeMap<usize, ChunkOut> = Default::default();
        // Temporal properties checked during the search are checked between two states of the merge,
        // which then runs at the end of the level only, in state order (see `merge_checked`).
        let checked = ck.checks_during_search();
        let mut early = !checked;
        let mut merge_ms = 0.0;
        let mut done = 0;
        while done < eng.txs.len() {
            match eng.rx.recv().expect("a worker thread stopped unexpectedly") {
                FromWorker::Chunk(c) => {
                    pending.insert(c.start, c);
                }
                FromWorker::Done => done += 1,
                FromWorker::Ready(_) | FromWorker::Finished => {}
            }
            while early {
                let whole = match pending.get(&pos) {
                    Some(c) => c.event.is_none() && c.done == chunk.min(n - c.start),
                    None => break,
                };
                let c = pending.remove(&pos).unwrap();
                let cands = c.ent.iter().filter(|e| e.kind == CAND).count();
                if !whole || !job.fps.room(cands) {
                    pending.insert(c.start, c);
                    early = false;
                    break;
                }
                let tm = ck.ev.host.borrow().now_ms();
                merge_chunk(ck, &self.de, &c, c.done, a, lvl, record, &mut found, &mut |fp, id| job.fps.put_shared(fp, id).expect("parallel search: no room in the fingerprint set"), &|fp| job.fps.get(fp));
                merge_ms += ck.ev.host.borrow().now_ms() - tm;
                pos += c.done;
            }
        }
        let stop = job.stop.load(Ordering::Relaxed);
        drop(job);
        let eng = self.engine.as_mut().unwrap();
        let fps_now = Arc::get_mut(&mut eng.fps).expect("parallel search: the fingerprint set is still shared");
        std::mem::swap(&mut ck.fps, fps_now);

        let t2 = ck.ev.host.borrow().now_ms();
        self.times.1 += t2 - t1;
        self.times.2 += merge_ms;
        // merge, in state order, everything before the first state a worker stopped at
        let p = stop.min(n);
        let mut event: Option<Event> = None;
        for (_, mut c) in pending {
            if c.start + c.done == p && c.event.is_some() {
                event = c.event.take();
            }
            if c.start >= p {
                continue;
            }
            assert_eq!(c.start, pos, "parallel search: a part of the level is missing");
            let upto = c.done.min(p - c.start);
            if !checked {
                merge_chunk_seq(ck, &self.de, &c, upto, a, lvl, record, &mut found);
            } else if self.merge_checked(ck, events, &c, upto, a, lvl, record, &mut found) {
                return true;
            }
            pos += upto;
        }
        assert_eq!(pos, p, "parallel search: a part of the level is missing");
        debug_assert!(NO_PARENT as usize > ck.states.len());
        ck.head = a + p;
        ck.cur_level = lvl;
        self.stats.0 += 1;
        self.stats.1 += p as u64;
        self.times.2 += ck.ev.host.borrow().now_ms() - t2;
        self.end_level(ck, events, found, p == n, event)
    }
    /// After a level: `found` is the next one (`complete`: the workers expanded the whole level), else
    /// the sequential search takes over at `ck.head` because of `event`.
    fn end_level(&mut self, ck: &mut Checker, events: &mut dyn Events, found: Batch, complete: bool, event: Option<Event>) -> bool {
        let lvl = ck.cur_level;
        if found.len() > 0 {
            ck.depth = ck.depth.max(lvl + 1);
            let found = Arc::new(found);
            self.store.push(found.clone());
            if complete {
                self.next = Some(found);
            }
        }
        if !complete {
            match event {
                Some(Event::Fallback(why)) => self.strike(ck, events, &why),
                _ => {
                    // the sequential search re-expands state `head` and reports what the worker met
                    self.off = true;
                    self.engine = None;
                    self.next = None;
                    self.materialize(ck, ck.head);
                    self.stats.2 = Some("violation or error".into());
                }
            }
            return true;
        }
        let now = ck.ev.host.borrow().now_ms();
        if now - ck.last_progress > 60000.0 {
            ck.last_progress = now;
            events.progress(ck.depth, ck.generated, ck.states.len() as u64, (ck.states.len() - ck.head) as u64);
        }
        true
    }
}