armdb 0.11.2

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
//! Upsert semantics across Db-openable collection families.
//!
//! Keep observables by backend:
//! - **Bitcask (Zero/Typed/VarTyped)**: hook count unchanged, value unchanged, `len()` unchanged.
//! - **FixedStore (Zero)**: value equality after Keep (no hook on Fixed).
//! - **LSM**: hook fires synchronously under the held stripe lock (before `atomic` returns).

#![cfg(all(feature = "typed-tree", feature = "rapira-codec"))]

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use armdb::codec::Codec;
use armdb::{
    Config, DbError, FixedConfig, RapiraCodec, TypedMap, TypedTree, TypedWriteHook, Upsert,
    ZeroMap, ZeroTree,
};
use rapira::Rapira;
use tempfile::tempdir;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

#[cfg(feature = "var-collections")]
use armdb::{VarTypedMap, VarTypedTree};

#[cfg(feature = "fjall")]
use armdb::lsm::{LsmConfig, LsmTree};

#[derive(
    FromBytes, IntoBytes, Immutable, KnownLayout, Clone, Copy, Debug, PartialEq, Eq, Rapira,
)]
#[repr(C)]
struct Counter {
    n: u64,
}

#[derive(Default, Clone)]
struct CountHook {
    writes: Arc<AtomicUsize>,
    /// `(old, new)` per fired hook, in the order the engine replayed them.
    log: Arc<Mutex<Vec<(Option<u64>, Option<u64>)>>>,
}

impl TypedWriteHook<[u8; 8], Counter> for CountHook {
    const NEEDS_WRITE: bool = true;
    fn on_write(&self, _k: &[u8; 8], old: Option<&Counter>, new: Option<&Counter>) {
        self.writes.fetch_add(1, Ordering::Relaxed);
        self.log
            .lock()
            .expect("hook log")
            .push((old.map(|c| c.n), new.map(|c| c.n)));
    }
}

struct U64Codec;

impl Codec<u64> for U64Codec {
    fn encode_to(&self, value: &u64, buf: &mut Vec<u8>) -> armdb::DbResult<()> {
        buf.clear();
        buf.extend_from_slice(&value.to_be_bytes());
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> armdb::DbResult<u64> {
        let arr: [u8; 8] = bytes
            .try_into()
            .map_err(|_| DbError::CorruptedEntry { offset: 0 })?;
        Ok(u64::from_be_bytes(arr))
    }
}

impl CountHook {
    fn new() -> Self {
        Self {
            writes: Arc::new(AtomicUsize::new(0)),
            log: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn count(&self) -> usize {
        self.writes.load(Ordering::Relaxed)
    }

    fn log(&self) -> Vec<(Option<u64>, Option<u64>)> {
        self.log.lock().expect("hook log").clone()
    }
}

fn key(n: u64) -> [u8; 8] {
    n.to_be_bytes()
}

/// Five-cell semantics table for Bitcask collections with a counting hook.
fn assert_bitcask_counter_semantics(
    coll: &impl BitcaskCounterHarness,
    hook: &CountHook,
    k: &[u8; 8],
) {
    // absent + Put
    coll.upsert(k, |_| Upsert::Put(Counter { n: 1 })).unwrap();
    assert_eq!(coll.get(k).unwrap().n, 1);
    assert_eq!(hook.count(), 1);

    // present + Put
    coll.upsert(k, |c| {
        Upsert::Put(Counter {
            n: c.unwrap().n + 1,
        })
    })
    .unwrap();
    assert_eq!(coll.get(k).unwrap().n, 2);
    assert_eq!(hook.count(), 2);

    // Keep — hook silence + value unchanged + len unchanged
    let len_before = coll.len();
    let writes_before = hook.count();
    coll.upsert(k, |_| Upsert::Keep).unwrap();
    assert_eq!(coll.get(k).unwrap().n, 2);
    assert_eq!(hook.count(), writes_before);
    assert_eq!(coll.len(), len_before);

    // present + Delete
    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert!(coll.get(k).is_none());
    assert_eq!(hook.count(), writes_before + 1);

    // absent + Delete — no-op, no hook
    let w = hook.count();
    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert_eq!(hook.count(), w);
}

trait BitcaskCounterHarness {
    fn get(&self, k: &[u8; 8]) -> Option<Counter>;
    fn len(&self) -> usize;
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Counter>) -> Upsert<Counter>,
    ) -> armdb::DbResult<()>;
}

impl<H: TypedWriteHook<[u8; 8], Counter>, D: armdb::durability::Durability> BitcaskCounterHarness
    for ZeroTree<[u8; 8], 8, Counter, H, D>
{
    fn get(&self, k: &[u8; 8]) -> Option<Counter> {
        ZeroTree::get(self, k)
    }
    fn len(&self) -> usize {
        ZeroTree::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Counter>) -> Upsert<Counter>,
    ) -> armdb::DbResult<()> {
        ZeroTree::upsert(self, k, f)
    }
}

// `ZeroMap` is gated on `typed-tree` (see `lib.rs`), which the file-level
// `#![cfg]` already requires — no extra feature gate here.
impl<H: TypedWriteHook<[u8; 8], Counter>, D: armdb::durability::Durability> BitcaskCounterHarness
    for ZeroMap<[u8; 8], 8, Counter, H, D>
{
    fn get(&self, k: &[u8; 8]) -> Option<Counter> {
        ZeroMap::get(self, k)
    }
    fn len(&self) -> usize {
        ZeroMap::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Counter>) -> Upsert<Counter>,
    ) -> armdb::DbResult<()> {
        ZeroMap::upsert(self, k, f)
    }
}

/// Five-cell semantics table for Typed* collections using u64 + U64Codec.
fn assert_bitcask_u64_semantics(coll: &impl BitcaskU64Harness, hook: &CountHookU64, k: &[u8; 8]) {
    coll.upsert(k, |_| Upsert::Put(1)).unwrap();
    assert_eq!(coll.get(k), Some(1));
    assert_eq!(hook.count(), 1);

    coll.upsert(k, |c| Upsert::Put(c.unwrap() + 1)).unwrap();
    assert_eq!(coll.get(k), Some(2));
    assert_eq!(hook.count(), 2);

    let len_before = coll.len();
    let writes_before = hook.count();
    coll.upsert(k, |_| Upsert::Keep).unwrap();
    assert_eq!(coll.get(k), Some(2));
    assert_eq!(hook.count(), writes_before);
    assert_eq!(coll.len(), len_before);

    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert!(coll.get(k).is_none());
    assert_eq!(hook.count(), writes_before + 1);

    let w = hook.count();
    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert_eq!(hook.count(), w);
}

#[derive(Default, Clone)]
struct CountHookU64 {
    writes: Arc<AtomicUsize>,
}

impl TypedWriteHook<[u8; 8], u64> for CountHookU64 {
    const NEEDS_WRITE: bool = true;
    fn on_write(&self, _k: &[u8; 8], _old: Option<&u64>, _new: Option<&u64>) {
        self.writes.fetch_add(1, Ordering::Relaxed);
    }
}

impl CountHookU64 {
    fn new() -> Self {
        Self {
            writes: Arc::new(AtomicUsize::new(0)),
        }
    }
    fn count(&self) -> usize {
        self.writes.load(Ordering::Relaxed)
    }
}

trait BitcaskU64Harness {
    fn get(&self, k: &[u8; 8]) -> Option<u64>;
    fn len(&self) -> usize;
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&u64>) -> Upsert<u64>,
    ) -> armdb::DbResult<()>;
}

impl<H: TypedWriteHook<[u8; 8], u64>> BitcaskU64Harness for TypedTree<[u8; 8], u64, U64Codec, H> {
    fn get(&self, k: &[u8; 8]) -> Option<u64> {
        TypedTree::get(self, k).map(|r| *r)
    }
    fn len(&self) -> usize {
        TypedTree::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&u64>) -> Upsert<u64>,
    ) -> armdb::DbResult<()> {
        TypedTree::upsert(self, k, f)
    }
}

impl<H: TypedWriteHook<[u8; 8], u64>> BitcaskU64Harness for TypedMap<[u8; 8], u64, U64Codec, H> {
    fn get(&self, k: &[u8; 8]) -> Option<u64> {
        TypedMap::get(self, k).map(|r| *r)
    }
    fn len(&self) -> usize {
        TypedMap::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&u64>) -> Upsert<u64>,
    ) -> armdb::DbResult<()> {
        TypedMap::upsert(self, k, f)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Rapira)]
struct Item {
    n: u64,
}

#[cfg(feature = "var-collections")]
trait BitcaskItemHarness {
    fn get(&self, k: &[u8; 8]) -> Option<Item>;
    fn len(&self) -> usize;
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Item>) -> Upsert<Item>,
    ) -> armdb::DbResult<()>;
}

#[derive(Default, Clone)]
struct CountHookItem {
    writes: Arc<AtomicUsize>,
}

#[cfg(feature = "var-collections")]
impl TypedWriteHook<[u8; 8], Item> for CountHookItem {
    const NEEDS_WRITE: bool = true;
    fn on_write(&self, _k: &[u8; 8], _old: Option<&Item>, _new: Option<&Item>) {
        self.writes.fetch_add(1, Ordering::Relaxed);
    }
}

#[cfg(feature = "var-collections")]
impl CountHookItem {
    fn new() -> Self {
        Self {
            writes: Arc::new(AtomicUsize::new(0)),
        }
    }
    fn count(&self) -> usize {
        self.writes.load(Ordering::Relaxed)
    }
}

#[cfg(feature = "var-collections")]
impl<H: TypedWriteHook<[u8; 8], Item>> BitcaskItemHarness
    for VarTypedMap<[u8; 8], Item, RapiraCodec, H>
{
    fn get(&self, k: &[u8; 8]) -> Option<Item> {
        VarTypedMap::get(self, k)
    }
    fn len(&self) -> usize {
        VarTypedMap::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Item>) -> Upsert<Item>,
    ) -> armdb::DbResult<()> {
        VarTypedMap::upsert(self, k, f)
    }
}

#[cfg(feature = "var-collections")]
impl<H: TypedWriteHook<[u8; 8], Item>> BitcaskItemHarness
    for VarTypedTree<[u8; 8], Item, RapiraCodec, H>
{
    fn get(&self, k: &[u8; 8]) -> Option<Item> {
        VarTypedTree::get(self, k)
    }
    fn len(&self) -> usize {
        VarTypedTree::len(self)
    }
    fn upsert(
        &self,
        k: &[u8; 8],
        f: impl FnOnce(Option<&Item>) -> Upsert<Item>,
    ) -> armdb::DbResult<()> {
        VarTypedTree::upsert(self, k, f)
    }
}

#[cfg(feature = "var-collections")]
fn assert_bitcask_item_semantics(
    coll: &impl BitcaskItemHarness,
    hook: &CountHookItem,
    k: &[u8; 8],
) {
    coll.upsert(k, |_| Upsert::Put(Item { n: 1 })).unwrap();
    assert_eq!(coll.get(k).unwrap().n, 1);
    assert_eq!(hook.count(), 1);

    coll.upsert(k, |c| {
        Upsert::Put(Item {
            n: c.unwrap().n + 1,
        })
    })
    .unwrap();
    assert_eq!(coll.get(k).unwrap().n, 2);
    assert_eq!(hook.count(), 2);

    let len_before = coll.len();
    let writes_before = hook.count();
    coll.upsert(k, |_| Upsert::Keep).unwrap();
    assert_eq!(coll.get(k).unwrap().n, 2);
    assert_eq!(hook.count(), writes_before);
    assert_eq!(coll.len(), len_before);

    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert!(coll.get(k).is_none());
    assert_eq!(hook.count(), writes_before + 1);

    let w = hook.count();
    coll.upsert(k, |_| Upsert::Delete).unwrap();
    assert_eq!(hook.count(), w);
}

#[test]
fn zero_tree_bitcask_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHook::new();
    let tree =
        ZeroTree::<[u8; 8], 8, Counter, _>::open_hooked(dir.path(), Config::test(), hook.clone())
            .unwrap();
    assert_bitcask_counter_semantics(&tree, &hook, &key(1));
}

#[test]
fn zero_tree_fixed_keep_leaves_value() {
    let dir = tempdir().unwrap();
    let hook = CountHook::new();
    let tree =
        ZeroTree::<[u8; 8], 8, Counter, CountHook, armdb::durability::Fixed>::open_with_hook(
            dir.path(),
            FixedConfig::test(),
            hook.clone(),
        )
        .unwrap();
    let k = key(3);
    tree.upsert(&k, |_| Upsert::Put(Counter { n: 4 })).unwrap();
    let before = tree.get(&k).unwrap();
    assert_eq!(hook.count(), 1);

    // On FixedStore an in-place rewrite of the identical value is invisible to a
    // value comparison — it would still bump the slot version and emit a
    // replication event. The hook is the observable that catches it: `Keep` must
    // perform no write at all.
    tree.upsert(&k, |_| Upsert::Keep).unwrap();
    assert_eq!(tree.get(&k).unwrap(), before);
    assert_eq!(hook.count(), 1, "Keep must not write the slot");
    assert_eq!(hook.log(), vec![(None, Some(4))]);
}

#[test]
fn zero_map_bitcask_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHook::new();
    let map =
        ZeroMap::<[u8; 8], 8, Counter, _>::open_hooked(dir.path(), Config::test(), hook.clone())
            .unwrap();
    assert_bitcask_counter_semantics(&map, &hook, &key(1));
}

#[test]
fn zero_map_fixed_keep_leaves_value() {
    let dir = tempdir().unwrap();
    let hook = CountHook::new();
    let map = ZeroMap::<[u8; 8], 8, Counter, CountHook, armdb::durability::Fixed>::open_with_hook(
        dir.path(),
        FixedConfig::test(),
        hook.clone(),
    )
    .unwrap();
    let k = key(5);
    map.upsert(&k, |_| Upsert::Put(Counter { n: 7 })).unwrap();
    let before = map.get(&k).unwrap();
    assert_eq!(hook.count(), 1);

    // Same FixedStore observable as the Tree case — see the comment there.
    map.upsert(&k, |_| Upsert::Keep).unwrap();
    assert_eq!(map.get(&k).unwrap(), before);
    assert_eq!(hook.count(), 1, "Keep must not write the slot");
    assert_eq!(hook.log(), vec![(None, Some(7))]);
}

#[test]
fn typed_tree_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHookU64::new();
    let tree = TypedTree::<[u8; 8], u64, U64Codec, _>::open_hooked(
        dir.path(),
        Config::test(),
        U64Codec,
        hook.clone(),
    )
    .unwrap();
    assert_bitcask_u64_semantics(&tree, &hook, &key(1));
}

#[test]
fn typed_map_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHookU64::new();
    let map = TypedMap::<[u8; 8], u64, U64Codec, _>::open_hooked(
        dir.path(),
        Config::test(),
        U64Codec,
        hook.clone(),
    )
    .unwrap();
    assert_bitcask_u64_semantics(&map, &hook, &key(1));
}

#[cfg(feature = "var-collections")]
#[test]
fn var_typed_map_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHookItem::new();
    let map = VarTypedMap::<[u8; 8], Item, RapiraCodec, _>::open_hooked(
        dir.path(),
        Config::test(),
        RapiraCodec,
        hook.clone(),
    )
    .unwrap();
    assert_bitcask_item_semantics(&map, &hook, &key(1));
}

#[cfg(feature = "var-collections")]
#[test]
fn var_typed_tree_semantics_table() {
    let dir = tempdir().unwrap();
    let hook = CountHookItem::new();
    let tree = VarTypedTree::<[u8; 8], Item, RapiraCodec, _>::open_hooked(
        dir.path(),
        Config::test(),
        RapiraCodec,
        hook.clone(),
    )
    .unwrap();
    assert_bitcask_item_semantics(&tree, &hook, &key(1));
}

#[test]
fn shard_mismatch_on_foreign_key() {
    let dir = tempdir().unwrap();
    let mut cfg = Config::test();
    cfg.shard_count = 2;
    let tree = ZeroTree::<[u8; 8], 8, Counter>::open(dir.path(), cfg).unwrap();
    let k0 = key(0);
    let foreign = (0u64..10_000)
        .map(key)
        .find(|k| tree.shard_for(k) != tree.shard_for(&k0))
        .expect("foreign key");
    let err = tree
        .atomic(&k0, |s| s.upsert(&foreign, |_| Upsert::Keep))
        .unwrap_err();
    assert!(matches!(err, DbError::ShardMismatch));
}

#[test]
fn family_ctx_hook_order_inside_atomic() {
    let dir = tempdir().unwrap();
    let hook = CountHook::new();
    let tree =
        ZeroTree::<[u8; 8], 8, Counter, _>::open_hooked(dir.path(), Config::test(), hook.clone())
            .unwrap();
    let k = key(42);
    tree.atomic(&k, |s| {
        s.upsert(&k, |_| Upsert::Put(Counter { n: 1 }))?;
        assert_eq!(
            hook.count(),
            0,
            "hooks must be buffered, never fired under the held shard lock"
        );
        s.put(&k, &Counter { n: 2 })?;
        s.upsert(&k, |_| Upsert::Keep)?;
        s.upsert(&k, |_| Upsert::Delete)?;
        assert_eq!(
            hook.count(),
            0,
            "still buffered at the end of the atomic block"
        );
        Ok(())
    })
    .unwrap();
    // Replayed after unlock, interleaved with `put` in application order.
    // `Keep` wrote nothing, so it contributes no entry.
    assert_eq!(
        hook.log(),
        vec![
            (None, Some(1)),    // upsert Put — insert
            (Some(1), Some(2)), // put — overwrite
            (Some(2), None),    // upsert Delete
        ]
    );
    assert_eq!(hook.count(), 3);
    assert!(tree.get(&k).is_none());
}

#[cfg(feature = "fjall")]
mod lsm {
    use super::*;
    use armdb::CollectionMeta;
    use armour_core::{GetRefs, GetType};

    #[derive(Clone, Debug, PartialEq, Eq, Rapira, GetType, GetRefs)]
    struct LsmItem {
        n: u64,
    }

    impl CollectionMeta for LsmItem {
        type SelfId = [u8; 8];
        const NAME: &'static str = "upsert_lsm_item";
        const VERSION: u16 = 1;
    }

    #[derive(Default, Clone)]
    struct LsmCountHook {
        writes: Arc<AtomicUsize>,
    }

    impl TypedWriteHook<[u8; 8], LsmItem> for LsmCountHook {
        const NEEDS_WRITE: bool = true;
        fn on_write(&self, _k: &[u8; 8], _old: Option<&LsmItem>, _new: Option<&LsmItem>) {
            self.writes.fetch_add(1, Ordering::Relaxed);
        }
    }

    impl LsmCountHook {
        fn new() -> Self {
            Self {
                writes: Arc::new(AtomicUsize::new(0)),
            }
        }
        fn count(&self) -> usize {
            self.writes.load(Ordering::Relaxed)
        }
    }

    #[test]
    fn lsm_semantics_table() {
        let dir = tempdir().unwrap();
        let db = fjall::Database::builder(dir.path()).open().unwrap();
        let hook = LsmCountHook::new();
        let tree = LsmTree::<[u8; 8], LsmItem, RapiraCodec, _>::open(
            db,
            LsmConfig {
                lock_stripes: 1,
                ..LsmConfig::default()
            },
            RapiraCodec,
            hook.clone(),
        )
        .unwrap();
        let k = key(1);

        tree.upsert(&k, |_| Upsert::Put(LsmItem { n: 1 })).unwrap();
        assert_eq!(tree.get(&k).unwrap().n, 1);
        assert_eq!(hook.count(), 1);

        tree.upsert(&k, |c| {
            Upsert::Put(LsmItem {
                n: c.unwrap().n + 1,
            })
        })
        .unwrap();
        assert_eq!(tree.get(&k).unwrap().n, 2);
        assert_eq!(hook.count(), 2);

        let len_before = tree.len();
        let writes_before = hook.count();
        tree.upsert(&k, |_| Upsert::Keep).unwrap();
        assert_eq!(tree.get(&k).unwrap().n, 2);
        assert_eq!(hook.count(), writes_before);
        assert_eq!(tree.len(), len_before);

        tree.upsert(&k, |_| Upsert::Delete).unwrap();
        assert!(tree.get(&k).is_none());
        assert_eq!(hook.count(), writes_before + 1);

        let w = hook.count();
        tree.upsert(&k, |_| Upsert::Delete).unwrap();
        assert_eq!(hook.count(), w);
    }

    #[test]
    fn lsm_hook_fires_synchronously_under_stripe() {
        let dir = tempdir().unwrap();
        let db = fjall::Database::builder(dir.path()).open().unwrap();
        let hook = LsmCountHook::new();
        let tree = LsmTree::<[u8; 8], LsmItem, RapiraCodec, _>::open(
            db,
            LsmConfig {
                lock_stripes: 1,
                ..LsmConfig::default()
            },
            RapiraCodec,
            hook.clone(),
        )
        .unwrap();
        let k = key(9);

        tree.atomic(&k, |s| {
            assert_eq!(hook.count(), 0);
            s.upsert(&k, |_| Upsert::Put(LsmItem { n: 1 }))?;
            assert_eq!(hook.count(), 1, "hook must fire before atomic returns");
            Ok(())
        })
        .unwrap();
        assert_eq!(hook.count(), 1);
    }

    #[test]
    fn lsm_upsert_keep_rejects_foreign_stripe() {
        let dir = tempdir().unwrap();
        let db = fjall::Database::builder(dir.path()).open().unwrap();
        let tree = LsmTree::<[u8; 8], LsmItem, RapiraCodec>::open(
            db,
            LsmConfig {
                lock_stripes: 4,
                ..LsmConfig::default()
            },
            RapiraCodec,
            armdb::NoHook,
        )
        .unwrap();
        let k0 = key(0);
        let foreign = (0u64..10_000)
            .map(key)
            .find(|k| tree.shard_for(k) != tree.shard_for(&k0))
            .expect("foreign key");
        let err = tree
            .atomic(&k0, |s| s.upsert(&foreign, |_| Upsert::Keep))
            .unwrap_err();
        assert!(
            matches!(err, armdb::DbError::ShardMismatch),
            "Keep on a foreign stripe must ShardMismatch, got {err:?}"
        );
    }
}