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        // A write that panics poisons its range on the way out, so syncs that
352        // cover it fail instead of waiting forever for the gap to fill.
353        let guard = Reserved {
354            commit: &self.commit,
355            start,
356            armed: true,
357        };
358        match self.frame_and_write(start, record) {
359            Ok(()) => {
360                guard.disarm();
361                self.commit.mark_written(start, end);
362                Ok(Lsn::new(start))
363            }
364            Err(error) => Err(error), // the guard marks the range failed
365        }
366    }
367
368    /// Make every record appended before this call durable.
369    ///
370    /// Returns once the data is on stable storage, using the platform's true
371    /// durability barrier. Concurrent calls coalesce into a single fsync, so the
372    /// flush cost is shared by everyone committing at the same time.
373    ///
374    /// # Errors
375    ///
376    /// Returns [`WalError::Io`] if the flush fails, or [`WalError::Corruption`]
377    /// if an earlier append's write failed and left a gap that cannot be made
378    /// durable. A failed sync means the records are not durable, and the failure
379    /// is permanent for this handle: the operating system may have dropped the
380    /// pages it could not write, so a retry could succeed without them. Every
381    /// later sync covering anything not yet durable returns [`WalError::Io`].
382    /// Stop appending and reopen the log, so recovery decides what survived.
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// use wal_db::Wal;
388    /// # fn main() -> Result<(), wal_db::WalError> {
389    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
390    /// # let path = dir.path().join("log.wal");
391    /// let wal = Wal::open(&path)?;
392    /// wal.append(b"durable me")?;
393    /// wal.sync()?; // now on stable storage
394    /// # Ok(())
395    /// # }
396    /// ```
397    pub fn sync(&self) -> Result<()> {
398        let target = self.tail.0.load(Ordering::Acquire);
399        if target == 0 {
400            return Ok(());
401        }
402        self.commit.sync_to(&self.store, target)
403    }
404
405    /// Append `record` and make it durable in one call, returning its [`Lsn`].
406    ///
407    /// Equivalent to [`append`](Wal::append) followed by a [`sync`](Wal::sync)
408    /// scoped to this record, but with the sync coalesced into the group commit
409    /// of any other threads syncing at the same moment. Use it when every record
410    /// must be durable before you proceed and you want the group-commit
411    /// throughput without managing the two calls yourself.
412    ///
413    /// # Errors
414    ///
415    /// The union of [`append`](Wal::append)'s and [`sync`](Wal::sync)'s errors.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// use wal_db::Wal;
421    /// # fn main() -> Result<(), wal_db::WalError> {
422    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
423    /// # let path = dir.path().join("log.wal");
424    /// let wal = Wal::open(&path)?;
425    /// let lsn = wal.append_and_sync(b"committed immediately")?;
426    /// # let _ = lsn;
427    /// # Ok(())
428    /// # }
429    /// ```
430    pub fn append_and_sync(&self, record: &[u8]) -> Result<Lsn> {
431        let lsn = self.append(record)?;
432        let end = lsn.get() + record::framed_len(record.len()) as u64;
433        self.commit.sync_to(&self.store, end)?;
434        Ok(lsn)
435    }
436
437    /// Serialise `value` with `pack-io` and append it, returning its [`Lsn`].
438    ///
439    /// The typed counterpart to [`append`](Wal::append): the value is encoded to
440    /// bytes and appended as one record, which [`Record::decode`] reads back.
441    /// Available with the `pack-io` feature. Like `append`, it does not sync.
442    ///
443    /// # Errors
444    ///
445    /// - [`WalError::Encoding`] if the value fails to serialise.
446    /// - Otherwise the errors of [`append`](Wal::append) ([`WalError::RecordTooLarge`],
447    ///   [`WalError::Io`]).
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// use wal_db::{MemStore, Wal};
453    /// use wal_db::pack_io::{Deserialize, Serialize};
454    ///
455    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
456    /// struct Entry {
457    ///     key: String,
458    ///     value: u64,
459    /// }
460    ///
461    /// # fn main() -> Result<(), wal_db::WalError> {
462    /// let wal = Wal::with_store(MemStore::new())?;
463    /// wal.append_typed(&Entry { key: "balance".into(), value: 100 })?;
464    ///
465    /// let entry: Entry = wal.iter()?.next().unwrap()?.decode()?;
466    /// assert_eq!(entry.value, 100);
467    /// # Ok(())
468    /// # }
469    /// ```
470    #[cfg(feature = "pack-io")]
471    pub fn append_typed<T: pack_io::Serialize + ?Sized>(&self, value: &T) -> Result<Lsn> {
472        let bytes = pack_io::encode(value).map_err(WalError::encoding)?;
473        self.append(&bytes)
474    }
475
476    /// Serialise `value` with `pack-io` 2 and append it, returning its
477    /// [`Lsn`]. [`Record::unpack`] reads it back. Available with the
478    /// `pack-io-2` feature. Like `append`, it does not sync.
479    ///
480    /// For the values both codecs support, the bytes are the same as
481    /// [`append_typed`](Wal::append_typed) writes.
482    ///
483    /// # Errors
484    ///
485    /// - [`WalError::Encoding`] if the value fails to serialise.
486    /// - Otherwise the errors of [`append`](Wal::append).
487    ///
488    /// # Examples
489    ///
490    /// ```
491    /// use wal_db::{MemStore, Wal};
492    /// use wal_db::pack_io2::{Deserialize, Serialize};
493    ///
494    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
495    /// #[pack_io(crate = "wal_db::pack_io2")]
496    /// struct Entry {
497    ///     key: String,
498    ///     value: u64,
499    /// }
500    ///
501    /// # fn main() -> Result<(), wal_db::WalError> {
502    /// let wal = Wal::with_store(MemStore::new())?;
503    /// wal.append_pack(&Entry { key: "balance".into(), value: 100 })?;
504    ///
505    /// let entry: Entry = wal.iter()?.next().unwrap()?.unpack()?;
506    /// assert_eq!(entry.value, 100);
507    /// # Ok(())
508    /// # }
509    /// ```
510    #[cfg(feature = "pack-io-2")]
511    pub fn append_pack<T: pack_io2::Serialize + ?Sized>(&self, value: &T) -> Result<Lsn> {
512        let bytes = pack_io2::encode(value).map_err(WalError::encoding)?;
513        self.append(&bytes)
514    }
515
516    /// Iterate the log from the beginning, yielding each record in append order.
517    ///
518    /// The iterator walks the records that are fully written at the moment it is
519    /// created — it does not see records still being written by other threads, or
520    /// appended afterwards. Each item is a [`Result`]: a damaged record yields a
521    /// single [`WalError::Corruption`] and then the iterator stops. In a log
522    /// opened normally the torn tail has already been truncated, so iteration
523    /// runs cleanly to the end.
524    ///
525    /// # Examples
526    ///
527    /// ```
528    /// use wal_db::{MemStore, Wal};
529    /// # fn main() -> Result<(), wal_db::WalError> {
530    /// let wal = Wal::with_store(MemStore::new())?;
531    /// wal.append(b"one")?;
532    /// wal.append(b"two")?;
533    ///
534    /// let mut seen = Vec::new();
535    /// for entry in wal.iter()? {
536    ///     seen.push(entry?.into_data());
537    /// }
538    /// assert_eq!(seen, vec![b"one".to_vec(), b"two".to_vec()]);
539    /// # Ok(())
540    /// # }
541    /// ```
542    pub fn iter(&self) -> Result<WalIter<'_, S>> {
543        let end = self.commit.committed();
544        Ok(WalIter {
545            wal: self,
546            offset: self.head.load(Ordering::Acquire),
547            end,
548            done: false,
549            policy: self.recovery_policy,
550        })
551    }
552
553    /// Iterate from `from` (a record's [`Lsn`]) to the end, skipping the records
554    /// before it.
555    ///
556    /// Because an LSN is a byte offset, seeking is O(1): iteration simply starts
557    /// at `from` instead of 0. Pass an [`Lsn`] that a previous
558    /// [`append`](Wal::append) or [`iter`](Wal::iter) produced — a real record
559    /// boundary. An `Lsn` that does not land on a record boundary will be read as
560    /// a malformed record and surface as [`WalError::Corruption`]; an `Lsn` past
561    /// the end yields an empty iterator.
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// use wal_db::{MemStore, Wal};
567    /// # fn main() -> Result<(), wal_db::WalError> {
568    /// let wal = Wal::with_store(MemStore::new())?;
569    /// wal.append(b"one")?;
570    /// let second = wal.append(b"two")?;
571    /// wal.append(b"three")?;
572    ///
573    /// let from_second: Vec<Vec<u8>> = wal
574    ///     .iter_from(second)?
575    ///     .map(|entry| entry.map(|r| r.into_data()))
576    ///     .collect::<Result<_, _>>()?;
577    /// assert_eq!(from_second, vec![b"two".to_vec(), b"three".to_vec()]);
578    /// # Ok(())
579    /// # }
580    /// ```
581    pub fn iter_from(&self, from: Lsn) -> Result<WalIter<'_, S>> {
582        let end = self.commit.committed();
583        // Never read below the head: a dropped prefix is gone.
584        let start = from.get().max(self.head.load(Ordering::Acquire)).min(end);
585        Ok(WalIter {
586            wal: self,
587            offset: start,
588            end,
589            done: false,
590            policy: self.recovery_policy,
591        })
592    }
593
594    /// Drop every record after the one at `lsn`, keeping the log up to and
595    /// including it. For compaction.
596    ///
597    /// The record at `lsn` becomes the new last record; the next append lands
598    /// right after it, so the records appended next take the LSNs the dropped
599    /// ones had. The truncation is made durable before returning. `lsn`
600    /// must be a real record boundary from a previous [`append`](Wal::append) or
601    /// [`iter`](Wal::iter), and the record there must be intact.
602    ///
603    /// # Exclusive access
604    ///
605    /// This mutates the log's end, so it must **not** run concurrently with
606    /// [`append`](Wal::append), [`sync`](Wal::sync), or another `truncate_after`.
607    /// The caller is responsible for quiescing writers first — the usual case for
608    /// compaction, where the engine pauses the log, truncates, and resumes.
609    ///
610    /// # Errors
611    ///
612    /// - [`WalError::Corruption`] if `lsn` does not point at an intact record.
613    /// - [`WalError::Io`] if the truncation or its sync fails.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// use wal_db::{MemStore, Wal};
619    /// # fn main() -> Result<(), wal_db::WalError> {
620    /// let wal = Wal::with_store(MemStore::new())?;
621    /// wal.append(b"keep me")?;
622    /// let last_kept = wal.append(b"and me")?;
623    /// wal.append(b"drop me")?;
624    ///
625    /// wal.truncate_after(last_kept)?;
626    ///
627    /// let remaining: Vec<Vec<u8>> = wal
628    ///     .iter()?
629    ///     .map(|entry| entry.map(|r| r.into_data()))
630    ///     .collect::<Result<_, _>>()?;
631    /// assert_eq!(remaining, vec![b"keep me".to_vec(), b"and me".to_vec()]);
632    /// # Ok(())
633    /// # }
634    /// ```
635    pub fn truncate_after(&self, lsn: Lsn) -> Result<()> {
636        let new_end = self.record_end(lsn.get())?;
637        self.store.truncate(new_end)?;
638        // The log's end moves before the sync, so whatever the sync's outcome
639        // the next append lands at the new end, never past a gap; and the sync
640        // goes through the commit layer, so a failed one is permanent for this
641        // handle like any other.
642        self.tail.0.store(new_end, Ordering::Release);
643        self.commit.reset(new_end);
644        self.commit.sync_now(&self.store)
645    }
646
647    /// The end of the intact record at `start`.
648    ///
649    /// # Errors
650    ///
651    /// [`WalError::Corruption`] if no intact record starts at `start`.
652    fn record_end(&self, start: u64) -> Result<u64> {
653        let mut header = [0u8; HEADER_LEN];
654        if self.store.read_at(start, &mut header)? < HEADER_LEN {
655            return Err(WalError::corruption(start, "no record at this LSN"));
656        }
657        let parsed = record::parse_header(&header);
658        if parsed.len > self.max_record_size {
659            return Err(WalError::corruption(start, "no valid record at this LSN"));
660        }
661        let payload_start = start
662            .checked_add(HEADER_LEN as u64)
663            .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
664        let end = payload_start
665            .checked_add(u64::from(parsed.len))
666            .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
667        if end > self.store.len()? {
668            return Err(WalError::corruption(start, "incomplete record at this LSN"));
669        }
670        let mut payload = vec![0u8; parsed.len as usize];
671        if self.store.read_at(payload_start, &mut payload)? < payload.len() {
672            return Err(WalError::corruption(start, "incomplete record at this LSN"));
673        }
674        if !record::verify(&header, &payload, parsed.crc) {
675            return Err(WalError::corruption(start, "no valid record at this LSN"));
676        }
677        Ok(end)
678    }
679
680    /// Drop the records before the one at `lsn`, keeping the log from there on,
681    /// and return the new head [`Lsn`] — the lowest record still present.
682    ///
683    /// This is prefix compaction: once a consumer has durably applied (and
684    /// flushed elsewhere) everything up to a checkpoint, the old records can be
685    /// reclaimed. Offsets are preserved — surviving records keep their LSNs — so
686    /// [`iter`](Wal::iter) and [`iter_from`](Wal::iter_from) continue to work.
687    ///
688    /// Reading resumes at exactly `lsn` — the returned head is `lsn` itself
689    /// (clamped so it never moves backward or past the end). *Reclamation*,
690    /// though, is at the backend's granularity: a segmented log
691    /// ([`Wal::open_segmented`](Wal::open_segmented)) deletes whole leading segment
692    /// files below the one that holds `lsn`, so a little space just before `lsn` —
693    /// back to its segment boundary — is kept rather than reclaimed, and the
694    /// segment with the most recent records is never dropped. A single-file log
695    /// cannot reclaim a prefix without moving the surviving bytes (which would
696    /// change their LSNs), so it is left unchanged and the returned head is
697    /// `Lsn(0)`.
698    ///
699    /// # Exclusive access
700    ///
701    /// Like [`truncate_after`](Wal::truncate_after), this must **not** run
702    /// concurrently with [`append`](Wal::append), [`sync`](Wal::sync),
703    /// [`iter`](Wal::iter), or another truncation: it removes files a reader could
704    /// be holding open. Quiesce other users first.
705    ///
706    /// # Errors
707    ///
708    /// - [`WalError::Corruption`] if no intact record starts at `lsn` (and
709    ///   `lsn` is neither below the current head nor at the end of the log):
710    ///   the head is a record boundary, and a wrong one would make the next
711    ///   open read the log from a place that is not a record.
712    /// - [`WalError::Io`] if the removal fails.
713    ///
714    /// # Examples
715    ///
716    /// ```
717    /// use wal_db::Wal;
718    /// # fn main() -> Result<(), wal_db::WalError> {
719    /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
720    /// // 32-byte segments so a handful of records spans several files.
721    /// let wal = Wal::open_segmented(dir.path(), 32)?;
722    /// for i in 0..10 {
723    ///     let _ = wal.append(format!("record {i}").as_bytes())?;
724    /// }
725    /// let checkpoint = wal.append(b"checkpoint")?;
726    /// wal.sync()?;
727    ///
728    /// // Reclaim everything before the checkpoint's segment.
729    /// let head = wal.truncate_before(checkpoint)?;
730    /// assert!(head <= checkpoint);
731    /// // Iteration now starts at (or before) the checkpoint, never at 0.
732    /// assert!(wal.iter()?.next().unwrap()?.lsn() >= head);
733    /// # Ok(())
734    /// # }
735    /// ```
736    pub fn truncate_before(&self, lsn: Lsn) -> Result<Lsn> {
737        let at = lsn.get();
738        if at > self.head.load(Ordering::Acquire) && at < self.store.len()? {
739            let _ = self.record_end(at)?;
740        }
741        let new_head = self.store.truncate_before(at)?;
742        self.head.store(new_head, Ordering::Release);
743        Ok(Lsn::new(new_head))
744    }
745
746    /// The logical size of the log in bytes, including record framing.
747    ///
748    /// This is the offset at which the next append will land. It counts bytes
749    /// that have been reserved, which under heavy concurrency may include a
750    /// record another thread is still writing.
751    #[must_use]
752    pub fn len(&self) -> u64 {
753        self.tail.0.load(Ordering::Acquire)
754    }
755
756    /// Whether the log holds no records.
757    #[must_use]
758    pub fn is_empty(&self) -> bool {
759        self.len() == 0
760    }
761
762    /// Frame `record` into a reused buffer and write it at `start`.
763    fn frame_and_write(&self, start: u64, record: &[u8]) -> Result<()> {
764        with_frame_buffer(|buf| {
765            record::encode(buf, record);
766            self.store.write_at(start, buf)
767        })
768    }
769
770    /// Crate-internal access to the backing store, for tests that need to read,
771    /// corrupt, or extend the on-disk image directly.
772    #[cfg(test)]
773    pub(crate) fn store(&self) -> &S {
774        &self.store
775    }
776}
777
778/// Frame a record using a reused thread-local buffer, so steady-state appends do
779/// not allocate. Under loom a fresh buffer is used, since the model checker does
780/// not need (and does not instrument) the thread-local.
781#[cfg(not(loom))]
782fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
783    thread_local! {
784        static FRAME: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
785    }
786    FRAME.with(|cell| f(&mut cell.borrow_mut()))
787}
788
789#[cfg(loom)]
790fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
791    let mut buf = Vec::new();
792    f(&mut buf)
793}
794
795/// Why the open scan stopped before the end of the store.
796#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797enum Stop {
798    /// The frame there is incomplete: a write cut short.
799    Torn,
800    /// Its length is above `max_record_size`.
801    Oversized,
802    /// A whole frame whose checksum does not match.
803    Damaged,
804}
805
806/// A reserved byte range not yet written: poisoned when dropped unless
807/// [`disarm`](Self::disarm)ed, so a panicking write cannot wedge later syncs.
808struct Reserved<'a> {
809    commit: &'a Commit,
810    start: u64,
811    armed: bool,
812}
813
814impl Reserved<'_> {
815    fn disarm(mut self) {
816        self.armed = false;
817    }
818}
819
820impl Drop for Reserved<'_> {
821    fn drop(&mut self) {
822        if self.armed {
823            self.commit.mark_failed(self.start);
824        }
825    }
826}
827
828/// What the open scan recovered.
829#[derive(Debug, Clone, Copy)]
830struct Recovered {
831    /// End offset of the last intact record: where the next append lands.
832    end: u64,
833    /// Bytes cut from the store past `end`.
834    cut: u64,
835}
836
837/// Scan a store from the head, returning the end offset of the last intact
838/// record and cutting whatever follows it, as `config`'s [`OpenPolicy`] allows.
839///
840/// Under [`OpenPolicy::Strict`] a cut is made only when nothing intact follows
841/// the damage; otherwise the store is left untouched and the damaged record's
842/// offset is returned as [`WalError::Corruption`].
843fn recover<S: WalStore>(store: &S, config: &WalConfig, head: u64) -> Result<Recovered> {
844    let max_record_size = config.max_record_size();
845    let physical = store.len()?;
846    // Scan from the head: a log whose prefix was dropped no longer starts at 0.
847    let mut offset: u64 = head;
848    let mut header = [0u8; HEADER_LEN];
849    // One reused payload buffer for the whole scan: only the checksum needs the
850    // bytes, so the buffer is refilled per record rather than reallocated.
851    let mut payload = Vec::new();
852
853    // How the scan stopped: only an incomplete frame is a torn write.
854    let mut stop = Stop::Torn;
855    while offset < physical {
856        if store.read_at(offset, &mut header)? < HEADER_LEN {
857            break; // incomplete header: torn tail
858        }
859        // Zeros are bytes the file system never wrote (it may extend a file
860        // before its data reaches the disk): a torn tail, not damage.
861        if header == [0u8; HEADER_LEN] {
862            break;
863        }
864        let parsed = record::parse_header(&header);
865        if parsed.len > max_record_size {
866            stop = Stop::Oversized;
867            break;
868        }
869
870        let payload_start = match offset.checked_add(HEADER_LEN as u64) {
871            Some(start) => start,
872            None => break,
873        };
874        // A length the store cannot back is a torn tail: checked before any
875        // buffer is sized from it.
876        if payload_start.saturating_add(u64::from(parsed.len)) > physical {
877            break;
878        }
879        let len = parsed.len as usize;
880        payload.clear();
881        payload.resize(len, 0);
882        if store.read_at(payload_start, &mut payload)? < len {
883            break; // incomplete payload: torn tail
884        }
885        if !record::verify(&header, &payload, parsed.crc) {
886            stop = Stop::Damaged;
887            break;
888        }
889
890        offset = match payload_start.checked_add(u64::from(parsed.len)) {
891            Some(end) => end,
892            None => break,
893        };
894    }
895
896    if offset < physical {
897        // An intact record longer than `max_record_size` (a log written with
898        // a higher limit) is never cut as if it were damage.
899        if stop == Stop::Oversized
900            && config.open_policy() != OpenPolicy::Strict
901            && strict::classify(store, max_record_size, offset, physical)? == Tail::Oversized
902        {
903            return Err(WalError::corruption(
904                offset,
905                "an intact record is longer than max_record_size",
906            ));
907        }
908        // Nothing at the head verifies, and what is there is a whole frame
909        // that does not check (or a length past the limit), not a write cut
910        // short: this is not a log, or one damaged from its first record.
911        // Cutting would empty it, so refuse under every policy (after the
912        // strict checks below, which say more when they apply).
913        let refuse_at_head = offset == head && stop != Stop::Torn;
914        let not_a_log = || {
915            WalError::corruption(
916                offset,
917                "nothing at the start of the log verifies: not a log, or one damaged from its first record",
918            )
919        };
920        if refuse_at_head && config.open_policy() != OpenPolicy::Strict {
921            return Err(not_a_log());
922        }
923        if config.open_policy() == OpenPolicy::Strict {
924            match strict::classify(store, max_record_size, offset, physical)? {
925                Tail::Torn => {}
926                Tail::IntactAfter => {
927                    return Err(WalError::corruption(
928                        offset,
929                        "intact data follows a damaged record",
930                    ));
931                }
932                Tail::Unreadable => {
933                    return Err(WalError::corruption(
934                        offset,
935                        "the log cannot be read to its end after a damaged record",
936                    ));
937                }
938                Tail::Oversized => {
939                    return Err(WalError::corruption(
940                        offset,
941                        "an intact record is longer than max_record_size",
942                    ));
943                }
944            }
945            if refuse_at_head {
946                return Err(not_a_log());
947            }
948        }
949        store.truncate(offset)?;
950    }
951    Ok(Recovered {
952        end: offset,
953        cut: physical.saturating_sub(offset),
954    })
955}
956
957impl<S: WalStore> fmt::Debug for Wal<S> {
958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
959        f.debug_struct("Wal")
960            .field("len", &self.tail.0.load(Ordering::Relaxed))
961            .finish_non_exhaustive()
962    }
963}
964
965/// One record read back during iteration: its [`Lsn`] and its payload bytes.
966///
967/// Yielded by [`Wal::iter`]. The payload is owned (a fresh `Vec` per record);
968/// take it without copying via [`into_data`](Record::into_data), or borrow it
969/// via [`data`](Record::data).
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct Record {
972    lsn: Lsn,
973    data: Vec<u8>,
974}
975
976impl Record {
977    /// The sequence number this record was assigned — its byte offset in the log.
978    pub fn lsn(&self) -> Lsn {
979        self.lsn
980    }
981
982    /// The record's payload bytes.
983    #[must_use]
984    pub fn data(&self) -> &[u8] {
985        &self.data
986    }
987
988    /// The payload length in bytes.
989    #[must_use]
990    pub fn len(&self) -> usize {
991        self.data.len()
992    }
993
994    /// Whether the record's payload is empty.
995    #[must_use]
996    pub fn is_empty(&self) -> bool {
997        self.data.is_empty()
998    }
999
1000    /// Consume the record and take ownership of its payload without copying.
1001    #[must_use]
1002    pub fn into_data(self) -> Vec<u8> {
1003        self.data
1004    }
1005
1006    /// Decode the record's payload into a typed value via `pack-io`.
1007    ///
1008    /// The mirror of [`Wal::append_typed`]. Available with the `pack-io` feature.
1009    ///
1010    /// # Untrusted bytes
1011    ///
1012    /// `pack-io` 1.0's decoder is not bounded on hostile input: a five-byte
1013    /// record can make it allocate 1 GiB. A record's CRC32C catches
1014    /// damage, not a log written by someone else. Decode only logs this
1015    /// program wrote; for any other, use [`unpack`](Record::unpack) (feature
1016    /// `pack-io-2`), which reads the same records with bounded allocation and
1017    /// nesting.
1018    ///
1019    /// # Errors
1020    ///
1021    /// Returns [`WalError::Encoding`] if the bytes do not deserialise into `T` —
1022    /// for example reading a record written as a different type.
1023    ///
1024    /// # Examples
1025    ///
1026    /// ```
1027    /// use wal_db::{MemStore, Wal};
1028    /// use wal_db::pack_io::{Deserialize, Serialize};
1029    ///
1030    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
1031    /// struct Event {
1032    ///     id: u64,
1033    ///     name: String,
1034    /// }
1035    ///
1036    /// # fn main() -> Result<(), wal_db::WalError> {
1037    /// let wal = Wal::with_store(MemStore::new())?;
1038    /// wal.append_typed(&Event { id: 7, name: "boot".into() })?;
1039    ///
1040    /// let record = wal.iter()?.next().unwrap()?;
1041    /// let event: Event = record.decode()?;
1042    /// assert_eq!(event, Event { id: 7, name: "boot".into() });
1043    /// # Ok(())
1044    /// # }
1045    /// ```
1046    #[cfg(feature = "pack-io")]
1047    pub fn decode<T: pack_io::Deserialize>(&self) -> Result<T> {
1048        pack_io::decode(&self.data).map_err(WalError::encoding)
1049    }
1050
1051    /// Decode the record's payload with `pack-io` 2, under its default
1052    /// limits: no allocation the input cannot back, at most 1 GiB for one
1053    /// value, and at most 128 levels of nested types.
1054    ///
1055    /// The mirror of [`Wal::append_pack`]. It also reads records written by
1056    /// [`Wal::append_typed`]: the same values decode from the same bytes. A
1057    /// record nested deeper than 128 levels is refused; read it with
1058    /// [`unpack_with`](Record::unpack_with) and a higher
1059    /// [`max_depth`](pack_io2::Config::max_depth). Available with the
1060    /// `pack-io-2` feature.
1061    ///
1062    /// # Errors
1063    ///
1064    /// [`WalError::Encoding`] if the bytes do not decode into `T` within the
1065    /// limits.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// use wal_db::{MemStore, Wal};
1071    /// use wal_db::pack_io2::{Deserialize, Serialize};
1072    ///
1073    /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
1074    /// #[pack_io(crate = "wal_db::pack_io2")]
1075    /// struct Event {
1076    ///     id: u64,
1077    ///     name: String,
1078    /// }
1079    ///
1080    /// # fn main() -> Result<(), wal_db::WalError> {
1081    /// let wal = Wal::with_store(MemStore::new())?;
1082    /// wal.append_pack(&Event { id: 7, name: "boot".into() })?;
1083    /// let event: Event = wal.iter()?.next().unwrap()?.unpack()?;
1084    /// assert_eq!(event, Event { id: 7, name: "boot".into() });
1085    /// # Ok(())
1086    /// # }
1087    /// ```
1088    #[cfg(feature = "pack-io-2")]
1089    pub fn unpack<T: pack_io2::Deserialize>(&self) -> Result<T> {
1090        pack_io2::decode(&self.data).map_err(WalError::encoding)
1091    }
1092
1093    /// [`unpack`](Record::unpack) under the limits of `config`: raise
1094    /// [`max_depth`](pack_io2::Config::max_depth) to read an old record
1095    /// nested more than 128 levels deep, or lower the limits for bytes from
1096    /// a less trusted source. Available with the `pack-io-2` feature.
1097    ///
1098    /// # Errors
1099    ///
1100    /// [`WalError::Encoding`] if `config` is invalid or the bytes do not
1101    /// decode into `T` within its limits.
1102    #[cfg(feature = "pack-io-2")]
1103    pub fn unpack_with<T: pack_io2::Deserialize>(&self, config: pack_io2::Config) -> Result<T> {
1104        pack_io2::decode_with_config(&self.data, config).map_err(WalError::encoding)
1105    }
1106}
1107
1108/// The outcome of reading one record-sized chunk at the iterator's cursor.
1109enum Step {
1110    /// A valid record, plus the offset just past it.
1111    Record(Record, u64),
1112    /// A damaged record. `skip_to` is the offset of the next record if its
1113    /// extent is known (length and payload present, only the checksum failed),
1114    /// or `None` if the damage makes the next record's position unknowable.
1115    Damaged(WalError, Option<u64>),
1116    /// A clean end: a short read, meaning the log stops here (a torn tail).
1117    End,
1118}
1119
1120/// The iterator returned by [`Wal::iter`].
1121///
1122/// Walks the records fully written when it was created, yielding
1123/// `Result<`[`Record`]`>`. Behaviour at a damaged record follows the configured
1124/// [`RecoveryPolicy`]: by default the iterator yields the damage once and stops;
1125/// under [`RecoveryPolicy::SkipBadRecords`] it yields the damage and continues
1126/// past it when the next record's position is still recoverable.
1127pub struct WalIter<'a, S: WalStore = FileStore> {
1128    wal: &'a Wal<S>,
1129    offset: u64,
1130    end: u64,
1131    done: bool,
1132    policy: RecoveryPolicy,
1133}
1134
1135impl<S: WalStore> WalIter<'_, S> {
1136    /// Read and classify the record at the current offset, without advancing.
1137    fn step(&self) -> Result<Step> {
1138        let mut header = [0u8; HEADER_LEN];
1139        if self.wal.store.read_at(self.offset, &mut header)? < HEADER_LEN {
1140            return Ok(Step::End);
1141        }
1142        let parsed = record::parse_header(&header);
1143        if parsed.len > self.wal.max_record_size {
1144            // The length is implausible, so the next record's position is
1145            // unknowable — there is nothing to skip to.
1146            return Ok(Step::Damaged(
1147                WalError::corruption(self.offset, "record length exceeds the maximum"),
1148                None,
1149            ));
1150        }
1151
1152        let payload_start = self
1153            .offset
1154            .checked_add(HEADER_LEN as u64)
1155            .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
1156        let mut payload = vec![0u8; parsed.len as usize];
1157        if self.wal.store.read_at(payload_start, &mut payload)? < payload.len() {
1158            return Ok(Step::End);
1159        }
1160        let next = payload_start
1161            .checked_add(u64::from(parsed.len))
1162            .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
1163
1164        if !record::verify(&header, &payload, parsed.crc) {
1165            // The length and payload are present, so we know where the next
1166            // record starts even though this one is corrupt.
1167            return Ok(Step::Damaged(
1168                WalError::corruption(self.offset, "checksum mismatch"),
1169                Some(next),
1170            ));
1171        }
1172
1173        Ok(Step::Record(
1174            Record {
1175                lsn: Lsn::new(self.offset),
1176                data: payload,
1177            },
1178            next,
1179        ))
1180    }
1181}
1182
1183impl<S: WalStore> Iterator for WalIter<'_, S> {
1184    type Item = Result<Record>;
1185
1186    fn next(&mut self) -> Option<Self::Item> {
1187        if self.done || self.offset >= self.end {
1188            return None;
1189        }
1190        match self.step() {
1191            Ok(Step::Record(record, next)) => {
1192                self.offset = next;
1193                Some(Ok(record))
1194            }
1195            // Skip-bad-records, and the next record is locatable: surface the
1196            // damage but continue from past it on the next call.
1197            Ok(Step::Damaged(error, Some(next)))
1198                if self.policy == RecoveryPolicy::SkipBadRecords =>
1199            {
1200                self.offset = next;
1201                Some(Err(error))
1202            }
1203            // Stop-at-first-error, or damage that makes the next position
1204            // unknowable: surface the damage and end.
1205            Ok(Step::Damaged(error, _)) => {
1206                self.done = true;
1207                Some(Err(error))
1208            }
1209            Ok(Step::End) => {
1210                self.done = true;
1211                None
1212            }
1213            Err(error) => {
1214                self.done = true;
1215                Some(Err(error))
1216            }
1217        }
1218    }
1219}
1220
1221impl<S: WalStore> fmt::Debug for WalIter<'_, S> {
1222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1223        f.debug_struct("WalIter")
1224            .field("offset", &self.offset)
1225            .field("end", &self.end)
1226            .field("done", &self.done)
1227            .finish()
1228    }
1229}
1230
1231#[cfg(all(test, not(loom)))]
1232#[allow(
1233    clippy::unwrap_used,
1234    clippy::expect_used,
1235    unused_must_use,
1236    unused_results
1237)]
1238mod tests {
1239    use std::sync::Arc;
1240    use std::thread;
1241
1242    use super::*;
1243    use crate::store::MemStore;
1244
1245    fn drain(wal: &Wal<MemStore>) -> Vec<Vec<u8>> {
1246        wal.iter()
1247            .unwrap()
1248            .map(|r| r.unwrap().into_data())
1249            .collect()
1250    }
1251
1252    fn corrupt_byte(store: &MemStore, offset: u64) {
1253        let mut byte = [0u8; 1];
1254        store.read_at(offset, &mut byte).unwrap();
1255        byte[0] ^= 0xFF;
1256        store.write_at(offset, &byte).unwrap();
1257    }
1258
1259    #[test]
1260    fn test_stop_at_first_error_stops_at_corruption() {
1261        let wal = Wal::with_store(MemStore::new()).unwrap(); // default policy
1262        wal.append(b"first").unwrap();
1263        let second = wal.append(b"second").unwrap();
1264        wal.append(b"third").unwrap();
1265        corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1266
1267        let items: Vec<_> = wal.iter().unwrap().collect();
1268        assert_eq!(items.len(), 2); // first ok, second damaged, then stop
1269        assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1270        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1271    }
1272
1273    #[test]
1274    fn test_skip_bad_records_continues_past_corruption() {
1275        let config = WalConfig::new().with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1276        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1277        wal.append(b"first").unwrap();
1278        let second = wal.append(b"second").unwrap();
1279        wal.append(b"third").unwrap();
1280        // Corrupt the payload only; the length prefix stays intact, so the
1281        // record is skippable.
1282        corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1283
1284        let items: Vec<_> = wal.iter().unwrap().collect();
1285        assert_eq!(items.len(), 3);
1286        assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1287        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1288        assert_eq!(items[2].as_ref().unwrap().data(), b"third");
1289    }
1290
1291    #[test]
1292    fn test_skip_bad_records_still_stops_on_unreadable_length() {
1293        let config = WalConfig::new()
1294            .with_max_record_size(16)
1295            .with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1296        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1297        wal.append(b"ok").unwrap();
1298        let second = wal.append(b"victim").unwrap();
1299        // Corrupt the length field to an implausible value: the next record's
1300        // position becomes unknowable, so even skip-mode must stop.
1301        corrupt_byte(wal.store(), second.get() + 4); // LEN_OFFSET within the header
1302
1303        let items: Vec<_> = wal.iter().unwrap().collect();
1304        assert_eq!(items.len(), 2); // first ok, then a damaged stop
1305        assert_eq!(items[0].as_ref().unwrap().data(), b"ok");
1306        assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1307    }
1308
1309    #[cfg(feature = "pack-io")]
1310    #[test]
1311    fn test_typed_record_roundtrip() {
1312        use pack_io::{Deserialize, Serialize};
1313
1314        #[derive(Serialize, Deserialize, PartialEq, Debug)]
1315        struct Entry {
1316            id: u64,
1317            label: String,
1318        }
1319
1320        let wal = Wal::with_store(MemStore::new()).unwrap();
1321        wal.append_typed(&Entry {
1322            id: 9,
1323            label: "nine".into(),
1324        })
1325        .unwrap();
1326        wal.append_typed(&Entry {
1327            id: 10,
1328            label: "ten".into(),
1329        })
1330        .unwrap();
1331
1332        let decoded: Vec<Entry> = wal
1333            .iter()
1334            .unwrap()
1335            .map(|r| r.unwrap().decode().unwrap())
1336            .collect();
1337        assert_eq!(
1338            decoded[0],
1339            Entry {
1340                id: 9,
1341                label: "nine".into()
1342            }
1343        );
1344        assert_eq!(
1345            decoded[1],
1346            Entry {
1347                id: 10,
1348                label: "ten".into()
1349            }
1350        );
1351    }
1352
1353    #[cfg(feature = "pack-io")]
1354    #[test]
1355    fn test_typed_decode_wrong_type_errors() {
1356        use pack_io::{Deserialize, Serialize};
1357
1358        #[derive(Serialize)]
1359        struct Big {
1360            a: u64,
1361            b: u64,
1362            c: u64,
1363        }
1364        #[derive(Deserialize)]
1365        struct Small {
1366            _a: u8,
1367        }
1368
1369        let wal = Wal::with_store(MemStore::new()).unwrap();
1370        wal.append_typed(&Big { a: 1, b: 2, c: 3 }).unwrap();
1371        let record = wal.iter().unwrap().next().unwrap().unwrap();
1372        // Decoding 24 bytes as a 1-byte type leaves trailing bytes -> error.
1373        let result: Result<Small> = record.decode();
1374        assert!(matches!(result, Err(WalError::Encoding { .. })));
1375    }
1376
1377    #[test]
1378    fn test_append_assigns_byte_offset_lsns() {
1379        let wal = Wal::with_store(MemStore::new()).unwrap();
1380        let a = wal.append(b"abc").unwrap(); // 8 header + 3 = 11 bytes
1381        let b = wal.append(b"de").unwrap();
1382        assert_eq!(a.get(), 0);
1383        assert_eq!(b.get(), 11);
1384    }
1385
1386    #[test]
1387    fn test_iter_reads_back_all_records_in_order() {
1388        let wal = Wal::with_store(MemStore::new()).unwrap();
1389        wal.append(b"one").unwrap();
1390        wal.append(b"two").unwrap();
1391        wal.append(b"three").unwrap();
1392        assert_eq!(
1393            drain(&wal),
1394            vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]
1395        );
1396    }
1397
1398    #[test]
1399    fn test_empty_log_iterates_to_nothing() {
1400        let wal = Wal::with_store(MemStore::new()).unwrap();
1401        assert!(wal.is_empty());
1402        assert_eq!(drain(&wal).len(), 0);
1403    }
1404
1405    #[test]
1406    fn test_empty_record_roundtrips() {
1407        let wal = Wal::with_store(MemStore::new()).unwrap();
1408        wal.append(b"").unwrap();
1409        assert_eq!(drain(&wal), vec![Vec::<u8>::new()]);
1410    }
1411
1412    #[test]
1413    fn test_record_too_large_is_rejected() {
1414        let config = WalConfig::new().with_max_record_size(4);
1415        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1416        wal.append(b"ok").unwrap();
1417        let err = wal.append(b"too long").unwrap_err();
1418        assert!(matches!(err, WalError::RecordTooLarge { len: 8, max: 4 }));
1419        // The rejected append did not advance the log.
1420        assert_eq!(drain(&wal), vec![b"ok".to_vec()]);
1421    }
1422
1423    #[test]
1424    fn test_reopen_recovers_records() {
1425        let wal = Wal::with_store(MemStore::new()).unwrap();
1426        wal.append(b"first").unwrap();
1427        wal.append(b"second").unwrap();
1428        wal.sync().unwrap();
1429        let image = wal.store().snapshot();
1430
1431        let reopened = Wal::with_store(MemStore::from_bytes(image)).unwrap();
1432        assert_eq!(
1433            drain(&reopened),
1434            vec![b"first".to_vec(), b"second".to_vec()]
1435        );
1436        // The next append continues at the recovered end: two records of
1437        // (8 + 5) and (8 + 6) bytes leave the tail at 27.
1438        assert_eq!(reopened.append(b"third").unwrap().get(), 27);
1439    }
1440
1441    #[test]
1442    fn test_recovery_truncates_torn_tail() {
1443        let wal = Wal::with_store(MemStore::new()).unwrap();
1444        wal.append(b"good record").unwrap();
1445        let clean_len = wal.len();
1446        // Append raw garbage directly to the store: a torn tail.
1447        wal.store().write_at(clean_len, &[0xAB; 5]).unwrap();
1448
1449        let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1450        assert_eq!(drain(&reopened), vec![b"good record".to_vec()]);
1451        assert_eq!(reopened.len(), clean_len);
1452    }
1453
1454    #[test]
1455    fn test_corrupt_record_surfaces_error_then_stops() {
1456        let wal = Wal::with_store(MemStore::new()).unwrap();
1457        wal.append(b"intact").unwrap();
1458        let second = wal.append(b"victim").unwrap();
1459        // Flip a byte inside the second record's payload (offset + header).
1460        let payload_offset = second.get() + HEADER_LEN as u64;
1461        let mut byte = [0u8; 1];
1462        wal.store().read_at(payload_offset, &mut byte).unwrap();
1463        byte[0] ^= 0xFF;
1464        wal.store().write_at(payload_offset, &byte).unwrap();
1465
1466        let mut iter = wal.iter().unwrap();
1467        assert_eq!(iter.next().unwrap().unwrap().data(), b"intact");
1468        assert!(matches!(
1469            iter.next().unwrap(),
1470            Err(WalError::Corruption { .. })
1471        ));
1472        assert!(iter.next().is_none());
1473    }
1474
1475    #[test]
1476    fn test_append_and_sync_is_durable() {
1477        let wal = Wal::with_store(MemStore::new()).unwrap();
1478        wal.append_and_sync(b"committed").unwrap();
1479        assert_eq!(drain(&wal), vec![b"committed".to_vec()]);
1480    }
1481
1482    #[test]
1483    fn test_iter_from_seeks_to_lsn() {
1484        let wal = Wal::with_store(MemStore::new()).unwrap();
1485        wal.append(b"a").unwrap();
1486        let b = wal.append(b"b").unwrap();
1487        wal.append(b"c").unwrap();
1488
1489        let got: Vec<Vec<u8>> = wal
1490            .iter_from(b)
1491            .unwrap()
1492            .map(|r| r.unwrap().into_data())
1493            .collect();
1494        assert_eq!(got, vec![b"b".to_vec(), b"c".to_vec()]);
1495    }
1496
1497    #[test]
1498    fn test_iter_from_past_end_is_empty() {
1499        let wal = Wal::with_store(MemStore::new()).unwrap();
1500        wal.append(b"a").unwrap();
1501        assert_eq!(wal.iter_from(Lsn::new(9_999)).unwrap().count(), 0);
1502    }
1503
1504    #[test]
1505    fn test_truncate_after_drops_later_records() {
1506        let wal = Wal::with_store(MemStore::new()).unwrap();
1507        wal.append(b"first").unwrap(); // [0, 13)
1508        let keep = wal.append(b"second").unwrap(); // [13, 27)
1509        wal.append(b"third").unwrap();
1510        wal.append(b"fourth").unwrap();
1511
1512        wal.truncate_after(keep).unwrap();
1513        assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1514        assert_eq!(wal.len(), 27);
1515
1516        // Appends resume immediately after the kept record.
1517        assert_eq!(wal.append(b"new").unwrap().get(), 27);
1518        assert_eq!(
1519            drain(&wal),
1520            vec![b"first".to_vec(), b"second".to_vec(), b"new".to_vec()]
1521        );
1522    }
1523
1524    #[test]
1525    fn test_truncate_after_keeping_last_record_is_a_no_op() {
1526        let wal = Wal::with_store(MemStore::new()).unwrap();
1527        wal.append(b"first").unwrap();
1528        let last = wal.append(b"second").unwrap();
1529        let before = wal.len();
1530
1531        wal.truncate_after(last).unwrap();
1532        assert_eq!(wal.len(), before);
1533        assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1534    }
1535
1536    #[test]
1537    fn test_truncate_after_invalid_lsn_errors() {
1538        let config = WalConfig::new().with_max_record_size(64);
1539        let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1540        wal.append(b"only record").unwrap();
1541        // An LSN that does not land on a record boundary is rejected.
1542        let err = wal.truncate_after(Lsn::new(3)).unwrap_err();
1543        assert!(matches!(err, WalError::Corruption { .. }));
1544    }
1545
1546    #[test]
1547    fn test_concurrent_appends_no_overlap_all_recovered() {
1548        const THREADS: usize = 8;
1549        const PER_THREAD: usize = 200;
1550
1551        let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1552        let mut handles = Vec::new();
1553        for t in 0..THREADS {
1554            let wal = Arc::clone(&wal);
1555            handles.push(thread::spawn(move || {
1556                let mut lsns = Vec::with_capacity(PER_THREAD);
1557                for i in 0..PER_THREAD {
1558                    let payload = format!("t{t}-r{i}").into_bytes();
1559                    lsns.push(wal.append(&payload).unwrap().get());
1560                }
1561                lsns
1562            }));
1563        }
1564        let mut all_lsns = Vec::new();
1565        for h in handles {
1566            all_lsns.extend(h.join().unwrap());
1567        }
1568        wal.sync().unwrap();
1569
1570        // Every LSN is distinct (no two records shared a byte range).
1571        let mut sorted = all_lsns.clone();
1572        sorted.sort_unstable();
1573        sorted.dedup();
1574        assert_eq!(sorted.len(), THREADS * PER_THREAD);
1575
1576        // Recovery reads back exactly the records that were appended, in offset
1577        // order, with no gaps or corruption.
1578        let records = drain(&wal);
1579        assert_eq!(records.len(), THREADS * PER_THREAD);
1580
1581        // Reopening from the raw image recovers the same set.
1582        let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1583        assert_eq!(reopened.iter().unwrap().count(), THREADS * PER_THREAD);
1584    }
1585
1586    #[test]
1587    fn test_concurrent_append_and_sync_all_durable() {
1588        const THREADS: usize = 8;
1589
1590        let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1591        let mut handles = Vec::new();
1592        for t in 0..THREADS {
1593            let wal = Arc::clone(&wal);
1594            handles.push(thread::spawn(move || {
1595                for i in 0..50 {
1596                    wal.append_and_sync(format!("{t}:{i}").as_bytes()).unwrap();
1597                }
1598            }));
1599        }
1600        for h in handles {
1601            h.join().unwrap();
1602        }
1603        assert_eq!(drain(&wal).len(), THREADS * 50);
1604    }
1605}