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
//! WAL entry types with epoch-based ordering for per-core WAL.
use std::cmp::Ordering;
#[allow(clippy::disallowed_types)] // cold path: WAL coordination
use std::collections::HashMap;
// WAL entry types with derive macros
mod entry_types {
#![allow(missing_docs)] // Allow for derive-generated code
#[allow(clippy::disallowed_types)] // cold path: WAL coordination
use std::collections::HashMap;
use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
/// Operations that can be logged in the WAL.
#[derive(Debug, Clone, PartialEq, Eq, Archive, RkyvSerialize, RkyvDeserialize)]
pub enum WalOperation {
/// Put a key-value pair.
Put {
/// The key.
key: Vec<u8>,
/// The value.
value: Vec<u8>,
},
/// Delete a key.
Delete {
/// The key to delete.
key: Vec<u8>,
},
/// Checkpoint marker.
Checkpoint {
/// Checkpoint ID.
id: u64,
},
/// Commit offsets for exactly-once semantics.
Commit {
/// Map of topic/partition to offset.
offsets: HashMap<String, u64>,
/// Current watermark at commit time.
watermark: Option<i64>,
},
/// Barrier for epoch boundary.
EpochBarrier {
/// The epoch that just completed.
epoch: u64,
},
}
/// Per-core WAL entry with epoch for cross-core ordering.
///
/// Entries are ordered by (epoch, `timestamp_ns`) for deterministic recovery.
/// The 32-byte compact layout is designed for cache efficiency.
#[derive(Debug, Clone, PartialEq, Eq, Archive, RkyvSerialize, RkyvDeserialize)]
pub struct PerCoreWalEntry {
/// Global epoch (for ordering during recovery).
pub epoch: u64,
/// Core-local sequence number (monotonically increasing per core).
pub sequence: u64,
/// Core ID that wrote this entry.
pub core_id: u16,
/// Timestamp in nanoseconds since Unix epoch.
pub timestamp_ns: i64,
/// The actual operation.
pub operation: WalOperation,
}
}
pub use entry_types::{PerCoreWalEntry, WalOperation};
impl PerCoreWalEntry {
/// Creates a new Put entry.
///
/// # Arguments
///
/// * `timestamp_ns` - Pre-cached timestamp from [`now_ns()`](Self::now_ns)
#[must_use]
pub fn put(
core_id: u16,
epoch: u64,
sequence: u64,
key: Vec<u8>,
value: Vec<u8>,
timestamp_ns: i64,
) -> Self {
Self {
epoch,
sequence,
core_id,
timestamp_ns,
operation: WalOperation::Put { key, value },
}
}
/// Creates a new Delete entry.
///
/// # Arguments
///
/// * `timestamp_ns` - Pre-cached timestamp from [`now_ns()`](Self::now_ns)
#[must_use]
pub fn delete(
core_id: u16,
epoch: u64,
sequence: u64,
key: Vec<u8>,
timestamp_ns: i64,
) -> Self {
Self {
epoch,
sequence,
core_id,
timestamp_ns,
operation: WalOperation::Delete { key },
}
}
/// Creates a new Checkpoint entry.
///
/// # Arguments
///
/// * `timestamp_ns` - Pre-cached timestamp from [`now_ns()`](Self::now_ns)
#[must_use]
pub fn checkpoint(
core_id: u16,
epoch: u64,
sequence: u64,
checkpoint_id: u64,
timestamp_ns: i64,
) -> Self {
Self {
epoch,
sequence,
core_id,
timestamp_ns,
operation: WalOperation::Checkpoint { id: checkpoint_id },
}
}
/// Creates a new Commit entry.
///
/// # Arguments
///
/// * `timestamp_ns` - Pre-cached timestamp from [`now_ns()`](Self::now_ns)
#[must_use]
pub fn commit(
core_id: u16,
epoch: u64,
sequence: u64,
offsets: HashMap<String, u64>,
watermark: Option<i64>,
timestamp_ns: i64,
) -> Self {
Self {
epoch,
sequence,
core_id,
timestamp_ns,
operation: WalOperation::Commit { offsets, watermark },
}
}
/// Creates a new `EpochBarrier` entry.
///
/// # Arguments
///
/// * `timestamp_ns` - Pre-cached timestamp from [`now_ns()`](Self::now_ns)
#[must_use]
pub fn epoch_barrier(core_id: u16, epoch: u64, sequence: u64, timestamp_ns: i64) -> Self {
Self {
epoch,
sequence,
core_id,
timestamp_ns,
operation: WalOperation::EpochBarrier { epoch },
}
}
/// Returns true if this is a Put operation.
#[must_use]
pub fn is_put(&self) -> bool {
matches!(self.operation, WalOperation::Put { .. })
}
/// Returns true if this is a Delete operation.
#[must_use]
pub fn is_delete(&self) -> bool {
matches!(self.operation, WalOperation::Delete { .. })
}
/// Returns true if this is a Checkpoint operation.
#[must_use]
pub fn is_checkpoint(&self) -> bool {
matches!(self.operation, WalOperation::Checkpoint { .. })
}
/// Returns true if this is a state-modifying operation (Put or Delete).
#[must_use]
pub fn is_state_operation(&self) -> bool {
self.is_put() || self.is_delete()
}
/// Gets the key if this is a Put or Delete operation.
#[must_use]
pub fn key(&self) -> Option<&[u8]> {
match &self.operation {
WalOperation::Put { key, .. } | WalOperation::Delete { key } => Some(key),
_ => None,
}
}
/// Gets the value if this is a Put operation.
#[must_use]
pub fn value(&self) -> Option<&[u8]> {
match &self.operation {
WalOperation::Put { value, .. } => Some(value),
_ => None,
}
}
/// Returns current timestamp in nanoseconds.
///
/// Call once and pass the result to entry constructors to avoid
/// repeated `SystemTime::now()` syscalls in tight loops.
#[must_use]
#[allow(clippy::cast_possible_truncation)] // i64 ns won't overflow for ~292 years
pub fn now_ns() -> i64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64)
}
}
impl Ord for PerCoreWalEntry {
fn cmp(&self, other: &Self) -> Ordering {
// Order by epoch first, then by timestamp within epoch
match self.epoch.cmp(&other.epoch) {
Ordering::Equal => {
// Within same epoch, order by timestamp
match self.timestamp_ns.cmp(&other.timestamp_ns) {
Ordering::Equal => {
// Tie-breaker: use core_id then sequence
match self.core_id.cmp(&other.core_id) {
Ordering::Equal => self.sequence.cmp(&other.sequence),
ord => ord,
}
}
ord => ord,
}
}
ord => ord,
}
}
}
impl PartialOrd for PerCoreWalEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_entry_ordering_by_epoch() {
let e1 = PerCoreWalEntry {
epoch: 1,
sequence: 100,
core_id: 0,
timestamp_ns: 1000,
operation: WalOperation::Put {
key: vec![1],
value: vec![1],
},
};
let e2 = PerCoreWalEntry {
epoch: 2,
sequence: 1,
core_id: 1,
timestamp_ns: 500, // Earlier timestamp but later epoch
operation: WalOperation::Put {
key: vec![2],
value: vec![2],
},
};
assert!(e1 < e2); // Epoch takes precedence
}
#[test]
fn test_entry_ordering_by_timestamp() {
let e1 = PerCoreWalEntry {
epoch: 1,
sequence: 1,
core_id: 0,
timestamp_ns: 1000,
operation: WalOperation::Put {
key: vec![1],
value: vec![1],
},
};
let e2 = PerCoreWalEntry {
epoch: 1,
sequence: 2,
core_id: 1,
timestamp_ns: 2000,
operation: WalOperation::Put {
key: vec![2],
value: vec![2],
},
};
assert!(e1 < e2); // Same epoch, timestamp determines order
}
#[test]
fn test_entry_ordering_tiebreaker() {
let e1 = PerCoreWalEntry {
epoch: 1,
sequence: 1,
core_id: 0,
timestamp_ns: 1000,
operation: WalOperation::Put {
key: vec![1],
value: vec![1],
},
};
let e2 = PerCoreWalEntry {
epoch: 1,
sequence: 2,
core_id: 1,
timestamp_ns: 1000, // Same timestamp
operation: WalOperation::Put {
key: vec![2],
value: vec![2],
},
};
assert!(e1 < e2); // Same epoch and timestamp, core_id determines order
}
#[test]
fn test_entry_constructors() {
let ts = PerCoreWalEntry::now_ns();
let put = PerCoreWalEntry::put(0, 1, 1, b"key".to_vec(), b"value".to_vec(), ts);
assert!(put.is_put());
assert!(!put.is_delete());
assert_eq!(put.key(), Some(b"key".as_slice()));
assert_eq!(put.value(), Some(b"value".as_slice()));
let delete = PerCoreWalEntry::delete(1, 1, 2, b"key2".to_vec(), ts);
assert!(delete.is_delete());
assert!(!delete.is_put());
assert_eq!(delete.key(), Some(b"key2".as_slice()));
assert!(delete.value().is_none());
let checkpoint = PerCoreWalEntry::checkpoint(0, 1, 3, 100, ts);
assert!(checkpoint.is_checkpoint());
assert!(!checkpoint.is_state_operation());
}
#[test]
fn test_sorting_multiple_entries() {
let mut entries = [
PerCoreWalEntry {
epoch: 2,
sequence: 1,
core_id: 0,
timestamp_ns: 100,
operation: WalOperation::Put {
key: vec![1],
value: vec![1],
},
},
PerCoreWalEntry {
epoch: 1,
sequence: 2,
core_id: 1,
timestamp_ns: 200,
operation: WalOperation::Put {
key: vec![2],
value: vec![2],
},
},
PerCoreWalEntry {
epoch: 1,
sequence: 1,
core_id: 0,
timestamp_ns: 100,
operation: WalOperation::Put {
key: vec![3],
value: vec![3],
},
},
PerCoreWalEntry {
epoch: 2,
sequence: 2,
core_id: 1,
timestamp_ns: 200,
operation: WalOperation::Put {
key: vec![4],
value: vec![4],
},
},
];
entries.sort();
// Check ordering: epoch 1 entries first (by timestamp), then epoch 2 entries
assert_eq!(entries[0].epoch, 1);
assert_eq!(entries[0].timestamp_ns, 100);
assert_eq!(entries[1].epoch, 1);
assert_eq!(entries[1].timestamp_ns, 200);
assert_eq!(entries[2].epoch, 2);
assert_eq!(entries[2].timestamp_ns, 100);
assert_eq!(entries[3].epoch, 2);
assert_eq!(entries[3].timestamp_ns, 200);
}
#[test]
fn test_commit_entry() {
let mut offsets = HashMap::new();
offsets.insert("topic1".to_string(), 100);
offsets.insert("topic2".to_string(), 200);
let commit =
PerCoreWalEntry::commit(0, 1, 1, offsets, Some(12345), PerCoreWalEntry::now_ns());
match &commit.operation {
WalOperation::Commit { offsets, watermark } => {
assert_eq!(offsets.get("topic1"), Some(&100));
assert_eq!(offsets.get("topic2"), Some(&200));
assert_eq!(*watermark, Some(12345));
}
_ => panic!("Expected Commit operation"),
}
}
#[test]
fn test_epoch_barrier_entry() {
let barrier = PerCoreWalEntry::epoch_barrier(0, 5, 100, PerCoreWalEntry::now_ns());
match &barrier.operation {
WalOperation::EpochBarrier { epoch } => {
assert_eq!(*epoch, 5);
}
_ => panic!("Expected EpochBarrier operation"),
}
}
}