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