Skip to main content

wal_db/
wal.rs

1//! The log itself: [`Wal`], its recovery iterator [`WalIter`], and the
2//! [`Record`] iteration yields.
3
4use std::{fmt, io, sync::atomic::Ordering};
5
6#[cfg(not(loom))]
7use std::{cell::RefCell, path::Path};
8
9use crate::{
10    commit::Commit,
11    config::{OpenPolicy, RecoveryPolicy, WalConfig},
12    error::{Result, WalError},
13    lsn::Lsn,
14    record::{self, HEADER_LEN},
15    store::{FileStore, WalStore},
16    strict::{self, Tail},
17    sync::AtomicU64,
18};
19
20/// A cache-line-aligned wrapper, used to keep the heavily-written reservation
21/// counter off the same cache line as the rest of the log's fields so appenders
22/// hammering it do not invalidate readers' caches (false sharing).
23#[repr(align(64))]
24#[derive(Debug)]
25struct CacheAligned<T>(T);
26
27/// A durable, append-only log.
28///
29/// `Wal` is the entry point. The four calls that cover almost every use are
30/// [`open`](Wal::open), [`append`](Wal::append), [`sync`](Wal::sync), and
31/// [`iter`](Wal::iter). The type parameter `S` is the storage backend and
32/// defaults to [`FileStore`], so the plain name `Wal` is the file-backed log;
33/// custom backends are supplied through [`with_store`](Wal::with_store).
34///
35/// A `Wal` is [`Send`] and [`Sync`], and the append path is built for it: many
36/// threads can call [`append`](Wal::append) at once with no global lock. Share
37/// one behind an [`Arc`](std::sync::Arc) and write from every thread.
38///
39/// # Concurrency and durability
40///
41/// Appends are lock-free. Each one reserves its byte range with a single atomic
42/// step — the range's start offset *is* the record's [`Lsn`] — frames the record
43/// into a reused thread-local buffer, and writes it, all without blocking other
44/// appenders. [`sync`](Wal::sync) is the durability barrier; when several
45/// threads sync at once they coalesce into a single fsync (group commit), so the
46/// cost of making data durable is amortised across everyone committing together.
47///
48/// `append` returns once the record is in the OS page cache; `sync` returns once
49/// it is on stable storage. See the [crate docs](crate) for the full contract.
50///
51/// # Examples
52///
53/// ```
54/// use wal_db::Wal;
55///
56/// # fn main() -> Result<(), wal_db::WalError> {
57/// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
58/// # let path = dir.path().join("log.wal");
59/// let wal = Wal::open(&path)?;
60/// let first = wal.append(b"first")?;
61/// let second = wal.append(b"second")?;
62/// wal.sync()?;
63///
64/// // LSNs are byte offsets: the first record starts at 0, the second after it.
65/// assert_eq!(first.get(), 0);
66/// assert!(second.get() > first.get());
67///
68/// let read_back: Vec<Vec<u8>> = wal
69///     .iter()?
70///     .map(|entry| entry.map(|record| record.into_data()))
71///     .collect::<Result<_, _>>()?;
72/// assert_eq!(read_back, vec![b"first".to_vec(), b"second".to_vec()]);
73/// # Ok(())
74/// # }
75/// ```
76pub struct Wal<S = FileStore> {
77    /// Next byte offset to reserve. Hammered by every appender, so kept on its
78    /// own cache line.
79    tail: CacheAligned<AtomicU64>,
80    store: S,
81    max_record_size: u32,
82    recovery_policy: RecoveryPolicy,
83    /// Lowest readable offset — `0` until a prefix is dropped by
84    /// [`truncate_before`](Wal::truncate_before).
85    head: AtomicU64,
86    commit: Commit,
87    /// Bytes the open scan cut from the end of the store.
88    truncated_on_open: u64,
89}
90
91#[cfg(not(loom))]
92impl Wal<FileStore> {
93    /// Open the log at `path`, creating it if it does not exist.
94    ///
95    /// On open the log scans its contents, stops at the first record that is
96    /// incomplete or fails its checksum, and truncates that torn tail so the
97    /// next append lands on a clean boundary. The common cause of a torn tail is
98    /// a crash partway through an earlier append; that record was never
99    /// acknowledged durable, so discarding it loses nothing the caller was
100    /// promised. Damage in the middle of the log is cut the same way, with the
101    /// intact records after it; to refuse that instead, open with
102    /// [`OpenPolicy::Strict`] through [`open_with`](Wal::open_with).
103    /// [`truncated_on_open`](Wal::truncated_on_open) reports what was cut.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`WalError::Io`] if the file cannot be opened or scanned.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// use wal_db::Wal;
113    /// # fn main() -> Result<(), wal_db::WalError> {
114    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
115    /// # let path = dir.path().join("log.wal");
116    /// let wal = Wal::open(&path)?;
117    /// wal.append(b"hello")?;
118    /// wal.sync()?;
119    /// # Ok(())
120    /// # }
121    /// ```
122    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
123        Self::open_with(path, WalConfig::new())
124    }
125
126    /// Open the log at `path` with an explicit [`WalConfig`].
127    ///
128    /// # Errors
129    ///
130    /// - [`WalError::Io`] if the file cannot be opened or scanned.
131    /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
132    ///   follows a damaged record. Nothing is cut.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use wal_db::{Wal, WalConfig};
138    /// # fn main() -> Result<(), wal_db::WalError> {
139    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
140    /// # let path = dir.path().join("log.wal");
141    /// let config = WalConfig::new().with_max_record_size(1024);
142    /// let wal = Wal::open_with(&path, config)?;
143    /// # let _ = wal;
144    /// # Ok(())
145    /// # }
146    /// ```
147    pub fn open_with(path: impl AsRef<Path>, config: WalConfig) -> Result<Self> {
148        let store = FileStore::open(path)?;
149        Self::with_store_and_config(store, config)
150    }
151}
152
153#[cfg(not(loom))]
154impl Wal<crate::segment::SegmentedStore> {
155    /// Open a segmented log in directory `dir`, with segments of `segment_size`
156    /// bytes, creating the directory if needed.
157    ///
158    /// The log is one continuous byte stream striped across fixed-size files, so
159    /// it behaves exactly like a single-file log — records span segment
160    /// boundaries freely — while keeping each file bounded for recovery and
161    /// archival. Records larger than a segment simply occupy several.
162    ///
163    /// # Errors
164    ///
165    /// Returns [`WalError::Io`] if `segment_size` is zero or the directory cannot
166    /// be opened or scanned.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use wal_db::Wal;
172    /// # fn main() -> Result<(), wal_db::WalError> {
173    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
174    /// let wal = Wal::open_segmented(dir.path(), 16 * 1024 * 1024)?; // 16 MiB segments
175    /// wal.append(b"record")?;
176    /// wal.sync()?;
177    /// # Ok(())
178    /// # }
179    /// ```
180    pub fn open_segmented(dir: impl AsRef<Path>, segment_size: u64) -> Result<Self> {
181        Self::open_segmented_with(dir, segment_size, WalConfig::new())
182    }
183
184    /// Open a segmented log with an explicit [`WalConfig`].
185    ///
186    /// Like [`open_segmented`](Wal::open_segmented), but applies `config` (for
187    /// example a tighter [`max_record_size`](WalConfig::max_record_size)).
188    ///
189    /// # Errors
190    ///
191    /// - [`WalError::Io`] if `segment_size` is zero or the directory cannot be
192    ///   opened or scanned.
193    /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
194    ///   follows a damaged record. Nothing is cut.
195    pub fn open_segmented_with(
196        dir: impl AsRef<Path>,
197        segment_size: u64,
198        config: WalConfig,
199    ) -> Result<Self> {
200        let store = crate::segment::SegmentedStore::open(dir, segment_size)?;
201        Self::with_store_and_config(store, config)
202    }
203}
204
205impl<S: WalStore> Wal<S> {
206    /// Build a log over a custom [`WalStore`], using the default configuration.
207    ///
208    /// # Errors
209    ///
210    /// Returns an error if scanning the existing contents of the store fails.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use wal_db::{MemStore, Wal};
216    /// # fn main() -> Result<(), wal_db::WalError> {
217    /// let wal = Wal::with_store(MemStore::new())?;
218    /// wal.append(b"record")?;
219    /// # Ok(())
220    /// # }
221    /// ```
222    pub fn with_store(store: S) -> Result<Self> {
223        Self::with_store_and_config(store, WalConfig::new())
224    }
225
226    /// Build a log over a custom [`WalStore`] with an explicit [`WalConfig`].
227    ///
228    /// # Errors
229    ///
230    /// - Any error the store returns while its existing contents are scanned.
231    /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
232    ///   follows a damaged record. Nothing is cut.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// use wal_db::{MemStore, Wal, WalConfig};
238    /// # fn main() -> Result<(), wal_db::WalError> {
239    /// let config = WalConfig::new().with_max_record_size(64);
240    /// let wal = Wal::with_store_and_config(MemStore::new(), config)?;
241    /// # let _ = wal;
242    /// # Ok(())
243    /// # }
244    /// ```
245    pub fn with_store_and_config(store: S, config: WalConfig) -> Result<Self> {
246        let head = store.head()?;
247        let recovered = recover(&store, &config, head)?;
248        Ok(Wal {
249            tail: CacheAligned(AtomicU64::new(recovered.end)),
250            store,
251            max_record_size: config.max_record_size(),
252            recovery_policy: config.recovery_policy(),
253            head: AtomicU64::new(head),
254            commit: Commit::new(recovered.end),
255            truncated_on_open: recovered.cut,
256        })
257    }
258
259    /// How many bytes opening the log cut from its end.
260    ///
261    /// Zero when the log opened clean. Otherwise the open scan stopped at an
262    /// incomplete or damaged record and cut it and everything after it, as the
263    /// configured [`OpenPolicy`] allowed. Under
264    /// [`OpenPolicy::Strict`] a non-zero value is only ever a torn tail. Under
265    /// the default [`OpenPolicy::TruncateTail`] it can also include intact
266    /// records that followed damage in the middle of the log; a consumer that
267    /// knows how much it last made durable can compare.
268    ///
269    /// # Examples
270    ///
271    /// ```
272    /// use std::io::Write;
273    /// use wal_db::{Wal, WalError};
274    ///
275    /// # fn main() -> Result<(), WalError> {
276    /// # let dir = tempfile::tempdir().map_err(WalError::from)?;
277    /// # let path = dir.path().join("log.wal");
278    /// let wal = Wal::open(&path)?;
279    /// assert_eq!(wal.truncated_on_open(), 0); // a new log has nothing to cut
280    /// wal.append_and_sync(b"kept")?;
281    /// drop(wal);
282    ///
283    /// // Five stray bytes after the last record: a torn tail.
284    /// let mut file = std::fs::OpenOptions::new().append(true).open(&path)?;
285    /// file.write_all(&[0xAB; 5])?;
286    /// drop(file);
287    ///
288    /// let wal = Wal::open(&path)?;
289    /// assert_eq!(wal.truncated_on_open(), 5);
290    /// assert_eq!(wal.iter()?.count(), 1);
291    /// # Ok(())
292    /// # }
293    /// ```
294    #[must_use]
295    pub fn truncated_on_open(&self) -> u64 {
296        self.truncated_on_open
297    }
298
299    /// Append `record` to the log and return the [`Lsn`] it was assigned — the
300    /// byte offset where the record begins.
301    ///
302    /// Lock-free: the byte range is reserved with one atomic step and the record
303    /// is written without blocking other appenders. Returns once the bytes are
304    /// in the operating system's page cache. It does **not** flush the disk —
305    /// call [`sync`](Wal::sync) for that. A crash between `append` and `sync` may
306    /// lose the record.
307    ///
308    /// # Errors
309    ///
310    /// - [`WalError::RecordTooLarge`] if `record` is larger than the configured
311    ///   [`max_record_size`](WalConfig::max_record_size). The log is unchanged.
312    /// - [`WalError::Io`] if the write fails. The reserved range becomes a
313    ///   permanent gap: the log is durable only up to that point, recovery stops
314    ///   there, and later syncs covering it report the truncation.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use wal_db::{MemStore, Wal};
320    /// # fn main() -> Result<(), wal_db::WalError> {
321    /// let wal = Wal::with_store(MemStore::new())?;
322    /// let lsn = wal.append(b"some bytes")?;
323    /// assert_eq!(lsn.get(), 0);
324    /// # Ok(())
325    /// # }
326    /// ```
327    pub fn append(&self, record: &[u8]) -> Result<Lsn> {
328        let payload_len = record.len();
329        if payload_len > self.max_record_size as usize {
330            return Err(WalError::RecordTooLarge {
331                len: payload_len,
332                max: self.max_record_size,
333            });
334        }
335        let frame_len = record::framed_len(payload_len) as u64;
336
337        // Reserve the byte range. The returned start offset is the LSN, and
338        // because it comes from a single atomic it is unique and ordered.
339        let start = self.tail.0.fetch_add(frame_len, Ordering::Relaxed);
340        let end = match start.checked_add(frame_len) {
341            Some(end) => end,
342            None => {
343                self.commit.mark_failed(start);
344                return Err(WalError::io(
345                    "reserving a record offset",
346                    io::Error::other("log size exceeds u64"),
347                ));
348            }
349        };
350
351        match self.frame_and_write(start, record) {
352            Ok(()) => {
353                self.commit.mark_written(start, end);
354                Ok(Lsn::new(start))
355            }
356            Err(error) => {
357                self.commit.mark_failed(start);
358                Err(error)
359            }
360        }
361    }
362
363    /// Make every record appended before this call durable.
364    ///
365    /// Returns once the data is on stable storage, using the platform's true
366    /// durability barrier. Concurrent calls coalesce into a single fsync, so the
367    /// flush cost is shared by everyone committing at the same time.
368    ///
369    /// # Errors
370    ///
371    /// Returns [`WalError::Io`] if the flush fails, or [`WalError::Corruption`]
372    /// if an earlier append's write failed and left a gap that cannot be made
373    /// durable. A failed sync means the records are not durable; treat it as
374    /// fatal, not as something to retry blindly. The log does not remember the
375    /// failure: a later `sync` can return `Ok` although the operating system may
376    /// have dropped the pages the failed flush did not write. After a failed
377    /// sync, stop appending and reopen the log, so recovery decides what
378    /// survived.
379    ///
380    /// # Examples
381    ///
382    /// ```
383    /// use wal_db::Wal;
384    /// # fn main() -> Result<(), wal_db::WalError> {
385    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
386    /// # let path = dir.path().join("log.wal");
387    /// let wal = Wal::open(&path)?;
388    /// wal.append(b"durable me")?;
389    /// wal.sync()?; // now on stable storage
390    /// # Ok(())
391    /// # }
392    /// ```
393    pub fn sync(&self) -> Result<()> {
394        let target = self.tail.0.load(Ordering::Acquire);
395        if target == 0 {
396            return Ok(());
397        }
398        self.commit.sync_to(&self.store, target)
399    }
400
401    /// Append `record` and make it durable in one call, returning its [`Lsn`].
402    ///
403    /// Equivalent to [`append`](Wal::append) followed by a [`sync`](Wal::sync)
404    /// scoped to this record, but with the sync coalesced into the group commit
405    /// of any other threads syncing at the same moment. Use it when every record
406    /// must be durable before you proceed and you want the group-commit
407    /// throughput without managing the two calls yourself.
408    ///
409    /// # Errors
410    ///
411    /// The union of [`append`](Wal::append)'s and [`sync`](Wal::sync)'s errors.
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// use wal_db::Wal;
417    /// # fn main() -> Result<(), wal_db::WalError> {
418    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
419    /// # let path = dir.path().join("log.wal");
420    /// let wal = Wal::open(&path)?;
421    /// let lsn = wal.append_and_sync(b"committed immediately")?;
422    /// # let _ = lsn;
423    /// # Ok(())
424    /// # }
425    /// ```
426    pub fn append_and_sync(&self, record: &[u8]) -> Result<Lsn> {
427        let lsn = self.append(record)?;
428        let end = lsn.get() + record::framed_len(record.len()) as u64;
429        self.commit.sync_to(&self.store, end)?;
430        Ok(lsn)
431    }
432
433    /// Serialise `value` with `pack-io` and append it, returning its [`Lsn`].
434    ///
435    /// The typed counterpart to [`append`](Wal::append): the value is encoded to
436    /// bytes and appended as one record, which [`Record::decode`] reads back.
437    /// Available with the `pack-io` feature. Like `append`, it does not sync.
438    ///
439    /// # Errors
440    ///
441    /// - [`WalError::Encoding`] if the value fails to serialise.
442    /// - Otherwise the errors of [`append`](Wal::append) ([`WalError::RecordTooLarge`],
443    ///   [`WalError::Io`]).
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// use wal_db::{MemStore, Wal};
449    /// use wal_db::pack_io::{Deserialize, Serialize};
450    ///
451    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
452    /// struct Entry {
453    ///     key: String,
454    ///     value: u64,
455    /// }
456    ///
457    /// # fn main() -> Result<(), wal_db::WalError> {
458    /// let wal = Wal::with_store(MemStore::new())?;
459    /// wal.append_typed(&Entry { key: "balance".into(), value: 100 })?;
460    ///
461    /// let entry: Entry = wal.iter()?.next().unwrap()?.decode()?;
462    /// assert_eq!(entry.value, 100);
463    /// # Ok(())
464    /// # }
465    /// ```
466    #[cfg(feature = "pack-io")]
467    pub fn append_typed<T: pack_io::Serialize + ?Sized>(&self, value: &T) -> Result<Lsn> {
468        let bytes = pack_io::encode(value).map_err(WalError::encoding)?;
469        self.append(&bytes)
470    }
471
472    /// Iterate the log from the beginning, yielding each record in append order.
473    ///
474    /// The iterator walks the records that are fully written at the moment it is
475    /// created — it does not see records still being written by other threads, or
476    /// appended afterwards. Each item is a [`Result`]: a damaged record yields a
477    /// single [`WalError::Corruption`] and then the iterator stops. In a log
478    /// opened normally the torn tail has already been truncated, so iteration
479    /// runs cleanly to the end.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use wal_db::{MemStore, Wal};
485    /// # fn main() -> Result<(), wal_db::WalError> {
486    /// let wal = Wal::with_store(MemStore::new())?;
487    /// wal.append(b"one")?;
488    /// wal.append(b"two")?;
489    ///
490    /// let mut seen = Vec::new();
491    /// for entry in wal.iter()? {
492    ///     seen.push(entry?.into_data());
493    /// }
494    /// assert_eq!(seen, vec![b"one".to_vec(), b"two".to_vec()]);
495    /// # Ok(())
496    /// # }
497    /// ```
498    pub fn iter(&self) -> Result<WalIter<'_, S>> {
499        let end = self.commit.committed();
500        Ok(WalIter {
501            wal: self,
502            offset: self.head.load(Ordering::Acquire),
503            end,
504            done: false,
505            policy: self.recovery_policy,
506        })
507    }
508
509    /// Iterate from `from` (a record's [`Lsn`]) to the end, skipping the records
510    /// before it.
511    ///
512    /// Because an LSN is a byte offset, seeking is O(1): iteration simply starts
513    /// at `from` instead of 0. Pass an [`Lsn`] that a previous
514    /// [`append`](Wal::append) or [`iter`](Wal::iter) produced — a real record
515    /// boundary. An `Lsn` that does not land on a record boundary will be read as
516    /// a malformed record and surface as [`WalError::Corruption`]; an `Lsn` past
517    /// the end yields an empty iterator.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use wal_db::{MemStore, Wal};
523    /// # fn main() -> Result<(), wal_db::WalError> {
524    /// let wal = Wal::with_store(MemStore::new())?;
525    /// wal.append(b"one")?;
526    /// let second = wal.append(b"two")?;
527    /// wal.append(b"three")?;
528    ///
529    /// let from_second: Vec<Vec<u8>> = wal
530    ///     .iter_from(second)?
531    ///     .map(|entry| entry.map(|r| r.into_data()))
532    ///     .collect::<Result<_, _>>()?;
533    /// assert_eq!(from_second, vec![b"two".to_vec(), b"three".to_vec()]);
534    /// # Ok(())
535    /// # }
536    /// ```
537    pub fn iter_from(&self, from: Lsn) -> Result<WalIter<'_, S>> {
538        let end = self.commit.committed();
539        // Never read below the head: a dropped prefix is gone.
540        let start = from.get().max(self.head.load(Ordering::Acquire)).min(end);
541        Ok(WalIter {
542            wal: self,
543            offset: start,
544            end,
545            done: false,
546            policy: self.recovery_policy,
547        })
548    }
549
550    /// Drop every record after the one at `lsn`, keeping the log up to and
551    /// including it. For compaction.
552    ///
553    /// The record at `lsn` becomes the new last record; the next append lands
554    /// right after it. The truncation is made durable before returning. `lsn`
555    /// must be a real record boundary from a previous [`append`](Wal::append) or
556    /// [`iter`](Wal::iter), and the record there must be intact.
557    ///
558    /// # Exclusive access
559    ///
560    /// This mutates the log's end, so it must **not** run concurrently with
561    /// [`append`](Wal::append), [`sync`](Wal::sync), or another `truncate_after`.
562    /// The caller is responsible for quiescing writers first — the usual case for
563    /// compaction, where the engine pauses the log, truncates, and resumes.
564    ///
565    /// # Errors
566    ///
567    /// - [`WalError::Corruption`] if `lsn` does not point at an intact record.
568    /// - [`WalError::Io`] if the truncation or its sync fails.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use wal_db::{MemStore, Wal};
574    /// # fn main() -> Result<(), wal_db::WalError> {
575    /// let wal = Wal::with_store(MemStore::new())?;
576    /// wal.append(b"keep me")?;
577    /// let last_kept = wal.append(b"and me")?;
578    /// wal.append(b"drop me")?;
579    ///
580    /// wal.truncate_after(last_kept)?;
581    ///
582    /// let remaining: Vec<Vec<u8>> = wal
583    ///     .iter()?
584    ///     .map(|entry| entry.map(|r| r.into_data()))
585    ///     .collect::<Result<_, _>>()?;
586    /// assert_eq!(remaining, vec![b"keep me".to_vec(), b"and me".to_vec()]);
587    /// # Ok(())
588    /// # }
589    /// ```
590    pub fn truncate_after(&self, lsn: Lsn) -> Result<()> {
591        let start = lsn.get();
592
593        // Confirm an intact record really lives at `lsn` before keeping it.
594        let mut header = [0u8; HEADER_LEN];
595        if self.store.read_at(start, &mut header)? < HEADER_LEN {
596            return Err(WalError::corruption(start, "no record at this LSN"));
597        }
598        let parsed = record::parse_header(&header);
599        if parsed.len > self.max_record_size {
600            return Err(WalError::corruption(start, "no valid record at this LSN"));
601        }
602        let payload_start = start
603            .checked_add(HEADER_LEN as u64)
604            .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
605        let mut payload = vec![0u8; parsed.len as usize];
606        if self.store.read_at(payload_start, &mut payload)? < payload.len() {
607            return Err(WalError::corruption(start, "incomplete record at this LSN"));
608        }
609        if !record::verify(&header, &payload, parsed.crc) {
610            return Err(WalError::corruption(start, "no valid record at this LSN"));
611        }
612        let new_end = payload_start
613            .checked_add(u64::from(parsed.len))
614            .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
615
616        self.store.truncate(new_end)?;
617        self.store.sync()?;
618        self.tail.0.store(new_end, Ordering::Release);
619        self.commit.reset(new_end);
620        Ok(())
621    }
622
623    /// Drop the records before the one at `lsn`, keeping the log from there on,
624    /// and return the new head [`Lsn`] — the lowest record still present.
625    ///
626    /// This is prefix compaction: once a consumer has durably applied (and
627    /// flushed elsewhere) everything up to a checkpoint, the old records can be
628    /// reclaimed. Offsets are preserved — surviving records keep their LSNs — so
629    /// [`iter`](Wal::iter) and [`iter_from`](Wal::iter_from) continue to work.
630    ///
631    /// Reading resumes at exactly `lsn` — the returned head is `lsn` itself
632    /// (clamped so it never moves backward or past the end). *Reclamation*,
633    /// though, is at the backend's granularity: a segmented log
634    /// ([`Wal::open_segmented`](Wal::open_segmented)) deletes whole leading segment
635    /// files below the one that holds `lsn`, so a little space just before `lsn` —
636    /// back to its segment boundary — is kept rather than reclaimed, and the
637    /// segment with the most recent records is never dropped. A single-file log
638    /// cannot reclaim a prefix without moving the surviving bytes (which would
639    /// change their LSNs), so it is left unchanged and the returned head is
640    /// `Lsn(0)`.
641    ///
642    /// # Exclusive access
643    ///
644    /// Like [`truncate_after`](Wal::truncate_after), this must **not** run
645    /// concurrently with [`append`](Wal::append), [`sync`](Wal::sync),
646    /// [`iter`](Wal::iter), or another truncation: it removes files a reader could
647    /// be holding open. Quiesce other users first.
648    ///
649    /// # Errors
650    ///
651    /// Returns [`WalError::Io`] if the removal fails.
652    ///
653    /// # Examples
654    ///
655    /// ```
656    /// use wal_db::Wal;
657    /// # fn main() -> Result<(), wal_db::WalError> {
658    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
659    /// // 32-byte segments so a handful of records spans several files.
660    /// let wal = Wal::open_segmented(dir.path(), 32)?;
661    /// for i in 0..10 {
662    ///     let _ = wal.append(format!("record {i}").as_bytes())?;
663    /// }
664    /// let checkpoint = wal.append(b"checkpoint")?;
665    /// wal.sync()?;
666    ///
667    /// // Reclaim everything before the checkpoint's segment.
668    /// let head = wal.truncate_before(checkpoint)?;
669    /// assert!(head <= checkpoint);
670    /// // Iteration now starts at (or before) the checkpoint, never at 0.
671    /// assert!(wal.iter()?.next().unwrap()?.lsn() >= head);
672    /// # Ok(())
673    /// # }
674    /// ```
675    pub fn truncate_before(&self, lsn: Lsn) -> Result<Lsn> {
676        let new_head = self.store.truncate_before(lsn.get())?;
677        self.head.store(new_head, Ordering::Release);
678        Ok(Lsn::new(new_head))
679    }
680
681    /// The logical size of the log in bytes, including record framing.
682    ///
683    /// This is the offset at which the next append will land. It counts bytes
684    /// that have been reserved, which under heavy concurrency may include a
685    /// record another thread is still writing.
686    #[must_use]
687    pub fn len(&self) -> u64 {
688        self.tail.0.load(Ordering::Acquire)
689    }
690
691    /// Whether the log holds no records.
692    #[must_use]
693    pub fn is_empty(&self) -> bool {
694        self.len() == 0
695    }
696
697    /// Frame `record` into a reused buffer and write it at `start`.
698    fn frame_and_write(&self, start: u64, record: &[u8]) -> Result<()> {
699        with_frame_buffer(|buf| {
700            record::encode(buf, record);
701            self.store.write_at(start, buf)
702        })
703    }
704
705    /// Crate-internal access to the backing store, for tests that need to read,
706    /// corrupt, or extend the on-disk image directly.
707    #[cfg(test)]
708    pub(crate) fn store(&self) -> &S {
709        &self.store
710    }
711}
712
713/// Frame a record using a reused thread-local buffer, so steady-state appends do
714/// not allocate. Under loom a fresh buffer is used, since the model checker does
715/// not need (and does not instrument) the thread-local.
716#[cfg(not(loom))]
717fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
718    thread_local! {
719        static FRAME: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
720    }
721    FRAME.with(|cell| f(&mut cell.borrow_mut()))
722}
723
724#[cfg(loom)]
725fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
726    let mut buf = Vec::new();
727    f(&mut buf)
728}
729
730/// What the open scan recovered.
731#[derive(Debug, Clone, Copy)]
732struct Recovered {
733    /// End offset of the last intact record: where the next append lands.
734    end: u64,
735    /// Bytes cut from the store past `end`.
736    cut: u64,
737}
738
739/// Scan a store from the head, returning the end offset of the last intact
740/// record and cutting whatever follows it, as `config`'s [`OpenPolicy`] allows.
741///
742/// Under [`OpenPolicy::Strict`] a cut is made only when nothing intact follows
743/// the damage; otherwise the store is left untouched and the damaged record's
744/// offset is returned as [`WalError::Corruption`].
745fn recover<S: WalStore>(store: &S, config: &WalConfig, head: u64) -> Result<Recovered> {
746    let max_record_size = config.max_record_size();
747    let physical = store.len()?;
748    // Scan from the head: a log whose prefix was dropped no longer starts at 0.
749    let mut offset: u64 = head;
750    let mut header = [0u8; HEADER_LEN];
751    // One reused payload buffer for the whole scan: only the checksum needs the
752    // bytes, so the buffer is refilled per record rather than reallocated.
753    let mut payload = Vec::new();
754
755    while offset < physical {
756        if store.read_at(offset, &mut header)? < HEADER_LEN {
757            break; // incomplete header: torn tail
758        }
759        let parsed = record::parse_header(&header);
760        if parsed.len > max_record_size {
761            break; // implausible length: treat the rest as a torn tail
762        }
763
764        let payload_start = match offset.checked_add(HEADER_LEN as u64) {
765            Some(start) => start,
766            None => break,
767        };
768        let len = parsed.len as usize;
769        payload.clear();
770        payload.resize(len, 0);
771        if store.read_at(payload_start, &mut payload)? < len {
772            break; // incomplete payload: torn tail
773        }
774        if !record::verify(&header, &payload, parsed.crc) {
775            break; // checksum mismatch: stop here
776        }
777
778        offset = match payload_start.checked_add(u64::from(parsed.len)) {
779            Some(end) => end,
780            None => break,
781        };
782    }
783
784    if offset < physical {
785        if config.open_policy() == OpenPolicy::Strict {
786            match strict::classify(store, max_record_size, offset, physical)? {
787                Tail::Torn => {}
788                Tail::IntactAfter => {
789                    return Err(WalError::corruption(
790                        offset,
791                        "intact data follows a damaged record",
792                    ));
793                }
794                Tail::Unreadable => {
795                    return Err(WalError::corruption(
796                        offset,
797                        "the log cannot be read to its end after a damaged record",
798                    ));
799                }
800                Tail::Oversized => {
801                    return Err(WalError::corruption(
802                        offset,
803                        "an intact record is longer than max_record_size",
804                    ));
805                }
806            }
807        }
808        store.truncate(offset)?;
809    }
810    Ok(Recovered {
811        end: offset,
812        cut: physical.saturating_sub(offset),
813    })
814}
815
816impl<S: WalStore> fmt::Debug for Wal<S> {
817    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
818        f.debug_struct("Wal")
819            .field("len", &self.tail.0.load(Ordering::Relaxed))
820            .finish_non_exhaustive()
821    }
822}
823
824/// One record read back during iteration: its [`Lsn`] and its payload bytes.
825///
826/// Yielded by [`Wal::iter`]. The payload is owned (a fresh `Vec` per record);
827/// take it without copying via [`into_data`](Record::into_data), or borrow it
828/// via [`data`](Record::data).
829#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct Record {
831    lsn: Lsn,
832    data: Vec<u8>,
833}
834
835impl Record {
836    /// The sequence number this record was assigned — its byte offset in the log.
837    pub fn lsn(&self) -> Lsn {
838        self.lsn
839    }
840
841    /// The record's payload bytes.
842    #[must_use]
843    pub fn data(&self) -> &[u8] {
844        &self.data
845    }
846
847    /// The payload length in bytes.
848    #[must_use]
849    pub fn len(&self) -> usize {
850        self.data.len()
851    }
852
853    /// Whether the record's payload is empty.
854    #[must_use]
855    pub fn is_empty(&self) -> bool {
856        self.data.is_empty()
857    }
858
859    /// Consume the record and take ownership of its payload without copying.
860    #[must_use]
861    pub fn into_data(self) -> Vec<u8> {
862        self.data
863    }
864
865    /// Decode the record's payload into a typed value via `pack-io`.
866    ///
867    /// The mirror of [`Wal::append_typed`]. Available with the `pack-io` feature.
868    ///
869    /// # Errors
870    ///
871    /// Returns [`WalError::Encoding`] if the bytes do not deserialise into `T` —
872    /// for example reading a record written as a different type.
873    ///
874    /// # Examples
875    ///
876    /// ```
877    /// use wal_db::{MemStore, Wal};
878    /// use wal_db::pack_io::{Deserialize, Serialize};
879    ///
880    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
881    /// struct Event {
882    ///     id: u64,
883    ///     name: String,
884    /// }
885    ///
886    /// # fn main() -> Result<(), wal_db::WalError> {
887    /// let wal = Wal::with_store(MemStore::new())?;
888    /// wal.append_typed(&Event { id: 7, name: "boot".into() })?;
889    ///
890    /// let record = wal.iter()?.next().unwrap()?;
891    /// let event: Event = record.decode()?;
892    /// assert_eq!(event, Event { id: 7, name: "boot".into() });
893    /// # Ok(())
894    /// # }
895    /// ```
896    #[cfg(feature = "pack-io")]
897    pub fn decode<T: pack_io::Deserialize>(&self) -> Result<T> {
898        pack_io::decode(&self.data).map_err(WalError::encoding)
899    }
900}
901
902/// The outcome of reading one record-sized chunk at the iterator's cursor.
903enum Step {
904    /// A valid record, plus the offset just past it.
905    Record(Record, u64),
906    /// A damaged record. `skip_to` is the offset of the next record if its
907    /// extent is known (length and payload present, only the checksum failed),
908    /// or `None` if the damage makes the next record's position unknowable.
909    Damaged(WalError, Option<u64>),
910    /// A clean end: a short read, meaning the log stops here (a torn tail).
911    End,
912}
913
914/// The iterator returned by [`Wal::iter`].
915///
916/// Walks the records fully written when it was created, yielding
917/// `Result<`[`Record`]`>`. Behaviour at a damaged record follows the configured
918/// [`RecoveryPolicy`]: by default the iterator yields the damage once and stops;
919/// under [`RecoveryPolicy::SkipBadRecords`] it yields the damage and continues
920/// past it when the next record's position is still recoverable.
921pub struct WalIter<'a, S: WalStore = FileStore> {
922    wal: &'a Wal<S>,
923    offset: u64,
924    end: u64,
925    done: bool,
926    policy: RecoveryPolicy,
927}
928
929impl<S: WalStore> WalIter<'_, S> {
930    /// Read and classify the record at the current offset, without advancing.
931    fn step(&self) -> Result<Step> {
932        let mut header = [0u8; HEADER_LEN];
933        if self.wal.store.read_at(self.offset, &mut header)? < HEADER_LEN {
934            return Ok(Step::End);
935        }
936        let parsed = record::parse_header(&header);
937        if parsed.len > self.wal.max_record_size {
938            // The length is implausible, so the next record's position is
939            // unknowable — there is nothing to skip to.
940            return Ok(Step::Damaged(
941                WalError::corruption(self.offset, "record length exceeds the maximum"),
942                None,
943            ));
944        }
945
946        let payload_start = self
947            .offset
948            .checked_add(HEADER_LEN as u64)
949            .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
950        let mut payload = vec![0u8; parsed.len as usize];
951        if self.wal.store.read_at(payload_start, &mut payload)? < payload.len() {
952            return Ok(Step::End);
953        }
954        let next = payload_start
955            .checked_add(u64::from(parsed.len))
956            .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
957
958        if !record::verify(&header, &payload, parsed.crc) {
959            // The length and payload are present, so we know where the next
960            // record starts even though this one is corrupt.
961            return Ok(Step::Damaged(
962                WalError::corruption(self.offset, "checksum mismatch"),
963                Some(next),
964            ));
965        }
966
967        Ok(Step::Record(
968            Record {
969                lsn: Lsn::new(self.offset),
970                data: payload,
971            },
972            next,
973        ))
974    }
975}
976
977impl<S: WalStore> Iterator for WalIter<'_, S> {
978    type Item = Result<Record>;
979
980    fn next(&mut self) -> Option<Self::Item> {
981        if self.done || self.offset >= self.end {
982            return None;
983        }
984        match self.step() {
985            Ok(Step::Record(record, next)) => {
986                self.offset = next;
987                Some(Ok(record))
988            }
989            // Skip-bad-records, and the next record is locatable: surface the
990            // damage but continue from past it on the next call.
991            Ok(Step::Damaged(error, Some(next)))
992                if self.policy == RecoveryPolicy::SkipBadRecords =>
993            {
994                self.offset = next;
995                Some(Err(error))
996            }
997            // Stop-at-first-error, or damage that makes the next position
998            // unknowable: surface the damage and end.
999            Ok(Step::Damaged(error, _)) => {
1000                self.done = true;
1001                Some(Err(error))
1002            }
1003            Ok(Step::End) => {
1004                self.done = true;
1005                None
1006            }
1007            Err(error) => {
1008                self.done = true;
1009                Some(Err(error))
1010            }
1011        }
1012    }
1013}
1014
1015impl<S: WalStore> fmt::Debug for WalIter<'_, S> {
1016    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017        f.debug_struct("WalIter")
1018            .field("offset", &self.offset)
1019            .field("end", &self.end)
1020            .field("done", &self.done)
1021            .finish()
1022    }
1023}
1024
1025#[cfg(all(test, not(loom)))]
1026#[allow(
1027    clippy::unwrap_used,
1028    clippy::expect_used,
1029    unused_must_use,
1030    unused_results
1031)]
1032mod tests {
1033    use std::sync::Arc;
1034    use std::thread;
1035
1036    use super::*;
1037    use crate::store::MemStore;
1038
1039    fn drain(wal: &Wal<MemStore>) -> Vec<Vec<u8>> {
1040        wal.iter()
1041            .unwrap()
1042            .map(|r| r.unwrap().into_data())
1043            .collect()
1044    }
1045
1046    fn corrupt_byte(store: &MemStore, offset: u64) {
1047        let mut byte = [0u8; 1];
1048        store.read_at(offset, &mut byte).unwrap();
1049        byte[0] ^= 0xFF;
1050        store.write_at(offset, &byte).unwrap();
1051    }
1052
1053    #[test]
1054    fn test_stop_at_first_error_stops_at_corruption() {
1055        let wal = Wal::with_store(MemStore::new()).unwrap(); // default policy
1056        wal.append(b"first").unwrap();
1057        let second = wal.append(b"second").unwrap();
1058        wal.append(b"third").unwrap();
1059        corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1060
1061        let items: Vec<_> = wal.iter().unwrap().collect();
1062        assert_eq!(items.len(), 2); // first ok, second damaged, then stop
1063        assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1064        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1065    }
1066
1067    #[test]
1068    fn test_skip_bad_records_continues_past_corruption() {
1069        let config = WalConfig::new().with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1070        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1071        wal.append(b"first").unwrap();
1072        let second = wal.append(b"second").unwrap();
1073        wal.append(b"third").unwrap();
1074        // Corrupt the payload only; the length prefix stays intact, so the
1075        // record is skippable.
1076        corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1077
1078        let items: Vec<_> = wal.iter().unwrap().collect();
1079        assert_eq!(items.len(), 3);
1080        assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1081        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1082        assert_eq!(items[2].as_ref().unwrap().data(), b"third");
1083    }
1084
1085    #[test]
1086    fn test_skip_bad_records_still_stops_on_unreadable_length() {
1087        let config = WalConfig::new()
1088            .with_max_record_size(16)
1089            .with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1090        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1091        wal.append(b"ok").unwrap();
1092        let second = wal.append(b"victim").unwrap();
1093        // Corrupt the length field to an implausible value: the next record's
1094        // position becomes unknowable, so even skip-mode must stop.
1095        corrupt_byte(wal.store(), second.get() + 4); // LEN_OFFSET within the header
1096
1097        let items: Vec<_> = wal.iter().unwrap().collect();
1098        assert_eq!(items.len(), 2); // first ok, then a damaged stop
1099        assert_eq!(items[0].as_ref().unwrap().data(), b"ok");
1100        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1101    }
1102
1103    #[cfg(feature = "pack-io")]
1104    #[test]
1105    fn test_typed_record_roundtrip() {
1106        use pack_io::{Deserialize, Serialize};
1107
1108        #[derive(Serialize, Deserialize, PartialEq, Debug)]
1109        struct Entry {
1110            id: u64,
1111            label: String,
1112        }
1113
1114        let wal = Wal::with_store(MemStore::new()).unwrap();
1115        wal.append_typed(&Entry {
1116            id: 9,
1117            label: "nine".into(),
1118        })
1119        .unwrap();
1120        wal.append_typed(&Entry {
1121            id: 10,
1122            label: "ten".into(),
1123        })
1124        .unwrap();
1125
1126        let decoded: Vec<Entry> = wal
1127            .iter()
1128            .unwrap()
1129            .map(|r| r.unwrap().decode().unwrap())
1130            .collect();
1131        assert_eq!(
1132            decoded[0],
1133            Entry {
1134                id: 9,
1135                label: "nine".into()
1136            }
1137        );
1138        assert_eq!(
1139            decoded[1],
1140            Entry {
1141                id: 10,
1142                label: "ten".into()
1143            }
1144        );
1145    }
1146
1147    #[cfg(feature = "pack-io")]
1148    #[test]
1149    fn test_typed_decode_wrong_type_errors() {
1150        use pack_io::{Deserialize, Serialize};
1151
1152        #[derive(Serialize)]
1153        struct Big {
1154            a: u64,
1155            b: u64,
1156            c: u64,
1157        }
1158        #[derive(Deserialize)]
1159        struct Small {
1160            _a: u8,
1161        }
1162
1163        let wal = Wal::with_store(MemStore::new()).unwrap();
1164        wal.append_typed(&Big { a: 1, b: 2, c: 3 }).unwrap();
1165        let record = wal.iter().unwrap().next().unwrap().unwrap();
1166        // Decoding 24 bytes as a 1-byte type leaves trailing bytes -> error.
1167        let result: Result<Small> = record.decode();
1168        assert!(matches!(result, Err(WalError::Encoding { .. })));
1169    }
1170
1171    #[test]
1172    fn test_append_assigns_byte_offset_lsns() {
1173        let wal = Wal::with_store(MemStore::new()).unwrap();
1174        let a = wal.append(b"abc").unwrap(); // 8 header + 3 = 11 bytes
1175        let b = wal.append(b"de").unwrap();
1176        assert_eq!(a.get(), 0);
1177        assert_eq!(b.get(), 11);
1178    }
1179
1180    #[test]
1181    fn test_iter_reads_back_all_records_in_order() {
1182        let wal = Wal::with_store(MemStore::new()).unwrap();
1183        wal.append(b"one").unwrap();
1184        wal.append(b"two").unwrap();
1185        wal.append(b"three").unwrap();
1186        assert_eq!(
1187            drain(&wal),
1188            vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]
1189        );
1190    }
1191
1192    #[test]
1193    fn test_empty_log_iterates_to_nothing() {
1194        let wal = Wal::with_store(MemStore::new()).unwrap();
1195        assert!(wal.is_empty());
1196        assert_eq!(drain(&wal).len(), 0);
1197    }
1198
1199    #[test]
1200    fn test_empty_record_roundtrips() {
1201        let wal = Wal::with_store(MemStore::new()).unwrap();
1202        wal.append(b"").unwrap();
1203        assert_eq!(drain(&wal), vec![Vec::<u8>::new()]);
1204    }
1205
1206    #[test]
1207    fn test_record_too_large_is_rejected() {
1208        let config = WalConfig::new().with_max_record_size(4);
1209        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1210        wal.append(b"ok").unwrap();
1211        let err = wal.append(b"too long").unwrap_err();
1212        assert!(matches!(err, WalError::RecordTooLarge { len: 8, max: 4 }));
1213        // The rejected append did not advance the log.
1214        assert_eq!(drain(&wal), vec![b"ok".to_vec()]);
1215    }
1216
1217    #[test]
1218    fn test_reopen_recovers_records() {
1219        let wal = Wal::with_store(MemStore::new()).unwrap();
1220        wal.append(b"first").unwrap();
1221        wal.append(b"second").unwrap();
1222        wal.sync().unwrap();
1223        let image = wal.store().snapshot();
1224
1225        let reopened = Wal::with_store(MemStore::from_bytes(image)).unwrap();
1226        assert_eq!(
1227            drain(&reopened),
1228            vec![b"first".to_vec(), b"second".to_vec()]
1229        );
1230        // The next append continues at the recovered end: two records of
1231        // (8 + 5) and (8 + 6) bytes leave the tail at 27.
1232        assert_eq!(reopened.append(b"third").unwrap().get(), 27);
1233    }
1234
1235    #[test]
1236    fn test_recovery_truncates_torn_tail() {
1237        let wal = Wal::with_store(MemStore::new()).unwrap();
1238        wal.append(b"good record").unwrap();
1239        let clean_len = wal.len();
1240        // Append raw garbage directly to the store: a torn tail.
1241        wal.store().write_at(clean_len, &[0xAB; 5]).unwrap();
1242
1243        let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1244        assert_eq!(drain(&reopened), vec![b"good record".to_vec()]);
1245        assert_eq!(reopened.len(), clean_len);
1246    }
1247
1248    #[test]
1249    fn test_corrupt_record_surfaces_error_then_stops() {
1250        let wal = Wal::with_store(MemStore::new()).unwrap();
1251        wal.append(b"intact").unwrap();
1252        let second = wal.append(b"victim").unwrap();
1253        // Flip a byte inside the second record's payload (offset + header).
1254        let payload_offset = second.get() + HEADER_LEN as u64;
1255        let mut byte = [0u8; 1];
1256        wal.store().read_at(payload_offset, &mut byte).unwrap();
1257        byte[0] ^= 0xFF;
1258        wal.store().write_at(payload_offset, &byte).unwrap();
1259
1260        let mut iter = wal.iter().unwrap();
1261        assert_eq!(iter.next().unwrap().unwrap().data(), b"intact");
1262        assert!(matches!(
1263            iter.next().unwrap(),
1264            Err(WalError::Corruption { .. })
1265        ));
1266        assert!(iter.next().is_none());
1267    }
1268
1269    #[test]
1270    fn test_append_and_sync_is_durable() {
1271        let wal = Wal::with_store(MemStore::new()).unwrap();
1272        wal.append_and_sync(b"committed").unwrap();
1273        assert_eq!(drain(&wal), vec![b"committed".to_vec()]);
1274    }
1275
1276    #[test]
1277    fn test_iter_from_seeks_to_lsn() {
1278        let wal = Wal::with_store(MemStore::new()).unwrap();
1279        wal.append(b"a").unwrap();
1280        let b = wal.append(b"b").unwrap();
1281        wal.append(b"c").unwrap();
1282
1283        let got: Vec<Vec<u8>> = wal
1284            .iter_from(b)
1285            .unwrap()
1286            .map(|r| r.unwrap().into_data())
1287            .collect();
1288        assert_eq!(got, vec![b"b".to_vec(), b"c".to_vec()]);
1289    }
1290
1291    #[test]
1292    fn test_iter_from_past_end_is_empty() {
1293        let wal = Wal::with_store(MemStore::new()).unwrap();
1294        wal.append(b"a").unwrap();
1295        assert_eq!(wal.iter_from(Lsn::new(9_999)).unwrap().count(), 0);
1296    }
1297
1298    #[test]
1299    fn test_truncate_after_drops_later_records() {
1300        let wal = Wal::with_store(MemStore::new()).unwrap();
1301        wal.append(b"first").unwrap(); // [0, 13)
1302        let keep = wal.append(b"second").unwrap(); // [13, 27)
1303        wal.append(b"third").unwrap();
1304        wal.append(b"fourth").unwrap();
1305
1306        wal.truncate_after(keep).unwrap();
1307        assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1308        assert_eq!(wal.len(), 27);
1309
1310        // Appends resume immediately after the kept record.
1311        assert_eq!(wal.append(b"new").unwrap().get(), 27);
1312        assert_eq!(
1313            drain(&wal),
1314            vec![b"first".to_vec(), b"second".to_vec(), b"new".to_vec()]
1315        );
1316    }
1317
1318    #[test]
1319    fn test_truncate_after_keeping_last_record_is_a_no_op() {
1320        let wal = Wal::with_store(MemStore::new()).unwrap();
1321        wal.append(b"first").unwrap();
1322        let last = wal.append(b"second").unwrap();
1323        let before = wal.len();
1324
1325        wal.truncate_after(last).unwrap();
1326        assert_eq!(wal.len(), before);
1327        assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1328    }
1329
1330    #[test]
1331    fn test_truncate_after_invalid_lsn_errors() {
1332        let config = WalConfig::new().with_max_record_size(64);
1333        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1334        wal.append(b"only record").unwrap();
1335        // An LSN that does not land on a record boundary is rejected.
1336        let err = wal.truncate_after(Lsn::new(3)).unwrap_err();
1337        assert!(matches!(err, WalError::Corruption { .. }));
1338    }
1339
1340    #[test]
1341    fn test_concurrent_appends_no_overlap_all_recovered() {
1342        const THREADS: usize = 8;
1343        const PER_THREAD: usize = 200;
1344
1345        let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1346        let mut handles = Vec::new();
1347        for t in 0..THREADS {
1348            let wal = Arc::clone(&wal);
1349            handles.push(thread::spawn(move || {
1350                let mut lsns = Vec::with_capacity(PER_THREAD);
1351                for i in 0..PER_THREAD {
1352                    let payload = format!("t{t}-r{i}").into_bytes();
1353                    lsns.push(wal.append(&payload).unwrap().get());
1354                }
1355                lsns
1356            }));
1357        }
1358        let mut all_lsns = Vec::new();
1359        for h in handles {
1360            all_lsns.extend(h.join().unwrap());
1361        }
1362        wal.sync().unwrap();
1363
1364        // Every LSN is distinct (no two records shared a byte range).
1365        let mut sorted = all_lsns.clone();
1366        sorted.sort_unstable();
1367        sorted.dedup();
1368        assert_eq!(sorted.len(), THREADS * PER_THREAD);
1369
1370        // Recovery reads back exactly the records that were appended, in offset
1371        // order, with no gaps or corruption.
1372        let records = drain(&wal);
1373        assert_eq!(records.len(), THREADS * PER_THREAD);
1374
1375        // Reopening from the raw image recovers the same set.
1376        let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1377        assert_eq!(reopened.iter().unwrap().count(), THREADS * PER_THREAD);
1378    }
1379
1380    #[test]
1381    fn test_concurrent_append_and_sync_all_durable() {
1382        const THREADS: usize = 8;
1383
1384        let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1385        let mut handles = Vec::new();
1386        for t in 0..THREADS {
1387            let wal = Arc::clone(&wal);
1388            handles.push(thread::spawn(move || {
1389                for i in 0..50 {
1390                    wal.append_and_sync(format!("{t}:{i}").as_bytes()).unwrap();
1391                }
1392            }));
1393        }
1394        for h in handles {
1395            h.join().unwrap();
1396        }
1397        assert_eq!(drain(&wal).len(), THREADS * 50);
1398    }
1399}