Diffinery

homeflare/celldpublic

802 lines · 28.3 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 with either v0.5.2 LZ4 blocks or the
8//! older LZ4 frames. It verifies the CRC64-ISO file checksum and the rolling
9//! snapshot checksum. The v0.5.2 writer emits exact upstream bytes, while the
10//! default writer preserves the legacy layout during the staged rollout.
11
12use crate::error::{Error, Result};
13use crate::{Checksum, Pos, CHECKSUM_FLAG, TXID};
14use std::time::SystemTime;
15
16// ── Constants ([email protected] ltx.go:18-55) ──────────────────────────────────────
17
18/// First 4 bytes of every LTX file.
19pub const MAGIC: &[u8; 4] = b"LTX1";
20/// Current LTX file format version.
21pub const VERSION: i32 = 3;
22pub const HEADER_SIZE: usize = 100;
23pub const PAGE_HEADER_SIZE: usize = 6;
24pub const TRAILER_SIZE: usize = 16;
25pub const CHECKSUM_SIZE: usize = 8;
26
27/// Header flag: checksums are not tracked for this file.
28pub const HEADER_FLAG_NO_CHECKSUM: u32 = 1 << 1;
29pub const HEADER_FLAG_MASK: u32 = HEADER_FLAG_NO_CHECKSUM;
30
31/// A four-byte compressed-size field follows the page header, and the page
32/// uses raw LZ4 block compression. Files written before ltx v0.5.2 omit this
33/// flag and contain one LZ4 frame per page.
34pub const PAGE_HEADER_FLAG_SIZE: u16 = 1 << 0;
35pub const PAGE_HEADER_FLAG_MASK: u16 = PAGE_HEADER_FLAG_SIZE;
36
37/// SQLite PENDING_BYTE offset; the lock page derives from it.
38pub const PENDING_BYTE: i64 = 0x4000_0000;
39
40fn corrupt(msg: impl Into<String>) -> Error {
41 // Wrap a format error as LTXCorrupted, matching litestream's classification
42 // of malformed LTX content (litestream.go ErrLTXCorrupted).
43 let _ = msg;
44 Error::LTXCorrupted
45}
46
47/// Returns the lock page number for a given page size (ltx.go:494).
48///
49/// `page_size` is expected to be a validated SQLite page size (a power of two in
50/// `[512, 65536]`); for any such value the result is identical to Go's
51/// `LockPgno` (`PENDING_BYTE / page_size + 1`). A `page_size` of `0` — which
52/// only reaches here via an unvalidated/adversarial header — would make the
53/// underlying integer divide panic in both Go and Rust, so we guard it and
54/// return `0` (never a real page number) instead of dividing. All in-crate
55/// callers validate the header first, mirroring Go's `DecodeHeader`-before-
56/// `LockPgno` ordering, so this guard is reached only by a direct external call.
57pub fn lock_pgno(page_size: u32) -> u32 {
58 if page_size == 0 {
59 return 0;
60 }
61 (PENDING_BYTE / page_size as i64) as u32 + 1
62}
63
64// ── CRC64-ISO (checksum.go:177 `crc64.MakeTable(crc64.ISO)`) ──────────────────
65
66/// CRC-64/ISO polynomial (reflected), identical to Go's `crc64.ISO`.
67const CRC64_ISO_POLY: u64 = 0xD800_0000_0000_0000;
68
69const fn crc64_iso_table() -> [u64; 256] {
70 let mut table = [0u64; 256];
71 let mut i = 0usize;
72 while i < 256 {
73 let mut crc = i as u64;
74 let mut j = 0;
75 while j < 8 {
76 if crc & 1 == 1 {
77 crc = (crc >> 1) ^ CRC64_ISO_POLY;
78 } else {
79 crc >>= 1;
80 }
81 j += 1;
82 }
83 table[i] = crc;
84 i += 1;
85 }
86 table
87}
88
89static CRC64_TABLE: [u64; 256] = crc64_iso_table();
90
91/// Streaming CRC64-ISO hasher matching Go's `hash/crc64` digest semantics
92/// (init 0; each update performs the standard reflected invert-process-invert).
93#[derive(Clone, Default)]
94pub struct Crc64 {
95 crc: u64,
96}
97
98impl Crc64 {
99 pub fn new() -> Self {
100 Crc64 { crc: 0 }
101 }
102
103 pub fn update(&mut self, data: &[u8]) {
104 let mut crc = !self.crc;
105 for &b in data {
106 crc = CRC64_TABLE[((crc as u8) ^ b) as usize] ^ (crc >> 8);
107 }
108 self.crc = !crc;
109 }
110
111 pub fn sum64(&self) -> u64 {
112 self.crc
113 }
114}
115
116/// CRC64 checksum of a single page combined with its page number, with the
117/// ChecksumFlag set (checksum.go:106-116). Input is `BE_u32(pgno) ++ data`.
118pub fn checksum_page(pgno: u32, data: &[u8]) -> Checksum {
119 let mut h = Crc64::new();
120 h.update(&pgno.to_be_bytes());
121 h.update(data);
122 CHECKSUM_FLAG | h.sum64()
123}
124
125// ── Header / PageHeader / Trailer ─────────────────────────────────────────────
126
127/// LTX file header (100 bytes). Ported from [email protected] ltx.go:179-326.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub struct Header {
130 pub version: i32,
131 pub flags: u32,
132 pub page_size: u32,
133 pub commit: u32,
134 pub min_txid: TXID,
135 pub max_txid: TXID,
136 pub timestamp: i64,
137 pub pre_apply_checksum: Checksum,
138 pub wal_offset: i64,
139 pub wal_size: i64,
140 pub wal_salt1: u32,
141 pub wal_salt2: u32,
142 pub node_id: u64,
143}
144
145impl Header {
146 /// True if this header begins a complete database snapshot (MinTXID == 1).
147 pub fn is_snapshot(&self) -> bool {
148 self.min_txid == TXID(1)
149 }
150
151 /// True if checksum tracking is disabled for this file.
152 pub fn no_checksum(&self) -> bool {
153 self.flags & HEADER_FLAG_NO_CHECKSUM != 0
154 }
155
156 /// Decodes a header from a 100-byte slice (ltx.go:302-326). All big-endian.
157 pub fn parse(b: &[u8]) -> Result<Header> {
158 if b.len() < HEADER_SIZE {
159 return Err(corrupt("short header"));
160 }
161 if &b[0..4] != MAGIC {
162 return Err(corrupt("bad magic"));
163 }
164 Ok(Header {
165 version: VERSION,
166 flags: u32_be(&b[4..]),
167 page_size: u32_be(&b[8..]),
168 commit: u32_be(&b[12..]),
169 min_txid: TXID(u64_be(&b[16..])),
170 max_txid: TXID(u64_be(&b[24..])),
171 timestamp: u64_be(&b[32..]) as i64,
172 pre_apply_checksum: u64_be(&b[40..]),
173 wal_offset: u64_be(&b[48..]) as i64,
174 wal_size: u64_be(&b[56..]) as i64,
175 wal_salt1: u32_be(&b[64..]),
176 wal_salt2: u32_be(&b[68..]),
177 node_id: u64_be(&b[72..]),
178 })
179 }
180
181 /// Encodes the header to 100 bytes (ltx.go:283-299).
182 pub fn marshal(&self) -> [u8; HEADER_SIZE] {
183 let mut b = [0u8; HEADER_SIZE];
184 b[0..4].copy_from_slice(MAGIC);
185 b[4..8].copy_from_slice(&self.flags.to_be_bytes());
186 b[8..12].copy_from_slice(&self.page_size.to_be_bytes());
187 b[12..16].copy_from_slice(&self.commit.to_be_bytes());
188 b[16..24].copy_from_slice(&self.min_txid.0.to_be_bytes());
189 b[24..32].copy_from_slice(&self.max_txid.0.to_be_bytes());
190 b[32..40].copy_from_slice(&(self.timestamp as u64).to_be_bytes());
191 b[40..48].copy_from_slice(&self.pre_apply_checksum.to_be_bytes());
192 b[48..56].copy_from_slice(&(self.wal_offset as u64).to_be_bytes());
193 b[56..64].copy_from_slice(&(self.wal_size as u64).to_be_bytes());
194 b[64..68].copy_from_slice(&self.wal_salt1.to_be_bytes());
195 b[68..72].copy_from_slice(&self.wal_salt2.to_be_bytes());
196 b[72..80].copy_from_slice(&self.node_id.to_be_bytes());
197 b
198 }
199
200 /// Validates header invariants (ltx.go:208-267).
201 pub fn validate(&self) -> Result<()> {
202 if self.version != VERSION {
203 return Err(corrupt("invalid version"));
204 }
205 if self.flags != (self.flags & HEADER_FLAG_MASK) {
206 return Err(corrupt("invalid flags"));
207 }
208 if !is_valid_page_size(self.page_size) {
209 return Err(corrupt("invalid page size"));
210 }
211 if self.min_txid == TXID(0) {
212 return Err(corrupt("minimum transaction id required"));
213 }
214 if self.max_txid == TXID(0) {
215 return Err(corrupt("maximum transaction id required"));
216 }
217 if self.min_txid > self.max_txid {
218 return Err(corrupt("transaction ids out of order"));
219 }
220 if self.wal_offset < 0 {
221 return Err(corrupt("wal offset cannot be negative"));
222 }
223 if self.wal_size < 0 {
224 return Err(corrupt("wal size cannot be negative"));
225 }
226 if (self.wal_salt1 != 0 || self.wal_salt2 != 0) && self.wal_offset == 0 {
227 return Err(corrupt("wal offset required if salt exists"));
228 }
229 if self.wal_offset == 0 && self.wal_size != 0 {
230 return Err(corrupt("wal offset required if wal size exists"));
231 }
232 if self.is_snapshot() {
233 if self.pre_apply_checksum != 0 {
234 return Err(corrupt("pre-apply checksum must be zero on snapshots"));
235 }
236 } else if self.no_checksum() {
237 if self.pre_apply_checksum != 0 {
238 return Err(corrupt("pre-apply checksum not allowed"));
239 }
240 } else {
241 if self.pre_apply_checksum == 0 {
242 return Err(corrupt("pre-apply checksum required on non-snapshot files"));
243 }
244 if self.pre_apply_checksum & CHECKSUM_FLAG == 0 {
245 return Err(corrupt("invalid pre-apply checksum format"));
246 }
247 }
248 Ok(())
249 }
250}
251
252/// Per-page header (6 bytes). Ported from ltx.go:408-447.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
254pub struct PageHeader {
255 pub pgno: u32,
256 pub flags: u16,
257}
258
259impl PageHeader {
260 pub fn is_zero(&self) -> bool {
261 self.pgno == 0 && self.flags == 0
262 }
263
264 pub fn parse(b: &[u8]) -> Result<PageHeader> {
265 if b.len() < PAGE_HEADER_SIZE {
266 return Err(corrupt("short page header"));
267 }
268 Ok(PageHeader {
269 pgno: u32_be(&b[0..]),
270 flags: u16_be(&b[4..]),
271 })
272 }
273
274 pub fn marshal(&self) -> [u8; PAGE_HEADER_SIZE] {
275 let mut b = [0u8; PAGE_HEADER_SIZE];
276 b[0..4].copy_from_slice(&self.pgno.to_be_bytes());
277 b[4..6].copy_from_slice(&self.flags.to_be_bytes());
278 b
279 }
280
281 pub fn validate(&self) -> Result<()> {
282 if self.pgno == 0 {
283 return Err(corrupt("page number required"));
284 }
285 if self.flags != (self.flags & PAGE_HEADER_FLAG_MASK) {
286 return Err(corrupt("invalid page header flags"));
287 }
288 Ok(())
289 }
290}
291
292/// File trailer (16 bytes). Ported from ltx.go:348-393.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
294pub struct Trailer {
295 pub post_apply_checksum: Checksum,
296 pub file_checksum: Checksum,
297}
298
299impl Trailer {
300 /// Validates the checksum fields against the header checksum mode.
301 pub fn validate(&self, header: Header) -> Result<()> {
302 if header.no_checksum() {
303 if self.post_apply_checksum != 0 {
304 return Err(corrupt("post-apply checksum not allowed"));
305 }
306 } else if self.post_apply_checksum == 0 || self.post_apply_checksum & CHECKSUM_FLAG == 0 {
307 return Err(corrupt("invalid post-apply checksum"));
308 }
309
310 if self.file_checksum == 0 || self.file_checksum & CHECKSUM_FLAG == 0 {
311 return Err(corrupt("invalid file checksum"));
312 }
313 Ok(())
314 }
315
316 pub fn parse(b: &[u8]) -> Result<Trailer> {
317 if b.len() < TRAILER_SIZE {
318 return Err(corrupt("short trailer"));
319 }
320 Ok(Trailer {
321 post_apply_checksum: u64_be(&b[0..]),
322 file_checksum: u64_be(&b[8..]),
323 })
324 }
325
326 pub fn marshal(&self) -> [u8; TRAILER_SIZE] {
327 let mut b = [0u8; TRAILER_SIZE];
328 b[0..8].copy_from_slice(&self.post_apply_checksum.to_be_bytes());
329 b[8..16].copy_from_slice(&self.file_checksum.to_be_bytes());
330 b
331 }
332}
333
334/// True if `sz` is a power of two in [512, 65536] (ltx.go:399-406).
335pub fn is_valid_page_size(sz: u32) -> bool {
336 let mut i = 512u32;
337 while i <= 65536 {
338 if sz == i {
339 return true;
340 }
341 i *= 2;
342 }
343 false
344}
345
346/// Formats an LTX filename for a transaction range (ltx.go:487-489).
347pub fn format_filename(min_txid: TXID, max_txid: TXID) -> String {
348 format!("{}-{}.ltx", min_txid, max_txid)
349}
350
351/// Parses a `<min>-<max>.ltx` filename (ltx.go:450-459).
352pub fn parse_filename(name: &str) -> Result<(TXID, TXID)> {
353 let stem = name
354 .strip_suffix(".ltx")
355 .ok_or_else(|| corrupt("invalid ltx filename"))?;
356 let (a, b) = stem
357 .split_once('-')
358 .ok_or_else(|| corrupt("invalid ltx filename"))?;
359 if a.len() != 16 || b.len() != 16 {
360 return Err(corrupt("invalid ltx filename"));
361 }
362 let min = u64::from_str_radix(a, 16).map_err(|_| corrupt("invalid ltx filename"))?;
363 let max = u64::from_str_radix(b, 16).map_err(|_| corrupt("invalid ltx filename"))?;
364 Ok((TXID(min), TXID(max)))
365}
366
367// ── FileInfo ──────────────────────────────────────────────────────────────────
368
369/// Metadata about an LTX file on a replica. Ported from [email protected] ltx.go:571-596.
370///
371/// `pre_apply_checksum`/`post_apply_checksum` are populated when known (e.g. by
372/// decoding) and are zero when a file is discovered by a bare directory/bucket
373/// listing. Listings use the file mtime or object-store LastModified time, and
374/// write results use the LTX header timestamp.
375#[derive(Debug, Clone, PartialEq, Eq, Default)]
376pub struct FileInfo {
377 pub level: i32,
378 pub min_txid: TXID,
379 pub max_txid: TXID,
380 pub pre_apply_checksum: Checksum,
381 pub post_apply_checksum: Checksum,
382 pub size: i64,
383 pub created_at: Option<SystemTime>,
384}
385
386impl FileInfo {
387 /// Replication position *after* this file is applied (ltx.go:591-596).
388 pub fn pos(&self) -> Pos {
389 Pos::new(self.max_txid, self.post_apply_checksum)
390 }
391
392 /// Replication position *before* this file is applied (ltx.go:583-588).
393 pub fn pre_apply_pos(&self) -> Pos {
394 Pos::new(
395 TXID(self.min_txid.0.saturating_sub(1)),
396 self.pre_apply_checksum,
397 )
398 }
399}
400
401// ── Decoder ──────────────────────────────────────────────────────────────────
402
403/// The verified result of decoding a complete LTX file.
404#[derive(Debug, Clone)]
405pub struct DecodedFile {
406 pub header: Header,
407 pub trailer: Trailer,
408 /// Page numbers in file (write) order.
409 pub pgnos: Vec<u32>,
410}
411
412type DecodedPages = Vec<(u32, Vec<u8>)>;
413
414/// Decodes and fully verifies an in-memory LTX file: header, LZ4-framed pages,
415/// page index, trailer, the CRC64-ISO file checksum, and — for snapshots — the
416/// rolling post-apply checksum. Returns `Error::ChecksumMismatch` /
417/// `Error::LTXCorrupted` on any inconsistency.
418///
419/// Ported from the read+verify path in decoder.go:68-219.
420pub fn decode_file(bytes: &[u8]) -> Result<DecodedFile> {
421 decode_file_inner(bytes, false).map(|(file, _)| file)
422}
423
424/// Decodes a complete LTX file and retains each decompressed page.
425pub(crate) fn decode_file_with_pages(bytes: &[u8]) -> Result<(DecodedFile, DecodedPages)> {
426 decode_file_inner(bytes, true)
427}
428
429fn decode_file_inner(bytes: &[u8], retain_pages: bool) -> Result<(DecodedFile, DecodedPages)> {
430 let mut decoder = crate::codec::Decoder::new(std::io::Cursor::new(bytes));
431 decoder.decode_header()?;
432 let header = decoder.header;
433 let mut page_numbers = Vec::new();
434 let mut pages = Vec::new();
435 let mut data = vec![0; header.page_size as usize];
436
437 while let Some(page) = decoder.decode_page(&mut data)? {
438 page_numbers.push(page.pgno);
439 if retain_pages {
440 pages.push((page.pgno, data.clone()));
441 }
442 }
443 decoder.close()?;
444
445 Ok((
446 DecodedFile {
447 header,
448 trailer: decoder.trailer,
449 pgnos: page_numbers,
450 },
451 pages,
452 ))
453}
454
455/// Decodes and verifies a complete LTX file, returning each page's
456/// `(pgno, decompressed_data)` in write order.
457///
458/// The decoder retains the pages from its verification pass, so it does not
459/// decompress the file a second time.
460pub fn decode_file_pages(bytes: &[u8]) -> Result<Vec<(u32, Vec<u8>)>> {
461 decode_file_with_pages(bytes).map(|(_, pages)| pages)
462}
463
464/// Reconstructs the full SQLite database image from a **snapshot** LTX file
465/// (every page `1..=commit`, with the lock page zero-filled).
466///
467/// Ported from `Decoder.DecodeDatabaseTo` in [email protected] decoder.go:223-268. Used
468/// by the snapshot conformance test (the CRC64 of this image must equal the live
469/// DB's CRC64). Errors if the file is not a snapshot or a page is missing.
470pub fn decode_database_image(bytes: &[u8]) -> Result<Vec<u8>> {
471 // Verify the whole file before `lock_pgno` or `commit` is used. This rejects
472 // a zero page size and keeps the reconstruction panic-free on bad input.
473 let (decoded, pages) = decode_file_with_pages(bytes)?;
474 let header = decoded.header;
475 if !header.is_snapshot() {
476 return Err(corrupt(
477 "cannot decode non-snapshot LTX file to SQLite database",
478 ));
479 }
480 let page_size = header.page_size as usize;
481 let lock = lock_pgno(header.page_size);
482
483 // Materialize the pages, keyed by page number.
484 let mut by_pgno: std::collections::HashMap<u32, Vec<u8>> = std::collections::HashMap::new();
485 for (pgno, data) in pages {
486 by_pgno.insert(pgno, data);
487 }
488
489 let mut image = Vec::with_capacity(header.commit as usize * page_size);
490 for pgno in 1..=header.commit {
491 if pgno == lock {
492 image.extend(std::iter::repeat_n(0u8, page_size));
493 continue;
494 }
495 let data = by_pgno
496 .get(&pgno)
497 .ok_or_else(|| corrupt("missing page in snapshot"))?;
498 image.extend_from_slice(data);
499 }
500 Ok(image)
501}
502
503// ── Encoder (round-trip; byte-fidelity vs the real binary is D1's job) ────────
504
505/// Encodes a complete LTX file with the legacy LZ4 frame representation.
506///
507/// This function preserves the current celld write format during the staged
508/// v0.5.2 reader rollout. [`decode_file`] accepts this representation and the
509/// v0.5.2 block representation.
510pub fn encode_file(
511 header: &Header,
512 pages: &[(u32, Vec<u8>)],
513 post_apply_checksum: Checksum,
514) -> Result<Vec<u8>> {
515 encode_file_with_mode(header, pages, post_apply_checksum, false)
516}
517
518/// Encodes a complete LTX file with the byte-exact v0.5.2 block
519/// representation.
520pub fn encode_file_v0_5_2(
521 header: &Header,
522 pages: &[(u32, Vec<u8>)],
523 post_apply_checksum: Checksum,
524) -> Result<Vec<u8>> {
525 encode_file_with_mode(header, pages, post_apply_checksum, true)
526}
527
528fn encode_file_with_mode(
529 header: &Header,
530 pages: &[(u32, Vec<u8>)],
531 post_apply_checksum: Checksum,
532 use_v0_5_2: bool,
533) -> Result<Vec<u8>> {
534 let mut encoder = if use_v0_5_2 {
535 crate::codec::Encoder::new_block(Vec::new())
536 } else {
537 crate::codec::Encoder::new_legacy(Vec::new())
538 };
539 encoder.encode_header(*header)?;
540 for (page_number, data) in pages {
541 encoder.encode_page(
542 PageHeader {
543 pgno: *page_number,
544 flags: 0,
545 },
546 data,
547 )?;
548 }
549 encoder.close(post_apply_checksum)?;
550 Ok(encoder.writer)
551}
552
553// ── small byte / varint helpers ──────────────────────────────────────────────
554
555fn u16_be(b: &[u8]) -> u16 {
556 u16::from_be_bytes([b[0], b[1]])
557}
558fn u32_be(b: &[u8]) -> u32 {
559 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
560}
561fn u64_be(b: &[u8]) -> u64 {
562 u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
563}
564
565// ── Tests ─────────────────────────────────────────────────────────────────────
566
567#[cfg(test)]
568// Unit tests inspect materialized file-format fixtures outside production.
569#[allow(clippy::disallowed_methods)]
570mod tests {
571 use super::*;
572
573 const GOLDEN_DIR: &str = concat!(
574 env!("CARGO_MANIFEST_DIR"),
575 "/tests/fixtures/golden/replica/ltx/0"
576 );
577
578 // Byte-exact golden vectors: decode every real-Litestream L0 file and verify
579 // its CRC64-ISO checksums. A failure means the implementation is wrong, not
580 // the fixture.
581 #[test]
582 fn golden_ltx_files_decode_and_verify() {
583 for i in 1u64..=6 {
584 let name = format_filename(TXID(i), TXID(i));
585 let path = format!("{GOLDEN_DIR}/{name}");
586 let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
587
588 let f = decode_file(&bytes).unwrap_or_else(|e| panic!("decode {name} failed: {e}"));
589
590 assert_eq!(f.header.version, VERSION, "{name}: version");
591 assert_eq!(f.header.page_size, 4096, "{name}: page size");
592 assert_eq!(f.header.min_txid, TXID(i), "{name}: min txid");
593 assert_eq!(f.header.max_txid, TXID(i), "{name}: max txid");
594 assert!(!f.pgnos.is_empty(), "{name}: has pages");
595 // ChecksumFlag must be set on the stored file checksum.
596 assert_ne!(
597 f.trailer.file_checksum & CHECKSUM_FLAG,
598 0,
599 "{name}: file checksum flag"
600 );
601 // A successful decode means the CRC64-ISO *file checksum* matched
602 // byte-exact against what real litestream wrote — the strong proof.
603 // Real litestream L0 WAL-segment files set HeaderFlagNoChecksum (the
604 // rolling DB checksum is tracked at the DB layer, not here), so the
605 // trailer's post-apply checksum is untracked. decode_file verifies
606 // the post-apply checksum only when it IS tracked.
607 if i == 1 {
608 assert!(f.header.is_snapshot(), "txid 1 is a snapshot");
609 }
610 assert!(
611 f.header.no_checksum(),
612 "{name}: real L0 files set HeaderFlagNoChecksum"
613 );
614 }
615 }
616
617 // Corrupting any byte must be caught by the file checksum (not silently ok).
618 #[test]
619 fn golden_corruption_is_detected() {
620 let name = format_filename(TXID(1), TXID(1));
621 let path = format!("{GOLDEN_DIR}/{name}");
622 let mut bytes = std::fs::read(&path).unwrap();
623 // Flip a bit in the page block (after the header).
624 let mid = HEADER_SIZE + (bytes.len() - HEADER_SIZE) / 2;
625 bytes[mid] ^= 0x01;
626 match decode_file(&bytes) {
627 Err(Error::ChecksumMismatch) | Err(Error::LTXCorrupted) => {}
628 other => panic!("expected corruption to be detected, got {other:?}"),
629 }
630 }
631
632 #[test]
633 fn header_marshal_roundtrip() {
634 let h = Header {
635 version: VERSION,
636 flags: 0,
637 page_size: 4096,
638 commit: 3,
639 min_txid: TXID(1),
640 max_txid: TXID(1),
641 timestamp: 1_700_000_000_000,
642 pre_apply_checksum: 0,
643 wal_offset: 0,
644 wal_size: 0,
645 wal_salt1: 0,
646 wal_salt2: 0,
647 node_id: 0,
648 };
649 let b = h.marshal();
650 assert_eq!(b.len(), HEADER_SIZE);
651 assert_eq!(&b[0..4], MAGIC);
652 assert_eq!(Header::parse(&b).unwrap(), h);
653 }
654
655 #[test]
656 fn page_header_and_trailer_roundtrip() {
657 let ph = PageHeader { pgno: 7, flags: 0 };
658 assert_eq!(PageHeader::parse(&ph.marshal()).unwrap(), ph);
659 assert!(PageHeader {
660 pgno: 7,
661 flags: PAGE_HEADER_FLAG_SIZE,
662 }
663 .validate()
664 .is_ok());
665 assert!(PageHeader {
666 pgno: 7,
667 flags: PAGE_HEADER_FLAG_SIZE << 1,
668 }
669 .validate()
670 .is_err());
671 assert!(PageHeader::default().is_zero());
672
673 let t = Trailer {
674 post_apply_checksum: CHECKSUM_FLAG | 0x1234,
675 file_checksum: CHECKSUM_FLAG | 0xABCD,
676 };
677 assert_eq!(Trailer::parse(&t.marshal()).unwrap(), t);
678 }
679
680 #[test]
681 fn filename_roundtrip() {
682 let s = format_filename(TXID(1), TXID(6));
683 assert_eq!(s, "0000000000000001-0000000000000006.ltx");
684 assert_eq!(parse_filename(&s).unwrap(), (TXID(1), TXID(6)));
685 assert!(parse_filename("nope.txt").is_err());
686 assert!(parse_filename("0000000000000001.ltx").is_err());
687 }
688
689 #[test]
690 fn checksum_page_sets_flag_and_combines_pgno() {
691 let data = vec![0xABu8; 4096];
692 let c1 = checksum_page(1, &data);
693 let c2 = checksum_page(2, &data);
694 assert_ne!(c1, c2, "page number must affect the checksum");
695 assert_ne!(c1 & CHECKSUM_FLAG, 0, "flag must be set");
696 }
697
698 #[test]
699 fn encode_decode_roundtrip_snapshot() {
700 let page_size = 4096usize;
701 let pages: Vec<(u32, Vec<u8>)> =
702 (1u32..=3).map(|p| (p, vec![p as u8; page_size])).collect();
703
704 // Compute the post-apply checksum the way a snapshot does.
705 let mut rolling = CHECKSUM_FLAG;
706 for (p, d) in &pages {
707 rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(*p, d));
708 }
709
710 let header = Header {
711 version: VERSION,
712 flags: 0,
713 page_size: page_size as u32,
714 commit: 3,
715 min_txid: TXID(1),
716 max_txid: TXID(1),
717 timestamp: 1_700_000_000_000,
718 pre_apply_checksum: 0,
719 wal_offset: 0,
720 wal_size: 0,
721 wal_salt1: 0,
722 wal_salt2: 0,
723 node_id: 0,
724 };
725
726 for encoded in [
727 encode_file(&header, &pages, rolling).expect("legacy encode"),
728 encode_file_v0_5_2(&header, &pages, rolling).expect("v0.5.2 encode"),
729 ] {
730 let decoded = decode_file(&encoded).expect("decode");
731 assert_eq!(decoded.header, header);
732 assert_eq!(decoded.pgnos, vec![1, 2, 3]);
733 assert_eq!(decoded.trailer.post_apply_checksum, rolling);
734 }
735 }
736
737 #[test]
738 fn encoder_matches_superfly_ltx_v0_5_2_bytes() {
739 let page1 = vec![0x81; 1024];
740 let page2 = b"abcd".repeat(256);
741 let pages = vec![(1, page1), (2, page2)];
742 let mut rolling = CHECKSUM_FLAG;
743 for (pgno, data) in &pages {
744 rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(*pgno, data));
745 }
746
747 let header = Header {
748 version: VERSION,
749 page_size: 1024,
750 commit: 2,
751 min_txid: TXID(1),
752 max_txid: TXID(1),
753 timestamp: 1000,
754 ..Header::default()
755 };
756 let encoded = encode_file_v0_5_2(&header, &pages, rolling).expect("encode");
757
758 // Generated with github.com/superfly/[email protected] FileSpec.WriteTo.
759 let expected = hex::decode(concat!(
760 "4c54583100000000000004000000000200000000000000010000000000000001",
761 "00000000000003e8000000000000000000000000000000000000000000000000",
762 "0000000000000000000000000000000000000000000000000000000000000000",
763 "000000000000000100010000001a1f810100ffffffdc000200000200b0818181",
764 "81818181818181810000000200010000001b4f616263640400ffffffdc00ec03",
765 "c061626364616263646162636400000000000001642402880125000000000000",
766 "000008a09639bc718d9c58dc2f8726a386540e",
767 ))
768 .expect("fixture hex");
769 assert_eq!(encoded, expected);
770 decode_file(&encoded).expect("the exact fixture must also verify");
771 }
772
773 #[test]
774 fn legacy_encoder_uses_the_upstream_frame_contract() {
775 let pages = vec![(1, vec![0x81; 1024])];
776 let rolling = CHECKSUM_FLAG | checksum_page(1, &pages[0].1);
777 let header = Header {
778 version: VERSION,
779 page_size: 1024,
780 commit: 1,
781 min_txid: TXID(1),
782 max_txid: TXID(1),
783 ..Header::default()
784 };
785
786 let encoded = encode_file(&header, &pages, rolling).expect("legacy encode");
787 let frame = &encoded[HEADER_SIZE + PAGE_HEADER_SIZE..];
788
789 assert_eq!(&frame[..4], &0x184d_2204_u32.to_le_bytes());
790 assert_ne!(frame[4] & 0x20, 0, "blocks must be independent");
791 assert_ne!(frame[4] & 0x04, 0, "the content checksum must be present");
792 assert_eq!(frame[5] >> 4, 4, "the maximum block size must be 64 KiB");
793 }
794
795 #[test]
796 fn crc64_iso_matches_known_vector() {
797 // CRC-64/GO-ISO check value of "123456789".
798 let mut h = Crc64::new();
799 h.update(b"123456789");
800 assert_eq!(h.sum64(), 0xb909_56c7_75a4_1001);
801 }
802}