seerdb 0.0.10

Research-grade storage engine with learned data structures
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
// Real Workload Comparisons - Phase 4 Profiling
//
// Compares seerdb vs RocksDB vs fjall on three realistic workloads:
// 1. Graph pattern (HNSW graph: prefix scans)
// 2. Time series (sequential timestamps: range queries)
// 3. Random KV (random access: point lookups)
//
// Run with: cargo run --release --features baseline-benchmarks --example real_workload_comparisons

use std::time::{Duration, Instant};
use tempfile::tempdir;

#[cfg(feature = "baseline-benchmarks")]
use fjall::Config as FjallConfig;
#[cfg(feature = "baseline-benchmarks")]
use rocksdb::{Options as RocksDBOptions, DB as RocksDBInstance};

use seerdb::DBOptions;

const WARMUP_OPS: usize = 1_000;

// === Workload 1: Graph Pattern (HNSW graph edges) ===

fn benchmark_graph_seerdb() -> (Duration, Duration, f64) {
    let dir = tempdir().unwrap();
    let db = DBOptions::default()
        .memtable_capacity(64 * 1024 * 1024) // 64MB
        .block_cache_capacity(16_384)
        .open(dir.path())
        .unwrap();

    // Setup: 10K nodes × 32 edges/node = 320K entries
    let nodes = 10_000;
    let edges_per_node = 32;
    let value = vec![0u8; 128]; // 128 bytes (edge metadata)

    // Write phase
    let write_start = Instant::now();
    for node_id in 0..nodes {
        for edge_id in 0..edges_per_node {
            let key = format!("node:{}:edge:{:04}", node_id, edge_id);
            db.put(key.as_bytes(), &value).unwrap();
        }
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase: Prefix scans (typical HNSW query)
    let prefixes: Vec<String> = (0..100)
        .map(|i| format!("node:{}:", i * (nodes / 100)))
        .collect();

    // Warmup
    for prefix in prefixes.iter().take(10) {
        let iter = db.prefix(prefix.as_bytes()).unwrap();
        let _: Vec<_> = iter.collect::<Result<Vec<_>, _>>().unwrap();
    }

    let read_start = Instant::now();
    let mut total_entries = 0;
    for prefix in prefixes.iter() {
        let iter = db.prefix(prefix.as_bytes()).unwrap();
        let entries: Vec<_> = iter.collect::<Result<Vec<_>, _>>().unwrap();
        total_entries += entries.len();
    }
    let read_duration = read_start.elapsed();

    let stats = db.stats();
    (write_duration, read_duration, stats.cache_hit_rate)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_graph_rocksdb() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let mut opts = RocksDBOptions::default();
    opts.create_if_missing(true);
    opts.set_write_buffer_size(64 * 1024 * 1024);
    let db = RocksDBInstance::open(&opts, dir.path()).unwrap();

    let nodes = 10_000;
    let edges_per_node = 32;
    let value = vec![0u8; 128];

    // Write phase
    let write_start = Instant::now();
    for node_id in 0..nodes {
        for edge_id in 0..edges_per_node {
            let key = format!("node:{}:edge:{:04}", node_id, edge_id);
            db.put(key.as_bytes(), &value).unwrap();
        }
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase: Prefix scans
    let prefixes: Vec<String> = (0..100)
        .map(|i| format!("node:{}:", i * (nodes / 100)))
        .collect();

    // Warmup
    for prefix in prefixes.iter().take(10) {
        let mut iter = db.prefix_iterator(prefix.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }

    let read_start = Instant::now();
    for prefix in prefixes.iter() {
        let mut iter = db.prefix_iterator(prefix.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_graph_fjall() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let config = FjallConfig::new(dir.path());
    let keyspace = config.open().unwrap();
    let partition = keyspace
        .open_partition("default", Default::default())
        .unwrap();

    let nodes = 10_000;
    let edges_per_node = 32;
    let value = vec![0u8; 128];

    // Write phase
    let write_start = Instant::now();
    for node_id in 0..nodes {
        for edge_id in 0..edges_per_node {
            let key = format!("node:{}:edge:{:04}", node_id, edge_id);
            partition.insert(key.as_bytes(), &value).unwrap();
        }
    }
    keyspace.persist(fjall::PersistMode::SyncAll).unwrap();
    let write_duration = write_start.elapsed();

    // Read phase: Prefix scans
    let prefixes: Vec<String> = (0..100)
        .map(|i| format!("node:{}:", i * (nodes / 100)))
        .collect();

    // Warmup
    for prefix in prefixes.iter().take(10) {
        let mut iter = partition.prefix(prefix.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }

    let read_start = Instant::now();
    for prefix in prefixes.iter() {
        let mut iter = partition.prefix(prefix.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

// === Workload 2: Time Series (sequential timestamps) ===

fn benchmark_timeseries_seerdb() -> (Duration, Duration, f64) {
    let dir = tempdir().unwrap();
    let db = DBOptions::default()
        .memtable_capacity(64 * 1024 * 1024)
        .block_cache_capacity(16_384)
        .open(dir.path())
        .unwrap();

    // Setup: 1M time series entries (timestamp → sensor data)
    let entries = 1_000_000;
    let value = vec![0u8; 64]; // Sensor reading (64 bytes)

    // Write phase (sequential timestamps)
    let write_start = Instant::now();
    for ts in 0..entries {
        let key = format!("ts:{:016}", ts);
        db.put(key.as_bytes(), &value).unwrap();
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase: Range queries (typical time series query)
    let ranges: Vec<(u64, u64)> = (0..100)
        .map(|i| {
            let start = i * (entries / 100);
            let end = start + 10_000; // 10K entry window
            (start, end)
        })
        .collect();

    // Warmup
    for (start, end) in ranges.iter().take(10) {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let iter = db
            .range(start_key.as_bytes(), Some(end_key.as_bytes()))
            .unwrap();
        let _: Vec<_> = iter.collect::<Result<Vec<_>, _>>().unwrap();
    }

    let read_start = Instant::now();
    let mut total_entries = 0;
    for (start, end) in ranges.iter() {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let iter = db
            .range(start_key.as_bytes(), Some(end_key.as_bytes()))
            .unwrap();
        let entries: Vec<_> = iter.collect::<Result<Vec<_>, _>>().unwrap();
        total_entries += entries.len();
    }
    let read_duration = read_start.elapsed();

    let stats = db.stats();
    (write_duration, read_duration, stats.cache_hit_rate)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_timeseries_rocksdb() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let mut opts = RocksDBOptions::default();
    opts.create_if_missing(true);
    opts.set_write_buffer_size(64 * 1024 * 1024);
    let db = RocksDBInstance::open(&opts, dir.path()).unwrap();

    let entries = 1_000_000;
    let value = vec![0u8; 64];

    // Write phase
    let write_start = Instant::now();
    for ts in 0..entries {
        let key = format!("ts:{:016}", ts);
        db.put(key.as_bytes(), &value).unwrap();
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase
    let ranges: Vec<(u64, u64)> = (0..100)
        .map(|i| {
            let start = i * (entries / 100);
            let end = start + 10_000;
            (start, end)
        })
        .collect();

    // Warmup
    for (start, end) in ranges.iter().take(10) {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let mut iter = db.iterator(rocksdb::IteratorMode::From(
            start_key.as_bytes(),
            rocksdb::Direction::Forward,
        ));
        while let Some(Ok((key, _))) = iter.next() {
            if key.as_ref() >= end_key.as_bytes() {
                break;
            }
        }
    }

    let read_start = Instant::now();
    for (start, end) in ranges.iter() {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let mut iter = db.iterator(rocksdb::IteratorMode::From(
            start_key.as_bytes(),
            rocksdb::Direction::Forward,
        ));
        while let Some(Ok((key, _))) = iter.next() {
            if key.as_ref() >= end_key.as_bytes() {
                break;
            }
        }
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_timeseries_fjall() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let config = FjallConfig::new(dir.path());
    let keyspace = config.open().unwrap();
    let partition = keyspace
        .open_partition("default", Default::default())
        .unwrap();

    let entries = 1_000_000;
    let value = vec![0u8; 64];

    // Write phase
    let write_start = Instant::now();
    for ts in 0..entries {
        let key = format!("ts:{:016}", ts);
        partition.insert(key.as_bytes(), &value).unwrap();
    }
    keyspace.persist(fjall::PersistMode::SyncAll).unwrap();
    let write_duration = write_start.elapsed();

    // Read phase
    let ranges: Vec<(u64, u64)> = (0..100)
        .map(|i| {
            let start = i * (entries / 100);
            let end = start + 10_000;
            (start, end)
        })
        .collect();

    // Warmup
    for (start, end) in ranges.iter().take(10) {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let mut iter = partition.range(start_key.as_bytes()..end_key.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }

    let read_start = Instant::now();
    for (start, end) in ranges.iter() {
        let start_key = format!("ts:{:016}", start);
        let end_key = format!("ts:{:016}", end);
        let mut iter = partition.range(start_key.as_bytes()..end_key.as_bytes());
        while let Some(Ok(_)) = iter.next() {}
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

// === Workload 3: Random KV (point lookups) ===

fn benchmark_random_seerdb() -> (Duration, Duration, f64) {
    let dir = tempdir().unwrap();
    let db = DBOptions::default()
        .memtable_capacity(64 * 1024 * 1024)
        .block_cache_capacity(16_384)
        .open(dir.path())
        .unwrap();

    // Setup: 500K random key-value pairs
    let entries = 500_000;
    let value = vec![0u8; 1024]; // 1KB values

    use rand::Rng;
    let mut rng = rand::thread_rng();
    let keys: Vec<String> = (0..entries)
        .map(|_| format!("key:{:016x}", rng.gen::<u64>()))
        .collect();

    // Write phase (random keys)
    let write_start = Instant::now();
    for key in keys.iter() {
        db.put(key.as_bytes(), &value).unwrap();
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase: Point lookups (random order)
    let mut read_keys = keys.clone();
    use rand::seq::SliceRandom;
    read_keys.shuffle(&mut rng);

    // Warmup
    for key in read_keys.iter().take(WARMUP_OPS) {
        let _ = db.get(key.as_bytes()).unwrap();
    }

    let read_start = Instant::now();
    for key in read_keys.iter().take(100_000) {
        let _ = db.get(key.as_bytes()).unwrap();
    }
    let read_duration = read_start.elapsed();

    let stats = db.stats();
    (write_duration, read_duration, stats.cache_hit_rate)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_random_rocksdb() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let mut opts = RocksDBOptions::default();
    opts.create_if_missing(true);
    opts.set_write_buffer_size(64 * 1024 * 1024);
    let db = RocksDBInstance::open(&opts, dir.path()).unwrap();

    let entries = 500_000;
    let value = vec![0u8; 1024];

    use rand::Rng;
    let mut rng = rand::thread_rng();
    let keys: Vec<String> = (0..entries)
        .map(|_| format!("key:{:016x}", rng.gen::<u64>()))
        .collect();

    // Write phase
    let write_start = Instant::now();
    for key in keys.iter() {
        db.put(key.as_bytes(), &value).unwrap();
    }
    db.flush().unwrap();
    let write_duration = write_start.elapsed();

    // Read phase
    let mut read_keys = keys.clone();
    use rand::seq::SliceRandom;
    read_keys.shuffle(&mut rng);

    // Warmup
    for key in read_keys.iter().take(WARMUP_OPS) {
        let _ = db.get(key.as_bytes()).unwrap();
    }

    let read_start = Instant::now();
    for key in read_keys.iter().take(100_000) {
        let _ = db.get(key.as_bytes()).unwrap();
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

#[cfg(feature = "baseline-benchmarks")]
fn benchmark_random_fjall() -> (Duration, Duration) {
    let dir = tempdir().unwrap();
    let config = FjallConfig::new(dir.path());
    let keyspace = config.open().unwrap();
    let partition = keyspace
        .open_partition("default", Default::default())
        .unwrap();

    let entries = 500_000;
    let value = vec![0u8; 1024];

    use rand::Rng;
    let mut rng = rand::thread_rng();
    let keys: Vec<String> = (0..entries)
        .map(|_| format!("key:{:016x}", rng.gen::<u64>()))
        .collect();

    // Write phase
    let write_start = Instant::now();
    for key in keys.iter() {
        partition.insert(key.as_bytes(), &value).unwrap();
    }
    keyspace.persist(fjall::PersistMode::SyncAll).unwrap();
    let write_duration = write_start.elapsed();

    // Read phase
    let mut read_keys = keys.clone();
    use rand::seq::SliceRandom;
    read_keys.shuffle(&mut rng);

    // Warmup
    for key in read_keys.iter().take(WARMUP_OPS) {
        let _ = partition.get(key.as_bytes()).unwrap();
    }

    let read_start = Instant::now();
    for key in read_keys.iter().take(100_000) {
        let _ = partition.get(key.as_bytes()).unwrap();
    }
    let read_duration = read_start.elapsed();

    (write_duration, read_duration)
}

fn main() {
    println!("=== Real Workload Comparisons - Phase 4 Profiling ===\n");
    println!("Workloads:");
    println!("1. Graph (HNSW): 10K nodes × 32 edges = 320K entries, 100 prefix scans");
    println!("2. Time series: 1M entries, 100 range queries (10K entries each)");
    println!("3. Random KV: 500K entries, 100K point lookups\n");

    // Workload 1: Graph pattern
    println!("=== Workload 1: Graph Pattern (HNSW Graph) ===\n");

    print!("seerdb... ");
    let (seer_write, seer_read, seer_cache) = benchmark_graph_seerdb();
    println!(
        "Write: {:.2}s, Read: {:.2}s, Cache: {:.2}%",
        seer_write.as_secs_f64(),
        seer_read.as_secs_f64(),
        seer_cache * 100.0
    );

    #[cfg(feature = "baseline-benchmarks")]
    {
        print!("RocksDB... ");
        let (rocks_write, rocks_read) = benchmark_graph_rocksdb();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            rocks_write.as_secs_f64(),
            rocks_read.as_secs_f64()
        );

        print!("fjall... ");
        let (fjall_write, fjall_read) = benchmark_random_fjall();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            fjall_write.as_secs_f64(),
            fjall_read.as_secs_f64()
        );

        println!(
            "\nSpeedup vs RocksDB: Write {:.2}x, Read {:.2}x",
            rocks_write.as_secs_f64() / seer_write.as_secs_f64(),
            rocks_read.as_secs_f64() / seer_read.as_secs_f64()
        );
        println!(
            "Speedup vs fjall: Write {:.2}x, Read {:.2}x\n",
            fjall_write.as_secs_f64() / seer_write.as_secs_f64(),
            fjall_read.as_secs_f64() / seer_read.as_secs_f64()
        );
    }

    // Workload 2: Time series
    println!("=== Workload 2: Time Series (Sequential Timestamps) ===\n");

    print!("seerdb... ");
    let (seer_write, seer_read, seer_cache) = benchmark_timeseries_seerdb();
    println!(
        "Write: {:.2}s, Read: {:.2}s, Cache: {:.2}%",
        seer_write.as_secs_f64(),
        seer_read.as_secs_f64(),
        seer_cache * 100.0
    );

    #[cfg(feature = "baseline-benchmarks")]
    {
        print!("RocksDB... ");
        let (rocks_write, rocks_read) = benchmark_timeseries_rocksdb();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            rocks_write.as_secs_f64(),
            rocks_read.as_secs_f64()
        );

        print!("fjall... ");
        let (fjall_write, fjall_read) = benchmark_timeseries_fjall();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            fjall_write.as_secs_f64(),
            fjall_read.as_secs_f64()
        );

        println!(
            "\nSpeedup vs RocksDB: Write {:.2}x, Read {:.2}x",
            rocks_write.as_secs_f64() / seer_write.as_secs_f64(),
            rocks_read.as_secs_f64() / seer_read.as_secs_f64()
        );
        println!(
            "Speedup vs fjall: Write {:.2}x, Read {:.2}x\n",
            fjall_write.as_secs_f64() / seer_write.as_secs_f64(),
            fjall_read.as_secs_f64() / seer_read.as_secs_f64()
        );
    }

    // Workload 3: Random KV
    println!("=== Workload 3: Random Key-Value (Point Lookups) ===\n");

    print!("seerdb... ");
    let (seer_write, seer_read, seer_cache) = benchmark_random_seerdb();
    println!(
        "Write: {:.2}s, Read: {:.2}s, Cache: {:.2}%",
        seer_write.as_secs_f64(),
        seer_read.as_secs_f64(),
        seer_cache * 100.0
    );

    #[cfg(feature = "baseline-benchmarks")]
    {
        print!("RocksDB... ");
        let (rocks_write, rocks_read) = benchmark_random_rocksdb();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            rocks_write.as_secs_f64(),
            rocks_read.as_secs_f64()
        );

        print!("fjall... ");
        let (fjall_write, fjall_read) = benchmark_random_fjall();
        println!(
            "Write: {:.2}s, Read: {:.2}s",
            fjall_write.as_secs_f64(),
            fjall_read.as_secs_f64()
        );

        println!(
            "\nSpeedup vs RocksDB: Write {:.2}x, Read {:.2}x",
            rocks_write.as_secs_f64() / seer_write.as_secs_f64(),
            rocks_read.as_secs_f64() / seer_read.as_secs_f64()
        );
        println!(
            "Speedup vs fjall: Write {:.2}x, Read {:.2}x",
            fjall_write.as_secs_f64() / seer_write.as_secs_f64(),
            fjall_read.as_secs_f64() / seer_read.as_secs_f64()
        );
    }

    println!("\n=== Phase 4 Profiling Complete ===");
    println!("\nRun with --features baseline-benchmarks to compare against RocksDB and fjall");
}