armdb 0.2.0

sharded bitcask key-value storage optimized for NVMe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
use std::collections::HashMap;
use std::hash::Hash;
use std::mem::size_of;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

use crate::Key;
use crate::byte_view::ByteView;
use crate::cache::{BlockCache, BlockKey};
use crate::compaction::{CompactionIndex, compact_shard};
use crate::config::Config;
use crate::disk_loc::DiskLoc;
use crate::engine::Engine;
use crate::error::{DbError, DbResult};
use crate::hook::{NoHook, WriteHook};
use crate::io::aligned_buf::AlignedBuf;
use crate::recovery::recover_var_map;
use crate::shard::ShardInner;
use crate::sync::{self, Mutex, MutexGuard};

const MAX_STALE_RETRIES: usize = 3;

/// A map with fixed-size keys and variable-length values.
/// Uses per-shard HashMap for O(1) lookup. Values are stored on disk,
/// cached at 4096-byte block granularity via `BlockCache`.
/// No ordered iteration — use `VarTree` if you need prefix/range scans.
///
/// Each `VarMap` owns its storage engine — one map = one database directory.
pub struct VarMap<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K> = NoHook> {
    indexes: Vec<Mutex<HashMap<K, DiskLoc>>>,
    engine: Engine,
    cache: BlockCache,
    compaction_threshold: f64,
    shard_prefix_bits: usize,
    hook: H,
    entry_count: AtomicUsize,
}

impl<K: Key + Send + Sync + Hash + Eq> VarMap<K> {
    /// Open or create a `VarMap` at the given path.
    /// Recovers the index from existing data files on disk.
    pub fn open(path: impl AsRef<std::path::Path>, config: Config) -> DbResult<Self> {
        Self::open_inner(path, config, NoHook)
    }
}

impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> VarMap<K, H> {
    /// Open or create a `VarMap` with a write hook for secondary index maintenance.
    pub fn open_hooked(
        path: impl AsRef<std::path::Path>,
        config: Config,
        hook: H,
    ) -> DbResult<Self> {
        Self::open_inner(path, config, hook)
    }

    fn open_inner(path: impl AsRef<std::path::Path>, config: Config, hook: H) -> DbResult<Self> {
        let compaction_threshold = config.compaction_threshold;
        let shard_prefix_bits = config.shard_prefix_bits;
        let cache = BlockCache::new(&config.cache);
        let engine = Engine::open(path, config)?;

        let shard_count = engine.shards().len();
        let mut indexes = Vec::with_capacity(shard_count);
        for _ in 0..shard_count {
            indexes.push(Mutex::new(HashMap::new()));
        }

        let map = Self {
            indexes,
            engine,
            cache,
            compaction_threshold,
            shard_prefix_bits,
            hook,
            entry_count: AtomicUsize::new(0),
        };

        // Recover index from disk
        let shard_dirs = map.engine.shard_dirs();
        let shard_dir_refs = Engine::shard_dir_refs(&shard_dirs);
        let shard_ids = map.engine.shard_ids();

        let hints = map.engine.hints();
        let outcome = recover_var_map::<K>(
            &shard_dir_refs,
            &shard_ids,
            map.indexes(),
            hints,
            #[cfg(feature = "encryption")]
            map.engine.cipher(),
        )?;
        for tail in &outcome.active_tails {
            map.engine.shards()[tail.shard_idx].apply_recovery_tail(tail)?;
        }
        for (shard_idx, dead) in outcome.shard_dead_bytes {
            map.engine.shards()[shard_idx].install_dead_bytes(dead);
        }
        let max_gsn = outcome.max_gsn;

        let initial_len: usize = map.indexes.iter().map(|m| sync::lock(m).len()).sum();
        map.entry_count.store(initial_len, AtomicOrdering::Relaxed);

        map.engine
            .gsn()
            .fetch_max(max_gsn + 1, AtomicOrdering::Relaxed);
        if hints {
            for shard in map.engine.shards().iter() {
                shard.set_key_len(size_of::<K>());
            }
        }
        tracing::info!(
            key_size = size_of::<K>(),
            entries = map.len(),
            "var_map recovered"
        );

        Ok(map)
    }

    /// Graceful shutdown: write hint files (if enabled), flush write buffers + fsync.
    pub fn close(self) -> DbResult<()> {
        if self.engine.hints() {
            self.sync_hints()?;
        }
        self.engine.flush()
    }

    /// Flush all shard write buffers to disk (without fsync).
    pub fn flush_buffers(&self) -> DbResult<()> {
        self.engine.flush_buffers()
    }

    /// Get the database configuration.
    pub fn config(&self) -> &Config {
        self.engine.config()
    }
}

impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> CompactionIndex<K> for VarMap<K, H> {
    fn update_if_match(&self, key: &K, old_loc: DiskLoc, new_loc: DiskLoc) -> bool {
        let mut index = sync::lock(&self.indexes[self.shard_for(key)]);
        if let Some(disk) = index.get_mut(key)
            && *disk == old_loc
        {
            *disk = new_loc;
            return true;
        }
        false
    }

    fn invalidate_blocks(&self, shard_id: u8, file_id: u32, total_bytes: u64) {
        self.cache.invalidate_file(shard_id, file_id, total_bytes);
    }

    fn contains_key(&self, key: &K) -> bool {
        self.contains(key)
    }
}

impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> VarMap<K, H> {
    /// Trigger a compaction pass across all shards.
    pub fn compact(&self) -> DbResult<usize> {
        let mut total_compacted = 0;
        for shard in self.engine.shards().iter() {
            total_compacted += compact_shard(shard, self, self.compaction_threshold)?;
        }
        Ok(total_compacted)
    }

    /// Get a value by key. Checks block cache first, then reads from disk.
    pub fn get(&self, key: &K) -> Option<ByteView> {
        metrics::counter!("armdb.ops", "op" => "get", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.get");
        let shard_id = self.shard_for(key);
        for _ in 0..MAX_STALE_RETRIES {
            let disk = {
                let index = sync::lock(&self.indexes[shard_id]);
                match index.get(key) {
                    Some(d) => *d,
                    None => return None,
                }
            };
            match self.read_value_cached_inner(&disk) {
                Ok(v) => return Some(v),
                Err(DbError::StaleDiskLoc) => {
                    metrics::counter!("armdb.read.stale_retry", "tree" => "var_map").increment(1);
                    continue;
                }
                Err(_e) => {
                    #[cfg(feature = "hot-path-tracing")]
                    tracing::error!("VarMap read_value_cached error: {:?}", _e);
                    return None;
                }
            }
        }
        None
    }

    /// Get a value by key, returning `Err(KeyNotFound)` if absent.
    pub fn get_or_err(&self, key: &K) -> DbResult<ByteView> {
        self.get(key).ok_or(DbError::KeyNotFound)
    }

    /// Insert or update a key-value pair.
    pub fn put(&self, key: &K, value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "put", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.put");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let mut index = sync::lock(&self.indexes[shard_id]);
        let old_value = if H::NEEDS_OLD_VALUE {
            if let Some(disk) = index.get(key) {
                Some(self.read_value_locked_result(disk, &inner)?)
            } else {
                None
            }
        } else {
            None
        };
        self.put_locked(shard_id, &mut inner, &mut index, key, value)?;
        drop(index);
        drop(inner);
        self.hook.on_write(key, old_value.as_deref(), Some(value));
        Ok(())
    }

    /// Insert a key-value pair only if the key does not exist.
    /// Returns `Err(KeyExists)` if the key is already present.
    pub fn insert(&self, key: &K, value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "insert", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.insert");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let mut index = sync::lock(&self.indexes[shard_id]);
        self.insert_locked(shard_id, &mut inner, &mut index, key, value)?;
        drop(index);
        drop(inner);
        self.hook.on_write(key, None, Some(value));
        Ok(())
    }

    /// Delete a key. Returns `true` if the key existed.
    pub fn delete(&self, key: &K) -> DbResult<bool> {
        metrics::counter!("armdb.ops", "op" => "delete", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.delete");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let mut index = sync::lock(&self.indexes[shard_id]);
        let old_value = if H::NEEDS_OLD_VALUE {
            if let Some(disk) = index.get(key) {
                Some(self.read_value_locked_result(disk, &inner)?)
            } else {
                None
            }
        } else {
            None
        };
        let existed = self.delete_locked(shard_id, &mut inner, &mut index, key)?;
        drop(index);
        drop(inner);
        if existed {
            self.hook.on_write(key, old_value.as_deref(), None);
        }
        Ok(existed)
    }

    /// Compare-and-swap: if current value == expected, replace with new_value.
    /// Returns `Ok(())` on success, `Err(CasMismatch)` if current != expected,
    /// `Err(KeyNotFound)` if key doesn't exist.
    ///
    /// **Caveat:** Holds the shard lock while reading the current value. On a
    /// block-cache miss this performs disk I/O under the lock, blocking all
    /// writes to the same shard. Pre-warm the cache to avoid latency spikes.
    pub fn cas(&self, key: &K, expected: &[u8], new_value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "cas", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.cas");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let mut index = sync::lock(&self.indexes[shard_id]);

        let disk = *index.get(key).ok_or(DbError::KeyNotFound)?;
        let current = self
            .read_value_locked(&disk, &inner)
            .ok_or(DbError::KeyNotFound)?;
        if current.as_ref() != expected {
            return Err(DbError::CasMismatch);
        }

        let (new_disk_loc, _gsn) =
            inner.append_entry(shard_id as u8, key.as_bytes(), new_value, false)?;
        inner.add_dead_bytes(
            disk.file_id,
            crate::entry::entry_size(size_of::<K>(), disk.len),
        );
        let _old = index.insert(*key, new_disk_loc);
        debug_assert!(_old.is_some(), "cas: key must exist in index");

        drop(index);
        drop(inner);
        self.hook.on_write(
            key,
            if H::NEEDS_OLD_VALUE {
                Some(&*current)
            } else {
                None
            },
            Some(new_value),
        );
        Ok(())
    }

    /// Atomically read-modify-write. Returns `Some(new_value)` if key existed, `None` otherwise.
    /// The closure receives the current value and returns a new ByteView.
    /// The closure must not be heavy (shard lock is held).
    ///
    /// **Caveat:** Holds the shard lock while reading the current value. On a
    /// block-cache miss this performs disk I/O under the lock, blocking all
    /// writes to the same shard. Pre-warm the cache to avoid latency spikes.
    pub fn update(&self, key: &K, f: impl FnOnce(&[u8]) -> ByteView) -> DbResult<Option<ByteView>> {
        self.update_inner(key, f, false)
    }

    /// Like [`update()`](Self::update), but returns `Some(old_value)` instead of the new one.
    pub fn fetch_update(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> ByteView,
    ) -> DbResult<Option<ByteView>> {
        self.update_inner(key, f, true)
    }

    pub(crate) fn try_update_inner(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> DbResult<Option<ByteView>>,
        return_old: bool,
    ) -> DbResult<Option<ByteView>> {
        metrics::counter!("armdb.ops", "op" => "update", "tree" => "var_map").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_map.update");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let mut index = sync::lock(&self.indexes[shard_id]);

        let disk = match index.get(key) {
            Some(d) => *d,
            None => return Ok(None),
        };

        let current = match self.read_value_locked(&disk, &inner) {
            Some(v) => v,
            None => return Ok(None),
        };

        let new_value = match f(&current)? {
            Some(v) => v,
            None => return Ok(Some(current)),
        };

        let (new_disk_loc, _gsn) =
            inner.append_entry(shard_id as u8, key.as_bytes(), &new_value, false)?;
        inner.add_dead_bytes(
            disk.file_id,
            crate::entry::entry_size(size_of::<K>(), disk.len),
        );
        let _old = index.insert(*key, new_disk_loc);
        debug_assert!(_old.is_some(), "update: key must exist in index");

        drop(index);
        drop(inner);
        self.hook.on_write(
            key,
            if H::NEEDS_OLD_VALUE {
                Some(&*current)
            } else {
                None
            },
            Some(&*new_value),
        );
        Ok(Some(if return_old { current } else { new_value }))
    }

    fn update_inner(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> ByteView,
        return_old: bool,
    ) -> DbResult<Option<ByteView>> {
        self.try_update_inner(key, |bytes| Ok(Some(f(bytes))), return_old)
    }

    /// Check if a key exists.
    pub fn contains(&self, key: &K) -> bool {
        let index = sync::lock(&self.indexes[self.shard_for(key)]);
        index.contains_key(key)
    }

    /// Encoded value byte length for `key`, or `None` if absent.
    /// Reads only the in-memory index entry (`DiskLoc::len`); no disk I/O.
    pub fn entry_len(&self, key: &K) -> Option<u32> {
        let index = sync::lock(&self.indexes[self.shard_for(key)]);
        index.get(key).map(|disk| disk.len)
    }

    /// Total number of entries across all shards.
    pub fn len(&self) -> usize {
        self.entry_count.load(AtomicOrdering::Relaxed)
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Write hint files for all active shard files. Call during graceful shutdown.
    pub fn sync_hints(&self) -> DbResult<()> {
        for shard in self.engine.shards().iter() {
            shard.write_active_hint(size_of::<K>())?;
        }
        Ok(())
    }

    /// Pre-populate the block cache with blocks containing live values.
    ///
    /// Walks the index to collect unique block offsets, sorts them for sequential I/O,
    /// then reads each block into the cache. Only blocks with live data are loaded.
    pub fn warmup(&self) -> DbResult<()> {
        use std::collections::BTreeSet;

        let mut blocks: BTreeSet<(u8, u32, u64)> = BTreeSet::new();
        for index in self.indexes.iter() {
            let map = sync::lock(index);
            for disk in map.values() {
                let block_offset = disk.offset as u64 & !4095;
                blocks.insert((disk.shard_id, disk.file_id, block_offset));
            }
        }

        for (shard_id, file_id, block_offset) in &blocks {
            let key = BlockKey {
                shard_id: *shard_id,
                file_id: *file_id,
                block_offset: *block_offset,
            };
            if self.cache.get(&key).is_some() {
                continue;
            }
            let shard = &self.engine.shards()[*shard_id as usize];
            let (buf, is_full_block) = shard.read_block(*file_id, *block_offset)?;
            if is_full_block {
                self.cache.insert(key, Arc::new(buf));
            }
        }

        Ok(())
    }

    /// Iterate all entries and optionally mutate them. Call once at startup.
    ///
    /// - `Keep` — no change (fires `on_init` if `H::NEEDS_INIT`); not counted
    /// - `Update(new_value)` — replace value (hook-free write, fires `on_init`)
    /// - `Delete` — remove entry (hook-free tombstone, no hooks)
    ///
    /// `on_write` is NEVER fired during migrate — see `docs/hooks.md` in the armdb crate.
    /// Returns the number of mutated entries.
    pub fn migrate(
        &self,
        f: impl Fn(&K, &[u8]) -> crate::MigrateAction<ByteView>,
    ) -> DbResult<usize> {
        use crate::MigrateAction;

        let mut count = 0;
        for i in 0..self.engine.shards().len() {
            let keys: Vec<K> = {
                let index = sync::lock(&self.indexes[i]);
                index.keys().copied().collect()
            };
            for key in keys {
                let value = match self.get(&key) {
                    Some(v) => v,
                    None => {
                        tracing::warn!(
                            key = ?key.as_bytes(),
                            "var_map migrate: skipping entry — value read failed"
                        );
                        continue;
                    }
                };
                match f(&key, &value) {
                    MigrateAction::Keep => {
                        if H::NEEDS_INIT {
                            self.hook.on_init(&key, &value);
                        }
                    }
                    MigrateAction::Update(new_value) => {
                        // Keys were collected from indexes[i], so they always
                        // hash to shard i — no need to recompute via shard_for.
                        {
                            let mut inner = self.engine.shards()[i].lock();
                            let mut index = sync::lock(&self.indexes[i]);
                            self.put_locked(i, &mut inner, &mut index, &key, &new_value)?;
                        }
                        if H::NEEDS_INIT {
                            self.hook.on_init(&key, &new_value);
                        }
                        count += 1;
                    }
                    MigrateAction::Delete => {
                        let mut inner = self.engine.shards()[i].lock();
                        let mut index = sync::lock(&self.indexes[i]);
                        self.delete_locked(i, &mut inner, &mut index, &key)?;
                        count += 1;
                    }
                }
            }
        }

        tracing::info!(mutations = count, "var_map migration complete");
        Ok(count)
    }

    /// Replay `on_init` for every live entry. Used when no migration runs
    /// (Db calls this after `run_migration` returns `false`).
    ///
    /// Lock order: snapshot keys under per-shard index lock, release the
    /// lock, then call `self.get(key)` which re-acquires the index lock
    /// briefly to copy the `DiskLoc` and reads the value WITHOUT holding
    /// the index lock. This matches the lock order of public writes
    /// (shard → index) and avoids the inverted order that would deadlock
    /// against an active writer.
    pub(crate) fn replay_init(&self) {
        if !H::NEEDS_INIT {
            return;
        }
        let mut count = 0usize;
        for i in 0..self.engine.shards().len() {
            let keys: Vec<K> = {
                let index = sync::lock(&self.indexes[i]);
                index.keys().copied().collect()
            };
            for key in keys {
                let value = match self.get(&key) {
                    Some(v) => v,
                    None => {
                        tracing::warn!(
                            key = ?key.as_bytes(),
                            "var_map replay_init: skipping entry — value read failed"
                        );
                        continue;
                    }
                };
                self.hook.on_init(&key, &value);
                count += 1;
            }
        }
        tracing::debug!(replayed = count, "var_map replay_init complete");
    }

    /// Atomically execute multiple operations on a single shard.
    /// All keys must route to the same shard as `shard_key`.
    /// The closure must be short — shard lock is held for its duration.
    pub fn atomic<R>(
        &self,
        shard_key: &K,
        f: impl FnOnce(&mut VarMapShard<'_, K, H>) -> DbResult<R>,
    ) -> DbResult<R> {
        let shard_id = self.shard_for(shard_key);
        let inner = self.engine.shards()[shard_id].lock();
        let index = sync::lock(&self.indexes[shard_id]);
        let mut shard = VarMapShard {
            tree: self,
            inner,
            index,
            shard_id,
        };
        f(&mut shard)
    }

    pub(crate) fn indexes(&self) -> &[Mutex<HashMap<K, DiskLoc>>] {
        &self.indexes
    }

    fn put_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        index: &mut HashMap<K, DiskLoc>,
        key: &K,
        value: &[u8],
    ) -> DbResult<()> {
        let (disk_loc, _gsn) = inner.append_entry(shard_id as u8, key.as_bytes(), value, false)?;

        if let Some(old_disk) = index.insert(*key, disk_loc) {
            inner.add_dead_bytes(
                old_disk.file_id,
                crate::entry::entry_size(size_of::<K>(), old_disk.len),
            );
        } else {
            self.entry_count.fetch_add(1, AtomicOrdering::Relaxed);
        }

        Ok(())
    }

    fn insert_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        index: &mut HashMap<K, DiskLoc>,
        key: &K,
        value: &[u8],
    ) -> DbResult<()> {
        if index.contains_key(key) {
            return Err(DbError::KeyExists);
        }

        let (disk_loc, _gsn) = inner.append_entry(shard_id as u8, key.as_bytes(), value, false)?;
        index.insert(*key, disk_loc);
        self.entry_count.fetch_add(1, AtomicOrdering::Relaxed);
        Ok(())
    }

    fn delete_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        index: &mut HashMap<K, DiskLoc>,
        key: &K,
    ) -> DbResult<bool> {
        if !index.contains_key(key) {
            return Ok(false);
        }

        inner.append_entry(shard_id as u8, key.as_bytes(), &[], true)?;

        if let Some(old_disk) = index.remove(key) {
            inner.add_dead_bytes(
                old_disk.file_id,
                crate::entry::entry_size(size_of::<K>(), old_disk.len),
            );
            self.entry_count.fetch_sub(1, AtomicOrdering::Relaxed);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn read_value_cached_inner(&self, disk: &DiskLoc) -> DbResult<ByteView> {
        let len = disk.len as usize;
        let start = (disk.offset & 4095) as usize;

        // Large values (>2 blocks) bypass the cached path. This check MUST
        // sit before the cache lookup: a warm first block would otherwise
        // route a large value into `extract_from_block`, which only supports
        // two blocks and would panic on `next[..second_len]` when
        // `second_len > 4096`. StaleDiskLoc propagates so VarMap::get's
        // per-shard-index retry loop takes a fresh DiskLoc snapshot.
        if start + len > 8192 {
            let shard = &self.engine.shards()[disk.shard_id as usize];
            let inner = shard.lock();
            return self.read_value_locked_result(disk, &inner);
        }

        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };

        if let Some(block) = self.cache.get(&cache_key) {
            metrics::counter!("armdb.cache.hit").increment(1);
            return Self::extract_from_block(&block, start, len, || {
                self.get_or_read_block(disk.shard_id, disk.file_id, block_offset + 4096)
            });
        }

        {
            let shard = &self.engine.shards()[disk.shard_id as usize];
            let inner = shard.lock();
            if inner.active.file_id == disk.file_id
                && let Some(bytes) = inner.write_buf.read(disk.offset as u64, len)
            {
                return Ok(ByteView::new(bytes));
            }
        }

        metrics::counter!("armdb.cache.miss").increment(1);
        let block = self.get_or_read_block(disk.shard_id, disk.file_id, block_offset)?;
        Self::extract_from_block(&block, start, len, || {
            self.get_or_read_block(disk.shard_id, disk.file_id, block_offset + 4096)
        })
    }

    fn extract_from_block(
        block: &AlignedBuf,
        start: usize,
        len: usize,
        next_block: impl FnOnce() -> DbResult<Arc<AlignedBuf>>,
    ) -> DbResult<ByteView> {
        debug_assert!(
            start + len <= 8192,
            "extract_from_block supports at most 2 blocks (8192 bytes)"
        );
        if start + len <= 4096 {
            Ok(ByteView::new(&block[start..start + len]))
        } else {
            let next = next_block()?;
            let first_part = &block[start..];
            let second_len = len - first_part.len();
            let mut combined = Vec::with_capacity(len);
            combined.extend_from_slice(first_part);
            combined.extend_from_slice(&next[..second_len]);
            Ok(ByteView::from_vec(combined))
        }
    }

    fn get_or_read_block(
        &self,
        shard_id: u8,
        file_id: u32,
        block_offset: u64,
    ) -> DbResult<Arc<AlignedBuf>> {
        let key = BlockKey {
            shard_id,
            file_id,
            block_offset,
        };
        if let Some(cached) = self.cache.get(&key) {
            return Ok(cached);
        }
        let shard = &self.engine.shards()[shard_id as usize];
        let (buf, is_full_block) = shard.read_block(file_id, block_offset)?;
        let arc = Arc::new(buf);
        if is_full_block {
            self.cache.insert(key, arc.clone());
        }
        Ok(arc)
    }

    /// Read value when shard lock is already held, propagating `DbError`.
    /// Used by both `read_value_locked` (Option wrapper) and the large-value
    /// fallback in `read_value_cached_inner`.
    fn read_value_locked_result(&self, disk: &DiskLoc, inner: &ShardInner) -> DbResult<ByteView> {
        let len = disk.len as usize;

        // 1. Write buffer (for unflushed data)
        if inner.active.file_id == disk.file_id
            && let Some(bytes) = inner.write_buf.read(disk.offset as u64, len)
        {
            return Ok(ByteView::new(bytes));
        }

        // 2. Block cache (lock-free, single-block fast path)
        let block_offset = disk.offset as u64 & !4095;
        let start = (disk.offset & 4095) as usize;
        if start + len <= 4096 {
            let cache_key = BlockKey {
                shard_id: disk.shard_id,
                file_id: disk.file_id,
                block_offset,
            };
            if let Some(block) = self.cache.get(&cache_key) {
                return Ok(ByteView::new(&block[start..start + len]));
            }

            // 2b. Cache miss — read block under held lock, populate cache
            let (buf, is_full_block) = inner.read_block_locked(disk.file_id, block_offset)?;
            let arc = Arc::new(buf);
            if is_full_block {
                self.cache.insert(cache_key, arc.clone());
            }
            return Ok(ByteView::new(&arc[start..start + len]));
        }

        // 3. Multi-block: disk read via encryption-aware helper (no cache).
        let bytes = inner.read_value_from_disk_locked(disk)?;
        Ok(ByteView::new(&bytes))
    }

    /// Read value when shard lock is already held. Used by CAS/update.
    ///
    /// Thin `Option` wrapper around `read_value_locked_result` that preserves
    /// the existing call-site contract: `StaleDiskLoc` is logged at error
    /// level and collapsed to `None`; other errors collapse to `None` silently.
    fn read_value_locked(&self, disk: &DiskLoc, inner: &ShardInner) -> Option<ByteView> {
        match self.read_value_locked_result(disk, inner) {
            Ok(v) => Some(v),
            Err(DbError::StaleDiskLoc) => {
                tracing::error!(
                    file_id = disk.file_id,
                    shard_id = disk.shard_id,
                    "stale DiskLoc under shard lock - programming bug",
                );
                None
            }
            Err(_) => None,
        }
    }

    pub fn shard_for(&self, key: &K) -> usize {
        crate::shard_for_key(key, self.shard_prefix_bits, self.engine.shards().len())
    }
}

#[cfg(feature = "replication")]
impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> crate::replication::ReplicationTarget
    for VarMap<K, H>
{
    fn apply_entry(
        &self,
        _shard_inner: &mut crate::shard::ShardInner,
        shard_id: u8,
        file_id: u32,
        entry_offset: u64,
        header: &crate::entry::EntryHeader,
        key: &[u8],
        _value: &[u8],
    ) -> DbResult<crate::replication::ApplyOutcome> {
        use crate::replication::ApplyOutcome;

        let key = K::from_bytes(key);

        let disk = DiskLoc::new(
            shard_id,
            file_id,
            (entry_offset + size_of::<crate::entry::EntryHeader>() as u64 + size_of::<K>() as u64)
                as u32,
            header.value_len,
        );

        if header.is_tombstone() {
            let old = sync::lock(&self.indexes[self.shard_for(&key)]).remove(&key);
            match old {
                Some(old_disk) => {
                    self.entry_count.fetch_sub(1, AtomicOrdering::Relaxed);
                    Ok(ApplyOutcome::TombstoneRemoved(old_disk))
                }
                None => Ok(ApplyOutcome::Inserted), // no-op tombstone — no dead bytes
            }
        } else {
            let old = sync::lock(&self.indexes[self.shard_for(&key)]).insert(key, disk);
            match old {
                Some(old_disk) => Ok(ApplyOutcome::Replaced(old_disk)),
                None => {
                    self.entry_count.fetch_add(1, AtomicOrdering::Relaxed);
                    Ok(ApplyOutcome::Inserted)
                }
            }
        }
    }

    fn try_apply_entry(
        &self,
        shard_inner: &mut crate::shard::ShardInner,
        shard_id: u8,
        file_id: u32,
        entry_offset: u64,
        header: &crate::entry::EntryHeader,
        raw_after_header: &[u8],
    ) -> DbResult<crate::replication::ApplyOutcome> {
        use crate::replication::ApplyOutcome;

        if raw_after_header.len() < size_of::<K>() + header.value_len as usize {
            return Ok(ApplyOutcome::NotMatched);
        }
        let key = &raw_after_header[..size_of::<K>()];
        let value = &raw_after_header[size_of::<K>()..size_of::<K>() + header.value_len as usize];
        let crc = crate::entry::compute_crc32(header.gsn, header.value_len, key, value);
        if crc != header.crc32 {
            return Ok(ApplyOutcome::NotMatched);
        }
        self.apply_entry(
            shard_inner,
            shard_id,
            file_id,
            entry_offset,
            header,
            key,
            value,
        )
    }

    fn key_len(&self) -> usize {
        size_of::<K>()
    }
}

#[cfg(feature = "replication")]
impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> VarMap<K, H> {
    /// Install SPSC replication producers into every shard and start a
    /// `ReplicationServer` bound to `bind_addr`.
    ///
    /// # Single-call contract
    ///
    /// Each call installs fresh SPSC producers, replacing any previously
    /// installed ones. Call this at most once per `VarMap` instance — a
    /// second call will orphan the in-flight producer of any active streaming
    /// connection on the first server, which will then observe an empty ring
    /// buffer and silently stop forwarding entries.
    pub fn start_replication_server(
        &self,
        bind_addr: std::net::SocketAddr,
        signal: crate::shutdown::ShutdownSignal,
    ) -> crate::error::DbResult<crate::replication::ReplicationServer> {
        let consumers = self.install_replication_producers()?;
        crate::replication::ReplicationServer::start(
            bind_addr,
            self.engine.shards().clone(),
            consumers,
            self.engine.config().max_file_size,
            signal,
        )
    }

    fn install_replication_producers(
        &self,
    ) -> crate::error::DbResult<Vec<rtrb::Consumer<crate::replication::ReplicationEntry>>> {
        const SPSC_CAPACITY: usize = 4096;
        let shards = self.engine.shards();
        let mut consumers = Vec::with_capacity(shards.len());
        for shard in shards.iter() {
            let (p, c) = rtrb::RingBuffer::new(SPSC_CAPACITY);
            shard.set_replication_producer(p);
            consumers.push(c);
        }
        Ok(consumers)
    }

    /// Start a `ReplicationClient` that streams entries from `leader_addr`
    /// into `registry`. Symmetric to [`Self::start_replication_server`].
    ///
    /// `key_len` is derived from `size_of::<K>()`.
    pub fn start_replication_client(
        &self,
        leader_addr: std::net::SocketAddr,
        registry: std::sync::Arc<crate::replication::ReplicationRegistry>,
        signal: crate::shutdown::ShutdownSignal,
    ) -> crate::error::DbResult<crate::replication::ReplicationClient> {
        crate::replication::ReplicationClient::start(
            leader_addr,
            self.engine.shards().clone(),
            registry,
            size_of::<K>() as u16,
            signal,
        )
    }
}

#[cfg(feature = "replication")]
impl<K, H> VarMap<K, H>
where
    K: Key + Send + Sync + Hash + Eq + 'static,
    H: WriteHook<K> + Send + Sync + 'static,
{
    /// Wrap a shared handle to this map as a `Box<dyn ReplicationTarget>`.
    ///
    /// The returned box holds an `Arc` clone — the caller retains full read
    /// access to the original map through the `Arc` while the registry owns
    /// the box. This is the intended pattern for follower-side wiring:
    ///
    /// ```ignore
    /// let follower = Arc::new(VarMap::<[u8; 8]>::open(path, cfg)?);
    /// let registry = ReplicationRegistry::new(follower.as_replication_target());
    /// // `follower` remains usable for .get() etc.
    /// ```
    pub fn as_replication_target(
        self: &std::sync::Arc<Self>,
    ) -> Box<dyn crate::replication::ReplicationTarget> {
        Box::new(std::sync::Arc::clone(self))
    }
}

/// Handle for atomic multi-key operations within a single shard.
/// Obtained via [`VarMap::atomic`]. The shard + index locks are held for the
/// lifetime of this struct — keep the closure short.
pub struct VarMapShard<'a, K: Key + Send + Sync + Hash + Eq, H: WriteHook<K> = NoHook> {
    tree: &'a VarMap<K, H>,
    inner: MutexGuard<'a, ShardInner>,
    index: MutexGuard<'a, HashMap<K, DiskLoc>>,
    shard_id: usize,
}

impl<K: Key + Send + Sync + Hash + Eq, H: WriteHook<K>> VarMapShard<'_, K, H> {
    pub fn put(&mut self, key: &K, value: &[u8]) -> DbResult<()> {
        self.check_shard(key)?;
        self.tree
            .put_locked(self.shard_id, &mut self.inner, &mut self.index, key, value)
    }

    pub fn insert(&mut self, key: &K, value: &[u8]) -> DbResult<()> {
        self.check_shard(key)?;
        self.tree
            .insert_locked(self.shard_id, &mut self.inner, &mut self.index, key, value)
    }

    pub fn delete(&mut self, key: &K) -> DbResult<bool> {
        self.check_shard(key)?;
        self.tree
            .delete_locked(self.shard_id, &mut self.inner, &mut self.index, key)
    }

    pub fn get(&self, key: &K) -> Option<ByteView> {
        let disk = *self.index.get(key)?;
        self.tree.read_value_locked(&disk, &self.inner)
    }

    pub fn get_or_err(&self, key: &K) -> DbResult<ByteView> {
        self.get(key).ok_or(DbError::KeyNotFound)
    }

    pub fn contains(&self, key: &K) -> bool {
        self.index.contains_key(key)
    }

    fn check_shard(&self, key: &K) -> DbResult<()> {
        if self.tree.shard_for(key) != self.shard_id {
            return Err(DbError::ShardMismatch);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Config;
    use crate::compaction::compact_shard;
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
    use tempfile::tempdir;

    /// Test hook with counters for on_write / on_init calls and the last observed new value for
    /// on_write. NEEDS_INIT and NEEDS_OLD_VALUE are parameterized by const generics.
    #[derive(Default)]
    struct CountingHook<const NEEDS_INIT: bool, const NEEDS_OLD: bool> {
        writes: AtomicUsize,
        writes_with_old: AtomicUsize,
        inits: AtomicUsize,
        last_write_new: crate::sync::Mutex<Option<Vec<u8>>>,
        last_init_value: crate::sync::Mutex<Option<Vec<u8>>>,
    }

    impl<const NEEDS_INIT: bool, const NEEDS_OLD: bool> WriteHook<[u8; 8]>
        for CountingHook<NEEDS_INIT, NEEDS_OLD>
    {
        const NEEDS_OLD_VALUE: bool = NEEDS_OLD;
        const NEEDS_INIT: bool = NEEDS_INIT;

        fn on_write(&self, _key: &[u8; 8], old: Option<&[u8]>, new: Option<&[u8]>) {
            self.writes.fetch_add(1, AtomicOrdering::Relaxed);
            if old.is_some() {
                self.writes_with_old.fetch_add(1, AtomicOrdering::Relaxed);
            }
            *crate::sync::lock(&self.last_write_new) = new.map(<[u8]>::to_vec);
        }

        fn on_init(&self, _key: &[u8; 8], value: &[u8]) {
            self.inits.fetch_add(1, AtomicOrdering::Relaxed);
            *crate::sync::lock(&self.last_init_value) = Some(value.to_vec());
        }
    }

    fn open_test_map_hooked<const NEEDS_INIT: bool, const NEEDS_OLD: bool>(
        dir: &std::path::Path,
        hook: CountingHook<NEEDS_INIT, NEEDS_OLD>,
    ) -> VarMap<[u8; 8], CountingHook<NEEDS_INIT, NEEDS_OLD>> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        VarMap::open_hooked(dir, cfg, hook).expect("open hooked test map")
    }

    fn open_test_map(dir: &std::path::Path) -> VarMap<[u8; 8]> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        VarMap::open(dir, cfg).expect("open test map")
    }

    fn put_until_compactable(map: &VarMap<[u8; 8]>, key: [u8; 8]) -> DiskLoc {
        // Capture the FIRST put's DiskLoc — file 0 accumulates 100% dead bytes
        // as later overwrites move the live pointer to other files, so
        // compaction at threshold=0.0 erases it. The captured DiskLoc is
        // genuinely stale afterward. Each put is 280 bytes; with
        // max_file_size=8192, ~30 puts cross the first rotation boundary.
        // Use 65 puts so the snap file is sealed as immutable AND fully dead.
        map.put(&key, &[0u8; 256]).expect("first put");
        let snap = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");
        for i in 1..65u8 {
            map.put(&key, &[i; 256]).expect("overwrite");
        }
        map.put(&key, b"final-value-payload-XX").expect("final put");
        snap
    }

    #[test]
    fn var_map_len_tracks_mutations() {
        let dir = tempdir().unwrap();
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), Config::default()).unwrap();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());

        let k1 = [1u8; 8];
        let k2 = [2u8; 8];
        map.put(&k1, b"a").unwrap();
        assert_eq!(map.len(), 1);

        map.put(&k2, b"b").unwrap();
        assert_eq!(map.len(), 2);

        // Overwrite — len stays the same
        map.put(&k1, b"c").unwrap();
        assert_eq!(map.len(), 2);

        map.delete(&k1).unwrap();
        assert_eq!(map.len(), 1);

        map.delete(&k2).unwrap();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());

        // Delete non-existent — no change
        map.delete(&k1).unwrap();
        assert_eq!(map.len(), 0);
    }

    #[test]
    fn var_map_len_survives_reopen() {
        let dir = tempdir().unwrap();
        {
            let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), Config::default()).unwrap();
            for i in 0u64..50 {
                map.put(&i.to_le_bytes(), b"val").unwrap();
            }
            assert_eq!(map.len(), 50);
        }
        // Reopen
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), Config::default()).unwrap();
        assert_eq!(map.len(), 50);
    }

    #[test]
    fn read_value_cached_inner_returns_stale_after_compaction() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 7u64.to_be_bytes();
        let snap = put_until_compactable(&map, key);

        let shard = &map.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &map, 0.0).expect("compaction");

        match map.read_value_cached_inner(&snap) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn get_during_compaction_returns_some() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 11u64.to_be_bytes();
        let _snap = put_until_compactable(&map, key);
        let shard = &map.engine.shards()[0];
        let _ = compact_shard(shard, &map, 0.0).expect("compaction");

        let v = map.get(&key).expect("post-compaction get");
        assert_eq!(v.as_bytes(), b"final-value-payload-XX");
    }

    #[test]
    fn get_or_read_block_returns_stale_for_unknown_file_id() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        match map.get_or_read_block(0, 9999, 0) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(_) => panic!("expected StaleDiskLoc, got Ok"),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn retry_limit_returns_none_on_persistent_stale() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 99u64.to_be_bytes();
        map.put(&key, b"payload").expect("put");

        // Force every read_value_cached_inner call to see Stale by manually
        // clearing inner.immutable AND moving active.file_id out of the way.
        // The HashMap still points at the original (now-unreachable) file_id,
        // so each retry hits Shard::read_block which returns StaleDiskLoc.
        let snap = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");

        {
            let shard = &map.engine.shards()[snap.shard_id as usize];
            let mut inner = shard.lock();
            inner.immutable = Vec::new();
            inner.active.file_id = u32::MAX;
        }

        assert!(
            map.get(&key).is_none(),
            "MAX_STALE_RETRIES must terminate the retry loop and return None"
        );
    }

    #[test]
    fn var_map_replay_init_fires_on_init_per_live_key_raw() {
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        for i in 0u64..5 {
            map.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        map.delete(&3u64.to_be_bytes()).expect("delete");

        map.hook.writes.store(0, AtomicOrdering::Relaxed);
        map.hook.inits.store(0, AtomicOrdering::Relaxed);

        map.replay_init();

        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 4);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
    }

    #[test]
    fn var_map_replay_init_no_hook_is_noop() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        for i in 0u64..3 {
            map.put(&i.to_be_bytes(), &[i as u8; 8]).expect("put");
        }
        map.replay_init();
        assert!(map.get(&0u64.to_be_bytes()).is_some());
    }

    #[test]
    fn var_map_migrate_keep_fires_on_init_not_on_write_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        for i in 0u64..4 {
            map.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        map.hook.writes.store(0, AtomicOrdering::Relaxed);
        map.hook.inits.store(0, AtomicOrdering::Relaxed);

        let mutated = map.migrate(|_, _| MigrateAction::Keep).expect("migrate");

        assert_eq!(mutated, 0);
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 4);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
    }

    #[test]
    fn var_map_migrate_update_fires_on_init_with_new_value_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 42u64.to_be_bytes();
        map.put(&key, b"old-value").expect("put");
        map.hook.writes.store(0, AtomicOrdering::Relaxed);
        map.hook.inits.store(0, AtomicOrdering::Relaxed);

        let new = ByteView::new(b"new-value");
        let mutated = map
            .migrate(move |_, _| MigrateAction::Update(new.clone()))
            .expect("migrate");

        assert_eq!(mutated, 1);
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 1);
        let g = crate::sync::lock(&map.hook.last_init_value);
        assert_eq!(g.as_deref(), Some(b"new-value".as_ref()));
        drop(g);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(map.get(&key).unwrap().as_bytes(), b"new-value");
    }

    #[test]
    fn var_map_migrate_delete_fires_no_hooks_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 7u64.to_be_bytes();
        map.put(&key, b"x").expect("put");
        map.hook.writes.store(0, AtomicOrdering::Relaxed);
        map.hook.inits.store(0, AtomicOrdering::Relaxed);

        let mutated = map.migrate(|_, _| MigrateAction::Delete).expect("migrate");

        assert_eq!(mutated, 1);
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
        assert!(map.get(&key).is_none());
    }

    #[test]
    fn var_map_public_put_still_fires_on_write_once() {
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        map.put(&1u64.to_be_bytes(), b"v").expect("put");
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 1);
    }

    #[test]
    fn var_map_migrate_no_init_hook_is_silent_for_keep_and_update() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        // NEEDS_INIT = false: on_init must never be called.
        let map = open_test_map_hooked::<false, false>(dir.path(), CountingHook::default());

        for i in 0u64..3 {
            map.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        map.hook.writes.store(0, AtomicOrdering::Relaxed);
        map.hook.inits.store(0, AtomicOrdering::Relaxed);

        map.migrate(|_, _| MigrateAction::Keep)
            .expect("migrate keep");
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);

        let new = ByteView::new(b"new");
        map.migrate(move |_, _| MigrateAction::Update(new.clone()))
            .expect("migrate update");
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
    }

    #[test]
    fn var_map_atomic_does_not_fire_hooks() {
        let dir = tempdir().unwrap();
        let map = open_test_map_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 1u64.to_be_bytes();
        map.atomic(&key, |shard| {
            shard.put(&key, b"a")?;
            shard.delete(&key)?;
            Ok(())
        })
        .expect("atomic");

        assert_eq!(map.hook.writes.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(map.hook.inits.load(AtomicOrdering::Relaxed), 0);
    }

    /// `_result` returns Ok when the value sits in the active write buffer.
    #[test]
    fn read_value_locked_result_ok_from_write_buf() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 1u64.to_be_bytes();
        let payload = b"in-write-buffer-value";
        map.put(&key, payload).expect("put");

        let disk = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");
        let shard = &map.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        let v = map
            .read_value_locked_result(&disk, &inner)
            .expect("write-buf read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// `_result` returns Ok when the value is on an immutable file and the
    /// entry sits within a single 4 KiB block.
    #[test]
    fn read_value_locked_result_ok_from_disk_immutable() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 2u64.to_be_bytes();
        let payload = b"single-block-immutable";
        map.put(&key, payload).expect("put");
        // Each put is 280 bytes; with max_file_size=8192, need >30 puts to
        // cross the rotation boundary. Use keys 100..135 to avoid overwriting key 2.
        for i in 100u64..135 {
            map.put(&i.to_be_bytes(), &[i as u8; 256]).expect("rotator");
        }

        let disk = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");
        // `open_test_map` uses default CacheConfig (max_size = 0) — cache is
        // disabled, so step 2 returns None and the read exercises step 3 (disk).

        let shard = &map.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        assert_ne!(
            disk.file_id, inner.active.file_id,
            "test setup failed: key=2 entry is still in the active file's write buffer",
        );
        let v = map
            .read_value_locked_result(&disk, &inner)
            .expect("disk read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// `_result` propagates `StaleDiskLoc` from the disk read.
    #[test]
    fn read_value_locked_result_propagates_stale_disk_loc() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 3u64.to_be_bytes();
        let snap = put_until_compactable(&map, key);

        let shard = &map.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &map, 0.0).expect("compaction");

        let inner = shard.lock();
        match map.read_value_locked_result(&snap, &inner) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    /// Backward-compat: Option wrapper still returns None on StaleDiskLoc.
    /// No tracing assertion: the None is the load-bearing invariant.
    #[test]
    fn read_value_locked_returns_none_on_stale() {
        let dir = tempdir().unwrap();
        let map = open_test_map(dir.path());

        let key = 4u64.to_be_bytes();
        let snap = put_until_compactable(&map, key);

        let shard = &map.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &map, 0.0).expect("compaction");

        let inner = shard.lock();
        assert!(map.read_value_locked(&snap, &inner).is_none());
    }

    /// Pins the "size check sits before cache lookup" invariant for VarMap.
    /// Without the early `start + len > 8192` check, the cached path would
    /// hit `extract_from_block` and panic on `next[..second_len]`.
    #[test]
    fn large_value_with_first_block_cached_uses_fallback() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        // Enable the block cache so `cache.insert` actually takes effect
        // (default CacheConfig has max_size = 0, making the cache a no-op).
        cfg.cache.max_size = 1 << 20;
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), cfg).expect("open");

        let key = 42u64.to_be_bytes();
        let payload: Vec<u8> = (0..20_000u32).map(|i| i as u8).collect();
        map.put(&key, &payload).expect("put large");
        map.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let disk = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");
        let start = (disk.offset & 4095) as usize;
        assert!(
            start + disk.len as usize > 8192,
            "test precondition: large value must span >2 blocks",
        );

        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };
        map.cache
            .insert(cache_key, Arc::new(AlignedBuf::zeroed(4096)));
        assert!(
            map.cache.get(&cache_key).is_some(),
            "cache must be enabled for warm-cache scenario",
        );

        let v = map
            .read_value_cached_inner(&disk)
            .expect("large value must read via locked fallback");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    #[test]
    fn extract_from_block_single_block() {
        let mut block = AlignedBuf::zeroed(4096);
        for (i, byte) in block.iter_mut().enumerate() {
            *byte = i as u8;
        }
        let v = VarMap::<[u8; 8]>::extract_from_block(&block, 100, 50, || {
            panic!("next_block must not be called for single-block reads")
        })
        .expect("ok");
        let expected: Vec<u8> = (100u8..150u8).collect();
        assert_eq!(v.as_bytes(), expected.as_slice());
    }

    #[test]
    fn extract_from_block_two_blocks_exact() {
        let mut first = AlignedBuf::zeroed(4096);
        for byte in first.iter_mut() {
            *byte = 0xAA;
        }
        let mut second = AlignedBuf::zeroed(4096);
        for byte in second.iter_mut() {
            *byte = 0xBB;
        }
        let v = VarMap::<[u8; 8]>::extract_from_block(&first, 4095, 4097, || Ok(Arc::new(second)))
            .expect("ok");
        let bytes = v.as_bytes();
        assert_eq!(bytes.len(), 4097);
        assert_eq!(bytes[0], 0xAA);
        assert_eq!(bytes[1], 0xBB);
        assert_eq!(bytes[4096], 0xBB);
    }

    #[test]
    fn extract_from_block_two_blocks_partial() {
        let mut first = AlignedBuf::zeroed(4096);
        for byte in first.iter_mut() {
            *byte = 0x11;
        }
        let mut second = AlignedBuf::zeroed(4096);
        for byte in second.iter_mut() {
            *byte = 0x22;
        }
        let v = VarMap::<[u8; 8]>::extract_from_block(&first, 4000, 200, || Ok(Arc::new(second)))
            .expect("ok");
        let bytes = v.as_bytes();
        assert_eq!(bytes.len(), 200);
        assert!(bytes[..96].iter().all(|b| *b == 0x11));
        assert!(bytes[96..].iter().all(|b| *b == 0x22));
    }

    fn open_large_value_map(dir: &std::path::Path) -> VarMap<[u8; 8]> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        VarMap::open(dir, cfg).expect("open large-value test map")
    }

    fn build_large_payload(seed: u8) -> Vec<u8> {
        (0..50_000u32)
            .map(|i| (i as u8).wrapping_add(seed))
            .collect()
    }

    /// `open_large_value_map` uses default CacheConfig (max_size = 0), so
    /// the block cache is disabled and the read goes through the large-value
    /// locked fallback → disk read.
    #[test]
    fn large_value_read_via_locked_fallback() {
        let dir = tempdir().unwrap();
        let map = open_large_value_map(dir.path());

        let key = 100u64.to_be_bytes();
        let payload = build_large_payload(0);
        map.put(&key, &payload).expect("put large");
        map.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let v = map
            .get(&key)
            .expect("read must succeed via locked fallback");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn large_value_read_encrypted() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        cfg.encryption_key = Some([7u8; 32]);
        // Cache stays at default (max_size = 0, disabled), so the locked
        // fallback always routes through pread_value_encrypted.
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), cfg).expect("open enc");

        let key = 101u64.to_be_bytes();
        let payload = build_large_payload(0xAB);
        map.put(&key, &payload).expect("put encrypted large");
        map.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let v = map
            .get(&key)
            .expect("encrypted large read must succeed via pread_value_encrypted");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    #[test]
    fn large_value_stale_disk_loc_deterministic() {
        let dir = tempdir().unwrap();
        let map = open_large_value_map(dir.path());

        let key = 102u64.to_be_bytes();
        let payload = build_large_payload(0x42);
        map.put(&key, &payload).expect("first large put");

        let snap = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");

        // Rotate the active file so the large entry moves to an immutable file.
        map.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate after large put");

        // Overwrite many times to move the live pointer off the original file
        // (making it 100% dead so compaction erases it).
        for i in 1..20u8 {
            map.put(&key, &[i; 256]).expect("overwrite");
        }
        map.put(&key, b"live-after-compaction").expect("final put");

        let shard = &map.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &map, 0.0).expect("compaction");

        match map.read_value_cached_inner(&snap) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }

        let v = map
            .get(&key)
            .expect("public path must retry and return live value");
        assert_eq!(v.as_bytes(), b"live-after-compaction");
    }

    /// `_result` step 2: single-block cache fast path.
    #[test]
    fn read_value_locked_result_ok_from_cache_single_block() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        cfg.cache.max_size = 1 << 20;
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), cfg).expect("open");

        let key = 9u64.to_be_bytes();
        let payload = b"small-single-block-value";
        map.put(&key, payload).expect("put");
        // Need enough writes to push write_offset past max_file_size=8192.
        for i in 100u64..135 {
            map.put(&i.to_be_bytes(), &[i as u8; 256]).expect("rotator");
        }

        let disk = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");

        let start = (disk.offset & 4095) as usize;
        let len = disk.len as usize;
        assert!(
            start + len <= 4096,
            "test precondition: value must fit in a single block",
        );

        // Pre-warm the cache BEFORE acquiring the shard lock.
        // get_or_read_block → shard.read_block → sync::lock(&inner), so it
        // must not be called while the shard lock is already held.
        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };
        let block = map
            .get_or_read_block(disk.shard_id, disk.file_id, block_offset)
            .expect("read block");
        map.cache.insert(cache_key, block);
        assert!(
            map.cache.get(&cache_key).is_some(),
            "cache must contain the block for step 2 to fire",
        );

        let shard = &map.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        assert_ne!(
            disk.file_id, inner.active.file_id,
            "test setup failed: key entry is still in the active write buffer",
        );

        let v = map
            .read_value_locked_result(&disk, &inner)
            .expect("cache-hit read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// End-to-end roundtrip with file_id above u16::MAX.
    ///
    /// Uses write_buffer_size=128 KiB so a single 512-byte entry fits in one
    /// flush cycle; max_file_size=4096 forces per-entry rotation; cache
    /// enabled so the fast path is also exercised.  After bumping
    /// next_file_id to 70_000 and rotating, the active file gets an id that
    /// exceeds u16::MAX.  The entry is flushed + rotated to make it
    /// immutable, then `get` must return the correct bytes via the locked
    /// disk-read path.  Before the file_id u32 widening this would either
    /// panic or return wrong bytes because the high bits were truncated.
    #[test]
    fn var_map_get_with_file_id_above_u16() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        cfg.cache.max_size = 1 << 20;
        let map: VarMap<[u8; 8]> = VarMap::open(dir.path(), cfg).expect("open");

        let shard = &map.engine.shards()[0];

        // Bump file id well past u16::MAX and rotate so the next active file
        // carries the new id.
        shard.set_next_file_id(70_000);
        shard.rotate_active_for_test(8).expect("first rotate");
        assert!(
            shard.active_file_id() >= 70_000,
            "active_file_id should be >= 70_000 after rotation"
        );

        let key = 42u64.to_be_bytes();
        let value = vec![0xC3u8; 512];
        map.put(&key, &value).expect("put");

        // Confirm the DiskLoc has file_id > u16::MAX.
        {
            let disk = *sync::lock(&map.indexes[0]).get(&key).expect("indexed");
            assert!(
                disk.file_id > u16::MAX as u32,
                "DiskLoc.file_id must be above u16::MAX, got {}",
                disk.file_id,
            );
        }

        // Flush the write buffer and rotate so the entry lands on an
        // immutable file — reads will go through Shard::read_block.
        shard.flush().expect("flush");
        shard.rotate_active_for_test(8).expect("second rotate");

        let got = map.get(&key).expect("get must return Some");
        assert_eq!(got.as_bytes(), value.as_slice());
    }
}