Diffinery

homeflare/celldpublic

909 lines · 32.1 KBRaw History
1//! ltx.rs — LTX (Lite Transaction) file reader/writer + CRC64-ISO checksums.
2//!
3//! Ported from [email protected] `ltx.go`, `checksum.go`, `encoder.go`, `decoder.go`
4//! and [email protected] `v3.go`. The authoritative byte layout is written up
5//! in `reference/ltx-format.md` (produced by this task).
6//!
7//! The reader decodes a complete LTX file — header, LZ4-framed page block,
8//! varint page index, trailer — and verifies the CRC64-ISO file checksum and
9//! (for snapshots) the rolling post-apply checksum. The writer round-trips the
10//! same layout; byte-fidelity against the real binary is proven later by the
11//! differential test D1 (PLAN.md §6.3), not here.
12
13use crate::error::{Error, Result};
14use crate::{Checksum, Pos, CHECKSUM_FLAG, TXID};
15use std::io::{Read, Write};
16use std::time::SystemTime;
17
18// ── Constants ([email protected] ltx.go:18-55) ──────────────────────────────────────
19
20/// First 4 bytes of every LTX file.
21pub const MAGIC: &[u8; 4] = b"LTX1";
22/// Current LTX file format version.
23pub const VERSION: i32 = 3;
24pub const HEADER_SIZE: usize = 100;
25pub const PAGE_HEADER_SIZE: usize = 6;
26pub const TRAILER_SIZE: usize = 16;
27pub const CHECKSUM_SIZE: usize = 8;
28
29/// Header flag: checksums are not tracked for this file.
30pub const HEADER_FLAG_NO_CHECKSUM: u32 = 1 << 1;
31pub const HEADER_FLAG_MASK: u32 = HEADER_FLAG_NO_CHECKSUM;
32
33/// SQLite PENDING_BYTE offset; the lock page derives from it.
34pub const PENDING_BYTE: i64 = 0x4000_0000;
35
36fn corrupt(msg: impl Into<String>) -> Error {
37 // Wrap a format error as LTXCorrupted, matching litestream's classification
38 // of malformed LTX content (litestream.go ErrLTXCorrupted).
39 let _ = msg;
40 Error::LTXCorrupted
41}
42
43/// Returns the lock page number for a given page size (ltx.go:494).
44///
45/// `page_size` is expected to be a validated SQLite page size (a power of two in
46/// `[512, 65536]`); for any such value the result is identical to Go's
47/// `LockPgno` (`PENDING_BYTE / page_size + 1`). A `page_size` of `0` — which
48/// only reaches here via an unvalidated/adversarial header — would make the
49/// underlying integer divide panic in both Go and Rust, so we guard it and
50/// return `0` (never a real page number) instead of dividing. All in-crate
51/// callers validate the header first, mirroring Go's `DecodeHeader`-before-
52/// `LockPgno` ordering, so this guard is reached only by a direct external call.
53pub fn lock_pgno(page_size: u32) -> u32 {
54 if page_size == 0 {
55 return 0;
56 }
57 (PENDING_BYTE / page_size as i64) as u32 + 1
58}
59
60// ── CRC64-ISO (checksum.go:177 `crc64.MakeTable(crc64.ISO)`) ──────────────────
61
62/// CRC-64/ISO polynomial (reflected), identical to Go's `crc64.ISO`.
63const CRC64_ISO_POLY: u64 = 0xD800_0000_0000_0000;
64
65const fn crc64_iso_table() -> [u64; 256] {
66 let mut table = [0u64; 256];
67 let mut i = 0usize;
68 while i < 256 {
69 let mut crc = i as u64;
70 let mut j = 0;
71 while j < 8 {
72 if crc & 1 == 1 {
73 crc = (crc >> 1) ^ CRC64_ISO_POLY;
74 } else {
75 crc >>= 1;
76 }
77 j += 1;
78 }
79 table[i] = crc;
80 i += 1;
81 }
82 table
83}
84
85static CRC64_TABLE: [u64; 256] = crc64_iso_table();
86
87/// Streaming CRC64-ISO hasher matching Go's `hash/crc64` digest semantics
88/// (init 0; each update performs the standard reflected invert-process-invert).
89#[derive(Clone, Default)]
90pub struct Crc64 {
91 crc: u64,
92}
93
94impl Crc64 {
95 pub fn new() -> Self {
96 Crc64 { crc: 0 }
97 }
98
99 pub fn update(&mut self, data: &[u8]) {
100 let mut crc = !self.crc;
101 for &b in data {
102 crc = CRC64_TABLE[((crc as u8) ^ b) as usize] ^ (crc >> 8);
103 }
104 self.crc = !crc;
105 }
106
107 pub fn sum64(&self) -> u64 {
108 self.crc
109 }
110}
111
112/// CRC64 checksum of a single page combined with its page number, with the
113/// ChecksumFlag set (checksum.go:106-116). Input is `BE_u32(pgno) ++ data`.
114pub fn checksum_page(pgno: u32, data: &[u8]) -> Checksum {
115 let mut h = Crc64::new();
116 h.update(&pgno.to_be_bytes());
117 h.update(data);
118 CHECKSUM_FLAG | h.sum64()
119}
120
121// ── Header / PageHeader / Trailer ─────────────────────────────────────────────
122
123/// LTX file header (100 bytes). Ported from [email protected] ltx.go:179-326.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
125pub struct Header {
126 pub version: i32,
127 pub flags: u32,
128 pub page_size: u32,
129 pub commit: u32,
130 pub min_txid: TXID,
131 pub max_txid: TXID,
132 pub timestamp: i64,
133 pub pre_apply_checksum: Checksum,
134 pub wal_offset: i64,
135 pub wal_size: i64,
136 pub wal_salt1: u32,
137 pub wal_salt2: u32,
138 pub node_id: u64,
139}
140
141impl Header {
142 /// True if this header begins a complete database snapshot (MinTXID == 1).
143 pub fn is_snapshot(&self) -> bool {
144 self.min_txid == TXID(1)
145 }
146
147 /// True if checksum tracking is disabled for this file.
148 pub fn no_checksum(&self) -> bool {
149 self.flags & HEADER_FLAG_NO_CHECKSUM != 0
150 }
151
152 /// Decodes a header from a 100-byte slice (ltx.go:302-326). All big-endian.
153 pub fn parse(b: &[u8]) -> Result<Header> {
154 if b.len() < HEADER_SIZE {
155 return Err(corrupt("short header"));
156 }
157 if &b[0..4] != MAGIC {
158 return Err(corrupt("bad magic"));
159 }
160 Ok(Header {
161 version: VERSION,
162 flags: u32_be(&b[4..]),
163 page_size: u32_be(&b[8..]),
164 commit: u32_be(&b[12..]),
165 min_txid: TXID(u64_be(&b[16..])),
166 max_txid: TXID(u64_be(&b[24..])),
167 timestamp: u64_be(&b[32..]) as i64,
168 pre_apply_checksum: u64_be(&b[40..]),
169 wal_offset: u64_be(&b[48..]) as i64,
170 wal_size: u64_be(&b[56..]) as i64,
171 wal_salt1: u32_be(&b[64..]),
172 wal_salt2: u32_be(&b[68..]),
173 node_id: u64_be(&b[72..]),
174 })
175 }
176
177 /// Encodes the header to 100 bytes (ltx.go:283-299).
178 pub fn marshal(&self) -> [u8; HEADER_SIZE] {
179 let mut b = [0u8; HEADER_SIZE];
180 b[0..4].copy_from_slice(MAGIC);
181 b[4..8].copy_from_slice(&self.flags.to_be_bytes());
182 b[8..12].copy_from_slice(&self.page_size.to_be_bytes());
183 b[12..16].copy_from_slice(&self.commit.to_be_bytes());
184 b[16..24].copy_from_slice(&self.min_txid.0.to_be_bytes());
185 b[24..32].copy_from_slice(&self.max_txid.0.to_be_bytes());
186 b[32..40].copy_from_slice(&(self.timestamp as u64).to_be_bytes());
187 b[40..48].copy_from_slice(&self.pre_apply_checksum.to_be_bytes());
188 b[48..56].copy_from_slice(&(self.wal_offset as u64).to_be_bytes());
189 b[56..64].copy_from_slice(&(self.wal_size as u64).to_be_bytes());
190 b[64..68].copy_from_slice(&self.wal_salt1.to_be_bytes());
191 b[68..72].copy_from_slice(&self.wal_salt2.to_be_bytes());
192 b[72..80].copy_from_slice(&self.node_id.to_be_bytes());
193 b
194 }
195
196 /// Validates header invariants (ltx.go:208-267).
197 pub fn validate(&self) -> Result<()> {
198 if self.version != VERSION {
199 return Err(corrupt("invalid version"));
200 }
201 if self.flags != (self.flags & HEADER_FLAG_MASK) {
202 return Err(corrupt("invalid flags"));
203 }
204 if !is_valid_page_size(self.page_size) {
205 return Err(corrupt("invalid page size"));
206 }
207 if self.min_txid == TXID(0) {
208 return Err(corrupt("minimum transaction id required"));
209 }
210 if self.max_txid == TXID(0) {
211 return Err(corrupt("maximum transaction id required"));
212 }
213 if self.min_txid > self.max_txid {
214 return Err(corrupt("transaction ids out of order"));
215 }
216 if self.wal_offset < 0 {
217 return Err(corrupt("wal offset cannot be negative"));
218 }
219 if self.wal_size < 0 {
220 return Err(corrupt("wal size cannot be negative"));
221 }
222 if (self.wal_salt1 != 0 || self.wal_salt2 != 0) && self.wal_offset == 0 {
223 return Err(corrupt("wal offset required if salt exists"));
224 }
225 if self.wal_offset == 0 && self.wal_size != 0 {
226 return Err(corrupt("wal offset required if wal size exists"));
227 }
228 if self.is_snapshot() {
229 if self.pre_apply_checksum != 0 {
230 return Err(corrupt("pre-apply checksum must be zero on snapshots"));
231 }
232 } else if self.no_checksum() {
233 if self.pre_apply_checksum != 0 {
234 return Err(corrupt("pre-apply checksum not allowed"));
235 }
236 } else {
237 if self.pre_apply_checksum == 0 {
238 return Err(corrupt("pre-apply checksum required on non-snapshot files"));
239 }
240 if self.pre_apply_checksum & CHECKSUM_FLAG == 0 {
241 return Err(corrupt("invalid pre-apply checksum format"));
242 }
243 }
244 Ok(())
245 }
246}
247
248/// Per-page header (6 bytes). Ported from ltx.go:408-447.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
250pub struct PageHeader {
251 pub pgno: u32,
252 pub flags: u16,
253}
254
255impl PageHeader {
256 pub fn is_zero(&self) -> bool {
257 self.pgno == 0 && self.flags == 0
258 }
259
260 pub fn parse(b: &[u8]) -> Result<PageHeader> {
261 if b.len() < PAGE_HEADER_SIZE {
262 return Err(corrupt("short page header"));
263 }
264 Ok(PageHeader {
265 pgno: u32_be(&b[0..]),
266 flags: u16_be(&b[4..]),
267 })
268 }
269
270 pub fn marshal(&self) -> [u8; PAGE_HEADER_SIZE] {
271 let mut b = [0u8; PAGE_HEADER_SIZE];
272 b[0..4].copy_from_slice(&self.pgno.to_be_bytes());
273 b[4..6].copy_from_slice(&self.flags.to_be_bytes());
274 b
275 }
276
277 pub fn validate(&self) -> Result<()> {
278 if self.pgno == 0 {
279 return Err(corrupt("page number required"));
280 }
281 if self.flags != 0 {
282 return Err(corrupt("no page flags allowed"));
283 }
284 Ok(())
285 }
286}
287
288/// File trailer (16 bytes). Ported from ltx.go:348-393.
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
290pub struct Trailer {
291 pub post_apply_checksum: Checksum,
292 pub file_checksum: Checksum,
293}
294
295impl Trailer {
296 pub fn parse(b: &[u8]) -> Result<Trailer> {
297 if b.len() < TRAILER_SIZE {
298 return Err(corrupt("short trailer"));
299 }
300 Ok(Trailer {
301 post_apply_checksum: u64_be(&b[0..]),
302 file_checksum: u64_be(&b[8..]),
303 })
304 }
305
306 pub fn marshal(&self) -> [u8; TRAILER_SIZE] {
307 let mut b = [0u8; TRAILER_SIZE];
308 b[0..8].copy_from_slice(&self.post_apply_checksum.to_be_bytes());
309 b[8..16].copy_from_slice(&self.file_checksum.to_be_bytes());
310 b
311 }
312}
313
314/// True if `sz` is a power of two in [512, 65536] (ltx.go:399-406).
315pub fn is_valid_page_size(sz: u32) -> bool {
316 let mut i = 512u32;
317 while i <= 65536 {
318 if sz == i {
319 return true;
320 }
321 i *= 2;
322 }
323 false
324}
325
326/// Formats an LTX filename for a transaction range (ltx.go:487-489).
327pub fn format_filename(min_txid: TXID, max_txid: TXID) -> String {
328 format!("{}-{}.ltx", min_txid, max_txid)
329}
330
331/// Parses a `<min>-<max>.ltx` filename (ltx.go:450-459).
332pub fn parse_filename(name: &str) -> Result<(TXID, TXID)> {
333 let stem = name
334 .strip_suffix(".ltx")
335 .ok_or_else(|| corrupt("invalid ltx filename"))?;
336 let (a, b) = stem
337 .split_once('-')
338 .ok_or_else(|| corrupt("invalid ltx filename"))?;
339 if a.len() != 16 || b.len() != 16 {
340 return Err(corrupt("invalid ltx filename"));
341 }
342 let min = u64::from_str_radix(a, 16).map_err(|_| corrupt("invalid ltx filename"))?;
343 let max = u64::from_str_radix(b, 16).map_err(|_| corrupt("invalid ltx filename"))?;
344 Ok((TXID(min), TXID(max)))
345}
346
347// ── FileInfo ──────────────────────────────────────────────────────────────────
348
349/// Metadata about an LTX file on a replica. Ported from [email protected] ltx.go:571-596.
350///
351/// `pre_apply_checksum`/`post_apply_checksum` are populated when known (e.g. by
352/// decoding) and are zero when a file is discovered by a bare directory/bucket
353/// listing. `created_at` is the file's timestamp (mtime / LastModified, or the
354/// LTX header timestamp when `use_metadata` is requested).
355#[derive(Debug, Clone, PartialEq, Eq, Default)]
356pub struct FileInfo {
357 pub level: i32,
358 pub min_txid: TXID,
359 pub max_txid: TXID,
360 pub pre_apply_checksum: Checksum,
361 pub post_apply_checksum: Checksum,
362 pub size: i64,
363 pub created_at: Option<SystemTime>,
364}
365
366impl FileInfo {
367 /// Replication position *after* this file is applied (ltx.go:591-596).
368 pub fn pos(&self) -> Pos {
369 Pos::new(self.max_txid, self.post_apply_checksum)
370 }
371
372 /// Replication position *before* this file is applied (ltx.go:583-588).
373 pub fn pre_apply_pos(&self) -> Pos {
374 Pos::new(
375 TXID(self.min_txid.0.saturating_sub(1)),
376 self.pre_apply_checksum,
377 )
378 }
379}
380
381// ── Decoder ──────────────────────────────────────────────────────────────────
382
383/// The verified result of decoding a complete LTX file.
384#[derive(Debug, Clone)]
385pub struct DecodedFile {
386 pub header: Header,
387 pub trailer: Trailer,
388 /// Number of real pages (excludes the empty terminating page header).
389 pub page_count: usize,
390 /// Page numbers in file (write) order.
391 pub pgnos: Vec<u32>,
392}
393
394/// Decodes and fully verifies an in-memory LTX file: header, LZ4-framed pages,
395/// page index, trailer, the CRC64-ISO file checksum, and — for snapshots — the
396/// rolling post-apply checksum. Returns `Error::ChecksumMismatch` /
397/// `Error::LTXCorrupted` on any inconsistency.
398///
399/// Ported from the read+verify path in decoder.go:68-219.
400pub fn decode_file(bytes: &[u8]) -> Result<DecodedFile> {
401 let len = bytes.len();
402 if len < HEADER_SIZE + PAGE_HEADER_SIZE + 8 + TRAILER_SIZE {
403 return Err(corrupt("file too short"));
404 }
405
406 // `Header::parse` length-checks internally; pass the full slice so the bound
407 // is enforced by `parse` rather than relying on the floor check above.
408 let header = Header::parse(bytes)?;
409 header.validate()?;
410 let page_size = header.page_size as usize;
411
412 let trailer = Trailer::parse(&bytes[len - TRAILER_SIZE..len])?;
413
414 // Page index: the u64 size field sits just before the trailer; the index
415 // elements precede it. (encoder.go:137-173 / decoder.go:309-346.)
416 let size_field_off = len - TRAILER_SIZE - 8;
417 let index_size = u64_be(&bytes[size_field_off..]) as usize;
418 let idx_start = size_field_off
419 .checked_sub(index_size)
420 .ok_or_else(|| corrupt("bad page index size"))?;
421 if idx_start < HEADER_SIZE + PAGE_HEADER_SIZE {
422 return Err(corrupt("bad page index offset"));
423 }
424 let index = parse_page_index(&bytes[idx_start..size_field_off])?;
425
426 // The empty page header terminates the page block, immediately before the
427 // page index.
428 let empty_header_off = idx_start - PAGE_HEADER_SIZE;
429
430 let mut crc = Crc64::new();
431 crc.update(&bytes[0..HEADER_SIZE]); // header
432
433 // Rolling post-apply checksum (only meaningful for tracked snapshots).
434 let track = header.is_snapshot() && !header.no_checksum();
435 let mut rolling: Checksum = CHECKSUM_FLAG;
436 let lock = lock_pgno(header.page_size);
437
438 // Walk the page block sequentially in write order.
439 let mut off = HEADER_SIZE;
440 let mut pgnos = Vec::new();
441 let mut scratch = vec![0u8; page_size];
442 while off < empty_header_off {
443 let ph = PageHeader::parse(&bytes[off..off + PAGE_HEADER_SIZE])?;
444 if ph.is_zero() {
445 return Err(corrupt("unexpected empty page header"));
446 }
447 ph.validate()?;
448 let elem = index
449 .get(&ph.pgno)
450 .ok_or_else(|| corrupt("page missing from index"))?;
451 if elem.offset as usize != off {
452 return Err(corrupt("page index offset mismatch"));
453 }
454 let sz = elem.size as usize;
455 if sz < PAGE_HEADER_SIZE || off + sz > empty_header_off {
456 return Err(corrupt("bad page size in index"));
457 }
458
459 // page header bytes go into the file hash verbatim …
460 crc.update(&bytes[off..off + PAGE_HEADER_SIZE]);
461 // … and the *decompressed* data (the file checksum is over uncompressed
462 // page bytes — decoder.go:177-180).
463 decompress_page(&bytes[off + PAGE_HEADER_SIZE..off + sz], &mut scratch)?;
464 crc.update(&scratch);
465
466 if track && ph.pgno != lock {
467 rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(ph.pgno, &scratch));
468 }
469
470 pgnos.push(ph.pgno);
471 off += sz;
472 }
473 if off != empty_header_off {
474 return Err(corrupt("page block did not end on the index boundary"));
475 }
476
477 // empty page header (must be all zero) + page index + trailer[:8] all feed
478 // the file hash as raw bytes (decoder.go:82-83, 128, 163).
479 let empty = &bytes[empty_header_off..empty_header_off + PAGE_HEADER_SIZE];
480 if !PageHeader::parse(empty)?.is_zero() {
481 return Err(corrupt("missing empty page header terminator"));
482 }
483 crc.update(empty);
484 crc.update(&bytes[idx_start..len - CHECKSUM_SIZE]);
485
486 let file_checksum = CHECKSUM_FLAG | crc.sum64();
487 if file_checksum != trailer.file_checksum {
488 return Err(Error::ChecksumMismatch);
489 }
490
491 if track && rolling != trailer.post_apply_checksum {
492 return Err(Error::ChecksumMismatch);
493 }
494
495 Ok(DecodedFile {
496 header,
497 trailer,
498 page_count: pgnos.len(),
499 pgnos,
500 })
501}
502
503/// Decodes and verifies a complete LTX file, returning each page's
504/// `(pgno, decompressed_data)` in write order.
505///
506/// This reuses [`decode_file`] for full verification (file checksum + page
507/// index) and then re-walks the page block to materialize the page bytes —
508/// needed by `DB.verify`'s `lastPageMatch` check (db.go:1457-1474), which
509/// compares a WAL page against the pages stored in the last LTX file.
510pub fn decode_file_pages(bytes: &[u8]) -> Result<Vec<(u32, Vec<u8>)>> {
511 // Full verification first (also guarantees the index/geometry are sound).
512 decode_file(bytes)?;
513
514 let len = bytes.len();
515 let header = Header::parse(bytes)?;
516 let page_size = header.page_size as usize;
517
518 let size_field_off = len - TRAILER_SIZE - 8;
519 let index_size = u64_be(&bytes[size_field_off..]) as usize;
520 let idx_start = size_field_off
521 .checked_sub(index_size)
522 .ok_or_else(|| corrupt("bad page index size"))?;
523 let index = parse_page_index(&bytes[idx_start..size_field_off])?;
524 let empty_header_off = idx_start - PAGE_HEADER_SIZE;
525
526 let mut out = Vec::new();
527 let mut off = HEADER_SIZE;
528 let mut scratch = vec![0u8; page_size];
529 while off < empty_header_off {
530 let ph = PageHeader::parse(&bytes[off..off + PAGE_HEADER_SIZE])?;
531 let elem = index
532 .get(&ph.pgno)
533 .ok_or_else(|| corrupt("page missing from index"))?;
534 let sz = elem.size as usize;
535 decompress_page(&bytes[off + PAGE_HEADER_SIZE..off + sz], &mut scratch)?;
536 out.push((ph.pgno, scratch.clone()));
537 off += sz;
538 }
539 Ok(out)
540}
541
542/// Reconstructs the full SQLite database image from a **snapshot** LTX file
543/// (every page `1..=commit`, with the lock page zero-filled).
544///
545/// Ported from `Decoder.DecodeDatabaseTo` in [email protected] decoder.go:223-268. Used
546/// by the snapshot conformance test (the CRC64 of this image must equal the live
547/// DB's CRC64). Errors if the file is not a snapshot or a page is missing.
548pub fn decode_database_image(bytes: &[u8]) -> Result<Vec<u8>> {
549 // Verify the whole file FIRST. This mirrors Go's `DecodeDatabaseTo`, which
550 // calls `DecodeHeader` (and thus `Header.Validate`) before it computes
551 // `LockPgno` or touches `Commit` (decoder.go:224-236). Validating up front is
552 // what makes the steps below panic-free on adversarial input: a header with
553 // `page_size == 0` is rejected here, so `lock_pgno` (a `PENDING_BYTE / size`
554 // divide) and the `Header::parse` slice never see a degenerate header.
555 let pages = decode_file_pages(bytes)?;
556
557 // The header is now known-valid (decode_file_pages → decode_file validated
558 // it), so `Header::parse` cannot fail and `lock_pgno` cannot divide by zero.
559 let header = Header::parse(bytes)?;
560 if !header.is_snapshot() {
561 return Err(corrupt(
562 "cannot decode non-snapshot LTX file to SQLite database",
563 ));
564 }
565 let page_size = header.page_size as usize;
566 let lock = lock_pgno(header.page_size);
567
568 // Materialize the pages, keyed by page number.
569 let mut by_pgno: std::collections::HashMap<u32, Vec<u8>> = std::collections::HashMap::new();
570 for (pgno, data) in pages {
571 by_pgno.insert(pgno, data);
572 }
573
574 let mut image = Vec::with_capacity(header.commit as usize * page_size);
575 for pgno in 1..=header.commit {
576 if pgno == lock {
577 image.extend(std::iter::repeat_n(0u8, page_size));
578 continue;
579 }
580 let data = by_pgno
581 .get(&pgno)
582 .ok_or_else(|| corrupt("missing page in snapshot"))?;
583 image.extend_from_slice(data);
584 }
585 Ok(image)
586}
587
588/// Decompresses one LZ4 frame holding exactly one page into `out`.
589fn decompress_page(compressed: &[u8], out: &mut [u8]) -> Result<()> {
590 let mut fd = lz4_flex::frame::FrameDecoder::new(compressed);
591 fd.read_exact(out)
592 .map_err(|_| corrupt("lz4 decompress failed"))?;
593 Ok(())
594}
595
596#[derive(Debug, Clone, Copy)]
597struct PageIndexElem {
598 offset: u64,
599 size: u64,
600}
601
602/// Parses the varint page index (decoder.go:309-346): tuples of
603/// `(pgno, offset, size)` terminated by a `pgno == 0` marker.
604fn parse_page_index(buf: &[u8]) -> Result<std::collections::HashMap<u32, PageIndexElem>> {
605 let mut map = std::collections::HashMap::new();
606 let mut pos = 0usize;
607 loop {
608 let pgno = read_uvarint(buf, &mut pos)?;
609 if pgno == 0 {
610 break;
611 }
612 let offset = read_uvarint(buf, &mut pos)?;
613 let size = read_uvarint(buf, &mut pos)?;
614 map.insert(pgno as u32, PageIndexElem { offset, size });
615 }
616 Ok(map)
617}
618
619// ── Encoder (round-trip; byte-fidelity vs the real binary is D1's job) ────────
620
621/// Encodes a complete LTX file from a header, an ordered set of pages, and the
622/// post-apply checksum. Mirrors encoder.go's layout; LZ4 framing uses lz4_flex.
623pub fn encode_file(
624 header: &Header,
625 pages: &[(u32, Vec<u8>)],
626 post_apply_checksum: Checksum,
627) -> Result<Vec<u8>> {
628 header.validate()?;
629 let page_size = header.page_size as usize;
630
631 let mut out: Vec<u8> = Vec::new();
632 let mut crc = Crc64::new();
633
634 // Header.
635 let hb = header.marshal();
636 out.extend_from_slice(&hb);
637 crc.update(&hb);
638
639 // Pages.
640 let mut index: Vec<(u32, u64, u64)> = Vec::with_capacity(pages.len());
641 for (pgno, data) in pages {
642 if data.len() != page_size {
643 return Err(corrupt("page buffer size mismatch"));
644 }
645 let offset = out.len() as u64;
646 let ph = PageHeader {
647 pgno: *pgno,
648 flags: 0,
649 };
650 ph.validate()?;
651 let phb = ph.marshal();
652 out.extend_from_slice(&phb);
653 crc.update(&phb);
654
655 let compressed = compress_page(data)?;
656 out.extend_from_slice(&compressed);
657 crc.update(data); // hash feeds the *uncompressed* data
658
659 index.push((*pgno, offset, (PAGE_HEADER_SIZE + compressed.len()) as u64));
660 }
661
662 // Empty page header terminator.
663 let empty = [0u8; PAGE_HEADER_SIZE];
664 out.extend_from_slice(&empty);
665 crc.update(&empty);
666
667 // Page index (sorted ascending by pgno).
668 index.sort_by_key(|e| e.0);
669 let idx_region_start = out.len();
670 let mut idx_bytes: Vec<u8> = Vec::new();
671 for (pgno, offset, size) in &index {
672 write_uvarint(&mut idx_bytes, *pgno as u64);
673 write_uvarint(&mut idx_bytes, *offset);
674 write_uvarint(&mut idx_bytes, *size);
675 }
676 write_uvarint(&mut idx_bytes, 0); // end marker
677 out.extend_from_slice(&idx_bytes);
678 crc.update(&idx_bytes);
679
680 let index_size = (out.len() - idx_region_start) as u64;
681 let size_field = index_size.to_be_bytes();
682 out.extend_from_slice(&size_field);
683 crc.update(&size_field);
684
685 // Trailer: post-apply feeds the hash; file checksum is the hash result.
686 crc.update(&post_apply_checksum.to_be_bytes());
687 let file_checksum = CHECKSUM_FLAG | crc.sum64();
688 let trailer = Trailer {
689 post_apply_checksum,
690 file_checksum,
691 };
692 out.extend_from_slice(&trailer.marshal());
693
694 Ok(out)
695}
696
697fn compress_page(data: &[u8]) -> Result<Vec<u8>> {
698 let mut fe = lz4_flex::frame::FrameEncoder::new(Vec::new());
699 fe.write_all(data)
700 .map_err(|_| corrupt("lz4 compress failed"))?;
701 fe.finish().map_err(|_| corrupt("lz4 finish failed"))
702}
703
704// ── small byte / varint helpers ──────────────────────────────────────────────
705
706fn u16_be(b: &[u8]) -> u16 {
707 u16::from_be_bytes([b[0], b[1]])
708}
709fn u32_be(b: &[u8]) -> u32 {
710 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
711}
712fn u64_be(b: &[u8]) -> u64 {
713 u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
714}
715
716/// LEB128 unsigned varint reader, matching Go `binary.Uvarint`.
717fn read_uvarint(buf: &[u8], pos: &mut usize) -> Result<u64> {
718 let mut x: u64 = 0;
719 let mut s: u32 = 0;
720 loop {
721 let b = *buf.get(*pos).ok_or_else(|| corrupt("uvarint eof"))?;
722 *pos += 1;
723 if b < 0x80 {
724 if s >= 64 || (s == 63 && b > 1) {
725 return Err(corrupt("uvarint overflow"));
726 }
727 return Ok(x | ((b as u64) << s));
728 }
729 x |= ((b & 0x7f) as u64) << s;
730 s += 7;
731 if s >= 70 {
732 return Err(corrupt("uvarint too long"));
733 }
734 }
735}
736
737fn write_uvarint(out: &mut Vec<u8>, mut x: u64) {
738 while x >= 0x80 {
739 out.push((x as u8) | 0x80);
740 x >>= 7;
741 }
742 out.push(x as u8);
743}
744
745// ── Tests ─────────────────────────────────────────────────────────────────────
746
747#[cfg(test)]
748mod tests {
749 use super::*;
750
751 const GOLDEN_DIR: &str = concat!(
752 env!("CARGO_MANIFEST_DIR"),
753 "/tests/fixtures/golden/replica/ltx/0"
754 );
755
756 // Byte-exact golden vectors: decode every real-litestream L0 file and verify
757 // its CRC64-ISO checksums. A failure means rustyriver is wrong, never the
758 // fixture (AGENTS.md rule 3).
759 #[test]
760 fn golden_ltx_files_decode_and_verify() {
761 for i in 1u64..=6 {
762 let name = format_filename(TXID(i), TXID(i));
763 let path = format!("{GOLDEN_DIR}/{name}");
764 let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
765
766 let f = decode_file(&bytes).unwrap_or_else(|e| panic!("decode {name} failed: {e}"));
767
768 assert_eq!(f.header.version, VERSION, "{name}: version");
769 assert_eq!(f.header.page_size, 4096, "{name}: page size");
770 assert_eq!(f.header.min_txid, TXID(i), "{name}: min txid");
771 assert_eq!(f.header.max_txid, TXID(i), "{name}: max txid");
772 assert!(f.page_count >= 1, "{name}: has pages");
773 // ChecksumFlag must be set on the stored file checksum.
774 assert_ne!(
775 f.trailer.file_checksum & CHECKSUM_FLAG,
776 0,
777 "{name}: file checksum flag"
778 );
779 // A successful decode means the CRC64-ISO *file checksum* matched
780 // byte-exact against what real litestream wrote — the strong proof.
781 // Real litestream L0 WAL-segment files set HeaderFlagNoChecksum (the
782 // rolling DB checksum is tracked at the DB layer, not here), so the
783 // trailer's post-apply checksum is untracked. decode_file verifies
784 // the post-apply checksum only when it IS tracked.
785 if i == 1 {
786 assert!(f.header.is_snapshot(), "txid 1 is a snapshot");
787 }
788 assert!(
789 f.header.no_checksum(),
790 "{name}: real L0 files set HeaderFlagNoChecksum"
791 );
792 }
793 }
794
795 // Corrupting any byte must be caught by the file checksum (not silently ok).
796 #[test]
797 fn golden_corruption_is_detected() {
798 let name = format_filename(TXID(1), TXID(1));
799 let path = format!("{GOLDEN_DIR}/{name}");
800 let mut bytes = std::fs::read(&path).unwrap();
801 // Flip a bit in the page block (after the header).
802 let mid = HEADER_SIZE + (bytes.len() - HEADER_SIZE) / 2;
803 bytes[mid] ^= 0x01;
804 match decode_file(&bytes) {
805 Err(Error::ChecksumMismatch) | Err(Error::LTXCorrupted) => {}
806 other => panic!("expected corruption to be detected, got {other:?}"),
807 }
808 }
809
810 #[test]
811 fn header_marshal_roundtrip() {
812 let h = Header {
813 version: VERSION,
814 flags: 0,
815 page_size: 4096,
816 commit: 3,
817 min_txid: TXID(1),
818 max_txid: TXID(1),
819 timestamp: 1_700_000_000_000,
820 pre_apply_checksum: 0,
821 wal_offset: 0,
822 wal_size: 0,
823 wal_salt1: 0,
824 wal_salt2: 0,
825 node_id: 0,
826 };
827 let b = h.marshal();
828 assert_eq!(b.len(), HEADER_SIZE);
829 assert_eq!(&b[0..4], MAGIC);
830 assert_eq!(Header::parse(&b).unwrap(), h);
831 }
832
833 #[test]
834 fn page_header_and_trailer_roundtrip() {
835 let ph = PageHeader { pgno: 7, flags: 0 };
836 assert_eq!(PageHeader::parse(&ph.marshal()).unwrap(), ph);
837 assert!(PageHeader::default().is_zero());
838
839 let t = Trailer {
840 post_apply_checksum: CHECKSUM_FLAG | 0x1234,
841 file_checksum: CHECKSUM_FLAG | 0xABCD,
842 };
843 assert_eq!(Trailer::parse(&t.marshal()).unwrap(), t);
844 }
845
846 #[test]
847 fn filename_roundtrip() {
848 let s = format_filename(TXID(1), TXID(6));
849 assert_eq!(s, "0000000000000001-0000000000000006.ltx");
850 assert_eq!(parse_filename(&s).unwrap(), (TXID(1), TXID(6)));
851 assert!(parse_filename("nope.txt").is_err());
852 assert!(parse_filename("0000000000000001.ltx").is_err());
853 }
854
855 #[test]
856 fn checksum_page_sets_flag_and_combines_pgno() {
857 let data = vec![0xABu8; 4096];
858 let c1 = checksum_page(1, &data);
859 let c2 = checksum_page(2, &data);
860 assert_ne!(c1, c2, "page number must affect the checksum");
861 assert_ne!(c1 & CHECKSUM_FLAG, 0, "flag must be set");
862 }
863
864 // Our writer + reader agree (round-trip). Byte-fidelity against the real
865 // binary is verified later by differential D1, not here.
866 #[test]
867 fn encode_decode_roundtrip_snapshot() {
868 let page_size = 4096usize;
869 let pages: Vec<(u32, Vec<u8>)> =
870 (1u32..=3).map(|p| (p, vec![p as u8; page_size])).collect();
871
872 // Compute the post-apply checksum the way a snapshot does.
873 let mut rolling = CHECKSUM_FLAG;
874 for (p, d) in &pages {
875 rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(*p, d));
876 }
877
878 let header = Header {
879 version: VERSION,
880 flags: 0,
881 page_size: page_size as u32,
882 commit: 3,
883 min_txid: TXID(1),
884 max_txid: TXID(1),
885 timestamp: 1_700_000_000_000,
886 pre_apply_checksum: 0,
887 wal_offset: 0,
888 wal_size: 0,
889 wal_salt1: 0,
890 wal_salt2: 0,
891 node_id: 0,
892 };
893
894 let encoded = encode_file(&header, &pages, rolling).expect("encode");
895 let decoded = decode_file(&encoded).expect("decode");
896 assert_eq!(decoded.header, header);
897 assert_eq!(decoded.page_count, 3);
898 assert_eq!(decoded.pgnos, vec![1, 2, 3]);
899 assert_eq!(decoded.trailer.post_apply_checksum, rolling);
900 }
901
902 #[test]
903 fn crc64_iso_matches_known_vector() {
904 // CRC-64/GO-ISO check value of "123456789".
905 let mut h = Crc64::new();
906 h.update(b"123456789");
907 assert_eq!(h.sum64(), 0xb909_56c7_75a4_1001);
908 }
909}