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
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
//! Helpers shared by the unit tests of the segmented family.

use std::path::Path;
use std::sync::Arc;

use super::fs::SegFs;
use super::hash::{cmp_hk, key_hash};
use super::manifest::SegRecord;
use super::seal::{SegTimes, SegmentWriter};
use super::sidecar::{OrderKind, SegHeader};
use crate::codec::Codec;
use crate::entry::serialize_entry;
use crate::error::DbError;

pub(crate) const KEY_LEN: usize = 32;
pub(crate) const SEED: u64 = 0x5eed;
pub(crate) type TestKey = [u8; KEY_LEN];

/// Raw-byte key fixture; unlike `[u8; N]`, it declares no typed component boundaries.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct RawTestKey(pub TestKey);

impl crate::key::Key for RawTestKey {
    const KEY_SCHEME: armour_core::KeyScheme = armour_core::KeyScheme::Bytes;
    fn as_bytes(&self) -> &[u8] {
        &self.0
    }
    fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
    fn from_bytes(bytes: &[u8]) -> Self {
        Self(bytes.try_into().unwrap())
    }
    fn zeroed() -> Self {
        Self([0; KEY_LEN])
    }
}

pub(crate) struct TestEntry {
    pub h: u64,
    pub key: TestKey,
    /// `None` is a tombstone.
    pub value: Option<Vec<u8>>,
    pub gsn: u64,
}

impl TestEntry {
    /// The entry as the journal holds it.
    pub(crate) fn bytes(&self) -> Vec<u8> {
        match &self.value {
            Some(v) => serialize_entry(self.gsn, &self.key, v, false),
            None => serialize_entry(self.gsn, &self.key, &[], true),
        }
    }
}

pub(crate) fn key_of(i: u64) -> TestKey {
    let mut key = [0u8; KEY_LEN];
    for (n, chunk) in key.chunks_mut(8).enumerate() {
        let word = i.wrapping_mul(0x9e37_79b9_7f4a_7c15).wrapping_add(n as u64);
        chunk.copy_from_slice(&word.to_le_bytes());
    }
    key[..8].copy_from_slice(&i.to_le_bytes());
    key
}

/// Numeric test keys whose byte order matches their numeric order.
pub(crate) fn ordered_key(n: u64) -> TestKey {
    let mut key = [0; KEY_LEN];
    key[..8].copy_from_slice(&n.to_be_bytes());
    key
}

/// Ordered keys with values and regular tombstones.
pub(crate) fn ordered_entries(n: u64) -> Vec<TestEntry> {
    (0..n)
        .map(|i| {
            let key = ordered_key(i);
            TestEntry {
                h: key_hash(&key, SEED),
                key,
                value: (i % 10 != 9).then(|| value_of(i)),
                gsn: i + 1,
            }
        })
        .collect()
}

/// Writer fixture with an explicitly selected filter partition count.
pub(crate) fn write_segment_with_filter_bits(
    seg_dir: &Path,
    id: u64,
    entries: &[TestEntry],
    bits: u8,
) -> SegRecord {
    let mut writer =
        SegmentWriter::create(super::fs::real(), seg_dir, header(id), entries.len() as u64)
            .unwrap();
    writer.force_filter_bits(bits);
    for entry in entries {
        writer.push(entry.h, &entry.bytes()).unwrap();
    }
    writer.finish(times(), 0, 0).unwrap().into_record()
}

/// Damage every page of a section while retaining the original CRC metadata.
pub(crate) fn corrupt_section_everywhere(seg_dir: &Path, rec: &SegRecord, kind: u32) {
    use super::sidecar::*;
    let path = seg_dir.join(super::seal::sidx_name(rec.segment_id, rec.version));
    let mut bytes = std::fs::read(&path).unwrap();
    let footer = bytes.len() - SIDX_FOOTER_LEN;
    let (at, count, crc) = parse_footer(&bytes[footer..], bytes.len() as u64).unwrap();
    let records = parse_table(&bytes[at as usize..footer], count, crc, at).unwrap();
    let section = records.iter().find(|r| r.kind == kind).unwrap();
    for c in 0..super::page_index::chunk_count(section.offset, section.len) {
        bytes[super::page_index::chunk_range(section.offset, section.len, c).0 as usize] ^= 1;
    }
    std::fs::write(path, bytes).unwrap();
}

pub(crate) fn raw_ordered_key(n: u64) -> RawTestKey {
    RawTestKey(ordered_key(n))
}

pub(crate) fn value_of(i: u64) -> Vec<u8> {
    format!("value-{i:08}").into_bytes()
}

/// `n` entries for keys `key_of(0..n)`, sorted by `(h, key)`. Every tenth is
/// a tombstone. GSNs are `first_gsn ..`, assigned in key-number order.
pub(crate) fn entries(n: u64, first_gsn: u64) -> Vec<TestEntry> {
    let mut out: Vec<TestEntry> = (0..n)
        .map(|i| {
            let key = key_of(i);
            TestEntry {
                h: key_hash(&key, SEED),
                key,
                value: (i % 10 != 9).then(|| value_of(i)),
                gsn: first_gsn + i,
            }
        })
        .collect();
    out.sort_by(|a, b| cmp_hk(a.h, &a.key, b.h, &b.key));
    out
}

pub(crate) fn header(segment_id: u64) -> SegHeader {
    SegHeader {
        segment_id,
        version: 1,
        order: OrderKind::ByHash,
        key_len: KEY_LEN as u16,
        seed: SEED,
        block_size: 4 * 1024,
    }
}

pub(crate) fn times() -> SegTimes {
    SegTimes {
        opened_at_ms: 1_000,
        frozen_at_ms: 2_000,
        sealed_at_ms: 3_000,
    }
}

/// Small-block key segment fixture including a retained tombstone.
pub(crate) fn key_entries() -> Vec<TestEntry> {
    (0..100)
        .map(|n| {
            let key = ordered_key(n);
            TestEntry {
                h: key_hash(&key, SEED),
                key,
                value: (n != 99).then(|| vec![42; 80]),
                gsn: n + 1,
            }
        })
        .collect()
}

pub(crate) fn write_key_segment(seg_dir: &Path, entries: &[TestEntry]) -> SegRecord {
    let mut header = header(41);
    header.order = OrderKind::ByKey;
    header.block_size = 256;
    let mut writer = SegmentWriter::create_key(
        super::fs::real(),
        seg_dir,
        header,
        &[4, 8],
        entries.len() as u64,
    )
    .unwrap();
    for entry in entries {
        writer.push(entry.h, &entry.bytes()).unwrap();
    }
    writer.finish(times(), 0, 0).unwrap().into_record()
}

/// Rebuild section/table CRCs and manifest checksum after a semantic mutation.
pub(crate) fn rewrite_section(
    seg_dir: &Path,
    rec: &SegRecord,
    kind: u32,
    mutate: impl FnOnce(&mut Vec<u8>),
) -> SegRecord {
    rewrite_sections(seg_dir, rec, |sections| {
        mutate(&mut sections.iter_mut().find(|(k, _)| *k == kind).unwrap().1);
    })
}

/// Key-order compatibility wrapper for section mutation fixtures.
pub(crate) fn rewrite_key_section(
    seg_dir: &Path,
    rec: &SegRecord,
    kind: u32,
    mutate: impl FnOnce(&mut Vec<u8>),
) -> SegRecord {
    rewrite_section(seg_dir, rec, kind, mutate)
}

pub(crate) fn rewrite_sections(
    seg_dir: &Path,
    rec: &SegRecord,
    mutate: impl FnOnce(&mut Vec<(u32, Vec<u8>)>),
) -> SegRecord {
    use super::sidecar::*;
    let path = seg_dir.join(super::seal::sidx_name(rec.segment_id, rec.version));
    let bytes = std::fs::read(&path).unwrap();
    let footer = bytes.len() - SIDX_FOOTER_LEN;
    let (table_at, count, crc) = parse_footer(&bytes[footer..], bytes.len() as u64).unwrap();
    let table = parse_table(&bytes[table_at as usize..footer], count, crc, table_at).unwrap();
    let mut sections: Vec<_> = table
        .iter()
        .map(|r| {
            (
                r.kind,
                bytes[r.offset as usize..(r.offset + r.len) as usize].to_vec(),
            )
        })
        .collect();
    mutate(&mut sections);
    let header = SegHeader::decode(&bytes[..FILE_HEADER_LEN], SIDX_MAGIC).unwrap();
    let bytes = encode_sidecar(&header, &sections);
    std::fs::write(path, &bytes).unwrap();
    let mut rec = rec.clone();
    rec.sidx_len = bytes.len() as u64;
    rec.sidx_checksum = xxhash_rust::xxh3::xxh3_64(&bytes);
    rec
}

/// Write a whole segment and return the record a manifest would hold.
pub(crate) fn write_segment(
    fs: Arc<dyn SegFs>,
    seg_dir: &Path,
    segment_id: u64,
    entries: &[TestEntry],
) -> SegRecord {
    write(fs, seg_dir, segment_id, entries, false)
}

/// Write an old-format hash segment without the optional page index.
pub(crate) fn write_legacy_segment(
    fs: Arc<dyn SegFs>,
    seg_dir: &Path,
    segment_id: u64,
    entries: &[TestEntry],
) -> SegRecord {
    let rec = write_segment(fs, seg_dir, segment_id, entries);
    without_page_index(seg_dir, &rec)
}

/// Write an old-format ordered segment without the optional page index.
pub(crate) fn write_legacy_key_segment(seg_dir: &Path, entries: &[TestEntry]) -> SegRecord {
    let rec = write_key_segment(seg_dir, entries);
    without_page_index(seg_dir, &rec)
}

fn without_page_index(seg_dir: &Path, rec: &SegRecord) -> SegRecord {
    rewrite_sections(seg_dir, rec, |sections| {
        sections.retain(|(kind, _)| *kind != super::sidecar::SECTION_PAGE_INDEX);
    })
}

/// [`write_segment`] for entries whose `h` is staged, not `key_hash(key, SEED)`.
pub(crate) fn write_segment_with_staged_hashes(
    fs: Arc<dyn SegFs>,
    seg_dir: &Path,
    segment_id: u64,
    entries: &[TestEntry],
) -> SegRecord {
    write(fs, seg_dir, segment_id, entries, true)
}

fn write(
    fs: Arc<dyn SegFs>,
    seg_dir: &Path,
    segment_id: u64,
    entries: &[TestEntry],
    staged_hashes: bool,
) -> SegRecord {
    let mut writer =
        SegmentWriter::create(fs, seg_dir, header(segment_id), entries.len() as u64).unwrap();
    if staged_hashes {
        writer.trust_caller_hash();
    }
    for e in entries {
        writer.push(e.h, &e.bytes()).unwrap();
    }
    writer.finish(times(), 3, 0xcafe).unwrap().into_record()
}

use std::sync::atomic::{AtomicU64, Ordering};

use super::config::SegConfig;
use super::core::{Clock, OpenOptions, SegCore, SegMeta, create_layout};
use super::fs::real;
use super::generation::{GEN_DIR, Generation};
use super::manifest::{GenRecord, GenState, Manifest, publish};
use super::seal::SEG_DIR;
use crate::error::DbResult;
use crate::seg::config::Limits;

pub(crate) fn meta() -> SegMeta {
    SegMeta {
        name: "test_seg",
        typ_hash: 0xcafe,
        value_version: 3,
    }
}

/// A clock a test moves by hand.
#[derive(Clone)]
pub(crate) struct TestClock(Arc<AtomicU64>);

impl TestClock {
    pub(crate) fn new(now_ms: u64) -> Self {
        Self(Arc::new(AtomicU64::new(now_ms)))
    }

    pub(crate) fn set(&self, now_ms: u64) {
        self.0.store(now_ms, Ordering::SeqCst);
    }

    pub(crate) fn advance(&self, ms: u64) {
        self.0.fetch_add(ms, Ordering::SeqCst);
    }

    pub(crate) fn clock(&self) -> Clock {
        let now = self.0.clone();
        Arc::new(move || now.load(Ordering::SeqCst))
    }
}

/// Open without the worker thread: the test drives freeze, seal and
/// maintenance itself.
pub(crate) fn try_open_core(
    dir: &Path,
    config: SegConfig,
    fs: Arc<dyn SegFs>,
    clock: &TestClock,
) -> DbResult<Arc<SegCore<TestKey>>> {
    SegCore::open(
        dir,
        meta(),
        config,
        OpenOptions {
            fs,
            clock: clock.clock(),
            worker: false,
        },
    )
}

pub(crate) fn open_core(dir: &Path, config: SegConfig) -> Arc<SegCore<TestKey>> {
    try_open_core(dir, config, real(), &TestClock::new(1_000_000)).unwrap()
}

pub(crate) fn try_open_tree_core(
    path: &Path,
    config: SegConfig,
    clock: TestClock,
    prefix_filters: &'static [usize],
) -> DbResult<Arc<SegCore<TestKey>>> {
    SegCore::open_tree(
        path,
        meta(),
        prefix_filters,
        config,
        OpenOptions {
            fs: real(),
            clock: clock.clock(),
            worker: false,
        },
    )
}

pub(crate) fn open_tree_core(
    path: &Path,
    config: SegConfig,
    clock: TestClock,
    prefix_filters: &'static [usize],
) -> Arc<SegCore<TestKey>> {
    try_open_tree_core(path, config, clock, prefix_filters).unwrap()
}

pub(crate) fn try_open_raw_tree_core(
    path: &Path,
    config: SegConfig,
    clock: TestClock,
    prefix_filters: &'static [usize],
) -> DbResult<Arc<SegCore<RawTestKey>>> {
    SegCore::open_tree(
        path,
        meta(),
        prefix_filters,
        config,
        OpenOptions {
            fs: real(),
            clock: clock.clock(),
            worker: false,
        },
    )
}

pub(crate) fn open_raw_tree_core(
    path: &Path,
    config: SegConfig,
    clock: TestClock,
    prefix_filters: &'static [usize],
) -> Arc<SegCore<RawTestKey>> {
    try_open_raw_tree_core(path, config, clock, prefix_filters).unwrap()
}

const ROOMY: Limits = Limits {
    max_keys: u64::MAX,
    max_bytes: u64::MAX,
};

fn fill(g: &Generation<TestKey>, keys: std::ops::Range<u64>, deleted: u64, tag: &str) {
    for i in keys.clone() {
        let key = key_of(i);
        let h = key_hash(&key, SEED);
        let value = format!("{tag}-{i}");
        let value = (i >= keys.start + deleted).then_some(value.as_bytes());
        g.append(h, &key, value, ROOMY).unwrap();
    }
    g.write_hints().unwrap();
    g.close().unwrap();
}

/// A collection with one sealed segment, one frozen generation and one
/// active generation, written without `SegCore`. The layers overlap, so
/// reads must pick the newest.
pub(crate) fn build_collection(dir: &Path) {
    build_collection_shape(dir, CoreShape::ByHash);
}

pub(crate) fn build_collection_shape(dir: &Path, shape: CoreShape) {
    let fs = real();
    create_layout(&*fs, dir).unwrap();
    let gen_root = dir.join(GEN_DIR);
    let seg_root = dir.join(SEG_DIR);
    let config = SegConfig::test();

    let mut segment = entries(200, 1);
    if matches!(shape, CoreShape::ByKey) {
        segment.sort_by_key(|entry| entry.key);
    }
    let mut manifest = Manifest::new(KEY_LEN as u16, SEED, 1);
    manifest.order = shape.order();
    manifest.next_segment_id = 2;
    manifest.next_gen_id = 3;
    manifest.gsn_floor = 350;
    manifest.segments.push(match shape {
        CoreShape::ByHash => write_segment(fs.clone(), &seg_root, 1, &segment),
        CoreShape::ByKey => {
            let mut h = header(1);
            h.order = OrderKind::ByKey;
            let mut writer =
                SegmentWriter::create_key(fs.clone(), &seg_root, h, &[], segment.len() as u64)
                    .unwrap();
            for entry in &segment {
                writer.push(entry.h, &entry.bytes()).unwrap();
            }
            writer.finish(times(), 0, 0).unwrap().into_record()
        }
    });

    let frozen: Generation<TestKey> =
        Generation::create(fs.clone(), &gen_root, 1, &config, 2_500, shape.order()).unwrap();
    frozen.seed_gsn(201);
    fill(&frozen, 100..250, 10, "frozen");
    manifest.generations.push(GenRecord {
        gen_id: 1,
        state: GenState::Frozen,
        shard_count: config.shard_count as u8,
        opened_at_ms: 2_500,
        frozen_at_ms: 3_000,
        min_gsn: 201,
        max_gsn: 350,
    });

    let active: Generation<TestKey> =
        Generation::create(fs.clone(), &gen_root, 2, &config, 3_000, shape.order()).unwrap();
    active.seed_gsn(351);
    fill(&active, 200..300, 10, "active");
    manifest.generations.push(GenRecord {
        gen_id: 2,
        state: GenState::Active,
        shard_count: config.shard_count as u8,
        opened_at_ms: 3_000,
        frozen_at_ms: 0,
        min_gsn: 351,
        max_gsn: 0,
    });

    manifest.check().unwrap();
    publish(&*fs, dir, &manifest).unwrap();
}

/// Disjoint legacy layers and an empty active generation, without a worker.
pub(crate) fn build_legacy_collection(dir: &Path, segments: u64) {
    let fs = real();
    create_layout(&*fs, dir).unwrap();
    let config = SegConfig::test();
    let mut manifest = Manifest::new(KEY_LEN as u16, SEED, 1);
    for id in 1..=segments {
        let key = key_of(id);
        let entries = [TestEntry {
            h: key_hash(&key, SEED),
            key,
            value: Some(value_of(id)),
            gsn: id,
        }];
        let rec = write_legacy_segment(fs.clone(), &dir.join(SEG_DIR), id, &entries);
        manifest.segments.push(rec);
    }
    manifest.next_segment_id = segments + 1;
    manifest.next_gen_id = 2;
    manifest.gsn_floor = segments;
    let active: Generation<TestKey> = Generation::create(
        fs.clone(),
        &dir.join(GEN_DIR),
        1,
        &config,
        2000,
        OrderKind::ByHash,
    )
    .unwrap();
    active.seed_gsn(segments + 1);
    manifest.generations.push(GenRecord {
        gen_id: 1,
        state: GenState::Active,
        shard_count: config.shard_count as u8,
        opened_at_ms: 2000,
        frozen_at_ms: 0,
        min_gsn: segments + 1,
        max_gsn: 0,
    });
    manifest.check().unwrap();
    publish(&*fs, dir, &manifest).unwrap();
}

/// A collection with its worker thread running. Dropping it stops the thread
/// first, so the directory lease is released by the time `drop` returns.
pub(crate) struct Running(pub Arc<SegCore<TestKey>>);

impl std::ops::Deref for Running {
    type Target = SegCore<TestKey>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Drop for Running {
    fn drop(&mut self) {
        self.0.stop_worker();
    }
}

/// Open with the worker thread running, on the wall clock.
pub(crate) fn open_core_with_worker(dir: &Path, config: SegConfig) -> Running {
    Running(SegCore::open(dir, meta(), config, OpenOptions::production()).unwrap())
}

/// Small numbered values shared by core mutation tests.
pub(crate) fn value(i: u64) -> Vec<u8> {
    format!("v{i}").into_bytes()
}

/// Populate a core through its public mutation path.
pub(crate) fn fill_core(core: &SegCore<TestKey>, keys: std::ops::Range<u64>) {
    for i in keys {
        core.put(&key_of(i), &value(i)).unwrap();
    }
}

/// Copy a collection directory as a crash would leave it: whatever the
/// operating system holds, without the lock files.
pub(crate) fn copy_collection(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap() {
        let entry = entry.unwrap();
        let target = to.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_collection(&entry.path(), &target);
        } else if entry.file_name() != "db.lock" {
            std::fs::copy(entry.path(), target).unwrap();
        }
    }
}

/// Stores a `String` as its UTF-8 bytes. Bytes that are not UTF-8 do not
/// decode, which lets a test plant a row that cannot be read.
#[derive(Clone, Default)]
pub(crate) struct TextCodec;

impl Codec<String> for TextCodec {
    fn encode_to(&self, value: &String, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        buf.extend_from_slice(value.as_bytes());
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<String> {
        String::from_utf8(bytes.to_vec()).map_err(|_| DbError::CorruptedEntry { offset: 0 })
    }
}

/// Truncate generation journals while keeping their original bytes for teardown.
/// Open/recover the core before constructing this guard, and drop it first.
pub(crate) struct UnreadableJournals(Vec<(std::path::PathBuf, Vec<u8>)>);

impl UnreadableJournals {
    pub(crate) fn new(root: &Path) -> Self {
        fn damage(dir: &Path, saved: &mut Vec<(std::path::PathBuf, Vec<u8>)>) {
            for entry in std::fs::read_dir(dir).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    damage(&path, saved);
                } else if path.extension().is_some_and(|ext| ext == "data") {
                    saved.push((path.clone(), std::fs::read(&path).unwrap()));
                    std::fs::OpenOptions::new()
                        .write(true)
                        .open(&path)
                        .unwrap()
                        .set_len(0)
                        .unwrap();
                }
            }
        }
        let mut saved = Vec::new();
        damage(&root.join(GEN_DIR), &mut saved);
        assert!(saved.iter().any(|(_, bytes)| !bytes.is_empty()));
        Self(saved)
    }
}

impl Drop for UnreadableJournals {
    fn drop(&mut self) {
        for (path, bytes) in &self.0 {
            std::fs::write(path, bytes).unwrap();
        }
    }
}

/// Shape dispatch for shared recovery scenarios, preserving legacy key bytes.
#[derive(Clone, Copy)]
pub(crate) enum CoreShape {
    ByHash,
    ByKey,
}
impl CoreShape {
    pub(crate) fn order(self) -> OrderKind {
        match self {
            Self::ByHash => OrderKind::ByHash,
            Self::ByKey => OrderKind::ByKey,
        }
    }
    pub(crate) fn try_open_core(
        self,
        dir: &Path,
        config: SegConfig,
        fs: Arc<dyn SegFs>,
        clock: &TestClock,
    ) -> DbResult<Arc<SegCore<TestKey>>> {
        match self {
            Self::ByHash => try_open_core(dir, config, fs, clock),
            Self::ByKey => SegCore::open_tree(
                dir,
                meta(),
                &[],
                config,
                OpenOptions {
                    fs,
                    clock: clock.clock(),
                    worker: false,
                },
            ),
        }
    }
    pub(crate) fn open_core(self, dir: &Path, config: SegConfig) -> Arc<SegCore<TestKey>> {
        self.try_open_core(dir, config, real(), &TestClock::new(1_000_000))
            .unwrap()
    }
    pub(crate) fn build_collection(self, dir: &Path) {
        build_collection_shape(dir, self);
    }
}

/// Corrupt prefix-filter fingerprints without changing its resident wrapper.
pub(crate) fn corrupt_prefix_fingerprints(seg_dir: &Path, rec: &SegRecord, prefix_len: u16) {
    use super::sidecar::*;
    let path = seg_dir.join(super::seal::sidx_name(rec.segment_id, rec.version));
    let mut bytes = std::fs::read(&path).unwrap();
    let footer = bytes.len() - SIDX_FOOTER_LEN;
    let (at, count, crc) = parse_footer(&bytes[footer..], bytes.len() as u64).unwrap();
    let records = parse_table(&bytes[at as usize..footer], count, crc, at).unwrap();
    let section = records
        .iter()
        .find(|r| {
            r.kind == SECTION_PREFIX_FILTER
                && u16::from_le_bytes(
                    bytes[r.offset as usize..r.offset as usize + 2]
                        .try_into()
                        .unwrap(),
                ) == prefix_len
        })
        .unwrap();
    let filter_at = section.offset as usize + 8;
    let partitions =
        u32::from_le_bytes(bytes[filter_at + 4..filter_at + 8].try_into().unwrap()) as usize;
    let fingerprints_at = filter_at + 8 + partitions * 32;
    assert!(fingerprints_at < (section.offset + section.len) as usize);
    bytes[fingerprints_at] ^= 1;
    std::fs::write(path, bytes).unwrap();
}