Diffinery

homeflare/celldpublic

939 lines · 36.8 KBRaw History
1//! wal.rs — SQLite WAL header/frame parsing + cumulative SQLite checksums.
2//!
3//! Ported from [email protected] wal_reader.go:14-295 (read path) and the
4//! `WALChecksum` helper in [email protected] litestream.go:110-119 (re-exported
5//! from the crate root as [`crate::wal_checksum`]).
6//!
7//! A [`WalReader`] wraps a byte buffer and parses SQLite WAL frames, verifying
8//! salt and cumulative-checksum integrity as it reads. It does **not** enforce
9//! transaction boundaries (it may return uncommitted frames); honoring commit
10//! records is the caller's responsibility (see [`WalReader::page_map`]).
11//!
12//! ## Byte format (read straight from the SQLite WAL spec; see wal_reader.go)
13//!
14//! WAL header (32 bytes, all fields big-endian at fixed offsets):
15//! ```text
16//! [0..4] magic 0x377f0682 => checksums LITTLE-endian
17//! 0x377f0683 => checksums BIG-endian
18//! [4..8] version must equal 3007000
19//! [8..12] page size
20//! [12..16] checkpoint sequence number
21//! [16..20] salt-1
22//! [20..24] salt-2
23//! [24..28] checksum-1 (cumulative checksum of bytes [0..24])
24//! [28..32] checksum-2
25//! ```
26//!
27//! WAL frame header (24 bytes, all fields big-endian):
28//! ```text
29//! [0..4] page number
30//! [4..8] commit size in pages for a commit record, else 0
31//! [8..12] salt-1 (must match the header salt-1)
32//! [12..16] salt-2 (must match the header salt-2)
33//! [16..20] checksum-1 (cumulative checksum through this frame's data)
34//! [20..24] checksum-2
35//! ```
36//!
37//! A frame is `pageSize + 24` bytes. The cumulative checksum is seeded with the
38//! header checksum and rolled forward over each frame's 8-byte header prefix and
39//! then its page data, in the byte order chosen by the magic.
40
41use std::collections::HashMap;
42
43use crate::{wal_checksum, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE};
44
45/// Required WAL format version (`3007000`), as found at header offset 4.
46///
47/// Ported from [email protected] wal_reader.go:118.
48pub const WAL_VERSION: u32 = 3_007_000;
49
50/// WAL header magic indicating checksums are computed **little-endian**.
51///
52/// Ported from [email protected] wal_reader.go:101.
53pub const WAL_MAGIC_LITTLE_ENDIAN: u32 = 0x377f_0682;
54
55/// WAL header magic indicating checksums are computed **big-endian**.
56///
57/// Ported from [email protected] wal_reader.go:103.
58pub const WAL_MAGIC_BIG_ENDIAN: u32 = 0x377f_0683;
59
60// ── Errors ────────────────────────────────────────────────────────────────────
61
62/// Errors returned by [`WalReader`].
63///
64/// The Go reader leans on `io.EOF` as a control-flow sentinel: it signals the
65/// clean end of the *valid* WAL, but also a short/partial read, a salt mismatch,
66/// or a checksum mismatch — all of which mean "stop reading here, the rest of the
67/// file is not a valid continuation." We model that single sentinel as
68/// [`WalError::Eof`] so callers can branch on it exactly like Go's
69/// `errors.Is(err, io.EOF)` (see [`WalError::is_eof`]). Non-EOF variants carry
70/// the same human-readable messages as the Go `fmt.Errorf` strings so the ported
71/// tests can assert them byte-for-byte.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum WalError {
74 /// End of the valid WAL.
75 ///
76 /// Mirrors every `return ..., io.EOF` in wal_reader.go: a partial header, a
77 /// failed header checksum, a short frame read, a salt mismatch, or a frame
78 /// checksum mismatch. In all of these the WAL has no further valid frames.
79 Eof,
80
81 /// `invalid wal header magic: <hex>` — the magic was neither
82 /// `0x377f0682` nor `0x377f0683`.
83 ///
84 /// Ported from [email protected] wal_reader.go:106.
85 InvalidMagic(u32),
86
87 /// `unsupported wal version: <n>` — header version field was not `3007000`.
88 ///
89 /// Ported from [email protected] wal_reader.go:119.
90 UnsupportedVersion(u32),
91
92 /// `WALReader.ReadFrame(): buffer size (<n>) must match page size (<m>)`.
93 ///
94 /// Ported from [email protected] wal_reader.go:139.
95 BufferSize {
96 /// Length of the buffer the caller supplied.
97 got: usize,
98 /// The WAL's page size.
99 want: u32,
100 },
101
102 /// `offset (<n>) must be greater than the wal header size (<m>)` — passed to
103 /// [`WalReader::new_with_offset`] with an offset at or before the header.
104 ///
105 /// Ported from [email protected] wal_reader.go:48.
106 OffsetTooSmall {
107 /// The requested offset.
108 offset: i64,
109 /// The WAL header size.
110 header_size: i64,
111 },
112
113 /// `unaligned wal offset <n> for page size <m>` — the offset does not land on
114 /// a frame boundary.
115 ///
116 /// Ported from [email protected] wal_reader.go:64.
117 UnalignedOffset {
118 /// The requested offset.
119 offset: i64,
120 /// The WAL's page size.
121 page_size: u32,
122 },
123
124 /// The previous frame at the seek offset could not be re-read (its salt or
125 /// checksum did not match). **Load-bearing**: `DB.sync` catches this and
126 /// falls back to a full snapshot (db.go:1571-1577).
127 ///
128 /// Ported from `PrevFrameMismatchError` in [email protected]
129 /// wal_reader.go:284-294.
130 PrevFrameMismatch,
131}
132
133impl WalError {
134 /// Returns `true` for the [`WalError::Eof`] sentinel.
135 ///
136 /// This is the analog of Go's `errors.Is(err, io.EOF)`, which the upstream
137 /// callers (`PageMap`, the test suite) use to detect the end of the WAL.
138 #[inline]
139 pub fn is_eof(&self) -> bool {
140 matches!(self, WalError::Eof)
141 }
142}
143
144impl std::fmt::Display for WalError {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 match self {
147 // Matches the Go string "EOF" (io.EOF.Error()).
148 WalError::Eof => f.write_str("EOF"),
149 // Go: fmt.Errorf("invalid wal header magic: %x", magic) — lowercase
150 // hex, no leading zeros (matches Go's %x for a uint32).
151 WalError::InvalidMagic(magic) => write!(f, "invalid wal header magic: {magic:x}"),
152 WalError::UnsupportedVersion(v) => write!(f, "unsupported wal version: {v}"),
153 WalError::BufferSize { got, want } => write!(
154 f,
155 "WALReader.ReadFrame(): buffer size ({got}) must match page size ({want})"
156 ),
157 WalError::OffsetTooSmall {
158 offset,
159 header_size,
160 } => write!(
161 f,
162 "offset ({offset}) must be greater than the wal header size ({header_size})"
163 ),
164 WalError::UnalignedOffset { offset, page_size } => {
165 write!(f, "unaligned wal offset {offset} for page size {page_size}")
166 }
167 WalError::PrevFrameMismatch => f.write_str("previous frame mismatch"),
168 }
169 }
170}
171
172impl std::error::Error for WalError {}
173
174impl From<WalError> for crate::Error {
175 /// Lifts a [`WalError`] into the crate-wide error type for callers that work
176 /// in terms of [`crate::Error`]. EOF and the structured WAL errors become
177 /// `Error::Other` carrying the same message.
178 fn from(e: WalError) -> Self {
179 crate::Error::Other(Box::new(e))
180 }
181}
182
183/// `WalReader`'s `Result` alias.
184pub type WalResult<T> = std::result::Result<T, WalError>;
185
186// ── WalReader ───────────────────────────────────────────────────────────────
187
188/// Reads SQLite WAL frames from an in-memory byte buffer, verifying salts and
189/// the cumulative SQLite checksum as it goes.
190///
191/// This is the faithful analog of Go's `WALReader` (wal_reader.go:19-31). Go
192/// wraps an `io.ReaderAt`; the upstream tests always back that with a
193/// `bytes.Reader` over the whole WAL, so we wrap a borrowed `&[u8]` and emulate
194/// `ReadAt` semantics directly: a read whose requested length runs past the end
195/// of the buffer yields fewer bytes, which the algorithm treats as `io.EOF`
196/// exactly as Go does.
197///
198/// Ported from [email protected] wal_reader.go:19-187.
199#[derive(Debug)]
200pub struct WalReader<'a> {
201 /// Backing WAL bytes (the whole file, as the Go `io.ReaderAt`).
202 data: &'a [u8],
203 /// Index of the *next* frame to read (0-based). Go field `frameN`.
204 frame_n: i64,
205
206 /// `true` when checksums are big-endian (magic `0x377f0683`),
207 /// `false` when little-endian (magic `0x377f0682`). Go field `bo`.
208 big_endian: bool,
209 /// Page size from the header. Go field `pageSize`.
210 page_size: u32,
211 /// Checkpoint sequence number from the header. Go field `seq`.
212 #[allow(dead_code)]
213 seq: u32,
214
215 /// Header salt-1 / salt-2; frames must match these. Go fields `salt1/salt2`.
216 salt1: u32,
217 salt2: u32,
218 /// Running cumulative checksum. Seeded from the header checksum, then rolled
219 /// forward frame by frame. Go fields `chksum1/chksum2`.
220 chksum1: u32,
221 chksum2: u32,
222}
223
224impl<'a> WalReader<'a> {
225 /// Creates a new reader over `data`, parsing the WAL header immediately.
226 ///
227 /// Returns [`WalError::Eof`] if the buffer is too short to hold a header or
228 /// the header checksum does not validate (a partial WAL-header write during
229 /// checkpointing). Returns [`WalError::InvalidMagic`] /
230 /// [`WalError::UnsupportedVersion`] for a malformed header.
231 ///
232 /// Ported from `NewWALReader` in [email protected] wal_reader.go:34-40.
233 pub fn new(data: &'a [u8]) -> WalResult<Self> {
234 let mut r = WalReader {
235 data,
236 frame_n: 0,
237 big_endian: false,
238 page_size: 0,
239 seq: 0,
240 salt1: 0,
241 salt2: 0,
242 chksum1: 0,
243 chksum2: 0,
244 };
245 r.read_header()?;
246 Ok(r)
247 }
248
249 /// Creates a new reader positioned at `offset`, loading the running checksum
250 /// from the *previous* frame so reading can resume mid-WAL.
251 ///
252 /// `salt1`/`salt2` are the expected salts of the segment being resumed; they
253 /// override the header salts in case the start of the file was overwritten by
254 /// a later transaction. Returns:
255 /// - [`WalError::OffsetTooSmall`] if `offset <= WAL_HEADER_SIZE` (we must be
256 /// able to read a previous frame),
257 /// - [`WalError::UnalignedOffset`] if `offset` is not on a frame boundary,
258 /// - [`WalError::PrevFrameMismatch`] if the previous frame cannot be re-read
259 /// (salt/checksum mismatch) — the caller falls back to a full snapshot.
260 ///
261 /// Ported from `NewWALReaderWithOffset` in [email protected]
262 /// wal_reader.go:42-75.
263 pub fn new_with_offset(data: &'a [u8], offset: i64, salt1: u32, salt2: u32) -> WalResult<Self> {
264 // Must not start on the first page — we need to read the previous frame.
265 if offset <= WAL_HEADER_SIZE as i64 {
266 return Err(WalError::OffsetTooSmall {
267 offset,
268 header_size: WAL_HEADER_SIZE as i64,
269 });
270 }
271
272 let mut r = WalReader {
273 data,
274 frame_n: 0,
275 big_endian: false,
276 page_size: 0,
277 seq: 0,
278 salt1: 0,
279 salt2: 0,
280 chksum1: 0,
281 chksum2: 0,
282 };
283
284 // Read header to determine page size & byte order.
285 r.read_header()?;
286
287 // Override salts in case the beginning of the file was overwritten.
288 r.salt1 = salt1;
289 r.salt2 = salt2;
290
291 // Ensure the offset lands on a frame start.
292 let frame_size = r.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
293 if (offset - WAL_HEADER_SIZE as i64) % frame_size != 0 {
294 return Err(WalError::UnalignedOffset {
295 offset,
296 page_size: r.page_size,
297 });
298 }
299 r.frame_n = (offset - WAL_HEADER_SIZE as i64) / frame_size;
300
301 // Read the previous frame to load the running checksum. Any failure here
302 // (salt/checksum mismatch surfaces as WalError::Eof from read_frame_inner)
303 // means the previous frame doesn't match what we expect → mismatch.
304 r.frame_n -= 1;
305 let mut buf = vec![0u8; r.page_size as usize];
306 if r.read_frame_inner(&mut buf, false).is_err() {
307 return Err(WalError::PrevFrameMismatch);
308 }
309
310 Ok(r)
311 }
312
313 /// Returns the page size from the header.
314 ///
315 /// Ported from `PageSize` in [email protected] wal_reader.go:78.
316 #[inline]
317 pub fn page_size(&self) -> u32 {
318 self.page_size
319 }
320
321 /// Returns `true` when checksums for this WAL are big-endian (magic
322 /// `0x377f0683`), `false` when little-endian (`0x377f0682`).
323 ///
324 /// Exposed because the byte order is a load-bearing, hard-to-observe property
325 /// that the golden test asserts directly.
326 #[inline]
327 pub fn is_big_endian(&self) -> bool {
328 self.big_endian
329 }
330
331 /// Returns the header salt pair `(salt1, salt2)`.
332 #[inline]
333 pub fn salt(&self) -> (u32, u32) {
334 (self.salt1, self.salt2)
335 }
336
337 /// Returns the file offset of the last frame read, or `0` if no frame has
338 /// been read yet.
339 ///
340 /// Ported from `Offset` in [email protected] wal_reader.go:82-87.
341 pub fn offset(&self) -> i64 {
342 if self.frame_n == 0 {
343 return 0;
344 }
345 WAL_HEADER_SIZE as i64
346 + ((self.frame_n - 1) * (WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64))
347 }
348
349 /// Reads `n` bytes at absolute `offset`, returning `None` (the `io.EOF`
350 /// case) when fewer than `n` bytes are available — exactly the behavior of
351 /// Go's `io.ReaderAt.ReadAt` over a `bytes.Reader` short read, which the
352 /// upstream code converts to `io.EOF`.
353 fn read_at(&self, offset: i64, n: usize) -> Option<&'a [u8]> {
354 if offset < 0 {
355 return None;
356 }
357 let start = offset as usize;
358 let end = start.checked_add(n)?;
359 if end > self.data.len() {
360 return None;
361 }
362 Some(&self.data[start..end])
363 }
364
365 /// Reads and validates the WAL header into `self`.
366 ///
367 /// Ported from `readHeader` in [email protected] wal_reader.go:90-129.
368 fn read_header(&mut self) -> WalResult<()> {
369 // If we have a partial WAL, mark WAL as done (io.EOF).
370 let hdr = match self.read_at(0, WAL_HEADER_SIZE) {
371 Some(b) => b,
372 None => return Err(WalError::Eof),
373 };
374
375 // Determine byte order of checksums from the magic (always read
376 // big-endian, like Go's binary.BigEndian.Uint32(hdr[0:])).
377 let magic = be_u32(&hdr[0..]);
378 self.big_endian = match magic {
379 WAL_MAGIC_LITTLE_ENDIAN => false,
380 WAL_MAGIC_BIG_ENDIAN => true,
381 _ => return Err(WalError::InvalidMagic(magic)),
382 };
383
384 // If the header checksum doesn't match then we may have failed with a
385 // partial WAL header write during checkpointing => io.EOF.
386 let chksum1 = be_u32(&hdr[24..]);
387 let chksum2 = be_u32(&hdr[28..]);
388 let (v0, v1) = wal_checksum(self.big_endian, 0, 0, &hdr[..24]);
389 if v0 != chksum1 || v1 != chksum2 {
390 return Err(WalError::Eof);
391 }
392
393 // Verify version is correct.
394 let version = be_u32(&hdr[4..]);
395 if version != WAL_VERSION {
396 return Err(WalError::UnsupportedVersion(version));
397 }
398
399 self.page_size = be_u32(&hdr[8..]);
400 self.seq = be_u32(&hdr[12..]);
401 self.salt1 = be_u32(&hdr[16..]);
402 self.salt2 = be_u32(&hdr[20..]);
403 self.chksum1 = chksum1;
404 self.chksum2 = chksum2;
405
406 Ok(())
407 }
408
409 /// Reads the next frame into `data` and returns `(pgno, commit)`.
410 ///
411 /// Returns [`WalError::Eof`] at the end of the valid WAL (including on a
412 /// salt or checksum mismatch, which terminate the valid region). `data` must
413 /// be exactly `page_size` bytes or [`WalError::BufferSize`] is returned.
414 ///
415 /// Ported from `ReadFrame` in [email protected] wal_reader.go:131-135.
416 pub fn read_frame(&mut self, data: &mut [u8]) -> WalResult<(u32, u32)> {
417 self.read_frame_inner(data, true)
418 }
419
420 /// Frame-read core shared by [`Self::read_frame`] and the offset constructor.
421 ///
422 /// When `verify_checksum` is `false`, the running checksum is *set* from the
423 /// frame's stored checksum rather than verified against a rolling value —
424 /// used when seeking to an offset without checksumming from the beginning.
425 ///
426 /// Ported from `readFrame` in [email protected] wal_reader.go:137-187.
427 fn read_frame_inner(
428 &mut self,
429 data: &mut [u8],
430 verify_checksum: bool,
431 ) -> WalResult<(u32, u32)> {
432 if data.len() != self.page_size as usize {
433 return Err(WalError::BufferSize {
434 got: data.len(),
435 want: self.page_size,
436 });
437 }
438
439 let frame_size = self.page_size as i64 + WAL_FRAME_HEADER_SIZE as i64;
440 let offset = WAL_HEADER_SIZE as i64 + (self.frame_n * frame_size);
441
442 // Read WAL frame header. A short read is io.EOF.
443 let hdr = match self.read_at(offset, WAL_FRAME_HEADER_SIZE) {
444 Some(b) => b,
445 None => return Err(WalError::Eof),
446 };
447
448 // Read WAL page data. A short read is io.EOF.
449 let page = match self.read_at(offset + WAL_FRAME_HEADER_SIZE as i64, data.len()) {
450 Some(b) => b,
451 None => return Err(WalError::Eof),
452 };
453 data.copy_from_slice(page);
454
455 // Verify salt matches the salt in the header; otherwise end of valid WAL.
456 let salt1 = be_u32(&hdr[8..]);
457 let salt2 = be_u32(&hdr[12..]);
458 if self.salt1 != salt1 || self.salt2 != salt2 {
459 return Err(WalError::Eof);
460 }
461
462 // Verify the cumulative checksum. If verification is disabled, it is
463 // because we are jumping to an offset and not checksumming from the
464 // beginning, so we simply adopt the frame's stored checksum.
465 let chksum1 = be_u32(&hdr[16..]);
466 let chksum2 = be_u32(&hdr[20..]);
467 if verify_checksum {
468 let (c0, c1) = wal_checksum(self.big_endian, self.chksum1, self.chksum2, &hdr[..8]);
469 let (c0, c1) = wal_checksum(self.big_endian, c0, c1, data);
470 self.chksum1 = c0;
471 self.chksum2 = c1;
472 if self.chksum1 != chksum1 || self.chksum2 != chksum2 {
473 return Err(WalError::Eof);
474 }
475 } else {
476 self.chksum1 = chksum1;
477 self.chksum2 = chksum2;
478 }
479
480 let pgno = be_u32(&hdr[0..]);
481 let commit = be_u32(&hdr[4..]);
482
483 self.frame_n += 1;
484
485 Ok((pgno, commit))
486 }
487
488 /// Reads all committed frames to end-of-file and returns a map of page
489 /// number → byte offset of the latest committed version of that page, the
490 /// max offset of the WAL segment read, and the final database size in pages.
491 ///
492 /// Pages above the final commit size are dropped (handles a DB that shrank,
493 /// e.g. via `VACUUM`, between transactions).
494 ///
495 /// Ported from `PageMap` in [email protected] wal_reader.go:189-244.
496 pub fn page_map(&mut self) -> WalResult<(HashMap<u32, i64>, i64, u32)> {
497 let mut m: HashMap<u32, i64> = HashMap::new();
498 let mut tx_map: HashMap<u32, i64> = HashMap::new();
499 let mut commit: u32 = 0;
500 let mut data = vec![0u8; self.page_size as usize];
501
502 loop {
503 let (pgno, fcommit) = match self.read_frame(&mut data) {
504 Ok(v) => v,
505 Err(e) if e.is_eof() => break,
506 Err(e) => return Err(e),
507 };
508
509 // Update latest offset for this page within the current transaction.
510 // Not promoted to the full map until the txn commits.
511 let offset = self.offset();
512 tx_map.insert(pgno, offset);
513
514 // On a commit record, transfer the txn offsets into the full map and
515 // record the new DB size.
516 if fcommit != 0 {
517 for (p, o) in tx_map.drain() {
518 m.insert(p, o);
519 }
520 commit = fcommit;
521 }
522 }
523
524 // Remove pages that exceed the final commit size (DB shrank mid-WAL).
525 m.retain(|&pgno, _| pgno <= commit);
526
527 // No complete transactions => original (zero) offset.
528 if m.is_empty() {
529 return Ok((m, 0, 0));
530 }
531
532 // Highest page offset, extended to the end of that frame.
533 let mut end: i64 = 0;
534 for &offset in m.values() {
535 if end == 0 || offset > end {
536 end = offset;
537 }
538 }
539 end += WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64;
540
541 Ok((m, end, commit))
542 }
543
544 /// Returns the set of unique frame salt pairs in the WAL, scanning until the
545 /// `until` salt pair is seen or end-of-file is reached.
546 ///
547 /// Unlike frame reading, this does **not** verify checksums or that frame
548 /// salts match the header — it deliberately collects *every* distinct salt,
549 /// including those from superseded transactions.
550 ///
551 /// Ported from `FrameSaltsUntil` in [email protected] wal_reader.go:246-270.
552 pub fn frame_salts_until(
553 &self,
554 until: (u32, u32),
555 ) -> WalResult<std::collections::HashSet<(u32, u32)>> {
556 let mut m = std::collections::HashSet::new();
557 let step = WAL_FRAME_HEADER_SIZE as i64 + self.page_size as i64;
558 let mut offset = WAL_HEADER_SIZE as i64;
559 // The loop ends either when a frame-header read runs short (the Go
560 // `n != len(hdr)` => break) or when we reach the `until` salt below.
561 while let Some(hdr) = self.read_at(offset, WAL_FRAME_HEADER_SIZE) {
562 let salt1 = be_u32(&hdr[8..]);
563 let salt2 = be_u32(&hdr[12..]);
564
565 // Track unique salts.
566 m.insert((salt1, salt2));
567
568 // Stop once we've seen the salt we were asked to read up to.
569 if salt1 == until.0 && salt2 == until.1 {
570 break;
571 }
572
573 offset += step;
574 }
575 Ok(m)
576 }
577}
578
579/// Reads a big-endian `u32` from the first four bytes of `b`.
580///
581/// All WAL header/frame scalar fields are big-endian regardless of the checksum
582/// byte order (Go uses `binary.BigEndian.Uint32`). Panics if `b.len() < 4`,
583/// which never happens for the fixed-offset accesses in this module.
584#[inline]
585fn be_u32(b: &[u8]) -> u32 {
586 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592 use std::path::PathBuf;
593
594 /// Loads a WAL test vector from the **read-only** upstream Go testdata tree
595 /// (`reference/litestream-go/testdata/wal-reader/<name>/wal`). These are the
596 /// exact fixtures the ported Go tests (`wal_reader_test.go`) consume.
597 fn read_testdata(name: &str) -> Vec<u8> {
598 let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
599 p.push("reference/litestream-go/testdata/wal-reader");
600 p.push(name);
601 p.push("wal");
602 std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display()))
603 }
604
605 /// Loads the immutable golden SQLite WAL fixture.
606 fn read_golden_wal() -> Vec<u8> {
607 let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
608 p.push("tests/fixtures/golden/sample.wal");
609 std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display()))
610 }
611
612 // ── Port of TestWALReader/OK (wal_reader_test.go:16-75) ────────────────────
613 #[test]
614 fn test_wal_reader_ok() {
615 let mut buf = vec![0u8; 4096];
616 let b = read_testdata("ok");
617
618 let mut r = WalReader::new(&b).expect("new reader");
619 assert_eq!(r.page_size(), 4096, "PageSize");
620 assert_eq!(r.offset(), 0, "Offset");
621
622 // First frame.
623 let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1");
624 assert_eq!(pgno, 1, "pgno");
625 assert_eq!(commit, 0, "commit");
626 assert_eq!(&buf[..], &b[56..4152], "page data mismatch");
627 assert_eq!(r.offset(), 32, "Offset");
628
629 // Second frame: end of transaction.
630 let (pgno, commit) = r.read_frame(&mut buf).expect("frame 2");
631 assert_eq!(pgno, 2, "pgno");
632 assert_eq!(commit, 2, "commit");
633 assert_eq!(&buf[..], &b[4176..8272], "page data mismatch");
634 assert_eq!(r.offset(), 4152, "Offset");
635
636 // Third frame.
637 let (pgno, commit) = r.read_frame(&mut buf).expect("frame 3");
638 assert_eq!(pgno, 2, "pgno");
639 assert_eq!(commit, 2, "commit");
640 assert_eq!(&buf[..], &b[8296..12392], "page data mismatch");
641 assert_eq!(r.offset(), 8272, "Offset");
642
643 // End of WAL.
644 let err = r.read_frame(&mut buf).expect_err("expected EOF");
645 assert!(err.is_eof(), "unexpected error: {err}");
646 }
647
648 // ── Port of TestWALReader/SaltMismatch (wal_reader_test.go:77-109) ─────────
649 #[test]
650 fn test_wal_reader_salt_mismatch() {
651 let mut buf = vec![0u8; 4096];
652 let b = read_testdata("salt-mismatch");
653
654 let mut r = WalReader::new(&b).expect("new reader");
655 assert_eq!(r.page_size(), 4096);
656 assert_eq!(r.offset(), 0);
657
658 // First frame is valid.
659 let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1");
660 assert_eq!(pgno, 1);
661 assert_eq!(commit, 0);
662 assert_eq!(&buf[..], &b[56..4152], "page data mismatch");
663
664 // Second frame: salt altered so it doesn't match header => EOF.
665 let err = r.read_frame(&mut buf).expect_err("expected EOF");
666 assert!(err.is_eof(), "unexpected error: {err}");
667 }
668
669 // ── Port of TestWALReader/FrameChecksumMismatch (wal_reader_test.go:111-143) ─
670 #[test]
671 fn test_wal_reader_frame_checksum_mismatch() {
672 let mut buf = vec![0u8; 4096];
673 let b = read_testdata("frame-checksum-mismatch");
674
675 let mut r = WalReader::new(&b).expect("new reader");
676 assert_eq!(r.page_size(), 4096);
677 assert_eq!(r.offset(), 0);
678
679 // First frame is valid.
680 let (pgno, commit) = r.read_frame(&mut buf).expect("frame 1");
681 assert_eq!(pgno, 1);
682 assert_eq!(commit, 0);
683 assert_eq!(&buf[..], &b[56..4152], "page data mismatch");
684
685 // Second frame: checksum altered => EOF.
686 let err = r.read_frame(&mut buf).expect_err("expected EOF");
687 assert!(err.is_eof(), "unexpected error: {err}");
688 }
689
690 // ── Port of TestWALReader/ZeroLength (wal_reader_test.go:145-150) ──────────
691 #[test]
692 fn test_wal_reader_zero_length() {
693 let err = WalReader::new(&[]).expect_err("expected EOF");
694 assert!(err.is_eof(), "unexpected error: {err}");
695 }
696
697 // ── Port of TestWALReader/PartialHeader (wal_reader_test.go:152-157) ───────
698 #[test]
699 fn test_wal_reader_partial_header() {
700 let err = WalReader::new(&[0u8; 10]).expect_err("expected EOF");
701 assert!(err.is_eof(), "unexpected error: {err}");
702 }
703
704 // ── Port of TestWALReader/BadMagic (wal_reader_test.go:159-164) ────────────
705 #[test]
706 fn test_wal_reader_bad_magic() {
707 // All-zero 32-byte header => magic 0.
708 let err = WalReader::new(&[0u8; 32]).expect_err("expected error");
709 assert_eq!(err.to_string(), "invalid wal header magic: 0");
710 }
711
712 // ── Port of TestWALReader/BadHeaderChecksum (wal_reader_test.go:166-176) ───
713 #[test]
714 fn test_wal_reader_bad_header_checksum() {
715 // Valid big-endian magic, zero checksum fields => header checksum fails.
716 let data: [u8; 32] = [
717 0x37, 0x7f, 0x06, 0x83, 0x00, 0x00, 0x00, 0x00, //
718 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
719 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
720 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
721 ];
722 let err = WalReader::new(&data).expect_err("expected EOF");
723 assert!(err.is_eof(), "unexpected error: {err}");
724 }
725
726 // ── Port of TestWALReader/BadHeaderVersion (wal_reader_test.go:178-188) ────
727 #[test]
728 fn test_wal_reader_bad_header_version() {
729 // Valid magic + version 1 + a header checksum that actually validates
730 // over bytes [0..24] (these checksum bytes are taken verbatim from the
731 // upstream Go test vector).
732 let data: [u8; 32] = [
733 0x37, 0x7f, 0x06, 0x83, 0x00, 0x00, 0x00, 0x01, //
734 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
735 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
736 0x15, 0x7b, 0x20, 0x92, 0xbb, 0xf8, 0x34, 0x1d,
737 ];
738 let err = WalReader::new(&data).expect_err("expected error");
739 assert_eq!(err.to_string(), "unsupported wal version: 1");
740 }
741
742 // ── Port of TestWALReader/ErrBufferSize (wal_reader_test.go:190-204) ───────
743 #[test]
744 fn test_wal_reader_err_buffer_size() {
745 let b = read_testdata("ok");
746 let mut r = WalReader::new(&b).expect("new reader");
747 let mut small = vec![0u8; 512];
748 let err = r
749 .read_frame(&mut small)
750 .expect_err("expected buffer-size error");
751 assert_eq!(
752 err.to_string(),
753 "WALReader.ReadFrame(): buffer size (512) must match page size (4096)"
754 );
755 }
756
757 // ── Port of TestWALReader/ErrPartialFrameHeader (wal_reader_test.go:206-218) ─
758 #[test]
759 fn test_wal_reader_err_partial_frame_header() {
760 let b = read_testdata("ok");
761 // Truncate to 40 bytes: header (32) + 8 bytes of frame header.
762 let mut r = WalReader::new(&b[..40]).expect("new reader");
763 let mut buf = vec![0u8; 4096];
764 let err = r.read_frame(&mut buf).expect_err("expected EOF");
765 assert!(err.is_eof(), "unexpected error: {err}");
766 }
767
768 // ── Port of TestWALReader/ErrFrameHeaderOnly (wal_reader_test.go:220-232) ──
769 #[test]
770 fn test_wal_reader_err_frame_header_only() {
771 let b = read_testdata("ok");
772 // Truncate to 56 bytes: header (32) + full frame header (24), no page.
773 let mut r = WalReader::new(&b[..56]).expect("new reader");
774 let mut buf = vec![0u8; 4096];
775 let err = r.read_frame(&mut buf).expect_err("expected EOF");
776 assert!(err.is_eof(), "unexpected error: {err}");
777 }
778
779 // ── Port of TestWALReader/ErrPartialFrameData (wal_reader_test.go:234-246) ──
780 #[test]
781 fn test_wal_reader_err_partial_frame_data() {
782 let b = read_testdata("ok");
783 // Truncate to 1000 bytes: full frame header but only partial page data.
784 let mut r = WalReader::new(&b[..1000]).expect("new reader");
785 let mut buf = vec![0u8; 4096];
786 let err = r.read_frame(&mut buf).expect_err("expected EOF");
787 assert!(err.is_eof(), "unexpected error: {err}");
788 }
789
790 // ── new_with_offset (port of NewWALReaderWithOffset, wal_reader.go:42-75) ──
791 //
792 // Resuming at a frame boundary must load the running checksum from the
793 // previous frame and continue reading the rest of the WAL identically to a
794 // fresh full read. We cross-check against a from-start read of the same WAL.
795 #[test]
796 fn test_wal_reader_new_with_offset_resumes() {
797 let b = read_testdata("ok");
798 let page_size = 4096i64;
799 let frame_size = WAL_FRAME_HEADER_SIZE as i64 + page_size;
800
801 // Header salts (offsets 16/20) are the segment's expected salts.
802 let salt1 = be_u32(&b[16..]);
803 let salt2 = be_u32(&b[20..]);
804
805 // Resume at the SECOND frame: offset = 32 + 1*frame_size. This requires
806 // re-reading frame 0 to seed the checksum.
807 let offset = WAL_HEADER_SIZE as i64 + frame_size;
808 let mut r = WalReader::new_with_offset(&b, offset, salt1, salt2)
809 .expect("new_with_offset at frame 1");
810
811 // The next frame read should be frame index 1 (the second frame), whose
812 // page/commit match what a full read returns for that frame.
813 let mut buf = vec![0u8; page_size as usize];
814 let (pgno, commit) = r.read_frame(&mut buf).expect("resume frame");
815 assert_eq!(pgno, 2, "second frame pgno");
816 assert_eq!(commit, 2, "second frame commit");
817 assert_eq!(&buf[..], &b[4176..8272], "resumed page data matches");
818 }
819
820 #[test]
821 fn test_wal_reader_new_with_offset_too_small() {
822 let b = read_testdata("ok");
823 let salt1 = be_u32(&b[16..]);
824 let salt2 = be_u32(&b[20..]);
825 // Offset at the header is rejected (need a previous frame to re-read).
826 let err = WalReader::new_with_offset(&b, WAL_HEADER_SIZE as i64, salt1, salt2)
827 .expect_err("expected offset-too-small");
828 assert_eq!(
829 err,
830 WalError::OffsetTooSmall {
831 offset: WAL_HEADER_SIZE as i64,
832 header_size: WAL_HEADER_SIZE as i64
833 }
834 );
835 }
836
837 #[test]
838 fn test_wal_reader_new_with_offset_unaligned() {
839 let b = read_testdata("ok");
840 let salt1 = be_u32(&b[16..]);
841 let salt2 = be_u32(&b[20..]);
842 // An offset off the frame grid is rejected.
843 let err = WalReader::new_with_offset(&b, WAL_HEADER_SIZE as i64 + 7, salt1, salt2)
844 .expect_err("expected unaligned");
845 assert!(
846 matches!(err, WalError::UnalignedOffset { .. }),
847 "unexpected error: {err}"
848 );
849 }
850
851 #[test]
852 fn test_wal_reader_new_with_offset_prev_frame_mismatch() {
853 let b = read_testdata("ok");
854 let frame_size = WAL_FRAME_HEADER_SIZE as i64 + 4096;
855 let offset = WAL_HEADER_SIZE as i64 + frame_size;
856 // Wrong expected salts → the previous frame won't validate → mismatch
857 // (the load-bearing snapshot-fallback signal for DB.sync).
858 let err = WalReader::new_with_offset(&b, offset, 0xdead_beef, 0xfeed_face)
859 .expect_err("expected prev-frame mismatch");
860 assert_eq!(err, WalError::PrevFrameMismatch);
861 }
862
863 // ── Port of TestWALReader_FrameSaltsUntil/OK (wal_reader_test.go:249-278) ──
864 #[test]
865 fn test_wal_reader_frame_salts_until_ok() {
866 let b = read_testdata("frame-salts");
867 let r = WalReader::new(&b).expect("new reader");
868
869 // No frame carries salt (0,0), so the scan runs to EOF and collects all
870 // three distinct salt pairs present in the file.
871 let m = r
872 .frame_salts_until((0x0000_0000, 0x0000_0000))
873 .expect("frame salts");
874 assert_eq!(m.len(), 3, "len(m)");
875 assert!(m.contains(&(0x1b9a_294b, 0x37f9_1916)), "salt 0 not found");
876 assert!(m.contains(&(0x1b9a_294a, 0x031f_195e)), "salt 1 not found");
877 assert!(m.contains(&(0x1b9a_2949, 0x13b3_dd67)), "salt 2 not found");
878 }
879
880 // ── GOLDEN (byte-exact): real SQLite WAL from tests/fixtures/golden ────────
881 //
882 // sample.wal: 16,512 bytes, page size 4096, magic 0x377f0682 (little-endian
883 // checksums), per tests/fixtures/golden/MANIFEST.md. A checksum failure here
884 // means the port is wrong, NOT the fixture (AGENTS.md rule 3).
885 #[test]
886 fn test_golden_sample_wal() {
887 let b = read_golden_wal();
888 assert_eq!(b.len(), 16_512, "fixture size changed unexpectedly");
889
890 let mut r = WalReader::new(&b).expect("new reader over golden WAL");
891
892 // Byte order: magic 0x377f0682 => checksums little-endian.
893 assert!(
894 !r.is_big_endian(),
895 "golden WAL magic 0x377f0682 selects LITTLE-endian checksums"
896 );
897
898 // Page size from the header.
899 assert_eq!(r.page_size(), 4096, "golden WAL page size");
900
901 // Salt values straight from the header bytes (offsets 16/20).
902 assert_eq!(
903 r.salt(),
904 (0x9bf2_9a02, 0x6867_0130),
905 "golden WAL header salts"
906 );
907
908 // Every frame must read cleanly and pass the cumulative SQLite checksum.
909 // read_frame returns EOF the instant a checksum (or salt) check fails, so
910 // a successful read of a frame == that frame's checksum verified.
911 let mut buf = vec![0u8; r.page_size() as usize];
912 let mut frame_count = 0u64;
913 loop {
914 match r.read_frame(&mut buf) {
915 Ok((pgno, _commit)) => {
916 assert!(pgno >= 1, "page numbers are 1-based");
917 frame_count += 1;
918 }
919 Err(e) if e.is_eof() => break,
920 Err(e) => panic!("unexpected non-EOF error reading golden WAL: {e}"),
921 }
922 }
923
924 // A real WAL with data => a nonzero frame count, every frame checksummed.
925 assert!(
926 frame_count > 0,
927 "expected a nonzero frame count in the golden WAL"
928 );
929
930 // Cross-check the geometry: with all frames valid to EOF, the file must
931 // be exactly header + frame_count whole frames (no trailing partial).
932 let frame_size = WAL_FRAME_HEADER_SIZE as i64 + r.page_size() as i64;
933 assert_eq!(
934 WAL_HEADER_SIZE as i64 + frame_count as i64 * frame_size,
935 b.len() as i64,
936 "golden WAL is not an exact header + N*frame layout"
937 );
938 }
939}