kividb 1.2.1

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
use crate::store::Key;
use crate::{
    store::{self, Store},
    types::KiviDBValue,
    vector::IndexStore,
};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Redis `when` / `SETEX` style upper bound: absolute deadline in milliseconds as `long long`.
pub const REDIS_WHEN_MAX_MS: i128 = 9223372036854775807; // i64::MAX

pub const ERR_VALUE_NOT_INTEGER: &str = "ERR value is not an integer or out of range";
pub const ERR_INVALID_EXPIRE_EXPIRE_CMD: &str = "ERR invalid expire time in 'expire' command";
pub const ERR_INVALID_EXPIRE_SET_CMD: &str = "ERR invalid expire time in 'set' command";
pub const ERR_INVALID_EXPIRE_GETEX_CMD: &str = "ERR invalid expire time in 'getex' command";
pub const ERR_INVALID_EXPIRE_PEXPIRE_CMD: &str = "ERR invalid expire time in 'pexpire' command";
pub const ERR_INVALID_EXPIRE_PEXPIREAT_CMD: &str = "ERR invalid expire time in 'pexpireat' command";
pub const ERR_INVALID_EXPIRE_EXPIREAT_CMD: &str = "ERR invalid expire time in 'expireat' command";
pub const ERR_INVALID_EXPIRE_SETEX_CMD: &str = "ERR invalid expire time in 'setex' command";
pub const ERR_INVALID_EXPIRE_PSETEX_CMD: &str = "ERR invalid expire time in 'psetex' command";
pub const ERR_INVALID_EXPIRE_MSETEX_CMD: &str = "ERR invalid expire time in 'msetex' command";
pub const ERR_INVALID_EXPIRE_INCREX_CMD: &str = "ERR invalid expire time in 'increx' command";

/// How a command gives a key's time: a time to live in seconds (`EX`,
/// `SETEX`, `EXPIRE`) or milliseconds (`PX`, `PSETEX`, `PEXPIRE`), or a Unix
/// time in seconds (`EXAT`, `EXPIREAT`) or milliseconds (`PXAT`,
/// `PEXPIREAT`).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TimeArg {
    Secs,
    Millis,
    UnixSecs,
    UnixMillis,
}

impl TimeArg {
    /// `EX`, `PX`, `EXAT` or `PXAT`, in any case.
    pub fn of_option(token: &[u8]) -> Option<TimeArg> {
        if token.eq_ignore_ascii_case(b"EX") {
            Some(TimeArg::Secs)
        } else if token.eq_ignore_ascii_case(b"PX") {
            Some(TimeArg::Millis)
        } else if token.eq_ignore_ascii_case(b"EXAT") {
            Some(TimeArg::UnixSecs)
        } else if token.eq_ignore_ascii_case(b"PXAT") {
            Some(TimeArg::UnixMillis)
        } else {
            None
        }
    }
}

/// Whether the running command comes from a master's stream or the AOF
/// being replayed rather than from a client. A time given there is taken as
/// it comes, within what the clock holds: an earlier version wrote, and a
/// master a clock tick ahead may send, one this refuses from a client, and
/// refused there the key or its time to live was lost.
#[inline]
pub fn applying_stream(ctx: &crate::commands::ctx::Ctx) -> bool {
    ctx.apply_replication || crate::expiry::replaying()
}

/// The deadline, in Unix milliseconds, of the time `n` a command gave a key,
/// checked as Redis's `getExpireMillisecondsOrReply` and
/// `expireGenericCommand` check it: past `i64::MAX` milliseconds,
/// `err_invalid`. With `positive`, a time of zero or less is `err_invalid`
/// too, as for `SET`, `GETEX`, `SETEX`, `PSETEX` and `MSETEX`.
///
/// From a stream ([`applying_stream`]): a deadline past `i64::MAX` ms is
/// taken as `i64::MAX` ms, and a Unix time of 0 as the epoch. 1.2.0 took
/// both, and wrote `SET … PXAT` up to `u64::MAX`.
///
/// Worked out in 128 bits: nothing here can overflow.
pub fn deadline_ms_of(
    n: i128,
    arg: TimeArg,
    err_invalid: &'static str,
    lenient: bool,
    positive: bool,
) -> Result<i128, &'static str> {
    let relative = matches!(arg, TimeArg::Secs | TimeArg::Millis);
    if positive && n <= 0 && !(lenient && !relative && n == 0) {
        return Err(err_invalid);
    }
    let secs = matches!(arg, TimeArg::Secs | TimeArg::UnixSecs);
    if secs && !lenient && (n > (i64::MAX / 1000) as i128 || n < (i64::MIN / 1000) as i128) {
        return Err(err_invalid);
    }
    let ms = if secs { n * 1000 } else { n };
    let when = if relative {
        wall_now_ms_i128() + ms
    } else {
        ms
    };
    if when > REDIS_WHEN_MAX_MS {
        return if lenient {
            Ok(REDIS_WHEN_MAX_MS)
        } else {
            Err(err_invalid)
        };
    }
    if when < i64::MIN as i128 {
        return Err(err_invalid);
    }
    Ok(when)
}

/// A time argument as Redis reads it, a `long long`: anything else is
/// `ERR value is not an integer or out of range`, before any bound is
/// looked at. From a stream, up to `u64::MAX`, which 1.2.0 wrote.
#[inline]
pub fn time_arg_of(arg: &[u8], lenient: bool) -> Result<i128, &'static str> {
    match parse_bytes_as_i128(arg) {
        Some(n) if i64::try_from(n).is_ok() => Ok(n),
        Some(n) if lenient && (0..=u64::MAX as i128).contains(&n) => Ok(n),
        _ => Err(ERR_VALUE_NOT_INTEGER),
    }
}

/// `when` (Unix ms) as the `SystemTime` a key keeps. Past what the
/// platform's clock holds: `err_invalid`, or, from a stream, the furthest
/// it holds.
#[inline]
fn system_time_of(
    when: i128,
    err_invalid: &'static str,
    lenient: bool,
) -> Result<SystemTime, &'static str> {
    match system_time_from_unix_millis_i128(when) {
        Some(t) => Ok(t),
        None if lenient && when > 0 => Ok(from_unix_ms(when as u64)),
        None => Err(err_invalid),
    }
}

/// The deadline a key is given by `SET`, `GETEX` or `MSETEX` with `EX`,
/// `PX`, `EXAT` or `PXAT`, or by `SETEX` or `PSETEX`, as Redis's
/// `getExpireMillisecondsOrReply`: not an integer, then zero or less or past
/// the latest, refused. See [`deadline_ms_of`] for a stream.
#[inline]
pub fn key_deadline(
    raw: &[u8],
    arg: TimeArg,
    err_invalid: &'static str,
    lenient: bool,
) -> Result<SystemTime, &'static str> {
    let n = time_arg_of(raw, lenient)?;
    let when = deadline_ms_of(n, arg, err_invalid, lenient, true)?;
    system_time_of(when, err_invalid, lenient)
}

/// The time `EXPIRE`, `PEXPIRE`, `EXPIREAT` or `PEXPIREAT` gives, as
/// Redis's `expireGenericCommand` reads it: the number given, and the
/// deadline. Zero or less is taken; the caller deletes the key for it.
#[inline]
pub fn expire_deadline(
    raw: &[u8],
    arg: TimeArg,
    err_invalid: &'static str,
    lenient: bool,
) -> Result<(i128, SystemTime), &'static str> {
    let n = time_arg_of(raw, lenient)?;
    let when = deadline_ms_of(n, arg, err_invalid, lenient, false)?;
    Ok((n, system_time_of(when, err_invalid, lenient)?))
}

/// Optional `[NX | XX | GT | LT]` modifiers on `EXPIRE` / `PEXPIRE` / `EXPIREAT` / `PEXPIREAT`
/// (same semantics as Redis `expireGenericCommand`).
#[derive(Default, Clone, Copy)]
pub struct ExpireModifierFlags {
    pub nx: bool,
    pub xx: bool,
    pub gt: bool,
    pub lt: bool,
}

/// Parse trailing tokens from `cmd[start..]` as expire modifiers; errors match Redis strings.
pub fn parse_expire_modifier_flags(
    cmd: &[&[u8]],
    start: usize,
) -> Result<ExpireModifierFlags, String> {
    let mut f = ExpireModifierFlags::default();
    let mut i = start;
    while i < cmd.len() {
        let raw = match parse_utf8(cmd[i]) {
            Some(s) => s,
            None => return Err("ERR syntax error".to_string()),
        };
        let u = raw.to_ascii_uppercase();
        match u.as_str() {
            "NX" => f.nx = true,
            "XX" => f.xx = true,
            "GT" => f.gt = true,
            "LT" => f.lt = true,
            _ => {
                return Err(format!("ERR Unsupported option {}", raw));
            }
        }
        i += 1;
    }
    if (f.lt || f.gt || f.xx) && f.nx {
        return Err(
            "ERR NX and XX, GT or LT options at the same time are not compatible".to_string(),
        );
    }
    if f.gt && f.lt {
        return Err("ERR GT and LT options at the same time are not compatible".to_string());
    }
    Ok(f)
}

/// Redis `expireGenericCommand` conditional checks (absolute `new_abs` vs existing deadline).
pub fn expire_modifier_allows_set(
    flags: &ExpireModifierFlags,
    current: Option<SystemTime>,
    new_abs: SystemTime,
) -> bool {
    if flags.nx && current.is_some() {
        return false;
    }
    if flags.xx && current.is_none() {
        return false;
    }
    // GT: set only if the new absolute deadline is after the current one. A
    // key with no time to live has, for this, an infinite one: nothing is
    // after it.
    if flags.gt && current.is_none_or(|c| new_abs <= c) {
        return false;
    }
    if flags.lt
        && let Some(c) = current
        && new_abs >= c
    {
        return false;
    }
    true
}

/// Wall clock in ms since UNIX epoch, matching [`crate::script_clock::ttl_wall_ms_now`].
#[inline]
pub fn wall_now_ms_i128() -> i128 {
    crate::script_clock::ttl_wall_ms_now() as i128
}

/// Parse a command token as a base-10 `i128` (no leading-only whitespace edge cases in Redis).
#[inline]
pub fn parse_bytes_as_i128(arg: &[u8]) -> Option<i128> {
    let s = std::str::from_utf8(arg).ok()?;
    if s.is_empty() {
        return None;
    }
    s.parse().ok()
}

/// Absolute [`SystemTime`] from signed Unix milliseconds (past → before UNIX_EPOCH).
pub fn system_time_from_unix_millis_i128(ms: i128) -> Option<SystemTime> {
    if ms >= 0 {
        let u = u64::try_from(ms).ok()?;
        UNIX_EPOCH.checked_add(Duration::from_millis(u))
    } else {
        let neg = ms.checked_neg()?;
        let u = u64::try_from(neg).ok()?;
        UNIX_EPOCH.checked_sub(Duration::from_millis(u))
    }
}

/// `PTTL`: what is left of a time to live that ends at `at` (Unix ms), in
/// milliseconds, as Redis's `ttlGenericCommand` has it: the end less now,
/// both whole milliseconds, and 0, never less, for a key still there in the
/// millisecond it ends in.
#[inline]
pub fn ttl_remaining_ms(at: u64) -> i64 {
    i64::try_from(at.saturating_sub(now_ms())).unwrap_or(i64::MAX)
}

/// `TTL` and `EXPIRETIME`: milliseconds to the nearest second, a half up,
/// as Redis's `(ms + 500) / 1000`. `SET k v PX 1499` has a `TTL` of 1, and
/// `PX 1500` one of 2 (#557). In 128 bits, as Redis: the latest deadline,
/// `i64::MAX` ms, is 9223372036854776 s there, where saturating gave one
/// less.
#[inline]
pub fn ms_to_nearest_secs(ms: i64) -> i64 {
    ((ms as i128 + 500) / 1000) as i64
}

#[macro_export]
macro_rules! read_lock {
    ($shard:expr) => {
        $shard.read()
    };
}

#[macro_export]
macro_rules! write_lock {
    ($shard:expr) => {
        $shard.write()
    };
}

/// Most keys one batch deletes from a shard between releases of its locks.
const ACTIVE_EXPIRE_BATCH: usize = 1024;

/// Most keys a sweep of a shard's keys with a time to live looks at under
/// one lock of the shard (`ShardMap::sweep_ttl`): some tens of
/// microseconds.
const TTL_SWEEP_STEPS: usize = 2048;

/// How long one cycle may run: a quarter of the time between cycles, as in
/// Redis. Reads expire keys lazily whatever this does.
const ACTIVE_EXPIRE_BUDGET: Duration = Duration::from_millis(25);

/// A cycle whose time runs out while more than this percentage of the keys
/// it looked at were past their time is behind, and the next starts at once:
/// Redis's `ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE`.
const ACTIVE_EXPIRE_STALE_PERCENT: usize = 10;

/// Where the active expiry cycle has got to. A cycle that runs out of time
/// is taken up from here by the next.
#[derive(Default)]
pub struct ExpireCursor {
    db: usize,
    shard: usize,
    /// This cycle's share of the shards: those whose number is `part` modulo
    /// `parts` (one thread of several, each with its own). `parts` 0 is 1.
    part: usize,
    parts: usize,
}

impl ExpireCursor {
    /// The cursor of expiry thread `part` of `parts`.
    pub fn part(part: usize, parts: usize) -> Self {
        Self {
            part,
            parts,
            ..Self::default()
        }
    }

    fn parts(&self) -> usize {
        self.parts.max(1)
    }

    fn owns(&self, shard: usize) -> bool {
        shard % self.parts() == self.part
    }
}

/// Threads that expire keys, each going through its own share of the
/// shards: a quarter of the cores, at least one. One thread deleted at most
/// about 700,000 keys a second, and a pipelined load of `SET ... EX` on 8
/// vCPUs wrote about 650,000 a second: it fell behind, and memory grew until
/// the server was killed. Each rests 100 ms between cycles when it is not
/// behind, so the threads cost next to nothing when there is little to do.
fn expiry_threads() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get() / 4)
        .unwrap_or(1)
        .max(1)
}

/// Active expiration (Redis `activeExpireCycle`): remove the keys whose time
/// has passed, in every database, without waiting for them to be read.
///
/// It goes round every shard of every database once, and stops when it has,
/// or when its time is up. It returns whether it is behind: its time ran out
/// while more than a tenth of the keys it looked at were past their time
/// ([`ACTIVE_EXPIRE_STALE_PERCENT`]), so the caller should come back at once
/// rather than in 100 ms. Running out of time with few expired keys found is
/// not being behind: the next cycle takes up where this one stopped. In a
/// shard it finds the keys past their time [`ACTIVE_EXPIRE_BATCH`] at a time,
/// each pass over the shard's list of keys with a time to live stopping at
/// its batch's last key, and deletes each batch under one lock of the shard.
///
/// It used to take twenty keys at a time, each time searching the shard from
/// its start: every twenty passed over the same live keys again, so the more
/// keys a shard held the slower it went. Under a steady stream of `SET ...
/// EX`, keys came due faster than that removed them (about 80,000 a second at
/// 17 million keys), and memory grew without end (#87).
///
/// Coming back at once whenever its time ran out, as #87's fix first did,
/// kept it scanning without a pause under steady TTL traffic: a pass over
/// 1.8 million live keys takes more than its 25 ms, and each found only the
/// few that had come due since. That was a whole core of eight, taken from
/// the workers, with its shard locks in their way.
///
/// `target` is where the store's expired keys are told (`expiry::of`),
/// found once by the thread rather than on every cycle.
pub fn active_expire_cycle(
    store: &Store,
    index_store: &IndexStore,
    cursor: &mut ExpireCursor,
    target: Option<&crate::expiry::Target>,
) -> bool {
    // A replica expires nothing itself: its master's `DEL`s say what has
    // gone (see `expiry`). Its clients are told a key past its time is not
    // there all the same. Unless its master sends no `DEL`s (before 1.1.3).
    if target.is_some_and(crate::expiry::Target::on_replica) {
        return false;
    }
    // Whom the keys it expires are told to, if anyone.
    let told = target.filter(|target| target.observed());
    // The shards this cycle's part owns.
    let shards: usize = store
        .iter()
        .map(|db| (0..db.len()).filter(|&s| cursor.owns(s)).count())
        .sum();
    if shards == 0 {
        return false;
    }
    let started = std::time::Instant::now();
    let mut visited = 0usize;
    // Keys looked at, and of them those past their time.
    let (mut seen, mut due_total) = (0usize, 0usize);
    let behind = stale;
    while visited < shards {
        if cursor.db >= store.len() {
            cursor.db = 0;
        }
        let db_values = &store[cursor.db];
        if cursor.shard >= db_values.len() {
            cursor.db += 1;
            cursor.shard = 0;
            continue;
        }
        if !cursor.owns(cursor.shard) {
            cursor.shard += 1;
            continue;
        }
        let (db, shard) = (cursor.db, cursor.shard);
        if !db_values[shard].holds_no_ttl() {
            let now = now_ms();
            // About every 20 s, the keys that may come due before the next
            // horizon are set apart from those that cannot, so that a pass
            // looks only at those (#618): before, every cycle went over every
            // key with a time to live, due or not.
            if read_lock!(db_values[shard]).ttl_sweep_due(now) {
                while !write_lock!(db_values[shard]).sweep_ttl(now, TTL_SWEEP_STEPS) {}
            }
            // A batch at a time: a pass stops at the batch's last key, so it
            // copies no more keys than it deletes. Collecting every due key
            // of the shard first copied all of them, again each cycle, when
            // the budget ran out after the first batch: with 49 million keys
            // the thread spent its time copying and deleted 5,000 a second.
            loop {
                let (looked, due) = expire_pass(store, index_store, db, shard, now, told);
                seen += looked;
                due_total += due;
                if started.elapsed() >= ACTIVE_EXPIRE_BUDGET {
                    // This shard is gone through again next time: what is
                    // left of it, and what has come due since.
                    return behind(seen, due_total);
                }
                if due < ACTIVE_EXPIRE_BATCH {
                    break;
                }
            }
        }
        cursor.shard += 1;
        visited += 1;
        if visited.is_multiple_of(64) && started.elapsed() >= ACTIVE_EXPIRE_BUDGET {
            return visited < shards && behind(seen, due_total);
        }
    }
    false
}

/// One pass over shard `shard` of database `db`: up to
/// [`ACTIVE_EXPIRE_BATCH`] keys past their time at `now` (milliseconds since
/// the Unix epoch), the pass stopping at the last of them, deleted. Returns
/// how many keys it looked at and how many were due.
fn expire_pass(
    store: &Store,
    index_store: &IndexStore,
    db: usize,
    shard: usize,
    now: u64,
    told: Option<&crate::expiry::Target>,
) -> (usize, usize) {
    // Found with the shard locked for reading: what reads it goes on.
    let (due, looked) = read_lock!(store[db][shard]).due(now, ACTIVE_EXPIRE_BATCH);
    if told.is_some() {
        // Each `DEL` is ordered against the writes to its key, which wait
        // on it meanwhile: a few keys at a time, so that a batch does not
        // hold the order of a thousand keys at once.
        for part in due.chunks(TOLD_BATCH) {
            expire_batch(store, index_store, db, shard, part, now, told);
        }
    } else if !due.is_empty() {
        expire_batch(store, index_store, db, shard, &due, now, None);
    }
    (looked, due.len())
}

/// How many keys active expiry deletes under one lock of their shard while
/// their `DEL`s are propagated.
const TOLD_BATCH: usize = 64;

/// Delete every key of `store` whose time to live ended before `before`
/// (milliseconds since the Unix epoch), propagating nothing; returns how
/// many went. What a replica does once, at a partial resync with a master
/// that sends the deletion of every key it expires, for the keys no master
/// will send one of: those that went past their time under a master that
/// sent none (`ReplState::expiry_sweep_owed`, #231). A key whose hash tag a
/// script holds is left, as by the sweep, for that master's deletion.
pub fn expire_keys_due_before(store: &Store, index_store: &IndexStore, before: u64) -> usize {
    let mut deleted = 0;
    for db in 0..store.len() {
        for shard in 0..store[db].len() {
            if store[db][shard].holds_no_ttl() {
                continue;
            }
            loop {
                let (due, _) = read_lock!(store[db][shard]).due(before, ACTIVE_EXPIRE_BATCH);
                let full = due.len() == ACTIVE_EXPIRE_BATCH;
                let gone = expire_batch(store, index_store, db, shard, &due, before, None);
                deleted += gone;
                // A batch of which nothing went (all held) would be found
                // again: go on to the next shard.
                if !full || gone == 0 {
                    break;
                }
            }
        }
    }
    deleted
}

/// Whether more than [`ACTIVE_EXPIRE_STALE_PERCENT`] of the `seen` keys
/// were `due`: a cycle whose time ran out with this true is behind.
fn stale(seen: usize, due: usize) -> bool {
    due > 0 && due * 100 > seen * ACTIVE_EXPIRE_STALE_PERCENT
}

/// Delete the keys of `batch`, all in shard `shard` of database `db`, that
/// are still past their time, under one lock of the shard; returns how many
/// went. A key given a new
/// time meanwhile, or a new value without one, is left alone. With `told`,
/// the `DEL` of each key deleted is propagated, as a write's record is:
/// holding the write gate and the keys' order from before they go.
///
/// Inside the command gate, as a command: not in the middle of a
/// transaction or a script, which is one step, nor of a script that runs
/// beside others under the keys' hash tag (`tag_locks`). Taken there, the
/// key went from under the script, and its `DEL` went ahead of the script's
/// writes. And nothing while a dataset is being loaded (`expiry::Loading`).
///
/// The tags' locks are not waited for (`tag_locks::try_lock_keys`): a key
/// whose tag is held is left for the next cycle. Waiting for one, holding a
/// slot of the write gate, hung the server: a read under the tag that found
/// a key expired waited for the same slot, behind a checkpoint that waited
/// for the sweep.
fn expire_batch(
    store: &Store,
    index_store: &IndexStore,
    db: usize,
    shard: usize,
    batch: &[Key],
    now: u64,
    told: Option<&crate::expiry::Target>,
) -> usize {
    // In the order a command takes them: the command gate, the write gate,
    // the keys' tags' locks, the keys' order.
    let _command = crate::command_gate::enter();
    let _gate = told.map(|_| crate::write_gate::enter());
    let tags = if crate::tag_locks::enabled() {
        crate::tag_locks::try_lock_keys(batch.iter().map(|k| k.as_bytes()))
    } else {
        None
    };
    // The keys of a tag that is held are left for the next cycle.
    let batch: Vec<&Key> = match &tags {
        Some(tags) if tags.left_some() => batch
            .iter()
            .filter(|key| tags.may_take(key.as_bytes()))
            .collect(),
        _ => batch.iter().collect(),
    };
    if batch.is_empty() {
        return 0;
    }
    let ordered = told.map(|_| crate::expiry::order(db, batch.iter().map(|k| k.as_bytes())));
    let unobserved = unobserved_order(told.is_none(), db, batch.iter().map(|k| k.as_bytes()));
    // Writes were paused, for a handoff say, while this waited for the
    // gate: a `DEL` now would come after the cut the handoff took. The
    // keys go once the pause is over.
    if ordered.is_some() && crate::pause::expiry_deferred() {
        return 0;
    }
    // The keys taken are marked leaving until they have left their indexes
    // too (see `vector::mark_leaving`), where the database has one.
    let id = crate::vector::store_id(store);
    let marks = crate::vector::has_index_of(index_store, db);
    let mut gone: Vec<&Key> = Vec::with_capacity(batch.len());
    let mut freed: Vec<store::Taken> = Vec::with_capacity(batch.len());
    {
        let mut values = write_lock!(store[db][shard]);
        // Looked at with the shard locked: a load counted in after this
        // finds the keys gone before it writes to them.
        if !crate::expiry::loading() {
            for key in batch.iter().copied() {
                if let Some(value) = values.remove_if_due(key, now) {
                    // Announced before the shard is let go of (see
                    // `delete_key_if_expired`).
                    crate::keyspace_events::notify_expired(store, db, key);
                    if marks {
                        crate::vector::mark_leaving(id, db, key);
                    }
                    freed.push(value);
                    gone.push(key);
                }
            }
        }
    }
    if let Some(told) = told {
        told.propagate(db, gone.iter().map(|key| key.as_bytes()));
    }
    drop(ordered);
    drop(unobserved);
    // Freed outside the lock.
    drop(freed);
    let count = gone.len();
    for key in gone {
        crate::stats::record_expired();
        crate::stats::EXPIRED_KEYS_ACTIVE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        crate::watch::expired(store, db, key);
        crate::tracking::expired(store, key);
        crate::vector::maybe_unindex(index_store, db, key);
        if marks {
            crate::vector::unmark_leaving(id, db, key);
        }
    }
    count
}

/// How often each expiry thread looks for tables to shrink.
const SHRINK_PERIOD: Duration = Duration::from_secs(1);

/// Shrink the tables, and lists of keys with a time to live, of `cursor`'s
/// shards that keys have mostly left ([`store::ShardLock::shrink_if_sparse`],
/// #113).
fn shrink_sparse_tables(store: &Store, cursor: &ExpireCursor) {
    for db in store.iter() {
        for (s, shard) in db.iter().enumerate() {
            if cursor.owns(s) {
                shard.shrink_if_sparse();
            }
        }
    }
}

/// The order of `keys` (`write_order`), for an expiry that nothing observes
/// (`unobserved`) and so takes neither the write gate nor `expiry::order`:
/// a client's write to one of them holds it from before it reads the key
/// until after it has written it, and the expiry falls before or after the
/// whole of that write (#271). Nothing when this thread is alone, or holds
/// the order already.
pub(crate) fn unobserved_order<'a>(
    unobserved: bool,
    db: usize,
    keys: impl Iterator<Item = &'a [u8]>,
) -> Option<crate::write_order::OrderGuard> {
    (unobserved && !crate::command_gate::alone_on_this_thread())
        .then(|| crate::write_order::lock_keys(db, keys))
}

/// Lazy TTL: delete an expired key before a read and return true if it was removed.
#[inline]
pub fn lazy_expire_key(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    if is_expired(store, db, key) {
        delete_key_if_expired(store, db, key)
    } else {
        false
    }
}

/// What a read does with a key it has found expired: deletes it, as
/// [`delete_key_if_expired`] does, unless writes are paused
/// ([`crate::pause::expiry_deferred`]). Then the key is left where it is, to
/// be deleted, counted and announced once the pause is over, and the read
/// takes it as gone all the same. Returns whether it is to be taken as gone.
///
/// For reads only. A write that goes on to work on the key needs it really
/// gone, and writes are held while writes are paused, so they never meet a
/// key left this way.
#[inline]
pub fn expire_on_read(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    if crate::pause::expiry_deferred() {
        return true;
    }
    delete_key_if_expired(store, db, key)
}

/// [`lazy_expire_key`] for a read: see [`expire_on_read`].
#[inline]
pub fn lazy_expire_on_read(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    is_expired(store, db, key) && expire_on_read(store, db, key)
}

/// Background sampler so keys — and hash fields — expire without a read
/// (Redis `active_expire_cycle`). `pubsub` is where their expiry is announced.
pub fn spawn_active_expire_task(
    store: Store,
    index_store: IndexStore,
    pubsub: crate::pubsub::PubSubHub,
    latency: crate::latency::SharedLatencyTracker,
    repl_state: &std::sync::Arc<crate::replication::ReplState>,
    hub_tx: &crate::replication::HubTx,
) {
    crate::keyspace_events::register_hub(&store, &pubsub);
    // Where the keys it expires are told (see `expiry`).
    crate::expiry::register(&store, repl_state, hub_tx);
    crate::vector::register_index_store(&store, &index_store);
    // Whatever the store already holds that has field TTLs. At startup that
    // is nothing yet: the dataset is loaded after this, and rescanned then.
    crate::field_expiry::rescan(&store);
    let parts = expiry_threads();
    for part in 0..parts {
        let (store, index_store) = (store.clone(), index_store.clone());
        // The first thread also reports the latency event and sweeps the
        // hash fields' times.
        let latency = (part == 0).then(|| latency.clone());
        std::thread::spawn(move || {
            let mut cursor = ExpireCursor::part(part, parts);
            let target = crate::expiry::of(&store);
            // Every 100 ms, as Redis's `hz 10`; straight after a cycle that
            // is behind (its time ran out while more than a tenth of what it
            // looked at was expired), as Redis goes on while it keeps finding
            // them.
            let mut wait = Duration::from_millis(100);
            let mut shrunk_at = std::time::Instant::now();
            loop {
                std::thread::sleep(wait);
                // Nothing expires while writes are paused, as in Redis: the
                // keys and fields that come due meanwhile go once the pause
                // is over. Nor while a dataset is being loaded: the load
                // says what is gone, by the `DEL`s in it (`expiry::Loading`).
                // Nor once a shutdown has ended the write stream: the keys
                // that come due go after the restart.
                if !crate::expiry::active() {
                    wait = Duration::from_millis(100);
                    continue;
                }
                if crate::pause::expiry_deferred()
                    || crate::expiry::loading()
                    || target
                        .as_ref()
                        .is_some_and(crate::expiry::Target::stream_closed)
                {
                    continue;
                }
                let started = std::time::Instant::now();
                let behind =
                    active_expire_cycle(&store, &index_store, &mut cursor, target.as_ref());
                wait = Duration::from_millis(if behind { 1 } else { 100 });
                if shrunk_at.elapsed() >= SHRINK_PERIOD {
                    shrink_sparse_tables(&store, &cursor);
                    shrunk_at = std::time::Instant::now();
                }
                let Some(latency) = &latency else {
                    continue;
                };
                // Redis's `expire-cycle` latency event: a cycle that took at
                // least `latency-monitor-threshold` ms (0, the default, is
                // off).
                let threshold = crate::latency::threshold_ms();
                let took = started.elapsed().as_millis() as u64;
                if threshold > 0 && took >= threshold {
                    latency.record("expire-cycle", took.min(u32::MAX as u64) as u32);
                }
                crate::field_expiry::sweep(&store, &index_store);
            }
        });
    }
}

/// Glob-style match (Redis KEYS / PSUBSCRIBE). Fast path avoids `glob::Pattern` stack use on
/// huge `*?…` patterns; bracket / escape syntax defers to `glob`.
pub fn glob_match(pattern: &str, text: &str) -> bool {
    super::glob_redis::matches(pattern.as_bytes(), text.as_bytes())
}

/// [`glob_match`] of bytes: a channel's name need not be UTF-8.
pub fn glob_match_bytes(pattern: &[u8], text: &[u8]) -> bool {
    super::glob_redis::matches(pattern, text)
}

/// The latest deadline a command may give a hash field, in Unix
/// milliseconds: Redis's `HFE_MAX_ABS_TIME_MSEC`, 2^46 - 1 (the year 4199).
pub const MAX_FIELD_DEADLINE_MS: i64 = 0xFFFF_FFFF_FFFF >> 2;

/// The deadline of a hash field given `n`, seconds if `secs` and else
/// milliseconds, after `base_ms` (now, for a time to live; 0 for a Unix
/// time), as Redis's `parseExpireTime` checks it: `None` past
/// [`MAX_FIELD_DEADLINE_MS`]. `n` is not negative.
pub fn field_deadline_ms(n: i64, secs: bool, base_ms: i64) -> Option<i64> {
    let ms = if secs {
        if n > MAX_FIELD_DEADLINE_MS / 1000 {
            return None;
        }
        n * 1000
    } else {
        n
    };
    // Checked: `then_some(ms + base_ms)` added before it compared, and
    // overflowed for a time to live near `i64::MAX` ms.
    ms.checked_add(base_ms)
        .filter(|&at| at <= MAX_FIELD_DEADLINE_MS)
}

/// The deadline of a hash field given a time to live of `n` seconds if
/// `secs` and else milliseconds, from now: the Unix milliseconds it is kept
/// as and sent on as, the same number (#489). `None` past
/// [`MAX_FIELD_DEADLINE_MS`], or for a negative `n`. Checked throughout:
/// `HEXPIRE h 9223372036854775807 FIELDS 1 f` used to panic.
#[inline]
pub fn field_deadline_after(n: i64, secs: bool) -> Option<u64> {
    if n < 0 {
        return None;
    }
    field_deadline_ms(n, secs, now_ms() as i64).map(|at| at as u64)
}

/// Redis's reply to a hash field TTL past [`MAX_FIELD_DEADLINE_MS`].
pub fn invalid_field_expire_time(command: &str) -> Vec<u8> {
    crate::resp::write::resp_error(&format!(
        "ERR invalid expire time in '{}' command",
        command.to_ascii_lowercase()
    ))
}

/// `t` as a key's entry keeps a time to live: whole milliseconds since the
/// Unix epoch, a time before it as the epoch itself.
#[inline]
pub fn unix_ms(t: SystemTime) -> u64 {
    match t.duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_millis().min(u64::MAX as u128) as u64,
        Err(_) => 0,
    }
}

/// The time a key's entry keeps, as a `SystemTime`. One past what the
/// platform's clock can hold is taken as the end of year 9999, which every
/// platform's can (Windows' cannot hold `i64::MAX` milliseconds).
#[inline]
pub fn from_unix_ms(ms: u64) -> SystemTime {
    UNIX_EPOCH
        .checked_add(Duration::from_millis(ms))
        .unwrap_or_else(|| UNIX_EPOCH + Duration::from_secs(253_402_300_799))
}

/// Now, as times to live are kept: the script's clock inside a script.
/// The same number as `unix_ms(script_clock::wall_system_time_now())`,
/// without the round trip through a `SystemTime` and two 128-bit divisions.
#[inline]
pub fn now_ms() -> u64 {
    crate::script_clock::wall_ms_now()
}

/// Whether the time to live that ends at `at` has: past it, not at it. A
/// key lives through the millisecond it ends in, as in Redis, so never for
/// less than it was given. Never while this thread is loading a dataset or
/// applying its master's stream (`expiry::held`).
#[inline(always)]
pub fn is_past(at: u64) -> bool {
    now_ms() > at && !crate::expiry::held()
}

pub fn is_expired(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    let shard = store::get_shard(&store[db], key);
    // Usually: nothing in this shard expires, and no lock is needed to know.
    if shard.holds_no_ttl() {
        return false;
    }
    read_lock!(shard).expires(key).is_some_and(is_past)
}

/// When `key`'s time to live ends, if it has one.
pub fn get_expiry(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<SystemTime> {
    let shard = store::get_shard(&store[db], key);
    if shard.holds_no_ttl() {
        return None;
    }
    read_lock!(shard).expires(key).map(from_unix_ms)
}

// parse a command argument as utf8 - used everywhere
pub fn parse_utf8(bytes: &[u8]) -> Option<&str> {
    std::str::from_utf8(bytes).ok()
}

/// Write a value, the key's time to live taken away in the same step.
pub fn store_value(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
    value: KiviDBValue,
) {
    let shard = store::get_shard(&store[db], key);
    let replaced = write_lock!(shard).insert_expiring(key, value, None);
    // Freed with the shard unlocked.
    drop(replaced);
}

/// Write a value with the time to live that ends at `expires_at`, or none,
/// in one step.
pub fn store_value_expiring(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
    value: KiviDBValue,
    expires_at: Option<SystemTime>,
) {
    let shard = store::get_shard(&store[db], key);
    let replaced = write_lock!(shard).insert_expiring(key, value, expires_at.map(unix_ms));
    drop(replaced);
}

/// Give `key` the time to live that ends at `expires_at`. A key that is not
/// there is given none: a time to live is the key's. Returns whether it was
/// given it. A key found past its time is taken as gone, and is deleted
/// ([`expire_if_past`]).
pub fn set_expiry(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
    expires_at: SystemTime,
) -> bool {
    let shard = store::get_shard(&store[db], key);
    let set = write_lock!(shard).set_expires(key, unix_ms(expires_at));
    if !set {
        expire_if_past(store, db, key);
    }
    set
}

/// Take `key`'s time to live away. Returns whether it had one. A key found
/// past its time is taken as gone, and is deleted ([`expire_if_past`]).
pub fn clear_expiry(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    let shard = store::get_shard(&store[db], key);
    if shard.holds_no_ttl() {
        // Nothing to take away, and nothing to lock for that; but the key
        // is still used, if this command's use is being written.
        if store::AccessScope::active() {
            read_lock!(shard).contains_key(key);
        }
        return false;
    }
    let cleared = write_lock!(shard).persist(key);
    if !cleared {
        expire_if_past(store, db, key);
    }
    cleared
}

/// After a write to `key`'s time to live that found the key past its time
/// and left it alone (`PERSIST`, `EXPIRE`, `GETEX`): the key is deleted,
/// and its deletion sent, as a read that finds it so deletes it
/// ([`delete_key_if_expired`]). Left for the sweep, the key was still there
/// on a replica, and the write that had changed nothing on the master was
/// sent, and took the key's time away there (#628). Usually the write found
/// the key so before it ran, and it is gone already
/// (`handler::expire_named_keys_first`); this is for one whose time ran out
/// while it ran.
#[cold]
fn expire_if_past(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
    if is_expired(store, db, key) {
        delete_key_if_expired(store, db, key);
    }
}

pub fn delete_key(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    take_key(store, db, key).is_some()
}

/// [`delete_key`], saying about how much memory the key took: what
/// deleting it gives back, or leaves to a snapshot that still holds it
/// (`store::Taken::footprint`). For eviction to see that it gets anywhere.
pub fn delete_key_sized(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<usize> {
    let value_shard = store::get_shard(&store[db], key);
    let removed = write_lock!(value_shard).remove(key)?;
    // Freed (or left to what holds it) with the shard unlocked.
    Some(removed.footprint())
}

/// [`delete_key`], handing back the value, for `UNLINK` to free: after the
/// shard lock is released, and in the background if it is large.
pub fn take_key(
    store: &Store,
    db: usize,
    key: &(impl AsRef<[u8]> + ?Sized),
) -> Option<KiviDBValue> {
    let value_shard = store::get_shard(&store[db], key);
    let removed = write_lock!(value_shard).remove(key);
    // To be freed: what a snapshot still holds of the key is not to be
    // evicted for (#284).
    removed.map(store::Taken::into_value_to_free)
}

/// [`delete_key`] plus `expired_keys` stat — use only after an `is_expired`
/// check (lazy TTL). A key given a new time meanwhile is left alone.
///
/// On a master something reads the write stream of, the key's `DEL` is
/// propagated, ordered as a write to the key is. A replica deletes nothing:
/// it answers whether the key is past its time, and leaves it for its
/// master's `DEL` (see `expiry`). Unless that master sends none (before
/// 1.1.3): then the replica deletes the key, and tells no one.
#[inline]
pub fn delete_key_if_expired(store: &Store, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> bool {
    // Loading, or applying the master's stream: a key's time does not make
    // it gone. The `DEL` that follows does.
    if crate::expiry::held() {
        return false;
    }
    let shard = store::get_shard(&store[db], key);
    let target = crate::expiry::of(store);
    if target
        .as_ref()
        .is_some_and(crate::expiry::Target::on_replica)
    {
        return read_lock!(shard).expires(key).is_some_and(is_past);
    }
    let told = target.filter(crate::expiry::Target::observed);
    // Its indexes, if its database has one: the key is marked leaving from
    // when it is gone from the store until it is gone from them too (see
    // `vector::mark_leaving`).
    let id = crate::vector::store_id(store);
    let indexes = crate::vector::indexes_of(id, db);
    let ordered = told
        .as_ref()
        .map(|_| crate::expiry::order(db, std::iter::once(key.as_ref())));
    // Unobserved, the key's order all the same: a write that read the key
    // before it was due must not write its old value back after it is gone
    // (#271).
    let unobserved = unobserved_order(told.is_none(), db, std::iter::once(key.as_ref()));
    // `expired` is announced before the shard is let go of: a command that
    // then finds the key gone, and writes it anew, announces its own event
    // after it, as in Redis. Announced once the lock was let go of, the
    // `expired` of a key the sweep took could come after the `incrby` of an
    // INCR that came in between and made the key again.
    let removed = {
        let mut map = write_lock!(shard);
        let removed = map.remove_if_due(key, now_ms());
        if removed.is_some() {
            crate::keyspace_events::notify_expired(store, db, key);
            if indexes.is_some() {
                crate::vector::mark_leaving(id, db, key);
            }
        }
        removed
    };
    let gone = removed.is_some();
    if gone && let Some(told) = &told {
        told.propagate(db, [key.as_ref()]);
    }
    drop(ordered);
    drop(unobserved);
    drop(removed);
    if gone {
        crate::stats::record_expired();
        crate::watch::expired(store, db, key);
        crate::tracking::expired(store, key);
        // Out of its indexes too: it used to stay in the graph, and be
        // found by a KNN query, until something else deleted it.
        if let Some(indexes) = &indexes {
            crate::vector::maybe_unindex(indexes, db, key);
            crate::vector::unmark_leaving(id, db, key);
        }
    }
    gone
}

/// Format a score for RESP output.
/// Redis returns "1" not "1.0", but "1.5" not "1.50000000001".
/// A score that is a whole number of fewer than nine digits, as that
/// number: `3` for `3.0`. Most scores are (a rank, a count, a timestamp in
/// seconds is not, quite), and they are written as their digits and nothing
/// else. Finding that out the long way cost a formatted float and five
/// strings for every score in every reply.
///
/// Not zero: minus zero is a score too, and is written `-0`.
#[inline]
pub fn whole_score(score: f64) -> Option<i64> {
    if score != 0.0 && score.abs() < 1e8 && score.fract() == 0.0 {
        Some(score as i64)
    } else {
        None
    }
}

pub fn format_score(score: f64) -> String {
    if let Some(whole) = whole_score(score) {
        return whole.to_string();
    }
    if score == f64::INFINITY {
        return "inf".to_string();
    }
    if score == f64::NEG_INFINITY {
        return "-inf".to_string();
    }
    if score == 0.0 {
        return if score.is_sign_negative() { "-0" } else { "0" }.to_string();
    }
    // The shortest digits that read back as the same double, laid out as
    // Redis lays them out (its `fpconv_dtoa`): plain decimal for ordinary
    // magnitudes, `d.ddde+XX` beyond them — 1.7976931348623157e+308, not
    // three hundred digits.
    let scientific = format!("{:e}", score.abs());
    let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
    let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
    let exponent: i32 = exponent.parse().unwrap_or(0);
    let count = digits.len() as i32;
    // The number is `digits` Ɨ 10^k.
    let k = exponent - (count - 1);
    let body = if k >= 0 && exponent.abs() < count + 7 {
        format!("{digits}{}", "0".repeat(k as usize))
    } else if k < 0 && (k > -7 || exponent.abs() < 4) {
        let point = count + k;
        if point <= 0 {
            format!("0.{}{digits}", "0".repeat((-point) as usize))
        } else {
            format!(
                "{}.{}",
                &digits[..point as usize],
                &digits[point as usize..]
            )
        }
    } else {
        let sign = if exponent < 0 { '-' } else { '+' };
        if count > 1 {
            format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], exponent.abs())
        } else {
            format!("{digits}e{sign}{}", exponent.abs())
        }
    };
    if score < 0.0 {
        format!("-{body}")
    } else {
        body
    }
}

#[cfg(test)]
mod score_format_tests {
    use super::format_score;

    #[test]
    fn scores_are_written_as_redis_writes_them() {
        for (score, text) in [
            (0.0, "0"),
            (1.0, "1"),
            (-1.0, "-1"),
            (1.5, "1.5"),
            (-2.25, "-2.25"),
            (10.0, "10"),
            (100000.0, "100000"),
            (0.1, "0.1"),
            (0.001, "0.001"),
            (3.0e-5, "0.00003"),
            (1.0e-7, "1e-7"),
            (1.0e21, "1e+21"),
            (123456789012345680.0, "123456789012345680"),
            (1.7976931348623157e308, "1.7976931348623157e+308"),
            (-1.7976931348623157e308, "-1.7976931348623157e+308"),
            (f64::INFINITY, "inf"),
            (f64::NEG_INFINITY, "-inf"),
        ] {
            assert_eq!(format_score(score), text, "{score:e}");
        }
    }
}

/// The arguments the multi-key pops share (`LMPOP`, `ZMPOP` and their
/// blocking forms): `numkeys key [key ...] <first | second> [COUNT count]`,
/// with `numkeys` at `cmd[at]`. Returns how many keys there are, whether the
/// second of `words` was given, and the count.
pub fn parse_mpop(
    cmd: &[&[u8]],
    at: usize,
    words: [&str; 2],
) -> Result<(usize, bool, usize), Vec<u8>> {
    use crate::resp::write::resp_error;
    let num_keys =
        cmd.get(at)
            .and_then(|raw| std::str::from_utf8(raw).ok())
            .and_then(|s| s.parse::<i64>().ok())
            .filter(|n| *n > 0)
            .ok_or_else(|| resp_error("ERR numkeys should be greater than 0"))? as usize;
    let which = at + 1 + num_keys;
    let Some(word) = cmd.get(which) else {
        return Err(resp_error("ERR syntax error"));
    };
    let second = if word.eq_ignore_ascii_case(words[0].as_bytes()) {
        false
    } else if word.eq_ignore_ascii_case(words[1].as_bytes()) {
        true
    } else {
        return Err(resp_error("ERR syntax error"));
    };
    let count = match &cmd[which + 1..] {
        [] => 1,
        [option, n] if option.eq_ignore_ascii_case(b"COUNT") => std::str::from_utf8(n)
            .ok()
            .and_then(|s| s.parse::<i64>().ok())
            .filter(|n| *n > 0)
            .ok_or_else(|| resp_error("ERR count should be greater than 0"))?
            as usize,
        _ => return Err(resp_error("ERR syntax error")),
    };
    Ok((num_keys, second, count))
}

// ── Scanning ──────────────────────────────────────────────────────────────────
//
// SCAN, SSCAN, HSCAN and ZSCAN promise one thing: an element that is in the
// collection from the first call of a scan to the last is returned by one of
// them, whatever is added or removed in between.
//
// The cursor used to be a count of elements already returned, into an order
// — the hash map's own, or a sort done afresh on each call — that every
// insertion and removal shifts: delete a few elements behind the cursor and
// the scan steps over as many in front of it. (And the sort made each call
// of SSCAN and HSCAN cost a sort of the whole collection.)
//
// Here every element has a *position*: a hash of it, the same every time. A
// scan goes through the positions in order, and its cursor is the position
// to go on from. Adding and removing elements moves nothing: an element is
// where its hash puts it. One pass over the collection finds the next page.

/// Positions are 48 bits, so that a cursor has room above them for which
/// part of the keyspace it is in.
const SCAN_POSITION_BITS: u32 = 48;

/// Where `element` comes in the order a scan goes through its collection in.
pub fn scan_position(element: &[u8]) -> u64 {
    static HASHER: std::sync::LazyLock<ahash::RandomState> = std::sync::LazyLock::new(|| {
        ahash::RandomState::with_seeds(0x6b69_7669, 0x7363_616e, 0x636f_6e73, 0x6973_7465)
    });
    HASHER.hash_one(element) >> (64 - SCAN_POSITION_BITS)
}

/// The next page of a scan of a collection of `len` elements: the elements
/// from `cursor` on, as many as `count` asks for, and the cursor to go on
/// from — zero when that was the last page.
///
/// `count` is a hint, as in Redis. A page holds at least `len / pages`
/// elements whatever it says, so that a scan is over in `pages` calls: each
/// call is a pass over the collection, and `COUNT 10` on a million elements
/// would otherwise be a hundred thousand of them.
pub fn scan_page<T>(
    elements: impl Iterator<Item = (u64, T)>,
    cursor: u64,
    count: usize,
    len: usize,
    pages: usize,
) -> (Vec<T>, u64) {
    let want = count.max(len / pages.max(1)).max(1);
    let mut ahead: Vec<(u64, T)> = elements
        .filter(|(position, _)| *position >= cursor)
        .collect();
    if ahead.len() <= want {
        return (ahead.into_iter().map(|(_, element)| element).collect(), 0);
    }
    // The page ends before the position of the first element left out: so
    // that elements at one position are never split between two pages.
    ahead.select_nth_unstable_by_key(want, |(position, _)| *position);
    let mut boundary = ahead[want].0;
    if ahead[..want]
        .iter()
        .all(|(position, _)| *position == boundary)
    {
        // (Every one of them at a single position: take that position whole.)
        boundary += 1;
    }
    let more = ahead.iter().any(|(position, _)| *position >= boundary);
    (
        ahead
            .into_iter()
            .filter(|(position, _)| *position < boundary)
            .map(|(_, element)| element)
            .collect(),
        if more { boundary } else { 0 },
    )
}

/// `[MATCH pattern] [COUNT count]` and whatever else a scan command takes.
#[derive(Default)]
pub struct ScanOptions {
    pub pattern: Option<Vec<u8>>,
    pub count: usize,
    /// `SCAN … TYPE type`, in lower case.
    pub of_type: Option<String>,
    /// `HSCAN … NOVALUES`
    pub no_values: bool,
    /// `ZSCAN … NOSCORES`
    pub no_scores: bool,
}

/// The cursor and the options of a scan command, from `cmd[at..]`.
/// `extra` names the options this command takes besides `MATCH` and `COUNT`.
pub fn scan_arguments(
    cmd: &[&[u8]],
    at: usize,
    extra: &[&str],
) -> Result<(u64, ScanOptions), Vec<u8>> {
    use crate::resp::write::resp_error;
    let syntax = || resp_error("ERR syntax error");
    let cursor = cmd
        .get(at)
        .and_then(|raw| parse_utf8(raw))
        .and_then(|s| s.parse::<u64>().ok())
        .ok_or_else(|| resp_error("ERR invalid cursor"))?;
    let mut options = ScanOptions {
        count: 10,
        ..Default::default()
    };
    let mut i = at + 1;
    while i < cmd.len() {
        let word = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
        let value = cmd.get(i + 1);
        match (word.as_str(), value) {
            ("MATCH", Some(pattern)) => {
                options.pattern = Some(pattern.to_vec());
                i += 2;
            }
            ("COUNT", Some(count)) => {
                options.count = match parse_utf8(count).and_then(|s| s.parse::<i64>().ok()) {
                    Some(n) if n >= 1 => n as usize,
                    Some(_) => return Err(syntax()),
                    None => return Err(resp_error("ERR value is not an integer or out of range")),
                };
                i += 2;
            }
            ("TYPE", Some(of_type)) if extra.contains(&"TYPE") => {
                options.of_type = Some(String::from_utf8_lossy(of_type).to_ascii_lowercase());
                i += 2;
            }
            ("NOVALUES", _) if extra.contains(&"NOVALUES") => {
                options.no_values = true;
                i += 1;
            }
            ("NOSCORES", _) if extra.contains(&"NOSCORES") => {
                options.no_scores = true;
                i += 1;
            }
            _ => return Err(syntax()),
        }
    }
    Ok((cursor, options))
}

#[cfg(test)]
mod scan_tests {
    use super::{scan_page, scan_position};

    /// A whole scan of `set`, with `change` run on it after each page.
    fn scan(
        set: &mut std::collections::BTreeSet<u32>,
        count: usize,
        mut change: impl FnMut(&mut std::collections::BTreeSet<u32>, usize),
    ) -> Vec<u32> {
        let mut seen = Vec::new();
        let mut cursor = 0;
        let mut calls = 0;
        loop {
            let (page, next) = scan_page(
                set.iter().map(|n| (scan_position(&n.to_le_bytes()), *n)),
                cursor,
                count,
                set.len(),
                1024,
            );
            seen.extend(page);
            calls += 1;
            change(set, calls);
            if next == 0 {
                return seen;
            }
            assert!(next > cursor, "a scan goes forward");
            cursor = next;
        }
    }

    #[test]
    fn everything_is_returned_once_when_nothing_changes() {
        let mut set: std::collections::BTreeSet<u32> = (0..5000).collect();
        let mut seen = scan(&mut set, 10, |_, _| {});
        assert_eq!(seen.len(), 5000);
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(seen.len(), 5000);
    }

    #[test]
    fn what_stays_is_returned_whatever_else_comes_and_goes() {
        // 0..100 stay; the rest are removed part of the way through, and
        // others added: the collection shrinks and grows under the scan.
        let mut set: std::collections::BTreeSet<u32> = (0..1100).collect();
        let seen = scan(&mut set, 10, |set, calls| {
            if calls == 3 {
                set.retain(|n| *n < 100);
            }
            if calls == 5 {
                set.extend(5000..7000);
            }
            if calls == 9 {
                set.retain(|n| *n < 100 || *n % 2 == 0);
            }
        });
        for n in 0..100 {
            assert!(
                seen.contains(&n),
                "{n} was there throughout and was not returned"
            );
        }
    }

    #[test]
    fn a_page_is_not_smaller_than_a_scan_in_a_thousand_calls_needs() {
        let set: Vec<u32> = (0..100_000).collect();
        let (page, next) = scan_page(
            set.iter().map(|n| (scan_position(&n.to_le_bytes()), *n)),
            0,
            10,
            set.len(),
            1024,
        );
        assert!(page.len() >= 97 && next != 0);
        // A small collection comes in one page.
        let (page, next) = scan_page([(5u64, 'a'), (9, 'b')].into_iter(), 0, 10, 2, 1024);
        assert_eq!((page, next), (vec!['a', 'b'], 0));
    }
}

// The escape of names that are not text lives in `key_bytes` (`text_of`,
// `bytes_of`): keys use it too, wherever something keeps them as text.
pub use crate::key_bytes::{bytes_of as name_to_bytes, text_of as name_from_bytes};

#[cfg(test)]
mod whole_score_tests {
    use super::{format_score, whole_score};

    #[test]
    fn a_whole_score_is_written_as_its_digits_and_the_rest_as_before() {
        for (score, text) in [
            (3.0, "3"),
            (-12.0, "-12"),
            (1.0, "1"),
            (99_999_999.0, "99999999"),
            (-99_999_999.0, "-99999999"),
            // Past eight digits it is the long way round, as it always was.
            (100_000_000.0, "1e+8"),
            (10_000_000.0, "10000000"),
            (123_456_789.0, "123456789"),
            (0.0, "0"),
            (-0.0, "-0"),
            (1.5, "1.5"),
            (-0.25, "-0.25"),
            (f64::INFINITY, "inf"),
            (f64::NEG_INFINITY, "-inf"),
        ] {
            assert_eq!(format_score(score), text, "{score:?}");
        }
        assert_eq!(whole_score(42.0), Some(42));
        assert_eq!(whole_score(0.0), None);
        assert_eq!(whole_score(-0.0), None);
        assert_eq!(whole_score(0.5), None);
        assert_eq!(whole_score(1e8), None);
        assert_eq!(whole_score(f64::NAN), None);
        assert_eq!(whole_score(f64::INFINITY), None);
    }
}

#[cfg(test)]
mod active_expiry_tests {
    use super::*;
    use crate::shared_bytes::SharedBytes;

    fn put(store: &Store, key: &(impl AsRef<[u8]> + ?Sized), at: SystemTime) {
        store_value(
            store,
            0,
            key,
            KiviDBValue::String(SharedBytes::from(&b"v"[..])),
        );
        set_expiry(store, 0, key, at);
    }

    fn keys(store: &Store) -> usize {
        store[0].iter().map(|s| s.read().len()).sum()
    }

    fn times(store: &Store) -> usize {
        store[0].iter().map(|s| s.read().ttl_len()).sum()
    }

    /// A time to live set on, or taken from, a key past its time that the
    /// sweep has not taken out yet: the key is gone, so neither is done,
    /// and it is deleted then and there (#628). It was left in place, and
    /// `EXPIRE` answered 1 for a time it had not set.
    #[test]
    fn a_time_to_live_set_or_taken_away_finds_a_key_past_its_time_gone() {
        let store = store::new_store(1);
        let past = SystemTime::now() - Duration::from_secs(5);
        let later = SystemTime::now() + Duration::from_secs(3600);
        put(&store, "persisted", past);
        put(&store, "expired", past);
        put(&store, "live", later);
        assert_eq!(keys(&store), 3);
        assert!(!clear_expiry(&store, 0, "persisted"));
        assert!(!set_expiry(&store, 0, "expired", later));
        assert_eq!(keys(&store), 1, "both deleted");
        assert_eq!(times(&store), 1);
        // A live key is given its time, or has it taken away, as before.
        assert!(set_expiry(
            &store,
            0,
            "live",
            later + Duration::from_secs(1)
        ));
        assert!(clear_expiry(&store, 0, "live"));
        assert_eq!((keys(&store), times(&store)), (1, 0));
        // A key that is not there: nothing, and nothing deleted.
        assert!(!set_expiry(&store, 0, "missing", later));
        assert!(!clear_expiry(&store, 0, "missing"));
        assert_eq!(keys(&store), 1);
    }

    /// Times as entries keep them come back as they went in, and one past
    /// what the clock can hold does not panic (it did on Windows).
    #[test]
    fn unix_milliseconds_go_both_ways() {
        let t = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
        assert_eq!(from_unix_ms(unix_ms(t)), t);
        assert_eq!(unix_ms(UNIX_EPOCH - Duration::from_secs(1)), 0);
        assert!(from_unix_ms(u64::MAX) > t);
    }

    /// Every key past its time goes, in as few cycles as the budget allows;
    /// a key with time left, or none, stays.
    #[test]
    fn a_cycle_removes_every_expired_key_and_no_other() {
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        let future = SystemTime::now() + Duration::from_secs(3600);
        for i in 0..20_000 {
            put(&store, &format!("gone:{i}"), past);
            put(&store, &format!("kept:{i}"), future);
        }
        store_value(
            &store,
            0,
            "forever",
            KiviDBValue::String(SharedBytes::from(&b"v"[..])),
        );
        assert_eq!(times(&store), 40_000);
        let before = crate::stats::EXPIRED_KEYS_ACTIVE.load(std::sync::atomic::Ordering::Relaxed);

        let mut cursor = ExpireCursor::default();
        let mut cycles = 0;
        while keys(&store) > 20_001 {
            active_expire_cycle(&store, &index, &mut cursor, None);
            cycles += 1;
            assert!(cycles < 1000, "the cycle never caught up");
        }
        assert_eq!(keys(&store), 20_001);
        assert_eq!(times(&store), 20_000);
        assert!(
            store[0]
                .iter()
                .all(|s| s.read().keys().all(|k| !k.starts_with(b"gone:")))
        );
        let after = crate::stats::EXPIRED_KEYS_ACTIVE.load(std::sync::atomic::Ordering::Relaxed);
        assert!(after - before >= 20_000);
    }

    /// Keys that are not text expire as any other: the cycle stopped on the
    /// first one, with the key taken from the store and nothing said of it,
    /// when it made a `&str` of each (#437).
    #[test]
    fn keys_that_are_not_text_expire() {
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        let names: [&[u8]; 3] = [b"\xff\x00k", b"\xfe", b"text"];
        for key in names {
            put(&store, key, past);
        }
        let now = now_ms();
        for key in names {
            let shard = store::shard_index(store[0].len(), key);
            expire_batch(&store, &index, 0, shard, &[Key::new(key)], now, None);
        }
        assert_eq!(keys(&store), 0);
        assert_eq!(times(&store), 0);
    }

    /// A key whose time was put back after the cycle found it due is kept,
    /// and so is one given a new value without a time.
    #[test]
    fn a_key_given_a_new_time_is_kept() {
        // Not stopped by a load another test runs (`expiry::LOADING`).
        let _u = crate::expiry::Undisturbed::here();
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        put(&store, "k", past);
        put(&store, "j", past);
        let now = now_ms();
        let due = |key: &str| {
            let shard = store::shard_index(store[0].len(), key);
            assert!(
                read_lock!(store[0][shard])
                    .due(now, 10)
                    .0
                    .iter()
                    .any(|k| k == key)
            );
            shard
        };
        let shard = due("k");
        // A key past its time takes a new one only with a new value.
        put(&store, "k", SystemTime::now() + Duration::from_secs(60));
        expire_batch(&store, &index, 0, shard, &[Key::from("k")], now, None);
        let shard = due("j");
        store_value(
            &store,
            0,
            "j",
            KiviDBValue::String(SharedBytes::from(&b"w"[..])),
        );
        expire_batch(&store, &index, 0, shard, &[Key::from("j")], now, None);
        assert_eq!(keys(&store), 2);
        assert_eq!(times(&store), 1);
    }

    /// Behind only when more than a tenth of what was seen was due: the few
    /// keys that come due between passes under steady TTL traffic do not
    /// keep the thread from resting.
    #[test]
    fn behind_takes_more_than_a_tenth_due() {
        assert!(!stale(1_800_000, 9_000));
        assert!(!stale(1_000, 100));
        assert!(stale(1_000, 101));
        assert!(stale(40_000, 20_000));
        assert!(!stale(0, 0));
    }

    /// A cycle that goes round every shard within its time is not behind,
    /// whatever it removed, and keeps what is live.
    #[test]
    fn a_full_round_is_not_behind() {
        // Not stopped by a load another test runs (`expiry::LOADING`).
        let _u = crate::expiry::Undisturbed::here();
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        let future = SystemTime::now() + Duration::from_secs(3600);
        for i in 0..2_000 {
            put(&store, &format!("kept:{i}"), future);
        }
        put(&store, "gone", past);
        let mut cursor = ExpireCursor::default();
        assert!(!active_expire_cycle(&store, &index, &mut cursor, None));
        assert_eq!(keys(&store), 2_000);
    }

    /// A shard with three batches' worth due: a pass takes one batch and
    /// stops there, so it copies no more keys than it deletes (it used to copy
    /// every due key of the shard, then run out of time after one batch).
    #[test]
    fn a_pass_takes_one_batch_and_stops() {
        // Not stopped by a load another test runs (`expiry::LOADING`).
        let _u = crate::expiry::Undisturbed::here();
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        let shards = store[0].len();
        // Long keys, as UUIDs are: past a key's inline length.
        let mut n = 0;
        let mut i = 0;
        while n < 3 * ACTIVE_EXPIRE_BATCH {
            let key = format!("gone:{i:0>40}");
            i += 1;
            if store::shard_index(shards, &key) == 0 {
                put(&store, &key, past);
                n += 1;
            }
        }
        let (looked, due) = expire_pass(&store, &index, 0, 0, now_ms(), None);
        assert_eq!(due, ACTIVE_EXPIRE_BATCH);
        assert_eq!(
            looked, ACTIVE_EXPIRE_BATCH,
            "it went past the batch's last key"
        );
        assert_eq!(keys(&store), n - ACTIVE_EXPIRE_BATCH);

        let mut cursor = ExpireCursor::default();
        let mut cycles = 0;
        while keys(&store) > 0 {
            active_expire_cycle(&store, &index, &mut cursor, None);
            cycles += 1;
            assert!(cycles < 1000, "never emptied");
        }
    }

    /// Two parts between them go through every shard, each only its own.
    #[test]
    fn parts_share_the_shards() {
        // Not stopped by a load another test runs (`expiry::LOADING`).
        let _u = crate::expiry::Undisturbed::here();
        let store = store::new_store(1);
        let index: IndexStore = Default::default();
        let past = SystemTime::now() - Duration::from_secs(5);
        for i in 0..5_000 {
            put(&store, &format!("gone:{i}"), past);
        }
        let mut even = ExpireCursor::part(0, 2);
        while active_expire_cycle(&store, &index, &mut even, None) {}
        let shards = store[0].len();
        for (s, cell) in store[0].iter().enumerate() {
            let left = cell.read().ttl_len();
            if s % 2 == 0 {
                assert_eq!(left, 0, "shard {s} is part 0's");
            }
        }
        let odd_left: usize = (1..shards)
            .step_by(2)
            .map(|s| store[0][s].read().ttl_len())
            .sum();
        assert!(odd_left > 0, "part 0 went through part 1's shards");
        let mut odd = ExpireCursor::part(1, 2);
        while active_expire_cycle(&store, &index, &mut odd, None) {}
        assert_eq!(times(&store), 0);
        assert_eq!(keys(&store), 0);
    }
}