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
use std::sync::Arc;

use ahash::AHashMap;
use ahash::AHashSet;
use parking_lot::RwLock;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread::available_parallelism;

mod access;
mod entry;
mod shard_map;
mod ttl_list;
pub use access::AccessScope;
#[allow(unused_imports)] // Not every item is named outside the store yet.
pub use shard_map::{
    EntryRef, EntryView, Leftover, Lookup, Relocated, Removal, ShardMap, StrRef, Taken, ValueRef,
    Written,
};

/// Which shard `key` is in, of `shards` (a power of two).
///
/// 64-bit FNV-1a on every target (a 32-bit `usize` can't hold its
/// constants); the shard is taken from its low bits.
#[inline]
pub fn shard_index(shards: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> usize {
    shard_index_of_bytes(shards, key.as_ref())
}

/// [`shard_index`] of a key as the command gave it, not yet checked to be
/// UTF-8 (the same shard: the hash is of the bytes).
#[inline]
pub fn shard_index_of_bytes(shards: usize, key: &[u8]) -> usize {
    let mut hash: u64 = 0xcbf29ce484222325;
    for &byte in key {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    (hash as usize) & (shards - 1)
}

#[inline(always)]
pub fn get_shard<'a>(db: &'a Db, key: &(impl AsRef<[u8]> + ?Sized)) -> &'a Shard {
    &db[shard_index(db.len(), key)]
}

/// [`get_shard`] of a key as the command gave it, in bytes.
#[inline(always)]
pub fn get_shard_of_bytes<'a>(db: &'a Db, key: &[u8]) -> &'a Shard {
    &db[shard_index_of_bytes(db.len(), key)]
}

pub fn num_shards() -> usize {
    let cores = available_parallelism().map(|n| n.get()).unwrap_or(8);

    // 8 shards per core, rounded up to nearest power of 2
    // 8 cores  → 64 shards
    // 16 cores → 128 shards
    // 64 cores → 512 shards
    let target = cores * 8;
    target.next_power_of_two()
}

/// One shard of expiry times.
///
/// Its table behind a lock, and beside the lock how many of its keys have a
/// time to live.
///
/// Nearly every command asks whether its key has expired, and in most
/// datasets most shards hold no key with a time to live. A read that finds
/// its key finds the key's time in the same entry; a command that asks
/// before it locks the shard for what it does would take the lock twice. So
/// the shard keeps the count beside the lock, written by whoever held the
/// lock for writing as they let go, and read by anybody without taking
/// anything.
pub struct ShardLock {
    map: RwLock<ShardMap>,
    /// Keys in `map` with a time to live, as of the last writer to let go.
    ttls: AtomicUsize,
    /// Whether `map` holds any key, as of the last writer to let go.
    keys: AtomicBool,
    /// The store (its address) and database this shard is in, for what is
    /// done about keys past their time that a write puts a value over
    /// (`expiry::written_over`).
    place: std::sync::OnceLock<(usize, usize)>,
}

/// How long [`ShardLock::write_after_spinning`] looks for a busy shard to
/// come free before it sleeps on it.
const SPIN_FOR: std::time::Duration = std::time::Duration::from_micros(50);

/// The write lock of a [`ShardLock`]. It is the table, and on the way out
/// it leaves the count of keys with a time to live where a reader can see
/// it without the lock.
pub struct ShardWrite<'a> {
    map: std::mem::ManuallyDrop<parking_lot::RwLockWriteGuard<'a, ShardMap>>,
    lock: &'a ShardLock,
}

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

impl std::ops::DerefMut for ShardWrite<'_> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut ShardMap {
        &mut self.map
    }
}

impl Drop for ShardWrite<'_> {
    #[inline(always)]
    fn drop(&mut self) {
        // Before the lock is released. Its line is this thread's already:
        // the lock's word is beside it.
        self.map.unpin_now();
        let ttls = self.map.ttl_len();
        if self.lock.ttls.load(Ordering::Relaxed) != ttls {
            self.lock.ttls.store(ttls, Ordering::Release);
        }
        let keys = !self.map.is_empty();
        if self.lock.keys.load(Ordering::Relaxed) != keys {
            self.lock.keys.store(keys, Ordering::Release);
        }
        if self.map.wrote_over_expired() {
            return self.unlock_and_announce();
        }
        // SAFETY: dropped once, here; `map` is not used after.
        unsafe { std::mem::ManuallyDrop::drop(&mut self.map) };
    }
}

impl ShardWrite<'_> {
    /// Let go of the shard, then expire the keys past their time that
    /// writes under the lock put new values over: their events, watches,
    /// caches and indexes, and their `DEL` propagated, all before the
    /// write's own (`expiry::written_over`).
    #[cold]
    #[inline(never)]
    fn unlock_and_announce(&mut self) {
        let keys = self.map.take_written_over();
        // SAFETY: dropped once, here, from `drop`; `map` is not used after.
        unsafe { std::mem::ManuallyDrop::drop(&mut self.map) };
        self.lock.announce(&keys);
    }
}

/// Let go of every shard of `held`, then expire the keys past their time
/// that the writes under their locks put new values over
/// ([`ShardLock::announce`]): how a writer that holds several shards at
/// once lets go of them.
///
/// Dropped one by one, the first shard let go of announced while the others
/// were still held. Announcing takes the indexes' lock and reads the key's
/// shard, so a writer of several shards waited for the indexes with a shard
/// held, another announcer held the indexes and waited for that shard, and
/// with something waiting to write the indexes between them neither moved.
pub fn unlock_together<'a>(held: impl IntoIterator<Item = ShardWrite<'a>>) {
    let mut left = Vec::new();
    for mut shard in held {
        if shard.map.wrote_over_expired() {
            left.push((shard.lock, shard.map.take_written_over()));
        }
    }
    for (lock, keys) in left {
        lock.announce(&keys);
    }
}

impl ShardLock {
    pub fn new(map: ShardMap) -> Self {
        ShardLock {
            ttls: AtomicUsize::new(map.ttl_len()),
            keys: AtomicBool::new(!map.is_empty()),
            map: RwLock::new(map),
            place: std::sync::OnceLock::new(),
        }
    }

    #[inline(always)]
    pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, ShardMap> {
        self.map.read()
    }

    /// Expire `keys`, past their time and written over under this shard's
    /// lock, with no shard held: their events, watches, caches and indexes,
    /// and their `DEL` propagated, all before the write's own
    /// (`expiry::written_over`).
    #[cold]
    #[inline(never)]
    fn announce(&self, keys: &[Key]) {
        if let Some(&(store, db)) = self.place.get() {
            crate::expiry::written_over(store, db, keys);
        }
    }

    /// [`ShardLock::write`], if nobody holds the shard now; `None` at once
    /// if somebody does.
    #[inline(always)]
    pub fn try_write(&self) -> Option<ShardWrite<'_>> {
        let mut map = self.map.try_write()?;
        map.pin_now();
        Some(ShardWrite {
            map: std::mem::ManuallyDrop::new(map),
            lock: self,
        })
    }

    /// [`ShardLock::write`] for a writer that holds no other shard and
    /// found this one busy: it looks again, for up to [`SPIN_FOR`], before
    /// it sleeps until the shard is let go of.
    ///
    /// A shard is held for a few microseconds at a time. A thread that goes
    /// to sleep on it is woken some tens of microseconds after it is let go
    /// of, and the connections it serves wait with it: `MSET`s of keys in
    /// many shards spent more time asleep than holding them.
    #[cold]
    #[inline(never)]
    pub fn write_after_spinning(&self) -> ShardWrite<'_> {
        let started = std::time::Instant::now();
        loop {
            for _ in 0..32 {
                std::hint::spin_loop();
            }
            if !self.map.is_locked()
                && let Some(guard) = self.try_write()
            {
                return guard;
            }
            if started.elapsed() >= SPIN_FOR {
                return self.write();
            }
        }
    }

    #[inline(always)]
    pub fn write(&self) -> ShardWrite<'_> {
        let mut map = self.map.write();
        map.pin_now();
        ShardWrite {
            map: std::mem::ManuallyDrop::new(map),
            lock: self,
        }
    }

    /// No key in this shard has a time to live, as of the last write to
    /// it. Costs one load and takes no lock. A writer giving the first one
    /// a time at this moment is not seen, exactly as if this had been asked
    /// a moment earlier.
    #[inline(always)]
    pub fn holds_no_ttl(&self) -> bool {
        self.ttls.load(Ordering::Acquire) == 0
    }

    /// The shard holds no key, as of the last write to it. One load, no
    /// lock: what eviction asks of every shard of every database before it
    /// samples, on every write while memory is full.
    #[inline(always)]
    pub fn holds_no_keys(&self) -> bool {
        !self.keys.load(Ordering::Acquire)
    }

    /// How many of this shard's keys have a time to live, as of the last
    /// write to it, read without the lock.
    #[inline]
    pub fn ttl_count(&self) -> usize {
        self.ttls.load(Ordering::Acquire)
    }

    /// Give the table back the room of keys that have gone (#113).
    ///
    /// A hash table grows as keys come and does not shrink as they go:
    /// after a reshard moved half the keys away, or a big delete, each
    /// shard's table kept the size it had at its largest, and the memory of
    /// every empty slot. Called on each shard about once a second (see
    /// `commands::helpers::shrink_sparse_tables`), as Redis resizes its
    /// tables from its cron.
    ///
    /// A table holding no more than 4/9 of what it has room for is shrunk
    /// to its keys and an eighth more, and so is the list of the keys with
    /// a time to live. Tables grow by doubling, so the smallest one with
    /// that room has room for less than twice it: a table just shrunk, and
    /// one just grown, are never sparse enough to shrink, and a shard does
    /// not go back and forth unless its keys do, by more than an eighth.
    /// The rehash holds the shard's lock no longer than the growth it
    /// undoes did. Returns whether it shrank.
    pub fn shrink_if_sparse(&self) -> bool {
        if !self.read().is_sparse() {
            return false;
        }
        let mut m = self.write();
        if !m.is_sparse() {
            return false;
        }
        let keep = m.len() + m.len() / 8;
        m.shrink_to(keep);
        true
    }
}

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

/// A key kept outside the keyspace (the keyspace keeps its keys in their
/// entries): any bytes, inline when there are twenty-four or fewer, as
/// nearly every key is, and on the heap only past that. See
/// [`crate::key_bytes`].
pub type Key = crate::key_bytes::KeyBytes;

pub type Shard = Arc<ShardLock>;
pub type Db = Arc<Vec<Shard>>;
pub type Store = Arc<Vec<Db>>;

// Global label index for TimeSeries: "label=value" -> set of ts keys
pub type TsLabelIndex = AHashMap<String, AHashSet<String>>;
pub type SharedTsIndex = Arc<RwLock<TsLabelIndex>>;

pub fn new_ts_index() -> SharedTsIndex {
    Arc::new(RwLock::new(AHashMap::new()))
}

pub fn new_store(dbs: usize) -> Store {
    let num_shards = num_shards();
    // let total_shards = dbs * num_shards;
    // println!("Using {total_shards} shards");

    let dbs = (0..dbs)
        .map(|_| {
            let shards = (0..num_shards)
                .map(|_| Arc::new(ShardLock::default()))
                .collect::<Vec<_>>();
            Arc::new(shards)
        })
        .collect::<Vec<_>>();

    let store = Arc::new(dbs);
    let id = Arc::as_ptr(&store) as *const () as usize;
    for (db, shards) in store.iter().enumerate() {
        for shard in shards.iter() {
            let _ = shard.place.set((id, db));
        }
    }
    store
}

macro_rules! mem_swap_rwlock_maps {
    ($a:expr, $b:expr) => {
        std::mem::swap(&mut *$a.write(), &mut *$b.write());
    };
}

/// What a flush handed back, so the caller can decide whether it is worth
/// asking the allocator to return pages to the OS.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Flushed {
    /// Entries removed: keys.
    pub entries: usize,
    /// Keys removed.
    pub keys: usize,
    /// Bucket slots whose backing allocation was freed. Zero when every shard
    /// took the keep-capacity path.
    pub slots_released: usize,
}

impl std::ops::AddAssign for Flushed {
    fn add_assign(&mut self, rhs: Self) {
        self.entries += rhs.entries;
        self.keys += rhs.keys;
        self.slots_released += rhs.slots_released;
    }
}

/// Bucket-slot capacity at or above which a flush drops a shard's table
/// instead of just emptying it.
///
/// `HashMap::clear()` keeps the bucket array at its high-water capacity. For a
/// large keyspace that is the single biggest thing a flush fails to give back —
/// 1.7M keys leave ~100 MB of empty tables resident, which no `MEMORY PURGE`
/// can reclaim because the process still owns them.
///
/// Dropping unconditionally would be worse for the common case though: the test
/// suite issues `FLUSHALL` before every test and benchmarks flush between runs,
/// where the tables are a few dozen slots, freeing them returns nothing to the
/// OS (the allocation is far below the mmap threshold), and the next fill pays
/// to grow them back from zero. So small tables keep the old behaviour and only
/// tables big enough to matter are released.
const SHARD_RELEASE_MIN_CAPACITY: usize = 128;

/// Entry count at or above which a flush is worth a `malloc_trim`.
///
/// The key strings and values freed by a flush are small allocations that glibc
/// parks in its arena free lists, so they stay resident until something asks for
/// them back. Trimming a nearly-empty heap costs little but is pure overhead in
/// the flush-between-tests loop, hence the floor.
const TRIM_MIN_ENTRIES: usize = 4096;

impl Flushed {
    /// Whether this flush freed enough for a `malloc_trim` to pay for itself.
    pub fn should_trim(&self) -> bool {
        self.slots_released > 0 || self.entries >= TRIM_MIN_ENTRIES
    }
}

/// Empty one shard, releasing its table when the table is large enough to be
/// worth releasing. See [`SHARD_RELEASE_MIN_CAPACITY`].
fn clear_shard_map(map: &mut ShardMap) -> Flushed {
    let entries = map.len();
    let capacity = map.capacity();
    if capacity >= SHARD_RELEASE_MIN_CAPACITY {
        *map = ShardMap::default();
        Flushed {
            entries,
            slots_released: capacity,
            ..Flushed::default()
        }
    } else {
        map.clear();
        Flushed {
            entries,
            ..Flushed::default()
        }
    }
}

/// Empty every shard of one database. Used by `FLUSHDB`.
pub fn clear_db(db: &Db) -> Flushed {
    let mut total = Flushed::default();
    for shard in db.iter() {
        total += clear_shard_map(&mut shard.write());
    }
    total.keys = total.entries;
    total
}

/// The values of one database, taken out of it to be freed elsewhere: what
/// `FLUSHDB ASYNC` and `FLUSHALL ASYNC` hand to the lazyfree thread. A shard
/// keeps a small table, as [`clear_shard_map`] does.
pub fn take_db(db: &Db) -> (Vec<ShardMap>, Flushed) {
    let mut taken = Vec::with_capacity(db.len());
    let mut total = Flushed::default();
    for shard in db.iter() {
        let mut map = shard.write();
        let capacity = map.capacity();
        total.entries += map.len();
        taken.push(if capacity >= SHARD_RELEASE_MIN_CAPACITY {
            total.slots_released += capacity;
            std::mem::take(&mut *map)
        } else {
            std::mem::replace(&mut *map, ShardMap::with_capacity(capacity))
        });
    }
    total.keys = total.entries;
    (taken, total)
}

/// Empty every database. Used by `FLUSHALL` and `CLUSTER RESET HARD`.
pub fn clear_store(store: &Store) -> Flushed {
    let mut total = Flushed::default();
    for db in store.iter() {
        total += clear_db(db);
    }
    total
}

#[inline]
pub fn clear_ts_label_index(ts: &SharedTsIndex) {
    ts.write().clear();
}

/// Rebuild the time-series label index from the series actually stored.
///
/// The index is derived state: it is maintained by `TS.CREATE` / `TS.ALTER`
/// as they run and is not part of a snapshot. Nothing rebuilt it after a
/// snapshot load or a replica full sync, so `TS.MGET` / `TS.MRANGE` /
/// `TS.QUERYINDEX` — everything that selects series by label — matched nothing
/// on a restarted server or a freshly synced replica, while the series
/// themselves were all present.
pub fn rebuild_ts_label_index(store: &Store, ts: &SharedTsIndex) {
    let mut index = TsLabelIndex::new();
    for db in store.iter() {
        for shard in db.iter() {
            for (key, value) in shard.read().iter() {
                if let ValueRef::TimeSeries(series) = value {
                    for (label, label_value) in series.read().labels.iter() {
                        index
                            .entry(format!("{label}={label_value}"))
                            .or_default()
                            .insert(crate::key_bytes::text_of(key).into_owned());
                    }
                }
            }
        }
    }
    *ts.write() = index;
}

/// Swap every shard HashMap between `live` and `staging`; layouts must match (same databases / shards).
pub fn swap_kv_with_staging(live: &Store, staging: &Store) {
    assert_eq!(live.len(), staging.len(), "staging store db count mismatch");
    for (db_live, db_staging) in live.iter().zip(staging.iter()) {
        assert_eq!(
            db_live.len(),
            db_staging.len(),
            "staging shard count mismatch"
        );
        for (s_live, s_staging) in db_live.iter().zip(db_staging.iter()) {
            mem_swap_rwlock_maps!(s_live, s_staging);
        }
    }
}

#[cfg(test)]
mod flush_tests {
    use super::*;
    use crate::types::KiviDBValue;

    fn val() -> KiviDBValue {
        KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]))
    }

    fn fill(store: &Store, db_index: usize, count: usize) {
        for i in 0..count {
            let key = format!("flush-key-{i:012}");
            get_shard(&store[db_index], &key)
                .write()
                .insert(key.as_str(), val());
        }
    }

    fn total(db: &Db) -> (usize, usize) {
        db.iter().fold((0, 0), |(len, cap), s| {
            let m = s.read();
            (len + m.len(), cap + m.capacity())
        })
    }

    /// The bug this guards: `clear()` empties a shard but keeps its bucket array
    /// at high-water capacity, so flushing a large keyspace leaves the tables
    /// resident and no `MEMORY PURGE` can get them back.
    #[test]
    fn clear_db_releases_large_shard_tables() {
        let store = new_store(1);
        // Enough keys that every shard lands well above the release floor.
        fill(&store, 0, SHARD_RELEASE_MIN_CAPACITY * num_shards() * 4);

        let (len_before, cap_before) = total(&store[0]);
        assert!(len_before > 0);
        assert!(cap_before >= SHARD_RELEASE_MIN_CAPACITY);

        let flushed = clear_db(&store[0]);

        let (len_after, cap_after) = total(&store[0]);
        assert_eq!(len_after, 0, "flush must remove every key");
        assert_eq!(cap_after, 0, "flush must hand the bucket arrays back");
        assert_eq!(flushed.entries, len_before);
        assert_eq!(flushed.slots_released, cap_before);
        assert!(flushed.should_trim());
    }

    /// The flip side: the suite runs `FLUSHALL` before every test and benchmarks
    /// flush between runs. Those tables are tiny, freeing them returns nothing to
    /// the OS, and dropping them would make the next fill pay to grow from zero.
    #[test]
    fn clear_db_keeps_small_shard_tables() {
        let store = new_store(1);
        fill(&store, 0, 8);

        let (_, cap_before) = total(&store[0]);
        let flushed = clear_db(&store[0]);
        let (len_after, cap_after) = total(&store[0]);

        assert_eq!(len_after, 0, "flush must remove every key");
        assert_eq!(cap_after, cap_before, "small tables keep their capacity");
        assert_eq!(flushed.slots_released, 0);
        assert!(
            !flushed.should_trim(),
            "a handful of keys must not trigger a malloc_trim"
        );
    }

    #[test]
    fn clear_store_empties_every_db_and_its_times_to_live() {
        let store = new_store(4);
        for db in 0..4 {
            fill(&store, db, 64);
            let key = format!("flush-key-{:012}", 7);
            assert!(get_shard(&store[db], &key).write().set_expires(&key, 1));
        }

        let flushed = clear_store(&store);

        assert_eq!(flushed.entries, 4 * 64);
        for db in 0..4 {
            assert_eq!(total(&store[db]).0, 0, "db{db} still has keys");
            assert!(
                store[db]
                    .iter()
                    .all(|s| s.holds_no_ttl() && s.read().ttl_len() == 0),
                "db{db} still has times to live"
            );
        }
    }

    /// `FLUSHDB` is scoped to the selected database.
    #[test]
    fn clear_db_leaves_other_dbs_alone() {
        let store = new_store(2);
        fill(&store, 0, 32);
        fill(&store, 1, 32);

        clear_db(&store[0]);

        assert_eq!(total(&store[0]).0, 0);
        assert_eq!(total(&store[1]).0, 32, "FLUSHDB must not touch other dbs");
    }

    /// A flush big enough to matter is worth a trim even when every individual
    /// table stayed under the release floor.
    #[test]
    fn should_trim_tracks_entry_volume() {
        assert!(!Flushed::default().should_trim());
        assert!(
            !Flushed {
                entries: TRIM_MIN_ENTRIES - 1,
                slots_released: 0,
                ..Flushed::default()
            }
            .should_trim()
        );
        assert!(
            Flushed {
                entries: TRIM_MIN_ENTRIES,
                slots_released: 0,
                ..Flushed::default()
            }
            .should_trim()
        );
        assert!(
            Flushed {
                entries: 1,
                slots_released: 1,
                ..Flushed::default()
            }
            .should_trim()
        );
    }

    /// Flushing must leave the shards usable, not just empty.
    #[test]
    fn store_is_writable_after_flush() {
        let store = new_store(1);
        fill(&store, 0, SHARD_RELEASE_MIN_CAPACITY * num_shards() * 4);
        clear_db(&store[0]);

        fill(&store, 0, 100);
        assert_eq!(total(&store[0]).0, 100);
        let key = "flush-key-000000000042".to_string();
        assert!(get_shard(&store[0], &key).read().contains_key(key.as_str()));
    }
}

#[cfg(test)]
mod staging_swap_tests {
    use super::*;
    use crate::types::KiviDBValue;

    /// Full-resync uses swap so live never serves an empty cleared map while RDB is on the wire.
    #[test]
    fn swap_kv_with_staging_moves_staging_maps_into_live() {
        let live = new_store(1);
        let staging = new_store(1);
        let k = "swap-key";
        let val = KiviDBValue::String(crate::types::SharedBytes::from(&b"from-staging"[..]));
        get_shard(&staging[0], k).write().insert(k, val);
        assert!(get_shard(&live[0], k).read().get(k).is_none());
        swap_kv_with_staging(&live, &staging);
        match get_shard(&live[0], k)
            .read()
            .get(k)
            .expect("key on live after swap")
        {
            ValueRef::String(b) => assert_eq!(&b[..], b"from-staging"),
            _ => panic!("expected string value"),
        }
    }

    #[test]
    fn a_swap_moves_times_to_live_with_their_keys() {
        let live = new_store(1);
        let staging = new_store(1);
        let k = "exp-key";
        let val = KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]));
        get_shard(&staging[0], k)
            .write()
            .insert_expiring(k, val, Some(1_234));
        assert!(!get_shard(&staging[0], k).holds_no_ttl());
        swap_kv_with_staging(&live, &staging);
        assert_eq!(get_shard(&live[0], k).read().expires(k), Some(1_234));
        assert!(!get_shard(&live[0], k).holds_no_ttl());
        assert!(get_shard(&staging[0], k).holds_no_ttl());
    }
}

#[cfg(test)]
mod shrink_tests {
    use super::*;
    use crate::types::KiviDBValue;

    fn table(keys: usize) -> ShardLock {
        let mut map = ShardMap::new();
        for i in 0..keys {
            map.insert(
                format!("key-{i}"),
                KiviDBValue::String(crate::types::SharedBytes::from(i.to_string().as_str())),
            );
        }
        ShardLock::new(map)
    }

    fn value(map: &ShardLock, key: &str) -> Option<Vec<u8>> {
        match map.read().get(key) {
            Some(ValueRef::String(b)) => Some(b.to_vec()),
            _ => None,
        }
    }

    #[test]
    fn a_table_keys_have_mostly_left_shrinks_once() {
        let map = table(100_000);
        let grown = map.read().capacity();
        for i in (0..100_000).filter(|i| i % 10 != 0) {
            map.write().remove(&format!("key-{i}"));
        }
        assert!(map.shrink_if_sparse());
        let shrunk = map.read().capacity();
        assert!(shrunk * 4 < grown, "{grown} -> {shrunk}");
        assert!(shrunk >= 10_000 + 10_000 / 8, "no room left: {shrunk}");
        assert_eq!(map.read().len(), 10_000);
        assert_eq!(value(&map, "key-990"), Some(b"990".to_vec()));
        // Not again until more keys go.
        assert!(!map.shrink_if_sparse());
    }

    #[test]
    fn a_list_of_times_to_live_most_have_left_shrinks() {
        let map = table(10_000);
        for i in 0..10_000 {
            map.write().set_expires(&format!("key-{i}"), u64::MAX / 2);
        }
        let grown = {
            let m = map.read();
            assert_eq!(m.ttl_len(), 10_000);
            m.ttl_len()
        };
        for i in (0..10_000).filter(|i| i % 10 != 0) {
            assert!(map.write().persist(&format!("key-{i}")));
        }
        // The table is full; the list is not.
        assert!(map.shrink_if_sparse());
        assert_eq!(map.read().ttl_len(), 1_000);
        assert_eq!(map.read().len(), 10_000);
        assert_eq!(map.read().expires("key-990"), Some(u64::MAX / 2));
        assert_eq!(map.read().expires("key-991"), None);
        assert!(grown > 1_000);
        assert!(!map.shrink_if_sparse());
    }

    #[test]
    fn full_small_and_just_grown_tables_are_left_alone() {
        let map = table(100_000);
        assert!(!map.shrink_if_sparse());
        let small = table(100);
        small.write().clear();
        assert!(!small.shrink_if_sparse());
        // Grown by one key past its room: half empty, but not sparse.
        let map = table(0);
        let mut i = 0u64;
        loop {
            let before = map.read().capacity();
            map.write().insert_str(format!("key-{i}"), b"v");
            i += 1;
            if before >= 4096 && map.read().capacity() > before {
                break;
            }
        }
        assert!(!map.shrink_if_sparse());
    }
}

#[cfg(test)]
mod shard_lock_tests {
    use super::*;
    use crate::types::KiviDBValue;

    fn s() -> KiviDBValue {
        KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]))
    }

    /// The count readers see without the lock follows every way a writer
    /// can give a key a time to live or take it away, because it is taken
    /// as the writer lets go.
    #[test]
    fn the_count_follows_what_writers_do() {
        let cell = ShardLock::default();
        assert!(cell.holds_no_ttl());
        assert!(cell.holds_no_keys());
        cell.write().insert_str("k", b"v");
        assert!(!cell.holds_no_keys());
        cell.write().remove("k");
        assert!(cell.holds_no_keys());
        // Times to come: a key past its time is absent to these writes.
        let t = u64::MAX / 2;

        cell.write().insert_expiring("a", s(), Some(t + 5));
        assert!(!cell.holds_no_ttl());

        cell.write().insert_str("b", b"x");
        cell.write().set_expires("b", t + 9);
        assert_eq!(cell.ttl_count(), 2);
        cell.write().remove("a");
        assert!(!cell.holds_no_ttl());
        // An overwrite keeps it; one that says so takes it away.
        cell.write().insert("b", s());
        assert_eq!(cell.read().expires("b"), Some(t + 9));
        cell.write().insert_expiring("b", s(), None);
        assert!(cell.holds_no_ttl());

        cell.write().insert_expiring("c", s(), Some(t + 1));
        assert!(cell.write().persist("c"));
        assert!(cell.holds_no_ttl());
        cell.write().set_expires("c", t + 3);
        cell.write().clear();
        assert!(cell.holds_no_ttl());

        // A write over a key past its time takes the old time away.
        cell.write().insert_expiring("d", s(), Some(1));
        assert_eq!(cell.ttl_count(), 1);
        cell.write().insert("d", s());
        assert!(cell.holds_no_ttl());
        assert_eq!(cell.read().expires("d"), None);
        cell.write().clear();

        // Swapped whole, as SWAPDB and a flush do.
        let other = ShardLock::default();
        other.write().insert_expiring("c", s(), Some(t + 2));
        std::mem::swap(&mut *cell.write(), &mut *other.write());
        assert!(!cell.holds_no_ttl());
        assert!(other.holds_no_ttl());
        assert!(!cell.holds_no_keys());
        assert!(other.holds_no_keys());
        assert_eq!(cell.read().ttl_len(), 1);
    }
}