d-engine-server 0.2.3

Production-ready Raft consensus engine server and runtime
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
//! State Machine Performance Benchmarks
//!
//! This benchmark suite measures the core performance characteristics of the state machine,
//! focusing on the overhead introduced by TTL functionality and Watch mechanism.
//!
//! Performance Targets:
//! - Without TTL: < 10ns overhead per operation
//! - With TTL passive check: < 50ns overhead per read
//! - Watch overhead on Apply path: < 0.01% (< 10ns per watcher)
//! - End-to-end Watch notification latency: < 100µs
//! - Batch operations: Linear scaling

use bytes::Bytes;
use criterion::BenchmarkId;
use criterion::Criterion;
use criterion::black_box;
use criterion::criterion_group;
use criterion::criterion_main;
use d_engine_core::StateMachine;
use d_engine_core::watch::WatchDispatcher;
use d_engine_core::watch::WatchRegistry;
use d_engine_core::watch::WatcherHandle;
use d_engine_proto::client::WriteCommand;
use d_engine_proto::client::write_command::Insert;
use d_engine_proto::client::write_command::Operation;
use d_engine_proto::common::Entry;
use d_engine_proto::common::EntryPayload;
use d_engine_proto::common::entry_payload::Payload;
use d_engine_server::storage::FileStateMachine;
use prost::Message;
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use tokio::sync::broadcast;
use tokio::sync::mpsc;

/// Helper to create a temporary state machine for benchmarking
async fn create_test_state_machine() -> (FileStateMachine, TempDir) {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let mut sm = FileStateMachine::new(temp_dir.path().to_path_buf())
        .await
        .expect("Failed to create state machine");

    // Enable TTL for benchmarks that need it
    let lease_config = d_engine_core::config::LeaseConfig {
        enabled: true,
        interval_ms: 1000,
        max_cleanup_duration_ms: 1,
    };
    let lease = Arc::new(d_engine_server::storage::DefaultLease::new(lease_config));
    sm.set_lease(lease);

    (sm, temp_dir)
}

/// Helper to create a WatchRegistry + WatchDispatcher for benchmarking
fn create_watch_system(
    event_queue_size: usize,
    watcher_buffer_size: usize,
) -> (
    Arc<WatchRegistry>,
    broadcast::Sender<d_engine_proto::client::WatchResponse>,
) {
    let (broadcast_tx, broadcast_rx) = broadcast::channel(event_queue_size);
    let (unregister_tx, unregister_rx) = mpsc::unbounded_channel();

    let registry = Arc::new(WatchRegistry::new(watcher_buffer_size, unregister_tx));

    // Spawn dispatcher
    let dispatcher = WatchDispatcher::new(Arc::clone(&registry), broadcast_rx, unregister_rx);
    tokio::spawn(async move {
        dispatcher.run().await;
    });

    (registry, broadcast_tx)
}

/// Helper to register multiple watchers
///
/// Returns the watcher handles to keep watchers alive during benchmarks.
/// Handles must be kept in scope or watchers will be immediately unregistered.
fn register_watchers(
    registry: &WatchRegistry,
    count: usize,
    key_prefix: &str,
) -> Vec<WatcherHandle> {
    let mut handles = Vec::with_capacity(count);
    for i in 0..count {
        let key = format!("{key_prefix}{i}");
        handles.push(registry.register(key.into()));
    }
    handles
}

/// Helper to create write entries without TTL
fn create_entries_without_ttl(
    count: usize,
    start_index: u64,
) -> Vec<Entry> {
    (0..count)
        .map(|i| {
            let key = format!("key_{}", start_index + i as u64);
            let value = format!("value_{}", start_index + i as u64);

            let insert = Insert {
                key: Bytes::from(key),
                value: Bytes::from(value),
                ttl_secs: 0,
            };
            let write_cmd = WriteCommand {
                operation: Some(Operation::Insert(insert)),
            };
            let payload = Payload::Command(write_cmd.encode_to_vec().into());

            Entry {
                index: start_index + i as u64,
                term: 1,
                payload: Some(EntryPayload {
                    payload: Some(payload),
                }),
            }
        })
        .collect()
}

/// Helper to create write entries with TTL
fn create_entries_with_ttl(
    count: usize,
    start_index: u64,
    ttl_secs: u64,
) -> Vec<Entry> {
    (0..count)
        .map(|i| {
            let key = format!("key_ttl_{}", start_index + i as u64);
            let value = format!("value_ttl_{}", start_index + i as u64);

            let insert = Insert {
                key: Bytes::from(key),
                value: Bytes::from(value),
                ttl_secs,
            };
            let write_cmd = WriteCommand {
                operation: Some(Operation::Insert(insert)),
            };
            let payload = Payload::Command(write_cmd.encode_to_vec().into());

            Entry {
                index: start_index + i as u64,
                term: 1,
                payload: Some(EntryPayload {
                    payload: Some(payload),
                }),
            }
        })
        .collect()
}

/// Benchmark: Apply operations WITHOUT TTL
/// Target: < 10ns overhead per operation
fn bench_apply_without_ttl(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_without_ttl", |b| {
        b.to_async(&runtime).iter(|| async {
            let entries = create_entries_without_ttl(1, 1);

            // Measure pure apply performance
            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: Apply operations WITH TTL
/// This measures the overhead of registering TTL entries
fn bench_apply_with_ttl(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_with_ttl", |b| {
        b.to_async(&runtime).iter(|| async {
            let entries = create_entries_with_ttl(1, 1, 3600); // 1 hour TTL

            // Measure apply with TTL registration
            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: Get operation WITHOUT TTL data
/// Baseline for read performance
fn bench_get_without_ttl(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    // Setup state machine once before benchmark
    let (sm, _temp_dir) = runtime.block_on(async {
        let (sm, temp_dir) = create_test_state_machine().await;
        let entries = create_entries_without_ttl(100, 1);
        sm.apply_chunk(entries).await.unwrap();
        (sm, temp_dir)
    });

    c.bench_function("get_without_ttl", |b| {
        b.iter(|| {
            // Measure pure read performance (synchronous get)
            let key = b"key_50";
            black_box(sm.get(key).unwrap());
        });
    });
}

/// Benchmark: Get operation WITH TTL passive check
/// Target: < 50ns overhead compared to non-TTL reads
fn bench_get_with_ttl_check(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    // Setup state machine once before benchmark
    let (sm, _temp_dir) = runtime.block_on(async {
        let (sm, temp_dir) = create_test_state_machine().await;
        let entries = create_entries_with_ttl(100, 1, 3600); // Long TTL
        sm.apply_chunk(entries).await.unwrap();
        (sm, temp_dir)
    });

    c.bench_function("get_with_ttl_check", |b| {
        b.iter(|| {
            // Measure read with TTL check (synchronous get)
            let key = b"key_ttl_50";
            black_box(sm.get(key).unwrap());
        });
    });
}

/// Benchmark: Get operation with EXPIRED TTL entry
/// This measures the cost of passive deletion
fn bench_get_expired_ttl(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    // Setup state machine once before benchmark
    let (sm, _temp_dir) = runtime.block_on(async {
        let (sm, temp_dir) = create_test_state_machine().await;
        let entries = create_entries_with_ttl(100, 1, 1); // 1 second TTL
        sm.apply_chunk(entries).await.unwrap();

        // Wait for expiration
        tokio::time::sleep(Duration::from_secs(2)).await;

        (sm, temp_dir)
    });

    c.bench_function("get_expired_ttl", |b| {
        b.iter(|| {
            // Measure read with expired entry (should trigger passive deletion)
            let key = b"key_ttl_50";
            black_box(sm.get(key).unwrap());
        });
    });
}

/// Benchmark: Batch apply operations (scaling test)
/// Verify that performance scales linearly with batch size
fn bench_batch_apply(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
    let mut group = c.benchmark_group("batch_apply");

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    for size in [10, 100, 1000].iter() {
        group.bench_with_input(BenchmarkId::from_parameter(size), size, |b, &size| {
            b.to_async(&runtime).iter(|| async {
                let entries = create_entries_without_ttl(size, 1);

                sm.apply_chunk(entries).await.unwrap();
                black_box(());
            });
        });
    }

    group.finish();
}

/// Benchmark: Batch apply with TTL (scaling test)
fn bench_batch_apply_with_ttl(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
    let mut group = c.benchmark_group("batch_apply_with_ttl");

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    for size in [10, 100, 1000].iter() {
        group.bench_with_input(BenchmarkId::from_parameter(size), size, |b, &size| {
            b.to_async(&runtime).iter(|| async {
                let entries = create_entries_with_ttl(size, 1, 3600);

                sm.apply_chunk(entries).await.unwrap();
                black_box(());
            });
        });
    }

    group.finish();
}

/// Benchmark: Apply operations WITHOUT Watch (baseline)
/// Target: Establish baseline performance
fn bench_apply_without_watch(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    // Initialize state machine once outside the iteration loop
    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_without_watch", |b| {
        b.to_async(&runtime).iter(|| async {
            let entries = create_entries_without_ttl(100, 1);

            // Measure pure apply performance without watch
            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: Apply operations WITH 1 watcher
/// Target: < 10ns overhead compared to baseline
fn bench_apply_with_1_watcher(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_with_1_watcher", |b| {
        b.to_async(&runtime).iter(|| async {
            let (registry, broadcast_tx) = create_watch_system(1000, 10);

            // Register 1 watcher (keep handle alive to prevent unregistration)
            let _watchers = register_watchers(&registry, 1, "key_");

            let entries = create_entries_without_ttl(100, 1);

            // Simulate notify_watchers call for each entry
            for entry in &entries {
                if let Some(payload) = &entry.payload {
                    if let Some(Payload::Command(cmd_bytes)) = &payload.payload {
                        if let Ok(write_cmd) = WriteCommand::decode(cmd_bytes.as_ref()) {
                            if let Some(op) = write_cmd.operation {
                                match op {
                                    Operation::Insert(insert) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: insert.key.clone(),
                                            value: insert.value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::Delete(delete) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: delete.key.clone(),
                                            value: bytes::Bytes::new(),
                                            event_type:
                                                d_engine_proto::client::WatchEventType::Delete
                                                    as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::CompareAndSwap(cas) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: cas.key.clone(),
                                            value: cas.new_value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: Apply operations WITH 10 watchers
/// Target: < 100ns overhead compared to baseline
fn bench_apply_with_10_watchers(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_with_10_watchers", |b| {
        b.to_async(&runtime).iter(|| async {
            let (registry, broadcast_tx) = create_watch_system(1000, 10);

            // Register 10 watchers (keep handles alive to prevent unregistration)
            let _watchers = register_watchers(&registry, 10, "key_");

            let entries = create_entries_without_ttl(100, 1);

            // Simulate notify_watchers call for each entry
            for entry in &entries {
                if let Some(payload) = &entry.payload {
                    if let Some(Payload::Command(cmd_bytes)) = &payload.payload {
                        if let Ok(write_cmd) = WriteCommand::decode(cmd_bytes.as_ref()) {
                            if let Some(op) = write_cmd.operation {
                                match op {
                                    Operation::Insert(insert) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: insert.key.clone(),
                                            value: insert.value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::Delete(delete) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: delete.key.clone(),
                                            value: bytes::Bytes::new(),
                                            event_type:
                                                d_engine_proto::client::WatchEventType::Delete
                                                    as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::CompareAndSwap(cas) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: cas.key.clone(),
                                            value: cas.new_value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: Apply operations WITH 100 watchers
/// Target: < 1µs overhead compared to baseline
fn bench_apply_with_100_watchers(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    let (sm, _temp_dir) = runtime.block_on(async { create_test_state_machine().await });

    c.bench_function("apply_with_100_watchers", |b| {
        b.to_async(&runtime).iter(|| async {
            let (registry, broadcast_tx) = create_watch_system(1000, 10);

            // Register 100 watchers (keep handles alive to prevent unregistration)
            let _watchers = register_watchers(&registry, 100, "key_");

            let entries = create_entries_without_ttl(100, 1);

            // Simulate notify_watchers call for each entry
            for entry in &entries {
                if let Some(payload) = &entry.payload {
                    if let Some(Payload::Command(cmd_bytes)) = &payload.payload {
                        if let Ok(write_cmd) = WriteCommand::decode(cmd_bytes.as_ref()) {
                            if let Some(op) = write_cmd.operation {
                                match op {
                                    Operation::Insert(insert) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: insert.key.clone(),
                                            value: insert.value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::Delete(delete) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: delete.key.clone(),
                                            value: bytes::Bytes::new(),
                                            event_type:
                                                d_engine_proto::client::WatchEventType::Delete
                                                    as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                    Operation::CompareAndSwap(cas) => {
                                        let event = d_engine_proto::client::WatchResponse {
                                            key: cas.key.clone(),
                                            value: cas.new_value.clone(),
                                            event_type: d_engine_proto::client::WatchEventType::Put
                                                as i32,
                                            error: 0,
                                        };
                                        let _ = broadcast_tx.send(event);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sm.apply_chunk(entries).await.unwrap();
            black_box(());
        });
    });
}

/// Benchmark: End-to-end Watch notification latency
/// Target: < 100µs from notify to receiver
fn bench_watch_e2e_latency(c: &mut Criterion) {
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();

    c.bench_function("watch_e2e_latency", |b| {
        b.to_async(&runtime).iter(|| async {
            let (registry, broadcast_tx) = create_watch_system(1000, 10);

            let key = Bytes::from("test_key");
            let value = Bytes::from("test_value");

            // Register a watcher
            let mut watcher = registry.register(key.clone());

            // Measure time from broadcast to receive
            let start = tokio::time::Instant::now();

            // Simulate watch event broadcast
            let event = d_engine_proto::client::WatchResponse {
                key: key.clone(),
                value: value.clone(),
                event_type: d_engine_proto::client::WatchEventType::Put as i32,
                error: 0, // No error
            };
            let _ = broadcast_tx.send(event);

            // Wait for event to arrive at watcher
            if let Some(_event) = watcher.receiver_mut().recv().await {
                let latency = start.elapsed();
                black_box(latency);
            }
        });
    });
}

criterion_group!(
    benches,
    bench_apply_without_ttl,
    bench_apply_with_ttl,
    bench_get_without_ttl,
    bench_get_with_ttl_check,
    bench_get_expired_ttl,
    bench_batch_apply,
    bench_batch_apply_with_ttl,
    bench_apply_without_watch,
    bench_apply_with_1_watcher,
    bench_apply_with_10_watchers,
    bench_apply_with_100_watchers,
    bench_watch_e2e_latency,
);

criterion_main!(benches);