legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
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
//! An index's change log on disk: one append-only file of framed, checksummed records, a task's
//! entries and then its commit, written in one write and made durable before the task is answered.
//!
//! # The format
//!
//! The file `changes.log` in the index's state directory is a run of records. Every record is
//! framed the same way, all integers little-endian:
//!
//! | Bytes | Field |
//! |---|---|
//! | 4 | [`MAGIC`], `a5 4c 48 5a` |
//! | 4 | `length`: the bytes of `kind` and `payload`, 1 to [`MAX_RECORD`] |
//! | 1 | `kind`: `H` header, `E` entry, `T` task |
//! | `length − 1` | `payload` |
//! | 4 | CRC-32C (Castagnoli) of `length`, `kind` and `payload` |
//!
//! - **`H`, the header**, the first record and only there: the version (`u32`, 1), the width
//!   (`u16`, 64 or 256), `base_seq` (`u64`: every change up to it has been dropped, so the next seq
//!   is above it), then the format name `legit-hamming-log` and the index's name, each a `u8`
//!   length and its bytes.
//! - **`E`, an entry**, one a record of a change task: its `seq` (`u64`), the task's number in the
//!   file (`u64`), the operation (`u8`: `S` set or `R` remove), the id (`u64`), and for a set the
//!   value, 8 or 32 bytes, an unsigned little-endian integer as a snapshot stores it.
//! - **`T`, a task**, after its entries: its number (`u64`), the first entry's `seq` (`u64`), how
//!   many entries it has (`u32`), its `task_name` (`u8`: `A` append, `P` replace, `R` remove), its
//!   outcome (`u8`: 0 applied, 1 conflict), the `seq` its result gave (`u64`), its counts added,
//!   changed, removed and unchanged (`u32` each), when it was applied (`u64`, Unix milliseconds),
//!   for a conflict the conflicting records' count (`u32`) and up to 100 of their ids (a `u8`
//!   count and `u64`s), and its `task_id` (a `u8` length and its bytes: 1 to 64 of `A-Z`, `a-z`,
//!   `0-9`, `_` and `-`).
//!
//! Tasks are numbered from 1, one after another, in the file; entries' `seq`s rise by one from
//! entry to entry, across tasks, and the first entry in the file is at most one above `base_seq`;
//! it is at or below it only for a task that straddles it, whose last entry is above. An applied
//! task's counts add up to its entries; one kept without its entries was covered (its `seq` is at
//! most `base_seq`); a conflict has no entries. No two tasks share a `task_id`. A task is whole
//! when its entries are followed by its own `T` record, which names as many entries as went before
//! it. Nothing is written that can't be read back: a field too long for its length byte refuses
//! the task before a byte is written.
//!
//! # Recovery
//!
//! A task's records are written in one call and made durable (`fdatasync`) before its result is
//! written, so a crash can leave only the last task unfinished: some of its records, whole or
//! torn, with or without its `T` record, perhaps with blocks of zeros among them. Reading keeps
//! every whole task, and at the first record that isn't whole (its frame or checksum is wrong),
//! looks at everything from the end of the last whole task on:
//!
//! - if every whole, valid record there belongs to the one task after the last whole one, that
//!   task never finished, and it is cut: the bytes are dropped (the file is truncated when it is
//!   opened for writing) and the log line says how many;
//! - if any belongs to another task, or is a header, the damage is in the middle of the log, not
//!   at its end: the index is refused rather than guessing which changes stood.
//!
//! A record that is whole but breaks a rule above is no unfinished write: it refuses the index. A
//! damaged last task can't be told from one that never finished, and is cut the same way: the log
//! trusts that what `fdatasync` made durable reads back.
//!
//! Opening a log to write it always makes it durable before anything in it is used: the file is
//! cut if it must be, then synced, and its directory synced, so a task a process wrote before it
//! died, and that a restart reads whole, is durable before a repeat of it is answered from it.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use crate::value::Value;

/// The log file's name in an index's state directory.
pub const LOG_FILE: &str = "changes.log";

/// The lock file's name in an index's state directory: held exclusively by the one process that
/// writes the log.
pub const LOCK_FILE: &str = "LOCK";

/// How long opening a log waits for its lock before another holder counts: long enough for a
/// child process that holds a copy of it between its fork and its exec to drop it.
const LOCK_WAIT: Duration = Duration::from_secs(1);

/// The file a shortened log is written to before it replaces the log.
pub const NEW_FILE: &str = "changes.log.new";

/// The format name in a log's header.
pub const FORMAT: &str = "legit-hamming-log";

/// The version of the format this crate reads and writes.
pub const VERSION: u32 = 1;

/// The four bytes every record begins with.
pub const MAGIC: [u8; 4] = [0xa5, 0x4c, 0x48, 0x5a];

/// The most bytes a record's `kind` and `payload` take.
pub const MAX_RECORD: usize = 4096;

/// The longest `task_id` a change task may give, in bytes.
pub const TASK_ID_MAX: usize = 64;

/// The most conflicting ids a task record keeps.
const CONFLICT_IDS: usize = super::error::CONFLICT_IDS;

/// The bytes of framing around a payload: magic, length, kind, checksum.
const FRAME: usize = 4 + 4 + 1 + 4;

/// The bytes of an entry record at `width` bits that sets a value.
const fn entry_bytes(width: u32) -> usize {
    FRAME + 8 + 8 + 1 + 8 + width as usize / 8
}

/// The bytes of an entry record that removes an id.
const REMOVE_BYTES: usize = FRAME + 8 + 8 + 1 + 8;

/// The bytes of a task record without its conflicting ids and its `task_id`.
const TASK_RECORD_FIXED: usize = FRAME + 8 + 8 + 4 + 1 + 1 + 8 + 16 + 8 + 4 + 1 + 1;

/// The most bytes a task record takes.
const TASK_RECORD_MAX: usize = TASK_RECORD_FIXED + CONFLICT_IDS * 8 + TASK_ID_MAX;

/// The most bytes a change task of `records` records takes in the log at `width` bits, or `None`
/// when that is more than a `u64` holds.
#[must_use]
pub const fn task_bytes(width: u32, records: usize) -> Option<u64> {
    match records.checked_mul(entry_bytes(width)) {
        Some(entries) => match entries.checked_add(TASK_RECORD_MAX) {
            Some(bytes) => Some(bytes as u64),
            None => None,
        },
        None => None,
    }
}

/// The exact bytes a task takes in the log: `sets` entries setting a value and `removes` removing
/// one at `width` bits, `conflicts` conflicting ids listed (at most [`CONFLICT_IDS`] are), and a
/// `task_id` of `task_id` bytes. `None` when it can't be counted in a `u64`.
pub(crate) fn framed_bytes(width: u32, sets: usize, removes: usize, conflicts: usize, task_id: usize) -> Option<u64> {
    let entries = sets
        .checked_mul(entry_bytes(width))?
        .checked_add(removes.checked_mul(REMOVE_BYTES)?)?;
    let task = TASK_RECORD_FIXED
        .checked_add(conflicts.min(CONFLICT_IDS) * 8)?
        .checked_add(task_id)?;
    u64::try_from(entries.checked_add(task)?).ok()
}

/// Whether `task_id` is one a change task may give: 1 to [`TASK_ID_MAX`] of `A-Z`, `a-z`, `0-9`,
/// `_` and `-`, as the stream contract's task ids are.
#[must_use]
pub fn is_valid_task_id(task_id: &str) -> bool {
    (1..=TASK_ID_MAX).contains(&task_id.len())
        && task_id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}

/// A change task's name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum ChangeName {
    Append,
    Replace,
    Remove,
}

impl ChangeName {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Append => "append",
            Self::Replace => "replace",
            Self::Remove => "remove",
        }
    }

    const fn code(self) -> u8 {
        match self {
            Self::Append => b'A',
            Self::Replace => b'P',
            Self::Remove => b'R',
        }
    }

    const fn from_code(code: u8) -> Option<Self> {
        match code {
            b'A' => Some(Self::Append),
            b'P' => Some(Self::Replace),
            b'R' => Some(Self::Remove),
            _ => None,
        }
    }
}

/// What a change task's records did to the index, as its result reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Tally {
    pub(crate) added: u32,
    pub(crate) changed: u32,
    pub(crate) removed: u32,
    pub(crate) unchanged: u32,
}

impl Tally {
    /// The records counted.
    fn total(self) -> u64 {
        u64::from(self.added) + u64::from(self.changed) + u64::from(self.removed) + u64::from(self.unchanged)
    }
}

/// How a change task was answered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Outcome {
    /// Its changes were applied, and its result gave `seq`.
    Applied { seq: u64, tally: Tally },
    /// An `append` met ids held with other values, and nothing was applied.
    Conflict { ids: Vec<u64>, count: u32 },
}

/// A change task as the log records it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TaskRecord {
    pub(crate) task_id: String,
    pub(crate) name: ChangeName,
    pub(crate) outcome: Outcome,
    /// When it was applied, in Unix milliseconds.
    pub(crate) applied_at: u64,
    /// The first entry's `seq`, or the position before it when it has none.
    pub(crate) first_seq: u64,
    /// The entries it has in the file: 0 for a conflict, and for a task kept only so a repeat of
    /// it is recognised after its entries were dropped.
    pub(crate) entries: u32,
}

impl TaskRecord {
    /// The last entry's `seq`, if it has entries. A record read from a log, or planned, never
    /// overflows: both are checked. The entries after the first are added, not all of them less
    /// one, so a task whose last entry is `u64::MAX` ends there.
    pub(crate) fn last_seq(&self) -> Option<u64> {
        (self.entries > 0).then(|| self.first_seq.saturating_add(u64::from(self.entries - 1)))
    }
}

/// One change: an id set to a value, or removed. The value is its words, most significant first,
/// of which the width's first one or four are used.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Entry {
    pub(crate) seq: u64,
    pub(crate) id: u64,
    pub(crate) value: Option<[u64; 4]>,
}

impl Entry {
    /// The entry's value at `V`'s width.
    pub(crate) fn value<V: Value>(&self) -> Option<V> {
        self.value.map(|words| V::from_words(&words[..V::WORDS]))
    }

    /// An entry setting `id` to `value`, or removing it.
    pub(crate) fn new<V: Value>(seq: u64, id: u64, value: Option<V>) -> Self {
        Self {
            seq,
            id,
            value: value.map(|value| {
                let mut words = [0; 4];
                for (index, word) in words.iter_mut().take(V::WORDS).enumerate() {
                    *word = value.word(index);
                }
                words
            }),
        }
    }
}

/// A log's header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Header {
    pub(crate) index: String,
    pub(crate) width: u32,
    pub(crate) base_seq: u64,
}

/// A log read back: its header, its whole tasks and their entries, and what was cut.
#[derive(Debug, Clone, Default)]
pub(crate) struct Parsed {
    pub(crate) header: Option<Header>,
    /// Every whole task, in order, with the range of its entries in `entries`.
    pub(crate) tasks: Vec<(TaskRecord, std::ops::Range<usize>)>,
    pub(crate) entries: Vec<Entry>,
    /// The bytes of the whole tasks and the header: where the next task is written.
    pub(crate) end: u64,
    /// The bytes after `end` that were an unfinished task, and how many of its entries were whole.
    pub(crate) cut: Option<(u64, usize)>,
}

impl Parsed {
    /// The base `seq` from the header: 0 for a log that doesn't exist yet.
    pub(crate) fn base_seq(&self) -> u64 {
        self.header.as_ref().map_or(0, |header| header.base_seq)
    }

    /// The log's position: the last `seq` given, or the base when no entry is left.
    pub(crate) fn last_seq(&self) -> u64 {
        self.entries.last().map_or(0, |entry| entry.seq).max(self.base_seq())
    }
}

/// Why a log can't be used: a short code, for `stats` and the log line, and what was found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LogError {
    /// `no_header`, `other_index`, `damaged`, `invalid`, `too_large`, `unreadable`, `sync_failed`,
    /// `symlink`, or for a live writer's read at a swap, `missing`, `replaced`, `appeared`,
    /// `changed` or `cut`.
    pub(crate) code: &'static str,
    pub(crate) message: String,
}

impl LogError {
    fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

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

/// A field too long for the log's format: the task is refused before anything is written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Unrepresentable(pub(crate) &'static str);

/// A record decoded.
enum Record {
    Header(Header),
    Entry { task: u64, entry: Entry },
    Task { number: u64, record: TaskRecord },
}

/// The CRC-32C lookup table, computed at compile time.
const CRC_TABLE: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut index = 0;
    while index < 256 {
        let mut crc = index as u32;
        let mut bit = 0;
        while bit < 8 {
            crc = if crc & 1 == 1 {
                (crc >> 1) ^ 0x82f6_3b78
            } else {
                crc >> 1
            };
            bit += 1;
        }
        table[index] = crc;
        index += 1;
    }
    table
};

/// The CRC-32C (Castagnoli) of `bytes`, as iSCSI and ext4 compute it.
pub(crate) fn crc32c(bytes: &[u8]) -> u32 {
    !bytes.iter().fold(!0u32, |crc, &byte| {
        CRC_TABLE[((crc ^ u32::from(byte)) & 0xff) as usize] ^ (crc >> 8)
    })
}

/// Append one framed record of `kind` and `payload` to `out`.
fn frame(out: &mut Vec<u8>, kind: u8, payload: &[u8]) -> Result<(), Unrepresentable> {
    if payload.len() >= MAX_RECORD {
        return Err(Unrepresentable("record"));
    }
    let length = u32::try_from(payload.len() + 1).map_err(|_| Unrepresentable("record"))?;
    out.extend_from_slice(&MAGIC);
    let start = out.len();
    out.extend_from_slice(&length.to_le_bytes());
    out.push(kind);
    out.extend_from_slice(payload);
    let crc = crc32c(&out[start..]);
    out.extend_from_slice(&crc.to_le_bytes());
    Ok(())
}

/// Push `text`'s length as a byte and its bytes, or refuse a text longer than a byte counts.
fn push_text(payload: &mut Vec<u8>, text: &str, field: &'static str) -> Result<(), Unrepresentable> {
    payload.push(u8::try_from(text.len()).map_err(|_| Unrepresentable(field))?);
    payload.extend_from_slice(text.as_bytes());
    Ok(())
}

fn header_record(out: &mut Vec<u8>, header: &Header) -> Result<(), Unrepresentable> {
    let mut payload = Vec::with_capacity(64);
    payload.extend_from_slice(&VERSION.to_le_bytes());
    if !matches!(header.width, 64 | 256) {
        return Err(Unrepresentable("width"));
    }
    payload.extend_from_slice(
        &u16::try_from(header.width)
            .map_err(|_| Unrepresentable("width"))?
            .to_le_bytes(),
    );
    payload.extend_from_slice(&header.base_seq.to_le_bytes());
    push_text(&mut payload, FORMAT, "format")?;
    push_text(&mut payload, &header.index, "index")?;
    frame(out, b'H', &payload)
}

fn entry_record(out: &mut Vec<u8>, width: u32, task: u64, entry: &Entry) -> Result<(), Unrepresentable> {
    let mut payload = Vec::with_capacity(64);
    payload.extend_from_slice(&entry.seq.to_le_bytes());
    payload.extend_from_slice(&task.to_le_bytes());
    match entry.value {
        Some(words) => {
            payload.push(b'S');
            payload.extend_from_slice(&entry.id.to_le_bytes());
            let used = width as usize / 64;
            // Little-endian, least significant word first, as a snapshot stores a value...
            for word in words[..used].iter().rev() {
                payload.extend_from_slice(&word.to_le_bytes());
            }
        }
        None => {
            payload.push(b'R');
            payload.extend_from_slice(&entry.id.to_le_bytes());
        }
    }
    frame(out, b'E', &payload)
}

fn task_record(out: &mut Vec<u8>, number: u64, record: &TaskRecord) -> Result<(), Unrepresentable> {
    if !is_valid_task_id(&record.task_id) {
        return Err(Unrepresentable("task_id"));
    }
    let mut payload = Vec::with_capacity(128);
    payload.extend_from_slice(&number.to_le_bytes());
    payload.extend_from_slice(&record.first_seq.to_le_bytes());
    payload.extend_from_slice(&record.entries.to_le_bytes());
    payload.push(record.name.code());
    let (outcome, seq, tally, count, ids): (u8, u64, Tally, u32, &[u64]) = match &record.outcome {
        Outcome::Applied { seq, tally } => (0, *seq, *tally, 0, &[]),
        Outcome::Conflict { ids, count } => (1, record.first_seq, Tally::default(), *count, ids),
    };
    if ids.len() > CONFLICT_IDS {
        return Err(Unrepresentable("conflict ids"));
    }
    payload.push(outcome);
    payload.extend_from_slice(&seq.to_le_bytes());
    for count in [tally.added, tally.changed, tally.removed, tally.unchanged] {
        payload.extend_from_slice(&count.to_le_bytes());
    }
    payload.extend_from_slice(&record.applied_at.to_le_bytes());
    payload.extend_from_slice(&count.to_le_bytes());
    payload.push(u8::try_from(ids.len()).map_err(|_| Unrepresentable("conflict ids"))?);
    for id in ids {
        payload.extend_from_slice(&id.to_le_bytes());
    }
    push_text(&mut payload, &record.task_id, "task_id")?;
    frame(out, b'T', &payload)
}

/// A reader of a payload's fields, which fails at the end rather than panicking.
struct Fields<'a>(&'a [u8]);

impl Fields<'_> {
    fn take(&mut self, count: usize) -> Option<&[u8]> {
        let (head, rest) = self.0.split_at_checked(count)?;
        self.0 = rest;
        Some(head)
    }

    fn u8(&mut self) -> Option<u8> {
        self.take(1).map(|bytes| bytes[0])
    }

    fn u16(&mut self) -> Option<u16> {
        self.take(2).map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]]))
    }

    fn u32(&mut self) -> Option<u32> {
        self.take(4)
            .map(|bytes| u32::from_le_bytes(bytes.try_into().expect("four bytes")))
    }

    fn u64(&mut self) -> Option<u64> {
        self.take(8)
            .map(|bytes| u64::from_le_bytes(bytes.try_into().expect("eight bytes")))
    }

    fn text(&mut self) -> Option<String> {
        let length = usize::from(self.u8()?);
        String::from_utf8(self.take(length)?.to_vec()).ok()
    }

    fn done(&self) -> bool {
        self.0.is_empty()
    }
}

/// The record at `at` in `bytes`, decoded at `width` bits (or any width for a header), and where
/// the next one begins; `None` unless it is whole, framed, checksummed and well-formed.
fn read_record(bytes: &[u8], at: usize, width: u32) -> Option<(Record, usize)> {
    let rest = bytes.get(at..)?;
    if rest.get(..4)? != MAGIC {
        return None;
    }
    let length = u32::from_le_bytes(rest.get(4..8)?.try_into().ok()?) as usize;
    if !(1..=MAX_RECORD).contains(&length) {
        return None;
    }
    let body = rest.get(4..8 + length)?;
    let stored = u32::from_le_bytes(rest.get(8 + length..12 + length)?.try_into().ok()?);
    if crc32c(body) != stored {
        return None;
    }
    let kind = body[4];
    let mut fields = Fields(&body[5..]);
    let record = match kind {
        b'H' => {
            let version = fields.u32()?;
            let width = u32::from(fields.u16()?);
            let base_seq = fields.u64()?;
            let format = fields.text()?;
            let index = fields.text()?;
            if version != VERSION || format != FORMAT || !matches!(width, 64 | 256) {
                return None;
            }
            Record::Header(Header { index, width, base_seq })
        }
        b'E' => {
            let seq = fields.u64()?;
            let task = fields.u64()?;
            let op = fields.u8()?;
            let id = fields.u64()?;
            let value = match op {
                b'S' => {
                    let used = width as usize / 64;
                    let mut words = [0u64; 4];
                    for index in (0..used).rev() {
                        words[index] = fields.u64()?;
                    }
                    Some(words)
                }
                b'R' => None,
                _ => return None,
            };
            Record::Entry {
                task,
                entry: Entry { seq, id, value },
            }
        }
        b'T' => {
            let number = fields.u64()?;
            let first_seq = fields.u64()?;
            let entries = fields.u32()?;
            let name = ChangeName::from_code(fields.u8()?)?;
            let outcome_code = fields.u8()?;
            let seq = fields.u64()?;
            let tally = Tally {
                added: fields.u32()?,
                changed: fields.u32()?,
                removed: fields.u32()?,
                unchanged: fields.u32()?,
            };
            let applied_at = fields.u64()?;
            let count = fields.u32()?;
            let listed = usize::from(fields.u8()?);
            let ids = (0..listed).map(|_| fields.u64()).collect::<Option<Vec<_>>>()?;
            let task_id = fields.text()?;
            let outcome = match outcome_code {
                0 if count == 0 && ids.is_empty() => Outcome::Applied { seq, tally },
                1 if tally == Tally::default() && seq == first_seq => Outcome::Conflict { ids, count },
                _ => return None,
            };
            Record::Task {
                number,
                record: TaskRecord {
                    task_id,
                    name,
                    outcome,
                    applied_at,
                    first_seq,
                    entries,
                },
            }
        }
        _ => return None,
    };
    fields.done().then_some((record, at + 12 + length))
}

/// Why a whole task record doesn't keep the log's rules, given the entries before it, the
/// header's base, and whether an entry came before it in the file; `None` when it does.
fn task_fault(record: &TaskRecord, pending: &[Entry], base: u64, entries_before: bool) -> Option<&'static str> {
    if !is_valid_task_id(&record.task_id) {
        return Some("a task's id isn't 1 to 64 of `A-Z`, `a-z`, `0-9`, `_` and `-`");
    }
    if record.entries as usize != pending.len() {
        return Some("a task names another number of entries than precede it");
    }
    match &record.outcome {
        Outcome::Applied { seq, tally } => match (pending.first(), pending.last()) {
            (Some(first), Some(last)) => {
                if first.seq != record.first_seq || last.seq != *seq {
                    return Some("a task's seqs aren't its entries'");
                }
                if tally.total() != u64::from(record.entries) {
                    return Some("an applied task's counts don't add up to its entries");
                }
                if !entries_before && (first.seq > base.saturating_add(1) || last.seq <= base) {
                    return Some("the first entry in the log doesn't follow the header's base_seq");
                }
                None
            }
            _ => {
                // Kept only for its repeat: its changes were covered and dropped...
                if *seq > base || tally.total() == 0 {
                    return Some("a task kept without its entries isn't covered by the header's base_seq");
                }
                None
            }
        },
        Outcome::Conflict { ids, count } => {
            if !pending.is_empty() || ids.len() > CONFLICT_IDS || (*count as usize) < ids.len() || *count == 0 {
                return Some("a conflict's record doesn't hold together");
            }
            if ids.windows(2).any(|pair| pair[0] >= pair[1]) {
                return Some("a conflict's ids don't rise");
            }
            None
        }
    }
}

/// Read a log's bytes: every whole task, and either what was cut from its end, or why it is
/// refused. `index` is the name the log must carry.
pub(crate) fn parse(bytes: &[u8], index: &str) -> Result<Parsed, LogError> {
    let Some((Record::Header(header), mut at)) = read_record(bytes, 0, 64) else {
        return Err(LogError::new(
            "no_header",
            "the log doesn't begin with a whole, valid header",
        ));
    };
    if header.index != index {
        return Err(LogError::new("other_index", "the log belongs to another index"));
    }
    let width = header.width;
    let base = header.base_seq;
    let mut parsed = Parsed {
        end: at as u64,
        header: Some(header),
        ..Parsed::default()
    };
    let invalid = |at: usize, why: &str| LogError::new("invalid", format!("the log is invalid at byte {at}: {why}"));
    let mut pending: Vec<Entry> = Vec::new();
    let mut last_seq: Option<u64> = None;
    let mut task_ids: HashSet<String> = HashSet::new();
    loop {
        let number = (parsed.tasks.len() as u64)
            .checked_add(1)
            .ok_or_else(|| invalid(at, "too many tasks"))?;
        match read_record(bytes, at, width) {
            Some((Record::Header(_), _)) => return Err(invalid(at, "a second header")),
            Some((Record::Entry { task, entry }, next)) => {
                if task != number {
                    return Err(invalid(at, "an entry names another task than the one it belongs to"));
                }
                let follows = match pending.last().map(|entry| entry.seq).or(last_seq) {
                    Some(previous) => previous.checked_add(1) == Some(entry.seq),
                    None => entry.seq > 0,
                };
                if !follows {
                    return Err(invalid(at, "an entry's seq doesn't follow the one before it"));
                }
                pending.push(entry);
                at = next;
            }
            Some((Record::Task { number: task, record }, next)) => {
                if task != number {
                    return Err(invalid(at, "a task's number doesn't follow the one before it"));
                }
                if let Some(fault) = task_fault(&record, &pending, base, last_seq.is_some()) {
                    return Err(invalid(at, fault));
                }
                if !task_ids.insert(record.task_id.clone()) {
                    return Err(invalid(at, "two tasks have one `task_id`"));
                }
                if let Some(entry) = pending.last() {
                    last_seq = Some(entry.seq);
                }
                let start = parsed.entries.len();
                parsed.entries.append(&mut pending);
                parsed.tasks.push((record, start..parsed.entries.len()));
                parsed.end = next as u64;
                at = next;
            }
            None if at == bytes.len() && pending.is_empty() => return Ok(parsed),
            None => break,
        }
    }
    // From the end of the last whole task on: one unfinished task, or damage in the middle...
    let end = parsed.end as usize;
    let next_task = parsed.tasks.len() as u64 + 1;
    let tail = &bytes[end..];
    let mut whole_entries = 0;
    for (offset, _) in tail.windows(4).enumerate().filter(|(_, window)| *window == MAGIC) {
        match read_record(bytes, end + offset, width) {
            Some((Record::Entry { task, .. }, _)) if task == next_task => whole_entries += 1,
            Some((Record::Task { number, .. }, _)) if number == next_task => {}
            Some(_) => {
                return Err(LogError::new(
                    "damaged",
                    format!(
                        "the log is damaged at byte {end}: a record there isn't whole or doesn't follow, and whole \
                         records of other tasks come after it"
                    ),
                ));
            }
            None => {}
        }
    }
    parsed.cut = Some(((bytes.len() - end) as u64, whole_entries));
    Ok(parsed)
}

/// What reading a log found.
#[derive(Debug)]
pub(crate) enum LogBytes {
    /// No log: it doesn't exist yet.
    Missing,
    /// A log of this many bytes, more than the bound: not read.
    TooLarge(u64),
    /// The log's bytes.
    Bytes(Vec<u8>),
}

/// Parse what was read, or say why it can't be: a log over `max` bytes is refused unread.
fn parse_read(read: LogBytes, index: &str, max: u64) -> Result<Parsed, LogError> {
    match read {
        LogBytes::Missing => Ok(Parsed::default()),
        LogBytes::TooLarge(bytes) => Err(too_large(bytes, max)),
        LogBytes::Bytes(bytes) => parse(&bytes, index),
    }
}

fn too_large(bytes: u64, max: u64) -> LogError {
    LogError::new(
        "too_large",
        format!(
            "the log is {bytes} bytes, more than {max}, the most read: raise `--max-log-bytes` to read it, then \
             export a snapshot that covers it so it is shortened"
        ),
    )
}

/// Read the log in `dir` for the index `index`, as [`parse`] does, without its lock, as `query` and
/// `stats` do; a log that doesn't exist yet reads as empty, and one over `max` bytes, or that is a
/// symbolic link or is in a state directory that is one, is refused unread.
pub(crate) fn read(dir: &Path, index: &str, max: u64) -> Result<Parsed, LogError> {
    // The writer's opening refuses a linked state directory as it makes it; a reader checks it
    // here, so neither replays another directory's log...
    match fs::symlink_metadata(dir) {
        Ok(metadata) if metadata.is_dir() => {}
        Ok(_) => {
            return Err(LogError::new(
                "symlink",
                format!(
                    "the state directory `{}` is a symbolic link or not a directory; it must be a directory",
                    dir.display()
                ),
            ));
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Parsed::default()),
        Err(error) => return Err(LogError::new("unreadable", format!("the log can't be read: {error}"))),
    }
    let path = dir.join(LOG_FILE);
    let not_a_file = || LogError::new("symlink", "the log is a symbolic link or not a file; it must be a file");
    // The name is looked at before it is opened: a link whose target is missing is a link, not an
    // absent log, and opening a pipe would wait for a writer before anything could be checked...
    match fs::symlink_metadata(&path) {
        Ok(metadata) if metadata.is_file() => {}
        Ok(_) => return Err(not_a_file()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Parsed::default()),
        Err(error) => return Err(LogError::new("unreadable", format!("the log can't be read: {error}"))),
    }
    // ...and the file opened is checked to be the one named.
    let file =
        File::open(&path).map_err(|error| LogError::new("unreadable", format!("the log can't be read: {error}")))?;
    if !names(&file, &path).map_err(|error| LogError::new("unreadable", format!("the log can't be read: {error}")))? {
        return Err(not_a_file());
    }
    let read = read_bounded(&file, max)
        .map_err(|error| LogError::new("unreadable", format!("the log can't be read: {error}")))?;
    parse_read(read, index, max)
}

/// Read `file` from its start, at most `max` bytes: a longer one is not read.
fn read_bounded(mut file: &File, max: u64) -> io::Result<LogBytes> {
    let bytes = file.metadata()?.len();
    if bytes > max {
        return Ok(LogBytes::TooLarge(bytes));
    }
    file.seek(SeekFrom::Start(0))?;
    let mut out = Vec::with_capacity(usize::try_from(bytes).unwrap_or(0));
    file.take(max.saturating_add(1)).read_to_end(&mut out)?;
    if out.len() as u64 > max {
        return Ok(LogBytes::TooLarge(out.len() as u64));
    }
    Ok(LogBytes::Bytes(out))
}

/// Whether the open `file` is a file that `path` names, not through a symbolic link: the name
/// isn't a link, and on Unix its device and inode are the handle's.
pub(crate) fn names(file: &File, path: &Path) -> io::Result<bool> {
    let held = file.metadata()?;
    let named = match fs::symlink_metadata(path) {
        Ok(named) => named,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error),
    };
    if named.file_type().is_symlink() || !named.is_file() || !held.is_file() {
        return Ok(false);
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        Ok(held.dev() == named.dev() && held.ino() == named.ino())
    }
    #[cfg(not(unix))]
    {
        Ok(true)
    }
}

/// What a live writer's read of its own log at a swap found that isn't what it wrote.
#[derive(Debug)]
pub(crate) enum Reread {
    /// The log's name no longer names the file the writer appends to: `missing` or `replaced`, or
    /// `appeared` for a log this writer never wrote.
    Moved(&'static str),
    /// The log over the bound.
    TooLarge(u64),
    /// It can't be read.
    Io(io::Error),
}

/// Where an index's log lives: the files of its state directory, `STATE/<index>`, and the
/// operations the log needs of them. The file system's is the one in use; tests use a double that
/// keeps what a read sees apart from what a crash keeps.
pub(crate) trait Disk: fmt::Debug + Send {
    /// Make the state directory and each missing directory above it, one at a time, and make
    /// every name on its path durable in its parent, made now or found, except the state
    /// directory's own; refuse a symbolic link.
    fn make_dir(&mut self) -> io::Result<()>;
    /// Make the state directory's own name durable: sync the directory that holds it. Done on
    /// every opening, for a directory found may be one an earlier run made and never synced.
    fn sync_parent(&mut self) -> io::Result<()>;
    /// Take the state directory's lock, held until this is dropped: `Err` with why when another
    /// process holds it or it can't be taken.
    fn lock(&mut self) -> Result<(), String>;
    /// Remove a shortened log left half-written, if there is one.
    fn remove_new(&mut self) -> io::Result<()>;
    /// Open the log, when there is one, to read it and then append to it: its bytes, at most
    /// `max`. Refuses a log that is a symbolic link.
    fn open_log(&mut self, max: u64) -> io::Result<LogBytes>;
    /// Read the log again through the file opened, after checking its name still names it.
    fn reread(&mut self, max: u64) -> Result<LogBytes, Reread>;
    /// Cut the open log to `len` bytes.
    fn truncate(&mut self, len: u64) -> io::Result<()>;
    /// Append `bytes` to the open log.
    fn append(&mut self, bytes: &[u8]) -> io::Result<()>;
    /// Make the open log's data durable (`fdatasync`).
    fn sync_data(&mut self) -> io::Result<()>;
    /// Make the open log durable, its size too (`fsync`).
    fn sync(&mut self) -> io::Result<()>;
    /// Make the state directory durable: the names in it.
    fn sync_dir(&mut self) -> io::Result<()>;
    /// Write `bytes` as the whole log: to a new file created for it, made durable, renamed over
    /// the log, the directory made durable, then opened to append.
    fn replace(&mut self, bytes: &[u8]) -> io::Result<()>;
}

/// The file system's [`Disk`]: the files of the directory `dir`.
#[derive(Debug)]
pub(crate) struct FsDisk {
    dir: PathBuf,
    lock: Option<File>,
    log: Option<File>,
}

impl FsDisk {
    pub(crate) fn new(dir: &Path) -> Self {
        Self {
            dir: dir.to_owned(),
            lock: None,
            log: None,
        }
    }

    fn open_append(&self) -> io::Result<File> {
        let path = self.dir.join(LOG_FILE);
        let file = OpenOptions::new().read(true).append(true).open(&path)?;
        if !names(&file, &path)? {
            return Err(io::Error::other(
                "`changes.log` is a symbolic link or not a file; it must be a file",
            ));
        }
        Ok(file)
    }

    fn log(&mut self) -> io::Result<&mut File> {
        self.log.as_mut().ok_or_else(|| io::Error::other("the log isn't open"))
    }
}

/// Make `dir` and every missing directory above it, one level at a time, then call `synced` with
/// every directory on `dir`'s path that holds the next one's name, except `dir`'s parent, whether
/// or not a directory was made: whether `dir` was made. A symbolic link where a directory is
/// wanted is refused.
///
/// A directory found is not known to be durable: a run that stopped between making it and syncing
/// its parent leaves its name visible and nothing more, so the names are made durable on every call.
pub(crate) fn make_dirs(dir: &Path, synced: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<bool> {
    let mut missing = Vec::new();
    let mut at = dir;
    loop {
        match fs::symlink_metadata(at) {
            Ok(metadata) if metadata.is_dir() => break,
            Ok(_) => {
                return Err(io::Error::other(format!(
                    "`{}` is a symbolic link or not a directory",
                    at.display()
                )));
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                missing.push(at);
                match at.parent() {
                    Some(parent) if !parent.as_os_str().is_empty() => at = parent,
                    _ => break,
                }
            }
            Err(error) => return Err(error),
        }
    }
    let made = !missing.is_empty();
    for level in missing.into_iter().rev() {
        match fs::create_dir(level) {
            Err(error) if error.kind() != io::ErrorKind::AlreadyExists => return Err(error),
            _ => {}
        }
    }
    // Every name on the path is made durable, made now or found, for one found may be what an
    // earlier run made and never synced. The root has no parent to hold it.
    for level in dir.ancestors().skip(1).filter(|level| level.parent().is_some()) {
        synced(parent_of(level))?;
    }
    Ok(made)
}

/// The directory that holds `level`'s name: a relative path's first directory is named in the
/// current one.
fn parent_of(level: &Path) -> &Path {
    level
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

fn sync_directory(dir: &Path) -> io::Result<()> {
    File::open(dir)?.sync_all()
}

impl Disk for FsDisk {
    fn make_dir(&mut self) -> io::Result<()> {
        make_dirs(&self.dir, &mut |parent| sync_directory(parent)).map(|_| ())
    }

    fn sync_parent(&mut self) -> io::Result<()> {
        match self.dir.parent().filter(|parent| !parent.as_os_str().is_empty()) {
            Some(parent) => sync_directory(parent),
            None => sync_directory(Path::new(".")),
        }
    }

    fn lock(&mut self) -> Result<(), String> {
        let path = self.dir.join(LOCK_FILE);
        let lock = OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .map_err(|error| format!("`{}` can't be opened: {error}", path.display()))?;
        if !names(&lock, &path).map_err(|error| format!("`{}` can't be opened: {error}", path.display()))? {
            return Err(format!(
                "`{}` is a symbolic link or not a file; it must be a file",
                path.display()
            ));
        }
        // A child process this one spawns holds a copy of every open file from its fork to its
        // exec, a lock just released included: a holder is waited for a moment before it counts...
        let started = Instant::now();
        loop {
            match lock.try_lock() {
                Ok(()) => {
                    self.lock = Some(lock);
                    return Ok(());
                }
                Err(TryLockError::WouldBlock) if started.elapsed() < LOCK_WAIT => {
                    std::thread::sleep(Duration::from_millis(5));
                }
                Err(TryLockError::WouldBlock) => {
                    return Err(format!(
                        "another process holds `{}`: with changes on, one process serves an index",
                        path.display()
                    ));
                }
                Err(TryLockError::Error(error)) => {
                    return Err(format!("`{}` can't be locked: {error}", path.display()));
                }
            }
        }
    }

    fn remove_new(&mut self) -> io::Result<()> {
        // A symbolic link of that name is removed, not followed...
        match fs::remove_file(self.dir.join(NEW_FILE)) {
            Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
            _ => Ok(()),
        }
    }

    fn open_log(&mut self, max: u64) -> io::Result<LogBytes> {
        self.log = None;
        let file = match self.open_append() {
            Ok(file) => file,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(LogBytes::Missing),
            Err(error) => return Err(error),
        };
        let read = read_bounded(&file, max)?;
        self.log = Some(file);
        Ok(read)
    }

    fn reread(&mut self, max: u64) -> Result<LogBytes, Reread> {
        let path = self.dir.join(LOG_FILE);
        let Some(file) = &self.log else {
            return match fs::symlink_metadata(&path) {
                Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(LogBytes::Missing),
                Err(error) => Err(Reread::Io(error)),
                Ok(_) => Err(Reread::Moved("appeared")),
            };
        };
        match fs::symlink_metadata(&path) {
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(Reread::Moved("missing")),
            Err(error) => return Err(Reread::Io(error)),
            Ok(_) => {}
        }
        if !names(file, &path).map_err(Reread::Io)? {
            return Err(Reread::Moved("replaced"));
        }
        match read_bounded(file, max).map_err(Reread::Io)? {
            LogBytes::TooLarge(bytes) => Err(Reread::TooLarge(bytes)),
            read => Ok(read),
        }
    }

    fn truncate(&mut self, len: u64) -> io::Result<()> {
        self.log()?.set_len(len)
    }

    fn append(&mut self, bytes: &[u8]) -> io::Result<()> {
        // Opened to append: every write goes at the end, whatever the handle's offset...
        self.log()?.write_all(bytes)
    }

    fn sync_data(&mut self) -> io::Result<()> {
        self.log()?.sync_data()
    }

    fn sync(&mut self) -> io::Result<()> {
        self.log()?.sync_all()
    }

    fn sync_dir(&mut self) -> io::Result<()> {
        sync_directory(&self.dir)
    }

    fn replace(&mut self, bytes: &[u8]) -> io::Result<()> {
        let new = self.dir.join(NEW_FILE);
        self.remove_new()?;
        {
            let mut file = OpenOptions::new().write(true).create_new(true).open(&new)?;
            file.write_all(bytes)?;
            file.sync_all()?;
        }
        fs::rename(&new, self.dir.join(LOG_FILE))?;
        sync_directory(&self.dir)?;
        self.log = Some(self.open_append()?);
        Ok(())
    }
}

/// Why a task couldn't be appended.
#[derive(Debug)]
pub(crate) enum AppendError {
    /// A field doesn't fit the format: nothing was written.
    Unrepresentable(&'static str),
    /// Writing failed: what failed, a code (`create_failed`, `write_failed`, `sync_failed`, or
    /// `rollback_failed` when cutting the file back failed as well), and the error. What reached
    /// the disk isn't known; the caller writes no more.
    Failed(&'static str, io::Error),
}

/// The log of one index, open for appending, with its lock held.
#[derive(Debug)]
pub(crate) struct LogFile {
    disk: Box<dyn Disk>,
    index: String,
    /// Whether the log exists: this process opened or created it.
    exists: bool,
    /// The bytes of whole tasks: where the next is written.
    end: u64,
    /// The next task's number in the file.
    next_task: u64,
    /// The header's base `seq`.
    base_seq: u64,
    /// The last `seq` the log holds, or the base.
    last_seq: u64,
    /// The width the log was made for, once it exists.
    width: Option<u32>,
}

impl LogFile {
    /// Open the log of `index` on `disk` for writing: make its directory durably, take its lock,
    /// remove a shortened log left half-written, read the log (at most `max` bytes), cut an
    /// unfinished task from its end, and make what is left durable.
    ///
    /// The outer error is a lock another process holds or a directory that can't be used, which
    /// stops the program; the inner one a log that is refused, which leaves the lock held so no
    /// other process writes it.
    pub(crate) fn open(
        mut disk: Box<dyn Disk>,
        index: &str,
        max: u64,
    ) -> Result<(Self, Result<Parsed, LogError>), String> {
        disk.make_dir()
            .map_err(|error| format!("the state directory of `{index}` can't be made: {error}"))?;
        disk.sync_parent()
            .map_err(|error| format!("the state directory of `{index}` can't be made durable: {error}"))?;
        disk.lock()?;
        disk.remove_new()
            .map_err(|error| format!("a half-written shortened log can't be removed: {error}"))?;
        let mut log = Self {
            disk,
            index: index.to_owned(),
            exists: false,
            end: 0,
            next_task: 1,
            base_seq: 0,
            last_seq: 0,
            width: None,
        };
        let parsed = match log.disk.open_log(max) {
            Ok(read) => {
                let exists = !matches!(read, LogBytes::Missing);
                parse_read(read, index, max).and_then(|parsed| {
                    log.recover(&parsed, exists)?;
                    Ok(parsed)
                })
            }
            Err(error) => Err(LogError::new("unreadable", format!("the log can't be read: {error}"))),
        };
        Ok((log, parsed))
    }

    /// Take `parsed`, the log as read, as the log's state: cut what follows its whole tasks, then
    /// make the file and its directory durable, so nothing in it is answered from before it is.
    fn recover(&mut self, parsed: &Parsed, exists: bool) -> Result<(), LogError> {
        if exists {
            let synced = (|| {
                if parsed.cut.is_some() {
                    self.disk.truncate(parsed.end)?;
                }
                self.disk.sync()?;
                self.disk.sync_dir()
            })();
            synced.map_err(|error| {
                LogError::new(
                    "sync_failed",
                    format!("the log can't be made durable as it is opened: {error}"),
                )
            })?;
        }
        self.adopt(parsed, exists);
        Ok(())
    }

    fn adopt(&mut self, parsed: &Parsed, exists: bool) {
        self.exists = exists && parsed.header.is_some();
        self.end = parsed.end;
        self.next_task = parsed.tasks.len() as u64 + 1;
        self.base_seq = parsed.base_seq();
        self.last_seq = parsed.last_seq();
        self.width = parsed.header.as_ref().map(|header| header.width);
    }

    /// Whether the log exists yet: a task's header bytes count when it doesn't.
    fn header_bytes(&self, width: u32) -> Result<u64, Unrepresentable> {
        if self.exists {
            return Ok(0);
        }
        let mut header = Vec::new();
        header_record(
            &mut header,
            &Header {
                index: self.index.clone(),
                width,
                base_seq: self.base_seq,
            },
        )?;
        Ok(header.len() as u64)
    }

    /// Whether `bytes` more, with the header when the log doesn't exist yet, keep it within
    /// `bound`: what a task is checked against before any work is done for it.
    pub(crate) fn fits(&self, width: u32, bytes: u64, bound: u64) -> bool {
        self.header_bytes(width)
            .ok()
            .and_then(|header| self.end.checked_add(header)?.checked_add(bytes))
            .is_some_and(|total| total <= bound)
    }

    /// Append a task's entries and its record, then make them durable. Returns how many bytes the
    /// log grew by, its header included when this created it.
    ///
    /// `bound` is the log's limit: a task that would take the log past it is refused with
    /// `Ok(None)` and nothing written. On a failure the file is cut back to its whole tasks if it
    /// can be, and the error says whether that worked; the caller stops writing either way, as a
    /// failed `fdatasync` leaves what reached the disk unknown.
    pub(crate) fn append(
        &mut self,
        width: u32,
        record: &TaskRecord,
        entries: &[Entry],
        bound: u64,
    ) -> Result<Option<u64>, AppendError> {
        let encode = || -> Result<(Vec<u8>, u64), Unrepresentable> {
            let mut bytes = Vec::with_capacity(entries.len().saturating_mul(entry_bytes(width)) + TASK_RECORD_MAX);
            for entry in entries {
                entry_record(&mut bytes, width, self.next_task, entry)?;
            }
            task_record(&mut bytes, self.next_task, record)?;
            Ok((bytes, self.header_bytes(width)?))
        };
        let (bytes, header) = encode().map_err(|Unrepresentable(field)| AppendError::Unrepresentable(field))?;
        let total = self
            .end
            .checked_add(header)
            .and_then(|total| total.checked_add(bytes.len() as u64));
        if total.is_none_or(|total| total > bound) {
            return Ok(None);
        }
        let before = self.end;
        if !self.exists {
            self.create(width)
                .map_err(|error| AppendError::Failed("create_failed", error))?;
        }
        let failed = match self.disk.append(&bytes) {
            Err(error) => Some(("write_failed", error)),
            Ok(()) => self.disk.sync_data().err().map(|error| ("sync_failed", error)),
        };
        if let Some((code, error)) = failed {
            let end = self.end;
            let rolled_back = self.disk.truncate(end).and_then(|()| self.disk.sync());
            let code = if rolled_back.is_ok() { code } else { "rollback_failed" };
            return Err(AppendError::Failed(code, error));
        }
        self.end += bytes.len() as u64;
        self.next_task += 1;
        if let Some(last) = entries.last() {
            self.last_seq = last.seq;
        }
        Ok(Some(self.end - before))
    }

    /// Create the log with its header: written beside it, made durable, and renamed into place, so
    /// a log is never seen without its whole header.
    fn create(&mut self, width: u32) -> io::Result<()> {
        let mut bytes = Vec::new();
        header_record(
            &mut bytes,
            &Header {
                index: self.index.clone(),
                width,
                base_seq: self.base_seq,
            },
        )
        .map_err(|Unrepresentable(field)| io::Error::other(format!("the header's {field} doesn't fit")))?;
        self.disk.replace(&bytes)?;
        self.exists = true;
        self.end = bytes.len() as u64;
        self.next_task = 1;
        self.width = Some(width);
        Ok(())
    }

    /// Read the log again, as a live writer does at a swap, through the file it appends to, and
    /// check it is what this writer made durable: the same header, no cut, the same end, and a
    /// last `seq` not below its own. A log missing when this writer has written one, replaced
    /// under it, or changed, is refused with its code, and the caller writes no more.
    pub(crate) fn reread(&mut self, max: u64) -> Result<Parsed, LogError> {
        let read = match self.disk.reread(max) {
            Ok(read) => read,
            Err(Reread::Moved(code)) => {
                let what = match code {
                    "missing" => "no longer exists",
                    "replaced" => "was replaced by another file",
                    _ => "exists, though this writer never wrote it",
                };
                return Err(LogError::new(
                    code,
                    format!("the log {what} while this process writes it"),
                ));
            }
            Err(Reread::TooLarge(bytes)) => return Err(too_large(bytes, max)),
            Err(Reread::Io(error)) => {
                return Err(LogError::new("unreadable", format!("the log can't be read: {error}")));
            }
        };
        let exists = !matches!(read, LogBytes::Missing);
        let parsed = parse_read(read, &self.index, max)?;
        if exists != self.exists {
            return Err(if self.exists {
                LogError::new("missing", "the log no longer exists while this process writes it")
            } else {
                LogError::new("appeared", "the log exists, though this writer never wrote it")
            });
        }
        let same_header = match (&parsed.header, self.width) {
            (None, None) => true,
            (Some(header), Some(width)) => header.width == width && header.base_seq == self.base_seq,
            _ => false,
        };
        if !same_header {
            return Err(LogError::new(
                "changed",
                "the log's header isn't the one this process wrote",
            ));
        }
        if parsed.cut.is_some() {
            return Err(LogError::new(
                "cut",
                "the log ends in a task that isn't whole, though this process made every task durable",
            ));
        }
        if parsed.end != self.end || parsed.last_seq() < self.last_seq {
            return Err(LogError::new(
                "changed",
                format!(
                    "the log is {} bytes to seq {}; this process made it {} bytes to seq {}",
                    parsed.end,
                    parsed.last_seq(),
                    self.end,
                    self.last_seq
                ),
            ));
        }
        Ok(parsed)
    }

    /// Shorten the log once a snapshot covers every change to `covers`: drop the entries of every
    /// task that is covered, keep the task's record without its entries while it was applied
    /// within `keep_since` (Unix milliseconds) so a repeat of it is still recognised, and keep
    /// every later task whole. `parsed` is the log as it is now.
    ///
    /// Returns the log as it now is.
    pub(crate) fn shorten(&mut self, parsed: &Parsed, covers: u64, keep_since: u64) -> io::Result<Parsed> {
        let Some(header) = &parsed.header else {
            return Ok(parsed.clone());
        };
        let width = header.width;
        let header = Header {
            base_seq: header.base_seq.max(covers),
            ..header.clone()
        };
        let mut shortened = Parsed {
            header: Some(header.clone()),
            ..Parsed::default()
        };
        let unrepresentable = |Unrepresentable(field)| io::Error::other(format!("the log's {field} doesn't fit"));
        let mut bytes = Vec::new();
        header_record(&mut bytes, &header).map_err(unrepresentable)?;
        for (record, range) in &parsed.tasks {
            let covered = record.last_seq().is_none_or(|last| last <= covers);
            let record = if covered {
                if record.applied_at < keep_since {
                    continue;
                }
                TaskRecord {
                    entries: 0,
                    ..record.clone()
                }
            } else {
                record.clone()
            };
            let number = shortened.tasks.len() as u64 + 1;
            let start = shortened.entries.len();
            if !covered {
                for entry in &parsed.entries[range.clone()] {
                    entry_record(&mut bytes, width, number, entry).map_err(unrepresentable)?;
                    shortened.entries.push(*entry);
                }
            }
            task_record(&mut bytes, number, &record).map_err(unrepresentable)?;
            shortened.tasks.push((record, start..shortened.entries.len()));
        }
        shortened.end = bytes.len() as u64;
        self.disk.replace(&bytes)?;
        self.exists = true;
        self.end = shortened.end;
        self.next_task = shortened.tasks.len() as u64 + 1;
        self.base_seq = header.base_seq;
        self.last_seq = shortened.last_seq();
        Ok(shortened)
    }
}

/// The remembered outcome of every change task in a log, by `task_id`.
pub(crate) fn remembered(parsed: &Parsed) -> HashMap<String, TaskRecord> {
    parsed
        .tasks
        .iter()
        .map(|(record, _)| (record.task_id.clone(), record.clone()))
        .collect()
}

/// A [`Disk`] in memory for tests: what a read sees (`visible`) kept apart from what a machine
/// failure keeps (`durable`), the state directory's name likewise, and failures to inject.
#[cfg(test)]
pub(crate) mod double {
    use std::io;
    use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

    use super::{Disk, LogBytes, Reread};

    /// What the double holds; shared, so a restart opens the same disk.
    #[derive(Debug, Default)]
    pub(crate) struct State {
        pub(crate) dir_visible: bool,
        pub(crate) dir_durable: bool,
        pub(crate) visible: Option<Vec<u8>>,
        pub(crate) durable: Option<Vec<u8>>,
        /// The next append writes half its bytes, then fails.
        pub(crate) fail_append: bool,
        /// The next `fdatasync` fails, making nothing durable.
        pub(crate) fail_sync_data: bool,
        /// Every truncation fails.
        pub(crate) fail_truncate: bool,
        /// The operations, in order.
        pub(crate) calls: Vec<&'static str>,
    }

    /// The double: a handle on the shared state.
    #[derive(Debug, Clone, Default)]
    pub(crate) struct MemDisk(pub(crate) Arc<Mutex<State>>);

    impl MemDisk {
        pub(crate) fn state(&self) -> MutexGuard<'_, State> {
            self.0.lock().unwrap_or_else(PoisonError::into_inner)
        }

        /// A machine failure: only what was durable is left.
        pub(crate) fn crash(&self) {
            let mut state = self.state();
            if !state.dir_durable {
                state.dir_visible = false;
                state.durable = None;
            }
            state.visible = state.durable.clone();
        }
    }

    impl Disk for MemDisk {
        fn make_dir(&mut self) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("make_dir");
            state.dir_visible = true;
            Ok(())
        }

        fn sync_parent(&mut self) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("sync_parent");
            state.dir_durable = state.dir_visible;
            Ok(())
        }

        fn lock(&mut self) -> Result<(), String> {
            Ok(())
        }

        fn remove_new(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn open_log(&mut self, max: u64) -> io::Result<LogBytes> {
            let mut state = self.state();
            state.calls.push("open_log");
            Ok(match &state.visible {
                None => LogBytes::Missing,
                Some(bytes) if bytes.len() as u64 > max => LogBytes::TooLarge(bytes.len() as u64),
                Some(bytes) => LogBytes::Bytes(bytes.clone()),
            })
        }

        fn reread(&mut self, max: u64) -> Result<LogBytes, Reread> {
            self.open_log(max).map_err(Reread::Io)
        }

        fn truncate(&mut self, len: u64) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("truncate");
            if state.fail_truncate {
                return Err(io::Error::other("injected: truncate fails"));
            }
            if let Some(bytes) = &mut state.visible {
                bytes.truncate(usize::try_from(len).expect("small"));
            }
            Ok(())
        }

        fn append(&mut self, bytes: &[u8]) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("append");
            let fail = std::mem::take(&mut state.fail_append);
            let written = if fail { &bytes[..bytes.len() / 2] } else { bytes };
            state
                .visible
                .as_mut()
                .ok_or_else(|| io::Error::other("no log"))?
                .extend_from_slice(written);
            if fail {
                return Err(io::Error::other("injected: the write fails half way"));
            }
            Ok(())
        }

        fn sync_data(&mut self) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("sync_data");
            if std::mem::take(&mut state.fail_sync_data) {
                return Err(io::Error::other("injected: fdatasync fails"));
            }
            state.durable = state.visible.clone();
            Ok(())
        }

        fn sync(&mut self) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("sync");
            state.durable = state.visible.clone();
            Ok(())
        }

        fn sync_dir(&mut self) -> io::Result<()> {
            self.state().calls.push("sync_dir");
            Ok(())
        }

        fn replace(&mut self, bytes: &[u8]) -> io::Result<()> {
            let mut state = self.state();
            state.calls.push("replace");
            state.visible = Some(bytes.to_vec());
            state.durable = Some(bytes.to_vec());
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::double::MemDisk;
    use super::*;

    #[test]
    fn crc32c_matches_its_check_value() {
        // The check value of CRC-32C, the CRC of the ASCII digits 1 to 9...
        assert_eq!(crc32c(b"123456789"), 0xe306_9283);
        assert_eq!(crc32c(b""), 0);
    }

    fn conflict_record() -> TaskRecord {
        TaskRecord {
            task_id: "app_01J".to_owned(),
            name: ChangeName::Append,
            outcome: Outcome::Conflict {
                ids: vec![3, 9],
                count: 2,
            },
            applied_at: 1_764_000_000_000,
            first_seq: 7,
            entries: 0,
        }
    }

    #[test]
    fn a_task_record_reads_back_as_written() {
        let record = conflict_record();
        let mut bytes = Vec::new();
        task_record(&mut bytes, 4, &record).expect("fits");
        assert!(bytes.len() <= TASK_RECORD_MAX);
        assert_eq!(
            framed_bytes(64, 0, 0, 2, record.task_id.len()),
            Some(bytes.len() as u64)
        );
        match read_record(&bytes, 0, 64) {
            Some((Record::Task { number, record: read }, next)) => {
                assert_eq!((number, next), (4, bytes.len()));
                assert_eq!(read, record);
            }
            _ => panic!("the record reads back"),
        }
    }

    #[test]
    fn a_field_that_does_not_fit_is_refused_not_cut() {
        for task_id in ["", &"a".repeat(65), &"a".repeat(255), &"a".repeat(256), "é", "a:b"] {
            let record = TaskRecord {
                task_id: task_id.to_owned(),
                ..conflict_record()
            };
            let mut bytes = Vec::new();
            assert_eq!(task_record(&mut bytes, 1, &record), Err(Unrepresentable("task_id")));
        }
        let record = TaskRecord {
            outcome: Outcome::Conflict {
                ids: (0..101).collect(),
                count: 101,
            },
            ..conflict_record()
        };
        assert_eq!(
            task_record(&mut Vec::new(), 1, &record),
            Err(Unrepresentable("conflict ids"))
        );
        let header = Header {
            index: "x".repeat(256),
            width: 64,
            base_seq: 0,
        };
        assert_eq!(header_record(&mut Vec::new(), &header), Err(Unrepresentable("index")));
        assert_eq!(
            frame(&mut Vec::new(), b'E', &[0; MAX_RECORD]),
            Err(Unrepresentable("record"))
        );
    }

    /// The bytes of a log: a header at `base`, then `tasks`, each its entries `(seq, id)` and its
    /// record.
    fn log_bytes(base: u64, tasks: &[(Vec<(u64, u64)>, TaskRecord)]) -> Vec<u8> {
        let mut bytes = Vec::new();
        let header = Header {
            index: "m".to_owned(),
            width: 64,
            base_seq: base,
        };
        header_record(&mut bytes, &header).expect("fits");
        for (number, (entries, record)) in tasks.iter().enumerate() {
            for &(seq, id) in entries {
                entry_record(&mut bytes, 64, number as u64 + 1, &Entry::new(seq, id, Some(id))).expect("fits");
            }
            task_record(&mut bytes, number as u64 + 1, record).expect("fits");
        }
        bytes
    }

    fn applied(task_id: &str, first: u64, entries: u32, added: u32) -> TaskRecord {
        TaskRecord {
            task_id: task_id.to_owned(),
            name: ChangeName::Replace,
            outcome: Outcome::Applied {
                seq: first + (u64::from(entries.max(1)) - 1),
                tally: Tally {
                    added,
                    ..Tally::default()
                },
            },
            applied_at: 1,
            first_seq: first,
            entries,
        }
    }

    fn task(task_id: &str, seqs: std::ops::RangeInclusive<u64>) -> (Vec<(u64, u64)>, TaskRecord) {
        let entries: Vec<(u64, u64)> = seqs.clone().map(|seq| (seq, seq.wrapping_mul(10))).collect();
        let count = u32::try_from(entries.len()).expect("small");
        (entries, applied(task_id, *seqs.start(), count, count))
    }

    #[test]
    fn a_coherent_log_reads_and_one_that_breaks_a_rule_is_refused_not_cut() {
        let good = log_bytes(0, &[task("a", 1..=2), task("b", 3..=3)]);
        let parsed = parse(&good, "m").expect("reads");
        assert_eq!((parsed.tasks.len(), parsed.last_seq(), parsed.cut), (2, 3, None));
        // A gap between two whole tasks, at the end: not an unfinished write...
        let gap = log_bytes(0, &[task("a", 1..=2), task("b", 5..=5)]);
        assert_eq!(parse(&gap, "m").expect_err("refused").code, "invalid");
        // ...nor one between the header's base and the first entry...
        let after_base = log_bytes(3, &[task("a", 6..=7)]);
        assert_eq!(parse(&after_base, "m").expect_err("refused").code, "invalid");
        // ...though a task straddling the base is kept whole, and one just above it reads.
        assert!(parse(&log_bytes(3, &[task("a", 2..=5)]), "m").is_ok());
        assert!(parse(&log_bytes(3, &[task("a", 4..=5)]), "m").is_ok());
        assert_eq!(
            parse(&log_bytes(5, &[task("a", 2..=5)]), "m")
                .expect_err("refused")
                .code,
            "invalid"
        );
        // Counts that don't add up to the entries, and a task id given twice...
        let (entries, mut record) = task("a", 1..=2);
        record.outcome = Outcome::Applied {
            seq: 2,
            tally: Tally {
                added: 1,
                ..Tally::default()
            },
        };
        assert_eq!(
            parse(&log_bytes(0, &[(entries, record)]), "m")
                .expect_err("refused")
                .code,
            "invalid"
        );
        let twice = log_bytes(0, &[task("a", 1..=1), task("a", 2..=2)]);
        assert_eq!(parse(&twice, "m").expect_err("refused").code, "invalid");
        // ...a task kept without its entries that the base doesn't cover...
        let uncovered = log_bytes(2, &[(Vec::new(), applied("a", 3, 0, 1))]);
        assert_eq!(parse(&uncovered, "m").expect_err("refused").code, "invalid");
        assert!(parse(&log_bytes(3, &[(Vec::new(), applied("a", 3, 0, 1))]), "m").is_ok());
        // ...and a conflict whose ids don't rise.
        let mut conflict = conflict_record();
        conflict.outcome = Outcome::Conflict {
            ids: vec![9, 3],
            count: 2,
        };
        assert_eq!(
            parse(&log_bytes(7, &[(Vec::new(), conflict)]), "m")
                .expect_err("refused")
                .code,
            "invalid"
        );
    }

    #[test]
    fn damage_across_several_frames_is_cut_in_the_last_task_and_refused_before_it() {
        let bytes = log_bytes(0, &[task("a", 1..=3), task("b", 4..=6), task("c", 7..=9)]);
        let starts: Vec<usize> = bytes
            .windows(4)
            .enumerate()
            .filter(|(_, window)| *window == MAGIC)
            .map(|(at, _)| at)
            .collect();
        // Frames: header, a×3, T, b×3, T, c×3, T. Two frames of the last task damaged: cut...
        let mut last = bytes.clone();
        last[starts[10] + 9] ^= 1;
        last[starts[12] + 9] ^= 1;
        let parsed = parse(&last, "m").expect("cut");
        assert_eq!((parsed.tasks.len(), parsed.last_seq()), (2, 6));
        // ...a frame of the second task and one of the last: whole records of the last task
        // follow the damage, so it is in the middle...
        let mut middle = bytes.clone();
        middle[starts[6] + 9] ^= 1;
        middle[starts[11] + 9] ^= 1;
        assert_eq!(parse(&middle, "m").expect_err("refused").code, "damaged");
        // ...and garbage over the whole of the last two tasks can't be told from an unfinished
        // write of the second: everything after the first is cut.
        let mut garbage = bytes;
        for byte in &mut garbage[starts[5]..] {
            *byte = 0x5a;
        }
        let parsed = parse(&garbage, "m").expect("cut");
        assert_eq!((parsed.tasks.len(), parsed.last_seq()), (1, 3));
    }

    #[test]
    fn a_base_near_the_end_of_the_seqs_reads_and_a_seq_past_it_is_refused() {
        let base = u64::MAX - 2;
        let parsed = parse(&log_bytes(base, &[task("a", base + 1..=u64::MAX)]), "m").expect("reads");
        assert_eq!(parsed.last_seq(), u64::MAX);
        // A task after it would need the seq after u64::MAX: it can only be 0, which doesn't follow...
        let mut bytes = log_bytes(base, &[task("a", base + 1..=u64::MAX)]);
        entry_record(&mut bytes, 64, 2, &Entry::new(0, 1, Some(1u64))).expect("fits");
        task_record(&mut bytes, 2, &applied("b", 0, 1, 1)).expect("fits");
        assert_eq!(parse(&bytes, "m").expect_err("refused").code, "invalid");
    }

    #[test]
    fn the_state_directory_and_its_missing_parents_are_made_one_level_at_a_time() {
        let root = std::env::temp_dir().join(format!("legit-hamming-dirs-{}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("a root");
        let dir = root.join("a").join("b").join("c");
        let mut synced = Vec::new();
        let made = make_dirs(&dir, &mut |parent| {
            synced.push(parent.to_owned());
            Ok(())
        })
        .expect("made");
        assert!(made && dir.is_dir());
        // Every directory on the path that holds the next one's name is synced, up to the root,
        // but the last, which the log's opening syncs itself...
        let path: Vec<PathBuf> = dir.ancestors().skip(2).map(Path::to_owned).collect();
        assert_eq!(synced[..2], [root.join("a"), root.clone()]);
        assert_eq!(synced, path);
        // ...and again when nothing is made: a directory found may be one a run that stopped
        // before its parent was synced left visible but not durable.
        let mut again = Vec::new();
        let made = make_dirs(&dir, &mut |parent| {
            again.push(parent.to_owned());
            Ok(())
        })
        .expect("there");
        assert!(!made);
        assert_eq!(again, path);
        // A relative root: the current directory holds its first directory, and is synced...
        let relative = PathBuf::from(format!("legit-hamming-dirs-relative-{}", std::process::id()));
        let _ = fs::remove_dir_all(&relative);
        let mut synced = Vec::new();
        let made = make_dirs(&relative.join("m"), &mut |parent| {
            synced.push(parent.to_owned());
            Ok(())
        });
        let _ = fs::remove_dir_all(&relative);
        assert!(made.expect("made"));
        assert_eq!(synced, [PathBuf::from(".")]);
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&dir, root.join("link")).expect("a link");
            assert!(make_dirs(&root.join("link"), &mut |_| Ok(())).is_err());
        }
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn opening_a_log_makes_every_whole_task_durable() {
        // A process died after a task reached the file and before `fdatasync` returned: the task
        // reads whole, but only the header is durable...
        let disk = MemDisk::default();
        {
            let mut state = disk.state();
            state.dir_visible = true;
            state.dir_durable = true;
            state.durable = Some(log_bytes(0, &[]));
            state.visible = Some(log_bytes(0, &[task("a", 1..=1)]));
        }
        // ...so opening it makes it durable before it can be answered from.
        let (_log, parsed) = LogFile::open(Box::new(disk.clone()), "m", u64::MAX).expect("opens");
        assert_eq!(parsed.expect("reads").tasks.len(), 1);
        disk.crash();
        let durable = disk.state().visible.clone().expect("the log survives");
        assert_eq!(parse(&durable, "m").expect("reads").tasks.len(), 1);
    }

    #[test]
    fn a_task_ending_at_the_last_seq_is_kept_whole_by_a_snapshot_that_does_not_cover_it() {
        let last = TaskRecord {
            entries: 1,
            first_seq: u64::MAX,
            ..applied("b", u64::MAX, 1, 1)
        };
        assert_eq!(last.last_seq(), Some(u64::MAX));
        let base = u64::MAX - 3;
        let bytes = log_bytes(base, &[task("a", base + 1..=base + 2), task("b", u64::MAX..=u64::MAX)]);
        // A snapshot covers the first task and not the second, which applied the last seq there
        // is; whether the first is kept for its repeats or dropped, the second keeps its entry...
        for keep_since in [0, u64::MAX] {
            let disk = MemDisk::default();
            {
                let mut state = disk.state();
                state.dir_visible = true;
                state.dir_durable = true;
                state.durable = Some(bytes.clone());
                state.visible = Some(bytes.clone());
            }
            let (mut log, parsed) = LogFile::open(Box::new(disk.clone()), "m", u64::MAX).expect("opens");
            let shortened = log
                .shorten(&parsed.expect("reads"), u64::MAX - 1, keep_since)
                .expect("shortened");
            assert_eq!(shortened.last_seq(), u64::MAX, "{keep_since}");
            // ...and the log a restart reads is valid, and still holds it.
            disk.crash();
            let durable = disk.state().visible.clone().expect("the log survives");
            let reread = parse(&durable, "m").expect("reads");
            assert_eq!(reread.last_seq(), u64::MAX, "{keep_since}");
            let (record, range) = reread.tasks.last().expect("a task");
            assert_eq!((record.task_id.as_str(), range.len()), ("b", 1), "{keep_since}");
            assert_eq!(reread.tasks.len(), if keep_since == 0 { 2 } else { 1 }, "{keep_since}");
        }
    }

    #[test]
    fn a_state_directory_found_but_never_synced_is_made_durable_before_the_log_is_used() {
        // A first start made the state directory and stopped before syncing the directory that
        // holds its name: it is visible, not durable...
        let disk = MemDisk::default();
        disk.state().dir_visible = true;
        let (mut log, parsed) = LogFile::open(Box::new(disk.clone()), "m", u64::MAX).expect("opens");
        parsed.expect("reads");
        // ...so a restart's opening makes it durable, and a task it then makes durable survives
        // a machine failure.
        let (entries, record) = task("a", 1..=1);
        let entries: Vec<Entry> = entries.iter().map(|&(seq, id)| Entry::new(seq, id, Some(id))).collect();
        log.append(64, &record, &entries, u64::MAX)
            .expect("appended")
            .expect("within the bound");
        disk.crash();
        let durable = disk.state().visible.clone().expect("the log survives");
        assert_eq!(parse(&durable, "m").expect("reads").tasks.len(), 1);
    }
}