durability 0.6.12

Crash-consistent persistence primitives: directory abstraction, generic WAL, checkpoints, and recovery.
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Append-only record log (generic WAL primitive).
//!
//! This is the *generic* record log primitive intended for reuse by multiple
//! segment/index implementations.
//!
//! Vocabulary note:
//! - This module provides **integrity** (CRC + framing) and **crash-recovery posture**
//!   (strict vs best-effort tail).
//! - It does not, by itself, guarantee stable-storage **durability**; that depends on
//!   the underlying `Directory` implementation.
//!
//! ## Public invariants (must not change without a format bump)
//!
//! - **File header**: `[RECORDLOG_MAGIC][FORMAT_VERSION]` at byte 0.
//! - **Record framing** (little-endian):
//!   `len:u32 | crc32:u32 | payload bytes...`
//! - **Checksum**: `crc32fast` over the payload bytes.
//! - **Limits**: payload length is capped at `MAX_RECORD_BYTES`.
//!
//! ## Recovery posture
//!
//! This module supports both strict replay and best-effort replay.
//! Best-effort replay is the common WAL posture used by systems like SQLite:
//! scan forward validating checksums and stop at the first truncated tail record.
//!
//! The writer poisons itself after a write, flush, or sync failure. Once bytes
//! may have reached the underlying file in an indeterminate state, subsequent
//! appends return `InvalidState` instead of extending a possibly ambiguous log.

use crate::error::{PersistenceError, PersistenceResult};
use crate::formats::{FORMAT_VERSION, RECORDLOG_MAGIC};
use crate::storage::{self, Directory, FlushPolicy};
use std::io::{Read, Write};
use std::sync::Arc;

/// Hard cap to avoid unbounded allocations on corrupt logs.
const MAX_RECORD_BYTES: u32 = 64 * 1024 * 1024; // 64 MiB

/// Read mode for record logs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordLogReadMode {
    /// Any corruption/truncation is an error.
    Strict,
    /// Allow a torn tail record (e.g. after a crash) by treating certain decode
    /// failures as clean EOF.
    BestEffort,
}

/// A decoded record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Record {
    /// The raw payload bytes for this record (CRC-validated).
    pub payload: Vec<u8>,
}

/// Append-only record log writer.
///
/// Single-writer assumption: unlike [`crate::walog::WalWriter`], this type does
/// not use an advisory lockfile. Two writers on the same path will interleave
/// writes and corrupt the log. Callers are responsible for ensuring at most one
/// active writer per path.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "postcard")]
/// # {
/// use durability::recordlog::{RecordLogWriter, RecordLogReader, RecordLogReadMode};
/// use durability::storage::MemoryDirectory;
///
/// let dir = MemoryDirectory::arc();
/// let mut w = RecordLogWriter::new(dir.clone(), "log.bin");
/// w.append_postcard(&"hello").unwrap();
/// w.append_postcard(&"world").unwrap();
/// w.flush().unwrap();
///
/// let r = RecordLogReader::new(dir, "log.bin");
/// let msgs: Vec<String> = r.read_all_postcard(RecordLogReadMode::Strict).unwrap();
/// assert_eq!(msgs, vec!["hello", "world"]);
/// # }
/// ```
pub struct RecordLogWriter {
    dir: Arc<dyn Directory>,
    path: String,
    header_checked: bool,
    w: Option<Box<dyn Write + Send>>,
    flush_policy: FlushPolicy,
    since_flush: usize,
    write_buffer: Vec<u8>,
    write_buffer_limit: usize,
    last_flush_at: std::time::Instant,
    poisoned: bool,
    /// Whether this writer has fsync'd the file's parent directory since creating
    /// the file. The parent-dir fsync makes the file *name* durable and only needs
    /// doing once: appends don't change the directory entry, so it is skipped on
    /// later `flush_and_sync` calls (doing it per record roughly doubled the per-op
    /// sync cost under a per-record sync policy).
    parent_synced: bool,
}

impl RecordLogWriter {
    /// Create a record log writer that appends to `path`.
    pub fn new(dir: impl Into<Arc<dyn Directory>>, path: impl Into<String>) -> Self {
        // Fast-by-default: buffer writes to reduce syscalls, and flush periodically.
        //
        // Contract note:
        // - `append_*` does not guarantee the bytes are visible to a reader until a `flush()`
        //   boundary (explicit or via policy). This is acceptable for WAL-style usage, where
        //   logs are typically replayed after process restart.
        Self::with_options(dir, path, FlushPolicy::EveryN(64), 64 * 1024)
    }

    /// Create a record log writer with an explicit flush policy.
    pub fn with_flush_policy(
        dir: impl Into<Arc<dyn Directory>>,
        path: impl Into<String>,
        flush_policy: FlushPolicy,
    ) -> Self {
        Self::with_options(dir, path, flush_policy, 0)
    }

    /// Create a record log writer with explicit flush policy and write buffer size.
    ///
    /// `write_buffer_limit_bytes == 0` disables buffering (writes are issued on each append).
    pub fn with_options(
        dir: impl Into<Arc<dyn Directory>>,
        path: impl Into<String>,
        flush_policy: FlushPolicy,
        write_buffer_limit_bytes: usize,
    ) -> Self {
        Self {
            dir: dir.into(),
            path: path.into(),
            header_checked: false,
            w: None,
            flush_policy,
            since_flush: 0,
            write_buffer: Vec::new(),
            write_buffer_limit: write_buffer_limit_bytes,
            last_flush_at: std::time::Instant::now(),
            poisoned: false,
            parent_synced: false,
        }
    }

    #[inline]
    fn ensure_not_poisoned(&self) -> PersistenceResult<()> {
        if self.poisoned {
            return Err(PersistenceError::InvalidState(
                "recordlog writer is poisoned after a prior write error".into(),
            ));
        }
        Ok(())
    }

    #[inline]
    fn poison(&mut self) {
        self.poisoned = true;
        self.write_buffer.clear();
    }

    fn ensure_header(&mut self) -> PersistenceResult<()> {
        if self.header_checked {
            return Ok(());
        }
        if self.dir.exists(&self.path) {
            let mut r = self.dir.open_file(&self.path)?;
            let mut magic = [0u8; 4];
            r.read_exact(&mut magic)?;
            if magic != RECORDLOG_MAGIC {
                return Err(PersistenceError::Format("invalid recordlog magic".into()));
            }
            let mut vbuf = [0u8; 4];
            r.read_exact(&mut vbuf)?;
            let version = u32::from_le_bytes(vbuf);
            if version != FORMAT_VERSION {
                return Err(PersistenceError::Format(
                    "recordlog version mismatch".into(),
                ));
            }
            self.header_checked = true;
            return Ok(());
        }

        let mut w = self.dir.create_file(&self.path)?;
        if let Err(e) = w.write_all(&RECORDLOG_MAGIC) {
            self.poison();
            return Err(e.into());
        }
        if let Err(e) = w.write_all(&FORMAT_VERSION.to_le_bytes()) {
            self.poison();
            return Err(e.into());
        }
        if self.flush_policy == FlushPolicy::PerAppend {
            if let Err(e) = w.flush() {
                self.poison();
                return Err(e.into());
            }
        }
        self.header_checked = true;
        Ok(())
    }

    fn ensure_writer(&mut self) -> PersistenceResult<()> {
        if self.w.is_none() {
            self.w = Some(self.dir.append_file(&self.path)?);
        }
        Ok(())
    }

    fn drain_buffer_to_writer(&mut self) -> PersistenceResult<()> {
        if self.write_buffer.is_empty() {
            return Ok(());
        }
        self.ensure_writer()?;
        let w = self.w.as_mut().expect("writer exists");
        if let Err(e) = w.write_all(&self.write_buffer) {
            self.poison();
            return Err(e.into());
        }
        self.write_buffer.clear();
        Ok(())
    }

    /// Flush the underlying writer (if one is open).
    pub fn flush(&mut self) -> PersistenceResult<()> {
        self.ensure_not_poisoned()?;
        self.flush_checked()
    }

    fn flush_checked(&mut self) -> PersistenceResult<()> {
        self.drain_buffer_to_writer()?;
        if let Some(w) = self.w.as_mut() {
            if let Err(e) = w.flush() {
                self.poison();
                return Err(e.into());
            }
        }
        self.since_flush = 0;
        self.last_flush_at = std::time::Instant::now();
        Ok(())
    }

    /// Flush buffered bytes and attempt to make the record log durable on stable storage.
    ///
    /// This is an *opt-in* stronger guarantee than `flush()`:
    /// - `flush()` is a visibility boundary (userspace → OS / underlying writer).
    /// - `flush_and_sync()` additionally calls `sync_all` on the underlying file.
    ///
    /// Returns `NotSupported` if the underlying `Directory` does not provide `file_path()`.
    pub fn flush_and_sync(&mut self) -> PersistenceResult<()> {
        self.ensure_not_poisoned()?;
        self.flush_checked()?;
        if let Err(e) = storage::sync_file(&*self.dir, &self.path) {
            self.poison();
            return Err(e);
        }
        // The file's directory entry only needs a parent-dir fsync once (after the
        // file is created); appends never change the name, so syncing the parent on
        // every record adds no durability and roughly doubles the per-op sync cost.
        if !self.parent_synced {
            if let Err(e) = storage::sync_parent_dir(&*self.dir, &self.path) {
                self.poison();
                return Err(e);
            }
            self.parent_synced = true;
        }
        Ok(())
    }

    /// Append one record containing `payload`.
    pub fn append_bytes(&mut self, payload: &[u8]) -> PersistenceResult<()> {
        self.ensure_not_poisoned()?;
        self.ensure_header()?;
        if payload.len() > usize::try_from(MAX_RECORD_BYTES).unwrap_or(usize::MAX) {
            return Err(PersistenceError::Format(format!(
                "record payload too large: {} (max {})",
                payload.len(),
                MAX_RECORD_BYTES
            )));
        }
        let len_u32 = u32::try_from(payload.len())
            .map_err(|_| PersistenceError::Format("record length overflows u32".into()))?;

        // Small optimization: write the fixed 8-byte header in one call.
        let crc = crc32fast::hash(payload);
        let mut header = [0u8; 8];
        header[..4].copy_from_slice(&len_u32.to_le_bytes());
        header[4..].copy_from_slice(&crc.to_le_bytes());
        self.write_buffer.extend_from_slice(&header);
        self.write_buffer.extend_from_slice(payload);

        if self.write_buffer_limit > 0 && self.write_buffer.len() >= self.write_buffer_limit {
            self.drain_buffer_to_writer()?;
        } else if self.write_buffer_limit == 0 {
            // Unbuffered mode: write immediately.
            self.drain_buffer_to_writer()?;
        }

        self.since_flush = self.since_flush.saturating_add(1);
        match self.flush_policy {
            FlushPolicy::PerAppend => {
                self.flush_checked()?;
            }
            FlushPolicy::EveryN(n) => {
                // Note: guards don't participate in exhaustiveness checking; handle `n` here.
                let n = n.max(1);
                if self.since_flush >= n {
                    self.flush_checked()?;
                }
            }
            FlushPolicy::Interval(d) => {
                if self.last_flush_at.elapsed() >= d {
                    self.flush_checked()?;
                }
            }
            FlushPolicy::Manual => {}
        }
        Ok(())
    }

    /// Append one postcard-encoded value as a record payload.
    #[cfg(feature = "postcard")]
    pub fn append_postcard<T: serde::Serialize>(&mut self, value: &T) -> PersistenceResult<()> {
        let payload =
            postcard::to_allocvec(value).map_err(|e| PersistenceError::Encode(e.to_string()))?;
        self.append_bytes(&payload)
    }
}

/// Sequential record log reader.
pub struct RecordLogReader {
    dir: Arc<dyn Directory>,
    path: String,
}

impl RecordLogReader {
    /// Create a record log reader for `path`.
    pub fn new(dir: impl Into<Arc<dyn Directory>>, path: impl Into<String>) -> Self {
        Self {
            dir: dir.into(),
            path: path.into(),
        }
    }

    pub(crate) fn open_stream(&self) -> PersistenceResult<Box<dyn Read + Send>> {
        let mut f = self.dir.open_file(&self.path)?;

        let mut magic = [0u8; 4];
        f.read_exact(&mut magic)?;
        if magic != RECORDLOG_MAGIC {
            return Err(PersistenceError::Format("invalid recordlog magic".into()));
        }
        let mut vbuf = [0u8; 4];
        f.read_exact(&mut vbuf)?;
        let version = u32::from_le_bytes(vbuf);
        if version != FORMAT_VERSION {
            return Err(PersistenceError::Format(
                "recordlog version mismatch".into(),
            ));
        }
        Ok(f)
    }

    pub(crate) fn next_record_inner(
        &self,
        r: &mut dyn Read,
        mode: RecordLogReadMode,
    ) -> PersistenceResult<Option<Record>> {
        // Tail-aware length decode:
        // - clean EOF at record boundary => Ok(None)
        // - truncated length prefix => error in Strict, EOF in BestEffort
        let mut first = [0u8; 1];
        match r.read_exact(&mut first) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
            Err(e) => return Err(e.into()),
        }
        let mut rest = [0u8; 3];
        if let Err(e) = r.read_exact(&mut rest) {
            if e.kind() == std::io::ErrorKind::UnexpectedEof {
                return match mode {
                    RecordLogReadMode::Strict => Err(e.into()),
                    RecordLogReadMode::BestEffort => Ok(None),
                };
            }
            return Err(e.into());
        }
        let len = u32::from_le_bytes([first[0], rest[0], rest[1], rest[2]]);
        if len > MAX_RECORD_BYTES {
            return Err(PersistenceError::Format(format!(
                "record length too large: {len} (max {MAX_RECORD_BYTES})"
            )));
        }

        let expected_crc = {
            let mut crc_buf = [0u8; 4];
            match r.read_exact(&mut crc_buf) {
                Ok(()) => u32::from_le_bytes(crc_buf),
                Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    return match mode {
                        RecordLogReadMode::Strict => Err(e.into()),
                        RecordLogReadMode::BestEffort => Ok(None),
                    };
                }
                Err(e) => return Err(e.into()),
            }
        };
        let mut payload = vec![0u8; len as usize];
        if let Err(e) = r.read_exact(&mut payload) {
            if e.kind() == std::io::ErrorKind::UnexpectedEof {
                return match mode {
                    RecordLogReadMode::Strict => Err(e.into()),
                    RecordLogReadMode::BestEffort => Ok(None),
                };
            }
            return Err(e.into());
        }
        let got = crc32fast::hash(&payload);
        if got != expected_crc {
            return Err(PersistenceError::CrcMismatch {
                expected: expected_crc,
                actual: got,
            });
        }
        Ok(Some(Record { payload }))
    }

    /// Read all records from the log.
    pub fn read_all(&self, mode: RecordLogReadMode) -> PersistenceResult<Vec<Record>> {
        if !self.dir.exists(&self.path) {
            return Ok(vec![]);
        }
        let mut f = match self.open_stream() {
            Ok(f) => f,
            Err(PersistenceError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                // Best-effort recovery: if the file exists but is too small to even contain a
                // header, treat it as an empty log (crash during initial creation).
                match mode {
                    RecordLogReadMode::Strict => return Err(PersistenceError::Io(e)),
                    RecordLogReadMode::BestEffort => return Ok(vec![]),
                }
            }
            Err(e) => return Err(e),
        };
        let mut out = Vec::new();
        while let Some(rec) = self.next_record_inner(&mut *f, mode)? {
            out.push(rec);
        }
        Ok(out)
    }

    /// Read all records as postcard-decoded values.
    #[cfg(feature = "postcard")]
    pub fn read_all_postcard<T: serde::de::DeserializeOwned>(
        &self,
        mode: RecordLogReadMode,
    ) -> PersistenceResult<Vec<T>> {
        let records = self.read_all(mode)?;
        let mut out = Vec::with_capacity(records.len());
        for r in records {
            let v: T = postcard::from_bytes(&r.payload)
                .map_err(|e| PersistenceError::Decode(e.to_string()))?;
            out.push(v);
        }
        Ok(out)
    }
}

#[cfg(test)]
mod raw_tests {
    use super::*;
    use crate::storage::MemoryDirectory;
    use std::io::{Read, Write};
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    #[derive(Clone, Copy)]
    enum FailOn {
        Write,
        Flush,
    }

    struct FailingWriterDir {
        inner: Arc<dyn Directory>,
        fail_next: Arc<AtomicBool>,
        fail_on: FailOn,
    }

    impl FailingWriterDir {
        fn wrap(&self, inner: Box<dyn Write + Send>) -> Box<dyn Write + Send> {
            Box::new(FailingWriter {
                inner,
                fail_next: self.fail_next.clone(),
                fail_on: self.fail_on,
            })
        }
    }

    impl Directory for FailingWriterDir {
        fn create_file(&self, path: &str) -> PersistenceResult<Box<dyn Write + Send>> {
            Ok(self.wrap(self.inner.create_file(path)?))
        }

        fn open_file(&self, path: &str) -> PersistenceResult<Box<dyn Read + Send>> {
            self.inner.open_file(path)
        }

        fn exists(&self, path: &str) -> bool {
            self.inner.exists(path)
        }

        fn delete(&self, path: &str) -> PersistenceResult<()> {
            self.inner.delete(path)
        }

        fn atomic_rename(&self, from: &str, to: &str) -> PersistenceResult<()> {
            self.inner.atomic_rename(from, to)
        }

        fn create_dir_all(&self, path: &str) -> PersistenceResult<()> {
            self.inner.create_dir_all(path)
        }

        fn list_dir(&self, path: &str) -> PersistenceResult<Vec<String>> {
            self.inner.list_dir(path)
        }

        fn append_file(&self, path: &str) -> PersistenceResult<Box<dyn Write + Send>> {
            Ok(self.wrap(self.inner.append_file(path)?))
        }

        fn atomic_write(&self, path: &str, data: &[u8]) -> PersistenceResult<()> {
            self.inner.atomic_write(path, data)
        }

        fn file_path(&self, path: &str) -> Option<PathBuf> {
            self.inner.file_path(path)
        }
    }

    struct FailingWriter {
        inner: Box<dyn Write + Send>,
        fail_next: Arc<AtomicBool>,
        fail_on: FailOn,
    }

    impl Write for FailingWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            if matches!(self.fail_on, FailOn::Write) && self.fail_next.swap(false, Ordering::SeqCst)
            {
                return Err(std::io::Error::other("injected write failure"));
            }
            self.inner.write(buf)
        }

        fn flush(&mut self) -> std::io::Result<()> {
            if matches!(self.fail_on, FailOn::Flush) && self.fail_next.swap(false, Ordering::SeqCst)
            {
                return Err(std::io::Error::other("injected flush failure"));
            }
            self.inner.flush()
        }
    }

    fn existing_recordlog() -> Arc<dyn Directory> {
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
        let mut w = RecordLogWriter::with_options(dir.clone(), "log.bin", FlushPolicy::Manual, 0);
        w.append_bytes(b"seed").unwrap();
        w.flush().unwrap();
        dir
    }

    fn failing_writer_dir(inner: Arc<dyn Directory>, fail_on: FailOn) -> Arc<dyn Directory> {
        Arc::new(FailingWriterDir {
            inner,
            fail_next: Arc::new(AtomicBool::new(true)),
            fail_on,
        })
    }

    fn assert_poisoned<T>(result: PersistenceResult<T>) {
        match result {
            Err(PersistenceError::InvalidState(msg)) => {
                assert!(
                    msg.contains("poisoned"),
                    "expected poisoned error, got: {msg}"
                );
            }
            Err(other) => panic!("expected poisoned error, got: {other:?}"),
            Ok(_) => panic!("expected poisoned error, got success"),
        }
    }

    fn replay_payloads(dir: Arc<dyn Directory>) -> Vec<Vec<u8>> {
        RecordLogReader::new(dir, "log.bin")
            .read_all(RecordLogReadMode::Strict)
            .unwrap()
            .into_iter()
            .map(|record| record.payload)
            .collect()
    }

    #[test]
    fn recordlog_roundtrip_bytes() {
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
        let mut w = RecordLogWriter::new(dir.clone(), "log.bin");
        w.append_bytes(b"one").unwrap();
        w.append_bytes(b"two").unwrap();
        w.flush().unwrap();

        let r = RecordLogReader::new(dir, "log.bin");
        let records = r.read_all(RecordLogReadMode::Strict).unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].payload, b"one");
        assert_eq!(records[1].payload, b"two");
    }

    #[test]
    fn recordlog_writer_poisons_after_write_failure() {
        let base = existing_recordlog();
        let dir = failing_writer_dir(base.clone(), FailOn::Write);
        let mut w = RecordLogWriter::with_options(dir, "log.bin", FlushPolicy::Manual, 0);

        let err = w.append_bytes(b"after").unwrap_err();
        assert!(matches!(err, PersistenceError::Io(_)));
        assert_poisoned(w.append_bytes(b"next"));
        drop(w);

        assert_eq!(
            replay_payloads(base),
            vec![b"seed".to_vec()],
            "failed write does not leak the failed or post-poison records"
        );
    }

    #[test]
    fn recordlog_writer_poisons_after_flush_failure() {
        let base = existing_recordlog();
        let dir = failing_writer_dir(base.clone(), FailOn::Flush);
        let mut w = RecordLogWriter::with_options(dir, "log.bin", FlushPolicy::Manual, 0);

        w.append_bytes(b"after").unwrap();
        let err = w.flush().unwrap_err();
        assert!(matches!(err, PersistenceError::Io(_)));
        assert_poisoned(w.append_bytes(b"next"));
        drop(w);

        assert_eq!(
            replay_payloads(base),
            vec![b"seed".to_vec(), b"after".to_vec()],
            "flush failure poisons future writes without discarding an already written record"
        );
    }

    #[test]
    fn recordlog_writer_poisons_after_sync_failure() {
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
        let mut w = RecordLogWriter::new(dir.clone(), "log.bin");

        w.append_bytes(b"before").unwrap();
        let err = w.flush_and_sync().unwrap_err();
        assert!(matches!(err, PersistenceError::NotSupported(_)));
        assert_poisoned(w.append_bytes(b"next"));
        drop(w);

        assert_eq!(
            replay_payloads(dir),
            vec![b"before".to_vec()],
            "sync failure poisons future writes without appending post-poison records"
        );
    }
}

#[cfg(all(test, feature = "postcard"))]
mod tests {
    use super::*;
    use crate::storage::{FsDirectory, MemoryDirectory};
    use std::io::Read;

    fn read_all_bytes(dir: &Arc<dyn Directory>, path: &str) -> Vec<u8> {
        let mut f = dir.open_file(path).unwrap();
        let mut buf = Vec::new();
        f.read_to_end(&mut buf).unwrap();
        buf
    }

    #[test]
    fn recordlog_roundtrip_postcard() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());

        let mut w = RecordLogWriter::new(dir.clone(), "log.bin");
        w.append_postcard(&E {
            msg: "東京".into()
        })
        .unwrap();
        w.append_postcard(&E {
            msg: "Москва".into(),
        })
        .unwrap();
        w.flush().unwrap();

        let r = RecordLogReader::new(dir, "log.bin");
        let xs: Vec<E> = r.read_all_postcard(RecordLogReadMode::Strict).unwrap();
        assert_eq!(xs.len(), 2);
        assert_eq!(xs[0].msg, "東京");
        assert_eq!(xs[1].msg, "Москва");
    }

    #[test]
    fn recordlog_tolerates_torn_tail_record() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }

        let tmp = tempfile::tempdir().unwrap();
        let dir = FsDirectory::new(tmp.path()).unwrap();
        let dir: Arc<dyn Directory> = Arc::new(dir);

        let mut w = RecordLogWriter::new(dir.clone(), "log.bin");
        w.append_postcard(&E {
            msg: "東京".into()
        })
        .unwrap();
        w.append_postcard(&E {
            msg: "Москва".into(),
        })
        .unwrap();
        w.flush().unwrap();

        let Some(path) = dir.file_path("log.bin") else {
            panic!("FsDirectory must return file_path()");
        };
        let mut bytes = std::fs::read(&path).unwrap();
        bytes.truncate(bytes.len().saturating_sub(3)); // tear last record
        std::fs::write(&path, bytes).unwrap();

        let r = RecordLogReader::new(dir, "log.bin");
        let xs: Vec<E> = r.read_all_postcard(RecordLogReadMode::BestEffort).unwrap();
        assert_eq!(xs.len(), 1);
        assert_eq!(xs[0].msg, "東京");
    }

    #[test]
    fn recordlog_truncated_length_prefix_is_error_in_strict_but_eof_in_best_effort() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }

        let tmp = tempfile::tempdir().unwrap();
        let dir = FsDirectory::new(tmp.path()).unwrap();
        let dir: Arc<dyn Directory> = Arc::new(dir);

        let mut w = RecordLogWriter::new(dir.clone(), "log.bin");
        w.append_postcard(&E {
            msg: "東京".into()
        })
        .unwrap();
        w.flush().unwrap();

        let Some(path) = dir.file_path("log.bin") else {
            panic!("FsDirectory must return file_path()");
        };
        let bytes = std::fs::read(&path).unwrap();

        // Keep header, then keep only 1 byte of the next record's u32 length prefix.
        let header_len = 4 + 4; // magic + version
        let truncated = &bytes[..header_len + 1];
        std::fs::write(&path, truncated).unwrap();

        let r = RecordLogReader::new(dir.clone(), "log.bin");
        assert!(r.read_all_postcard::<E>(RecordLogReadMode::Strict).is_err());

        let xs: Vec<E> = r.read_all_postcard(RecordLogReadMode::BestEffort).unwrap();
        assert_eq!(xs.len(), 0);
    }

    #[test]
    fn recordlog_writer_refuses_to_append_to_wrong_file() {
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());

        // Create a file with the wrong magic at the expected path.
        dir.atomic_write("log.bin", b"NOPE0000").unwrap();

        let mut w = RecordLogWriter::new(dir, "log.bin");
        let err = w.append_bytes(b"hello").unwrap_err();
        assert!(err.to_string().contains("invalid recordlog magic"));
    }

    #[test]
    fn recordlog_best_effort_treats_truncated_header_as_empty() {
        let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
        // Write fewer than 8 bytes (magic+version), simulating a crash during initial create.
        dir.atomic_write("log.bin", b"\xAA\xBB\xCC").unwrap();

        let r = RecordLogReader::new(dir.clone(), "log.bin");
        assert!(r.read_all(RecordLogReadMode::Strict).is_err());
        let xs = r.read_all(RecordLogReadMode::BestEffort).unwrap();
        assert_eq!(xs.len(), 0);
    }

    #[test]
    fn recordlog_flush_policy_does_not_change_bytes() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }

        let make = |policy: FlushPolicy| {
            let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
            let mut w = RecordLogWriter::with_flush_policy(dir.clone(), "log.bin", policy);
            w.append_postcard(&E {
                msg: "東京".into()
            })
            .unwrap();
            w.append_postcard(&E {
                msg: "Москва".into(),
            })
            .unwrap();
            w.append_postcard(&E {
                msg: "التقى محمد بن سلمان".into(),
            })
            .unwrap();
            w.flush().unwrap();
            (dir.clone(), read_all_bytes(&dir, "log.bin"))
        };

        let (_d1, b1) = make(FlushPolicy::PerAppend);
        let (_d2, b2) = make(FlushPolicy::EveryN(64));
        let (_d3, b3) = make(FlushPolicy::Manual);
        assert_eq!(b1, b2);
        assert_eq!(b1, b3);
    }

    #[test]
    fn recordlog_buffered_and_unbuffered_produce_same_bytes() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }

        let make = |buf_limit: usize| {
            let dir: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
            let mut w = RecordLogWriter::with_options(
                dir.clone(),
                "log.bin",
                FlushPolicy::Manual,
                buf_limit,
            );
            for i in 0..200usize {
                w.append_postcard(&E {
                    msg: format!("msg-{i}-東京-Москва-الرياض"),
                })
                .unwrap();
            }
            w.flush().unwrap();
            read_all_bytes(&dir, "log.bin")
        };

        let unbuffered = make(0);
        let buffered = make(64 * 1024);
        assert_eq!(unbuffered, buffered);
    }

    #[test]
    fn recordlog_flush_and_sync_requires_fs_backend() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        struct E {
            msg: String,
        }

        // MemoryDirectory cannot provide stable-storage barriers.
        let mem: Arc<dyn Directory> = Arc::new(MemoryDirectory::new());
        let mut w = RecordLogWriter::new(mem.clone(), "log.bin");
        w.append_postcard(&E { msg: "x".into() }).unwrap();
        let err = w.flush_and_sync().unwrap_err();
        assert!(matches!(err, PersistenceError::NotSupported(_)));

        // FsDirectory supports `file_path`, so sync succeeds.
        let tmp = tempfile::tempdir().unwrap();
        let fs = FsDirectory::new(tmp.path()).unwrap();
        let fs: Arc<dyn Directory> = Arc::new(fs);
        let mut w2 = RecordLogWriter::new(fs.clone(), "log.bin");
        w2.append_postcard(&E {
            msg: "東京".into()
        })
        .unwrap();
        w2.flush_and_sync().unwrap();

        let r = RecordLogReader::new(fs, "log.bin");
        let xs: Vec<E> = r.read_all_postcard(RecordLogReadMode::Strict).unwrap();
        assert_eq!(xs.len(), 1);
        assert_eq!(xs[0].msg, "東京");
    }

    #[test]
    fn recordlog_flush_and_sync_durable_across_many_appends() {
        // The parent-dir fsync is done once (after creation), not per record. Many
        // append + flush_and_sync cycles must still recover every record; the
        // once-only parent sync must not drop durability of the file's name.
        let tmp = tempfile::tempdir().unwrap();
        let fs: Arc<dyn Directory> = Arc::new(FsDirectory::new(tmp.path()).unwrap());
        let mut w = RecordLogWriter::new(fs.clone(), "log.bin");
        for i in 0..20u32 {
            w.append_postcard(&i).unwrap();
            w.flush_and_sync().unwrap();
        }
        let r = RecordLogReader::new(fs, "log.bin");
        let xs: Vec<u32> = r.read_all_postcard(RecordLogReadMode::Strict).unwrap();
        assert_eq!(xs, (0..20u32).collect::<Vec<_>>());
    }
}