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
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
//! The indexes and subsets a service serves, each loaded from the snapshot its `CURRENT` names,
//! and swapped for a newer one without stopping a search.

use std::collections::HashMap;
use std::fs;
use std::io::{ErrorKind, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use super::CURRENT;
use super::error::{CONFLICT_IDS, ErrorType, ServiceError};
use super::limits::Limits;
use super::log::{
    self, AppendError, ChangeName, Disk, Entry, FsDisk, LogError, LogFile, Outcome, Parsed, Tally, TaskRecord,
};
use super::memory::available_memory;
use super::request::{ChangeRecords, ChangeRequest, is_valid_name, unknown};
use super::set::{Overlay, SearchSet, Sets, collapse};
use crate::error::Error;
use crate::neighbours::NeighbourTable;
use crate::planned::Planned;
use crate::snapshot::{self, Fault, Manifest};
use crate::value::Value;

/// The longest `CURRENT` file read, in bytes.
const CURRENT_MAX_BYTES: u64 = 256;

/// The longest snapshot directory name `CURRENT` may give.
const SNAPSHOT_NAME_MAX: usize = 128;

/// The memory the automatic table budget leaves free: a quarter of what is available, and at
/// least this much.
const TABLE_MARGIN_MIN: u64 = 512 << 20;

/// An index or subset to serve: its names and its directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetSpec {
    index: String,
    subset: Option<String>,
    dir: PathBuf,
}

impl SetSpec {
    /// The index `name`, served from `dir`.
    #[must_use]
    pub fn index(name: &str, dir: impl Into<PathBuf>) -> Self {
        Self {
            index: name.to_owned(),
            subset: None,
            dir: dir.into(),
        }
    }

    /// The subset `name` of the index `index`, served from `dir`.
    #[must_use]
    pub fn subset(index: &str, name: &str, dir: impl Into<PathBuf>) -> Self {
        Self {
            index: index.to_owned(),
            subset: Some(name.to_owned()),
            dir: dir.into(),
        }
    }

    /// An index from a command line's `name=dir`.
    ///
    /// # Errors
    ///
    /// A message when there is no `=` or the name isn't 1 to 32 of `a-z`, `0-9`, `_` and `-`.
    pub fn parse_index(argument: &str) -> Result<Self, String> {
        let (name, dir) = argument
            .split_once('=')
            .ok_or_else(|| "`--index` takes `name=dir`".to_owned())?;
        check_name(name)?;
        Ok(Self::index(name, dir))
    }

    /// A subset from a command line's `index.name=dir`.
    ///
    /// # Errors
    ///
    /// A message when there is no `.` or `=`, or a name isn't 1 to 32 of `a-z`, `0-9`, `_` and
    /// `-`.
    pub fn parse_subset(argument: &str) -> Result<Self, String> {
        let (names, dir) = argument
            .split_once('=')
            .ok_or_else(|| "`--subset` takes `index.name=dir`".to_owned())?;
        let (index, name) = names
            .split_once('.')
            .ok_or_else(|| "`--subset` takes `index.name=dir`".to_owned())?;
        check_name(index)?;
        check_name(name)?;
        Ok(Self::subset(index, name, dir))
    }

    /// The name logs and messages give it: `index`, or `index.subset`.
    #[must_use]
    pub fn label(&self) -> String {
        label(&self.index, self.subset.as_deref())
    }
}

fn check_name(name: &str) -> Result<(), String> {
    if is_valid_name(name) {
        Ok(())
    } else {
        Err("a name is 1 to 32 of `a-z`, `0-9`, `_` and `-`".to_owned())
    }
}

fn label(index: &str, subset: Option<&str>) -> String {
    subset.map_or_else(|| index.to_owned(), |subset| format!("{index}.{subset}"))
}

/// How much memory the multi-index tables of a snapshot may take.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableMemory {
    /// Build them when they fit in the memory available once the records are loaded, less a
    /// quarter of it and at least 512 MiB; where the available memory can't be read, build them.
    Auto,
    /// Build them when they take at most this many bytes. 0 scans every query.
    Bytes(u64),
}

/// How a [`Catalog`] loads snapshots.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadConfig {
    /// The tables' memory budget, [`TableMemory::Auto`] by default.
    pub table_memory: TableMemory,
    /// Threads a load builds tables and measures neighbours on: the available cores by default.
    pub threads: usize,
    /// Whether to measure each snapshot's neighbour table once it is serving. On by default.
    pub neighbours: bool,
    /// Records sampled for the neighbour table: 2,000 by default.
    pub sample: usize,
    /// The farthest distance the neighbour table counts at 64 bits: 16 by default.
    pub max_distance_64: u32,
    /// The farthest distance the neighbour table counts at 256 bits: 96 by default.
    pub max_distance_256: u32,
    /// The seed the sample is drawn with: 0 by default, so a snapshot's table is the same at every
    /// load.
    pub seed: u64,
    /// How long a snapshot that failed to load waits before it is tried again while `CURRENT`
    /// still names it: 300 s by default.
    pub retry_failed: Duration,
    /// The state directory that holds each index's change log, `STATE/<index>/`: changes are
    /// taken only with one. `None` by default: snapshots only.
    pub state_dir: Option<PathBuf>,
    /// Whether this catalog writes the change logs, holding each index's lock, as `serve` does;
    /// otherwise it only reads them, as `query` and `stats` do. Off by default.
    pub write_changes: bool,
    /// How long after it was applied a change task is still recognised as a repeat once a snapshot
    /// has covered its changes and the log has dropped them: 1 hour by default. While its changes
    /// are in the log it is recognised whatever this is.
    pub repeat_window: Duration,
    /// The largest change log read, in bytes, when an index opens and at each swap: a longer one
    /// refuses the index (`too_large`) without being read into memory. By default the default
    /// [`Limits::max_log_bytes`] and one largest change task: [`Limits::log_read_bound`]. To read
    /// a log a lowered bound refuses, raise it again.
    pub max_log_read_bytes: u64,
}

impl Default for LoadConfig {
    fn default() -> Self {
        Self {
            table_memory: TableMemory::Auto,
            threads: std::thread::available_parallelism().map_or(1, usize::from),
            neighbours: true,
            sample: 2_000,
            max_distance_64: 16,
            max_distance_256: 96,
            seed: 0,
            retry_failed: Duration::from_secs(300),
            state_dir: None,
            write_changes: false,
            repeat_window: Duration::from_secs(3600),
            max_log_read_bytes: Limits::new().log_read_bound(),
        }
    }
}

impl LoadConfig {
    /// The neighbour table's farthest distance at `width` bits.
    #[must_use]
    pub fn max_distance(&self, width: u32) -> u32 {
        if width == 64 {
            self.max_distance_64.min(64)
        } else {
            self.max_distance_256.min(256)
        }
    }
}

/// Something that happened while a [`Catalog`] refreshed, for a log.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Event {
    /// A `CURRENT` was refused, and what is served stays. Given once until it changes.
    Refused {
        /// `index` or `index.subset`.
        set: String,
        /// Why.
        reason: String,
    },
    /// A snapshot began to load, beside the one served if there is one.
    Loading {
        /// `index` or `index.subset`.
        set: String,
        /// The snapshot directory's name.
        snapshot: String,
        /// The bytes of its parts.
        bytes: u64,
    },
    /// A snapshot loaded and is now served.
    Loaded {
        /// `index` or `index.subset`.
        set: String,
        /// The snapshot directory's name.
        snapshot: String,
        /// Its records.
        records: usize,
        /// Its width.
        width: u32,
        /// Whether its multi-index tables were built.
        tables: bool,
        /// Milliseconds reading and checking the parts.
        load_ms: u64,
        /// Milliseconds building the tables.
        build_ms: u64,
        /// The snapshot it replaced, freed once the searches on it finish.
        replaced: Option<String>,
        /// The changes from the log replayed over it: entries above its `covers_seq`.
        replayed: usize,
        /// Milliseconds replaying them.
        replay_ms: u64,
        /// The last change applied over it: the log's position.
        seq: u64,
    },
    /// An index's change log was read when the program started: how much it holds, and what was
    /// cut from its end, an unfinished task's bytes and whole entries.
    LogOpened {
        /// The index.
        set: String,
        /// Whole tasks in the log.
        tasks: usize,
        /// Entries in the log.
        entries: usize,
        /// Its position, the last `seq` it gave.
        seq: u64,
        /// The bytes cut from its end, an unfinished task's.
        cut_bytes: u64,
        /// The whole entries among them.
        cut_entries: usize,
    },
    /// An index's change log was refused: damaged in the middle, or not this index's. The index
    /// serves nothing until it is repaired and the program restarted.
    LogRefused {
        /// The index.
        set: String,
        /// Why.
        reason: String,
    },
    /// An index's change log was shortened after a snapshot covering its first changes was
    /// served.
    LogShortened {
        /// The index.
        set: String,
        /// The snapshot's `covers_seq`.
        covers_seq: u64,
        /// The entries dropped.
        entries: usize,
        /// The log's bytes before and after.
        bytes_before: u64,
        /// The log's bytes after.
        bytes_after: u64,
    },
    /// Writing an index's change log failed. Changes to it are refused until the program
    /// restarts and reads the log again; searches go on.
    LogFailed {
        /// The index.
        set: String,
        /// What failed.
        reason: String,
    },
    /// A snapshot failed to load; what is served stays.
    Failed {
        /// `index` or `index.subset`.
        set: String,
        /// The snapshot directory's name.
        snapshot: String,
        /// The failure's code: `manifest`, `checksum`, `ids`, `io`, `memory`, `width`, or for an
        /// index that takes changes, `covers_seq` or `log`.
        code: &'static str,
        /// The failure in full, with the file at fault, and no record id or value in it.
        reason: String,
    },
    /// A served snapshot's neighbour table was measured.
    Measured {
        /// `index` or `index.subset`.
        set: String,
        /// The snapshot directory's name.
        snapshot: String,
        /// Records sampled.
        sample: usize,
        /// Milliseconds it took.
        ms: u64,
    },
}

/// A loaded snapshot, served until a newer one replaces it and the last search on it ends.
#[derive(Debug)]
pub(crate) struct Generation {
    pub(crate) snapshot: String,
    pub(crate) set: Sets,
    pub(crate) loaded_at: SystemTime,
    pub(crate) covers_seq: Option<u64>,
    pub(crate) load_ms: u64,
    pub(crate) build_ms: u64,
    pub(crate) table_bytes: u64,
    pub(crate) table_budget: Option<u64>,
    /// The changes replayed over the snapshot when it loaded, and the milliseconds it took.
    pub(crate) replayed: usize,
    pub(crate) replay_ms: u64,
    /// Measured over the snapshot alone, so shared by the generations a change makes of it.
    pub(crate) neighbours: Arc<OnceLock<Neighbours>>,
}

impl Generation {
    /// The same snapshot with `set`, the changes to a later `seq` over it.
    fn with_set(&self, set: Sets) -> Self {
        Self {
            snapshot: self.snapshot.clone(),
            set,
            loaded_at: self.loaded_at,
            covers_seq: self.covers_seq,
            load_ms: self.load_ms,
            build_ms: self.build_ms,
            table_bytes: self.table_bytes,
            table_budget: self.table_budget,
            replayed: self.replayed,
            replay_ms: self.replay_ms,
            neighbours: Arc::clone(&self.neighbours),
        }
    }
}

/// A measured neighbour table.
#[derive(Debug)]
pub(crate) struct Neighbours {
    pub(crate) table: NeighbourTable,
    pub(crate) max_distance: u32,
    pub(crate) ms: u64,
}

/// A load in progress.
#[derive(Debug, Clone)]
pub(crate) struct Loading {
    pub(crate) snapshot: String,
    pub(crate) read: Arc<AtomicU64>,
    pub(crate) total: u64,
}

impl Loading {
    /// The fraction of the parts' bytes read, when the total is known.
    pub(crate) fn fraction(&self) -> Option<f64> {
        (self.total > 0).then(|| {
            #[expect(clippy::cast_precision_loss, reason = "a fraction for a person to read")]
            let fraction = self.read.load(Ordering::Relaxed) as f64 / self.total as f64;
            (fraction * 1000.0).floor() / 1000.0
        })
    }
}

/// The last failed load.
#[derive(Debug, Clone)]
pub(crate) struct Failed {
    pub(crate) snapshot: String,
    pub(crate) code: &'static str,
    /// The reason, given in `stats` for the codes whose reasons name no file: `covers_seq`.
    pub(crate) reason: Option<String>,
    pub(crate) at: SystemTime,
    retry_at: Instant,
}

/// What an index's change log holds, for `stats`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct LogSummary {
    pub(crate) tasks: usize,
    pub(crate) entries: usize,
    pub(crate) bytes: u64,
    pub(crate) first_seq: Option<u64>,
    pub(crate) last_seq: u64,
    pub(crate) base_seq: u64,
}

impl LogSummary {
    fn of(parsed: &Parsed) -> Self {
        Self {
            tasks: parsed.tasks.len(),
            entries: parsed.entries.len(),
            bytes: parsed.end,
            first_seq: parsed.entries.first().map(|entry| entry.seq),
            last_seq: parsed.last_seq(),
            base_seq: parsed.base_seq(),
        }
    }
}

/// An index's change log, and the tasks it remembers.
#[derive(Debug)]
pub(crate) struct Changes {
    dir: PathBuf,
    /// The log open to append, with its lock; `None` when the catalog only reads it.
    file: Option<LogFile>,
    /// Every task in the log, by `task_id`, as it was answered.
    tasks: HashMap<String, TaskRecord>,
    summary: LogSummary,
    width: Option<u32>,
    /// Why the log can't be written since a write failed, until the program restarts: a code and
    /// what failed.
    broken: Option<Broken>,
    /// What opening the log found, told at the first refresh.
    events: Vec<Event>,
}

impl Changes {
    fn adopt(&mut self, parsed: &Parsed) {
        self.tasks = log::remembered(parsed);
        self.summary = LogSummary::of(parsed);
        self.width = parsed.header.as_ref().map(|header| header.width);
    }
}

/// Whether the process writes an index's change log: `Ok`, or `Broken` with a short code since a
/// write, a sync, a shortening or a swap's read of the log failed, until the program restarts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Writer {
    Ok,
    Broken(&'static str),
}

/// Marks the writer broken in `stats` when the section it guards unwinds: a change made durable
/// and not yet published leaves memory behind the log.
struct Unwinding<'a>(&'a Slot);

impl Drop for Unwinding<'_> {
    fn drop(&mut self) {
        if std::thread::panicking() {
            self.0.state().writer = Some(Writer::Broken("panicked"));
        }
    }
}

#[derive(Debug, Default)]
struct State {
    current: Option<Arc<Generation>>,
    loading: Option<Loading>,
    failed: Option<Failed>,
    refused: Option<String>,
    /// Why the index's change log is refused: nothing is served until it is repaired.
    log_refused: Option<LogError>,
    /// What the change log holds, when the index keeps one.
    log: Option<LogSummary>,
    /// Whether this process writes the change log, when it does.
    writer: Option<Writer>,
    /// The change tasks remembered, so a repeat is answered from the log.
    remembered: usize,
}

/// One index or subset.
#[derive(Debug)]
pub(crate) struct Slot {
    pub(crate) index: String,
    pub(crate) subset: Option<String>,
    dir: PathBuf,
    parent: Option<usize>,
    state: Mutex<State>,
    /// The change log of an index served with a state directory. Held while a change is applied
    /// and while a new snapshot is replayed and swapped in, so the two never interleave; a search
    /// never waits for it.
    changes: Option<Mutex<Changes>>,
}

/// What a slot holds at one moment, for `stats`.
#[derive(Debug, Clone)]
pub(crate) struct View {
    pub(crate) current: Option<Arc<Generation>>,
    pub(crate) loading: Option<Loading>,
    pub(crate) failed: Option<Failed>,
    pub(crate) log_refused: Option<LogError>,
    pub(crate) log: Option<LogSummary>,
    pub(crate) writer: Option<Writer>,
    pub(crate) remembered: usize,
}

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

    fn changes(&self) -> Option<MutexGuard<'_, Changes>> {
        self.changes
            .as_ref()
            .map(|changes| changes.lock().unwrap_or_else(PoisonError::into_inner))
    }

    pub(crate) fn label(&self) -> String {
        label(&self.index, self.subset.as_deref())
    }

    /// The snapshot served, to search: its `Arc` keeps it alive until the search ends, whatever
    /// replaces it meanwhile.
    pub(crate) fn ready(&self) -> Result<Arc<Generation>, ServiceError> {
        let state = self.state();
        if let Some(current) = &state.current {
            return Ok(Arc::clone(current));
        }
        let what = if self.subset.is_some() { "subset" } else { "index" };
        if let Some(reason) = &state.log_refused {
            let mut error = ServiceError::new(
                ErrorType::NotReady,
                format!("the index `{}` is refused: {}", self.label(), reason.message),
            );
            error.state = Some("refused");
            return Err(error);
        }
        let mut error = match &state.loading {
            Some(loading) => {
                let mut error = ServiceError::new(
                    ErrorType::NotReady,
                    format!("the {what} `{}` is loading its first snapshot", self.label()),
                );
                error.state = Some("loading");
                error.fraction = loading.fraction();
                error
            }
            None => ServiceError::new(
                ErrorType::NotReady,
                format!("the {what} `{}` has no snapshot loaded yet", self.label()),
            ),
        };
        error.state.get_or_insert("empty");
        Err(error)
    }

    pub(crate) fn view(&self) -> View {
        let state = self.state();
        View {
            current: state.current.clone(),
            loading: state.loading.clone(),
            failed: state.failed.clone(),
            log_refused: state.log_refused.clone(),
            log: state.log,
            writer: state.writer,
            remembered: state.remembered,
        }
    }

    fn width(&self) -> Option<u32> {
        self.state().current.as_ref().map(|current| current.set.width())
    }

    /// Show what the change log now holds in `stats`.
    fn mirror(&self, changes: &Changes) {
        let mut state = self.state();
        state.log = Some(changes.summary);
        state.remembered = changes.tasks.len();
    }

    /// Stop writing the change log until the program restarts, and say why: in `stats` with
    /// `code`, and in the log line the event returned gives.
    fn break_writer(&self, changes: &mut Changes, code: &'static str, reason: String) -> Event {
        let message = format!("changes are refused until the program restarts ({code}): {reason}");
        changes.broken = Some((code, reason));
        self.state().writer = Some(Writer::Broken(code));
        Event::LogFailed {
            set: self.label(),
            reason: message,
        }
    }
}

/// What a catalog serves, summed over its indexes and subsets, as [`Catalog::totals`] reads it: the
/// totals of `serve --stats-file`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Totals {
    /// The indexes and subsets served, loaded or not: `ready` plus `not_ready`.
    pub sets: u64,
    /// The records of the snapshots served, without the changes held over them.
    pub records: u64,
    /// The changes held over the snapshots served: ids with a changed value and ids removed.
    pub changes_held: u64,
    /// The indexes and subsets with a snapshot served, which a search is answered from.
    pub ready: u64,
    /// The rest: empty, loading a first snapshot, or refused, whose searches get `not_ready`.
    pub not_ready: u64,
}

/// The indexes and subsets a service serves.
#[derive(Debug)]
pub struct Catalog {
    slots: Vec<Slot>,
    config: LoadConfig,
    /// Points at which a test makes the catalog panic, by name.
    #[cfg(test)]
    pub(crate) faults: Mutex<Vec<&'static str>>,
}

/// Why a load failed: a code for `stats` and the reason in full for the log.
type Failure = (&'static str, String);

/// Why the writer stopped: a code for `stats` and what failed.
type Broken = (&'static str, String);

impl Catalog {
    /// A catalog of `specs`, nothing loaded yet: [`refresh`](Self::refresh) loads them.
    ///
    /// With a [`LoadConfig::state_dir`], each index's change log is read from `STATE/<index>/`, and
    /// with [`LoadConfig::write_changes`] it is opened to write: the index's lock is taken, and an
    /// unfinished task at the log's end is cut. A log damaged in the middle refuses its index, which
    /// then serves nothing (`stats` says why); the others are served.
    ///
    /// # Errors
    ///
    /// A message for a name that isn't valid, a set named twice, a subset of an index not given,
    /// a directory that isn't one, or when writing changes, a state directory that can't be used
    /// or an index whose lock another process holds.
    pub fn new(specs: Vec<SetSpec>, config: LoadConfig) -> Result<Self, String> {
        Self::with_disk(specs, config, &|dir| Box::new(FsDisk::new(dir)))
    }

    /// [`new`](Self::new), each index's change log on the [`Disk`] `disk` gives for its state
    /// directory: the file system's, or a test's double.
    pub(crate) fn with_disk(
        specs: Vec<SetSpec>,
        config: LoadConfig,
        disk: &dyn Fn(&Path) -> Box<dyn Disk>,
    ) -> Result<Self, String> {
        let mut ordered: Vec<SetSpec> = specs.iter().filter(|spec| spec.subset.is_none()).cloned().collect();
        ordered.extend(specs.into_iter().filter(|spec| spec.subset.is_some()));
        let mut slots: Vec<Slot> = Vec::with_capacity(ordered.len());
        for spec in ordered {
            check_name(&spec.index)?;
            if let Some(subset) = &spec.subset {
                check_name(subset)?;
            }
            if slots
                .iter()
                .any(|slot| slot.index == spec.index && slot.subset == spec.subset)
            {
                return Err(format!("`{}` is given twice", spec.label()));
            }
            let parent = match &spec.subset {
                None => None,
                Some(_) => Some(
                    slots
                        .iter()
                        .position(|slot| slot.subset.is_none() && slot.index == spec.index)
                        .ok_or_else(|| format!("the subset `{}` belongs to no `--index`", spec.label()))?,
                ),
            };
            if !spec.dir.is_dir() {
                return Err(format!(
                    "`{}` isn't a directory, for `{}`",
                    spec.dir.display(),
                    spec.label()
                ));
            }
            slots.push(Slot {
                index: spec.index,
                subset: spec.subset,
                dir: spec.dir,
                parent,
                state: Mutex::new(State::default()),
                changes: None,
            });
        }
        if slots.is_empty() {
            return Err("give at least one `--index name=dir`".to_owned());
        }
        if let Some(state_dir) = &config.state_dir {
            for slot in slots.iter_mut().filter(|slot| slot.subset.is_none()) {
                let dir = state_dir.join(&slot.index);
                let (file, parsed) = if config.write_changes {
                    let (file, parsed) = LogFile::open(disk(&dir), &slot.index, config.max_log_read_bytes)?;
                    (Some(file), parsed)
                } else {
                    (None, log::read(&dir, &slot.index, config.max_log_read_bytes))
                };
                let mut changes = Changes {
                    dir,
                    file,
                    tasks: HashMap::new(),
                    summary: LogSummary::default(),
                    width: None,
                    broken: None,
                    events: Vec::new(),
                };
                let state = slot.state.get_mut().unwrap_or_else(PoisonError::into_inner);
                match parsed {
                    Ok(parsed) => {
                        changes.adopt(&parsed);
                        state.log = Some(changes.summary);
                        state.remembered = changes.tasks.len();
                        state.writer = config.write_changes.then_some(Writer::Ok);
                        // A reader may meet a task being written: it isn't cut, and isn't told...
                        if config.write_changes {
                            let (cut_bytes, cut_entries) = parsed.cut.unwrap_or((0, 0));
                            changes.events.push(Event::LogOpened {
                                set: slot.index.clone(),
                                tasks: parsed.tasks.len(),
                                entries: parsed.entries.len(),
                                seq: parsed.last_seq(),
                                cut_bytes,
                                cut_entries,
                            });
                        }
                    }
                    Err(error) => {
                        changes.events.push(Event::LogRefused {
                            set: slot.index.clone(),
                            reason: format!("{} ({})", error.message, error.code),
                        });
                        state.log_refused = Some(error);
                    }
                }
                slot.changes = Some(Mutex::new(changes));
            }
        }
        Ok(Self {
            slots,
            config,
            #[cfg(test)]
            faults: Mutex::new(Vec::new()),
        })
    }

    /// Panic at `point` when a test asked for it; nothing outside tests.
    #[cfg_attr(not(test), expect(clippy::unused_self, reason = "a test's hook"))]
    #[cfg_attr(not(test), inline(always))]
    pub(crate) fn fault(&self, point: &'static str) {
        #[cfg(test)]
        assert!(
            !self
                .faults
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .contains(&point),
            "a fault injected at `{point}`"
        );
        #[cfg(not(test))]
        let _ = point;
    }

    /// How it loads.
    #[must_use]
    pub const fn config(&self) -> &LoadConfig {
        &self.config
    }

    /// Every index and subset, by its label, `index` or `index.subset`, with its directory.
    #[must_use]
    pub fn sets(&self) -> Vec<(String, PathBuf)> {
        self.slots.iter().map(|slot| (slot.label(), slot.dir.clone())).collect()
    }

    /// The labels of the indexes and subsets with no snapshot loaded, and why: what a one-shot
    /// command checks after [`refresh`](Self::refresh).
    #[must_use]
    pub fn unready(&self) -> Vec<(String, String)> {
        self.slots
            .iter()
            .filter_map(|slot| slot.ready().err().map(|error| (slot.label(), error.message)))
            .collect()
    }

    /// What every index and subset serves now, summed: counts only, no name.
    ///
    /// ```
    /// use legit_hamming::service::{Catalog, LoadConfig, SetSpec};
    ///
    /// let dir = std::env::temp_dir().join(format!("legit-hamming-totals-doc-{}", std::process::id()));
    /// std::fs::create_dir_all(&dir)?;
    /// let catalog = Catalog::new(vec![SetSpec::index("images", &dir)], LoadConfig::default())?;
    /// let totals = catalog.totals();
    /// // No `CURRENT` yet: served, and not ready...
    /// assert_eq!((totals.sets, totals.ready, totals.not_ready, totals.records), (1, 0, 1, 0));
    /// # std::fs::remove_dir_all(&dir)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn totals(&self) -> Totals {
        let mut totals = Totals::default();
        for slot in &self.slots {
            totals.sets += 1;
            // What a search finds: a snapshot served, whatever else the slot says...
            let current = slot.state().current.clone();
            match current {
                Some(generation) => {
                    totals.ready += 1;
                    totals.records += generation.set.len() as u64;
                    let (values, removals, _) = generation.set.changes();
                    totals.changes_held += (values + removals) as u64;
                }
                None => totals.not_ready += 1,
            }
        }
        totals
    }

    pub(crate) fn find(&self, index: &str, subset: Option<&str>) -> Result<&Slot, ServiceError> {
        let mut of_index = self.slots.iter().filter(|slot| slot.index == index).peekable();
        if of_index.peek().is_none() {
            return Err(unknown(ErrorType::UnknownIndex, "index", index));
        }
        of_index
            .find(|slot| slot.subset.as_deref() == subset)
            .ok_or_else(|| unknown(ErrorType::UnknownSubset, "subset", subset.unwrap_or_default()))
    }

    pub(crate) fn slots(&self) -> &[Slot] {
        &self.slots
    }

    /// Read every `CURRENT` and load each snapshot that changed, then measure the neighbour table
    /// of each snapshot served that has none yet: [`load_changed`](Self::load_changed), then
    /// [`measure_neighbours`](Self::measure_neighbours), telling `observe` what happens as it
    /// happens.
    pub fn refresh(&self, observe: &mut dyn FnMut(&Event)) {
        self.fault("refresh");
        self.load_changed(observe);
        self.measure_neighbours(observe);
    }

    /// Read every `CURRENT` and load each snapshot that changed, one at a time, indexes before
    /// their subsets, telling `observe` what happens as it happens.
    ///
    /// A new snapshot loads beside the one served, which goes on answering; once it has loaded
    /// and every checksum matched, it is swapped in, and the old one is freed when the last search
    /// on it ends. A `CURRENT` that is refused, or a snapshot that fails to load, leaves what is
    /// served as it is. A failed snapshot is tried again after [`LoadConfig::retry_failed`] while
    /// `CURRENT` still names it, at once when it names another.
    pub fn load_changed(&self, observe: &mut dyn FnMut(&Event)) {
        for slot in &self.slots {
            self.refresh_slot(slot, observe);
        }
    }

    /// Measure the neighbour table of each snapshot served that has none yet, if
    /// [`LoadConfig::neighbours`] is on. A search goes on meanwhile; `stats` says `measuring`.
    pub fn measure_neighbours(&self, observe: &mut dyn FnMut(&Event)) {
        if !self.config.neighbours {
            return;
        }
        for slot in &self.slots {
            let current = slot.state().current.clone();
            if let Some(generation) = current.filter(|generation| generation.neighbours.get().is_none()) {
                self.measure(slot, &generation, observe);
            }
        }
    }

    fn refresh_slot(&self, slot: &Slot, observe: &mut dyn FnMut(&Event)) {
        let events = slot.changes().map(|mut changes| std::mem::take(&mut changes.events));
        for event in events.iter().flatten() {
            observe(event);
        }
        if slot.state().log_refused.is_some() {
            return;
        }
        let name = match read_current(&slot.dir) {
            Ok(None) => {
                slot.state().refused = None;
                return;
            }
            Ok(Some(name)) => name,
            Err(reason) => {
                let mut state = slot.state();
                if state.refused.as_deref() != Some(reason.as_str()) {
                    state.refused = Some(reason.clone());
                    drop(state);
                    observe(&Event::Refused {
                        set: slot.label(),
                        reason,
                    });
                }
                return;
            }
        };
        {
            let mut state = slot.state();
            state.refused = None;
            if state.current.as_ref().is_some_and(|current| current.snapshot == name) {
                return;
            }
            if state
                .failed
                .as_ref()
                .is_some_and(|failed| failed.snapshot == name && Instant::now() < failed.retry_at)
            {
                return;
            }
        }
        let parent_width = match slot.parent {
            None => None,
            // A subset waits for its index, whose width it must have...
            Some(parent) => match self.slots[parent].width() {
                None => return,
                width => width,
            },
        };
        self.load(slot, &name, parent_width, observe);
    }

    fn load(&self, slot: &Slot, name: &str, parent_width: Option<u32>, observe: &mut dyn FnMut(&Event)) {
        let dir = slot.dir.join(name);
        // The manifest is opened and read once; its width and size come from those bytes...
        let loaded = open_manifest(&dir).and_then(|(path, manifest)| {
            let (width, bytes) = (manifest.width, manifest.part_bytes());
            let held = slot.width();
            if let Some(served) = parent_width.filter(|&served| served != width) {
                return Err((
                    "width",
                    format!("holds {width}-bit values; its index holds {served}-bit values"),
                ));
            }
            if let Some(served) = held.filter(|&served| served != width) {
                return Err((
                    "width",
                    format!("holds {width}-bit values; the snapshot served holds {served}-bit values"),
                ));
            }
            // The manifest adds up, and its parts are files of their sizes, no two the same, before
            // a load is told or anything reserved...
            let checked = if width == 64 {
                manifest.check::<u64>(&path)
            } else {
                manifest.check::<[u64; 4]>(&path)
            };
            checked
                .and_then(|()| snapshot::check_parts(&dir, &manifest))
                .map_err(|error| failure(&error, &dir))?;
            if let Some(available) = available_memory()
                && bytes > available
            {
                return Err((
                    "memory",
                    format!("needs {bytes} bytes for its records; {available} bytes are available"),
                ));
            }
            let loading = Loading {
                snapshot: name.to_owned(),
                read: Arc::new(AtomicU64::new(0)),
                total: bytes,
            };
            slot.state().loading = Some(loading.clone());
            observe(&Event::Loading {
                set: slot.label(),
                snapshot: name.to_owned(),
                bytes,
            });
            if width == 64 {
                self.build::<u64>(&dir, name, &manifest, &loading.read, Sets::W64)
            } else {
                self.build::<[u64; 4]>(&dir, name, &manifest, &loading.read, Sets::W256)
            }
        });
        // A change is applied, or a new snapshot replayed and swapped in, one at a time: a change
        // logged while the snapshot loaded is replayed over it...
        let mut changes = slot.changes();
        let mut broke = None;
        let loaded = loaded.and_then(|generation| match changes.as_deref_mut() {
            Some(changes) => {
                let parsed = self.read_log(changes, &slot.index).map_err(|(failure, broken)| {
                    broke = broken;
                    failure
                })?;
                replay(changes, &generation, parsed)
            }
            None => Ok((generation, None)),
        });
        if let (Some(changes), Some((code, reason))) = (changes.as_deref_mut(), broke) {
            let event = slot.break_writer(changes, code, reason);
            observe(&event);
        }
        let mut state = slot.state();
        state.loading = None;
        match loaded {
            Ok((generation, parsed)) => {
                let generation = Arc::new(generation);
                let replaced = state.current.replace(Arc::clone(&generation));
                state.failed = None;
                drop(state);
                observe(&Event::Loaded {
                    set: slot.label(),
                    snapshot: name.to_owned(),
                    records: generation.set.len(),
                    width: generation.set.width(),
                    tables: generation.set.has_tables(),
                    load_ms: generation.load_ms,
                    build_ms: generation.build_ms,
                    replaced: replaced.as_ref().map(|old| old.snapshot.clone()),
                    replayed: generation.replayed,
                    replay_ms: generation.replay_ms,
                    seq: generation.set.seq(),
                });
                // Freed here unless a search still holds it...
                drop(replaced);
                if let (Some(changes), Some(parsed), Some(covers)) =
                    (changes.as_deref_mut(), parsed, generation.covers_seq)
                {
                    self.shorten(slot, changes, &parsed, covers, observe);
                }
            }
            Err((code, reason)) => {
                state.failed = Some(Failed {
                    snapshot: name.to_owned(),
                    code,
                    reason: matches!(code, "covers_seq" | "log").then(|| reason.clone()),
                    at: SystemTime::now(),
                    retry_at: Instant::now() + self.config.retry_failed,
                });
                drop(state);
                observe(&Event::Failed {
                    set: slot.label(),
                    snapshot: name.to_owned(),
                    code,
                    reason,
                });
            }
        }
    }

    /// Drop from `slot`'s log what a snapshot covering every change to `covers` makes needless,
    /// when it is written by this process and there is something to drop: the entries of every
    /// covered task, and the records of covered tasks applied before the repeat window.
    fn shorten(
        &self,
        slot: &Slot,
        changes: &mut Changes,
        parsed: &Parsed,
        covers: u64,
        observe: &mut dyn FnMut(&Event),
    ) {
        let Some(file) = changes.file.as_mut() else {
            return;
        };
        if changes.broken.is_some() {
            return;
        }
        let keep_since = unix_millis().saturating_sub(millis(self.config.repeat_window));
        let needless = parsed.tasks.iter().any(|(record, _)| {
            record.last_seq().is_none_or(|last| last <= covers)
                && (record.entries > 0 || record.applied_at < keep_since)
        });
        if !needless && covers <= parsed.base_seq() {
            return;
        }
        match file.shorten(parsed, covers, keep_since) {
            Ok(shortened) => {
                changes.adopt(&shortened);
                slot.mirror(changes);
                observe(&Event::LogShortened {
                    set: slot.label(),
                    covers_seq: covers,
                    entries: parsed.entries.len() - shortened.entries.len(),
                    bytes_before: parsed.end,
                    bytes_after: shortened.end,
                });
            }
            Err(error) => {
                // Which file the log is now, and whether that is durable, isn't known: an append
                // could go to a file the directory no longer names. Changes stop until a restart
                // reads the log again; searches go on...
                let event = slot.break_writer(
                    changes,
                    "shorten_failed",
                    format!("the log couldn't be shortened: {error}"),
                );
                observe(&event);
            }
        }
    }

    /// Apply a change task to its index: log it, make it durable, then make it searchable, and
    /// return its result object. A task whose `task_id` the log holds is answered as it was the
    /// first time, and changes nothing.
    ///
    /// Whether the task fits the log, its bytes and its `seq`s, is decided before any work is
    /// done for it: a task the log can't take builds no level and encodes nothing.
    pub(crate) fn change(
        &self,
        task_id: &str,
        request: ChangeRequest,
        limits: &Limits,
    ) -> Result<String, ServiceError> {
        if !log::is_valid_task_id(task_id) {
            return Err(invalid_task_id());
        }
        let slot = self.find(&request.index, None)?;
        let Some(mut changes) = slot.changes() else {
            return Err(ServiceError::new(
                ErrorType::InvalidTask,
                "this service keeps no change log: start it with `--state-dir` to take changes",
            ));
        };
        if changes.file.is_none() {
            return Err(ServiceError::new(
                ErrorType::InvalidTask,
                "this program only reads the change log; `serve` takes changes",
            ));
        }
        let generation = slot.ready()?;
        if let Some((code, broken)) = &changes.broken {
            return Err(ServiceError::new(
                ErrorType::Internal,
                format!(
                    "writing the change log failed ({code}: {broken}); changes are refused until the program restarts"
                ),
            ));
        }
        let width = generation.set.width();
        if width != request.width {
            return Err(ServiceError::new(
                ErrorType::WidthMismatch,
                format!(
                    "`{}` holds {width}-bit values; the task gives `width` {}",
                    slot.label(),
                    request.width
                ),
            ));
        }
        if let Some(record) = changes.tasks.get(task_id) {
            return answer(&slot.index, record);
        }
        let room = Room {
            file: changes.file.as_ref().expect("checked above"),
            position: changes.summary.last_seq,
            bound: limits.max_log_bytes,
            held: changes.summary.bytes,
            label: slot.label(),
        };
        let (set, record, entries) = match (&generation.set, request.records) {
            (Sets::W64(set), ChangeRecords::W64(records)) => {
                let records: Vec<_> = records.into_iter().map(|(id, value)| (id, Some(value))).collect();
                plan(set, task_id, request.name, &records, &room, Sets::W64)
            }
            (Sets::W256(set), ChangeRecords::W256(records)) => {
                let records: Vec<_> = records.into_iter().map(|(id, value)| (id, Some(value))).collect();
                plan(set, task_id, request.name, &records, &room, Sets::W256)
            }
            (Sets::W64(set), ChangeRecords::Remove(ids)) => {
                let records: Vec<_> = ids.into_iter().map(|id| (id, None)).collect();
                plan(set, task_id, request.name, &records, &room, Sets::W64)
            }
            (Sets::W256(set), ChangeRecords::Remove(ids)) => {
                let records: Vec<_> = ids.into_iter().map(|id| (id, None)).collect();
                plan(set, task_id, request.name, &records, &room, Sets::W256)
            }
            _ => return Err(ServiceError::new(ErrorType::Internal, "the widths disagree")),
        }?;
        // From the write until the change is published, an unwinding leaves the writer broken:
        // the log may hold a change memory doesn't...
        let unwinding = Unwinding(slot);
        changes.broken = Some(("panicked", "a change unwound between the log and memory".to_owned()));
        let file = changes.file.as_mut().expect("checked above");
        match file.append(width, &record, &entries, limits.max_log_bytes) {
            Ok(Some(bytes)) => {
                self.fault("commit");
                let summary = &mut changes.summary;
                summary.tasks += 1;
                summary.entries += entries.len();
                summary.bytes += bytes;
                if let Some(last) = entries.last() {
                    summary.first_seq.get_or_insert(entries[0].seq);
                    summary.last_seq = last.seq;
                }
                changes.width = Some(width);
            }
            Ok(None) => {
                changes.broken = None;
                return Err(log_full(&slot.label(), changes.summary.bytes, limits.max_log_bytes));
            }
            Err(AppendError::Unrepresentable(field)) => {
                changes.broken = None;
                return Err(ServiceError::new(
                    ErrorType::InvalidTask,
                    format!("the task's {field} can't be recorded in the change log; nothing was written"),
                ));
            }
            Err(AppendError::Failed(code, error)) => {
                let event = slot.break_writer(&mut changes, code, format!("a change couldn't be written: {error}"));
                changes.events.push(event);
                return Err(ServiceError::new(
                    ErrorType::Internal,
                    format!(
                        "the change couldn't be written to the log ({code}: {error}); whether it was is unknown, \
                         and changes are refused until the program restarts: send it again with the same \
                         `task_id` then"
                    ),
                ));
            }
        }
        // Durable: now searchable, before the result can be read...
        self.fault("publish");
        if let Some(set) = set {
            let mut state = slot.state();
            if let Some(current) = &state.current {
                state.current = Some(Arc::new(current.with_set(set)));
            }
        }
        self.fault("remember");
        let answered = answer(&slot.index, &record);
        changes.tasks.insert(task_id.to_owned(), record);
        slot.mirror(&changes);
        changes.broken = None;
        drop(unwinding);
        answered
    }

    /// The change log of `changes` as a swap replays it: for this process's writer, read through
    /// the file it appends to and checked against what it made durable; for a reader, read as it
    /// is. A failure is the snapshot's, with the writer's code and reason when the writer must stop.
    fn read_log(&self, changes: &mut Changes, index: &str) -> Result<Parsed, (Failure, Option<Broken>)> {
        let max = self.config.max_log_read_bytes;
        match changes.file.as_mut() {
            None => log::read(&changes.dir, index, max).map_err(|error| (("log", error.message), None)),
            Some(_) if changes.broken.is_some() => {
                let code = changes.broken.as_ref().map_or("", |(code, _)| code);
                Err((
                    (
                        "log",
                        format!(
                            "this process stopped writing the change log ({code}), so what it holds isn't known; a \
                             restart reads it again"
                        ),
                    ),
                    None,
                ))
            }
            Some(file) => file.reread(max).map_err(|error| {
                let code = match error.code {
                    "missing" => "log_missing",
                    "replaced" => "log_replaced",
                    "appeared" => "log_appeared",
                    "changed" => "log_changed",
                    "cut" => "log_cut",
                    "too_large" => "log_too_large",
                    _ => "log_unreadable",
                };
                let reason = format!("{} ({code}); the snapshot served stays", error.message);
                (("log", reason), Some((code, error.message)))
            }),
        }
    }

    /// Read the parts of the snapshot in `dir` whose manifest has been read and checked, checking
    /// each, and build its tables within the budget.
    fn build<V: Value>(
        &self,
        dir: &Path,
        name: &str,
        manifest: &Manifest,
        read: &AtomicU64,
        wrap: fn(SearchSet<V>) -> Sets,
    ) -> Result<Generation, Failure> {
        let started = Instant::now();
        let records = snapshot::load_listed::<V>(dir, manifest, read).map_err(|error| failure(&error, dir))?;
        let load_ms = millis(started.elapsed());
        let records = Arc::new(records);
        let table_bytes = Planned::<V>::table_bytes(records.len()) as u64;
        let table_budget = match self.config.table_memory {
            TableMemory::Bytes(bytes) => Some(bytes),
            TableMemory::Auto => {
                available_memory().map(|available| available.saturating_sub((available / 4).max(TABLE_MARGIN_MIN)))
            }
        };
        let started = Instant::now();
        let planned = match table_budget {
            Some(budget) if table_bytes > budget => Planned::scan_only(records),
            _ => Planned::try_new(records, usize::MAX, self.config.threads).map_err(|error| failure(&error, dir))?,
        };
        Ok(Generation {
            snapshot: name.to_owned(),
            set: wrap(SearchSet::new(planned)),
            loaded_at: SystemTime::now(),
            covers_seq: manifest.covers_seq,
            load_ms,
            build_ms: millis(started.elapsed()),
            table_bytes,
            table_budget,
            replayed: 0,
            replay_ms: 0,
            neighbours: Arc::new(OnceLock::new()),
        })
    }

    fn measure(&self, slot: &Slot, generation: &Generation, observe: &mut dyn FnMut(&Event)) {
        let started = Instant::now();
        let max_distance = self.config.max_distance(generation.set.width());
        let table = generation
            .set
            .neighbours(self.config.sample, self.config.seed, max_distance, self.config.threads);
        let sample = table.sample;
        let ms = millis(started.elapsed());
        let _ = generation.neighbours.set(Neighbours {
            table,
            max_distance,
            ms,
        });
        observe(&Event::Measured {
            set: slot.label(),
            snapshot: generation.snapshot.clone(),
            sample,
            ms,
        });
    }
}

pub(crate) fn millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

/// Now, in Unix milliseconds.
fn unix_millis() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, millis)
}

/// Put the changes logged above a new snapshot's `covers_seq` over it, in order: the generation to
/// serve, at the log's position, and the log as it was read, `parsed`, for shortening.
///
/// A snapshot is refused when it can't be made exact: one without ids; one of another width than
/// the log; one whose `covers_seq` is past the log's last `seq`, claiming changes this service never
/// saw; and one that covers less than the log has dropped (no `covers_seq` counts as 0), whose
/// missing changes can't be replayed.
fn replay(
    changes: &mut Changes,
    generation: &Generation,
    parsed: Parsed,
) -> Result<(Generation, Option<Parsed>), Failure> {
    if !generation.set.has_ids() {
        return Err((
            "ids",
            "has no record ids; an index that takes changes needs them".to_owned(),
        ));
    }
    let width = generation.set.width();
    for logged in [changes.width, parsed.header.as_ref().map(|header| header.width)] {
        if let Some(logged) = logged.filter(|&logged| logged != width) {
            return Err((
                "width",
                format!("holds {width}-bit values; the index's change log holds {logged}-bit values"),
            ));
        }
    }
    let position = parsed.last_seq();
    let base = parsed.base_seq();
    match generation.covers_seq {
        Some(covers) if covers > position => {
            return Err((
                "covers_seq",
                format!(
                    "its covers_seq is {covers}, past {position}, the last change this service logged: it claims \
                     changes this service never saw"
                ),
            ));
        }
        Some(covers) if covers < base => {
            return Err((
                "covers_seq",
                format!(
                    "its covers_seq is {covers}, but the log has dropped every change to {base}, so the changes it \
                     misses can't be replayed"
                ),
            ));
        }
        None if base > 0 => {
            return Err((
                "covers_seq",
                format!(
                    "it has no covers_seq, but the log has dropped every change to {base}, so the changes it may \
                     miss can't be replayed"
                ),
            ));
        }
        _ => {}
    }
    let from = generation.covers_seq.unwrap_or(0);
    let entries = &parsed.entries[parsed.entries.partition_point(|entry| entry.seq <= from)..];
    let started = Instant::now();
    let set = match &generation.set {
        Sets::W64(set) => Sets::W64(set.with_changes(Overlay::over(set.records(), collapse(entries)), position)),
        Sets::W256(set) => Sets::W256(set.with_changes(Overlay::over(set.records(), collapse(entries)), position)),
    };
    let generation = Generation {
        replayed: entries.len(),
        replay_ms: millis(started.elapsed()),
        ..generation.with_set(set)
    };
    changes.adopt(&parsed);
    Ok((generation, Some(parsed)))
}

/// The `invalid_task` error for a `task_id` the log can't hold.
pub(crate) fn invalid_task_id() -> ServiceError {
    ServiceError::new(
        ErrorType::InvalidTask,
        format!(
            "a change task's `task_id` is 1 to {} of `A-Z`, `a-z`, `0-9`, `_` and `-`",
            log::TASK_ID_MAX
        ),
    )
}

/// The `log_full` error for a task that would take the log of `label`, holding `held` bytes, past
/// `bound`.
fn log_full(label: &str, held: u64, bound: u64) -> ServiceError {
    ServiceError::new(
        ErrorType::LogFull,
        format!(
            "the change log of `{label}` holds {held} bytes, and this task would take it past its bound of {bound}: \
             export a snapshot that covers its changes so it can be shortened"
        ),
    )
}

/// What a change is planned against: the log it must fit, and its position.
struct Room<'a> {
    file: &'a LogFile,
    position: u64,
    bound: u64,
    held: u64,
    label: String,
}

/// The entries and task record of a change task over `set`, and the set it makes, or for an
/// `append` that meets an id held with another value, a conflict record and no set.
///
/// The outcome is decided first, then whether the task fits the log, its exact bytes and its
/// `seq`s, refused `log_full` before any level is built or any byte encoded; then the entries and
/// the new set are made.
///
/// Every record of a task is logged, a value set to what it was and an id removed that isn't held
/// included: a later snapshot may have been read before the change, and the replay over it must
/// make the change again.
fn plan<V: Value>(
    set: &SearchSet<V>,
    task_id: &str,
    name: ChangeName,
    records: &[(u64, Option<V>)],
    room: &Room<'_>,
    wrap: fn(SearchSet<V>) -> Sets,
) -> Result<(Option<Sets>, TaskRecord, Vec<Entry>), ServiceError> {
    let mut tally = Tally::default();
    let mut conflicts = Vec::new();
    for &(id, value) in records {
        match (set.get(id), value) {
            (Some(held), Some(value)) if held == value => tally.unchanged += 1,
            (Some(_), Some(_)) if name == ChangeName::Append => conflicts.push(id),
            (Some(_), Some(_)) => tally.changed += 1,
            (None, Some(_)) => tally.added += 1,
            (Some(_), None) => tally.removed += 1,
            (None, None) => tally.unchanged += 1,
        }
    }
    let position = room.position;
    let width = V::BITS;
    // Whether the log can take it, before anything is built...
    let (sets, removes) = if conflicts.is_empty() {
        let sets = records.iter().filter(|(_, value)| value.is_some()).count();
        (sets, records.len() - sets)
    } else {
        (0, 0)
    };
    let bytes = log::framed_bytes(width, sets, removes, conflicts.len(), task_id.len());
    if bytes.is_none_or(|bytes| !room.file.fits(width, bytes, room.bound)) {
        return Err(log_full(&room.label, room.held, room.bound));
    }
    let last = if conflicts.is_empty() {
        position.checked_add(records.len() as u64)
    } else {
        Some(position)
    };
    let Some(seq) = last else {
        return Err(ServiceError::new(
            ErrorType::LogFull,
            format!(
                "the change log of `{}` is at seq {position}, and this task's {} changes would take it past the last \
                 seq there is: the sequence is exhausted",
                room.label,
                records.len()
            ),
        ));
    };
    let record = |outcome, entries| TaskRecord {
        task_id: task_id.to_owned(),
        name,
        outcome,
        applied_at: unix_millis(),
        first_seq: position.saturating_add(1),
        entries,
    };
    if !conflicts.is_empty() {
        let count = u32::try_from(conflicts.len()).unwrap_or(u32::MAX);
        conflicts.truncate(CONFLICT_IDS);
        let record = TaskRecord {
            first_seq: position,
            ..record(Outcome::Conflict { ids: conflicts, count }, 0)
        };
        return Ok((None, record, Vec::new()));
    }
    let entries: Vec<Entry> = records
        .iter()
        .zip(position + 1..=seq)
        .map(|(&(id, value), seq)| Entry::new(seq, id, value))
        .collect();
    let count = u32::try_from(entries.len()).unwrap_or(u32::MAX);
    let next = set.with_changes(set.overlay().with(records), seq);
    Ok((
        Some(wrap(next)),
        record(Outcome::Applied { seq, tally }, count),
        entries,
    ))
}

/// A change task's result object, its keys in the contract's order.
#[derive(serde::Serialize)]
struct ChangeObject<'a> {
    format: u32,
    index: &'a str,
    seq: u64,
    added: u32,
    changed: u32,
    removed: u32,
    unchanged: u32,
}

/// The answer a task got: its result object, or its conflict.
fn answer(index: &str, record: &TaskRecord) -> Result<String, ServiceError> {
    match &record.outcome {
        Outcome::Applied { seq, tally } => serde_json::to_string(&ChangeObject {
            format: super::FORMAT,
            index,
            seq: *seq,
            added: tally.added,
            changed: tally.changed,
            removed: tally.removed,
            unchanged: tally.unchanged,
        })
        .map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string())),
        Outcome::Conflict { ids, count } => {
            let mut error = ServiceError::new(
                ErrorType::Conflict,
                format!(
                    "{count} of the task's records give an id the index holds with another value; nothing was applied"
                ),
            );
            error.ids = Some(ids.clone());
            error.count = Some(u64::from(*count));
            Err(error)
        }
    }
}

/// The most bytes of a name from a file a log line quotes.
const LABEL_BYTES: usize = 64;

/// `text` as a log may quote it: its first 64 bytes, each byte that isn't printable ASCII, or is a
/// backtick, replaced by `?`.
fn log_label(text: &str) -> String {
    text.bytes()
        .take(LABEL_BYTES)
        .map(|byte| {
            if (byte.is_ascii_graphic() && byte != b'`') || byte == b' ' {
                char::from(byte)
            } else {
                '?'
            }
        })
        .collect()
}

/// The file at `path`, in the snapshot directory `dir`, as a load failure names it: the directory,
/// which the configuration and a checked `CURRENT` gave, and a label of the file's name.
fn shown(dir: &Path, path: &Path) -> String {
    let name = path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default();
    format!("{}/{}", dir.display(), log_label(&name))
}

/// A library error loading the snapshot in `dir` as a failure: its code, and a reason in fixed
/// words with positions and counts, naming the file at fault by a label of its name. Nothing a
/// manifest holds as text is quoted, nor any record id or value, which are an application's data:
/// `legit-hamming verify` gives the library's message in full to the person who runs it.
fn failure(error: &Error, dir: &Path) -> Failure {
    match error {
        Error::Checksum { path, .. } => (
            "checksum",
            format!(
                "snapshot part `{}`: its SHA-256 isn't the one the manifest records",
                shown(dir, path)
            ),
        ),
        Error::Io { path, source } => ("io", format!("couldn't read `{}`: {source}", shown(dir, path))),
        Error::IdOrder { .. } => (
            "ids",
            format!(
                "snapshot `{}`: a record id isn't above the id before it; records go in rising id order",
                dir.display()
            ),
        ),
        Error::OutOfMemory { .. } => ("memory", format!("snapshot `{}`: {error}", dir.display())),
        Error::Snapshot { path, reason } => {
            let fault = Fault::of(reason);
            let words = fault.map_or("doesn't agree with the snapshot format", Fault::words);
            // The parser's message can quote the file: only where it went wrong is kept...
            let location = if fault == Some(Fault::Parse) {
                reason
                    .rfind(" at line ")
                    .map(|at| &reason[at..])
                    .filter(|location| {
                        location
                            .bytes()
                            .all(|byte| byte.is_ascii_digit() || b" atlinecolum".contains(&byte))
                    })
                    .unwrap_or_default()
            } else {
                ""
            };
            (
                "manifest",
                format!("snapshot file `{}`: {words}{location}", shown(dir, path)),
            )
        }
        _ => ("manifest", format!("snapshot `{}`: {error}", dir.display())),
    }
}

/// The snapshot name `dir`'s `CURRENT` gives, `None` when there is no `CURRENT`, or why it is
/// refused: a `CURRENT` that is a symbolic link or not a file, longer than a name, or not one line
/// naming one directory inside `dir` that isn't itself a symbolic link. `CURRENT` is opened once,
/// and its type, size and identity checked on the handle read. A refusal quotes nothing of the
/// file but a name it gave that is a valid snapshot name.
fn read_current(dir: &Path) -> Result<Option<String>, String> {
    let path = dir.join(CURRENT);
    let (file, metadata) = match snapshot::open_file(&path) {
        Ok(opened) => opened,
        Err(Error::Io { source, .. }) if source.kind() == ErrorKind::NotFound => return Ok(None),
        Err(Error::Io { source, .. }) => return Err(format!("`CURRENT` can't be read: {source}")),
        Err(Error::Snapshot { reason, .. }) => {
            return Err(match Fault::of(&reason) {
                Some(Fault::Link) => "`CURRENT` is a symbolic link; it must be a file".to_owned(),
                Some(Fault::NotFile) => "`CURRENT` isn't a file".to_owned(),
                _ => "`CURRENT` changed while it was opened".to_owned(),
            });
        }
        Err(error) => return Err(format!("`CURRENT` can't be read: {error}")),
    };
    let too_long = || format!("`CURRENT` is more than {CURRENT_MAX_BYTES} bytes; it names one directory");
    if metadata.len() > CURRENT_MAX_BYTES {
        return Err(too_long());
    }
    let mut bytes = Vec::new();
    file.take(CURRENT_MAX_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| format!("`CURRENT` can't be read: {error}"))?;
    if bytes.len() as u64 > CURRENT_MAX_BYTES {
        return Err(format!(
            "`CURRENT` is more than {CURRENT_MAX_BYTES} bytes; it names one directory"
        ));
    }
    let text = String::from_utf8(bytes).map_err(|_| "`CURRENT` isn't UTF-8".to_owned())?;
    let name = text
        .strip_suffix('\n')
        .map_or(text.as_str(), |line| line.strip_suffix('\r').unwrap_or(line));
    if !is_snapshot_name(name) {
        return Err(format!(
            "`CURRENT` must be one line naming a snapshot directory inside `{}`: 1 to {SNAPSHOT_NAME_MAX} of \
             `A-Z`, `a-z`, `0-9`, `.`, `_`, `:` and `-`, not starting with `.`",
            dir.display()
        ));
    }
    let snapshot = dir.join(name);
    let shown = log_label(name);
    let metadata = match fs::symlink_metadata(&snapshot) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == ErrorKind::NotFound => {
            return Err(format!("`CURRENT` names `{shown}`, which doesn't exist"));
        }
        Err(error) => return Err(format!("`CURRENT` names `{shown}`, which can't be read: {error}")),
    };
    if metadata.file_type().is_symlink() {
        return Err(format!(
            "`CURRENT` names `{shown}`, a symbolic link; it must be a directory"
        ));
    }
    if !metadata.is_dir() {
        return Err(format!("`CURRENT` names `{shown}`, which isn't a directory"));
    }
    let inside = fs::canonicalize(&snapshot)
        .ok()
        .zip(fs::canonicalize(dir).ok())
        .is_some_and(|(snapshot, dir)| snapshot.parent() == Some(dir.as_path()));
    if !inside {
        return Err(format!(
            "`CURRENT` names `{shown}`, which isn't inside `{}`",
            dir.display()
        ));
    }
    Ok(Some(name.to_owned()))
}

/// Whether `name` can be a snapshot directory's name: one path component, of a plain character set.
fn is_snapshot_name(name: &str) -> bool {
    (1..=SNAPSHOT_NAME_MAX).contains(&name.len())
        && !name.starts_with('.')
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
}

/// Read the manifest of the snapshot in `dir`, opened and read once within its cap, a file and not
/// a symbolic link, of the width 64 or 256: its path and it, which the load then checks and reads
/// the parts of. Its width and the bytes of its parts come from these bytes, read before anything
/// is reserved.
fn open_manifest(dir: &Path) -> Result<(PathBuf, Manifest), Failure> {
    let (path, manifest) = snapshot::read_manifest(dir).map_err(|error| failure(&error, dir))?;
    if !matches!(manifest.width, 64 | 256) {
        return Err((
            "manifest",
            format!("snapshot file `{}`: gives no width of 64 or 256", shown(dir, &path)),
        ));
    }
    Ok((path, manifest))
}

/// What `verify` found in a sound snapshot.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[non_exhaustive]
pub struct Verified {
    /// The value width in bits.
    pub width: u32,
    /// Whether its records carry ids.
    pub ids: bool,
    /// How many records it holds.
    pub records: u64,
    /// The first record's id, with ids.
    pub first_id: Option<u64>,
    /// The last record's id, with ids.
    pub last_id: Option<u64>,
    /// How many part files it has.
    pub parts: usize,
    /// The bytes of its parts.
    pub bytes: u64,
    /// The manifest's `covers_seq`, if it gives one.
    pub covers_seq: Option<u64>,
}

/// Check the snapshot in `dir` as a service would before loading it, without holding its records
/// in memory: the manifest and every part are files, not symbolic links, each opened once; the
/// manifest adds up; and every part has its size and SHA-256 and the ids rise, read once through a
/// buffer of 4,096 records ([`snapshot::verify`]). Nothing is mapped.
///
/// # Errors
///
/// What is wrong, in full, with the file at fault: the library's message, for the person who runs
/// the check, which may quote what the manifest holds.
pub fn verify_snapshot(dir: &Path) -> Result<Verified, String> {
    let (path, manifest) = snapshot::read_manifest(dir).map_err(|error| error.to_string())?;
    let manifest = match manifest.width {
        64 => snapshot::verify_listed::<u64>(dir, &path, manifest),
        256 => snapshot::verify_listed::<[u64; 4]>(dir, &path, manifest),
        width => {
            return Err(format!(
                "snapshot file `{}`: gives width {width}, not 64 or 256",
                path.display()
            ));
        }
    }
    .map_err(|error| error.to_string())?;
    Ok(Verified {
        width: manifest.width,
        ids: manifest.ids,
        records: manifest.records,
        first_id: manifest.first_id,
        last_id: manifest.last_id,
        parts: manifest.parts.len(),
        bytes: manifest.part_bytes(),
        covers_seq: manifest.covers_seq,
    })
}

#[cfg(test)]
mod tests {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    use serde_json::Value as Json;

    use super::super::log::double::MemDisk;
    use super::super::set::LEVELS_BUILT;
    use super::*;
    use crate::Records;
    use crate::service::{Lane, Service};

    /// A set directory serving `s0`, removed when dropped.
    struct SetDir(PathBuf);

    impl SetDir {
        fn new(name: &str) -> Self {
            let dir = std::env::temp_dir().join(format!("legit-hamming-catalog-{name}-{}", std::process::id()));
            let _ = fs::remove_dir_all(&dir);
            let records = Records::from_records([(1u64, 0xffu64), (2, 0xf0)]).expect("ids rise");
            snapshot::write(&dir.join("s0"), &records, 10).expect("written");
            fs::write(dir.join(CURRENT), "s0\n").expect("written");
            Self(dir)
        }
    }

    impl Drop for SetDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// A service over `dir` whose index writes its change log on `disk`: a process started.
    fn open(dir: &SetDir, disk: &MemDisk, limits: Limits) -> Service {
        let config = LoadConfig {
            neighbours: false,
            threads: 1,
            state_dir: Some(PathBuf::from("state")),
            write_changes: true,
            ..LoadConfig::default()
        };
        let disk = disk.clone();
        let catalog = Catalog::with_disk(vec![SetSpec::index("m", &dir.0)], config, &move |_| {
            Box::new(disk.clone()) as Box<dyn Disk>
        })
        .expect("opens");
        catalog.refresh(&mut |_| {});
        Service::new(Arc::new(catalog), limits, 1)
    }

    fn replace(service: &Service, task_id: &str, id: u64, value: u64) -> Result<Json, ServiceError> {
        let options = format!(r#"{{"format":1,"index":"m","width":64,"records":[[{id},"{value:016x}"]]}}"#);
        service
            .change(task_id, "replace", &options)
            .map(|json| serde_json::from_str(&json).expect("JSON"))
    }

    fn stats(service: &Service) -> Json {
        serde_json::from_str(&service.stats(r#"{"format":1,"index":"m"}"#).expect("stats")).expect("JSON")
    }

    fn found(service: &Service, value: u64) -> Json {
        let options = format!(r#"{{"format":1,"index":"m","width":64,"radius":0,"values":["{value:016x}"]}}"#);
        let json = service.search(&options, Lane::Bulk).expect("searched").json;
        serde_json::from_str::<Json>(&json).expect("JSON")["queries"][0]["matches"].clone()
    }

    /// The task ids the durable bytes hold: what a machine failure leaves.
    fn durable_tasks(disk: &MemDisk) -> Vec<String> {
        disk.state().durable.as_ref().map_or_else(Vec::new, |bytes| {
            log::parse(bytes, "m")
                .expect("reads")
                .tasks
                .iter()
                .map(|(record, _)| record.task_id.clone())
                .collect()
        })
    }

    #[test]
    fn a_task_written_before_a_crash_is_durable_before_its_repeat_is_answered() {
        let dir = SetDir::new("recovered");
        let disk = MemDisk::default();
        let service = open(&dir, &disk, Limits::default());
        // The task reaches the file; `fdatasync` and then the cut back fail, as a process that
        // dies there leaves it...
        {
            let mut state = disk.state();
            state.fail_sync_data = true;
            state.fail_truncate = true;
        }
        assert_eq!(
            replace(&service, "t1", 7, 0x0f).expect_err("unknown").error_type,
            ErrorType::Internal
        );
        drop(service);
        disk.state().fail_truncate = false;
        assert!(durable_tasks(&disk).is_empty());
        // ...a restart reads it whole, and a repeat is answered from it: only once it is durable.
        let service = open(&dir, &disk, Limits::default());
        let again = replace(&service, "t1", 7, 0x0f).expect("answered");
        assert_eq!(again["seq"], 1);
        assert_eq!(durable_tasks(&disk), ["t1"]);
        disk.crash();
        let service = open(&dir, &disk, Limits::default());
        assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), again);
        assert_eq!(stats(&service)["seq"], 1);
    }

    #[test]
    fn the_state_directory_is_durable_from_the_first_change() {
        let dir = SetDir::new("first");
        let disk = MemDisk::default();
        let service = open(&dir, &disk, Limits::default());
        let first = replace(&service, "t1", 7, 0x0f).expect("applied");
        drop(service);
        disk.crash();
        let service = open(&dir, &disk, Limits::default());
        assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), first);
        assert_eq!(found(&service, 0x0f)[0]["id"], 7);
        let calls = disk.state().calls.clone();
        let made = calls.iter().position(|call| *call == "make_dir").expect("made");
        assert_eq!(calls[made + 1], "sync_parent", "{calls:?}");
    }

    #[test]
    fn a_failed_sync_breaks_the_writer_and_stats_says_how() {
        for (fail_truncate, code, survives) in [(false, "sync_failed", false), (true, "rollback_failed", true)] {
            let dir = SetDir::new(code);
            let disk = MemDisk::default();
            let service = open(&dir, &disk, Limits::default());
            replace(&service, "t0", 9, 0x01).expect("applied");
            {
                let mut state = disk.state();
                state.fail_sync_data = true;
                state.fail_truncate = fail_truncate;
            }
            let error = replace(&service, "t1", 7, 0x0f).expect_err("unknown");
            assert_eq!(error.error_type, ErrorType::Internal);
            assert!(error.message.contains("same `task_id`"), "{}", error.message);
            let changes = &stats(&service)["changes"];
            assert_eq!(
                (&changes["writer"], &changes["writer_reason"]),
                (&json("broken"), &json(code))
            );
            // Nothing more is written, and searches go on at the last change answered...
            assert_eq!(
                replace(&service, "t2", 8, 0x02).expect_err("refused").error_type,
                ErrorType::Internal
            );
            assert_eq!(stats(&service)["seq"], 1);
            drop(service);
            disk.state().fail_truncate = false;
            // ...and a restart reads what the disk holds: the task cut back, or whole and applied,
            // and either way a repeat under the same id gives one answer from then on.
            let service = open(&dir, &disk, Limits::default());
            assert_eq!(stats(&service)["changes"]["writer"], "ok");
            assert_eq!(stats(&service)["seq"], if survives { 2 } else { 1 });
            let again = replace(&service, "t1", 7, 0x0f).expect("answered");
            assert_eq!(again["seq"], 2);
            assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), again);
            assert_eq!(durable_tasks(&disk), ["t0", "t1"]);
        }
    }

    fn json(text: &str) -> Json {
        Json::String(text.to_owned())
    }

    #[test]
    fn log_full_is_decided_before_any_level_is_built() {
        let dir = SetDir::new("full");
        let disk = MemDisk::default();
        let service = open(&dir, &disk, Limits::default());
        LEVELS_BUILT.with(|built| built.set(0));
        replace(&service, "t1", 7, 0x0f).expect("applied");
        assert!(LEVELS_BUILT.with(std::cell::Cell::get) > 0, "a change builds a level");
        let held = stats(&service)["changes"]["log"]["bytes"].as_u64().expect("bytes");
        drop(service);
        // Room for less than one more task...
        let limits = Limits {
            max_log_bytes: held + 50,
            ..Limits::default()
        };
        let service = open(&dir, &disk, limits);
        LEVELS_BUILT.with(|built| built.set(0));
        let full = replace(&service, "t2", 8, 0x0f).expect_err("full");
        assert_eq!(full.error_type, ErrorType::LogFull);
        assert_eq!(
            LEVELS_BUILT.with(std::cell::Cell::get),
            0,
            "a refused task builds no level"
        );
        assert_eq!(disk.state().visible.as_ref().map(Vec::len), Some(held as usize));
    }

    #[test]
    fn a_change_that_unwinds_between_the_log_and_memory_breaks_the_writer() {
        for point in ["commit", "publish", "remember"] {
            let dir = SetDir::new(point);
            let disk = MemDisk::default();
            let service = open(&dir, &disk, Limits::default());
            service.catalog().faults.lock().expect("faults").push(point);
            let unwound = catch_unwind(AssertUnwindSafe(|| replace(&service, "t1", 7, 0x0f)));
            assert!(unwound.is_err(), "{point}");
            service.catalog().faults.lock().expect("faults").clear();
            let changes = &stats(&service)["changes"];
            assert_eq!(
                (&changes["writer"], &changes["writer_reason"]),
                (&json("broken"), &json("panicked")),
                "{point}"
            );
            assert_eq!(
                replace(&service, "t2", 8, 0x02).expect_err("refused").error_type,
                ErrorType::Internal,
                "{point}"
            );
            drop(service);
            // The task was durable: a restart serves it, and answers its repeat.
            let service = open(&dir, &disk, Limits::default());
            assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered")["seq"], 1, "{point}");
            assert_eq!(replace(&service, "t2", 8, 0x02).expect("applied")["seq"], 2, "{point}");
        }
    }
}