armdb 0.15.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
//! What a restart finds, and what it makes of it.

use std::sync::Arc;

use super::config::SegConfig;
use super::core::SegCore;
use super::manifest::load;
use super::seal::{sdat_name, sidx_name};
use super::testkit::{CoreShape, TestKey, copy_collection, fill_core as fill, key_of, value};
use crate::error::DbError;

fn wide(shard_count: usize) -> SegConfig {
    SegConfig {
        seal_max_keys: 1_000_000,
        max_frozen_generations: 8,
        shard_count,
        ..SegConfig::test()
    }
}

fn assert_holds(core: &SegCore<TestKey>, keys: std::ops::Range<u64>) {
    assert!(core.verify_all().unwrap().is_clean());
    for i in keys {
        assert_eq!(core.get(&key_of(i)).unwrap(), Some(value(i)), "key {i}");
    }
}

/// Reopen a flushed copy while the original core still holds its directory lease.
/// This exercises restart recovery, not process kills or power-loss durability.
fn restart(
    core: &SegCore<TestKey>,
    config: SegConfig,
    shape: CoreShape,
) -> (tempfile::TempDir, Arc<SegCore<TestKey>>) {
    core.durable_flush().unwrap();
    let dir = tempfile::tempdir().unwrap();
    copy_collection(&core.dir, dir.path());
    let reopened = shape.open_core(dir.path(), config);
    (dir, reopened)
}

fn a_freeze_without_its_seal_survives_a_restart(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..100);
    core.seal().unwrap();
    fill(&core, 100..150);

    let (_copy, reopened) = restart(&core, wide(2), shape);
    let view = reopened.view();
    assert_eq!(view.frozen.len(), 1);
    assert!(view.frozen[0].is_frozen());
    assert_eq!(view.frozen[0].keys(), 100);
    assert_eq!(view.active.keys(), 50);
    assert_holds(&reopened, 0..150);

    // The seal that the crash interrupted is done after the restart.
    assert!(reopened.seal_oldest().unwrap());
    assert_eq!(reopened.view().sealed.len(), 1);
    assert_holds(&reopened, 0..150);

    // New writes continue the GSN sequence.
    fill(&reopened, 150..160);
    reopened.seal().unwrap();
    let manifest = load(&reopened.dir).unwrap().unwrap();
    manifest.check().unwrap();
    assert_eq!(manifest.segments[0].max_gsn, 100);
    assert_eq!(manifest.generations[0].min_gsn, 101);
    assert_eq!(manifest.generations[0].max_gsn, 160);
}

fn a_crashed_seal_is_started_over(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..100);
    core.seal().unwrap();
    core.durable_flush().unwrap();

    // The crash hit while the seal was writing: one file has its final
    // name, the other is still temporary.
    let copy = tempfile::tempdir().unwrap();
    copy_collection(dir.path(), copy.path());
    let manifest = load(copy.path()).unwrap().unwrap();
    let (reserved, burned_id) = manifest.reserve_segment_id().unwrap();
    super::manifest::publish(&*super::fs::real(), copy.path(), &reserved).unwrap();
    let seg = copy.path().join("seg");
    std::fs::write(seg.join(sdat_name(burned_id, 1)), b"half a segment").unwrap();
    std::fs::write(
        seg.join(format!("{}.tmp", sidx_name(burned_id, 1))),
        b"torn",
    )
    .unwrap();

    let reopened = shape.open_core(copy.path(), wide(2));
    assert_eq!(
        std::fs::read_dir(&seg).unwrap().count(),
        0,
        "the leftovers are gone"
    );
    assert_eq!(reopened.view().frozen.len(), 1);
    assert_eq!(
        load(copy.path()).unwrap().unwrap().next_segment_id,
        burned_id + 1
    );

    assert!(reopened.seal_oldest().unwrap());
    assert_eq!(reopened.view().sealed.len(), 1);
    assert_eq!(reopened.view().sealed[0].id(), burned_id + 1);
    assert_holds(&reopened, 0..100);
    assert!(reopened.verify_all().unwrap().is_clean());
}

fn a_frozen_generation_that_lost_its_whole_tail_is_retired(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..100);
    core.seal().unwrap();
    assert!(core.seal_oldest().unwrap());
    // These writes stay in the write buffer: a freeze does not flush.
    fill(&core, 100..110);
    core.seal().unwrap();

    // The crash hit before the seal made the frozen generation durable.
    let copy = tempfile::tempdir().unwrap();
    copy_collection(dir.path(), copy.path());
    let reopened = shape.open_core(copy.path(), wide(2));
    assert_eq!(reopened.view().frozen.len(), 1);
    assert_eq!(reopened.view().frozen[0].keys(), 0, "the tail was lost");
    assert_eq!(reopened.view().sealed.len(), 1);

    // The empty generation leaves without a segment instead of blocking
    // every later seal.
    assert!(reopened.seal_oldest().unwrap());
    assert!(reopened.view().frozen.is_empty());
    assert_eq!(reopened.view().sealed.len(), 1);
    assert!(!copy.path().join("gen/0000000000000002").exists());
    assert_holds(&reopened, 0..100);
    assert_eq!(reopened.get(&key_of(105)).unwrap(), None);

    fill(&reopened, 200..210);
    reopened.seal().unwrap();
    assert!(reopened.seal_oldest().unwrap());
    assert_eq!(reopened.view().sealed.len(), 2);
    assert_holds(&reopened, 200..210);
    load(copy.path()).unwrap().unwrap().check().unwrap();
    assert!(reopened.verify_all().unwrap().is_clean());
}

fn a_frozen_journal_past_its_recorded_last_gsn_is_refused(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    shape.build_collection(dir.path());
    // The frozen generation holds GSNs 201..=350; name it as ending at 300.
    let mut manifest = load(dir.path()).unwrap().unwrap();
    manifest.generations[0].max_gsn = 300;
    manifest.check().unwrap();
    super::manifest::publish(&*super::fs::real(), dir.path(), &manifest).unwrap();

    let err = shape
        .try_open_core(
            dir.path(),
            SegConfig::test(),
            super::fs::real(),
            &super::testkit::TestClock::new(1),
        )
        .map(drop)
        .unwrap_err();
    match err {
        DbError::GenerationMissing { gen_id, reason, .. } => {
            assert_eq!(gen_id, 1);
            assert!(reason.contains("GSN 350"), "{reason}");
        }
        other => panic!("{other:?}"),
    }
}

fn a_generation_that_outlived_its_seal_is_removed(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..100);
    core.seal().unwrap();
    // A reader keeps the generation's directory on disk across the seal.
    let held = core.view();
    core.seal_oldest().unwrap();
    assert!(dir.path().join("gen/0000000000000001").exists());

    let (copy, reopened) = restart(&core, wide(2), shape);
    drop(held);
    assert!(!copy.path().join("gen/0000000000000001").exists());
    assert!(reopened.view().frozen.is_empty());
    assert_eq!(reopened.view().sealed.len(), 1);
    assert_holds(&reopened, 0..100);
}

fn files_of_a_dropped_segment_are_removed(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..50);
    core.seal().unwrap();
    core.seal_oldest().unwrap();
    fill(&core, 50..100);
    core.seal().unwrap();
    core.seal_oldest().unwrap();

    let held = core.view();
    assert_eq!(core.drop_segments_before(u64::MAX).unwrap(), 2);
    assert!(dir.path().join("seg").join(sdat_name(1, 1)).exists());

    let (copy, reopened) = restart(&core, wide(2), shape);
    drop(held);
    assert_eq!(
        std::fs::read_dir(copy.path().join("seg")).unwrap().count(),
        0
    );
    assert!(reopened.view().sealed.is_empty());
    assert_eq!(reopened.get(&key_of(10)).unwrap(), None);
}

fn the_shard_count_changes_across_restarts(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(4));
    fill(&core, 0..100);
    core.seal().unwrap();
    core.seal_oldest().unwrap();
    fill(&core, 100..200);
    core.seal().unwrap();
    fill(&core, 200..300);
    core.clean_shutdown().unwrap();
    drop(core);

    // 4 → 16: existing generations keep 4, the next one gets 16.
    let core = shape.open_core(dir.path(), wide(16));
    assert_eq!(core.view().active.shard_count(), 4);
    assert_eq!(core.view().frozen[0].shard_count(), 4);
    assert_holds(&core, 0..300);
    fill(&core, 300..400);
    core.seal().unwrap();
    assert_eq!(core.view().active.shard_count(), 16);
    fill(&core, 400..500);
    core.clean_shutdown().unwrap();
    drop(core);

    // 16 → 2.
    let core = shape.open_core(dir.path(), wide(2));
    let counts: Vec<usize> = std::iter::once(&core.view().active)
        .chain(core.view().frozen.iter())
        .map(|g| g.shard_count())
        .collect();
    assert_eq!(counts, [16, 4, 4]);
    assert_holds(&core, 0..500);

    assert!(matches!(
        core.insert(&key_of(250), b"x"),
        Err(DbError::KeyExists)
    ));
    core.insert(&key_of(900), b"new").unwrap();
    core.delete(&key_of(50)).unwrap();
    assert_eq!(core.get(&key_of(50)).unwrap(), None);
    assert_eq!(core.count_exact().unwrap(), 500);

    while core.seal_oldest().unwrap() {}
    core.seal().unwrap();
    core.seal_oldest().unwrap();
    assert_eq!(core.view().active.shard_count(), 2);
    assert_holds(&core, 0..50);
    assert_holds(&core, 51..500);
    assert_eq!(core.get(&key_of(50)).unwrap(), None);
    assert_eq!(core.get(&key_of(900)).unwrap(), Some(b"new".to_vec()));
    assert_eq!(core.count_exact().unwrap(), 500);

    // The full scan agrees with the point reads, row by row.
    let mut scanned = std::collections::BTreeMap::new();
    core.scan(&mut |row| {
        let (key, value) = row.unwrap();
        assert!(scanned.insert(key, value).is_none(), "a key came twice");
        std::ops::ControlFlow::Continue(())
    });
    let mut expected: std::collections::BTreeMap<TestKey, Vec<u8>> = (0..500)
        .filter(|&i| i != 50)
        .map(|i| (key_of(i), value(i)))
        .collect();
    expected.insert(key_of(900), b"new".to_vec());
    assert_eq!(scanned, expected);
    assert!(core.verify_all().unwrap().is_clean());
}

fn a_restart_changes_no_answer(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..200);
    for i in (0..200).step_by(7) {
        core.delete(&key_of(i)).unwrap();
    }
    core.seal().unwrap();
    core.seal_oldest().unwrap();
    for i in (0..200).step_by(5) {
        core.put(&key_of(i), b"again").unwrap();
    }
    core.seal().unwrap();
    for i in (0..200).step_by(11) {
        core.delete(&key_of(i)).unwrap();
    }

    let before: Vec<Option<Vec<u8>>> = (0..220).map(|i| core.get(&key_of(i)).unwrap()).collect();
    let (_copy, reopened) = restart(&core, wide(2), shape);
    let after: Vec<Option<Vec<u8>>> = (0..220)
        .map(|i| reopened.get(&key_of(i)).unwrap())
        .collect();
    assert_eq!(before, after);
    assert_eq!(core.count_exact().unwrap(), reopened.count_exact().unwrap());
}

fn recovered_saturated_queue_refuses_every_mutation_across_reopens(shape: CoreShape) {
    for by_bytes in [false, true] {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: if by_bytes { 1_000_000 } else { 2 },
            seal_max_bytes: if by_bytes {
                2 * crate::entry::entry_size(32, 2)
            } else {
                u64::MAX
            },
            max_frozen_generations: 1,
            seal_wait_timeout: std::time::Duration::ZERO,
            ..SegConfig::test()
        };
        let core = shape.open_core(dir.path(), config.clone());
        fill(&core, 0..4);
        assert_eq!(core.view().frozen.len(), 1);
        assert!(core.view().active.is_full());
        core.clean_shutdown().unwrap();
        drop(core);
        let mut baseline = None;
        for _ in 0..3 {
            let core = shape.open_core(dir.path(), config.clone());
            let active = core.view().active.clone();
            let before = (active.keys(), active.bytes(), active.next_gsn());
            assert_eq!(*baseline.get_or_insert(before), before);
            let locations = active.snapshot_range(0, u64::MAX, core.seed);
            for result in [
                core.put(&key_of(9), b"new"),
                core.put(&key_of(2), b"overwrite"),
                core.insert(&key_of(10), b"new"),
                core.delete(&key_of(2)),
            ] {
                assert!(
                    matches!(result, Err(DbError::SealBackpressure { .. })),
                    "{result:?}"
                );
            }
            assert_eq!((active.keys(), active.bytes(), active.next_gsn()), before);
            assert_eq!(active.snapshot_range(0, u64::MAX, core.seed), locations);
            assert_eq!(core.get(&key_of(9)).unwrap(), None);
            assert_eq!(core.get(&key_of(10)).unwrap(), None);
            assert_holds(&core, 0..4);
            core.clean_shutdown().unwrap();
        }
    }
}

fn recovered_lowered_limits_freeze_before_write_or_tick(shape: CoreShape) {
    for by_bytes in [false, true] {
        for by_tick in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let core = shape.open_core(dir.path(), wide(2));
            fill(&core, 0..3);
            core.clean_shutdown().unwrap();
            let bytes = core.view().active.bytes();
            drop(core);
            let config = SegConfig {
                seal_max_keys: if by_bytes { 1_000_000 } else { 3 },
                seal_max_bytes: if by_bytes { bytes } else { u64::MAX },
                ..wide(2)
            };
            let core = shape.open_core(dir.path(), config);
            let recovered = core.view().active.clone();
            assert!(
                recovered.is_full(),
                "keys/bytes limits must apply before exposure"
            );
            let before = (recovered.keys(), recovered.bytes(), recovered.next_gsn());
            if by_tick {
                core.tick().unwrap();
                assert_ne!(
                    core.view().active.id(),
                    recovered.id(),
                    "tick must freeze before any write"
                );
            }
            core.put(&key_of(9), b"new").unwrap();
            assert_ne!(core.view().active.id(), recovered.id());
            assert!(recovered.is_frozen());
            assert_eq!(
                (recovered.keys(), recovered.bytes(), recovered.next_gsn()),
                before
            );
            assert_eq!(core.get(&key_of(9)).unwrap(), Some(b"new".to_vec()));
            assert_holds(&core, 0..3);
        }
    }
}

fn unrepresentable_configured_seal_wait_is_rejected(shape: CoreShape) {
    let bad = SegConfig {
        seal_wait_timeout: std::time::Duration::MAX,
        ..SegConfig::test()
    };
    assert!(matches!(bad.validate(), Err(DbError::Config(_))));
    let dir = tempfile::tempdir().unwrap();
    assert!(matches!(
        shape.try_open_core(
            dir.path(),
            bad,
            super::fs::real(),
            &super::testkit::TestClock::new(1_000_000)
        ),
        Err(DbError::Config(_))
    ));
    assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}

fn unrepresentable_public_seal_wait_returns_error_without_mutation(shape: CoreShape) {
    let dir = tempfile::tempdir().unwrap();
    let core = shape.open_core(dir.path(), wide(2));
    fill(&core, 0..3);
    let active = core.view().active.clone();
    let before = (active.keys(), active.bytes(), active.next_gsn());
    assert!(matches!(
        core.wait_sealed(std::time::Duration::MAX),
        Err(DbError::Client(_))
    ));
    assert_eq!((active.keys(), active.bytes(), active.next_gsn()), before);
    assert_holds(&core, 0..3);
    assert!(core.wait_sealed(std::time::Duration::ZERO).unwrap());
    core.seal().unwrap();
    assert!(!core.wait_sealed(std::time::Duration::ZERO).unwrap());
}

mod by_hash {
    #[test]
    fn a_freeze_without_its_seal_survives_a_restart() {
        super::a_freeze_without_its_seal_survives_a_restart(super::CoreShape::ByHash);
    }
    #[test]
    fn a_crashed_seal_is_started_over() {
        super::a_crashed_seal_is_started_over(super::CoreShape::ByHash);
    }
    #[test]
    fn a_frozen_generation_that_lost_its_whole_tail_is_retired() {
        super::a_frozen_generation_that_lost_its_whole_tail_is_retired(super::CoreShape::ByHash);
    }
    #[test]
    fn a_frozen_journal_past_its_recorded_last_gsn_is_refused() {
        super::a_frozen_journal_past_its_recorded_last_gsn_is_refused(super::CoreShape::ByHash);
    }
    #[test]
    fn a_generation_that_outlived_its_seal_is_removed() {
        super::a_generation_that_outlived_its_seal_is_removed(super::CoreShape::ByHash);
    }
    #[test]
    fn files_of_a_dropped_segment_are_removed() {
        super::files_of_a_dropped_segment_are_removed(super::CoreShape::ByHash);
    }
    #[test]
    fn the_shard_count_changes_across_restarts() {
        super::the_shard_count_changes_across_restarts(super::CoreShape::ByHash);
    }
    #[test]
    fn a_restart_changes_no_answer() {
        super::a_restart_changes_no_answer(super::CoreShape::ByHash);
    }
    #[test]
    fn recovered_saturated_queue_refuses_every_mutation_across_reopens() {
        super::recovered_saturated_queue_refuses_every_mutation_across_reopens(
            super::CoreShape::ByHash,
        );
    }
    #[test]
    fn recovered_lowered_limits_freeze_before_write_or_tick() {
        super::recovered_lowered_limits_freeze_before_write_or_tick(super::CoreShape::ByHash);
    }
    #[test]
    fn unrepresentable_configured_seal_wait_is_rejected() {
        super::unrepresentable_configured_seal_wait_is_rejected(super::CoreShape::ByHash);
    }
    #[test]
    fn unrepresentable_public_seal_wait_returns_error_without_mutation() {
        super::unrepresentable_public_seal_wait_returns_error_without_mutation(
            super::CoreShape::ByHash,
        );
    }
}

mod by_key {
    #[test]
    fn a_freeze_without_its_seal_survives_a_restart() {
        super::a_freeze_without_its_seal_survives_a_restart(super::CoreShape::ByKey);
    }
    #[test]
    fn a_crashed_seal_is_started_over() {
        super::a_crashed_seal_is_started_over(super::CoreShape::ByKey);
    }
    #[test]
    fn a_frozen_generation_that_lost_its_whole_tail_is_retired() {
        super::a_frozen_generation_that_lost_its_whole_tail_is_retired(super::CoreShape::ByKey);
    }
    #[test]
    fn a_frozen_journal_past_its_recorded_last_gsn_is_refused() {
        super::a_frozen_journal_past_its_recorded_last_gsn_is_refused(super::CoreShape::ByKey);
    }
    #[test]
    fn a_generation_that_outlived_its_seal_is_removed() {
        super::a_generation_that_outlived_its_seal_is_removed(super::CoreShape::ByKey);
    }
    #[test]
    fn files_of_a_dropped_segment_are_removed() {
        super::files_of_a_dropped_segment_are_removed(super::CoreShape::ByKey);
    }
    #[test]
    fn the_shard_count_changes_across_restarts() {
        super::the_shard_count_changes_across_restarts(super::CoreShape::ByKey);
    }
    #[test]
    fn a_restart_changes_no_answer() {
        super::a_restart_changes_no_answer(super::CoreShape::ByKey);
    }
    #[test]
    fn recovered_saturated_queue_refuses_every_mutation_across_reopens() {
        super::recovered_saturated_queue_refuses_every_mutation_across_reopens(
            super::CoreShape::ByKey,
        );
    }
    #[test]
    fn recovered_lowered_limits_freeze_before_write_or_tick() {
        super::recovered_lowered_limits_freeze_before_write_or_tick(super::CoreShape::ByKey);
    }
    #[test]
    fn unrepresentable_configured_seal_wait_is_rejected() {
        super::unrepresentable_configured_seal_wait_is_rejected(super::CoreShape::ByKey);
    }
    #[test]
    fn unrepresentable_public_seal_wait_returns_error_without_mutation() {
        super::unrepresentable_public_seal_wait_returns_error_without_mutation(
            super::CoreShape::ByKey,
        );
    }
}