lora-wal 0.11.0

Write-ahead log and replay engine for LoraDB.
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
use std::fs::{self, OpenOptions};
use std::path::Path;
use std::sync::Arc;

use lora_store::{MutationEvent, Properties, PropertyValue};

use super::wal::Wal;
use crate::config::SyncMode;
use crate::dir::SegmentDir;
use crate::errors::WalError;
use crate::lsn::Lsn;
use crate::testing::TmpDir;

fn ev(id: u64) -> MutationEvent {
    let mut p = Properties::new();
    p.insert("v".into(), PropertyValue::Int(id as i64));
    MutationEvent::CreateNode {
        id,
        labels: vec!["N".into()],
        properties: p,
    }
}

fn open_default(dir: &Path) -> (Arc<Wal>, Vec<MutationEvent>) {
    Wal::open(
        dir,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    )
    .unwrap()
}

#[test]
fn fresh_open_creates_first_segment() {
    let dir = TmpDir::new("fresh");
    let (wal, replay) = open_default(&dir.path);
    assert!(replay.is_empty());
    assert_eq!(wal.next_lsn(), Lsn::new(1));
    assert_eq!(wal.active_segment_id(), 1);
    // No CURRENT pointer file is written — the highest segment id
    // is the source of truth for "active segment".
    let entries: Vec<_> = fs::read_dir(&dir.path)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect();
    assert!(
        entries.iter().any(|n| n == ".lora-wal.lock"),
        "WAL dir should contain the live directory lock, found: {entries:?}"
    );
    assert!(
        entries
            .iter()
            .filter(|n| n.as_str() != ".lora-wal.lock")
            .all(|n| n.ends_with(".wal")),
        "WAL dir should contain only segment files plus the lock, found: {entries:?}"
    );
}

#[test]
fn opening_same_directory_twice_fails_until_first_handle_drops() {
    let dir = TmpDir::new("exclusive");
    let (wal, _) = open_default(&dir.path);

    match Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    ) {
        Err(WalError::AlreadyOpen { dir: locked_dir }) => {
            assert_eq!(locked_dir, dir.path);
        }
        Err(err) => panic!("expected AlreadyOpen, got {err:?}"),
        Ok(_) => panic!("second WAL open on same directory should fail"),
    }

    drop(wal);
    let (reopened, _) = open_default(&dir.path);
    drop(reopened);
}

#[test]
fn begin_append_commit_round_trip_through_replay() {
    let dir = TmpDir::new("commit");

    // First boot: write three transactions and crash without
    // running shutdown.
    {
        let (wal, _) = open_default(&dir.path);
        let begin = wal.begin().unwrap();
        wal.append(begin, &ev(1)).unwrap();
        wal.append(begin, &ev(2)).unwrap();
        wal.commit(begin).unwrap();
        wal.flush().unwrap();

        let begin = wal.begin().unwrap();
        wal.append(begin, &ev(3)).unwrap();
        wal.commit(begin).unwrap();
        wal.flush().unwrap();
        // drop without explicit close
    }

    // Second boot: replay should yield events 1, 2, 3 in order.
    let (wal, replay) = open_default(&dir.path);
    assert_eq!(replay.len(), 3);
    assert_eq!(replay[0], ev(1));
    assert_eq!(replay[1], ev(2));
    assert_eq!(replay[2], ev(3));
    // next_lsn should be past every record we wrote (2 begins +
    // 3 mutations + 2 commits = 7 records → next_lsn = 8).
    assert_eq!(wal.next_lsn(), Lsn::new(8));
}

#[test]
fn aborted_transaction_is_dropped_on_replay() {
    let dir = TmpDir::new("abort");

    {
        let (wal, _) = open_default(&dir.path);
        let b1 = wal.begin().unwrap();
        wal.append(b1, &ev(1)).unwrap();
        wal.commit(b1).unwrap();
        wal.flush().unwrap();

        let b2 = wal.begin().unwrap();
        wal.append(b2, &ev(99)).unwrap();
        wal.abort(b2).unwrap();
        wal.flush().unwrap();
    }

    let (_, replay) = open_default(&dir.path);
    assert_eq!(replay, vec![ev(1)]);
}

#[test]
fn uncommitted_transaction_at_end_of_log_is_discarded() {
    let dir = TmpDir::new("uncommitted");

    {
        let (wal, _) = open_default(&dir.path);
        let b1 = wal.begin().unwrap();
        wal.append(b1, &ev(1)).unwrap();
        wal.commit(b1).unwrap();
        wal.flush().unwrap();

        // Begin + append but never commit. Simulates a crash
        // mid-query.
        let b2 = wal.begin().unwrap();
        wal.append(b2, &ev(99)).unwrap();
        wal.flush().unwrap();
    }

    let (_, replay) = open_default(&dir.path);
    assert_eq!(replay, vec![ev(1)]);
}

#[test]
fn segment_rotation_at_begin_boundary() {
    let dir = TmpDir::new("rotate");

    // Tiny segment target so we trip rotation on the second
    // transaction.
    let (wal, _) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        256,
        Lsn::ZERO,
    )
    .unwrap();

    // First tx: a few events, takes us past 256 bytes.
    let b1 = wal.begin().unwrap();
    for i in 0..5 {
        wal.append(b1, &ev(i)).unwrap();
    }
    wal.commit(b1).unwrap();
    wal.flush().unwrap();
    assert_eq!(wal.active_segment_id(), 1);

    // Second `begin` triggers rotation.
    let b2 = wal.begin().unwrap();
    wal.append(b2, &ev(100)).unwrap();
    wal.commit(b2).unwrap();
    wal.flush().unwrap();
    assert_eq!(
        wal.active_segment_id(),
        2,
        "begin() should have rotated to segment 2"
    );

    let segments = SegmentDir::new(&dir.path).list().unwrap();
    assert_eq!(segments.len(), 2);

    drop(wal);
    let (_, replay) = open_default(&dir.path);
    assert_eq!(replay.len(), 6);
}

#[test]
fn checkpoint_lsn_skips_already_checkpointed_events() {
    let dir = TmpDir::new("ckpt-skip");
    let (wal, _) = open_default(&dir.path);

    // Tx A: events 1,2 — ends at lsn 4.
    let a = wal.begin().unwrap();
    wal.append(a, &ev(1)).unwrap();
    wal.append(a, &ev(2)).unwrap();
    let commit_a = wal.commit(a).unwrap();
    wal.flush().unwrap();

    // Tx B: event 3 — past the fence.
    let b = wal.begin().unwrap();
    wal.append(b, &ev(3)).unwrap();
    wal.commit(b).unwrap();
    wal.flush().unwrap();
    drop(wal);

    // Re-open with checkpoint_lsn = commit_a so tx A is treated
    // as already-applied.
    let (_, replay) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        commit_a,
    )
    .unwrap();
    assert_eq!(replay, vec![ev(3)]);
}

#[test]
fn replay_rejects_commit_without_begin() {
    let dir = TmpDir::new("commit-without-begin");

    {
        let (wal, _) = open_default(&dir.path);
        wal.commit(Lsn::new(99)).unwrap();
        wal.flush().unwrap();
    }

    let err = match Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    ) {
        Ok(_) => panic!("malformed WAL should not open"),
        Err(err) => err,
    };
    assert!(
        matches!(err, WalError::Malformed(ref msg) if msg.contains("missing tx begin")),
        "expected malformed missing-begin error, got {err:?}"
    );
}

#[test]
fn replay_rejects_mutation_without_begin() {
    let dir = TmpDir::new("mutation-without-begin");

    {
        let (wal, _) = open_default(&dir.path);
        wal.append(Lsn::new(99), &ev(1)).unwrap();
        wal.flush().unwrap();
    }

    let err = match Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    ) {
        Ok(_) => panic!("malformed WAL should not open"),
        Err(err) => err,
    };
    assert!(
        matches!(err, WalError::Malformed(ref msg) if msg.contains("missing tx begin")),
        "expected malformed missing-begin error, got {err:?}"
    );
}

#[test]
fn torn_tail_is_truncated_on_open() {
    let dir = TmpDir::new("torn");

    {
        let (wal, _) = open_default(&dir.path);
        let b = wal.begin().unwrap();
        wal.append(b, &ev(1)).unwrap();
        wal.commit(b).unwrap();
        wal.flush().unwrap();
    }

    // Append garbage to the active segment by hand.
    let segments = SegmentDir::new(&dir.path).list().unwrap();
    let active = &segments.last().unwrap().path;
    {
        use std::io::Write;
        let mut f = OpenOptions::new().append(true).open(active).unwrap();
        f.write_all(&[0xff; 32]).unwrap();
        f.sync_all().unwrap();
    }

    // Re-open. Torn tail must be truncated; replay still yields
    // ev(1); next_lsn picks up cleanly.
    let (wal, replay) = open_default(&dir.path);
    assert_eq!(replay, vec![ev(1)]);

    // Subsequent appends don't trip a CRC failure.
    let b = wal.begin().unwrap();
    wal.append(b, &ev(2)).unwrap();
    wal.commit(b).unwrap();
    wal.flush().unwrap();
    drop(wal);

    let (_, replay) = open_default(&dir.path);
    assert_eq!(replay, vec![ev(1), ev(2)]);
}

#[test]
fn checkpoint_marker_is_recorded_and_observed() {
    let dir = TmpDir::new("ckpt-marker");

    let snapshot_lsn = {
        let (wal, _) = open_default(&dir.path);
        let b = wal.begin().unwrap();
        wal.append(b, &ev(1)).unwrap();
        let commit = wal.commit(b).unwrap();
        wal.flush().unwrap();
        wal.checkpoint_marker(commit).unwrap();
        wal.flush().unwrap();
        commit
    };

    let outcome = crate::replay::replay_dir(&dir.path, Lsn::ZERO).unwrap();
    assert_eq!(
        outcome.checkpoint_lsn_observed,
        Some(snapshot_lsn),
        "checkpoint marker should be surfaced by replay"
    );
}

#[test]
fn group_mode_is_cooperative_until_force_fsync() {
    let dir = TmpDir::new("group");
    let (wal, _) = Wal::open(
        &dir.path,
        SyncMode::GroupSync { interval_ms: 25 },
        8 * 1024 * 1024,
        Lsn::ZERO,
    )
    .unwrap();

    let begin = wal.begin().unwrap();
    wal.append(begin, &ev(1)).unwrap();
    wal.commit(begin).unwrap();
    wal.flush().unwrap(); // Group: write_buffer only; durable_lsn untouched.

    assert_eq!(
        wal.durable_lsn(),
        Lsn::ZERO,
        "Group flush() must not advance durable_lsn"
    );

    wal.force_fsync().unwrap();
    assert_eq!(wal.durable_lsn().raw(), wal.next_lsn().raw() - 1);
    drop(wal);
}

#[test]
fn group_sync_flush_does_not_advance_durable_lsn() {
    let dir = TmpDir::new("group-sync-durable");
    let (wal, _) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    )
    .unwrap();

    let begin = wal.begin().unwrap();
    wal.append(begin, &ev(1)).unwrap();
    wal.commit(begin).unwrap();
    wal.flush().unwrap();

    assert_eq!(wal.durable_lsn(), Lsn::ZERO);
    wal.force_fsync().unwrap();
    assert_eq!(wal.durable_lsn().raw(), wal.next_lsn().raw() - 1);
}

#[test]
fn force_fsync_always_advances_durable_lsn() {
    let dir = TmpDir::new("force-fsync");
    let (wal, _) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        8 * 1024 * 1024,
        Lsn::ZERO,
    )
    .unwrap();

    let begin = wal.begin().unwrap();
    wal.append(begin, &ev(1)).unwrap();
    wal.commit(begin).unwrap();
    wal.flush().unwrap(); // Group flush: durable_lsn unchanged.
    assert_eq!(wal.durable_lsn(), Lsn::ZERO);

    // force_fsync bypasses the configured cadence — used by
    // checkpoints to grab a fence on demand.
    wal.force_fsync().unwrap();
    assert_eq!(wal.durable_lsn().raw(), wal.next_lsn().raw() - 1);
}

#[test]
fn truncate_up_to_drops_old_sealed_segments() {
    let dir = TmpDir::new("truncate");

    // Tiny target so each tx forces a rotation on the next begin.
    let (wal, _) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        64,
        Lsn::ZERO,
    )
    .unwrap();

    let mut last_commit = Lsn::ZERO;
    for i in 0..5 {
        let b = wal.begin().unwrap();
        wal.append(b, &ev(i)).unwrap();
        last_commit = wal.commit(b).unwrap();
        wal.flush().unwrap();
    }
    // Five transactions × tiny target: we should be on segment ≥ 4.
    assert!(
        wal.active_segment_id() >= 4,
        "expected several rotations, got {}",
        wal.active_segment_id()
    );

    let segments = SegmentDir::new(&dir.path);
    let before = segments.list().unwrap().len();
    wal.truncate_up_to(last_commit).unwrap();
    let after = segments.list().unwrap().len();

    assert!(
        after < before,
        "truncate_up_to should have dropped at least one segment ({} → {})",
        before,
        after
    );
    // Active + tombstone are always retained.
    assert!(
        after >= 2,
        "active and the segment preceding it must be kept"
    );

    // Subsequent appends + reopen still produce all five events
    // because the dropped segments only contained transactions
    // already at or below `last_commit`, which we feed back as
    // the checkpoint fence on reopen.
    drop(wal);
    let (_, replay) = Wal::open(
        &dir.path,
        SyncMode::GroupSync {
            interval_ms: 60_000,
        },
        64,
        last_commit,
    )
    .unwrap();
    // Everything was at or below the fence, so replay is empty.
    assert!(replay.is_empty());
}