| 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 | |
| 12 | use crate::error::{Error, Result}; |
| 13 | use crate::{Checksum, Pos, CHECKSUM_FLAG, TXID}; |
| 14 | use std::time::SystemTime; |
| 15 | |
| 16 | // ── Constants ([email protected] ltx.go:18-55) ────────────────────────────────────── |
| 17 | |
| 18 | /// First 4 bytes of every LTX file. |
| 19 | pub const MAGIC: &[u8; 4] = b"LTX1"; |
| 20 | /// Current LTX file format version. |
| 21 | pub const VERSION: i32 = 3; |
| 22 | pub const HEADER_SIZE: usize = 100; |
| 23 | pub const PAGE_HEADER_SIZE: usize = 6; |
| 24 | pub const TRAILER_SIZE: usize = 16; |
| 25 | pub const CHECKSUM_SIZE: usize = 8; |
| 26 | |
| 27 | /// Header flag: checksums are not tracked for this file. |
| 28 | pub const HEADER_FLAG_NO_CHECKSUM: u32 = 1 << 1; |
| 29 | pub 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. |
| 34 | pub const PAGE_HEADER_FLAG_SIZE: u16 = 1 << 0; |
| 35 | pub const PAGE_HEADER_FLAG_MASK: u16 = PAGE_HEADER_FLAG_SIZE; |
| 36 | |
| 37 | /// SQLite PENDING_BYTE offset; the lock page derives from it. |
| 38 | pub const PENDING_BYTE: i64 = 0x4000_0000; |
| 39 | |
| 40 | fn 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. |
| 57 | pub 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`. |
| 67 | const CRC64_ISO_POLY: u64 = 0xD800_0000_0000_0000; |
| 68 | |
| 69 | const 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 | |
| 89 | static 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)] |
| 94 | pub struct Crc64 { |
| 95 | crc: u64, |
| 96 | } |
| 97 | |
| 98 | impl 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`. |
| 118 | pub 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)] |
| 129 | pub 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 | |
| 145 | impl 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)] |
| 254 | pub struct PageHeader { |
| 255 | pub pgno: u32, |
| 256 | pub flags: u16, |
| 257 | } |
| 258 | |
| 259 | impl 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)] |
| 294 | pub struct Trailer { |
| 295 | pub post_apply_checksum: Checksum, |
| 296 | pub file_checksum: Checksum, |
| 297 | } |
| 298 | |
| 299 | impl 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). |
| 335 | pub 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). |
| 347 | pub 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). |
| 352 | pub 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)] |
| 376 | pub 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 | |
| 386 | impl 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)] |
| 405 | pub struct DecodedFile { |
| 406 | pub header: Header, |
| 407 | pub trailer: Trailer, |
| 408 | /// Page numbers in file (write) order. |
| 409 | pub pgnos: Vec<u32>, |
| 410 | } |
| 411 | |
| 412 | type 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. |
| 420 | pub 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. |
| 425 | pub(crate) fn decode_file_with_pages(bytes: &[u8]) -> Result<(DecodedFile, DecodedPages)> { |
| 426 | decode_file_inner(bytes, true) |
| 427 | } |
| 428 | |
| 429 | fn 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. |
| 460 | pub 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. |
| 470 | pub 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. |
| 510 | pub 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. |
| 520 | pub 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 | |
| 528 | fn 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 | |
| 555 | fn u16_be(b: &[u8]) -> u16 { |
| 556 | u16::from_be_bytes([b[0], b[1]]) |
| 557 | } |
| 558 | fn u32_be(b: &[u8]) -> u32 { |
| 559 | u32::from_be_bytes([b[0], b[1], b[2], b[3]]) |
| 560 | } |
| 561 | fn 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 | mod tests { |
| 569 | use super::*; |
| 570 | |
| 571 | const GOLDEN_DIR: &str = concat!( |
| 572 | env!("CARGO_MANIFEST_DIR"), |
| 573 | "/tests/fixtures/golden/replica/ltx/0" |
| 574 | ); |
| 575 | |
| 576 | // Byte-exact golden vectors: decode every real-litestream L0 file and verify |
| 577 | // its CRC64-ISO checksums. A failure means rustyriver is wrong, never the |
| 578 | // fixture (AGENTS.md rule 3). |
| 579 | #[test] |
| 580 | fn golden_ltx_files_decode_and_verify() { |
| 581 | for i in 1u64..=6 { |
| 582 | let name = format_filename(TXID(i), TXID(i)); |
| 583 | let path = format!("{GOLDEN_DIR}/{name}"); |
| 584 | let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}")); |
| 585 | |
| 586 | let f = decode_file(&bytes).unwrap_or_else(|e| panic!("decode {name} failed: {e}")); |
| 587 | |
| 588 | assert_eq!(f.header.version, VERSION, "{name}: version"); |
| 589 | assert_eq!(f.header.page_size, 4096, "{name}: page size"); |
| 590 | assert_eq!(f.header.min_txid, TXID(i), "{name}: min txid"); |
| 591 | assert_eq!(f.header.max_txid, TXID(i), "{name}: max txid"); |
| 592 | assert!(!f.pgnos.is_empty(), "{name}: has pages"); |
| 593 | // ChecksumFlag must be set on the stored file checksum. |
| 594 | assert_ne!( |
| 595 | f.trailer.file_checksum & CHECKSUM_FLAG, |
| 596 | 0, |
| 597 | "{name}: file checksum flag" |
| 598 | ); |
| 599 | // A successful decode means the CRC64-ISO *file checksum* matched |
| 600 | // byte-exact against what real litestream wrote — the strong proof. |
| 601 | // Real litestream L0 WAL-segment files set HeaderFlagNoChecksum (the |
| 602 | // rolling DB checksum is tracked at the DB layer, not here), so the |
| 603 | // trailer's post-apply checksum is untracked. decode_file verifies |
| 604 | // the post-apply checksum only when it IS tracked. |
| 605 | if i == 1 { |
| 606 | assert!(f.header.is_snapshot(), "txid 1 is a snapshot"); |
| 607 | } |
| 608 | assert!( |
| 609 | f.header.no_checksum(), |
| 610 | "{name}: real L0 files set HeaderFlagNoChecksum" |
| 611 | ); |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | // Corrupting any byte must be caught by the file checksum (not silently ok). |
| 616 | #[test] |
| 617 | fn golden_corruption_is_detected() { |
| 618 | let name = format_filename(TXID(1), TXID(1)); |
| 619 | let path = format!("{GOLDEN_DIR}/{name}"); |
| 620 | let mut bytes = std::fs::read(&path).unwrap(); |
| 621 | // Flip a bit in the page block (after the header). |
| 622 | let mid = HEADER_SIZE + (bytes.len() - HEADER_SIZE) / 2; |
| 623 | bytes[mid] ^= 0x01; |
| 624 | match decode_file(&bytes) { |
| 625 | Err(Error::ChecksumMismatch) | Err(Error::LTXCorrupted) => {} |
| 626 | other => panic!("expected corruption to be detected, got {other:?}"), |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | #[test] |
| 631 | fn header_marshal_roundtrip() { |
| 632 | let h = Header { |
| 633 | version: VERSION, |
| 634 | flags: 0, |
| 635 | page_size: 4096, |
| 636 | commit: 3, |
| 637 | min_txid: TXID(1), |
| 638 | max_txid: TXID(1), |
| 639 | timestamp: 1_700_000_000_000, |
| 640 | pre_apply_checksum: 0, |
| 641 | wal_offset: 0, |
| 642 | wal_size: 0, |
| 643 | wal_salt1: 0, |
| 644 | wal_salt2: 0, |
| 645 | node_id: 0, |
| 646 | }; |
| 647 | let b = h.marshal(); |
| 648 | assert_eq!(b.len(), HEADER_SIZE); |
| 649 | assert_eq!(&b[0..4], MAGIC); |
| 650 | assert_eq!(Header::parse(&b).unwrap(), h); |
| 651 | } |
| 652 | |
| 653 | #[test] |
| 654 | fn page_header_and_trailer_roundtrip() { |
| 655 | let ph = PageHeader { pgno: 7, flags: 0 }; |
| 656 | assert_eq!(PageHeader::parse(&ph.marshal()).unwrap(), ph); |
| 657 | assert!(PageHeader { |
| 658 | pgno: 7, |
| 659 | flags: PAGE_HEADER_FLAG_SIZE, |
| 660 | } |
| 661 | .validate() |
| 662 | .is_ok()); |
| 663 | assert!(PageHeader { |
| 664 | pgno: 7, |
| 665 | flags: PAGE_HEADER_FLAG_SIZE << 1, |
| 666 | } |
| 667 | .validate() |
| 668 | .is_err()); |
| 669 | assert!(PageHeader::default().is_zero()); |
| 670 | |
| 671 | let t = Trailer { |
| 672 | post_apply_checksum: CHECKSUM_FLAG | 0x1234, |
| 673 | file_checksum: CHECKSUM_FLAG | 0xABCD, |
| 674 | }; |
| 675 | assert_eq!(Trailer::parse(&t.marshal()).unwrap(), t); |
| 676 | } |
| 677 | |
| 678 | #[test] |
| 679 | fn filename_roundtrip() { |
| 680 | let s = format_filename(TXID(1), TXID(6)); |
| 681 | assert_eq!(s, "0000000000000001-0000000000000006.ltx"); |
| 682 | assert_eq!(parse_filename(&s).unwrap(), (TXID(1), TXID(6))); |
| 683 | assert!(parse_filename("nope.txt").is_err()); |
| 684 | assert!(parse_filename("0000000000000001.ltx").is_err()); |
| 685 | } |
| 686 | |
| 687 | #[test] |
| 688 | fn checksum_page_sets_flag_and_combines_pgno() { |
| 689 | let data = vec![0xABu8; 4096]; |
| 690 | let c1 = checksum_page(1, &data); |
| 691 | let c2 = checksum_page(2, &data); |
| 692 | assert_ne!(c1, c2, "page number must affect the checksum"); |
| 693 | assert_ne!(c1 & CHECKSUM_FLAG, 0, "flag must be set"); |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn encode_decode_roundtrip_snapshot() { |
| 698 | let page_size = 4096usize; |
| 699 | let pages: Vec<(u32, Vec<u8>)> = |
| 700 | (1u32..=3).map(|p| (p, vec![p as u8; page_size])).collect(); |
| 701 | |
| 702 | // Compute the post-apply checksum the way a snapshot does. |
| 703 | let mut rolling = CHECKSUM_FLAG; |
| 704 | for (p, d) in &pages { |
| 705 | rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(*p, d)); |
| 706 | } |
| 707 | |
| 708 | let header = Header { |
| 709 | version: VERSION, |
| 710 | flags: 0, |
| 711 | page_size: page_size as u32, |
| 712 | commit: 3, |
| 713 | min_txid: TXID(1), |
| 714 | max_txid: TXID(1), |
| 715 | timestamp: 1_700_000_000_000, |
| 716 | pre_apply_checksum: 0, |
| 717 | wal_offset: 0, |
| 718 | wal_size: 0, |
| 719 | wal_salt1: 0, |
| 720 | wal_salt2: 0, |
| 721 | node_id: 0, |
| 722 | }; |
| 723 | |
| 724 | for encoded in [ |
| 725 | encode_file(&header, &pages, rolling).expect("legacy encode"), |
| 726 | encode_file_v0_5_2(&header, &pages, rolling).expect("v0.5.2 encode"), |
| 727 | ] { |
| 728 | let decoded = decode_file(&encoded).expect("decode"); |
| 729 | assert_eq!(decoded.header, header); |
| 730 | assert_eq!(decoded.pgnos, vec![1, 2, 3]); |
| 731 | assert_eq!(decoded.trailer.post_apply_checksum, rolling); |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | #[test] |
| 736 | fn encoder_matches_superfly_ltx_v0_5_2_bytes() { |
| 737 | let page1 = vec![0x81; 1024]; |
| 738 | let page2 = b"abcd".repeat(256); |
| 739 | let pages = vec![(1, page1), (2, page2)]; |
| 740 | let mut rolling = CHECKSUM_FLAG; |
| 741 | for (pgno, data) in &pages { |
| 742 | rolling = CHECKSUM_FLAG | (rolling ^ checksum_page(*pgno, data)); |
| 743 | } |
| 744 | |
| 745 | let header = Header { |
| 746 | version: VERSION, |
| 747 | page_size: 1024, |
| 748 | commit: 2, |
| 749 | min_txid: TXID(1), |
| 750 | max_txid: TXID(1), |
| 751 | timestamp: 1000, |
| 752 | ..Header::default() |
| 753 | }; |
| 754 | let encoded = encode_file_v0_5_2(&header, &pages, rolling).expect("encode"); |
| 755 | |
| 756 | // Generated with github.com/superfly/[email protected] FileSpec.WriteTo. |
| 757 | let expected = hex::decode(concat!( |
| 758 | "4c54583100000000000004000000000200000000000000010000000000000001", |
| 759 | "00000000000003e8000000000000000000000000000000000000000000000000", |
| 760 | "0000000000000000000000000000000000000000000000000000000000000000", |
| 761 | "000000000000000100010000001a1f810100ffffffdc000200000200b0818181", |
| 762 | "81818181818181810000000200010000001b4f616263640400ffffffdc00ec03", |
| 763 | "c061626364616263646162636400000000000001642402880125000000000000", |
| 764 | "000008a09639bc718d9c58dc2f8726a386540e", |
| 765 | )) |
| 766 | .expect("fixture hex"); |
| 767 | assert_eq!(encoded, expected); |
| 768 | decode_file(&encoded).expect("the exact fixture must also verify"); |
| 769 | } |
| 770 | |
| 771 | #[test] |
| 772 | fn legacy_encoder_uses_the_upstream_frame_contract() { |
| 773 | let pages = vec![(1, vec![0x81; 1024])]; |
| 774 | let rolling = CHECKSUM_FLAG | checksum_page(1, &pages[0].1); |
| 775 | let header = Header { |
| 776 | version: VERSION, |
| 777 | page_size: 1024, |
| 778 | commit: 1, |
| 779 | min_txid: TXID(1), |
| 780 | max_txid: TXID(1), |
| 781 | ..Header::default() |
| 782 | }; |
| 783 | |
| 784 | let encoded = encode_file(&header, &pages, rolling).expect("legacy encode"); |
| 785 | let frame = &encoded[HEADER_SIZE + PAGE_HEADER_SIZE..]; |
| 786 | |
| 787 | assert_eq!(&frame[..4], &0x184d_2204_u32.to_le_bytes()); |
| 788 | assert_ne!(frame[4] & 0x20, 0, "blocks must be independent"); |
| 789 | assert_ne!(frame[4] & 0x04, 0, "the content checksum must be present"); |
| 790 | assert_eq!(frame[5] >> 4, 4, "the maximum block size must be 64 KiB"); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn crc64_iso_matches_known_vector() { |
| 795 | // CRC-64/GO-ISO check value of "123456789". |
| 796 | let mut h = Crc64::new(); |
| 797 | h.update(b"123456789"); |
| 798 | assert_eq!(h.sum64(), 0xb909_56c7_75a4_1001); |
| 799 | } |
| 800 | } |