Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/litestream_helpers.rs
525 lines · 18.4 KBRaw History
1//! Port of litestream_test.go helper tests.
2//!
3//! Ported from [email protected] litestream_test.go:18-163
4
5use celld_ltx::{
6 ltx_dir, ltx_file_path, ltx_level_dir, new_ltx_error, parse_pos, parse_txid, Error, Pos, TXID,
7};
8
9// ── helpers ───────────────────────────────────────────────────────────────────
10
11fn decode_hex(s: &str) -> Vec<u8> {
12 assert!(s.len().is_multiple_of(2), "odd hex length");
13 (0..s.len())
14 .step_by(2)
15 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid hex"))
16 .collect()
17}
18
19// ── test vectors ──────────────────────────────────────────────────────────────
20//
21// Taken from litestream_test.go:20-46.
22//
23// OnePass total: 4128 bytes = WAL_HEADER (24) + FRAME_HEADER (8) + frame_data() (4096)
24//
25// WAL header and frame header are short enough to inline as hex constants.
26// The 4096-byte frame is reconstructed from its sparse non-zero bytes.
27
28const WAL_HEADER_HEX: &str = "377f0682002de218000010000000000052382eac857b1a4e";
29
30const FRAME_HEADER_HEX: &str = "0000000200000002";
31
32/// Reconstructs the exact 4096-byte SQLite page from litestream_test.go:42.
33///
34/// The page is mostly zeros; all 52 non-zero bytes are listed here.
35/// We use sparse patches instead of a 8192-character hex literal to keep
36/// the source readable while staying byte-identical to upstream.
37fn frame_data() -> Vec<u8> {
38 let mut b = vec![0u8; 4096];
39 // Non-zero bytes extracted verbatim from the litestream_test.go backtick hex.
40 let patches: &[(usize, u8)] = &[
41 (0, 0x0d),
42 (4, 0x08),
43 (5, 0x0f),
44 (6, 0xe0),
45 (8, 0x0f),
46 (9, 0xfc),
47 (10, 0x0f),
48 (11, 0xf8),
49 (12, 0x0f),
50 (13, 0xf4),
51 (14, 0x0f),
52 (15, 0xf0),
53 (16, 0x0f),
54 (17, 0xec),
55 (18, 0x0f),
56 (19, 0xe8),
57 (20, 0x0f),
58 (21, 0xe4),
59 (22, 0x0f),
60 (23, 0xe0),
61 (4064, 0x02),
62 (4065, 0x08),
63 (4066, 0x02),
64 (4067, 0x09),
65 (4068, 0x02),
66 (4069, 0x07),
67 (4070, 0x02),
68 (4071, 0x09),
69 (4072, 0x02),
70 (4073, 0x06),
71 (4074, 0x02),
72 (4075, 0x09),
73 (4076, 0x02),
74 (4077, 0x05),
75 (4078, 0x02),
76 (4079, 0x09),
77 (4080, 0x02),
78 (4081, 0x04),
79 (4082, 0x02),
80 (4083, 0x09),
81 (4084, 0x02),
82 (4085, 0x03),
83 (4086, 0x02),
84 (4087, 0x09),
85 (4088, 0x02),
86 (4089, 0x02),
87 (4090, 0x02),
88 (4091, 0x09),
89 (4092, 0x02),
90 (4093, 0x01),
91 (4094, 0x02),
92 (4095, 0x09),
93 ];
94 for &(off, val) in patches {
95 b[off] = val;
96 }
97 b
98}
99
100// ── TestChecksum ──────────────────────────────────────────────────────────────
101// Ported from litestream_test.go:18-47
102
103#[test]
104fn test_checksum_one_pass() {
105 // Ported from TestChecksum/OnePass — litestream_test.go:20-30
106 // Matches: hex.DecodeString("377f0682...0209") = 4128 bytes
107 let mut input = decode_hex(WAL_HEADER_HEX);
108 input.extend(decode_hex(FRAME_HEADER_HEX));
109 input.extend(frame_data());
110 assert_eq!(input.len(), 4128);
111 let (s0, s1) = celld_ltx::wal_checksum(false, 0, 0, &input);
112 assert_eq!([s0, s1], [0xdc2f3e84u32, 0x540488d3u32]);
113}
114
115#[test]
116fn test_checksum_incremental() {
117 // Ported from TestChecksum/Incremental — litestream_test.go:33-46
118 // Step 1: WAL header (24 bytes)
119 let (s0, s1) = celld_ltx::wal_checksum(false, 0, 0, &decode_hex(WAL_HEADER_HEX));
120 assert_eq!([s0, s1], [0x81153b65u32, 0x87178e8fu32]);
121
122 // Step 2: frame header (8 bytes)
123 let (s0a, s1a) = celld_ltx::wal_checksum(false, s0, s1, &decode_hex(FRAME_HEADER_HEX));
124
125 // Step 3: frame data (4096 bytes)
126 let fd = frame_data();
127 assert_eq!(fd.len(), 4096);
128 let (s0b, s1b) = celld_ltx::wal_checksum(false, s0a, s1a, &fd);
129
130 assert_eq!([s0b, s1b], [0xdc2f3e84u32, 0x540488d3u32]);
131}
132
133// ── TestLTXDir / TestLTXLevelDir ──────────────────────────────────────────────
134// Ported from litestream_test.go:48-57
135
136#[test]
137fn test_ltx_dir() {
138 assert_eq!(ltx_dir("foo"), "foo/ltx");
139}
140
141#[test]
142fn test_ltx_level_dir() {
143 assert_eq!(ltx_level_dir("foo", 0), "foo/ltx/0");
144}
145
146// ── REVIEWER (T4): path.Join normalization divergence ─────────────────────────
147//
148// Upstream `LTXDir`/`LTXLevelDir`/`LTXFilePath` ([email protected]
149// litestream.go:184-197) build their paths with Go's `path.Join`, which CLEANS
150// the result: it collapses repeated separators, resolves "." / "..", and strips
151// trailing slashes. The Rust port (lib.rs `ltx_dir` etc.) instead uses
152// `format!("{}/ltx", root)`, naive string concatenation that performs no
153// cleaning. The single ported happy-path test only exercises root="foo", so the
154// divergence is silently uncovered.
155//
156// The expected values below were produced by running the real Go helpers
157// (path.Join) — they are the source-of-truth oracle, NOT rustyriver output:
158//
159// LTXDir("foo/") = "foo/ltx" (Rust currently: "foo//ltx")
160// LTXDir("foo//bar") = "foo/bar/ltx" (Rust currently: "foo//bar/ltx")
161// LTXDir("foo/..") = "ltx" (Rust currently: "foo/../ltx")
162// LTXLevelDir("foo/",0) = "foo/ltx/0" (Rust currently: "foo//ltx/0")
163//
164// Why this matters: these helpers compute LTX object-store keys. On S3-style
165// stores "foo//ltx/0/..." and "foo/ltx/0/..." are DIFFERENT keys, so a root
166// carrying a trailing slash (a common prefix form) makes rustyriver read/write a
167// different key than the real binary, which breaks the differential oracle.
168// A faithful port must replicate path.Join's cleaning.
169#[test]
170fn test_ltx_dir_normalizes_like_path_join() {
171 // Trailing slash on the root: path.Join collapses the doubled separator.
172 assert_eq!(
173 ltx_dir("foo/"),
174 "foo/ltx",
175 "LTXDir must clean trailing slash like Go path.Join (litestream.go:185)"
176 );
177 // Doubled internal separator.
178 assert_eq!(
179 ltx_dir("foo//bar"),
180 "foo/bar/ltx",
181 "LTXDir must collapse repeated separators like Go path.Join"
182 );
183 // Level dir inherits the same cleaning.
184 assert_eq!(
185 ltx_level_dir("foo/", 0),
186 "foo/ltx/0",
187 "LTXLevelDir must clean like Go path.Join (litestream.go:190-191)"
188 );
189}
190
191// ── REVIEWER (T1 review): path.Clean ".." backtrack divergence ────────────────
192//
193// The sibling test above only exercises trailing/doubled-slash collapsing, which
194// the current `path_clean` (src/lib.rs) handles. It does NOT exercise a `..`
195// element that backtracks over a *surviving* prefix element — and that path is
196// BROKEN: the backtrack loop pops the element body but leaves the preceding '/'
197// in the buffer (Go's `lazybuf` cursor logically excludes it), so the next
198// element is appended after a doubled separator.
199//
200// Demonstration (Rust currently, confirmed by running the code):
201// path_clean("a/b/../c") = "a//c" (Go path.Clean: "a/c")
202// observed via the public helper:
203// ltx_dir("a/b/../c") = "a//c/ltx" (must be "a/c/ltx")
204//
205// Expected values come from the real Go `path.Join` upstream oracle, run with
206// go1.25 against `path.Join(root, "ltx")`, never from the Rust implementation:
207// path.Join("a/b/../c","ltx") = "a/c/ltx"
208// path.Join("x/y/../z","ltx") = "x/z/ltx"
209// path.Join("a/b/c/../d","ltx") = "a/b/d/ltx"
210// path.Join("aa/bb/../cc","ltx")= "aa/cc/ltx"
211//
212// Why this matters: these helpers compute LTX object-store keys (litestream.go
213// 184-197). Any `root` whose cleaned form contains an interior `..` over a
214// surviving prefix (e.g. a configured prefix like "bucket/db/../ltxroot") yields
215// a doubled-slash S3 key ("bucket//ltxroot/...") — a DIFFERENT object than the
216// real binary writes or reads, silently breaking the differential oracle. A
217// faithful port must match Go's `path.Clean` exactly.
218#[test]
219fn test_ltx_dir_cleans_dotdot_over_surviving_prefix() {
220 // Interior ".." that backtracks over one element, leaving a prefix.
221 assert_eq!(
222 ltx_dir("a/b/../c"),
223 "a/c/ltx",
224 "path.Clean must collapse 'a/b/../c' to 'a/c' (no doubled separator)"
225 );
226 assert_eq!(
227 ltx_dir("x/y/../z"),
228 "x/z/ltx",
229 "path.Clean must collapse 'x/y/../z' to 'x/z'"
230 );
231 // Backtrack with two surviving prefix elements.
232 assert_eq!(
233 ltx_dir("a/b/c/../d"),
234 "a/b/d/ltx",
235 "path.Clean must collapse 'a/b/c/../d' to 'a/b/d'"
236 );
237 // Multi-char element names (rules out any single-byte coincidence).
238 assert_eq!(
239 ltx_level_dir("aa/bb/../cc", 0),
240 "aa/cc/ltx/0",
241 "path.Clean must collapse 'aa/bb/../cc' to 'aa/cc'"
242 );
243}
244
245// ── LTXFilePath ───────────────────────────────────────────────────────────────
246// litestream_test.go:60-65 declares a function named `LTXFilePath` (no Test
247// prefix), so Go's test runner never executes it; it also uses "-" as the
248// expected value — a placeholder stub. We port it as a proper Rust test with
249// the correct expected value derived from [email protected] ltx.go:487 FormatFilename.
250// TXID(100) = 0x64 → "0000000000000064"
251// TXID(200) = 0xc8 → "00000000000000c8"
252
253#[test]
254fn test_ltx_file_path() {
255 assert_eq!(
256 ltx_file_path("foo", 0, TXID(100), TXID(200)),
257 "foo/ltx/0/0000000000000064-00000000000000c8.ltx"
258 );
259}
260
261// ── TXID formatting / parsing ─────────────────────────────────────────────────
262
263#[test]
264fn test_txid_display() {
265 assert_eq!(TXID(1).to_string(), "0000000000000001");
266 assert_eq!(TXID(0).to_string(), "0000000000000000");
267 assert_eq!(TXID(u64::MAX).to_string(), "ffffffffffffffff");
268 assert_eq!(TXID(0x64).to_string(), "0000000000000064");
269}
270
271#[test]
272fn test_txid_roundtrip() {
273 for v in [0u64, 1, 100, 200, 0xdead_beef_cafe_babe, u64::MAX] {
274 let s = TXID(v).to_string();
275 assert_eq!(s.len(), 16, "must be 16 chars: {s:?}");
276 let parsed = parse_txid(&s).expect("parse must succeed");
277 assert_eq!(parsed, TXID(v));
278 }
279}
280
281#[test]
282fn test_parse_txid_wrong_length() {
283 assert!(parse_txid("000000000000001").is_err()); // 15 chars
284 assert!(parse_txid("00000000000000001").is_err()); // 17 chars
285 assert!(parse_txid("").is_err());
286}
287
288#[test]
289fn test_parse_txid_invalid_chars() {
290 assert!(parse_txid("000000000000001g").is_err());
291}
292
293// ── REVIEWER (T4): leading-sign divergence vs Go strconv.ParseUint ─────────────
294//
295// Upstream `ParseTXID` ([email protected] ltx.go:130-138) and `ParseChecksum`
296// (checksum.go:135-144) both delegate to Go's `strconv.ParseUint(s, 16, 64)`.
297// Per the Go stdlib contract, ParseUint **does not permit a sign prefix**:
298// strconv.ParseUint("+000000000000abc", 16, 64) -> error.
299//
300// The Rust port (lib.rs `parse_txid` / `parse_pos`) uses
301// `u64::from_str_radix`, which **accepts a leading '+'**. So a 16-char,
302// '+'-prefixed string is rejected by upstream Litestream but ACCEPTED by
303// rustyriver — an observable Err-vs-Ok behavioral divergence on the public
304// parse surface. A faithful port must reject the leading sign.
305#[test]
306fn test_parse_txid_rejects_leading_plus_sign() {
307 // 16 characters, leading '+'. Go's strconv.ParseUint forbids sign prefixes,
308 // so upstream ParseTXID returns an error here. rustyriver's
309 // u64::from_str_radix accepts '+', so it currently returns Ok(...) — a real
310 // Err-vs-Ok divergence on the public parse surface. The faithful port must
311 // reject the leading sign.
312 assert!(
313 parse_txid("+000000000000abc").is_err(),
314 "Go strconv.ParseUint forbids a leading '+'; rustyriver must reject it too \
315 (diverges from [email protected] ParseTXID, which uses strconv.ParseUint)"
316 );
317}
318
319// ── Pos formatting / parsing ──────────────────────────────────────────────────
320
321#[test]
322fn test_pos_display() {
323 let p = Pos::new(TXID(1), 0x8000_0000_0000_0001);
324 assert_eq!(p.to_string(), "0000000000000001/8000000000000001");
325}
326
327#[test]
328fn test_pos_is_zero() {
329 assert!(Pos::ZERO.is_zero());
330 assert!(!Pos::new(TXID(1), 0).is_zero());
331}
332
333#[test]
334fn test_parse_pos_roundtrip() {
335 let p = Pos::new(TXID(42), 0x8000_0000_0000_0042);
336 let s = p.to_string();
337 let p2 = parse_pos(&s).expect("parse must succeed");
338 assert_eq!(p, p2);
339}
340
341#[test]
342fn test_parse_pos_wrong_length() {
343 assert!(parse_pos("").is_err());
344 assert!(parse_pos("0000000000000001/800000000000000").is_err()); // 32 chars
345 assert!(parse_pos("0000000000000001/80000000000000001").is_err()); // 34 chars
346}
347
348// ── TestNewLTXError ───────────────────────────────────────────────────────────
349// Ported from litestream_test.go:75-124
350
351#[test]
352fn test_new_ltx_error_missing_file_has_hint() {
353 let err = new_ltx_error(
354 "open",
355 "/path/to/file.ltx",
356 0,
357 1,
358 1,
359 Error::Io(std::io::Error::new(
360 std::io::ErrorKind::NotFound,
361 "file not found",
362 )),
363 );
364 assert!(!err.hint.is_empty(), "expected hint for missing file error");
365 assert!(
366 err.hint.contains("missing"),
367 "hint should mention missing: {}",
368 err.hint
369 );
370 assert!(
371 err.hint.contains("litestream reset"),
372 "hint should mention reset: {}",
373 err.hint
374 );
375}
376
377#[test]
378fn test_new_ltx_error_corrupted_has_hint() {
379 let err = new_ltx_error("decode", "/path/to/file.ltx", 0, 1, 1, Error::LTXCorrupted);
380 assert!(
381 !err.hint.is_empty(),
382 "expected hint for corrupted file error"
383 );
384 assert!(
385 err.hint.contains("corrupted"),
386 "hint should mention corruption: {}",
387 err.hint
388 );
389}
390
391#[test]
392fn test_new_ltx_error_checksum_mismatch_has_hint() {
393 let err = new_ltx_error(
394 "validate",
395 "/path/to/file.ltx",
396 0,
397 1,
398 1,
399 Error::ChecksumMismatch,
400 );
401 assert!(!err.hint.is_empty(), "expected hint for checksum mismatch");
402}
403
404#[test]
405fn test_new_ltx_error_string_contains_op_and_path() {
406 let err = new_ltx_error(
407 "open",
408 "/path/to/file.ltx",
409 0,
410 1,
411 1,
412 Error::Io(std::io::Error::new(
413 std::io::ErrorKind::NotFound,
414 "file not found",
415 )),
416 );
417 let s = err.to_string();
418 assert!(s.contains("open"), "error should contain operation: {s}");
419 assert!(
420 s.contains("/path/to/file.ltx"),
421 "error should contain path: {s}"
422 );
423}
424
425#[test]
426fn test_new_ltx_error_unwrap() {
427 // Ported from TestNewLTXError/Unwrap — litestream_test.go:117-123
428 // Go: errors.Is(err, underlying). Rust: source() must be Some.
429 use std::error::Error as StdError;
430 let err = new_ltx_error("read", "/path/to/file.ltx", 0, 1, 1, Error::LTXMissing);
431 assert!(
432 err.source().is_some(),
433 "LTXError should expose a source error"
434 );
435}
436
437// ── TestLTXErrorHints ─────────────────────────────────────────────────────────
438// Ported from litestream_test.go:126-137
439
440#[test]
441fn test_ltx_error_hints_ltx_missing() {
442 let err = new_ltx_error("open", "/path/to/file.ltx", 0, 1, 1, Error::LTXMissing);
443 assert!(!err.hint.is_empty(), "expected hint for ErrLTXMissing");
444 assert!(
445 err.hint.contains("litestream reset"),
446 "hint should mention reset: {}",
447 err.hint
448 );
449}
450
451// ── TestLTXError_IsAutoRecoverable ────────────────────────────────────────────
452// Ported from litestream_test.go:139-163
453
454#[test]
455fn test_ltx_error_is_auto_recoverable() {
456 struct Case {
457 name: &'static str,
458 err: Error,
459 recoverable: bool,
460 }
461
462 let cases = vec![
463 Case {
464 name: "NotExist",
465 err: Error::Io(std::io::Error::new(
466 std::io::ErrorKind::NotFound,
467 "not found",
468 )),
469 recoverable: true,
470 },
471 Case {
472 name: "LTXMissing",
473 err: Error::LTXMissing,
474 recoverable: true,
475 },
476 Case {
477 name: "LTXCorrupted",
478 err: Error::LTXCorrupted,
479 recoverable: true,
480 },
481 Case {
482 name: "ChecksumMismatch",
483 err: Error::ChecksumMismatch,
484 recoverable: true,
485 },
486 Case {
487 // Go: {"WrappedCorrupted", fmt.Errorf("%w: bad data", ErrLTXCorrupted), true}
488 // Mirrors a low-level reader returning context-wrapped corruption;
489 // errors.Is unwraps the chain, so still auto-recoverable.
490 name: "WrappedCorrupted",
491 err: Error::Other(Box::new(Error::LTXCorrupted)),
492 recoverable: true,
493 },
494 Case {
495 name: "PermissionDenied",
496 err: Error::Io(std::io::Error::new(
497 std::io::ErrorKind::PermissionDenied,
498 "permission denied",
499 )),
500 recoverable: false,
501 },
502 Case {
503 name: "GenericError",
504 err: Error::Other("something went wrong".into()),
505 recoverable: false,
506 },
507 Case {
508 // Go: {"IOError", fmt.Errorf("disk failure: %w", errors.New("EIO")), false}
509 // A generic wrapped I/O error (not NotFound) is not auto-recoverable.
510 name: "IOError",
511 err: Error::Other(Box::new(std::io::Error::other("EIO"))),
512 recoverable: false,
513 },
514 ];
515
516 for c in cases {
517 let ltx_err = new_ltx_error("open", "/path/to/file.ltx", 0, 1, 1, c.err);
518 assert_eq!(
519 ltx_err.is_auto_recoverable(),
520 c.recoverable,
521 "case '{}' failed",
522 c.name
523 );
524 }
525}