walogs 0.1.0

A crash-safe write-ahead log library with multi-segment rotation and configurable durability.
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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Integration tests for `Wal`.
//!
//! W1–W10 are adapted from v1 (directory-based API).
//! W11–W22 are new for v2 (segments, rotation, checkpoint).

use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};

use tempfile::TempDir;
use walogs::{Lsn, MAX_ENTRY_SIZE, TailState, Wal, WalConfig, WalError};

fn collect(wal: &Wal) -> Vec<(Lsn, Vec<u8>)> {
    wal.iter().map(|r| r.expect("io error")).collect()
}

// ============================================================
// Adapted v1 tests (W1–W10)
// ============================================================

// W1
#[test]
fn w1_open_empty_dir_creates_file() {
    let dir = TempDir::new().unwrap();
    let wal = Wal::open(dir.path()).unwrap();
    // Should create wal-000001.log
    assert!(dir.path().join("wal-000001.log").exists());
    assert_eq!(wal.next_lsn(), Lsn(1));
    assert_eq!(wal.tail_state(), TailState::Clean);
    assert_eq!(collect(&wal).len(), 0);
}

// W2
#[test]
fn w2_append_then_iter_same_handle() {
    let dir = TempDir::new().unwrap();
    let mut wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.append(b"one").unwrap(), Lsn(1));
    assert_eq!(wal.append(b"two").unwrap(), Lsn(2));
    assert_eq!(wal.append(b"three").unwrap(), Lsn(3));
    let entries = collect(&wal);
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0], (Lsn(1), b"one".to_vec()));
    assert_eq!(entries[1], (Lsn(2), b"two".to_vec()));
    assert_eq!(entries[2], (Lsn(3), b"three".to_vec()));
}

// W3
#[test]
fn w3_append_drop_reopen_iter() {
    let dir = TempDir::new().unwrap();
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        wal.append(b"one").unwrap();
        wal.append(b"two").unwrap();
        wal.append(b"three").unwrap();
    }
    let wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.next_lsn(), Lsn(4));
    assert_eq!(wal.tail_state(), TailState::Clean);
    let entries = collect(&wal);
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0].0, Lsn(1));
    assert_eq!(entries[2].1, b"three".to_vec());
}

// W4
#[test]
fn w4_corrupt_last_byte_truncates_on_open() {
    let dir = TempDir::new().unwrap();
    let seg_path = dir.path().join("wal-000001.log");
    // Use uniform 3-byte payloads → each frame = 16 + 3 = 19 bytes.
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        wal.append(b"aaa").unwrap();
        wal.append(b"bbb").unwrap();
        wal.append(b"ccc").unwrap();
    }
    let size_with_3 = fs::metadata(&seg_path).unwrap().len();
    assert_eq!(size_with_3, 57);
    let third_frame_start = 38u64;

    // Flip the last byte of the file (inside the third frame's data).
    {
        let mut f = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&seg_path)
            .unwrap();
        f.seek(SeekFrom::Start(size_with_3 - 1)).unwrap();
        let mut byte = [0u8; 1];
        f.read_exact(&mut byte).unwrap();
        f.seek(SeekFrom::Start(size_with_3 - 1)).unwrap();
        f.write_all(&[byte[0] ^ 0xFF]).unwrap();
        f.sync_all().unwrap();
    }

    let wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.tail_state(), TailState::TruncatedAt(third_frame_start));
    assert_eq!(
        fs::metadata(&seg_path).unwrap().len(),
        third_frame_start,
        "file must be physically truncated (I2)"
    );
    let entries = collect(&wal);
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0], (Lsn(1), b"aaa".to_vec()));
    assert_eq!(entries[1], (Lsn(2), b"bbb".to_vec()));
    assert_eq!(wal.next_lsn(), Lsn(3));
}

// W5 — buried-garbage regression test (the catastrophic one).
#[test]
fn w5_append_after_truncation_no_buried_garbage() {
    let dir = TempDir::new().unwrap();
    let seg_path = dir.path().join("wal-000001.log");
    // First open: write 3 entries, then corrupt the last byte.
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        wal.append(b"aaa").unwrap();
        wal.append(b"bbb").unwrap();
        wal.append(b"ccc").unwrap();
    }
    {
        let size = fs::metadata(&seg_path).unwrap().len();
        let mut f = OpenOptions::new().write(true).open(&seg_path).unwrap();
        f.seek(SeekFrom::Start(size - 1)).unwrap();
        f.write_all(&[0xFF]).unwrap();
        f.sync_all().unwrap();
    }
    // Reopen — should truncate the corrupt third frame.
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        assert_eq!(wal.next_lsn(), Lsn(3));
        // Note (per TESTING.md W5 note): LSN 3 is reused. The originally-corrupted
        // entry no longer exists, so new appends start at max_valid + 1 = 3.
        wal.append(b"ddd").unwrap();
        wal.append(b"eee").unwrap();
        wal.append(b"fff").unwrap();
    }
    // Final reopen + iter — must see exactly 5 entries, dense LSNs 1..=5,
    // and no buried garbage anywhere in the file.
    let wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.tail_state(), TailState::Clean);
    let entries = collect(&wal);
    assert_eq!(entries.len(), 5);
    assert_eq!(
        entries.iter().map(|(l, _)| l.0).collect::<Vec<_>>(),
        vec![1, 2, 3, 4, 5]
    );
    assert_eq!(entries[2].1, b"ddd".to_vec());
    assert_eq!(entries[4].1, b"fff".to_vec());
    assert_eq!(wal.next_lsn(), Lsn(6));
}

// W6
#[test]
fn w6_append_oversize_returns_error() {
    let dir = TempDir::new().unwrap();
    let seg_path = dir.path().join("wal-000001.log");
    let mut wal = Wal::open(dir.path()).unwrap();
    let size_before = fs::metadata(&seg_path).unwrap().len();
    let next_before = wal.next_lsn();

    let big = vec![0u8; MAX_ENTRY_SIZE + 1];
    match wal.append(&big) {
        Err(WalError::EntryTooLarge { size, max }) => {
            assert_eq!(size, MAX_ENTRY_SIZE + 1);
            assert_eq!(max, MAX_ENTRY_SIZE);
        }
        other => panic!("expected EntryTooLarge, got {:?}", other),
    }
    assert_eq!(wal.next_lsn(), next_before, "next_lsn must not advance");
    assert_eq!(
        fs::metadata(&seg_path).unwrap().len(),
        size_before,
        "file size must be unchanged"
    );
}

// W7
#[test]
fn w7_append_at_max_size_succeeds() {
    let dir = TempDir::new().unwrap();
    let payload = vec![0xCCu8; MAX_ENTRY_SIZE];
    // Disable auto-rotation to avoid segment boundary surprises at 16MiB.
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        let lsn = wal.append(&payload).unwrap();
        assert_eq!(lsn, Lsn(1));
    }
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    let entries = collect(&wal);
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].0, Lsn(1));
    assert_eq!(entries[0].1.len(), MAX_ENTRY_SIZE);
    assert_eq!(entries[0].1, payload);
}

// W8
#[test]
fn w8_multiple_open_close_cycles() {
    let dir = TempDir::new().unwrap();
    for i in 1u64..=10 {
        let mut wal = Wal::open(dir.path()).unwrap();
        let payload = format!("e-{}", i);
        let lsn = wal.append(payload.as_bytes()).unwrap();
        assert_eq!(lsn, Lsn(i));
    }
    let wal = Wal::open(dir.path()).unwrap();
    let entries = collect(&wal);
    assert_eq!(entries.len(), 10);
    for (i, (lsn, data)) in entries.iter().enumerate() {
        let expected_lsn = (i + 1) as u64;
        assert_eq!(lsn.0, expected_lsn);
        assert_eq!(data, format!("e-{}", expected_lsn).as_bytes());
    }
    assert_eq!(wal.next_lsn(), Lsn(11));
}

// W9
#[test]
fn w9_iter_on_empty_wal() {
    let dir = TempDir::new().unwrap();
    let wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.tail_state(), TailState::Clean);
    assert_eq!(collect(&wal).len(), 0);
    assert_eq!(wal.next_lsn(), Lsn(1));
}

// W10 — bogus full header at file start should truncate the file to zero bytes.
#[test]
fn w10_corrupt_first_header_zero_entries() {
    let dir = TempDir::new().unwrap();
    let seg_path = dir.path().join("wal-000001.log");
    {
        let mut f = File::create(&seg_path).unwrap();
        let mut bogus = vec![];
        bogus.extend_from_slice(&u32::MAX.to_le_bytes()); // len
        bogus.extend_from_slice(&0u32.to_le_bytes()); // crc
        bogus.extend_from_slice(&0u64.to_le_bytes()); // lsn
        f.write_all(&bogus).unwrap();
        f.sync_all().unwrap();
    }
    let wal = Wal::open(dir.path()).unwrap();
    assert_eq!(wal.tail_state(), TailState::TruncatedAt(0));
    assert_eq!(
        fs::metadata(&seg_path).unwrap().len(),
        0,
        "file must be truncated to 0 bytes (I2)"
    );
    assert_eq!(collect(&wal).len(), 0);
    assert_eq!(wal.next_lsn(), Lsn(1));
}

// ============================================================
// New v2 segment tests (W11–W22)
// ============================================================

// W11 — manual rotation, reopen, iterate across segments.
#[test]
fn w11_rotate_then_reopen_iter() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        wal.append(b"a1").unwrap();
        wal.append(b"a2").unwrap();
        wal.append(b"a3").unwrap();
        wal.rotate().unwrap();
        wal.append(b"b1").unwrap();
        wal.append(b"b2").unwrap();
        wal.append(b"b3").unwrap();
        assert_eq!(wal.segment_count(), 2);
    }
    assert!(dir.path().join("wal-000001.log").exists());
    assert!(dir.path().join("wal-000002.log").exists());

    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    assert_eq!(wal.tail_state(), TailState::Clean);
    assert_eq!(wal.next_lsn(), Lsn(7));
    assert_eq!(wal.segment_count(), 2);
    let entries = collect(&wal);
    assert_eq!(entries.len(), 6);
    assert_eq!(
        entries.iter().map(|(l, _)| l.0).collect::<Vec<_>>(),
        vec![1, 2, 3, 4, 5, 6]
    );
    assert_eq!(entries[0].1, b"a1".to_vec());
    assert_eq!(entries[3].1, b"b1".to_vec());
}

// W12 — checkpoint deletes completed segments.
#[test]
fn w12_checkpoint_deletes_completed_segments() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config).unwrap();
    wal.append(b"a1").unwrap(); // Lsn(1)
    wal.append(b"a2").unwrap(); // Lsn(2)
    wal.append(b"a3").unwrap(); // Lsn(3)
    wal.rotate().unwrap();
    wal.append(b"b1").unwrap(); // Lsn(4)
    wal.append(b"b2").unwrap(); // Lsn(5)
    wal.append(b"b3").unwrap(); // Lsn(6)
    wal.rotate().unwrap();
    wal.append(b"c1").unwrap(); // Lsn(7)
    assert_eq!(wal.segment_count(), 3);

    // Checkpoint up to LSN 3 → delete segment 1.
    let deleted = wal.checkpoint(Lsn(3)).unwrap();
    assert_eq!(deleted, 1);
    assert!(!dir.path().join("wal-000001.log").exists());
    assert!(dir.path().join("wal-000002.log").exists());
    assert!(dir.path().join("wal-000003.log").exists());
    assert_eq!(wal.segment_count(), 2);

    // Checkpoint up to LSN 6 → delete segment 2.
    let deleted = wal.checkpoint(Lsn(6)).unwrap();
    assert_eq!(deleted, 1);
    assert!(!dir.path().join("wal-000002.log").exists());
    assert!(dir.path().join("wal-000003.log").exists());
    assert_eq!(wal.segment_count(), 1);

    // Remaining entries are correct.
    let entries = collect(&wal);
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0], (Lsn(7), b"c1".to_vec()));
}

// W13 — auto-rotation at max_segment_size.
#[test]
fn w13_auto_rotation() {
    let dir = TempDir::new().unwrap();
    // Each 10-byte payload frame = 16 + 10 = 26 bytes.
    // max_segment_size=60 → fits 2 frames (52 bytes), third triggers rotation.
    let config = WalConfig {
        max_segment_size: Some(60),
    };
    let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
    for i in 1..=6 {
        let payload = format!("entry-{:04}", i);
        wal.append(payload.as_bytes()).unwrap();
    }
    // Segment 1: entry-0001 (26), entry-0002 (52). Third would be 78 > 60, rotate.
    // Segment 2: entry-0003 (26), entry-0004 (52). Fifth would be 78 > 60, rotate.
    // Segment 3: entry-0005 (26), entry-0006 (52).
    assert_eq!(wal.segment_count(), 3);
    assert!(dir.path().join("wal-000001.log").exists());
    assert!(dir.path().join("wal-000002.log").exists());
    assert!(dir.path().join("wal-000003.log").exists());

    drop(wal);
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    let entries = collect(&wal);
    assert_eq!(entries.len(), 6);
    for (i, (lsn, data)) in entries.iter().enumerate() {
        assert_eq!(lsn.0, (i + 1) as u64);
        assert_eq!(data, format!("entry-{:04}", i + 1).as_bytes());
    }
}

// W14 — corruption in non-last segment → open fails.
#[test]
fn w14_corrupt_non_last_segment_fails() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        wal.append(b"aaa").unwrap();
        wal.append(b"bbb").unwrap();
        wal.rotate().unwrap();
        wal.append(b"ccc").unwrap();
    }
    // Corrupt the first byte of segment 1 (a completed segment).
    let seg1 = dir.path().join("wal-000001.log");
    {
        let mut f = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&seg1)
            .unwrap();
        f.seek(SeekFrom::Start(0)).unwrap();
        let mut byte = [0u8; 1];
        f.read_exact(&mut byte).unwrap();
        f.seek(SeekFrom::Start(0)).unwrap();
        f.write_all(&[byte[0] ^ 0xFF]).unwrap();
        f.sync_all().unwrap();
    }
    // Reopen should fail because corruption is in a non-last segment.
    let result = Wal::open_with_config(dir.path(), config);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        format!("{}", err).contains("corrupt"),
        "expected corruption error, got: {}",
        err
    );
}

// W15 — v1 migration: wal.log → wal-000001.log.
#[test]
fn w15_v1_migration() {
    let dir = TempDir::new().unwrap();
    // Create data using the current WAL, then simulate v1 by renaming.
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        wal.append(b"hello").unwrap();
        wal.append(b"world").unwrap();
    }
    // Simulate v1: rename wal-000001.log → wal.log.
    let v2_path = dir.path().join("wal-000001.log");
    let v1_path = dir.path().join("wal.log");
    fs::rename(&v2_path, &v1_path).unwrap();
    assert!(v1_path.exists());
    assert!(!v2_path.exists());

    // Reopen — should migrate wal.log → wal-000001.log.
    let wal = Wal::open(dir.path()).unwrap();
    assert!(!v1_path.exists());
    assert!(v2_path.exists());
    assert_eq!(wal.next_lsn(), Lsn(3));
    let entries = collect(&wal);
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0], (Lsn(1), b"hello".to_vec()));
    assert_eq!(entries[1], (Lsn(2), b"world".to_vec()));
}

// W16 — mixed v1+v2 state → error.
#[test]
fn w16_mixed_v1_v2_error() {
    let dir = TempDir::new().unwrap();
    // Create both wal.log and wal-000001.log.
    File::create(dir.path().join("wal.log")).unwrap();
    File::create(dir.path().join("wal-000001.log")).unwrap();
    let result = Wal::open(dir.path());
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        format!("{}", err).contains("wal.log"),
        "expected mixed-version error, got: {}",
        err
    );
}

// W17 — checkpoint, then reopen → data intact.
#[test]
fn w17_checkpoint_then_reopen() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        wal.append(b"a").unwrap(); // Lsn(1)
        wal.append(b"b").unwrap(); // Lsn(2)
        wal.rotate().unwrap();
        wal.append(b"c").unwrap(); // Lsn(3)
        wal.append(b"d").unwrap(); // Lsn(4)
        wal.checkpoint(Lsn(2)).unwrap();
        // Segment 1 deleted. Segment 2 (active) has entries 3, 4.
    }
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    assert_eq!(wal.next_lsn(), Lsn(5));
    assert_eq!(wal.tail_state(), TailState::Clean);
    let entries = collect(&wal);
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0], (Lsn(3), b"c".to_vec()));
    assert_eq!(entries[1], (Lsn(4), b"d".to_vec()));
}

// W18 — rotate on empty segment is a no-op.
#[test]
fn w18_rotate_empty_segment_noop() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config).unwrap();
    wal.rotate().unwrap(); // should be no-op
    assert_eq!(wal.segment_count(), 1);
    assert!(!dir.path().join("wal-000002.log").exists());
    wal.append(b"test").unwrap();
    assert_eq!(collect(&wal).len(), 1);
}

// W19 — checkpoint never deletes the active segment.
#[test]
fn w19_checkpoint_never_deletes_active() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config).unwrap();
    wal.append(b"only").unwrap();
    // Only one segment (active). Checkpoint should delete nothing.
    let deleted = wal.checkpoint(Lsn(100)).unwrap();
    assert_eq!(deleted, 0);
    assert!(dir.path().join("wal-000001.log").exists());
    assert_eq!(collect(&wal).len(), 1);
}

// W20 — multiple rotations and checkpoints.
#[test]
fn w20_multiple_rotations_and_checkpoints() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();

    // Build 5 segments of 2 entries each.
    for seg in 0..5 {
        if seg > 0 {
            wal.rotate().unwrap();
        }
        let a = format!("s{}-a", seg + 1);
        let b = format!("s{}-b", seg + 1);
        wal.append(a.as_bytes()).unwrap();
        wal.append(b.as_bytes()).unwrap();
    }
    assert_eq!(wal.segment_count(), 5);

    // Checkpoint up to LSN 6 (covers segments 1, 2, 3).
    let deleted = wal.checkpoint(Lsn(6)).unwrap();
    assert_eq!(deleted, 3);
    assert_eq!(wal.segment_count(), 2);

    // Reopen: should only see entries from segments 4 and 5.
    drop(wal);
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    let entries = collect(&wal);
    assert_eq!(entries.len(), 4);
    assert_eq!(entries[0].0, Lsn(7));
    assert_eq!(entries[3].0, Lsn(10));
}

// W21 — LSN continuity across rotation boundaries.
#[test]
fn w21_lsn_continuity_across_rotations() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
    wal.append(b"x").unwrap();
    wal.rotate().unwrap();
    wal.append(b"y").unwrap();
    wal.rotate().unwrap();
    wal.append(b"z").unwrap();

    drop(wal);
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    let entries = collect(&wal);
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0], (Lsn(1), b"x".to_vec()));
    assert_eq!(entries[1], (Lsn(2), b"y".to_vec()));
    assert_eq!(entries[2], (Lsn(3), b"z".to_vec()));
}

// W22 — corrupt tail in last segment, other segments intact.
#[test]
fn w22_corrupt_last_segment_tail() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        wal.append(b"a1").unwrap(); // Lsn(1), frame=18 bytes
        wal.append(b"a2").unwrap(); // Lsn(2), frame=18 bytes
        wal.rotate().unwrap();
        wal.append(b"b1").unwrap(); // Lsn(3), frame=18 bytes
        wal.append(b"b2").unwrap(); // Lsn(4), frame=18 bytes
    }
    // Corrupt last byte of segment 2.
    let seg2 = dir.path().join("wal-000002.log");
    {
        let size = fs::metadata(&seg2).unwrap().len();
        assert_eq!(size, 36); // 2 × 18 bytes
        let mut f = OpenOptions::new().write(true).open(&seg2).unwrap();
        f.seek(SeekFrom::Start(size - 1)).unwrap();
        f.write_all(&[0xFF]).unwrap();
        f.sync_all().unwrap();
    }
    let wal = Wal::open_with_config(dir.path(), config).unwrap();
    // Should recover segment 1 fully and segment 2 partially (first entry only).
    let entries = collect(&wal);
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0], (Lsn(1), b"a1".to_vec()));
    assert_eq!(entries[1], (Lsn(2), b"a2".to_vec()));
    assert_eq!(entries[2], (Lsn(3), b"b1".to_vec()));
    assert_eq!(wal.tail_state(), TailState::TruncatedAt(18));
}

// W23 — segment sequence gap detection (I11).
#[test]
fn w23_segment_sequence_gap_detected() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    {
        let mut wal = Wal::open_with_config(dir.path(), config.clone()).unwrap();
        wal.append(b"a").unwrap(); // seg 1
        wal.rotate().unwrap();
        wal.append(b"b").unwrap(); // seg 2
        wal.rotate().unwrap();
        wal.append(b"c").unwrap(); // seg 3
    }
    // Delete the middle segment to create a gap: 1, 3.
    fs::remove_file(dir.path().join("wal-000002.log")).unwrap();

    let err = Wal::open_with_config(dir.path(), config).unwrap_err();
    match &err {
        WalError::Corrupt { reason } => {
            assert!(
                reason.contains("gap"),
                "expected 'gap' in error message, got: {}",
                reason
            );
        }
        other => panic!("expected WalError::Corrupt, got: {:?}", other),
    }
}

// W24 — open() on a path that is a file (not a directory) returns a clean Io error.
#[test]
fn w24_open_on_file_not_dir() {
    let tmp = TempDir::new().unwrap();
    let file_path = tmp.path().join("not-a-dir");
    // Create a regular file at that path.
    File::create(&file_path).unwrap();

    let err = Wal::open(&file_path).unwrap_err();
    assert!(
        matches!(err, WalError::Io(_)),
        "expected WalError::Io, got: {:?}",
        err
    );
}

// W25 — checkpoint(Lsn(0)) is a no-op (sentinel value, nothing applied yet).
#[test]
fn w25_checkpoint_lsn_zero_is_noop() {
    let dir = TempDir::new().unwrap();
    let config = WalConfig {
        max_segment_size: None,
    };
    let mut wal = Wal::open_with_config(dir.path(), config).unwrap();
    wal.append(b"a").unwrap(); // seg 1, lsn 1
    wal.rotate().unwrap();
    wal.append(b"b").unwrap(); // seg 2 (active), lsn 2

    let deleted = wal.checkpoint(Lsn(0)).unwrap();
    assert_eq!(deleted, 0, "checkpoint(Lsn(0)) must delete nothing");
    // Both segments still exist.
    assert!(dir.path().join("wal-000001.log").exists());
    assert!(dir.path().join("wal-000002.log").exists());
}

// W26 — corrupt tail with read-only active segment returns Io error, not a panic.
#[test]
fn w26_readonly_active_segment_truncation_error() {
    use std::os::unix::fs::PermissionsExt;

    let dir = TempDir::new().unwrap();
    let seg_path = dir.path().join("wal-000001.log");
    {
        let mut wal = Wal::open(dir.path()).unwrap();
        wal.append(b"hello").unwrap();
    }

    // Corrupt the last byte.
    {
        let meta = fs::metadata(&seg_path).unwrap();
        let size = meta.len();
        let mut f = OpenOptions::new().write(true).open(&seg_path).unwrap();
        f.seek(SeekFrom::Start(size - 1)).unwrap();
        f.write_all(&[0xFF]).unwrap();
        f.sync_all().unwrap();
    }

    // Make the segment read-only.
    fs::set_permissions(&seg_path, std::fs::Permissions::from_mode(0o444)).unwrap();

    // Open must fail with Io (can't truncate a read-only file), not panic.
    let result = Wal::open(dir.path());
    // Restore permissions so TempDir cleanup doesn't fail.
    fs::set_permissions(&seg_path, std::fs::Permissions::from_mode(0o644)).unwrap();

    assert!(
        matches!(result, Err(WalError::Io(_))),
        "expected WalError::Io when truncating read-only segment, got: {:?}",
        result
    );
}