walrus-rust 0.2.0

A high-performance Write-Ahead Log (WAL) implementation in Rust
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
use rand::Rng;
use std::env;
use std::fs;
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Barrier};
use std::thread;
use std::time::{Duration, Instant};
use walrus_rust::wal::{FsyncSchedule, ReadConsistency, Walrus};

fn parse_thread_range() -> (usize, usize) {
    if let Ok(threads_env) = env::var("WALRUS_THREADS") {
        if let Some((start_str, end_str)) = threads_env.split_once('-') {
            if let (Ok(start), Ok(end)) = (start_str.parse::<usize>(), end_str.parse::<usize>()) {
                if start > 0 && end >= start && end <= 128 {
                    return (start, end);
                }
            }
        } else if let Ok(max_threads) = threads_env.parse::<usize>() {
            if max_threads > 0 && max_threads <= 128 {
                return (1, max_threads);
            }
        }
    }

    let args: Vec<String> = env::args().collect();

    for i in 0..args.len() {
        if args[i] == "--threads" && i + 1 < args.len() {
            let threads_arg = &args[i + 1];
            if let Some((start_str, end_str)) = threads_arg.split_once('-') {
                if let (Ok(start), Ok(end)) = (start_str.parse::<usize>(), end_str.parse::<usize>())
                {
                    if start > 0 && end >= start && end <= 128 {
                        return (start, end);
                    }
                }
            } else if let Ok(max_threads) = threads_arg.parse::<usize>() {
                if max_threads > 0 && max_threads <= 128 {
                    return (1, max_threads);
                }
            }
        }
    }

    (1, 10)
}

fn parse_fsync_schedule() -> FsyncSchedule {
    if let Ok(fsync_env) = env::var("WALRUS_FSYNC") {
        match fsync_env.as_str() {
            "sync-each" => return FsyncSchedule::SyncEach,
            "no-fsync" | "none" => return FsyncSchedule::NoFsync,
            "async" => return FsyncSchedule::Milliseconds(1000),
            ms_str if ms_str.ends_with("ms") => {
                if let Ok(ms) = ms_str[..ms_str.len() - 2].parse::<u64>() {
                    return FsyncSchedule::Milliseconds(ms);
                }
            }
            ms_str => {
                if let Ok(ms) = ms_str.parse::<u64>() {
                    return FsyncSchedule::Milliseconds(ms);
                }
            }
        }
    }

    let args: Vec<String> = env::args().collect();

    for i in 0..args.len() {
        if args[i] == "--fsync" && i + 1 < args.len() {
            match args[i + 1].as_str() {
                "sync-each" => return FsyncSchedule::SyncEach,
                "no-fsync" | "none" => return FsyncSchedule::NoFsync,
                "async" => return FsyncSchedule::Milliseconds(1000),
                ms_str if ms_str.ends_with("ms") => {
                    if let Ok(ms) = ms_str[..ms_str.len() - 2].parse::<u64>() {
                        return FsyncSchedule::Milliseconds(ms);
                    }
                }
                ms_str => {
                    if let Ok(ms) = ms_str.parse::<u64>() {
                        return FsyncSchedule::Milliseconds(ms);
                    }
                }
            }
        }
    }

    FsyncSchedule::Milliseconds(1000)
}

fn parse_batch_size() -> usize {
    if let Ok(batch_env) = env::var("WALRUS_BATCH_SIZE") {
        if let Ok(size) = batch_env.parse::<usize>() {
            if size > 0 && size <= 10_000 {
                return size;
            }
        }
    }

    let args: Vec<String> = env::args().collect();

    for i in 0..args.len() {
        if args[i] == "--batch-size" && i + 1 < args.len() {
            if let Ok(size) = args[i + 1].parse::<usize>() {
                if size > 0 && size <= 10_000 {
                    return size;
                }
            }
        }
    }

    256
}

fn parse_storage_backend() -> Option<String> {
    fn normalize(value: &str) -> Option<String> {
        match value.to_ascii_lowercase().as_str() {
            "fd" | "io_uring" | "uring" | "file" => Some("fd".to_string()),
            "mmap" | "memory" => Some("mmap".to_string()),
            _ => None,
        }
    }

    if let Ok(backend_env) = env::var("WALRUS_BACKEND") {
        if let Some(norm) = normalize(&backend_env) {
            return Some(norm);
        }
    }

    let args: Vec<String> = env::args().collect();
    for i in 0..args.len() {
        if args[i] == "--backend" && i + 1 < args.len() {
            if let Some(norm) = normalize(&args[i + 1]) {
                return Some(norm);
            }
        }
    }

    None
}

fn configure_storage_backend() {
    let selection = parse_storage_backend();
    #[cfg(target_os = "linux")]
    {
        match selection.as_deref() {
            Some("mmap") => {
                walrus_rust::disable_fd_backend();
                println!("Storage backend: mmap");
            }
            Some("fd") | Some("io_uring") | Some("uring") | Some("file") | None => {
                walrus_rust::enable_fd_backend();
                println!("Storage backend: fd");
            }
            Some(other) => {
                println!(
                    "Unknown storage backend '{}'; defaulting to fd (io_uring) backend.",
                    other
                );
                walrus_rust::enable_fd_backend();
            }
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        if let Some(choice) = selection {
            println!(
                "Storage backend '{}' requested, but only the mmap backend is available on this platform.",
                choice
            );
        }
    }
}

fn print_usage() {
    println!(
        "Usage: WALRUS_FSYNC=<schedule> WALRUS_THREADS=<range> WALRUS_BATCH_SIZE=<entries> WALRUS_BACKEND=<fd|mmap>"
    );
    println!(
        "       cargo test batch_scaling_benchmark -- --fsync <schedule> --threads <range> --batch-size <entries> --backend <fd|mmap>"
    );
    println!();
    println!("Fsync Schedule Options:");
    println!("  sync-each    Fsync after every write (slowest, most durable)");
    println!("  no-fsync     Disable fsyncing entirely (fastest, no durability)");
    println!("  none         Same as no-fsync");
    println!("  async        Async fsync every 1000ms (default)");
    println!("  <number>ms   Async fsync every N milliseconds (e.g., 500ms)");
    println!("  <number>     Async fsync every N milliseconds (e.g., 500)");
    println!();
    println!("Thread Range Options:");
    println!("  <number>     Test from 1 to N threads (e.g., 8 means 1-8)");
    println!("  <start-end>  Test from start to end threads (e.g., 2-16)");
    println!("  Default: 1-10 threads");
    println!();
    println!("Batch Size Options:");
    println!("  <number>     Entries per batch (1-10000, default: 256)");
    println!();
    println!("Storage Backend Options (Linux only):");
    println!("  fd           Use fd/io_uring backend (default)");
    println!("  mmap         Use memory-mapped backend");
    println!("  Set via WALRUS_BACKEND=<fd|mmap> or --backend <value>");
    println!();
    println!("Examples:");
    println!(
        "  WALRUS_FSYNC=sync-each WALRUS_THREADS=12 WALRUS_BATCH_SIZE=128 cargo test batch_scaling_benchmark"
    );
    println!("  WALRUS_THREADS=4-32 cargo test batch_scaling_benchmark -- --batch-size 512");
    println!("  make bench-batch-scaling  # Uses Makefile convenience target");
}

fn cleanup_wal() {
    let _ = fs::remove_dir_all("wal_files");
    let _ = fs::remove_file("wal_files/read_offset_idx_index.db");
    let _ = fs::remove_file("wal_files/read_offset_idx_index.db.tmp");
    thread::sleep(Duration::from_millis(200));
    std::hint::black_box(());
}

#[derive(Debug)]
struct BatchScalingResult {
    batches_per_sec: f64,
    entries_per_sec: f64,
    mb_per_sec: f64,
}

fn run_benchmark_with_threads(num_threads: usize, batch_size: usize) -> BatchScalingResult {
    cleanup_wal();

    unsafe {
        std::env::set_var("WALRUS_QUIET", "1");
    }

    thread::sleep(Duration::from_millis(100));

    let fsync_schedule = parse_fsync_schedule();
    let wal = Arc::new(
        Walrus::with_consistency_and_schedule(
            ReadConsistency::AtLeastOnce {
                persist_every: 5000,
            },
            fsync_schedule,
        )
        .expect("Failed to create Walrus"),
    );

    let test_duration = Duration::from_secs(30);

    let total_batches = Arc::new(AtomicU64::new(0));
    let total_entries = Arc::new(AtomicU64::new(0));
    let total_bytes = Arc::new(AtomicU64::new(0));
    let batch_errors = Arc::new(AtomicU64::new(0));

    let start_barrier = Arc::new(Barrier::new(num_threads + 1));
    let write_end_barrier = Arc::new(Barrier::new(num_threads + 1));
    let topics: Vec<String> = (0..num_threads)
        .map(|i| format!("batch_scaling_topic_{}", i))
        .collect();

    let mut handles = Vec::new();

    for thread_id in 0..num_threads {
        let wal_clone = Arc::clone(&wal);
        let total_batches_clone = Arc::clone(&total_batches);
        let total_entries_clone = Arc::clone(&total_entries);
        let total_bytes_clone = Arc::clone(&total_bytes);
        let batch_errors_clone = Arc::clone(&batch_errors);
        let start_barrier_clone = Arc::clone(&start_barrier);
        let write_end_barrier_clone = Arc::clone(&write_end_barrier);
        let topic = topics[thread_id].clone();

        let handle = thread::spawn(move || {
            start_barrier_clone.wait();

            let start_time = Instant::now();
            let mut rng = rand::thread_rng();
            let mut local_batches = 0u64;
            let mut local_entries = 0u64;
            let mut local_bytes = 0u64;
            let mut local_errors = 0u64;
            let mut counter = 0u64;

            while start_time.elapsed() < test_duration {
                let mut batch_data = Vec::with_capacity(batch_size);
                let mut batch_bytes = 0usize;

                for _ in 0..batch_size {
                    let size = rng.gen_range(500..=1024);
                    let byte = (counter & 0xFF) as u8;
                    batch_data.push(vec![byte; size]);
                    batch_bytes += size;
                    counter += 1;
                }

                let batch_refs: Vec<&[u8]> = batch_data.iter().map(|v| v.as_slice()).collect();

                match wal_clone.batch_append_for_topic(&topic, &batch_refs) {
                    Ok(_) => {
                        local_batches += 1;
                        local_entries += batch_size as u64;
                        local_bytes += batch_bytes as u64;

                        total_batches_clone.fetch_add(1, Ordering::Relaxed);
                        total_entries_clone.fetch_add(batch_size as u64, Ordering::Relaxed);
                        total_bytes_clone.fetch_add(batch_bytes as u64, Ordering::Relaxed);
                    }
                    Err(e) => {
                        local_errors += 1;
                        batch_errors_clone.fetch_add(1, Ordering::Relaxed);
                        if e.kind() == std::io::ErrorKind::WouldBlock {
                            thread::sleep(Duration::from_micros(500));
                        } else {
                            eprintln!("Thread {} batch error: {}", thread_id, e);
                        }
                    }
                }
            }

            println!(
                "Thread {}: {} batches, {} entries, {:.2} MB, {} errors",
                thread_id,
                local_batches,
                local_entries,
                local_bytes as f64 / (1024.0 * 1024.0),
                local_errors
            );

            write_end_barrier_clone.wait();
        });

        handles.push(handle);
    }

    let benchmark_start = Instant::now();
    start_barrier.wait();
    write_end_barrier.wait();
    let elapsed = benchmark_start.elapsed();

    for handle in handles {
        let _ = handle.join();
    }

    let batches = total_batches.load(Ordering::Relaxed);
    let entries = total_entries.load(Ordering::Relaxed);
    let bytes = total_bytes.load(Ordering::Relaxed);
    let errors = batch_errors.load(Ordering::Relaxed);

    println!(
        "{} threads summary: {} batches, {} entries, {:.2} MB, {} errors in {:?}",
        num_threads,
        batches,
        entries,
        bytes as f64 / (1024.0 * 1024.0),
        errors,
        elapsed
    );

    drop(wal);
    cleanup_wal();

    let seconds = elapsed.as_secs_f64().max(0.001);
    BatchScalingResult {
        batches_per_sec: batches as f64 / seconds,
        entries_per_sec: entries as f64 / seconds,
        mb_per_sec: (bytes as f64 / (1024.0 * 1024.0)) / seconds,
    }
}

#[test]
fn batch_scaling_benchmark() {
    let args: Vec<String> = env::args().collect();
    if args.iter().any(|arg| arg == "--help" || arg == "-h") {
        print_usage();
        return;
    }

    let fsync_schedule = parse_fsync_schedule();
    let (start_threads, end_threads) = parse_thread_range();
    let batch_size = parse_batch_size();

    configure_storage_backend();

    println!("=== WAL Batch Scaling Benchmark ===");
    println!(
        "Testing batch throughput scaling from {} to {} threads",
        start_threads, end_threads
    );
    println!(
        "Each test runs for 30 seconds with batch size {}",
        batch_size
    );
    println!("Fsync schedule: {:?}", fsync_schedule);
    println!();

    let mut results = Vec::new();

    for num_threads in start_threads..=end_threads {
        println!("Testing with {} thread(s)...", num_threads);
        let result = run_benchmark_with_threads(num_threads, batch_size);
        println!(
            "{} threads throughput: {:.0} entries/sec, {:.2} MB/sec ({:.1} batches/sec)",
            num_threads, result.entries_per_sec, result.mb_per_sec, result.batches_per_sec
        );
        println!();
        results.push((num_threads, result));
        thread::sleep(Duration::from_millis(800));
    }

    cleanup_wal();

    println!("=== Batch Scaling Results ===");
    println!("Threads | Entries/sec | MB/sec | Batches/sec");
    println!("--------|-------------|--------|-------------");
    for (threads, result) in &results {
        println!(
            "{:7} | {:11.0} | {:6.2} | {:11.1}",
            threads, result.entries_per_sec, result.mb_per_sec, result.batches_per_sec
        );
    }

    let csv_rows = results
        .iter()
        .map(|(threads, res)| {
            format!(
                "{},{:.0},{:.2},{:.1}",
                threads, res.entries_per_sec, res.mb_per_sec, res.batches_per_sec
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    let csv_data = format!(
        "threads,entries_per_second,mb_per_second,batches_per_second\n{}",
        csv_rows
    );
    fs::write("batch_scaling_results.csv", csv_data).expect("Failed to write batch scaling CSV");

    println!("\nResults saved to: batch_scaling_results.csv");
    println!("Run 'make show-batch-scaling' to visualize the scaling curve");

    let best = results
        .iter()
        .map(|(_, res)| res.entries_per_sec)
        .fold(0.0_f64, f64::max);
    let baseline = results
        .first()
        .map(|(_, res)| res.entries_per_sec)
        .unwrap_or(0.0);

    assert!(
        best > baseline,
        "Multi-threading should improve entries/sec throughput"
    );
    assert!(
        baseline > 10_000.0,
        "Single thread throughput too low: {:.0} entries/sec",
        baseline
    );

    println!(
        "Best entries throughput: {:.0} entries/sec ({:.1}x over single thread)",
        best,
        if baseline > 0.0 { best / baseline } else { 0.0 }
    );
}