Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/litestream_helpers.rs
526 lines · 18.5 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 — breaking the differential oracle (G3,
168// PLAN.md §6.3 D1/D3). 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 ARE FROM THE REAL GO `path.Join` (the upstream oracle, run
206// with go1.25 against `path.Join(root, "ltx")`), never from rustyriver — per
207// AGENTS.md rule 3:
208// path.Join("a/b/../c","ltx") = "a/c/ltx"
209// path.Join("x/y/../z","ltx") = "x/z/ltx"
210// path.Join("a/b/c/../d","ltx") = "a/b/d/ltx"
211// path.Join("aa/bb/../cc","ltx")= "aa/cc/ltx"
212//
213// Why this matters: these helpers compute LTX object-store keys (litestream.go
214// 184-197). Any `root` whose cleaned form contains an interior `..` over a
215// surviving prefix (e.g. a configured prefix like "bucket/db/../ltxroot") yields
216// a doubled-slash S3 key ("bucket//ltxroot/...") — a DIFFERENT object than the
217// real binary writes/reads, silently breaking the differential oracle (G3,
218// PLAN.md §6.3 D1/D3). A faithful port must match Go's `path.Clean` exactly.
219#[test]
220fn test_ltx_dir_cleans_dotdot_over_surviving_prefix() {
221 // Interior ".." that backtracks over one element, leaving a prefix.
222 assert_eq!(
223 ltx_dir("a/b/../c"),
224 "a/c/ltx",
225 "path.Clean must collapse 'a/b/../c' to 'a/c' (no doubled separator)"
226 );
227 assert_eq!(
228 ltx_dir("x/y/../z"),
229 "x/z/ltx",
230 "path.Clean must collapse 'x/y/../z' to 'x/z'"
231 );
232 // Backtrack with two surviving prefix elements.
233 assert_eq!(
234 ltx_dir("a/b/c/../d"),
235 "a/b/d/ltx",
236 "path.Clean must collapse 'a/b/c/../d' to 'a/b/d'"
237 );
238 // Multi-char element names (rules out any single-byte coincidence).
239 assert_eq!(
240 ltx_level_dir("aa/bb/../cc", 0),
241 "aa/cc/ltx/0",
242 "path.Clean must collapse 'aa/bb/../cc' to 'aa/cc'"
243 );
244}
245
246// ── LTXFilePath ───────────────────────────────────────────────────────────────
247// litestream_test.go:60-65 declares a function named `LTXFilePath` (no Test
248// prefix), so Go's test runner never executes it; it also uses "-" as the
249// expected value — a placeholder stub. We port it as a proper Rust test with
250// the correct expected value derived from [email protected] ltx.go:487 FormatFilename.
251// TXID(100) = 0x64 → "0000000000000064"
252// TXID(200) = 0xc8 → "00000000000000c8"
253
254#[test]
255fn test_ltx_file_path() {
256 assert_eq!(
257 ltx_file_path("foo", 0, TXID(100), TXID(200)),
258 "foo/ltx/0/0000000000000064-00000000000000c8.ltx"
259 );
260}
261
262// ── TXID formatting / parsing ─────────────────────────────────────────────────
263
264#[test]
265fn test_txid_display() {
266 assert_eq!(TXID(1).to_string(), "0000000000000001");
267 assert_eq!(TXID(0).to_string(), "0000000000000000");
268 assert_eq!(TXID(u64::MAX).to_string(), "ffffffffffffffff");
269 assert_eq!(TXID(0x64).to_string(), "0000000000000064");
270}
271
272#[test]
273fn test_txid_roundtrip() {
274 for v in [0u64, 1, 100, 200, 0xdead_beef_cafe_babe, u64::MAX] {
275 let s = TXID(v).to_string();
276 assert_eq!(s.len(), 16, "must be 16 chars: {s:?}");
277 let parsed = parse_txid(&s).expect("parse must succeed");
278 assert_eq!(parsed, TXID(v));
279 }
280}
281
282#[test]
283fn test_parse_txid_wrong_length() {
284 assert!(parse_txid("000000000000001").is_err()); // 15 chars
285 assert!(parse_txid("00000000000000001").is_err()); // 17 chars
286 assert!(parse_txid("").is_err());
287}
288
289#[test]
290fn test_parse_txid_invalid_chars() {
291 assert!(parse_txid("000000000000001g").is_err());
292}
293
294// ── REVIEWER (T4): leading-sign divergence vs Go strconv.ParseUint ─────────────
295//
296// Upstream `ParseTXID` ([email protected] ltx.go:130-138) and `ParseChecksum`
297// (checksum.go:135-144) both delegate to Go's `strconv.ParseUint(s, 16, 64)`.
298// Per the Go stdlib contract, ParseUint **does not permit a sign prefix**:
299// strconv.ParseUint("+000000000000abc", 16, 64) -> error.
300//
301// The Rust port (lib.rs `parse_txid` / `parse_pos`) uses
302// `u64::from_str_radix`, which **accepts a leading '+'**. So a 16-char,
303// '+'-prefixed string is rejected by upstream Litestream but ACCEPTED by
304// rustyriver — an observable Err-vs-Ok behavioral divergence on the public
305// parse surface. A faithful port must reject the leading sign.
306#[test]
307fn test_parse_txid_rejects_leading_plus_sign() {
308 // 16 characters, leading '+'. Go's strconv.ParseUint forbids sign prefixes,
309 // so upstream ParseTXID returns an error here. rustyriver's
310 // u64::from_str_radix accepts '+', so it currently returns Ok(...) — a real
311 // Err-vs-Ok divergence on the public parse surface. The faithful port must
312 // reject the leading sign.
313 assert!(
314 parse_txid("+000000000000abc").is_err(),
315 "Go strconv.ParseUint forbids a leading '+'; rustyriver must reject it too \
316 (diverges from [email protected] ParseTXID, which uses strconv.ParseUint)"
317 );
318}
319
320// ── Pos formatting / parsing ──────────────────────────────────────────────────
321
322#[test]
323fn test_pos_display() {
324 let p = Pos::new(TXID(1), 0x8000_0000_0000_0001);
325 assert_eq!(p.to_string(), "0000000000000001/8000000000000001");
326}
327
328#[test]
329fn test_pos_is_zero() {
330 assert!(Pos::ZERO.is_zero());
331 assert!(!Pos::new(TXID(1), 0).is_zero());
332}
333
334#[test]
335fn test_parse_pos_roundtrip() {
336 let p = Pos::new(TXID(42), 0x8000_0000_0000_0042);
337 let s = p.to_string();
338 let p2 = parse_pos(&s).expect("parse must succeed");
339 assert_eq!(p, p2);
340}
341
342#[test]
343fn test_parse_pos_wrong_length() {
344 assert!(parse_pos("").is_err());
345 assert!(parse_pos("0000000000000001/800000000000000").is_err()); // 32 chars
346 assert!(parse_pos("0000000000000001/80000000000000001").is_err()); // 34 chars
347}
348
349// ── TestNewLTXError ───────────────────────────────────────────────────────────
350// Ported from litestream_test.go:75-124
351
352#[test]
353fn test_new_ltx_error_missing_file_has_hint() {
354 let err = new_ltx_error(
355 "open",
356 "/path/to/file.ltx",
357 0,
358 1,
359 1,
360 Error::Io(std::io::Error::new(
361 std::io::ErrorKind::NotFound,
362 "file not found",
363 )),
364 );
365 assert!(!err.hint.is_empty(), "expected hint for missing file error");
366 assert!(
367 err.hint.contains("missing"),
368 "hint should mention missing: {}",
369 err.hint
370 );
371 assert!(
372 err.hint.contains("litestream reset"),
373 "hint should mention reset: {}",
374 err.hint
375 );
376}
377
378#[test]
379fn test_new_ltx_error_corrupted_has_hint() {
380 let err = new_ltx_error("decode", "/path/to/file.ltx", 0, 1, 1, Error::LTXCorrupted);
381 assert!(
382 !err.hint.is_empty(),
383 "expected hint for corrupted file error"
384 );
385 assert!(
386 err.hint.contains("corrupted"),
387 "hint should mention corruption: {}",
388 err.hint
389 );
390}
391
392#[test]
393fn test_new_ltx_error_checksum_mismatch_has_hint() {
394 let err = new_ltx_error(
395 "validate",
396 "/path/to/file.ltx",
397 0,
398 1,
399 1,
400 Error::ChecksumMismatch,
401 );
402 assert!(!err.hint.is_empty(), "expected hint for checksum mismatch");
403}
404
405#[test]
406fn test_new_ltx_error_string_contains_op_and_path() {
407 let err = new_ltx_error(
408 "open",
409 "/path/to/file.ltx",
410 0,
411 1,
412 1,
413 Error::Io(std::io::Error::new(
414 std::io::ErrorKind::NotFound,
415 "file not found",
416 )),
417 );
418 let s = err.to_string();
419 assert!(s.contains("open"), "error should contain operation: {s}");
420 assert!(
421 s.contains("/path/to/file.ltx"),
422 "error should contain path: {s}"
423 );
424}
425
426#[test]
427fn test_new_ltx_error_unwrap() {
428 // Ported from TestNewLTXError/Unwrap — litestream_test.go:117-123
429 // Go: errors.Is(err, underlying). Rust: source() must be Some.
430 use std::error::Error as StdError;
431 let err = new_ltx_error("read", "/path/to/file.ltx", 0, 1, 1, Error::LTXMissing);
432 assert!(
433 err.source().is_some(),
434 "LTXError should expose a source error"
435 );
436}
437
438// ── TestLTXErrorHints ─────────────────────────────────────────────────────────
439// Ported from litestream_test.go:126-137
440
441#[test]
442fn test_ltx_error_hints_ltx_missing() {
443 let err = new_ltx_error("open", "/path/to/file.ltx", 0, 1, 1, Error::LTXMissing);
444 assert!(!err.hint.is_empty(), "expected hint for ErrLTXMissing");
445 assert!(
446 err.hint.contains("litestream reset"),
447 "hint should mention reset: {}",
448 err.hint
449 );
450}
451
452// ── TestLTXError_IsAutoRecoverable ────────────────────────────────────────────
453// Ported from litestream_test.go:139-163
454
455#[test]
456fn test_ltx_error_is_auto_recoverable() {
457 struct Case {
458 name: &'static str,
459 err: Error,
460 recoverable: bool,
461 }
462
463 let cases = vec![
464 Case {
465 name: "NotExist",
466 err: Error::Io(std::io::Error::new(
467 std::io::ErrorKind::NotFound,
468 "not found",
469 )),
470 recoverable: true,
471 },
472 Case {
473 name: "LTXMissing",
474 err: Error::LTXMissing,
475 recoverable: true,
476 },
477 Case {
478 name: "LTXCorrupted",
479 err: Error::LTXCorrupted,
480 recoverable: true,
481 },
482 Case {
483 name: "ChecksumMismatch",
484 err: Error::ChecksumMismatch,
485 recoverable: true,
486 },
487 Case {
488 // Go: {"WrappedCorrupted", fmt.Errorf("%w: bad data", ErrLTXCorrupted), true}
489 // Mirrors a low-level reader returning context-wrapped corruption;
490 // errors.Is unwraps the chain, so still auto-recoverable.
491 name: "WrappedCorrupted",
492 err: Error::Other(Box::new(Error::LTXCorrupted)),
493 recoverable: true,
494 },
495 Case {
496 name: "PermissionDenied",
497 err: Error::Io(std::io::Error::new(
498 std::io::ErrorKind::PermissionDenied,
499 "permission denied",
500 )),
501 recoverable: false,
502 },
503 Case {
504 name: "GenericError",
505 err: Error::Other("something went wrong".into()),
506 recoverable: false,
507 },
508 Case {
509 // Go: {"IOError", fmt.Errorf("disk failure: %w", errors.New("EIO")), false}
510 // A generic wrapped I/O error (not NotFound) is not auto-recoverable.
511 name: "IOError",
512 err: Error::Other(Box::new(std::io::Error::other("EIO"))),
513 recoverable: false,
514 },
515 ];
516
517 for c in cases {
518 let ltx_err = new_ltx_error("open", "/path/to/file.ltx", 0, 1, 1, c.err);
519 assert_eq!(
520 ltx_err.is_auto_recoverable(),
521 c.recoverable,
522 "case '{}' failed",
523 c.name
524 );
525 }
526}