Skip to main content

reddb_server/storage/wal/
writer.rs

1use super::record::WalRecord;
2use reddb_file::{OpenMode, StdVfs, Vfs, VfsFile};
3use std::io::{self, SeekFrom};
4use std::path::Path;
5use std::sync::Arc;
6
7/// User-space buffer size for the WAL writer.
8///
9/// Chosen so that ~5 000 small records (Begin/Commit ≈ 21 bytes,
10/// small PageWrite ≈ 34 bytes) coalesce into a single `write` syscall
11/// before the next `sync()` drains the buffer. Tunable; reflects the
12/// postgres XLOG block size (8 KiB) scaled up because we batch
13/// record-level rather than page-level.
14pub const WAL_BUFFER_BYTES: usize = 64 * 1024;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17enum WalSyncMethod {
18    Data,
19    All,
20}
21
22pub(crate) struct WalGroupSync<F: VfsFile> {
23    target_lsn: u64,
24    sync_handle: Arc<F>,
25    method: WalSyncMethod,
26}
27
28impl<F: VfsFile> WalGroupSync<F> {
29    pub(crate) fn target_lsn(&self) -> u64 {
30        self.target_lsn
31    }
32
33    pub(crate) fn sync(&self) -> io::Result<()> {
34        match self.method {
35            WalSyncMethod::Data => self.sync_handle.sync_data(),
36            WalSyncMethod::All => self.sync_handle.sync_all(),
37        }
38    }
39}
40
41struct VfsBufWriter<F: VfsFile> {
42    file: F,
43    buffer: Vec<u8>,
44    write_error: Option<io::Error>,
45    #[cfg(test)]
46    test_fail_flush_after: Option<usize>,
47}
48
49impl<F: VfsFile> VfsBufWriter<F> {
50    fn with_capacity(capacity: usize, file: F) -> Self {
51        Self {
52            file,
53            buffer: Vec::with_capacity(capacity),
54            write_error: None,
55            #[cfg(test)]
56            test_fail_flush_after: None,
57        }
58    }
59
60    fn write_all(&mut self, bytes: &[u8]) -> io::Result<()> {
61        self.check_write_error()?;
62        if self.buffer.len() + bytes.len() > self.buffer.capacity() {
63            self.flush()?;
64        }
65        if bytes.len() >= self.buffer.capacity() {
66            let result = self.file.write_all(bytes);
67            self.record_write_result(result)
68        } else {
69            self.buffer.extend_from_slice(bytes);
70            Ok(())
71        }
72    }
73
74    fn flush(&mut self) -> io::Result<()> {
75        self.check_write_error()?;
76        if !self.buffer.is_empty() {
77            #[cfg(test)]
78            let result = if let Some(limit) = self.test_fail_flush_after.take() {
79                let prefix = limit.min(self.buffer.len().saturating_sub(1));
80                self.file.write_all(&self.buffer[..prefix]).and_then(|_| {
81                    Err(io::Error::new(
82                        io::ErrorKind::StorageFull,
83                        "injected disk full",
84                    ))
85                })
86            } else {
87                self.file.write_all(&self.buffer)
88            };
89            #[cfg(not(test))]
90            let result = self.file.write_all(&self.buffer);
91            self.record_write_result(result)?;
92            self.buffer.clear();
93        }
94        Ok(())
95    }
96
97    fn check_write_error(&self) -> io::Result<()> {
98        match &self.write_error {
99            Some(error) => Err(io::Error::new(
100                error.kind(),
101                format!("WAL write failed; reopen required: {error}"),
102            )),
103            None => Ok(()),
104        }
105    }
106
107    fn record_write_result(&mut self, result: io::Result<()>) -> io::Result<()> {
108        if let Err(error) = &result {
109            // write_all may have advanced the file by an unknown prefix. Never
110            // append after that tail or retry this buffer, including on Drop:
111            // doing so can corrupt framing or publish a rejected transaction.
112            self.write_error = Some(io::Error::new(error.kind(), error.to_string()));
113        }
114        result
115    }
116
117    fn get_ref(&self) -> &F {
118        &self.file
119    }
120
121    fn get_mut(&mut self) -> &mut F {
122        &mut self.file
123    }
124}
125
126impl<F: VfsFile> Drop for VfsBufWriter<F> {
127    fn drop(&mut self) {
128        let _ = self.flush();
129    }
130}
131
132/// Whether a `fallocate` failure means "this filesystem can't preallocate"
133/// (tmpfs, overlayfs, many network filesystems) rather than a real I/O error.
134/// Those are soft failures that flip the feature off; anything else is left to
135/// the normal write path to surface (e.g. a genuine `ENOSPC`).
136fn fallocate_unsupported(err: &io::Error) -> bool {
137    if err.kind() == io::ErrorKind::Unsupported {
138        return true;
139    }
140    #[cfg(target_os = "linux")]
141    {
142        matches!(
143            err.raw_os_error(),
144            Some(libc::EOPNOTSUPP) | Some(libc::ENOSYS) | Some(libc::EINVAL)
145        )
146    }
147    #[cfg(not(target_os = "linux"))]
148    {
149        false
150    }
151}
152
153/// Writer for the Write-Ahead Log
154///
155/// Wraps the underlying file in a [`VfsBufWriter`] so each `append` does
156/// not pay a write syscall — bytes accumulate in a 64 KiB user-space
157/// buffer until `sync()` (or `flush_until()`) drains them and then
158/// calls `sync_data()`/`sync_all()` on the raw file. This is how postgres turns
159/// per-record append cost from ~500 ns down to ~5 ns; reddb's previous
160/// per-append `write_all` directly to the file paid the syscall on
161/// every record.
162///
163/// **Critical contract:** every code path that syncs the underlying
164/// file *must* drain the [`VfsBufWriter`] first via
165/// `VfsBufWriter::flush()`. Otherwise the bytes in user-space never reach
166/// the kernel before fsync, and durability is silently broken.
167pub struct WalWriter<V: Vfs = StdVfs> {
168    file: VfsBufWriter<V::File>,
169    /// Cloned file descriptor for `sync_all()` outside the writer
170    /// mutex. Both this and `file`'s inner `File` point at the same
171    /// kernel inode; calling `sync_all()` on either flushes ALL
172    /// pending bytes for that inode. This is the trick that lets
173    /// the group-commit leader release the WAL writer lock during
174    /// the expensive fsync — see [`WalWriter::drain_for_group_sync`].
175    ///
176    /// Without this clone, a leader holding the writer mutex during
177    /// `sync_all()` blocks every other writer from appending,
178    /// defeating the entire purpose of group commit.
179    sync_handle: Arc<V::File>,
180    /// Log Sequence Number — byte offset of the next record. Advances
181    /// every `append`; survives across restarts via `seek(End)`.
182    current_lsn: u64,
183    /// Highest LSN that has been `sync_all()`'d to disk. The WAL-first
184    /// flush invariant relies on this: a page with `header.lsn = L` may
185    /// only be written to its data file once `durable_lsn >= L`.
186    /// See `src/storage/cache/README.md` § Invariant 2 and the Target 3
187    /// section of `PLAN.md`.
188    durable_lsn: u64,
189    /// WAL byte frontier covered by the last full file sync. Appends that stay
190    /// inside this synced preallocation range can use `sync_data()`; crossing
191    /// it, or syncing after fresh preallocation metadata, falls back to
192    /// `sync_all()`.
193    last_synced_size: u64,
194    /// Exclusive byte offset up to which disk blocks are pre-reserved via
195    /// `fallocate(FALLOC_FL_KEEP_SIZE)`. Advances one
196    /// [`reddb_file::MAIN_WAL_SEGMENT_BYTES`]
197    /// segment at a time as `current_lsn` approaches it (issue #893). Reset to
198    /// `0` on [`truncate`](Self::truncate) — which frees the blocks — and
199    /// immediately re-extended (the checkpoint re-extend path).
200    preallocated_to: u64,
201    /// Cleared the first time `fallocate` reports the backing filesystem can't
202    /// preallocate (tmpfs/overlay/NFS → `EOPNOTSUPP`/`ENOSYS`, or any non-Linux
203    /// target) so we stop issuing syscalls that will always fail. Preallocation
204    /// is a best-effort optimization; clearing this never affects correctness.
205    prealloc_supported: bool,
206    /// Set when `fallocate(FALLOC_FL_KEEP_SIZE)` successfully reserved a new
207    /// range and that allocation metadata has not yet been covered by a full
208    /// sync.
209    prealloc_metadata_dirty: bool,
210    #[cfg(test)]
211    last_sync_method: Option<WalSyncMethod>,
212}
213
214impl WalWriter<StdVfs> {
215    /// Open a WAL file for writing. Creates it if it doesn't exist.
216    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
217        Self::open_with_vfs(StdVfs, path)
218    }
219}
220
221impl<V: Vfs> WalWriter<V> {
222    #[cfg(test)]
223    pub(crate) fn test_fail_flush_after(&mut self, bytes: usize) {
224        self.file.test_fail_flush_after = Some(bytes);
225    }
226
227    /// Open a WAL file through `vfs`. Creates it if it doesn't exist.
228    pub fn open_with_vfs<P: AsRef<Path>>(vfs: V, path: P) -> io::Result<Self> {
229        // We do all initial bookkeeping (write header, seek to EOF) on
230        // the raw VFS file BEFORE wrapping in a VfsBufWriter so we don't
231        // have to worry about flush ordering during construction.
232        let mut raw = vfs.open(path.as_ref(), OpenMode::create_keep())?;
233        let existing_len = raw.file_len()?;
234
235        let current_lsn = if existing_len == 0 {
236            raw.write_all(&reddb_file::encode_wal_file_header())?;
237            raw.sync_all()?;
238            reddb_file::WAL_FILE_HEADER_BYTES as u64
239        } else {
240            // Existing file, set LSN to current end. Append-mode files
241            // ignore this seek for *writes*, but we use the returned
242            // position as our LSN counter.
243            raw.seek(SeekFrom::End(0))?
244        };
245
246        // Clone the file handle BEFORE wrapping in BufWriter. The
247        // clone shares the same kernel file description, so
248        // sync_all() on either descriptor flushes the whole inode.
249        // The VfsBufWriter owns the original; the Arc handle is shared
250        // with the group-commit leader.
251        let sync_handle = Arc::new(raw.try_clone()?);
252        let file = VfsBufWriter::with_capacity(WAL_BUFFER_BYTES, raw);
253
254        // On open, every byte already on disk is by definition durable
255        // (any pre-crash unflushed tail was lost when the OS dropped
256        // page cache). Initialise `durable_lsn` to `current_lsn`.
257        let mut writer = Self {
258            file,
259            sync_handle,
260            current_lsn,
261            durable_lsn: current_lsn,
262            last_synced_size: current_lsn,
263            preallocated_to: 0,
264            prealloc_supported: true,
265            prealloc_metadata_dirty: false,
266            #[cfg(test)]
267            last_sync_method: None,
268        };
269        // Reserve the first segment up front so the very first appends land in
270        // contiguous extents rather than growing the file page-by-page.
271        writer.ensure_preallocated()?;
272        Ok(writer)
273    }
274
275    /// Ensure disk blocks are reserved at least up to the next segment
276    /// boundary above the current write frontier (`current_lsn`).
277    ///
278    /// Cheap (pure arithmetic) until the frontier crosses a
279    /// [`reddb_file::MAIN_WAL_SEGMENT_BYTES`] boundary, at which point it issues a single
280    /// `fallocate`. Best-effort: a filesystem that can't preallocate disables
281    /// the feature; a transient error is swallowed so a write never fails
282    /// because preallocation hiccuped (the write path surfaces a genuine
283    /// `ENOSPC` on its own). Never grows the file's logical length, so it is
284    /// invisible to crash recovery.
285    fn ensure_preallocated(&mut self) -> io::Result<()> {
286        if !self.prealloc_supported {
287            return Ok(());
288        }
289        let target = reddb_file::next_main_wal_segment_boundary(self.current_lsn);
290        if target <= self.preallocated_to {
291            return Ok(());
292        }
293        let from = self.preallocated_to;
294        match self.file.get_ref().reserve(from, target - from) {
295            Ok(()) => {
296                self.preallocated_to = target;
297                self.prealloc_metadata_dirty = true;
298            }
299            Err(ref e) if fallocate_unsupported(e) => self.prealloc_supported = false,
300            Err(_) => {
301                // Best-effort: leave `preallocated_to` as-is and retry at the
302                // next boundary. Never propagate.
303            }
304        }
305        Ok(())
306    }
307
308    /// Append a record to the WAL.
309    ///
310    /// Bytes go into the BufWriter — they are NOT durable on disk
311    /// after this call returns. Callers that need durability must
312    /// follow up with [`WalWriter::sync`] or
313    /// [`WalWriter::flush_until`].
314    ///
315    /// Returns the LSN (Log Sequence Number) of the record.
316    pub fn append(&mut self, record: &WalRecord) -> io::Result<u64> {
317        let bytes = record.encode();
318        self.file.write_all(&bytes)?;
319
320        let record_lsn = self.current_lsn;
321        self.current_lsn += bytes.len() as u64;
322
323        self.ensure_preallocated()?;
324        Ok(record_lsn)
325    }
326
327    /// Write already-encoded bytes and advance the LSN counter to
328    /// match. Used by the lock-free append path: writers encode +
329    /// atomically reserve an LSN range outside this writer, the
330    /// group-commit coordinator drains the pending queue in LSN
331    /// order, then calls `append_bytes` for each batch.
332    ///
333    /// The bytes MUST be a valid `WalRecord::encode()` payload (or a
334    /// concatenation of such) — no structural validation happens
335    /// here. The caller is responsible for keeping the on-disk
336    /// byte offset synchronised with the externally-tracked LSN
337    /// counter; this method just appends and advances.
338    pub fn append_bytes(&mut self, bytes: &[u8]) -> io::Result<u64> {
339        self.file.write_all(bytes)?;
340        let record_lsn = self.current_lsn;
341        self.current_lsn += bytes.len() as u64;
342        self.ensure_preallocated()?;
343        Ok(record_lsn)
344    }
345
346    /// Rewind the writer's LSN counter to a specific value. Used
347    /// by the lock-free append path to resync the writer with the
348    /// externally-tracked `next_lsn` after a drain batch; the
349    /// coordinator knows the exact byte offset it just wrote to
350    /// and needs `current_lsn` to match so subsequent direct
351    /// callers of `append` stay consistent.
352    pub fn set_current_lsn(&mut self, lsn: u64) {
353        self.current_lsn = lsn;
354    }
355
356    /// Drop an ordinary record that recovery proved was interrupted at EOF.
357    /// The caller must validate ownership state before invoking this method.
358    pub(crate) fn truncate_incomplete_tail(&mut self, valid_lsn: u64) -> io::Result<()> {
359        if valid_lsn < reddb_file::WAL_FILE_HEADER_BYTES as u64 || valid_lsn > self.current_lsn {
360            return Err(io::Error::new(
361                io::ErrorKind::InvalidInput,
362                "invalid incomplete WAL tail boundary",
363            ));
364        }
365        self.file.flush()?;
366        {
367            let raw = self.file.get_mut();
368            raw.set_len(valid_lsn)?;
369            raw.seek(SeekFrom::Start(valid_lsn))?;
370        }
371        self.file.get_ref().sync_all()?;
372        self.current_lsn = valid_lsn;
373        self.durable_lsn = valid_lsn;
374        self.last_synced_size = self.preallocated_to.max(valid_lsn);
375        self.prealloc_metadata_dirty = false;
376        Ok(())
377    }
378
379    /// Force sync to disk.
380    ///
381    /// Drains the user-space [`BufWriter`] first, then calls
382    /// `sync_all()` on the underlying file so every byte appended
383    /// since the last sync is durable. Updates `durable_lsn` so
384    /// subsequent `flush_until` calls become no-ops up to
385    /// `current_lsn`.
386    pub fn sync(&mut self) -> io::Result<()> {
387        self.file.flush()?;
388        self.sync_flushed_file()?;
389        self.durable_lsn = self.current_lsn;
390        Ok(())
391    }
392
393    /// Ensure the WAL is durable on disk at least up to byte offset
394    /// `target`. No-op when `target <= durable_lsn`.
395    ///
396    /// This is the postgres `XLogFlush(LSN)` analogue. Pager flush
397    /// paths call this with `max(dirty.header.lsn)` before writing
398    /// any data page so the WAL record describing the change is
399    /// guaranteed to be on disk before the page itself.
400    pub fn flush_until(&mut self, target: u64) -> io::Result<()> {
401        if self.durable_lsn >= target {
402            return self.file.check_write_error();
403        }
404        self.file.flush()?;
405        self.sync_flushed_file()?;
406        self.durable_lsn = self.current_lsn;
407        Ok(())
408    }
409
410    fn sync_flushed_file(&mut self) -> io::Result<()> {
411        let method = self.next_sync_method();
412        let result = match method {
413            WalSyncMethod::Data => self.file.get_ref().sync_data(),
414            WalSyncMethod::All => self.file.get_ref().sync_all(),
415        };
416        // A failed durability barrier has an uncertain outcome. Keep the
417        // writer fenced even if a later sync would succeed.
418        self.file.record_write_result(result)?;
419        self.mark_sync_complete(method, self.current_lsn);
420        Ok(())
421    }
422
423    fn next_sync_method(&self) -> WalSyncMethod {
424        if !self.prealloc_metadata_dirty && self.current_lsn <= self.last_synced_size {
425            WalSyncMethod::Data
426        } else {
427            WalSyncMethod::All
428        }
429    }
430
431    fn mark_sync_complete(&mut self, method: WalSyncMethod, lsn: u64) {
432        match method {
433            WalSyncMethod::Data => {}
434            WalSyncMethod::All => {
435                self.last_synced_size = self.preallocated_to.max(lsn);
436                self.prealloc_metadata_dirty = false;
437            }
438        }
439        #[cfg(test)]
440        {
441            self.last_sync_method = Some(method);
442        }
443    }
444
445    /// Highest byte offset that is durable on disk. Used by the pager
446    /// to decide whether a `flush_until` call would actually need a
447    /// `fsync`.
448    pub fn durable_lsn(&self) -> u64 {
449        self.durable_lsn
450    }
451
452    /// Get current LSN (end of file offset)
453    pub fn current_lsn(&self) -> u64 {
454        self.current_lsn
455    }
456
457    /// Drain the BufWriter into the kernel and return the captured
458    /// LSN plus a cloned file handle and sync method for the caller
459    /// **without holding the WAL writer mutex**.
460    ///
461    /// Used by the group-commit leader path. The flow is:
462    ///
463    /// 1. Take the WAL writer mutex.
464    /// 2. Call this method — drains user-space buffer to the kernel
465    ///    and captures a size-aware sync plan.
466    /// 3. Release the WAL writer mutex.
467    /// 4. Execute the sync plan — this is the expensive ~100 µs syscall,
468    ///    and other writers can keep appending while it runs.
469    /// 5. Take the WAL writer mutex briefly and call
470    ///    [`WalWriter::mark_durable`] to publish the new durable position.
471    ///
472    /// The cloned `sync_handle` shares the same kernel inode with
473    /// the writer's `file`, so syncing the clone flushes bytes that
474    /// have reached the kernel for that file.
475    /// This is the coalescing window that makes group commit win.
476    pub(crate) fn drain_for_group_sync(&mut self) -> io::Result<WalGroupSync<V::File>> {
477        // Drain user-space buffer into the kernel.
478        self.file.flush()?;
479        Ok(WalGroupSync {
480            target_lsn: self.current_lsn,
481            sync_handle: Arc::clone(&self.sync_handle),
482            method: self.next_sync_method(),
483        })
484    }
485
486    /// Manually advance `durable_lsn` after a successful out-of-lock
487    /// sync performed via [`WalWriter::drain_for_group_sync`].
488    ///
489    /// Monotonic — never lowers `durable_lsn`. Safe to call with a
490    /// stale `lsn`; just becomes a no-op.
491    pub(crate) fn mark_durable(&mut self, sync: &WalGroupSync<V::File>) {
492        let lsn = sync.target_lsn;
493        if lsn > self.durable_lsn {
494            self.durable_lsn = lsn;
495        }
496        self.mark_sync_complete(sync.method, lsn);
497    }
498
499    /// Truncate the WAL (usually after checkpoint).
500    ///
501    /// Drains the BufWriter first so no pending bytes hit the file
502    /// after the truncate. Then resets the underlying file, rewrites
503    /// the header through the buffered writer (header is small; the
504    /// followup `flush + sync_all` makes it durable), and resets
505    /// LSN bookkeeping.
506    pub fn truncate(&mut self) -> io::Result<()> {
507        // Drop any pending bytes BEFORE the truncate; otherwise the
508        // BufWriter would flush them to a re-shrunken file in
509        // confused order.
510        self.file.flush()?;
511
512        {
513            let raw = self.file.get_mut();
514            raw.set_len(0)?;
515            raw.seek(SeekFrom::Start(0))?;
516        }
517
518        // Rewrite header through the BufWriter then drain.
519        self.file.write_all(&reddb_file::encode_wal_file_header())?;
520        self.file.flush()?;
521        self.file.get_ref().sync_all()?;
522
523        self.current_lsn = reddb_file::WAL_FILE_HEADER_BYTES as u64;
524        self.durable_lsn = reddb_file::WAL_FILE_HEADER_BYTES as u64;
525        self.last_synced_size = reddb_file::WAL_FILE_HEADER_BYTES as u64;
526        self.prealloc_metadata_dirty = false;
527        #[cfg(test)]
528        {
529            self.last_sync_method = Some(WalSyncMethod::All);
530        }
531
532        // `set_len(0)` freed every reserved block, so the WAL would otherwise
533        // grow page-by-page again from here. Re-extend a fresh segment now —
534        // this is the "truncate/re-extend on checkpoint" half of issue #893.
535        self.preallocated_to = 0;
536        self.ensure_preallocated()?;
537        Ok(())
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use std::path::PathBuf;
545
546    struct FileGuard {
547        path: PathBuf,
548    }
549
550    impl Drop for FileGuard {
551        fn drop(&mut self) {
552            let _ = std::fs::remove_file(&self.path);
553        }
554    }
555
556    fn temp_wal(name: &str) -> (FileGuard, PathBuf) {
557        let path = reddb_file::layout::wal_component_temp_path(
558            &std::env::temp_dir(),
559            "writer",
560            name,
561            std::process::id(),
562        );
563        let guard = FileGuard { path: path.clone() };
564        let _ = std::fs::remove_file(&path);
565        (guard, path)
566    }
567
568    #[test]
569    fn test_create_new_wal() {
570        let (_guard, path) = temp_wal("create");
571        let writer = WalWriter::open(&path).expect("open() should succeed");
572
573        // Should start at LSN 8 (after 8-byte header)
574        assert_eq!(writer.current_lsn(), 8);
575        assert!(path.exists());
576    }
577
578    #[test]
579    fn test_append_record() {
580        let (_guard, path) = temp_wal("append");
581        let mut writer = WalWriter::open(&path).expect("open() should succeed");
582
583        let record = WalRecord::Begin { tx_id: 42 };
584        let lsn = writer.append(&record).expect("append() should succeed");
585
586        // First record starts at LSN 8
587        assert_eq!(lsn, 8);
588
589        // Next record should start after encoded size
590        // Begin record (v3 framing): 1 (type) + 8 (term) + 8 (ownership_epoch)
591        //   + 8 (tx_id) + 4 (checksum) = 29 bytes
592        assert_eq!(writer.current_lsn(), 8 + 29);
593    }
594
595    #[test]
596    fn test_append_multiple_records() {
597        let (_guard, path) = temp_wal("multi");
598        let mut writer = WalWriter::open(&path).expect("open() should succeed");
599
600        let lsn1 = writer
601            .append(&WalRecord::Begin { tx_id: 1 })
602            .expect("append() should succeed");
603        let lsn2 = writer
604            .append(&WalRecord::Begin { tx_id: 2 })
605            .expect("append() should succeed");
606        let lsn3 = writer
607            .append(&WalRecord::Commit { tx_id: 1 })
608            .expect("append() should succeed");
609
610        assert_eq!(lsn1, 8);
611        assert_eq!(lsn2, 8 + 29);
612        assert_eq!(lsn3, 8 + 29 + 29);
613    }
614
615    #[test]
616    fn test_page_write_lsn() {
617        let (_guard, path) = temp_wal("pagewrite");
618        let mut writer = WalWriter::open(&path).expect("open() should succeed");
619
620        // First record
621        let lsn1 = writer
622            .append(&WalRecord::Begin { tx_id: 1 })
623            .expect("append() should succeed");
624        assert_eq!(lsn1, 8);
625
626        // PageWrite record (v3 framing): +8 bytes for ownership_epoch vs v2
627        let data = vec![1, 2, 3, 4, 5];
628        let lsn2 = writer
629            .append(&WalRecord::PageWrite {
630                tx_id: 1,
631                page_id: 100,
632                data: data.clone(),
633            })
634            .expect("value is present");
635
636        assert_eq!(lsn2, 8 + 29); // after Begin
637
638        // Next LSN = lsn2 + (1 + 8 + 8 + 8 + 4 + 4 + 5 + 4) = lsn2 + 42
639        assert_eq!(writer.current_lsn(), 8 + 29 + 42);
640    }
641
642    #[test]
643    fn test_sync() {
644        let (_guard, path) = temp_wal("sync");
645        let mut writer = WalWriter::open(&path).expect("open() should succeed");
646
647        writer
648            .append(&WalRecord::Begin { tx_id: 1 })
649            .expect("append() should succeed");
650        writer.sync().expect("sync() should succeed");
651
652        // File should be synced, just verify no error
653        assert!(path.exists());
654    }
655
656    #[test]
657    fn test_truncate() {
658        let (_guard, path) = temp_wal("truncate");
659        let mut writer = WalWriter::open(&path).expect("open() should succeed");
660
661        // Write some records
662        writer
663            .append(&WalRecord::Begin { tx_id: 1 })
664            .expect("append() should succeed");
665        writer
666            .append(&WalRecord::PageWrite {
667                tx_id: 1,
668                page_id: 0,
669                data: vec![0; 100],
670            })
671            .expect("value is present");
672        writer
673            .append(&WalRecord::Commit { tx_id: 1 })
674            .expect("append() should succeed");
675
676        let lsn_before = writer.current_lsn();
677        assert!(lsn_before > 8);
678
679        // Truncate
680        writer.truncate().expect("truncate() should succeed");
681
682        // LSN should be back to 8
683        assert_eq!(writer.current_lsn(), 8);
684
685        // File should be 8 bytes (just header)
686        let len = std::fs::metadata(&path)
687            .expect("metadata() should succeed")
688            .len();
689        assert_eq!(len, 8);
690    }
691
692    #[test]
693    fn test_reopen_existing() {
694        let (_guard, path) = temp_wal("reopen");
695
696        // Create and write
697        let lsn_after_write;
698        {
699            let mut writer = WalWriter::open(&path).expect("open() should succeed");
700            writer
701                .append(&WalRecord::Begin { tx_id: 1 })
702                .expect("append() should succeed");
703            writer
704                .append(&WalRecord::Commit { tx_id: 1 })
705                .expect("append() should succeed");
706            lsn_after_write = writer.current_lsn();
707        }
708
709        // Reopen
710        {
711            let writer = WalWriter::open(&path).expect("open() should succeed");
712            // Should continue from where we left off
713            assert_eq!(writer.current_lsn(), lsn_after_write);
714        }
715    }
716
717    #[test]
718    fn test_checkpoint_record() {
719        let (_guard, path) = temp_wal("checkpoint");
720        let mut writer = WalWriter::open(&path).expect("open() should succeed");
721
722        // Checkpoint is same size as Begin (v3: 1 + 8 + 8 + 8 + 4 = 29)
723        let lsn = writer
724            .append(&WalRecord::Checkpoint { lsn: 12345 })
725            .expect("value is present");
726        assert_eq!(lsn, 8);
727        assert_eq!(writer.current_lsn(), 8 + 29);
728    }
729
730    // -----------------------------------------------------------------
731    // Target 3: durable_lsn / flush_until tests
732    // -----------------------------------------------------------------
733
734    #[test]
735    fn fresh_wal_has_durable_lsn_at_header_end() {
736        let (_guard, path) = temp_wal("durable_init");
737        let writer = WalWriter::open(&path).expect("open() should succeed");
738        assert_eq!(writer.durable_lsn(), 8);
739        assert_eq!(writer.current_lsn(), 8);
740    }
741
742    #[test]
743    fn flush_until_below_durable_is_noop() {
744        let (_guard, path) = temp_wal("flush_noop");
745        let mut writer = WalWriter::open(&path).expect("open() should succeed");
746        // After open, durable_lsn == 8.
747        let before = writer.durable_lsn();
748        writer.flush_until(0).expect("flush_until() should succeed");
749        writer.flush_until(8).expect("flush_until() should succeed");
750        assert_eq!(writer.durable_lsn(), before);
751    }
752
753    #[test]
754    fn flush_until_advances_durable_to_current() {
755        let (_guard, path) = temp_wal("flush_advance");
756        let mut writer = WalWriter::open(&path).expect("open() should succeed");
757        writer
758            .append(&WalRecord::Begin { tx_id: 7 })
759            .expect("append() should succeed");
760        writer
761            .append(&WalRecord::Commit { tx_id: 7 })
762            .expect("append() should succeed");
763        let target = writer.current_lsn();
764        // Before flush_until, durable still at the header.
765        assert_eq!(writer.durable_lsn(), 8);
766        writer
767            .flush_until(target)
768            .expect("flush_until() should succeed");
769        assert_eq!(writer.durable_lsn(), target);
770    }
771
772    #[test]
773    fn flush_until_is_monotonic() {
774        let (_guard, path) = temp_wal("flush_monotonic");
775        let mut writer = WalWriter::open(&path).expect("open() should succeed");
776        writer
777            .append(&WalRecord::Begin { tx_id: 1 })
778            .expect("append() should succeed");
779        let lo = writer.current_lsn();
780        writer
781            .flush_until(lo)
782            .expect("flush_until() should succeed");
783        let durable_after_lo = writer.durable_lsn();
784        writer
785            .append(&WalRecord::Commit { tx_id: 1 })
786            .expect("append() should succeed");
787        let hi = writer.current_lsn();
788        writer
789            .flush_until(hi)
790            .expect("flush_until() should succeed");
791        assert!(writer.durable_lsn() >= durable_after_lo);
792        // Calling flush_until(lo) after flush_until(hi) is a no-op.
793        writer
794            .flush_until(lo)
795            .expect("flush_until() should succeed");
796        assert_eq!(writer.durable_lsn(), hi);
797    }
798
799    #[test]
800    fn sync_advances_durable_lsn_too() {
801        let (_guard, path) = temp_wal("sync_durable");
802        let mut writer = WalWriter::open(&path).expect("open() should succeed");
803        writer
804            .append(&WalRecord::Begin { tx_id: 9 })
805            .expect("append() should succeed");
806        let before = writer.durable_lsn();
807        let after_append = writer.current_lsn();
808        assert!(after_append > before);
809        writer.sync().expect("sync() should succeed");
810        assert_eq!(writer.durable_lsn(), after_append);
811    }
812
813    #[test]
814    fn sync_all_is_used_when_wal_size_grew() {
815        let (_guard, path) = temp_wal("sync_all_grew");
816        let mut writer = WalWriter::open(&path).expect("open() should succeed");
817
818        writer
819            .append(&WalRecord::Begin { tx_id: 1 })
820            .expect("append() should succeed");
821        writer.sync().expect("sync() should succeed");
822
823        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::All));
824        assert!(writer.last_synced_size >= writer.current_lsn());
825        assert!(!writer.prealloc_metadata_dirty);
826    }
827
828    #[test]
829    fn sync_all_is_used_for_metadata_only_preallocation() {
830        let (_guard, path) = temp_wal("sync_all_prealloc_metadata");
831        let mut writer = WalWriter::open(&path).expect("open() should succeed");
832        if !writer.prealloc_supported {
833            return;
834        }
835
836        assert_eq!(writer.current_lsn(), 8);
837        assert!(writer.prealloc_metadata_dirty);
838
839        writer.sync().expect("sync() should succeed");
840
841        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::All));
842        assert_eq!(writer.last_synced_size, writer.preallocated_to);
843        assert!(!writer.prealloc_metadata_dirty);
844    }
845
846    #[test]
847    fn sync_data_is_used_when_wal_size_is_unchanged() {
848        let (_guard, path) = temp_wal("sync_data_unchanged");
849        let mut writer = WalWriter::open(&path).expect("open() should succeed");
850
851        writer
852            .append(&WalRecord::Begin { tx_id: 1 })
853            .expect("append() should succeed");
854        writer.sync().expect("sync() should succeed");
855        let synced_size = writer.last_synced_size;
856        writer.sync().expect("sync() should succeed");
857
858        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::Data));
859        assert_eq!(writer.last_synced_size, synced_size);
860        assert_eq!(writer.durable_lsn(), writer.current_lsn());
861    }
862
863    #[test]
864    fn sync_data_is_used_for_appends_within_synced_preallocation() {
865        let (_guard, path) = temp_wal("sync_data_preallocated_append");
866        let mut writer = WalWriter::open(&path).expect("open() should succeed");
867        if !writer.prealloc_supported {
868            return;
869        }
870
871        writer
872            .append(&WalRecord::Begin { tx_id: 1 })
873            .expect("append() should succeed");
874        writer.sync().expect("sync() should succeed");
875        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::All));
876
877        writer
878            .append(&WalRecord::Commit { tx_id: 1 })
879            .expect("append() should succeed");
880        writer.sync().expect("sync() should succeed");
881
882        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::Data));
883        assert_eq!(writer.durable_lsn(), writer.current_lsn());
884        assert!(writer.current_lsn() <= writer.last_synced_size);
885    }
886
887    #[test]
888    fn group_sync_uses_sync_data_within_synced_preallocation() {
889        let (_guard, path) = temp_wal("group_sync_data_preallocated_append");
890        let mut writer = WalWriter::open(&path).expect("open() should succeed");
891        if !writer.prealloc_supported {
892            return;
893        }
894
895        writer
896            .append(&WalRecord::Begin { tx_id: 1 })
897            .expect("append() should succeed");
898        writer.sync().expect("sync() should succeed");
899        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::All));
900
901        writer
902            .append(&WalRecord::Commit { tx_id: 1 })
903            .expect("append() should succeed");
904        let sync = writer
905            .drain_for_group_sync()
906            .expect("drain_for_group_sync() should succeed");
907        assert_eq!(sync.method, WalSyncMethod::Data);
908        sync.sync().expect("sync() should succeed");
909        writer.mark_durable(&sync);
910
911        assert_eq!(writer.last_sync_method, Some(WalSyncMethod::Data));
912        assert_eq!(writer.durable_lsn(), writer.current_lsn());
913    }
914
915    #[test]
916    fn truncate_resets_durable_lsn() {
917        let (_guard, path) = temp_wal("truncate_durable");
918        let mut writer = WalWriter::open(&path).expect("open() should succeed");
919        writer
920            .append(&WalRecord::Begin { tx_id: 1 })
921            .expect("append() should succeed");
922        writer.sync().expect("sync() should succeed");
923        assert!(writer.durable_lsn() > 8);
924        writer.truncate().expect("truncate() should succeed");
925        assert_eq!(writer.durable_lsn(), 8);
926        assert_eq!(writer.current_lsn(), 8);
927    }
928
929    #[test]
930    fn reopen_initialises_durable_to_current() {
931        let (_guard, path) = temp_wal("reopen_durable");
932        {
933            let mut writer = WalWriter::open(&path).expect("open() should succeed");
934            writer
935                .append(&WalRecord::Begin { tx_id: 1 })
936                .expect("append() should succeed");
937            writer.sync().expect("sync() should succeed");
938        }
939        let writer = WalWriter::open(&path).expect("open() should succeed");
940        // After reopen, every byte on disk is durable by definition.
941        assert_eq!(writer.durable_lsn(), writer.current_lsn());
942    }
943
944    // -----------------------------------------------------------------
945    // Perf 1.1: BufWriter coalesces small appends until sync
946    // -----------------------------------------------------------------
947
948    #[test]
949    fn bufwriter_coalesces_until_sync() {
950        // Append 100 small records but DO NOT sync. The on-disk file
951        // size must still equal the header (8 bytes) because the
952        // bytes are sitting in the BufWriter, not in the kernel.
953        let (_guard, path) = temp_wal("bufwriter_coalesce");
954        let mut writer = WalWriter::open(&path).expect("open() should succeed");
955        for tx in 0..100u64 {
956            writer
957                .append(&WalRecord::Begin { tx_id: tx })
958                .expect("append() should succeed");
959        }
960        // current_lsn reflects the in-buffer position. Each v3 Begin record is
961        // 29 bytes: 1 (type) + 8 (term) + 8 (ownership_epoch) + 8 (tx_id)
962        //   + 4 (checksum).
963        assert_eq!(writer.current_lsn(), 8 + 100 * 29);
964        // But the file on disk only has the header.
965        let on_disk = std::fs::metadata(&path)
966            .expect("metadata() should succeed")
967            .len();
968        assert_eq!(on_disk, 8, "BufWriter leaked bytes to disk before sync");
969    }
970
971    #[test]
972    fn sync_drains_bufwriter_before_fsync() {
973        // After sync(), the file size must equal current_lsn — the
974        // BufWriter has been flushed and sync_all has hit the kernel.
975        let (_guard, path) = temp_wal("sync_drains");
976        let mut writer = WalWriter::open(&path).expect("open() should succeed");
977        for tx in 0..50u64 {
978            writer
979                .append(&WalRecord::Begin { tx_id: tx })
980                .expect("append() should succeed");
981        }
982        writer.sync().expect("sync() should succeed");
983        let on_disk = std::fs::metadata(&path)
984            .expect("metadata() should succeed")
985            .len();
986        assert_eq!(on_disk, writer.current_lsn());
987        assert_eq!(writer.durable_lsn(), writer.current_lsn());
988    }
989
990    #[test]
991    fn flush_until_drains_bufwriter_too() {
992        // flush_until must drain the BufWriter before calling
993        // sync_all on the underlying file — otherwise pending bytes
994        // never become durable.
995        let (_guard, path) = temp_wal("flush_until_drains");
996        let mut writer = WalWriter::open(&path).expect("open() should succeed");
997        for tx in 0..30u64 {
998            writer
999                .append(&WalRecord::Begin { tx_id: tx })
1000                .expect("append() should succeed");
1001        }
1002        let target = writer.current_lsn();
1003        writer
1004            .flush_until(target)
1005            .expect("flush_until() should succeed");
1006        let on_disk = std::fs::metadata(&path)
1007            .expect("metadata() should succeed")
1008            .len();
1009        assert_eq!(on_disk, target);
1010        assert_eq!(writer.durable_lsn(), target);
1011    }
1012
1013    #[test]
1014    fn truncate_drains_pending_bufwriter_bytes_first() {
1015        // If truncate did NOT drain BufWriter first, the pending bytes
1016        // would either land in the post-truncate file (corrupting it
1017        // with stale records) or be lost. Verify the resulting file
1018        // contains only a fresh header.
1019        let (_guard, path) = temp_wal("truncate_drain");
1020        let mut writer = WalWriter::open(&path).expect("open() should succeed");
1021        // Write enough small records to fill some of the 64 KiB buffer
1022        // but stay below the auto-flush threshold.
1023        for tx in 0..200u64 {
1024            writer
1025                .append(&WalRecord::Begin { tx_id: tx })
1026                .expect("append() should succeed");
1027        }
1028        // Sanity: bytes are buffered.
1029        assert_eq!(
1030            std::fs::metadata(&path)
1031                .expect("metadata() should succeed")
1032                .len(),
1033            8
1034        );
1035
1036        writer.truncate().expect("truncate() should succeed");
1037        // After truncate the file is just the header again.
1038        let on_disk = std::fs::metadata(&path)
1039            .expect("metadata() should succeed")
1040            .len();
1041        assert_eq!(on_disk, 8);
1042        assert_eq!(writer.current_lsn(), 8);
1043        assert_eq!(writer.durable_lsn(), 8);
1044
1045        // And we can append again successfully.
1046        writer
1047            .append(&WalRecord::Begin { tx_id: 99 })
1048            .expect("append() should succeed");
1049        writer.sync().expect("sync() should succeed");
1050        assert_eq!(
1051            std::fs::metadata(&path)
1052                .expect("metadata() should succeed")
1053                .len(),
1054            8 + 29
1055        );
1056    }
1057
1058    #[test]
1059    fn reopen_sees_only_synced_records() {
1060        // Records that were appended but never sync'd must NOT
1061        // survive a reopen — they lived in the BufWriter, never made
1062        // it to the kernel, and the previous WalWriter went out of
1063        // scope. The new WalWriter reopens the file and reads from
1064        // EOF, which reflects only the bytes that hit disk.
1065        //
1066        // We sync some records, then drop the writer mid-buffer, and
1067        // assert the reopen LSN matches only the synced prefix.
1068        let (_guard, path) = temp_wal("reopen_synced_only");
1069        let synced_lsn;
1070        {
1071            let mut writer = WalWriter::open(&path).expect("open() should succeed");
1072            writer
1073                .append(&WalRecord::Begin { tx_id: 1 })
1074                .expect("append() should succeed");
1075            writer.sync().expect("sync() should succeed");
1076            synced_lsn = writer.current_lsn();
1077            // These records are never sync'd before drop. Drop runs
1078            // BufWriter::flush which DOES write them — see note below.
1079            for tx in 100..120u64 {
1080                writer
1081                    .append(&WalRecord::Begin { tx_id: tx })
1082                    .expect("append() should succeed");
1083            }
1084            // Without a sync, the in-buffer bytes are still pending.
1085            // BufWriter's Drop impl does flush to the file but does
1086            // not call sync_all. For reopen-LSN purposes, on-disk
1087            // bytes count regardless of fsync, so the reopened LSN
1088            // will reflect the dropped writes too.
1089        }
1090        let writer = WalWriter::open(&path).expect("open() should succeed");
1091        // The reopen LSN reflects what's physically on disk after
1092        // BufWriter::Drop flushes its buffer. That may or may not
1093        // include the unsync'd records depending on platform; the
1094        // contract we care about is that durable_lsn ≥ synced_lsn.
1095        assert!(writer.durable_lsn() >= synced_lsn);
1096    }
1097
1098    // -----------------------------------------------------------------
1099    // Issue #893: fallocate-based WAL segment preallocation
1100    // -----------------------------------------------------------------
1101
1102    /// On-disk blocks reserved by `fallocate`, in bytes. Returns the
1103    /// allocated size (st_blocks × 512), independent of the logical length.
1104    fn allocated_bytes(path: &std::path::Path) -> u64 {
1105        use fs2::FileExt;
1106        let f = std::fs::File::open(path).expect("open() should succeed");
1107        f.allocated_size().expect("allocated_size() should succeed")
1108    }
1109
1110    #[test]
1111    fn segment_boundary_rounds_strictly_up() {
1112        // Always lands one boundary ahead so the reservation stays in front
1113        // of the write frontier.
1114        assert_eq!(
1115            reddb_file::next_main_wal_segment_boundary(0),
1116            reddb_file::MAIN_WAL_SEGMENT_BYTES
1117        );
1118        assert_eq!(
1119            reddb_file::next_main_wal_segment_boundary(8),
1120            reddb_file::MAIN_WAL_SEGMENT_BYTES
1121        );
1122        assert_eq!(
1123            reddb_file::next_main_wal_segment_boundary(reddb_file::MAIN_WAL_SEGMENT_BYTES - 1),
1124            reddb_file::MAIN_WAL_SEGMENT_BYTES
1125        );
1126        // Exactly on a boundary still advances to the next one.
1127        assert_eq!(
1128            reddb_file::next_main_wal_segment_boundary(reddb_file::MAIN_WAL_SEGMENT_BYTES),
1129            2 * reddb_file::MAIN_WAL_SEGMENT_BYTES
1130        );
1131        assert_eq!(
1132            reddb_file::next_main_wal_segment_boundary(reddb_file::MAIN_WAL_SEGMENT_BYTES + 1),
1133            2 * reddb_file::MAIN_WAL_SEGMENT_BYTES
1134        );
1135    }
1136
1137    #[test]
1138    fn open_preallocates_first_segment() {
1139        // A freshly opened WAL must reserve a whole segment up front instead
1140        // of growing incrementally (acceptance #1).
1141        let (_guard, path) = temp_wal("prealloc_open");
1142        let writer = WalWriter::open(&path).expect("open() should succeed");
1143        if !writer.prealloc_supported {
1144            return; // filesystem without fallocate — feature is a no-op.
1145        }
1146        assert_eq!(writer.preallocated_to, reddb_file::MAIN_WAL_SEGMENT_BYTES);
1147        // The reservation is real on disk, yet the logical file is still just
1148        // the 8-byte header.
1149        assert!(allocated_bytes(&path) >= reddb_file::MAIN_WAL_SEGMENT_BYTES);
1150        assert_eq!(
1151            std::fs::metadata(&path)
1152                .expect("metadata() should succeed")
1153                .len(),
1154            8
1155        );
1156    }
1157
1158    #[test]
1159    fn preallocation_does_not_grow_logical_length() {
1160        // The load-bearing invariant for crash recovery: appending records
1161        // must NOT inflate the logical file size beyond the real data, or the
1162        // EOF scan in WalReader would walk into the reserved tail. Holds on
1163        // every filesystem (fallocate keeps i_size pinned; absent fallocate
1164        // there is no reservation at all).
1165        let (_guard, path) = temp_wal("prealloc_logical");
1166        let mut writer = WalWriter::open(&path).expect("open() should succeed");
1167        for tx in 0..50u64 {
1168            writer
1169                .append(&WalRecord::Begin { tx_id: tx })
1170                .expect("append() should succeed");
1171        }
1172        writer.sync().expect("sync() should succeed");
1173        let logical = std::fs::metadata(&path)
1174            .expect("metadata() should succeed")
1175            .len();
1176        assert_eq!(logical, 8 + 50 * 29, "preallocation inflated i_size");
1177        assert_eq!(writer.current_lsn(), logical);
1178    }
1179
1180    #[test]
1181    fn truncate_re_extends_a_fresh_segment() {
1182        // After checkpoint truncation the WAL must re-extend rather than grow
1183        // unbounded page-by-page (acceptance #2).
1184        let (_guard, path) = temp_wal("prealloc_truncate");
1185        let mut writer = WalWriter::open(&path).expect("open() should succeed");
1186        writer
1187            .append(&WalRecord::Begin { tx_id: 1 })
1188            .expect("append() should succeed");
1189        writer.sync().expect("sync() should succeed");
1190
1191        writer.truncate().expect("truncate() should succeed");
1192
1193        assert_eq!(writer.current_lsn(), 8);
1194        assert_eq!(
1195            std::fs::metadata(&path)
1196                .expect("metadata() should succeed")
1197                .len(),
1198            8
1199        );
1200        if writer.prealloc_supported {
1201            assert_eq!(writer.preallocated_to, reddb_file::MAIN_WAL_SEGMENT_BYTES);
1202            assert!(allocated_bytes(&path) >= reddb_file::MAIN_WAL_SEGMENT_BYTES);
1203        }
1204    }
1205
1206    #[test]
1207    fn preallocated_wal_recovers_records_without_trailing_garbage() {
1208        // End-to-end: a preallocated WAL must read back exactly the records
1209        // written — the reserved (unwritten) tail must be invisible to the
1210        // reader, proving crash-recovery is unchanged (acceptance #3).
1211        use super::super::reader::WalReader;
1212        let (_guard, path) = temp_wal("prealloc_recover");
1213        {
1214            let mut writer = WalWriter::open(&path).expect("open() should succeed");
1215            writer
1216                .append(&WalRecord::Begin { tx_id: 1 })
1217                .expect("append() should succeed");
1218            writer
1219                .append(&WalRecord::PageWrite {
1220                    tx_id: 1,
1221                    page_id: 7,
1222                    data: vec![1, 2, 3, 4],
1223                })
1224                .expect("value is present");
1225            writer
1226                .append(&WalRecord::Commit { tx_id: 1 })
1227                .expect("append() should succeed");
1228            writer.sync().expect("sync() should succeed");
1229        }
1230        let records: Vec<_> = WalReader::open(&path)
1231            .expect("value is present")
1232            .iter()
1233            .collect::<Result<_, _>>()
1234            .expect("reader must stop cleanly at real EOF, not in reserved tail");
1235        assert_eq!(records.len(), 3);
1236        assert_eq!(records[0].1, WalRecord::Begin { tx_id: 1 });
1237        assert_eq!(records[2].1, WalRecord::Commit { tx_id: 1 });
1238    }
1239}