kividb 1.2.2

A fast RedisĀ®-compatible in-memory store written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
//! One shard of a database's keyspace, behind an interface that does not
//! say how it is kept.
//!
//! Commands ask for a key's value and get a [`ValueRef`], a view of it that
//! lives as long as the shard's lock. They never see a `&KiviDBValue` from
//! the table. A value going in, coming out or moving between keys is an
//! owned [`KiviDBValue`] (or, coming out, a [`Taken`] entry that can give
//! one).
//!
//! The table is hashbrown's, used directly: its buckets can be reached by
//! index, which is what a cursor that survives the lock being let go
//! (compaction), and a key picked at random (`RANDOMKEY`, eviction), need.
//! Each bucket is an eight-byte [`Slot`]: the address of one block holding
//! the key and its value together (`entry`), and its time to live if it has
//! one.
//!
//! **Times to live.** A write that gives a key a value keeps the time to
//! live the key had ([`ShardMap::insert`], [`ShardMap::insert_str`]), as
//! writing the value of a key does in Redis when the command does not say
//! otherwise; the `_expiring` forms set it, or take it away, in the same
//! step. A key past its time is absent to reads and writes here, though it
//! stays in the table until expiry takes it out. Beside the table, the
//! shard keeps a list of the entries that have one, each entry knowing its
//! place in it: what active expiry goes through and what the `volatile-*`
//! policies pick from, at random in one step.
//!
//! **A key's use.** The lookups a command makes to read or write a key
//! write its use to the key's entry as they find it, when the command counts
//! as a use under the eviction policy (`access`): [`ShardMap::get`],
//! `get_expiring`, `lookup`, `contains_key`, `use_key`, every write of a
//! value, `set_expires` and `persist`. [`ShardMap::peek`], `expires`,
//! `access` and the walks over the table never do, and nothing does to a
//! key past its time: that key is gone, whatever its entry says.
//!
//! **Writes in place.** A string written over a string kept inline goes
//! into the same block when the table alone holds the entry, the key is not
//! past its time, and the new length keeps the block in its slab class
//! ([`ShardMap::set_str`], `append_in_place`, `set_range_in_place`): nothing
//! is allocated or freed, and the entry stays where it is. Anything else,
//! and every entry somebody else holds (a snapshot being written), gets a
//! new entry, as before.

use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use hashbrown::HashTable;
use parking_lot::RwLock;

use super::access;
use super::entry::{Entry, Left, Relocation, Slot};
pub use super::entry::{EntryRef, Taken};
use super::ttl_list::TtlList;
use crate::shared_bytes::SharedBytes;
use crate::types::{
    ArrayInner, HashFields, HashInner, KiviDBValue, SortedSetInner, StreamInner, TsInner,
    VectorSetInner,
};

/// A key's string value, borrowed from its shard: its bytes, kept in the
/// key's entry, or a `SharedBytes` of their own when they are too long.
#[derive(Clone, Copy)]
pub struct StrRef<'a>(Bytes<'a>);

#[derive(Clone, Copy)]
enum Bytes<'a> {
    Inline(&'a [u8]),
    Shared(&'a SharedBytes),
}

impl<'a> StrRef<'a> {
    #[inline]
    pub(super) fn bytes(bytes: &'a [u8]) -> Self {
        StrRef(Bytes::Inline(bytes))
    }

    #[inline]
    pub fn as_bytes(self) -> &'a [u8] {
        match self.0 {
            Bytes::Inline(bytes) => bytes,
            Bytes::Shared(shared) => shared.as_slice(),
        }
    }

    /// The bytes, to keep once the shard is let go of: a second hold on
    /// the same block when they have one of their own, a copy when they are
    /// in the key's entry.
    #[inline]
    pub fn to_shared(self) -> SharedBytes {
        match self.0 {
            Bytes::Inline(bytes) => SharedBytes::from(bytes),
            Bytes::Shared(shared) => shared.clone(),
        }
    }

    /// The `SharedBytes` the bytes are in, when they are not in the entry.
    #[inline]
    pub(super) fn shared(self) -> Option<&'a SharedBytes> {
        match self.0 {
            Bytes::Inline(_) => None,
            Bytes::Shared(shared) => Some(shared),
        }
    }

    /// Whether `other` is this very value, not merely equal bytes. Bytes
    /// in an entry are no `SharedBytes`: never.
    #[inline]
    pub fn is(self, other: &SharedBytes) -> bool {
        self.shared()
            .is_some_and(|shared| SharedBytes::ptr_eq(shared, other))
    }
}

impl std::ops::Deref for StrRef<'_> {
    type Target = [u8];
    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<[u8]> for StrRef<'_> {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

/// A key's value, borrowed from its shard: what [`ShardMap::get`] gives.
/// The variants are [`KiviDBValue`]'s. A collection is its shared handle,
/// which a command locks, or clones to keep.
#[derive(Clone, Copy)]
pub enum ValueRef<'a> {
    String(StrRef<'a>),
    List(&'a Arc<RwLock<VecDeque<Arc<[u8]>>>>),
    Hash(&'a Arc<RwLock<HashFields>>),
    Json(&'a Arc<RwLock<serde_json::Value>>),
    Set(&'a Arc<RwLock<crate::member_set::MemberSet>>),
    VectorSet(&'a Arc<RwLock<VectorSetInner>>),
    SortedSet(&'a Arc<RwLock<SortedSetInner>>),
    Stream(&'a Arc<RwLock<StreamInner>>),
    TimeSeries(&'a Arc<RwLock<TsInner>>),
    HashEx(&'a Arc<RwLock<HashInner>>),
    Array(&'a Arc<RwLock<ArrayInner>>),
}

impl<'a> From<&'a KiviDBValue> for ValueRef<'a> {
    #[inline]
    fn from(value: &'a KiviDBValue) -> Self {
        match value {
            KiviDBValue::String(v) => ValueRef::String(StrRef(Bytes::Shared(v))),
            KiviDBValue::List(v) => ValueRef::List(v),
            KiviDBValue::Hash(v) => ValueRef::Hash(v),
            KiviDBValue::Json(v) => ValueRef::Json(v),
            KiviDBValue::Set(v) => ValueRef::Set(v),
            KiviDBValue::VectorSet(v) => ValueRef::VectorSet(v),
            KiviDBValue::SortedSet(v) => ValueRef::SortedSet(v),
            KiviDBValue::Stream(v) => ValueRef::Stream(v),
            KiviDBValue::TimeSeries(v) => ValueRef::TimeSeries(v),
            KiviDBValue::HashEx(v) => ValueRef::HashEx(v),
            KiviDBValue::Array(v) => ValueRef::Array(v),
        }
    }
}

impl KiviDBValue {
    /// A view of an owned value, as [`ShardMap::get`] gives one of a stored
    /// value: for code that takes either.
    #[inline]
    pub fn view(&self) -> ValueRef<'_> {
        ValueRef::from(self)
    }
}

impl ValueRef<'_> {
    /// The value, to keep once the shard is let go of: another handle on
    /// the same string or collection (see [`KiviDBValue::deep_clone`] for a
    /// copy that shares nothing).
    pub fn to_value(self) -> KiviDBValue {
        match self {
            ValueRef::String(v) => KiviDBValue::String(v.to_shared()),
            ValueRef::List(v) => KiviDBValue::List(Arc::clone(v)),
            ValueRef::Hash(v) => KiviDBValue::Hash(Arc::clone(v)),
            ValueRef::Json(v) => KiviDBValue::Json(Arc::clone(v)),
            ValueRef::Set(v) => KiviDBValue::Set(Arc::clone(v)),
            ValueRef::VectorSet(v) => KiviDBValue::VectorSet(Arc::clone(v)),
            ValueRef::SortedSet(v) => KiviDBValue::SortedSet(Arc::clone(v)),
            ValueRef::Stream(v) => KiviDBValue::Stream(Arc::clone(v)),
            ValueRef::TimeSeries(v) => KiviDBValue::TimeSeries(Arc::clone(v)),
            ValueRef::HashEx(v) => KiviDBValue::HashEx(Arc::clone(v)),
            ValueRef::Array(v) => KiviDBValue::Array(Arc::clone(v)),
        }
    }

    /// [`KiviDBValue::deep_clone`] of the value.
    pub fn deep_clone(self) -> KiviDBValue {
        self.to_value().deep_clone()
    }

    /// [`KiviDBValue::is_empty_collection`].
    pub fn is_empty_collection(self) -> bool {
        match self {
            ValueRef::List(list) => list.read().is_empty(),
            ValueRef::Set(set) => set.read().is_empty(),
            ValueRef::SortedSet(zset) => zset.read().is_empty(),
            ValueRef::Hash(hash) => hash.read().is_empty(),
            ValueRef::HashEx(hash) => hash.read().is_empty(),
            ValueRef::VectorSet(vset) => vset.read().entries.is_empty(),
            ValueRef::String(_)
            | ValueRef::Json(_)
            | ValueRef::Stream(_)
            | ValueRef::TimeSeries(_)
            | ValueRef::Array(_) => false,
        }
    }

    /// [`KiviDBValue::type_name`].
    pub fn type_name(self) -> &'static str {
        match self {
            ValueRef::String(_) => "string",
            ValueRef::List(_) => "list",
            ValueRef::Hash(_) => "hash",
            ValueRef::Json(_) => "ReJSON-RL",
            ValueRef::Set(_) => "set",
            ValueRef::VectorSet(_) => "vectorset",
            ValueRef::SortedSet(_) => "zset",
            ValueRef::Stream(_) => "stream",
            ValueRef::TimeSeries(_) => "TSDB-TYPE",
            ValueRef::HashEx(_) => "hash",
            ValueRef::Array(_) => "array",
        }
    }
}

/// What [`ShardMap::relocate_at`] did.
pub enum Relocated {
    /// Moved: what was left behind, to be let go of once the shard is
    /// unlocked (freeing it can give a slab back to the kernel).
    Moved(Leftover),
    /// In a slab being emptied, but held by something besides its key.
    Held,
    /// Nothing there, or nothing in a slab being emptied.
    Stays,
}

/// A block compaction moved a key's entry, or its string, out of.
pub enum Leftover {
    Entry(Left),
    Bytes(SharedBytes),
}

/// What a write of a key's value did ([`ShardMap::set_str`]).
pub enum Written {
    /// The key was not there.
    New,
    /// The value was written over the old one, in the same entry.
    InPlace,
    /// The key has a new entry; this is the old one, best dropped once the
    /// shard is unlocked.
    Replaced(Taken),
}

/// What [`ShardMap::remove_if`] did with a key.
pub enum Removal {
    /// It was taken out: its entry, best dropped once the shard is unlocked.
    Taken(Taken),
    /// It is there, and was left as it was.
    Kept,
    /// There is no such key.
    Absent,
}

impl Written {
    /// The old entry, if the key had one that is not its entry now.
    #[inline]
    pub fn replaced(self) -> Option<Taken> {
        match self {
            Written::Replaced(old) => Some(old),
            Written::New | Written::InPlace => None,
        }
    }
}

/// `entry` was found or made by a lookup of a key hashed `hash` in the table
/// `map` (its address): the key's use is written, if the command this
/// thread runs counts as one (see `access`). One thread-local load when it
/// does not.
#[inline(always)]
fn used(entry: Entry, hash: u64, map: u64) {
    let stamp = access::stamp();
    if stamp != 0 {
        access::used(entry, stamp, map ^ hash);
    }
}

/// One shard's keys and values: a table of [`Slot`]s, each the address of
/// an entry holding a key and its value (`entry`).
pub struct ShardMap {
    table: HashTable<Slot>,
    hash: ahash::RandomState,
    /// Every entry whose key has a time to live, each knowing where it is
    /// here (`Entry::pos`), in two parts: those that may come due soon, and
    /// those that cannot (see `ttl_list`).
    ttl: TtlList,
    /// The time a write lock holds the shard at, so that a command sees one
    /// time throughout ([`now_at`]). [`UNPINNED`] while no write lock holds
    /// the shard: every look reads the clock. [`PENDING`] once one does,
    /// until the first entry with a time to live it looks at reads the
    /// clock and keeps the time here. So a lock that meets no such entry
    /// never reads the clock: reading it on every write lock of a shard
    /// with a key with a time to live cost SET, INCR and DEL on such keys
    /// 3-4% more instructions.
    ///
    /// Atomic so that a look through `&self` can keep the time; it is only
    /// written under the write lock, so a reader, which only ever finds
    /// [`UNPINNED`] here, never writes it.
    now: AtomicU64,
    /// Keys past their time that writes under this lock put new values
    /// over, to be expired when it lets go (`expiry::written_over`).
    written_over: Vec<crate::store::Key>,
}

/// What [`ShardMap::lookup`] finds under a key.
pub enum Lookup<'a> {
    /// The key's value: the key is live.
    Live(ValueRef<'a>),
    /// A key past its time, still in the table.
    Past,
    /// No such key.
    Absent,
}

/// What a write does with the time to live the key has.
#[derive(Clone, Copy)]
enum Ttl {
    /// Keeps it (none, if the key is new).
    Keep,
    /// Gives the key this one, or takes it away.
    Set(Option<u64>),
}

/// No write lock holds the shard: see `ShardMap::now`.
const UNPINNED: u64 = 0;
/// A write lock holds the shard and has not read the clock yet.
const PENDING: u64 = u64::MAX;

/// Whether `entry` is past its time, by the shard's time `now` (see
/// `ShardMap::now`). Keys without a time to live never read the clock.
#[inline(always)]
fn expired(entry: Entry, now: &AtomicU64) -> bool {
    entry.has_ttl() && entry.expires().is_some_and(|at| past(at, now))
}

/// Whether the time to live that ends at `at` has, by the shard's time.
/// Never while the thread is loading a dataset or applying its master's
/// stream (`expiry::held`): what expired there is said by a `DEL`.
#[inline]
fn past(at: u64, now: &AtomicU64) -> bool {
    now_at(now) > at && !crate::expiry::held()
}

/// The shard's time: the one its write lock keeps, read from the clock the
/// first time it is asked for; the clock's own without a write lock.
#[inline]
fn now_at(now: &AtomicU64) -> u64 {
    match now.load(Ordering::Relaxed) {
        UNPINNED => crate::commands::helpers::now_ms(),
        PENDING => {
            let t = crate::commands::helpers::now_ms();
            now.store(t, Ordering::Relaxed);
            t
        }
        t => t,
    }
}

/// A key a write found past its time: expired lazily, as Redis counts it.
/// Kept for the write lock to expire once it lets go (`ShardWrite`): its
/// `expired` event, the clients watching or caching it, its documents, and
/// the `DEL` propagated before the write's own record.
#[cold]
#[inline(never)]
fn written_over_expired(over: &mut Vec<crate::store::Key>, key: &[u8]) {
    crate::stats::record_expired();
    over.push(crate::store::Key::new(key));
}

impl Default for ShardMap {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ShardMap {
    fn drop(&mut self) {
        self.clear();
    }
}

impl ShardMap {
    pub fn new() -> Self {
        ShardMap {
            table: HashTable::new(),
            hash: ahash::RandomState::new(),
            ttl: TtlList::new(),
            now: AtomicU64::new(UNPINNED),
            written_over: Vec::new(),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        ShardMap {
            table: HashTable::with_capacity(capacity),
            hash: ahash::RandomState::new(),
            ttl: TtlList::new(),
            now: AtomicU64::new(UNPINNED),
            written_over: Vec::new(),
        }
    }

    #[inline(always)]
    fn hash_of(&self, key: &[u8]) -> u64 {
        self.hash.hash_one(key)
    }

    /// The slot of `key`, hashed `hash`.
    #[inline(always)]
    fn find(&self, hash: u64, key: &[u8]) -> Option<Slot> {
        self.table
            .find(hash, |s| s.may_be(hash) && s.entry().has_key(key))
            .copied()
    }

    /// The slot of `key`, unless the key is past its time.
    #[inline(always)]
    fn find_live(&self, hash: u64, key: &[u8]) -> Option<Slot> {
        self.find(hash, key)
            .filter(|s| !expired(s.entry(), &self.now))
    }

    /// A write lock holds the shard from now: its time is the clock's when
    /// it is first needed, and then the same throughout (see `now`).
    #[inline(always)]
    pub(super) fn pin_now(&mut self) {
        *self.now.get_mut() = PENDING;
    }

    /// The write lock lets go: the clock's time again.
    #[inline(always)]
    pub(super) fn unpin_now(&mut self) {
        *self.now.get_mut() = UNPINNED;
    }

    /// Whether [`written_over_expired`] kept any keys.
    #[inline(always)]
    pub(super) fn wrote_over_expired(&self) -> bool {
        !self.written_over.is_empty()
    }

    /// The keys [`written_over_expired`] kept, taken.
    pub(super) fn take_written_over(&mut self) -> Vec<crate::store::Key> {
        std::mem::take(&mut self.written_over)
    }

    /// This table, as a number: which table a key is in, for `access`.
    #[inline(always)]
    fn id(&self) -> u64 {
        self as *const Self as usize as u64
    }

    /// `key`'s value: a use of the key (see the module).
    #[inline(always)]
    pub fn get(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<ValueRef<'_>> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        self.find_live(hash, key).map(|s| {
            let e = s.entry();
            used(e, hash, self.id());
            e.value()
        })
    }

    /// `key`'s value, without its use being written: for what only looks
    /// (`OBJECT`, `SORT`'s `BY` and `GET` patterns, ...). A key past its
    /// time is absent here too.
    #[inline]
    pub fn peek(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<ValueRef<'_>> {
        let key = key.as_ref();
        self.find_live(self.hash_of(key), key)
            .map(|s| s.entry().value())
    }

    /// `key`'s value, and when its time to live ends (milliseconds since
    /// the Unix epoch) if it has one: both from the one entry. A use of the
    /// key.
    #[inline(always)]
    pub fn get_expiring(
        &self,
        key: &(impl AsRef<[u8]> + ?Sized),
    ) -> Option<(ValueRef<'_>, Option<u64>)> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        self.find_live(hash, key).map(|s| {
            let e = s.entry();
            used(e, hash, self.id());
            (e.value(), e.expires())
        })
    }

    /// [`ShardMap::get`], telling a key past its time from one not there:
    /// for a reader that expires the one it finds past its time, as `GET`
    /// does. The time is looked at once, here. A use of the key if it is
    /// live, and only then: the access word of a key past its time was
    /// brought up to date by a `GET` that went on to find it gone, by an
    /// `MGET`, and by a `GET` on a replica, which leaves it for its master.
    #[inline(always)]
    pub fn lookup(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Lookup<'_> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        match self.find(hash, key) {
            Some(s) => {
                let e = s.entry();
                if expired(e, &self.now) {
                    return Lookup::Past;
                }
                used(e, hash, self.id());
                Lookup::Live(e.value())
            }
            None => Lookup::Absent,
        }
    }

    /// `key`'s value and when its time to live ends, past its time or not,
    /// its use not written: what a key past its time still holds.
    pub fn peek_expiring(
        &self,
        key: &(impl AsRef<[u8]> + ?Sized),
    ) -> Option<(ValueRef<'_>, Option<u64>)> {
        let key = key.as_ref();
        self.find(self.hash_of(key), key)
            .map(|s| (s.entry().value(), s.entry().expires()))
    }

    /// When `key`'s time to live ends, in milliseconds since the Unix epoch:
    /// `None` if it has none, or there is no such key. Past or not: this is
    /// what lazy and active expiry go by.
    #[inline(always)]
    pub fn expires(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<u64> {
        let key = key.as_ref();
        self.find(self.hash_of(key), key)
            .and_then(|s| s.entry().expires())
    }

    /// Whether there is such a key: a use of it, if there is.
    #[inline(always)]
    pub fn contains_key(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        match self.find_live(hash, key) {
            Some(s) => {
                used(s.entry(), hash, self.id());
                true
            }
            None => false,
        }
    }

    /// `key`'s access word: when it was last used, or how often
    /// (`eviction::Access`). `None` if there is no such key.
    #[inline]
    pub fn access(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<u32> {
        let key = key.as_ref();
        self.find(self.hash_of(key), key)
            .map(|s| s.entry().access())
    }

    /// Make `key`'s access word over with `next`, written only if that
    /// changes it. A read lock is enough: the word is atomic, and no part
    /// of the key or its value (see `entry`'s note on it). Nothing happens
    /// if there is no such key, or it is past its time. The key is taken as
    /// the command gave it, in bytes: a key is found by its bytes, and one
    /// that is not UTF-8 is not there to find.
    #[inline]
    pub fn touch(&self, key: &[u8], next: impl FnOnce(u32) -> u32) {
        if let Some(s) = self.find_live(self.hash_of(key), key) {
            s.entry().touch(next);
        }
    }

    /// `key` is used, if it is there, not past its time, and this thread's
    /// command counts as a use (see the module): a lookup for nothing else.
    /// The key is taken in bytes, as `touch` takes it.
    #[inline]
    pub fn use_key(&self, key: &[u8]) {
        let hash = self.hash_of(key);
        if let Some(s) = self.find_live(hash, key) {
            used(s.entry(), hash, self.id());
        }
    }

    /// A hold on `key`'s entry: its key and value, readable once the shard
    /// is let go of, and unchanged for as long as it is held.
    pub fn get_ref(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<EntryRef> {
        let key = key.as_ref();
        // SAFETY: the entry is in this table, which the caller has locked.
        self.find_live(self.hash_of(key), key)
            .map(|s| unsafe { EntryRef::new(s.entry()) })
    }

    /// Whether `key`'s entry is the one `held` holds: whether the key's
    /// value is the very one it had when `held` was taken.
    pub fn holds(&self, key: &(impl AsRef<[u8]> + ?Sized), held: &EntryRef) -> bool {
        let key = key.as_ref();
        self.find_live(self.hash_of(key), key)
            .is_some_and(|s| held.is(s.entry()))
    }

    /// Put an entry under `key`, and say what became of what the key had,
    /// past its time or not. One probe, whether the key is there or not.
    ///
    /// `make` makes the entry, given the time to live it is to have: the one
    /// `ttl` says, or the key's own if it keeps it. Made once the key is
    /// found, so that keeping a time to live costs nothing more. A key past
    /// its time is put as a new one, without it.
    ///
    /// With `in_place`, the string the entry is to hold: written over the
    /// key's string in its own entry, if that can be done (see the module),
    /// and nothing is made. Never over a key past its time.
    #[inline(always)]
    fn put(
        &mut self,
        key: &[u8],
        ttl: Ttl,
        in_place: Option<&[u8]>,
        make: impl FnOnce(&[u8], Option<u64>) -> Entry,
    ) -> Written {
        let hash = self.hash_of(key);
        let now = &self.now;
        let map = self.id();
        let hasher = &self.hash;
        let list = &mut self.ttl;
        let over = &mut self.written_over;
        match self.table.entry(
            hash,
            |s| s.may_be(hash) && s.entry().has_key(key),
            |s| hasher.hash_one(s.entry().key()),
        ) {
            hashbrown::hash_table::Entry::Occupied(mut at) => {
                let old = at.get().entry();
                let stale = expired(old, now);
                if stale {
                    written_over_expired(over, key);
                }
                if !stale && let Some(bytes) = in_place {
                    // The time to live is in the block before the key: a
                    // write that gives the key one, or takes it away, needs
                    // a new block.
                    let room_stays = match ttl {
                        Ttl::Keep => true,
                        Ttl::Set(expires) => expires.is_some() == old.has_ttl(),
                    };
                    if room_stays && old.fits_in_place(bytes.len()) {
                        // The time it had, for the list's sum of them.
                        let was = match ttl {
                            Ttl::Set(Some(_)) => old.expires(),
                            _ => None,
                        };
                        // SAFETY: the shard is locked for writing (`&mut
                        // self`), the table alone holds the entry, and the
                        // bytes keep it in its class; a time to live it
                        // has is there to change.
                        unsafe {
                            old.write_in_place(bytes);
                            if let Ttl::Set(Some(ms)) = ttl {
                                old.set_expires(ms);
                            }
                        }
                        // A time that now ends before the horizon.
                        if let Some(was) = was {
                            list.retimed(old, was);
                        }
                        used(old, hash, map);
                        return Written::InPlace;
                    }
                }
                let entry = make(
                    key,
                    match ttl {
                        Ttl::Keep if stale => None,
                        Ttl::Keep => old.expires(),
                        Ttl::Set(expires) => expires,
                    },
                );
                // The key's use goes on: a value written over keeps the
                // count of an LFU policy, as in Redis. Not one past its
                // time: that key is gone, and this is a new one, which
                // starts where a new key does.
                if !stale {
                    entry.set_access(old.access());
                }
                used(entry, hash, map);
                *at.get_mut() = Slot::new(entry, hash);
                list.replaced(old, entry);
                // SAFETY: the table's hold on the old entry goes to the caller.
                Written::Replaced(unsafe { Taken::new(old) })
            }
            hashbrown::hash_table::Entry::Vacant(place) => {
                let entry = make(
                    key,
                    match ttl {
                        Ttl::Keep => None,
                        Ttl::Set(expires) => expires,
                    },
                );
                used(entry, hash, map);
                place.insert(Slot::new(entry, hash));
                if entry.has_ttl() {
                    list.push(entry);
                }
                Written::New
            }
        }
    }

    /// Set `key` to `value`, and give back what it had: dropping that frees
    /// it, which is best done once the shard is unlocked. The key keeps its
    /// time to live.
    #[inline]
    pub fn insert(&mut self, key: impl AsRef<[u8]>, value: KiviDBValue) -> Option<Taken> {
        self.put(key.as_ref(), Ttl::Keep, None, |key, expires| {
            Entry::new(key, value, expires)
        })
        .replaced()
    }

    /// [`ShardMap::insert`], the key's time to live set to `expires`
    /// (milliseconds since the Unix epoch), or taken away.
    #[inline]
    pub fn insert_expiring(
        &mut self,
        key: impl AsRef<[u8]>,
        value: KiviDBValue,
        expires: Option<u64>,
    ) -> Option<Taken> {
        self.put(key.as_ref(), Ttl::Set(expires), None, |key, expires| {
            Entry::new(key, value, expires)
        })
        .replaced()
    }

    /// Set `key` to the string `bytes`: [`ShardMap::insert`] of a string,
    /// with its bytes copied once, into the entry.
    #[inline]
    pub fn insert_str(&mut self, key: impl AsRef<[u8]>, bytes: impl AsRef<[u8]>) -> Option<Taken> {
        let bytes = bytes.as_ref();
        self.put(key.as_ref(), Ttl::Keep, None, |key, expires| {
            Entry::string(key, bytes, expires)
        })
        .replaced()
    }

    /// Set `key` to the string `bytes`, keeping its time to live: in place,
    /// in the key's own entry, when that can be done (see the module); else
    /// as [`ShardMap::insert_str`].
    #[inline]
    pub fn set_str(&mut self, key: impl AsRef<[u8]>, bytes: impl AsRef<[u8]>) -> Written {
        let bytes = bytes.as_ref();
        self.put(key.as_ref(), Ttl::Keep, Some(bytes), |key, expires| {
            Entry::string(key, bytes, expires)
        })
    }

    /// [`ShardMap::set_str`], the key's time to live set to `expires`, or
    /// taken away.
    #[inline]
    pub fn set_str_expiring(
        &mut self,
        key: impl AsRef<[u8]>,
        bytes: impl AsRef<[u8]>,
        expires: Option<u64>,
    ) -> Written {
        let bytes = bytes.as_ref();
        self.put(
            key.as_ref(),
            Ttl::Set(expires),
            Some(bytes),
            |key, expires| Entry::string(key, bytes, expires),
        )
    }

    /// `extra` added to the end of `key`'s string, in its own entry, if that
    /// can be done (see the module). Returns the string's new length if it
    /// was; `None` leaves everything as it was, for the caller to write a
    /// new value.
    pub fn append_in_place(
        &mut self,
        key: &(impl AsRef<[u8]> + ?Sized),
        extra: &[u8],
    ) -> Option<usize> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        let map = self.id();
        let entry = self.find_live(hash, key)?.entry();
        let len = entry.inline_len()? + extra.len();
        if !entry.fits_in_place(len) {
            return None;
        }
        // SAFETY: locked for writing, held by the table alone, and in class.
        unsafe { entry.write_at_in_place(len - extra.len(), extra) };
        used(entry, hash, map);
        Some(len)
    }

    /// `patch` written over `key`'s string from `offset`, the string grown
    /// with zero bytes to reach it, in its own entry if that can be done
    /// (see the module). Returns the string's new length if it was; `None`
    /// leaves everything as it was.
    pub fn set_range_in_place(
        &mut self,
        key: &(impl AsRef<[u8]> + ?Sized),
        offset: usize,
        patch: &[u8],
    ) -> Option<usize> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        let map = self.id();
        let entry = self.find_live(hash, key)?.entry();
        let len = entry.inline_len()?.max(offset.checked_add(patch.len())?);
        if !entry.fits_in_place(len) {
            return None;
        }
        // SAFETY: as in `append_in_place`.
        unsafe { entry.write_at_in_place(offset, patch) };
        used(entry, hash, map);
        Some(len)
    }

    /// [`ShardMap::insert_str`], the key's time to live set to `expires`, or
    /// taken away.
    #[inline]
    pub fn insert_str_expiring(
        &mut self,
        key: impl AsRef<[u8]>,
        bytes: impl AsRef<[u8]>,
        expires: Option<u64>,
    ) -> Option<Taken> {
        let bytes = bytes.as_ref();
        self.put(key.as_ref(), Ttl::Set(expires), None, |key, expires| {
            Entry::string(key, bytes, expires)
        })
        .replaced()
    }

    /// Give `key` the time to live that ends at `expires` (milliseconds
    /// since the Unix epoch). Returns whether there is such a key: one past
    /// its time is left for expiry to take out.
    pub fn set_expires(&mut self, key: &(impl AsRef<[u8]> + ?Sized), expires: u64) -> bool {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        let map = self.id();
        let Some(slot) = self
            .table
            .find_mut(hash, |s| s.may_be(hash) && s.entry().has_key(key))
        else {
            return false;
        };
        let old = slot.entry();
        if expired(old, &self.now) {
            return false;
        }
        if old.has_ttl() && old.holders() == 1 {
            let was = old.expires().unwrap_or(0);
            // SAFETY: the shard is locked for writing, and nothing but the
            // table holds the entry.
            unsafe { old.set_expires(expires) };
            self.ttl.retimed(old, was);
            used(old, hash, map);
            return true;
        }
        let new = old.remade(Some(expires));
        used(new, hash, map);
        *slot = Slot::new(new, slot.hash_part());
        self.ttl.replaced(old, new);
        // SAFETY: the table's hold, given up: whoever else holds the old
        // entry still reads it as it was.
        unsafe { old.let_go() };
        true
    }

    /// Take `key`'s time to live away. Returns whether it had one.
    pub fn persist(&mut self, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        let map = self.id();
        let Some(slot) = self
            .table
            .find_mut(hash, |s| s.may_be(hash) && s.entry().has_key(key))
        else {
            return false;
        };
        let old = slot.entry();
        if expired(old, &self.now) {
            return false;
        }
        used(old, hash, map);
        if !old.has_ttl() {
            return false;
        }
        let new = old.remade(None);
        *slot = Slot::new(new, slot.hash_part());
        self.ttl.replaced(old, new);
        // SAFETY: as in `set_expires`.
        unsafe { old.let_go() };
        true
    }

    /// How many keys have a time to live.
    #[inline]
    pub fn ttl_len(&self) -> usize {
        self.ttl.len()
    }

    /// The sum of when the times to live of the [`ShardMap::ttl_len`] keys
    /// that have one end (milliseconds since the Unix epoch), kept as they
    /// change: `INFO keyspace`'s `avg_ttl` without a pass over them (#622).
    /// Keys past their time that expiry has not taken out yet are in it.
    #[inline]
    pub fn ttl_deadline_sum(&self) -> u128 {
        self.ttl.deadline_sum()
    }

    /// The entry at place `index` of the list of keys with a time to live:
    /// what a pick at random from them is (`index` modulo how many there
    /// are).
    pub fn ttl_entry(&self, index: usize) -> Option<EntryView<'_>> {
        Some(EntryView {
            entry: self.ttl.pick(index)?,
            _map: std::marker::PhantomData,
        })
    }

    /// Every key with a time to live, and when it ends.
    pub fn expiring(&self) -> impl Iterator<Item = (&[u8], u64)> {
        self.ttl.iter().map(|e| (e.key(), e.expires().unwrap_or(0)))
    }

    /// The keys whose time to live ended before `now` (milliseconds since
    /// the Unix epoch), at most `limit` of them: one pass over those that
    /// may have (`ttl_list`), stopping at the last one it takes. Returns
    /// them, and how many keys it looked at.
    pub fn due(&self, now: u64, limit: usize) -> (Vec<crate::store::Key>, usize) {
        self.ttl.due(now, limit)
    }

    /// Whether the keys with a time to live should be sorted again at `now`
    /// by when they may come due ([`ShardMap::sweep_ttl`]).
    #[inline]
    pub fn ttl_sweep_due(&self, now: u64) -> bool {
        self.ttl.sweep_due(now)
    }

    /// Sort the keys with a time to live by whether they may come due before
    /// the next horizon, looking at `steps` keys at most: what lets a pass
    /// for due keys look only at those (`ttl_list`). Returns whether it is
    /// done; if not, the next call goes on from where this one stopped.
    pub fn sweep_ttl(&mut self, now: u64, steps: usize) -> bool {
        self.ttl.sweep(now, steps)
    }

    /// Take `key` out if its time to live ended before `now`.
    pub fn remove_if_due(&mut self, key: &(impl AsRef<[u8]> + ?Sized), now: u64) -> Option<Taken> {
        if self.expires(key).is_some_and(|at| at < now) {
            self.remove(key)
        } else {
            None
        }
    }

    #[inline]
    pub fn remove(&mut self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<Taken> {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        match self
            .table
            .find_entry(hash, |s| s.may_be(hash) && s.entry().has_key(key))
        {
            Ok(at) => {
                let entry = at.remove().0.entry();
                if entry.has_ttl() {
                    self.ttl.take(entry);
                }
                // SAFETY: the table's hold goes to the caller.
                Some(unsafe { Taken::new(entry) })
            }
            Err(_) => None,
        }
    }

    /// Take `key` out if `take` says so of its value. If it says no, the
    /// key is left as it was, its time to live and its access word with it,
    /// and the lookup is a use of the key: what a `GETDEL` of a key of
    /// another type does. One probe either way. Past its time or not, as
    /// [`ShardMap::remove`].
    ///
    /// Taking the key out and putting it back, as `GETDEL` did, made it a
    /// new entry: an LFU count of 5, whatever it had been (#221).
    #[inline]
    pub fn remove_if(
        &mut self,
        key: &(impl AsRef<[u8]> + ?Sized),
        take: impl FnOnce(ValueRef<'_>) -> bool,
    ) -> Removal {
        let key = key.as_ref();
        let hash = self.hash_of(key);
        let map = self.id();
        match self
            .table
            .find_entry(hash, |s| s.may_be(hash) && s.entry().has_key(key))
        {
            Ok(at) => {
                let entry = at.get().entry();
                if !take(entry.value()) {
                    used(entry, hash, map);
                    return Removal::Kept;
                }
                let entry = at.remove().0.entry();
                if entry.has_ttl() {
                    self.ttl.take(entry);
                }
                // SAFETY: the table's hold goes to the caller.
                Removal::Taken(unsafe { Taken::new(entry) })
            }
            Err(_) => Removal::Absent,
        }
    }

    /// Put an entry [`ShardMap::remove`] took, from this table or another
    /// database's, under its key here: the entry itself, so that the key's
    /// value, time to live and access word are what they were, as Redis
    /// moves a key's object (`MOVE`). A key here past its time is written
    /// over, and expired as a write expires it; that entry is given back,
    /// best dropped once the shard is unlocked. A live key is left alone,
    /// and `taken` is given back instead.
    pub fn put_back(&mut self, taken: Taken) -> Result<Option<Taken>, Taken> {
        let hash = self.hash_of(taken.key());
        let now = &self.now;
        let hasher = &self.hash;
        let list = &mut self.ttl;
        let over = &mut self.written_over;
        let key = taken.key();
        match self.table.entry(
            hash,
            |s| s.may_be(hash) && s.entry().has_key(key),
            |s| hasher.hash_one(s.entry().key()),
        ) {
            hashbrown::hash_table::Entry::Occupied(mut at) => {
                let old = at.get().entry();
                if !expired(old, now) {
                    return Err(taken);
                }
                written_over_expired(over, key);
                let entry = taken.into_entry();
                *at.get_mut() = Slot::new(entry, hash);
                list.replaced(old, entry);
                // SAFETY: the table's hold on the old entry goes to the caller.
                Ok(Some(unsafe { Taken::new(old) }))
            }
            hashbrown::hash_table::Entry::Vacant(place) => {
                let entry = taken.into_entry();
                place.insert(Slot::new(entry, hash));
                if entry.has_ttl() {
                    list.push(entry);
                }
                Ok(None)
            }
        }
    }

    /// The value of `key`, made with `make` if there is none.
    pub fn get_or_insert_with(
        &mut self,
        key: &(impl AsRef<[u8]> + ?Sized),
        make: impl FnOnce() -> KiviDBValue,
    ) -> ValueRef<'_> {
        if !self.contains_key(key) {
            self.insert(key, make());
        }
        self.get(key).expect("a key just put in")
    }

    pub fn iter(&self) -> impl Iterator<Item = (&[u8], ValueRef<'_>)> {
        self.table.iter().map(|s| {
            let e = s.entry();
            (e.key(), e.value())
        })
    }

    pub fn keys(&self) -> impl Iterator<Item = &[u8]> {
        self.table.iter().map(|s| s.entry().key())
    }

    pub fn values(&self) -> impl Iterator<Item = ValueRef<'_>> {
        self.table.iter().map(|s| s.entry().value())
    }

    /// Every entry, each as a key, a value and the means to hold it.
    pub fn entries(&self) -> impl Iterator<Item = EntryView<'_>> {
        self.table.iter().map(|s| EntryView {
            entry: s.entry(),
            _map: std::marker::PhantomData,
        })
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.table.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.table.is_empty()
    }

    /// What `key` takes in this shard besides its value (`MEMORY USAGE`):
    /// its entry's block, its share of the table's buckets, and, with a
    /// time to live, its share of the list of keys that have one. None if
    /// the key is absent or past its time. A look, not a use.
    pub fn entry_footprint(&self, key: &(impl AsRef<[u8]> + ?Sized)) -> Option<usize> {
        let key = key.as_ref();
        let entry = self.find_live(self.hash_of(key), key)?.entry();
        // The table (and the list) is shared by the shard's keys, so a key
        // is given a share of it, at most a half-full table's share. A table
        // that has only grown is at least half full (it doubles when full),
        // so this is the whole share until keys leave. After a mass deletion
        // the room they left stays until the shard is shrunk (a sweep a
        // second, and never below a minimum size); spread over the keys
        // left, it made one key's estimate several times what it was. Under
        // the cap it stays put, and that room is no key's: in the deletions
        // tested, the keys' estimates then added up to typically 3-4% less
        // than `used_memory`, and from 1.1% to 5.7% less in all of them (the
        // most before the sweep had shrunk the shards): measured, not a
        // bound. An estimate policy, not an exact accounting of every live
        // allocation. (The key is in the table, so it has at least one key,
        // and a time to live puts it on the list.)
        let half_room = |len: usize, room: usize| len.max(room / 2).max(1);
        let table = self.table.allocation_size()
            / half_room(self.table.len(), self.table.num_buckets() / 8 * 7);
        let ttl = if entry.has_ttl() {
            self.ttl.capacity() * std::mem::size_of::<Entry>()
                / half_room(self.ttl.len(), self.ttl.capacity())
        } else {
            0
        };
        Some(entry.block_bytes() + table + ttl)
    }

    /// Keys the table has room for before it grows.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.table.capacity()
    }

    /// Take every key out, keeping the table's room.
    pub fn clear(&mut self) {
        self.ttl.clear();
        for slot in self.table.drain() {
            // SAFETY: the table's hold, given up.
            unsafe { slot.entry().let_go() };
        }
    }

    /// Shrink the table to room for `keys`, and the list of keys with a
    /// time to live, if it is sparse, to its keys and an eighth more.
    pub fn shrink_to(&mut self, keys: usize) {
        let hasher = &self.hash;
        self.table
            .shrink_to(keys, |s| hasher.hash_one(s.entry().key()));
        self.ttl.shrink_if(sparse);
    }

    /// Whether the table, or the list of keys with a time to live, has room
    /// for many more keys than it holds (see `store::shrink_if_sparse`).
    pub fn is_sparse(&self) -> bool {
        sparse(self.len(), self.capacity()) || self.ttl.is_sparse(sparse)
    }

    /// How many buckets the table has: the positions [`ShardMap::bucket`]
    /// takes. They stay where they are while keys come and go, until the
    /// table grows or shrinks.
    #[inline]
    pub fn buckets(&self) -> usize {
        self.table.num_buckets()
    }

    /// The key and value in bucket `index`, if it holds one.
    #[inline]
    pub fn bucket(&self, index: usize) -> Option<(&[u8], ValueRef<'_>)> {
        self.table.get_bucket(index).map(|s| {
            let e = s.entry();
            (e.key(), e.value())
        })
    }

    /// The entry in bucket `index`, if it holds one: with a bucket picked
    /// at random, and another until one is full, a key picked at random
    /// with every key as likely as any other (see `eviction`).
    #[inline]
    pub fn entry_at(&self, index: usize) -> Option<EntryView<'_>> {
        self.table.get_bucket(index).map(|s| EntryView {
            entry: s.entry(),
            _map: std::marker::PhantomData,
        })
    }

    /// Up to `count` entries from the buckets at and after `start` (taken
    /// modulo the bucket count), wrapping round once. Costs about `count`
    /// divided by how full the table is. Not a sample of keys each as
    /// likely as the next: a key after a run of empty buckets comes first
    /// far more often than one after a full one.
    pub fn sample_from(&self, start: usize, count: usize) -> impl Iterator<Item = EntryView<'_>> {
        let buckets = self.buckets();
        let start = if buckets == 0 { 0 } else { start % buckets };
        (0..buckets)
            .filter_map(move |step| {
                self.table
                    .get_bucket((start + step) % buckets)
                    .map(|s| EntryView {
                        entry: s.entry(),
                        _map: std::marker::PhantomData,
                    })
            })
            .take(if self.is_empty() { 0 } else { count })
    }

    /// One key picked at random, `pick()` giving the random numbers. A
    /// random bucket is tried until one is full, as Redis's
    /// `dictGetFairRandomKey` does; a table that is very sparse is walked
    /// from a random bucket.
    pub fn random_entry(&self, mut pick: impl FnMut() -> usize) -> Option<(&[u8], ValueRef<'_>)> {
        if self.is_empty() {
            return None;
        }
        let buckets = self.buckets();
        for _ in 0..64 {
            if let Some(found) = self.bucket(pick() % buckets) {
                return Some(found);
            }
        }
        self.sample_from(pick(), 1)
            .next()
            .map(|e| (e.key(), e.value()))
    }

    /// Whether the entry in bucket `index`, or its string's bytes, is in a
    /// slab compaction is emptying (`regions` is
    /// `value_slab::regions_snapshot`).
    pub fn evacuating_at(&self, index: usize, regions: &[usize]) -> bool {
        let Some(slot) = self.table.get_bucket(index) else {
            return false;
        };
        let entry = slot.entry();
        (crate::value_slab::class_of(entry.size()).is_some()
            && crate::value_slab::is_evacuating(entry.base(), regions))
            || matches!(entry.value(), ValueRef::String(s)
                if s.shared().is_some_and(|b| crate::value_slab::is_evacuating(b.block(), regions)))
    }

    /// The buckets from `from` to `to` (not included) whose entry, or its
    /// string's bytes, is in a slab compaction is emptying: [`evacuating_at`]
    /// of each, with the entries' first lines asked for a few buckets ahead.
    /// Each entry is somewhere else in memory, and the shard is locked for
    /// reading while this runs: one after the other, their misses held the
    /// lock about 50 us for 512 buckets.
    ///
    /// [`evacuating_at`]: ShardMap::evacuating_at
    pub fn evacuating_in(&self, from: usize, to: usize, regions: &[usize]) -> Vec<usize> {
        const AHEAD: usize = 8;
        let to = to.min(self.buckets());
        for index in from..(from + AHEAD).min(to) {
            if let Some(slot) = self.table.get_bucket(index) {
                slot.prefetch_header();
            }
        }
        let mut found = Vec::new();
        for index in from..to {
            if index + AHEAD < to
                && let Some(slot) = self.table.get_bucket(index + AHEAD)
            {
                slot.prefetch_header();
            }
            if self.evacuating_at(index, regions) {
                found.push(index);
            }
        }
        found
    }

    /// Ask for the first lines of the entry in bucket `index`, if there is
    /// one: compaction's next copy.
    #[inline]
    pub fn prefetch_bucket(&self, index: usize) {
        if let Some(slot) = self.table.get_bucket(index) {
            slot.prefetch();
        }
    }

    /// Move the entry in bucket `index`, or its string's bytes, out of a
    /// slab compaction is emptying, if the table's is its only hold.
    pub fn relocate_at(&mut self, index: usize, regions: &[usize]) -> Relocated {
        let Some(slot) = self.table.get_bucket_mut(index) else {
            return Relocated::Stays;
        };
        let entry = slot.entry();
        // SAFETY: the table is locked for writing (`&mut self`), and holds
        // the entry.
        match unsafe { entry.relocate(regions) } {
            Relocation::Stays => Relocated::Stays,
            Relocation::Held => Relocated::Held,
            Relocation::Moved(moving) => {
                let to = moving.to();
                // What can panic runs before the store changes: unwinding
                // then frees only the copy (`Moving`).
                fail_point(1);
                // The hash is not stored; the fragment is in the slot.
                let moved = slot.moved_to(to);
                // The position moved with the block.
                let listed = if to.has_ttl() {
                    fail_point(2);
                    let listed = self.ttl.at_mut(to.pos());
                    debug_assert!(*listed == entry);
                    Some(listed)
                } else {
                    None
                };
                *slot = moved;
                if let Some(listed) = listed {
                    *listed = to;
                }
                Relocated::Moved(Leftover::Entry(moving.done()))
            }
            Relocation::BytesMoved(old) => Relocated::Moved(Leftover::Bytes(old)),
        }
    }
}

// For tests: the point in `ShardMap::relocate_at` at which to panic.
#[cfg(test)]
thread_local! {
    static FAIL_AT: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
fn fail_point(at: u8) {
    if FAIL_AT.with(|f| f.get()) == at {
        panic!("injected at {at}");
    }
}

#[cfg(not(test))]
#[inline(always)]
fn fail_point(_: u8) {}

/// Tables and lists with room for fewer keys than this are left as they
/// are: what shrinking one would give back is not worth it.
const SHRINK_MIN_CAPACITY: usize = 256;

/// Whether room for `capacity` is sparse for `len` keys: no more than 4/9
/// of it used (see `store::shrink_if_sparse`).
#[inline]
pub(super) fn sparse(len: usize, capacity: usize) -> bool {
    capacity >= SHRINK_MIN_CAPACITY && len * 9 <= capacity * 4
}

/// One entry of a locked shard, as [`ShardMap::entries`] gives them.
pub struct EntryView<'a> {
    entry: Entry,
    _map: std::marker::PhantomData<&'a ShardMap>,
}

impl<'a> EntryView<'a> {
    pub fn key(&self) -> &'a [u8] {
        self.entry.key()
    }

    pub fn value(&self) -> ValueRef<'a> {
        self.entry.value()
    }

    /// When the key's time to live ends, if it has one.
    pub fn expires(&self) -> Option<u64> {
        self.entry.expires()
    }

    /// The key's access word (`eviction::Access`).
    pub fn access(&self) -> u32 {
        self.entry.access()
    }

    /// Which entry this is, as long as it lives: a number no other entry
    /// has meanwhile. A place found holding the same number later holds
    /// the same entry, or one made since in the same memory; either is
    /// that place's key now.
    #[inline]
    pub fn id(&self) -> usize {
        self.entry.base() as usize
    }

    /// A hold on the entry, to read it once the shard is let go of.
    pub fn hold(&self) -> EntryRef {
        // SAFETY: the shard is locked for as long as `'a`.
        unsafe { EntryRef::new(self.entry) }
    }
}

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

    fn s(v: &str) -> KiviDBValue {
        KiviDBValue::String(SharedBytes::from(v))
    }

    fn text(v: Option<ValueRef<'_>>) -> Option<Vec<u8>> {
        match v {
            Some(ValueRef::String(b)) => Some(b.to_vec()),
            _ => None,
        }
    }

    /// What a relocation test does with the key once it has moved.
    enum Then {
        /// Drops the map, as a shard's going does.
        DropMap,
        /// Takes the key out.
        Remove,
        /// Lets its time to live end.
        Expire,
    }

    /// A panic in `relocate_at` at `point` (1: where the slot's new address
    /// is made, 2: where the entry's place in the TTL list is found) leaves
    /// the store as it was, frees only the copy, and the entry moves later;
    /// the moved key is then let go of as `then` says.
    fn relocation_unwinds_at(point: u8, ttl: bool, then: Then) {
        use crate::value_slab;
        // These share their slab class, and a pass of compaction's tests
        // would empty their slab: one at a time.
        let _one = value_slab::EVACUATION_TESTS.lock();
        let key = |i: usize| format!("{i:0>3000}");
        let expires = ttl.then_some(u64::MAX / 2);
        // Made on a thread that ends, so that its slabs are nobody's.
        let mut map = std::thread::spawn(move || {
            let mut map = ShardMap::new();
            for i in 0..64 {
                map.insert_str_expiring(key(i), b"v", expires);
            }
            map
        })
        .join()
        .unwrap();
        // One key left: its slab holds nothing else, and empties when its
        // block is freed.
        for i in 1..64 {
            map.remove(&key(i));
        }
        let listed = |map: &ShardMap, e: Entry| {
            if ttl {
                map.ttl.len() == 1 && map.ttl.at(e.pos()) == e
            } else {
                map.ttl.is_empty()
            }
        };
        let index = (0..map.buckets())
            .find(|&i| map.table.get_bucket(i).is_some())
            .unwrap();
        let old = map.table.get_bucket(index).unwrap().entry();
        assert_eq!(old.has_ttl(), ttl);
        let generation = value_slab::generation_of(old.base());
        // Only this key's slab, not every test's.
        let evacuating = value_slab::evacuate_only(old.base()).expect("a slab nobody owns");
        // A freed old block shows below as its slab emptying, which needs
        // the slab to hold only this key, not another test's block too.
        assert_eq!(evacuating.live(), 1, "the key's slab is shared");
        let regions = value_slab::regions_snapshot();
        assert!(map.evacuating_at(index, &regions));

        FAIL_AT.with(|f| f.set(point));
        let relocated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            map.relocate_at(index, &regions)
        }));
        FAIL_AT.with(|f| f.set(0));
        assert!(relocated.is_err());
        if value_slab::generation_of(old.base()) != generation {
            // The store points to freed memory: never drop it.
            std::mem::forget(map);
            drop(evacuating);
            panic!("the old block was freed while the store still points to it");
        }
        assert!(map.table.get_bucket(index).unwrap().entry() == old);
        assert!(listed(&map, old));
        assert_eq!(text(map.get(&key(0))), Some(b"v".to_vec()));
        assert_eq!(map.expires(&key(0)), expires);

        // Nothing was left half done: the move goes through now.
        match map.relocate_at(index, &regions) {
            Relocated::Moved(left) => drop(left),
            _ => panic!("not moved"),
        }
        let new = map.table.get_bucket(index).unwrap().entry();
        assert!(new != old && listed(&map, new));
        // Its slab emptied when the old block was freed.
        assert_ne!(value_slab::generation_of(old.base()), generation);
        drop(evacuating);
        assert_eq!(text(map.get(&key(0))), Some(b"v".to_vec()));
        assert_eq!(map.expires(&key(0)), expires);
        // Nothing else moves: the same bucket has nothing left to move.
        assert!(matches!(map.relocate_at(index, &regions), Relocated::Stays));

        // The moved key goes the usual ways, its value dropped once, from
        // the copy.
        match then {
            Then::DropMap => drop(map),
            Then::Remove => {
                let taken = map.remove(&key(0)).expect("the key");
                drop(taken);
                assert!(map.is_empty() && map.ttl.is_empty());
                assert!(map.get(&key(0)).is_none());
                drop(map);
            }
            Then::Expire => {
                let (due, _) = map.due(u64::MAX, 8);
                assert_eq!(due.len(), 1);
                assert!(map.remove_if_due(&key(0), u64::MAX).is_some());
                assert!(map.is_empty() && map.ttl.is_empty());
                drop(map);
            }
        }
    }

    #[test]
    fn a_panic_making_the_moved_slot_frees_only_the_copy() {
        relocation_unwinds_at(1, true, Then::DropMap);
    }

    #[test]
    fn a_panic_finding_the_ttl_place_frees_only_the_copy() {
        relocation_unwinds_at(2, true, Then::Expire);
    }

    #[test]
    fn a_panic_moving_a_key_with_no_ttl_frees_only_the_copy() {
        relocation_unwinds_at(1, false, Then::Remove);
    }

    #[test]
    fn insert_get_remove() {
        let mut map = ShardMap::new();
        assert!(map.insert("a", s("1")).is_none());
        assert_eq!(text(map.get("a")), Some(b"1".to_vec()));
        assert!(map.contains_key("a"));
        let old = map.insert(crate::store::Key::from("a"), s("2"));
        assert!(
            matches!(old.map(Taken::into_value), Some(KiviDBValue::String(b)) if &b[..] == b"1")
        );
        assert_eq!(map.len(), 1);
        assert!(map.remove("a").is_some());
        assert!(map.remove("a").is_none());
        assert!(map.is_empty());
    }

    /// The table takes and gives back keys as bytes, any bytes: what the
    /// commands will hand it once they take keys that are not text (#437).
    #[test]
    fn keys_are_bytes_of_any_kind() {
        let mut map = ShardMap::new();
        let keys: Vec<Vec<u8>> = vec![
            b"\xff\x00k".to_vec(),
            b"\xfe".to_vec(),
            vec![0xe7; 24],
            (0u8..=255).collect(),
            b"plain".to_vec(),
        ];
        for (i, key) in keys.iter().enumerate() {
            assert!(map.insert_str(key.as_slice(), i.to_string()).is_none());
        }
        assert_eq!(map.len(), keys.len());
        for (i, key) in keys.iter().enumerate() {
            match map.get(key.as_slice()) {
                Some(ValueRef::String(v)) => assert_eq!(&v[..], i.to_string().as_bytes()),
                _ => panic!("{key:?} not found"),
            }
        }
        // `\xfe` and `\xff\x00k` are two keys, not one U+FFFD.
        assert!(map.get(&b"\xef\xbf\xbd"[..]).is_none());
        let mut seen: Vec<Vec<u8>> = map.keys().map(<[u8]>::to_vec).collect();
        seen.sort();
        let mut want = keys.clone();
        want.sort();
        assert_eq!(seen, want);
        assert!(map.set_expires(&b"\xfe"[..], u64::MAX - 1));
        assert_eq!(
            map.expiring().map(|(k, _)| k.to_vec()).collect::<Vec<_>>(),
            vec![b"\xfe".to_vec()]
        );
        let taken = map.remove(&keys[0][..]).expect("there");
        assert_eq!(taken.key(), &keys[0][..]);
        assert!(map.get(&keys[0][..]).is_none());
    }

    #[test]
    fn keys_survive_growth_and_shrinking() {
        let mut map = ShardMap::new();
        for i in 0..10_000 {
            map.insert(format!("key-{i}"), s(&i.to_string()));
        }
        for i in (0..10_000).filter(|i| i % 10 != 0) {
            map.remove(&format!("key-{i}"));
        }
        map.shrink_to(1_000);
        assert_eq!(map.len(), 1_000);
        assert_eq!(text(map.get("key-990")), Some(b"990".to_vec()));
        assert!(map.get("key-991").is_none());
    }

    #[test]
    fn buckets_reach_every_key_once() {
        let mut map = ShardMap::new();
        for i in 0..1_000 {
            map.insert(format!("k{i}"), s("v"));
        }
        let mut seen: Vec<Vec<u8>> = (0..map.buckets())
            .filter_map(|i| map.bucket(i).map(|(k, _)| k.to_vec()))
            .collect();
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 1_000);
        assert!(map.bucket(map.buckets()).is_none());
    }

    #[test]
    fn samples_and_random_keys() {
        let mut map = ShardMap::new();
        assert!(map.random_entry(|| 7).is_none());
        assert_eq!(map.sample_from(3, 5).count(), 0);
        for i in 0..100 {
            map.insert(format!("k{i}"), s("v"));
        }
        assert_eq!(map.sample_from(12345, 5).count(), 5);
        assert_eq!(map.sample_from(12345, 500).count(), 100);
        let mut n = 0usize;
        let (key, _) = map
            .random_entry(|| {
                n += 7919;
                n
            })
            .unwrap();
        assert!(map.contains_key(key));
        // A table nearly empty after a big delete still gives its key.
        for i in 1..100 {
            map.remove(&format!("k{i}"));
        }
        assert_eq!(map.random_entry(|| 0).map(|(k, _)| k), Some(&b"k0"[..]));
    }

    #[test]
    fn a_key_past_its_time_is_absent_until_taken_out() {
        let mut map = ShardMap::new();
        map.insert_expiring("k", s("100"), Some(1));
        assert!(map.get("k").is_none());
        assert!(map.get_expiring("k").is_none());
        assert!(!map.contains_key("k"));
        assert!(map.get_ref("k").is_none());
        assert!(!map.set_expires("k", u64::MAX));
        assert!(!map.persist("k"));
        // Expiry still sees it, by its own time.
        assert_eq!(map.expires("k"), Some(1));
        assert_eq!(map.ttl_len(), 1);

        // A write puts a new key: the old time to live goes with the old value.
        assert!(map.insert("k", s("1")).is_some());
        assert_eq!(text(map.get("k")), Some(b"1".to_vec()));
        assert_eq!(map.expires("k"), None);
        assert_eq!(map.ttl_len(), 0);
        assert!(map.remove_if_due("k", u64::MAX).is_none());

        // A live key keeps its time to live through a write.
        map.insert_expiring("live", s("a"), Some(u64::MAX - 1));
        map.insert("live", s("b"));
        assert_eq!(map.expires("live"), Some(u64::MAX - 1));
    }

    /// Nothing writes the access word of a key past its time: not the
    /// lookup `GET` and `MGET` make, not `use_key` (a command refused, a key
    /// named twice), not `touch` (a command whose use is written after it).
    #[test]
    fn a_key_past_its_time_is_not_used() {
        let mut map = ShardMap::new();
        map.insert_expiring("dead", s("1"), Some(1));
        map.insert_expiring("live", s("1"), Some(u64::MAX - 1));
        let dead = map.access("dead").unwrap();
        // A use writes this word (an LRU clock).
        let stamp = 12345;
        assert_ne!(dead, stamp);
        let _scope = super::access::AccessScope::open(stamp);

        assert!(matches!(map.lookup("dead"), Lookup::Past));
        map.use_key(b"dead");
        map.touch(b"dead", |_| stamp);
        assert_eq!(map.access("dead"), Some(dead));

        assert!(matches!(
            map.lookup("live"),
            Lookup::Live(ValueRef::String(_))
        ));
        assert_eq!(map.access("live"), Some(stamp));
        map.touch(b"live", |_| 777);
        assert_eq!(map.access("live"), Some(777));
        map.use_key(b"live");
        assert_eq!(map.access("live"), Some(stamp));
        assert!(matches!(map.lookup("none"), Lookup::Absent));
    }

    #[test]
    fn a_key_past_its_time_is_not_written_in_place() {
        let mut map = ShardMap::new();
        // SET k v KEEPTTL, INCR, SETRANGE's fallback: a new key, no time to live.
        map.insert_str_expiring("set", "5", Some(1));
        assert!(matches!(map.set_str("set", "6"), Written::Replaced(_)));
        assert_eq!(text(map.get("set")), Some(b"6".to_vec()));
        assert_eq!(map.expires("set"), None);
        // APPEND and SETRANGE leave it to the caller's write of a new value.
        map.insert_str_expiring("app", "5", Some(1));
        assert_eq!(map.append_in_place("app", b"6"), None);
        map.insert_str_expiring("rng", "5", Some(1));
        assert_eq!(map.set_range_in_place("rng", 0, b"6"), None);
        assert_eq!(
            map.take_written_over(),
            vec![crate::store::Key::from("set")]
        );
        // A live key is still written in place.
        map.insert_str_expiring("live", "5", Some(u64::MAX - 1));
        assert!(matches!(map.set_str("live", "6"), Written::InPlace));
        assert_eq!(map.append_in_place("live", b"7"), Some(2));
        assert_eq!(map.expires("live"), Some(u64::MAX - 1));
    }

    #[test]
    fn a_write_lock_sees_one_time() {
        let shard = crate::store::ShardLock::default();
        let soon = crate::commands::helpers::now_ms() + 200;
        shard.write().insert_expiring("k", s("100"), Some(soon));
        let mut map = shard.write();
        // Live when the lock first looked at the time: the write that
        // follows keeps it, however long after.
        assert!(map.get("k").is_some());
        std::thread::sleep(std::time::Duration::from_millis(250));
        map.insert("k", s("101"));
        assert_eq!(map.expires("k"), Some(soon));
        drop(map);
        assert!(shard.read().get("k").is_none());
    }

    #[test]
    fn a_write_lock_reads_the_clock_only_for_a_key_with_a_time_to_live() {
        let shard = crate::store::ShardLock::default();
        shard.write().insert("plain", s("1"));
        shard
            .write()
            .insert_expiring("ttl", s("1"), Some(u64::MAX - 1));
        let mut map = shard.write();
        assert!(map.get("plain").is_some());
        map.insert("plain", s("2"));
        assert_eq!(map.now.load(Ordering::Relaxed), PENDING, "no clock read");
        assert!(map.get("ttl").is_some());
        let t = map.now.load(Ordering::Relaxed);
        assert!(t != PENDING && t != UNPINNED, "read once, and kept");
        drop(map);
        assert_eq!(shard.read().now.load(Ordering::Relaxed), UNPINNED);
    }

    #[test]
    fn get_or_insert_with_makes_once() {
        let mut map = ShardMap::new();
        let mut made = 0;
        for _ in 0..3 {
            map.get_or_insert_with("a", || {
                made += 1;
                s("x")
            });
        }
        assert_eq!(made, 1);
        assert_eq!(map.len(), 1);
    }

    /// With every key's time ending well after the horizon, a pass for due
    /// keys looks at none of them once the shard has been swept (#618):
    /// before, every pass looked at every one.
    #[test]
    fn a_pass_looks_at_no_key_that_cannot_be_due() {
        let mut map = ShardMap::new();
        let now = crate::commands::helpers::now_ms();
        for i in 0..1000 {
            map.insert_expiring(format!("k{i}"), s("v"), Some(now + 3_600_000));
        }
        // Not swept yet: everything is looked at.
        assert_eq!(map.due(now, usize::MAX), (vec![], 1000));
        assert!(map.ttl_sweep_due(now));
        while !map.sweep_ttl(now, 64) {}
        assert!(!map.ttl_sweep_due(now));
        assert_eq!(map.due(now, usize::MAX), (vec![], 0));
        // A key given a short time goes where a pass sees it, whichever way
        // it is given.
        map.insert_expiring("new", s("v"), Some(now + 5));
        map.set_expires("k1", now + 5);
        map.set_str_expiring("k2", "w", Some(now + 5));
        map.insert_expiring("k3", s("w"), Some(now + 5));
        map.ttl.check();
        let (mut due, looked) = map.due(now + 10, usize::MAX);
        due.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
        let due: Vec<&[u8]> = due.iter().map(|k| k.as_bytes()).collect();
        assert_eq!(due, [&b"k1"[..], b"k2", b"k3", b"new"]);
        assert_eq!(looked, 4);
        // Past the horizon, with no sweep since, a pass looks at them all.
        let later = now + super::super::ttl_list::HORIZON_MS + 1;
        assert_eq!(map.due(later, usize::MAX).1, 1001);
        assert!(map.ttl_sweep_due(later));
    }

    /// Whatever writes do between the steps of a sweep, a pass finds every
    /// key past its time and no other, and every entry knows its place.
    #[test]
    fn a_pass_finds_exactly_the_due_keys_whatever_writes_do_meanwhile() {
        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
        let mut rand = move |n: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed % n
        };
        // Far past the clock, so that no write takes a key for expired.
        let mut now = crate::commands::helpers::now_ms() + 1_000_000_000;
        let mut map = ShardMap::new();
        // What the table says, not the list under test: every key with a
        // time to live and when it ends.
        let timed = |map: &ShardMap| -> Vec<(Vec<u8>, u64)> {
            let mut timed: Vec<(Vec<u8>, u64)> = map
                .entries()
                .filter_map(|e| e.expires().map(|at| (e.key().to_vec(), at)))
                .collect();
            timed.sort();
            timed
        };
        for step in 0..80_000 {
            let key = format!("k{}", rand(300));
            let at = now + rand(60_000);
            match rand(16) {
                0 => {
                    map.set_str_expiring(&key, "v", Some(at));
                }
                1 => {
                    map.insert_expiring(&key, s("v"), Some(at));
                }
                2 => {
                    map.set_str(&key, "w");
                }
                3 => {
                    map.insert(&key, s("w"));
                }
                4 => {
                    map.set_str_expiring(&key, "v", None);
                }
                5 => {
                    map.remove(&key);
                }
                6 => {
                    map.set_expires(&key, at);
                }
                7 => {
                    map.persist(&key);
                }
                8 | 9 => {
                    map.sweep_ttl(now, 1 + rand(40) as usize);
                }
                10 => now += rand(4_000),
                // The clock stepped back, now and then by much more than a
                // horizon.
                11 => {
                    let most = if rand(20) == 0 { 600_000 } else { 4_000 };
                    now -= rand(most);
                }
                12 => {
                    // A key taken out and put back, as `MOVE` does.
                    if let Some(taken) = map.remove(&key) {
                        assert!(map.put_back(taken).is_ok_and(|old| old.is_none()));
                    }
                }
                13 => {
                    // A new time given to an entry someone else holds: a
                    // new entry takes its place.
                    let held = map.get_ref(&key);
                    map.set_expires(&key, at);
                    drop(held);
                }
                14 => {
                    // The sweep under way finished, then one from now if
                    // that is due: none is due after it, wherever the clock
                    // has gone meanwhile.
                    while !map.sweep_ttl(now, 64) {}
                    if map.ttl_sweep_due(now) {
                        while !map.sweep_ttl(now, 64) {}
                    }
                    assert!(!map.ttl_sweep_due(now), "step {step}");
                }
                _ => {
                    // A key past its time, taken out as expiry takes one.
                    let past = timed(&map)
                        .into_iter()
                        .find(|&(_, at)| at < now)
                        .map(|(k, _)| k);
                    if let Some(k) = past {
                        assert!(map.remove_if_due(&k, now).is_some());
                    }
                }
            }
            map.ttl.check();
            if step % 50 == 0 {
                let probe = now + rand(30_000);
                let table = timed(&map);
                let want: Vec<Vec<u8>> = table
                    .iter()
                    .filter(|&&(_, at)| at < probe)
                    .map(|(k, _)| k.clone())
                    .collect();
                let mut got: Vec<Vec<u8>> = map
                    .due(probe, usize::MAX)
                    .0
                    .iter()
                    .map(|k| k.as_bytes().to_vec())
                    .collect();
                got.sort();
                assert_eq!(got, want, "step {step}");
                // The list holds every key with a time to live, and nothing
                // else.
                let mut listed: Vec<(Vec<u8>, u64)> =
                    map.expiring().map(|(k, at)| (k.to_vec(), at)).collect();
                listed.sort();
                assert_eq!(listed, table, "step {step}");
                // And the sum of their times, kept as they changed, is the
                // table's (#622).
                let sum: u128 = table.iter().map(|&(_, at)| u128::from(at)).sum();
                assert_eq!(map.ttl_deadline_sum(), sum, "step {step}");
                assert_eq!(map.ttl_len(), table.len(), "step {step}");
            }
            if step % 20_000 == 19_999 {
                // Everything taken out at once, as `FLUSHDB` does.
                map.clear();
                assert_eq!((map.ttl_len(), map.ttl_deadline_sum()), (0, 0));
            }
        }
        // The near part is no bigger than what can come due before the
        // horizon, once a sweep is done: the one under way, then one from now.
        while !map.sweep_ttl(now, 7) {}
        while !map.sweep_ttl(now, 7) {}
        map.ttl.check();
        let soon = timed(&map)
            .iter()
            .filter(|&&(_, at)| at < now + super::super::ttl_list::HORIZON_MS)
            .count();
        assert_eq!(map.ttl.near_len(), soon);
    }

    /// The sum of the times to live is kept through every way a key gets,
    /// changes and loses one: what `avg_ttl` is made of (#622).
    #[test]
    fn the_sum_of_the_times_follows_every_change() {
        let mut map = ShardMap::new();
        let now = crate::commands::helpers::now_ms() + 1_000_000_000;
        let sum = |map: &ShardMap| {
            map.ttl.check();
            map.ttl_deadline_sum()
        };
        assert_eq!(sum(&map), 0);
        map.insert_expiring("a", s("v"), Some(now + 100));
        map.set_str_expiring("b", "v", Some(now + 200));
        map.set_str("c", "v");
        assert_eq!(sum(&map), u128::from(2 * now + 300));
        // Written over in place with a new time, and with none given (the
        // time stays).
        map.set_str_expiring("b", "w", Some(now + 250));
        assert_eq!(sum(&map), u128::from(2 * now + 350));
        map.set_str("b", "y");
        assert_eq!(sum(&map), u128::from(2 * now + 350));
        // A new time, in place and on an entry held elsewhere.
        assert!(map.set_expires("a", now + 50_000));
        let held = map.get_ref("a");
        assert!(map.set_expires("a", now + 60_000));
        drop(held);
        assert_eq!(sum(&map), u128::from(2 * now + 60_250));
        // A key without one given one, and one losing it.
        assert!(map.set_expires("c", now + 1));
        assert!(map.persist("a"));
        assert_eq!(sum(&map), u128::from(2 * now + 251));
        // Written over with its time taken away.
        map.set_str_expiring("b", "x", None);
        assert_eq!(sum(&map), u128::from(now + 1));
        // Taken out and put back, as `MOVE` does.
        let taken = map.remove("c").unwrap();
        assert_eq!(sum(&map), 0);
        assert!(map.put_back(taken).is_ok());
        assert_eq!(sum(&map), u128::from(now + 1));
        // A sweep moves entries between the lists and leaves the sum.
        for i in 0..100u64 {
            map.insert_expiring(format!("k{i}"), s("v"), Some(now + i * 1_000));
        }
        let before = sum(&map);
        while !map.sweep_ttl(now, 7) {}
        assert_eq!(sum(&map), before);
        // Times up to the largest there is do not overflow it.
        map.insert_expiring("max", s("v"), Some(u64::MAX - 1));
        assert_eq!(sum(&map), before + u128::from(u64::MAX - 1));
        map.clear();
        assert_eq!(sum(&map), 0);
    }

    /// A clock stepped forward, a sweep, then the clock stepped back: the
    /// next sweep brings the horizon back, and the keys that cannot be due
    /// soon go back to the far list, rather than every pass looking at them
    /// until the clock has caught up.
    #[test]
    fn a_clock_stepped_back_does_not_leave_every_key_near() {
        use super::super::ttl_list::HORIZON_MS;
        let mut map = ShardMap::new();
        let now = crate::commands::helpers::now_ms() + 1_000_000_000;
        for i in 0..1000 {
            let at = if i % 10 == 0 {
                now + 5_000
            } else {
                now + 3_600_000
            };
            map.insert_expiring(format!("k{i}"), s("v"), Some(at));
        }
        // An hour ahead: every key ends before that horizon.
        let ahead = now + 3_600_000;
        while !map.sweep_ttl(ahead, 64) {}
        assert_eq!(map.ttl.near_len(), 1000);
        // Back: a sweep is due at once, though the horizon is an hour off.
        assert!(map.ttl_sweep_due(now));
        while !map.sweep_ttl(now, 64) {}
        map.ttl.check();
        assert!(!map.ttl_sweep_due(now));
        assert_eq!(map.ttl.near_len(), 100);
        // A pass looks at those alone, and finds exactly the due ones.
        let (due, looked) = map.due(now + 6_000, usize::MAX);
        assert_eq!((due.len(), looked), (100, 100));
        assert!(
            due.iter()
                .all(|k| map.expires(k.as_bytes()) == Some(now + 5_000))
        );
        assert_eq!(map.due(now + 4_000, usize::MAX), (vec![], 100));
        // A key given a time now goes where the new horizon says.
        map.insert_expiring("late", s("v"), Some(now + HORIZON_MS + 1));
        map.insert_expiring("soon", s("v"), Some(now + 1));
        map.ttl.check();
        assert_eq!(map.ttl.near_len(), 101);
        // Past the horizon, a pass looks at everything again.
        let past = now + HORIZON_MS + 2;
        assert_eq!(map.due(past, usize::MAX).0.len(), 102);
    }

    /// Compaction moving an entry while a sweep is under way: its place in
    /// the list goes with it, and the sweep carries on.
    #[test]
    fn an_entry_moved_by_compaction_mid_sweep_keeps_its_place() {
        use crate::value_slab;
        let _one = value_slab::EVACUATION_TESTS.lock();
        let long = |i: usize| format!("{i:0>3000}");
        let now = crate::commands::helpers::now_ms() + 1_000_000_000;
        let late = now + 3_600_000;
        // Made on a thread that ends, so that its slabs are nobody's.
        let mut map = std::thread::spawn(move || {
            let mut map = ShardMap::new();
            for i in 0..64 {
                map.insert_str_expiring(long(i), b"v", Some(late));
            }
            map
        })
        .join()
        .unwrap();
        // One long key left: its slab holds nothing else.
        for i in 1..64 {
            map.remove(&long(i));
        }
        for i in 0..200 {
            let at = if i % 2 == 0 { now + 5_000 } else { late };
            map.insert_expiring(format!("k{i}"), s("v"), Some(at));
        }
        // Part of the way: the long key, first in the far list, is in the
        // part looked at.
        assert!(!map.sweep_ttl(now, 50));
        map.ttl.check();
        let index = (0..map.buckets())
            .find(|&i| {
                map.table
                    .get_bucket(i)
                    .is_some_and(|s| s.entry().has_key(long(0).as_bytes()))
            })
            .unwrap();
        let old = map.table.get_bucket(index).unwrap().entry();
        let evacuating = value_slab::evacuate_only(old.base()).expect("a slab nobody owns");
        assert_eq!(evacuating.live(), 1, "the key's slab is shared");
        let regions = value_slab::regions_snapshot();
        match map.relocate_at(index, &regions) {
            Relocated::Moved(left) => drop(left),
            _ => panic!("not moved"),
        }
        drop(evacuating);
        let new = map.table.get_bucket(index).unwrap().entry();
        assert!(new != old && map.ttl.at(new.pos()) == new);
        map.ttl.check();
        while !map.sweep_ttl(now, 50) {}
        map.ttl.check();
        assert_eq!(map.ttl.len(), 201);
        assert_eq!(map.ttl.near_len(), 100);
        assert_eq!(map.due(now + 6_000, usize::MAX).0.len(), 100);
        assert_eq!(map.expires(&long(0)), Some(late));
        assert_eq!(map.due(late + 1, usize::MAX).0.len(), 201);
    }
}