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
use std::fmt;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;
use crate::engine::disk::{LogEntry, SyncDisk, VirtualDisk};
use crate::engine::log::LogWriter;
/// Unique identifier for a durability request batch.
pub type BatchId = u64;
/// Errors that can occur in the durability layer.
#[derive(Debug, Clone)]
pub enum DurabilityError {
/// Worker is not running (shutdown or never started).
WorkerNotRunning,
/// Channel to worker is disconnected.
ChannelDisconnected,
/// Worker thread panicked.
WorkerPanicked,
/// Empty batch submitted.
EmptyBatch,
}
impl fmt::Display for DurabilityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DurabilityError::WorkerNotRunning => write!(f, "DurabilityWorker is not running"),
DurabilityError::ChannelDisconnected => write!(f, "DurabilityWorker channel disconnected"),
DurabilityError::WorkerPanicked => write!(f, "DurabilityWorker thread panicked"),
DurabilityError::EmptyBatch => write!(f, "Cannot submit empty batch"),
}
}
}
impl std::error::Error for DurabilityError {}
/// Request sent to the DurabilityWorker.
#[derive(Debug)]
pub enum DurabilityRequest {
/// Append a batch of entries to the log.
AppendBatch {
/// Unique batch identifier for correlation.
batch_id: BatchId,
/// Payloads to append.
payloads: Vec<Vec<u8>>,
/// Consensus timestamp (nanoseconds since epoch).
timestamp_ns: u64,
/// Reserved start index (from handle's atomic reservation).
/// INVARIANT: Writer's next_index must equal this when processing.
reserved_start_index: u64,
},
/// Append a single entry to the log.
Append {
/// Unique batch identifier for correlation.
batch_id: BatchId,
/// Payload to append.
payload: Vec<u8>,
/// Stream ID for the entry.
stream_id: u64,
/// Flags for the entry.
flags: u16,
/// Consensus timestamp (nanoseconds since epoch).
timestamp_ns: u64,
/// Reserved index (from handle's atomic reservation).
/// INVARIANT: Writer's next_index must equal this when processing.
reserved_index: u64,
},
/// Shutdown the worker gracefully.
Shutdown,
}
/// Result of a durability operation.
#[derive(Debug, Clone)]
pub enum DurabilityResult {
/// Batch append succeeded.
BatchSuccess {
/// First index in the batch.
start_index: u64,
/// Last index in the batch.
last_index: u64,
},
/// Single append succeeded.
AppendSuccess {
/// Index of the appended entry.
index: u64,
},
/// Operation failed.
Error {
/// Error message.
message: String,
},
}
/// Completion notification from the DurabilityWorker.
#[derive(Debug, Clone)]
pub struct DurabilityCompletion {
/// Batch ID that completed.
pub batch_id: BatchId,
/// Result of the operation.
pub result: DurabilityResult,
}
/// Handle for submitting work to the DurabilityWorker.
///
/// This is the interface used by VsrNode to enqueue durability work
/// without blocking the control plane.
#[derive(Clone)]
pub struct DurabilityHandle {
/// Channel for sending requests to the worker.
request_tx: Sender<DurabilityRequest>,
/// Next batch ID to assign.
next_batch_id: Arc<AtomicU64>,
/// Whether the worker is running.
running: Arc<AtomicBool>,
/// Current next_index (speculative, updated on completion).
/// This allows VsrNode to know what indices will be assigned.
next_index: Arc<AtomicU64>,
}
impl DurabilityHandle {
/// Submit a batch of entries for durable append.
///
/// Returns immediately with the batch_id and predicted (start_index, last_index).
/// The actual completion will be delivered on the completion channel.
///
/// # Returns
/// - `Ok((batch_id, start_index, last_index))` - Request enqueued successfully
/// - `Err(DurabilityError)` - Worker is not running or channel is disconnected
pub fn submit_batch(
&self,
payloads: Vec<Vec<u8>>,
timestamp_ns: u64,
) -> Result<(BatchId, u64, u64), DurabilityError> {
if !self.running.load(Ordering::SeqCst) {
return Err(DurabilityError::WorkerNotRunning);
}
let batch_id = self.next_batch_id.fetch_add(1, Ordering::SeqCst);
let count = payloads.len() as u64;
// Reserve indices atomically
let start_index = self.next_index.fetch_add(count, Ordering::SeqCst);
let last_index = start_index + count - 1;
let request = DurabilityRequest::AppendBatch {
batch_id,
payloads,
timestamp_ns,
reserved_start_index: start_index,
};
self.request_tx
.send(request)
.map_err(|_| DurabilityError::ChannelDisconnected)?;
Ok((batch_id, start_index, last_index))
}
/// Submit a single entry for durable append.
///
/// Returns immediately with the batch_id and predicted index.
pub fn submit_single(
&self,
payload: Vec<u8>,
stream_id: u64,
flags: u16,
timestamp_ns: u64,
) -> Result<(BatchId, u64), DurabilityError> {
if !self.running.load(Ordering::SeqCst) {
return Err(DurabilityError::WorkerNotRunning);
}
let batch_id = self.next_batch_id.fetch_add(1, Ordering::SeqCst);
// Reserve index atomically
let index = self.next_index.fetch_add(1, Ordering::SeqCst);
let request = DurabilityRequest::Append {
batch_id,
payload,
stream_id,
flags,
timestamp_ns,
reserved_index: index,
};
self.request_tx
.send(request)
.map_err(|_| DurabilityError::ChannelDisconnected)?;
Ok((batch_id, index))
}
/// Request graceful shutdown of the worker.
pub fn shutdown(&self) -> Result<(), DurabilityError> {
self.running.store(false, Ordering::SeqCst);
self.request_tx
.send(DurabilityRequest::Shutdown)
.map_err(|_| DurabilityError::ChannelDisconnected)
}
/// Check if the worker is running.
pub fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
/// Get the current speculative next_index.
///
/// This is the index that will be assigned to the next entry.
/// Note: This may be ahead of what's actually durable.
pub fn next_index(&self) -> u64 {
self.next_index.load(Ordering::SeqCst)
}
}
/// The DurabilityWorker background thread.
///
/// Owns the LogWriter and processes durability requests in a dedicated thread.
pub struct DurabilityWorker {
/// Handle for submitting work.
handle: DurabilityHandle,
/// Channel for receiving completions.
completion_rx: Receiver<DurabilityCompletion>,
/// When true, the worker will pause before processing requests.
stall_flag: Arc<AtomicBool>,
/// Join handle for the worker thread.
thread_handle: Option<JoinHandle<()>>,
}
impl DurabilityWorker {
/// Create a new DurabilityWorker with a fresh log file.
///
/// # Arguments
/// * `log_path` - Path to the log file
/// * `view_id` - Initial view ID
///
/// # Returns
/// The worker instance with handle and completion receiver.
pub fn create(log_path: &Path, view_id: u64) -> std::io::Result<Self> {
let writer = LogWriter::create(log_path, view_id)?;
let next_index = writer.next_index();
Self::spawn_with_writer(writer, next_index)
}
/// Create a new DurabilityWorker with an existing log file (recovery).
///
/// # Arguments
/// * `log_path` - Path to the log file
/// * `next_index` - Next index to write (from recovery)
/// * `write_offset` - Offset to start writing (from recovery)
/// * `tail_hash` - Hash accumulator state (from recovery)
/// * `view_id` - Current view ID
pub fn open(
log_path: &Path,
next_index: u64,
write_offset: u64,
tail_hash: [u8; 16],
view_id: u64,
) -> std::io::Result<Self> {
let writer = LogWriter::open(log_path, next_index, write_offset, tail_hash, view_id)?;
Self::spawn_with_writer(writer, next_index)
}
/// Spawn the worker thread with an existing LogWriter.
fn spawn_with_writer(writer: LogWriter, initial_next_index: u64) -> std::io::Result<Self> {
let disk = Box::new(SyncDisk::new(writer));
Self::spawn_with_disk(disk, initial_next_index)
}
/// Spawn the worker thread with a VirtualDisk implementation.
///
/// This is the unified entry point that works with any disk backend.
pub fn spawn_with_disk(
disk: Box<dyn VirtualDisk>,
initial_next_index: u64,
) -> std::io::Result<Self> {
let (request_tx, request_rx) = mpsc::channel::<DurabilityRequest>();
let (completion_tx, completion_rx) = mpsc::channel::<DurabilityCompletion>();
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let stall_flag = Arc::new(AtomicBool::new(false));
let stall_flag_clone = stall_flag.clone();
let next_index = Arc::new(AtomicU64::new(initial_next_index));
let handle = DurabilityHandle {
request_tx,
next_batch_id: Arc::new(AtomicU64::new(0)),
running,
next_index,
};
// Spawn the worker thread
let thread_handle = thread::Builder::new()
.name("durability-worker".to_string())
.spawn(move || {
Self::disk_worker_loop(disk, request_rx, completion_tx, running_clone, stall_flag_clone);
})
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
Ok(DurabilityWorker {
handle,
completion_rx,
stall_flag,
thread_handle: Some(thread_handle),
})
}
/// The main worker loop using VirtualDisk - runs in a dedicated thread.
fn disk_worker_loop(
mut disk: Box<dyn VirtualDisk>,
request_rx: Receiver<DurabilityRequest>,
completion_tx: Sender<DurabilityCompletion>,
running: Arc<AtomicBool>,
stall_flag: Arc<AtomicBool>,
) {
// Transfer ownership of the disk to this thread.
disk.transfer_ownership();
while running.load(Ordering::SeqCst) {
match request_rx.recv() {
Ok(request) => {
if !matches!(request, DurabilityRequest::Shutdown) {
while stall_flag.load(Ordering::SeqCst) && running.load(Ordering::SeqCst) {
thread::sleep(Duration::from_millis(1));
}
}
let completion = Self::process_disk_request(disk.as_mut(), request);
// If shutdown, exit after processing
if completion.is_none() {
break;
}
if let Some(c) = completion {
// Send completion - if receiver is gone, just exit
if completion_tx.send(c).is_err() {
break;
}
}
}
Err(_) => {
// Channel disconnected - exit
break;
}
}
}
running.store(false, Ordering::SeqCst);
}
/// Process a single durability request using VirtualDisk.
///
/// Returns None for Shutdown, Some(completion) for other requests.
fn process_disk_request(
disk: &mut dyn VirtualDisk,
request: DurabilityRequest,
) -> Option<DurabilityCompletion> {
match request {
DurabilityRequest::AppendBatch {
batch_id,
payloads,
timestamp_ns,
reserved_start_index,
} => {
// INVARIANT: Reserved index must match disk's next_index
let disk_next_index = disk.next_index();
if disk_next_index != reserved_start_index {
panic!(
"FATAL: DurabilityWorker index mismatch! \
Reserved start_index={}, disk next_index={}. \
This indicates a bug in index reservation or requests processed out of order.",
reserved_start_index, disk_next_index
);
}
// Convert payloads to LogEntry format
let entries: Vec<LogEntry> = payloads
.into_iter()
.map(|p| LogEntry::new(p, timestamp_ns))
.collect();
let result = match disk.submit_write_batch(&entries) {
Ok(token) => DurabilityResult::BatchSuccess {
start_index: reserved_start_index,
last_index: token.index(),
},
Err(e) => DurabilityResult::Error {
message: e.to_string(),
},
};
Some(DurabilityCompletion { batch_id, result })
}
DurabilityRequest::Append {
batch_id,
payload,
stream_id,
flags,
timestamp_ns,
reserved_index,
} => {
// INVARIANT: Reserved index must match disk's next_index
let disk_next_index = disk.next_index();
if disk_next_index != reserved_index {
panic!(
"FATAL: DurabilityWorker index mismatch! \
Reserved index={}, disk next_index={}. \
This indicates a bug in index reservation or requests processed out of order.",
reserved_index, disk_next_index
);
}
let entry = LogEntry::with_metadata(payload, stream_id, flags, timestamp_ns);
let result = match disk.submit_write(entry) {
Ok(token) => DurabilityResult::AppendSuccess { index: token.index() },
Err(e) => DurabilityResult::Error {
message: e.to_string(),
},
};
Some(DurabilityCompletion { batch_id, result })
}
DurabilityRequest::Shutdown => None,
}
}
/// Get a clone of the handle for submitting work.
pub fn handle(&self) -> DurabilityHandle {
self.handle.clone()
}
/// Try to receive a completion without blocking.
///
/// Returns:
/// - `Ok(Some(completion))` - A completion is available
/// - `Ok(None)` - No completion available right now
/// - `Err(DurabilityError)` - Channel disconnected (worker died)
pub fn try_recv_completion(&self) -> Result<Option<DurabilityCompletion>, DurabilityError> {
match self.completion_rx.try_recv() {
Ok(completion) => Ok(Some(completion)),
Err(TryRecvError::Empty) => Ok(None),
Err(TryRecvError::Disconnected) => {
Err(DurabilityError::ChannelDisconnected)
}
}
}
/// Receive a completion, blocking until one is available.
///
/// Returns:
/// - `Ok(completion)` - A completion is available
/// - `Err(DurabilityError)` - Channel disconnected (worker died)
pub fn recv_completion(&self) -> Result<DurabilityCompletion, DurabilityError> {
self.completion_rx
.recv()
.map_err(|_| DurabilityError::ChannelDisconnected)
}
/// Drain all available completions without blocking.
///
/// Returns a vector of all completions that were ready.
pub fn drain_completions(&self) -> Vec<DurabilityCompletion> {
let mut completions = Vec::new();
while let Ok(Some(c)) = self.try_recv_completion() {
completions.push(c);
}
completions
}
/// Shutdown the worker and wait for it to finish.
pub fn shutdown_and_join(mut self) -> Result<(), DurabilityError> {
self.handle.shutdown()?;
if let Some(handle) = self.thread_handle.take() {
handle
.join()
.map_err(|_| DurabilityError::WorkerPanicked)?;
}
Ok(())
}
pub fn set_stalled(&self, stalled: bool) {
self.stall_flag.store(stalled, Ordering::SeqCst);
}
pub fn is_stalled(&self) -> bool {
self.stall_flag.load(Ordering::SeqCst)
}
/// Check if the worker is still running.
pub fn is_running(&self) -> bool {
self.handle.is_running()
}
}
impl Drop for DurabilityWorker {
fn drop(&mut self) {
// Signal shutdown
let _ = self.handle.shutdown();
// Wait for thread to finish
if let Some(handle) = self.thread_handle.take() {
let _ = handle.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use tempfile::tempdir;
#[test]
fn test_durability_worker_basic() {
let dir = tempdir().unwrap();
let log_path = dir.path().join("test.log");
let worker = DurabilityWorker::create(&log_path, 0).unwrap();
let handle = worker.handle();
// Submit a batch
let payloads = vec![b"hello".to_vec(), b"world".to_vec()];
let (batch_id, start_idx, last_idx) = handle
.submit_batch(payloads, 12345)
.unwrap();
assert_eq!(batch_id, 0);
assert_eq!(start_idx, 0);
assert_eq!(last_idx, 1);
// Wait for completion
let completion = worker.recv_completion().unwrap();
assert_eq!(completion.batch_id, 0);
match completion.result {
DurabilityResult::BatchSuccess { start_index, last_index } => {
assert_eq!(start_index, 0);
assert_eq!(last_index, 1);
}
_ => panic!("Expected BatchSuccess"),
}
// Shutdown
worker.shutdown_and_join().unwrap();
}
#[test]
fn test_durability_worker_single_append() {
let dir = tempdir().unwrap();
let log_path = dir.path().join("test.log");
let worker = DurabilityWorker::create(&log_path, 0).unwrap();
let handle = worker.handle();
// Submit single entries
let (batch_id1, idx1) = handle
.submit_single(b"entry1".to_vec(), 0, 0, 1000)
.unwrap();
let (batch_id2, idx2) = handle
.submit_single(b"entry2".to_vec(), 0, 0, 2000)
.unwrap();
assert_eq!(idx1, 0);
assert_eq!(idx2, 1);
// Wait for completions
let c1 = worker.recv_completion().unwrap();
let c2 = worker.recv_completion().unwrap();
assert_eq!(c1.batch_id, batch_id1);
assert_eq!(c2.batch_id, batch_id2);
worker.shutdown_and_join().unwrap();
}
#[test]
fn test_durability_worker_multiple_batches() {
let dir = tempdir().unwrap();
let log_path = dir.path().join("test.log");
let worker = DurabilityWorker::create(&log_path, 0).unwrap();
let handle = worker.handle();
// Submit multiple batches
let (_, start1, last1) = handle
.submit_batch(vec![b"a".to_vec(), b"b".to_vec()], 1000)
.unwrap();
let (_, start2, last2) = handle
.submit_batch(vec![b"c".to_vec(), b"d".to_vec(), b"e".to_vec()], 2000)
.unwrap();
assert_eq!(start1, 0);
assert_eq!(last1, 1);
assert_eq!(start2, 2);
assert_eq!(last2, 4);
// Drain completions
std::thread::sleep(Duration::from_millis(50));
let completions = worker.drain_completions();
assert_eq!(completions.len(), 2);
worker.shutdown_and_join().unwrap();
}
#[test]
fn test_durability_worker_handle_clone() {
let dir = tempdir().unwrap();
let log_path = dir.path().join("test.log");
let worker = DurabilityWorker::create(&log_path, 0).unwrap();
let handle1 = worker.handle();
let handle2 = handle1.clone();
// Both handles should work
let (_, idx1, _) = handle1
.submit_batch(vec![b"from_handle1".to_vec()], 1000)
.unwrap();
let (_, idx2, _) = handle2
.submit_batch(vec![b"from_handle2".to_vec()], 2000)
.unwrap();
assert_eq!(idx1, 0);
assert_eq!(idx2, 1);
worker.shutdown_and_join().unwrap();
}
#[test]
fn test_durability_worker_shutdown_rejects_new_work() {
let dir = tempdir().unwrap();
let log_path = dir.path().join("test.log");
let worker = DurabilityWorker::create(&log_path, 0).unwrap();
let handle = worker.handle();
// Shutdown
handle.shutdown().unwrap();
// New submissions should fail
std::thread::sleep(Duration::from_millis(10));
let result = handle.submit_batch(vec![b"should_fail".to_vec()], 1000);
assert!(result.is_err());
}
}