mmdb 4.2.10

The storage engine behind vsdb — a pure-Rust LSM-Tree key-value store
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
//! MMDB Benchmarks — comparable to RocksDB's db_bench report format.
//!
//! Run:
//!   cargo bench                    # all benchmarks
//!   cargo bench -- "fillseq"       # specific group
//!   cargo bench -- "small_cache"   # small block-cache scenarios only
//!   cargo bench -- "warm"          # warm-cache scenarios only
//!
//! Two configurations are tested for cache-sensitive operations:
//! - **warm**: Large cache (256MB), data fits in memory — measures CPU/algorithm cost
//! - **small_cache**: Tiny cache (256KB) — measures block-cache-miss + decode cost
//!
//! Small-cache reads still use the same-process OS page cache, so they do not
//! measure storage latency. These cases use smaller datasets to keep runtime reasonable.

use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use std::path::Path;
use std::time::Duration;

/// Custom criterion config: 10 samples, 3s measurement — keeps total bench under 5 min.
fn bench_config() -> Criterion {
    Criterion::default()
        .sample_size(10)
        .measurement_time(Duration::from_secs(3))
}

// ── Helpers ─────────────────────────────────────────────────────────────

fn make_key(i: u64) -> Vec<u8> {
    format!("key_{:016}", i).into_bytes()
}

fn make_value(size: usize) -> Vec<u8> {
    vec![0x42u8; size]
}

/// Open DB with warm cache (256MB) — data stays in memory.
fn open_warm(path: &Path) -> mmdb::DB {
    mmdb::DB::open(
        mmdb::DbOptions {
            create_if_missing: true,
            write_buffer_size: 64 * 1024 * 1024,
            block_cache_capacity: 256 * 1024 * 1024,
            ..Default::default()
        },
        path,
    )
    .unwrap()
}

/// Open DB with a small block cache (256KB).
fn open_small_cache(path: &Path) -> mmdb::DB {
    mmdb::DB::open(
        mmdb::DbOptions {
            create_if_missing: true,
            write_buffer_size: 4 * 1024 * 1024, // 4MB — frequent flushes
            block_cache_capacity: 256 * 1024,   // 256KB — almost nothing cached
            l0_compaction_trigger: 4,
            ..Default::default()
        },
        path,
    )
    .unwrap()
}

fn open_with(path: &Path, opts: mmdb::DbOptions) -> mmdb::DB {
    mmdb::DB::open(opts, path).unwrap()
}

// ── fillseq: Sequential Write ───────────────────────────────────────────

fn bench_fillseq(c: &mut Criterion) {
    let mut group = c.benchmark_group("fillseq");

    let value = make_value(100);

    for &count in &[1_000u64, 10_000] {
        group.throughput(Throughput::Elements(count));
        group.bench_with_input(BenchmarkId::from_parameter(count), &count, |b, &count| {
            b.iter_with_setup(
                || {
                    let dir = tempfile::tempdir().unwrap();
                    let db = open_warm(dir.path());
                    (dir, db)
                },
                |(dir, db)| {
                    for i in 0..count {
                        db.put(&make_key(i), &value).unwrap();
                    }
                    db.close().unwrap();
                    drop(dir);
                },
            );
        });
    }
    group.finish();
}

// ── fillrandom: Random Write ────────────────────────────────────────────

fn bench_fillrandom(c: &mut Criterion) {
    let mut group = c.benchmark_group("fillrandom");

    let value = make_value(100);

    for &count in &[1_000u64, 10_000] {
        group.throughput(Throughput::Elements(count));
        group.bench_with_input(BenchmarkId::from_parameter(count), &count, |b, &count| {
            b.iter_with_setup(
                || {
                    let dir = tempfile::tempdir().unwrap();
                    let db = open_warm(dir.path());
                    let keys: Vec<Vec<u8>> = (0..count)
                        .map(|i| make_key(i.wrapping_mul(6364136223846793005).wrapping_add(1)))
                        .collect();
                    (dir, db, keys)
                },
                |(dir, db, keys)| {
                    for key in &keys {
                        db.put(key, &value).unwrap();
                    }
                    db.close().unwrap();
                    drop(dir);
                },
            );
        });
    }
    group.finish();
}

// ── fillbatch: Batch Write ──────────────────────────────────────────────

fn bench_fillbatch(c: &mut Criterion) {
    let mut group = c.benchmark_group("fillbatch");

    let value = make_value(100);

    for &batch_size in &[10usize, 100, 1000] {
        let total_ops = 100 * batch_size as u64;
        group.throughput(Throughput::Elements(total_ops));
        group.bench_with_input(
            BenchmarkId::from_parameter(batch_size),
            &batch_size,
            |b, &batch_size| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_warm(dir.path());
                        (dir, db)
                    },
                    |(dir, db)| {
                        for round in 0..100u64 {
                            let mut batch = mmdb::WriteBatch::new();
                            for i in 0..batch_size as u64 {
                                batch.put(&make_key(round * 1000 + i), &value);
                            }
                            db.write(batch).unwrap();
                        }
                        db.close().unwrap();
                        drop(dir);
                    },
                );
            },
        );
    }
    group.finish();
}

// ── overwrite ───────────────────────────────────────────────────────────

fn bench_overwrite(c: &mut Criterion) {
    let mut group = c.benchmark_group("overwrite");

    let value = make_value(100);
    let count = 10_000u64;

    group.throughput(Throughput::Elements(count));
    group.bench_function("10k", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..count {
                    db.put(&make_key(i), &value).unwrap();
                }
                (dir, db)
            },
            |(_dir, db)| {
                let new_value = make_value(100);
                for i in 0..count {
                    db.put(&make_key(i), &new_value).unwrap();
                }
            },
        );
    });
    group.finish();
}

// ── readrandom: warm vs small cache ────────────────────────────────────

fn bench_readrandom(c: &mut Criterion) {
    let mut group = c.benchmark_group("readrandom");

    let value = make_value(100);
    let read_count = 1_000u64;

    group.throughput(Throughput::Elements(read_count));

    // Warm: memtable only (no SST I/O)
    group.bench_function("warm/memtable_10k", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..10_000u64 {
                    db.put(&make_key(i), &value).unwrap();
                }
                let keys: Vec<Vec<u8>> = (0..read_count)
                    .map(|i| make_key((i * 7) % 10_000))
                    .collect();
                (dir, db, keys)
            },
            |(_dir, db, keys)| {
                for key in &keys {
                    let _ = db.get(key).unwrap();
                }
            },
        );
    });

    // Warm: SST with large cache (all blocks cached)
    group.bench_function("warm/sst_10k", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..10_000u64 {
                    db.put(&make_key(i), &value).unwrap();
                }
                db.flush().unwrap();
                // Pre-warm cache by reading all keys once
                for i in 0..10_000u64 {
                    let _ = db.get(&make_key(i));
                }
                let keys: Vec<Vec<u8>> = (0..read_count)
                    .map(|i| make_key((i * 7) % 10_000))
                    .collect();
                (dir, db, keys)
            },
            |(_dir, db, keys)| {
                for key in &keys {
                    let _ = db.get(key).unwrap();
                }
            },
        );
    });

    // Small cache: SST blocks miss the MMDB cache but remain in the OS page cache.
    // Smaller dataset (2K entries) to keep bench time reasonable
    group.throughput(Throughput::Elements(500));
    group.bench_function("small_cache/sst_2k", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_small_cache(dir.path());
                for i in 0..2_000u64 {
                    db.put(&make_key(i), &value).unwrap();
                }
                db.flush().unwrap();
                db.compact().unwrap();
                let keys: Vec<Vec<u8>> = (0..500u64).map(|i| make_key((i * 7) % 2_000)).collect();
                (dir, db, keys)
            },
            |(_dir, db, keys)| {
                for key in &keys {
                    let _ = db.get(key).unwrap();
                }
            },
        );
    });

    group.finish();
}

// ── readseq (scan): warm vs small cache ────────────────────────────────

fn bench_readseq(c: &mut Criterion) {
    let mut group = c.benchmark_group("readseq");

    let value = make_value(100);

    // Warm: 10K entries, large cache, data mostly in memtable/cache
    for &scan_count in &[100usize, 1_000, 10_000] {
        group.throughput(Throughput::Elements(scan_count as u64));
        group.bench_with_input(
            BenchmarkId::new("warm", scan_count),
            &scan_count,
            |b, &scan_count| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_warm(dir.path());
                        for i in 0..10_000u64 {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.flush().unwrap();
                        (dir, db)
                    },
                    |(_dir, db)| {
                        let n = db.iter().unwrap().take(scan_count).count();
                        assert!(n > 0);
                    },
                );
            },
        );
    }

    // Small cache: 5K entries (smaller to stay fast), multi-level SST
    for &scan_count in &[100usize, 1_000] {
        group.throughput(Throughput::Elements(scan_count as u64));
        group.bench_with_input(
            BenchmarkId::new("small_cache", scan_count),
            &scan_count,
            |b, &scan_count| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_small_cache(dir.path());
                        for i in 0..5_000u64 {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.flush().unwrap();
                        db.compact().unwrap();
                        (dir, db)
                    },
                    |(_dir, db)| {
                        let n = db.iter().unwrap().take(scan_count).count();
                        assert!(n > 0);
                    },
                );
            },
        );
    }

    group.finish();
}

// ── prefix scan: warm vs small cache ───────────────────────────────────

fn bench_prefix_scan(c: &mut Criterion) {
    let mut group = c.benchmark_group("prefix_scan");

    let value = make_value(100);
    let num_prefixes = 50u64;

    // Warm: prefix scan over 10K entries
    group.throughput(Throughput::Elements(100));
    group.bench_function("warm/100", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let opts = mmdb::DbOptions {
                    create_if_missing: true,
                    write_buffer_size: 64 * 1024 * 1024,
                    block_cache_capacity: 256 * 1024 * 1024,
                    prefix_len: 8,
                    ..Default::default()
                };
                let db = open_with(dir.path(), opts);
                for i in 0..10_000u64 {
                    let pfx = i % num_prefixes;
                    let key = format!("pfx_{:04}_{:010}", pfx, i);
                    db.put(key.as_bytes(), &value).unwrap();
                }
                db.flush().unwrap();
                (dir, db)
            },
            |(_dir, db)| {
                let n = db
                    .iter_with_prefix(b"pfx_0025", &mmdb::ReadOptions::default())
                    .unwrap()
                    .take(100)
                    .count();
                assert!(n > 0);
            },
        );
    });

    // Small cache: prefix scan over 3K entries
    group.throughput(Throughput::Elements(100));
    group.bench_function("small_cache/100", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let opts = mmdb::DbOptions {
                    create_if_missing: true,
                    write_buffer_size: 4 * 1024 * 1024,
                    block_cache_capacity: 256 * 1024,
                    prefix_len: 8,
                    l0_compaction_trigger: 4,
                    ..Default::default()
                };
                let db = open_with(dir.path(), opts);
                for i in 0..3_000u64 {
                    let pfx = i % num_prefixes;
                    let key = format!("pfx_{:04}_{:010}", pfx, i);
                    db.put(key.as_bytes(), &value).unwrap();
                }
                db.flush().unwrap();
                db.compact().unwrap();
                (dir, db)
            },
            |(_dir, db)| {
                let n = db
                    .iter_with_prefix(b"pfx_0025", &mmdb::ReadOptions::default())
                    .unwrap()
                    .take(100)
                    .count();
                assert!(n > 0);
            },
        );
    });

    group.finish();
}

// ── seek ────────────────────────────────────────────────────────────────

fn bench_seek(c: &mut Criterion) {
    let mut group = c.benchmark_group("seek");

    let value = make_value(100);

    group.throughput(Throughput::Elements(500));
    group.bench_function("warm/random_500", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..50_000u64 {
                    db.put(&make_key(i), &value).unwrap();
                }
                db.flush().unwrap();
                let targets: Vec<Vec<u8>> = (0..500u64)
                    .map(|i| make_key((i.wrapping_mul(6364136223846793005)) % 50_000))
                    .collect();
                (dir, db, targets)
            },
            |(_dir, db, targets)| {
                for target in &targets {
                    let mut iter = db.iter().unwrap();
                    iter.seek(target);
                    let _ = iter.next();
                }
            },
        );
    });
    group.finish();
}

// ── delete + range delete ───────────────────────────────────────────────

fn bench_delete(c: &mut Criterion) {
    let mut group = c.benchmark_group("delete");

    let value = make_value(100);
    let count = 10_000u64;

    group.throughput(Throughput::Elements(count));
    group.bench_function("point_delete_10k", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..count {
                    db.put(&make_key(i), &value).unwrap();
                }
                (dir, db)
            },
            |(_dir, db)| {
                for i in 0..count {
                    db.delete(&make_key(i)).unwrap();
                }
            },
        );
    });

    group.throughput(Throughput::Elements(1));
    group.bench_function("range_delete/one_tombstone_5k_span", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..count {
                    db.put(&make_key(i), &value).unwrap();
                }
                (dir, db)
            },
            |(_dir, db)| {
                db.delete_range(&make_key(0), &make_key(count / 2)).unwrap();
            },
        );
    });

    group.finish();
}

// ── value sizes ─────────────────────────────────────────────────────────

fn bench_value_sizes(c: &mut Criterion) {
    let mut group = c.benchmark_group("value_sizes");

    let count = 1_000u64;

    for &vsize in &[16usize, 100, 1024, 65536] {
        let value = make_value(vsize);
        let bytes_per_op = (24 + vsize) as u64;
        group.throughput(Throughput::Bytes(count * bytes_per_op));
        group.bench_with_input(
            BenchmarkId::new("write", format!("{}B", vsize)),
            &vsize,
            |b, _| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_warm(dir.path());
                        (dir, db)
                    },
                    |(dir, db)| {
                        for i in 0..count {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.close().unwrap();
                        drop(dir);
                    },
                );
            },
        );
    }
    group.finish();
}

// ── compression ─────────────────────────────────────────────────────────

fn bench_compression(c: &mut Criterion) {
    let mut group = c.benchmark_group("compression");

    let count = 5_000u64;
    let value: Vec<u8> = (0..=255u8).cycle().take(256).collect();

    group.throughput(Throughput::Elements(count));

    for (name, compression) in [
        ("none", mmdb::CompressionType::None),
        ("lz4", mmdb::CompressionType::Lz4),
        ("zstd", mmdb::CompressionType::Zstd),
    ] {
        group.bench_with_input(
            BenchmarkId::from_parameter(name),
            &compression,
            |b, &compression| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_with(
                            dir.path(),
                            mmdb::DbOptions {
                                create_if_missing: true,
                                write_buffer_size: 64 * 1024 * 1024,
                                compression,
                                ..Default::default()
                            },
                        );
                        (dir, db)
                    },
                    |(dir, db)| {
                        for i in 0..count {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.flush().unwrap();
                        db.close().unwrap();
                        drop(dir);
                    },
                );
            },
        );
    }
    group.finish();
}

// ── large scan: warm vs small cache ────────────────────────────────────

fn bench_scan_large(c: &mut Criterion) {
    let mut group = c.benchmark_group("scan_large");

    let value = make_value(128);

    // Warm: 100K entries, large cache
    for &scan_count in &[100usize, 1_000, 10_000] {
        group.throughput(Throughput::Elements(scan_count as u64));
        group.bench_with_input(
            BenchmarkId::new("warm", scan_count),
            &scan_count,
            |b, &scan_count| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_warm(dir.path());
                        for i in 0..100_000u64 {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.flush().unwrap();
                        (dir, db)
                    },
                    |(_dir, db)| {
                        let n = db.iter().unwrap().take(scan_count).count();
                        assert!(n > 0);
                    },
                );
            },
        );
    }

    // Small cache: 10K entries, multi-level SST
    for &scan_count in &[100usize, 1_000] {
        group.throughput(Throughput::Elements(scan_count as u64));
        group.bench_with_input(
            BenchmarkId::new("small_cache", scan_count),
            &scan_count,
            |b, &scan_count| {
                b.iter_with_setup(
                    || {
                        let dir = tempfile::tempdir().unwrap();
                        let db = open_small_cache(dir.path());
                        for i in 0..10_000u64 {
                            db.put(&make_key(i), &value).unwrap();
                        }
                        db.flush().unwrap();
                        db.compact().unwrap();
                        (dir, db)
                    },
                    |(_dir, db)| {
                        let n = db.iter().unwrap().take(scan_count).count();
                        assert!(n > 0);
                    },
                );
            },
        );
    }

    group.finish();
}

// ── mixed workload ──────────────────────────────────────────────────────

fn bench_mixed(c: &mut Criterion) {
    let mut group = c.benchmark_group("mixed");

    let value = make_value(100);
    let preload = 10_000u64;
    let ops = 5_000u64;

    group.throughput(Throughput::Elements(ops));

    group.bench_function("read90_write10", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..preload {
                    db.put(&make_key(i), &value).unwrap();
                }
                (dir, db)
            },
            |(_dir, db)| {
                for i in 0..ops {
                    if i % 10 == 0 {
                        db.put(&make_key(preload + i), &value).unwrap();
                    } else {
                        let _ = db.get(&make_key(i % preload)).unwrap();
                    }
                }
            },
        );
    });

    group.bench_function("read50_write50", |b| {
        b.iter_with_setup(
            || {
                let dir = tempfile::tempdir().unwrap();
                let db = open_warm(dir.path());
                for i in 0..preload {
                    db.put(&make_key(i), &value).unwrap();
                }
                (dir, db)
            },
            |(_dir, db)| {
                for i in 0..ops {
                    if i % 2 == 0 {
                        db.put(&make_key(preload + i), &value).unwrap();
                    } else {
                        let _ = db.get(&make_key(i % preload)).unwrap();
                    }
                }
            },
        );
    });

    group.finish();
}

criterion_group! {
    name = benches;
    config = bench_config();
    targets =
    bench_fillseq,
    bench_fillrandom,
    bench_fillbatch,
    bench_overwrite,
    bench_readrandom,
    bench_readseq,
    bench_prefix_scan,
    bench_seek,
    bench_delete,
    bench_value_sizes,
    bench_compression,
    bench_scan_large,
    bench_mixed,
}
criterion_main!(benches);