Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/differential_xtool.rs
454 lines · 18.8 KBRaw History
1//! differential_xtool — **GATE G3 ("M1 correct"), PLAN.md §6.3**: cross-tool
2//! differential tests against the REAL `litestream` binary (pinned v0.5.16).
3//!
4//! This is the strongest correctness oracle in the project. It does not compare
5//! against rustyriver's own output (forbidden by AGENTS.md rule 3): the expected
6//! value is whatever the real Litestream binary produces. Three directions, each
7//! exactly as specified in §6.3:
8//!
9//! * **D1 (write path):** rustyriver replicates a DB into a file replica, then the
10//! **real `litestream restore`** reproduces it → **Oracle A** vs the source.
11//! Proves our *written* LTX format is real-Litestream-readable. If this passes,
12//! our serializer is wire-compatible with upstream.
13//! * **D2 (restore path):** the **real `litestream replicate`** writes a replica,
14//! then **rustyriver restores** it → **Oracle A** vs the source. Proves our
15//! *reader* handles real-Litestream output.
16//! * **D3 (format cross-check):** both tools restore the **same** replica → the two
17//! output DB files are **byte-identical** (**Oracle B**, after a TRUNCATE
18//! checkpoint). Isolates format fidelity from SQLite-version noise because both
19//! replay identical page images. Run in both directions (over a
20//! rustyriver-written replica AND a real-Litestream-written replica).
21//!
22//! ## Skip policy
23//! Every test self-skips (logs + `return`, never a silent pass and never a
24//! failure) when the `litestream` binary or `sqlite3` is absent from PATH — but
25//! in the pinned CI/dev environment (PLAN.md D-3) both ARE present, so the gate
26//! actually runs. The skip is a runtime guard, not a compile-time ignore
27//! attribute, and no assertion is weakened (AGENTS.md rules 1-2).
28//!
29//! ## Why a file replica (not S3)
30//! D1–D3 exercise the *format* and the *restore algorithm*, which are transport
31//! agnostic. The file `ReplicaClient` is byte-for-byte the same object layout the
32//! S3 client uses (`<root>/ltx/<level>/<min>-<max>.ltx`), and the real binary's
33//! `file://` backend reads/writes that identical tree — so a file replica is the
34//! cleanest, hermetic way to put both tools on the *same* bytes. The S3
35//! transport is separately proven end-to-end by T7 (`integration_s3.rs`).
36
37use celld_ltx::client::file::FileReplicaClient;
38use celld_ltx::db::Db;
39use celld_ltx::replica::{self, Replica};
40use celld_ltx::TXID;
41use rusqlite::Connection;
42use std::path::Path;
43use std::process::Command;
44
45/// Absolute path to the `db_equal.sh` oracle (PLAN.md §6.1).
46fn db_equal_script() -> String {
47 format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR"))
48}
49
50/// Runs `db_equal.sh <mode> <a> <b>`; `Ok(())` on exit 0, else the captured
51/// stdout+stderr so a failure pinpoints the mismatch. Requires `sqlite3`.
52///
53/// `mode` is `"A"` (logical equality) or `"B"` (byte-identical main file).
54fn db_equal(mode: &str, a: &Path, b: &Path) -> Result<(), String> {
55 let out = Command::new("bash")
56 .arg(db_equal_script())
57 .arg(mode)
58 .arg(a)
59 .arg(b)
60 .output()
61 .map_err(|e| format!("spawn db_equal.sh: {e}"))?;
62 if out.status.success() {
63 Ok(())
64 } else {
65 Err(format!(
66 "db_equal {mode} failed:\nstdout: {}\nstderr: {}",
67 String::from_utf8_lossy(&out.stdout),
68 String::from_utf8_lossy(&out.stderr),
69 ))
70 }
71}
72
73/// The real binary under test: `$LITESTREAM_BIN`, or `litestream` on PATH.
74/// The oracle is pinned to Litestream v0.5.16, which uses superfly/ltx v0.5.2.
75/// Older v0.5 binaries cannot read the size-prefixed block representation, so
76/// the test must not accept any v0.5 binary as an equivalent oracle.
77fn litestream_bin() -> String {
78 std::env::var("LITESTREAM_BIN").unwrap_or_else(|_| "litestream".into())
79}
80
81/// True when the resolved binary exists AND speaks the pinned replica era.
82fn litestream_usable(test: &str) -> bool {
83 let out = Command::new(litestream_bin()).arg("version").output();
84 match out {
85 Err(_) => {
86 eprintln!(
87 "skipping {test}: `{}` not runnable; set LITESTREAM_BIN or \
88 put litestream on PATH",
89 litestream_bin()
90 );
91 false
92 }
93 Ok(o) => {
94 let v = String::from_utf8_lossy(&o.stdout).trim().to_string();
95 if v == "v0.5.16" || v == "0.5.16" {
96 true
97 } else {
98 eprintln!(
99 "skipping {test}: litestream {v:?} is not the pinned v0.5.16 \
100 oracle; point LITESTREAM_BIN at v0.5.16"
101 );
102 false
103 }
104 }
105 }
106}
107
108/// True if `bin` resolves on PATH (exits with any status code when run with a
109/// help-ish flag). Mirrors the probe used by the other integration suites.
110fn has_bin(bin: &str) -> bool {
111 Command::new(bin)
112 .arg("--help")
113 .output()
114 .map(|o| o.status.success() || o.status.code().is_some())
115 .unwrap_or(false)
116}
117
118/// Returns `true` and logs a skip note if either required tool is missing or
119/// the wrong era. The differential gate is meaningless without BOTH the real
120/// binary and `sqlite3`.
121fn skip_if_tools_missing(test: &str) -> bool {
122 if !litestream_usable(test) {
123 return true;
124 }
125 if !has_bin("sqlite3") {
126 eprintln!("skipping {test}: `sqlite3` not on PATH (required for the db_equal oracle)");
127 return true;
128 }
129 false
130}
131
132/// A `file://<abs-path>` URL for the real binary's `file:` backend. The path must
133/// be absolute (litestream rejects a relative `file://` host segment).
134fn file_url(root: &Path) -> String {
135 let abs = root
136 .canonicalize()
137 .unwrap_or_else(|_| root.to_path_buf())
138 .to_string_lossy()
139 .into_owned();
140 format!("file://{abs}")
141}
142
143/// Opens an application writer connection in WAL mode — the host's own SQLite
144/// handle writing alongside the managed `Db`, exactly as a library embedder does.
145fn open_writer(path: &Path) -> Connection {
146 let c = Connection::open(path).unwrap();
147 c.busy_timeout(std::time::Duration::from_secs(5)).unwrap();
148 let mode: String = c
149 .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0))
150 .unwrap();
151 assert_eq!(mode, "wal", "test DB must be in WAL mode");
152 c
153}
154
155/// The deterministic multi-transaction workload shared by the directions, so each
156/// case exercises a snapshot + several incremental L0 files (mixed
157/// insert/update/delete/DDL + a multi-page transaction). `apply` receives each
158/// SQL statement-group in order; the caller decides what to do after each
159/// (rustyriver capture+upload, or a real `litestream replicate -once`).
160fn workload() -> &'static [&'static str] {
161 &[
162 "CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL)",
163 "INSERT INTO kv (k, v) VALUES ('a','1'),('b','2'),('c','3')",
164 "UPDATE kv SET v='updated' WHERE k='a'",
165 "INSERT INTO kv (k, v) VALUES ('d','4'),('e','5')",
166 "DELETE FROM kv WHERE k='b'",
167 // A larger multi-page transaction to exercise multi-frame WAL capture.
168 "CREATE TABLE big (id INTEGER PRIMARY KEY, blob TEXT);\
169 INSERT INTO big (id, blob) SELECT value, hex(randomblob(200)) \
170 FROM (WITH RECURSIVE c(value) AS (SELECT 1 UNION ALL SELECT value+1 \
171 FROM c WHERE value<500) SELECT value FROM c);",
172 ]
173}
174
175/// Drives rustyriver's write path over `workload()`: opens a managed `Db`, an app
176/// writer, applies each statement-group, then captures (`db.sync`) and uploads
177/// (`replica.sync`) it. Leaves a replica tree at `replica_root` and the source DB
178/// at `src_path`. Returns the final captured TXID.
179async fn rustyriver_replicate(src_path: &Path, replica_root: &Path) -> TXID {
180 let db = Db::open(src_path).unwrap();
181 let writer = open_writer(src_path);
182 let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned());
183 let mut replica = Replica::new(db, client);
184
185 for sql in workload() {
186 writer.execute_batch(sql).unwrap();
187 replica.db_mut().unwrap().sync().unwrap();
188 replica.sync().await.unwrap();
189 }
190
191 let pos = replica.db_mut().unwrap().pos().unwrap();
192 assert!(
193 pos.txid.0 >= workload().len() as u64,
194 "expected at least {} captured TXIDs, got {}",
195 workload().len(),
196 pos.txid
197 );
198
199 // Clean shutdown so the source WAL is released before the real binary or the
200 // oracle reads the source file.
201 let db = replica.into_db().unwrap();
202 db.close().unwrap();
203 drop(writer);
204 pos.txid
205}
206
207/// Drives the REAL binary's write path over `workload()`: seeds WAL mode, then for
208/// each statement-group writes via plain `sqlite3` and runs `litestream replicate
209/// -once` to flush exactly one sync (no background timing races — the same
210/// deterministic method `capture-golden.sh` uses). Leaves a replica tree at
211/// `replica_root` and the source DB at `src_path`.
212fn litestream_replicate(src_path: &Path, replica_root: &Path) {
213 // Seed WAL mode + the first statement-group on a plain connection, then take
214 // the initial snapshot.
215 let url = file_url(replica_root);
216 {
217 let c = open_writer(src_path);
218 c.execute_batch(workload()[0]).unwrap();
219 }
220 run_litestream(&["replicate", "-once", &src_path.to_string_lossy(), &url]);
221
222 for sql in &workload()[1..] {
223 {
224 let c = open_writer(src_path);
225 c.execute_batch(sql).unwrap();
226 }
227 run_litestream(&["replicate", "-once", &src_path.to_string_lossy(), &url]);
228 }
229}
230
231/// Runs `litestream <args...>`, asserting success and surfacing stderr on failure.
232fn run_litestream(args: &[&str]) {
233 let out = Command::new(litestream_bin())
234 .args(args)
235 .output()
236 .unwrap_or_else(|e| panic!("spawn litestream {args:?}: {e}"));
237 assert!(
238 out.status.success(),
239 "litestream {args:?} failed (status {:?}):\nstdout: {}\nstderr: {}",
240 out.status.code(),
241 String::from_utf8_lossy(&out.stdout),
242 String::from_utf8_lossy(&out.stderr),
243 );
244}
245
246/// Runs the real `litestream restore -o <out> <file-url>` for a replica tree.
247fn litestream_restore(replica_root: &Path, out: &Path) {
248 let url = file_url(replica_root);
249 run_litestream(&["restore", "-o", &out.to_string_lossy(), &url]);
250 assert!(out.exists(), "litestream restore did not produce {out:?}");
251}
252
253// ───────────────────────────── D1 (write path) ─────────────────────────────
254
255/// **D1 — our write → real `litestream restore` → Oracle A vs source.**
256///
257/// rustyriver replicates the workload into a file replica; the *real* binary
258/// restores that tree; the restored DB must be logically identical to the source.
259/// This is the load-bearing proof that rustyriver's LTX serializer is byte-format
260/// compatible with upstream Litestream — if the real tool can read what we wrote,
261/// our format is correct (AGENTS.md rule 3: the binary, not us, is the oracle).
262#[tokio::test(flavor = "multi_thread")]
263async fn d1_our_write_real_restore_oracle_a() {
264 if skip_if_tools_missing("d1_our_write_real_restore_oracle_a") {
265 return;
266 }
267
268 let dir = tempfile::tempdir().unwrap();
269 let src = dir.path().join("source.db");
270 let replica_root = dir.path().join("replica");
271 let restored = dir.path().join("restored-by-litestream.db");
272
273 // 1. rustyriver writes the replica.
274 rustyriver_replicate(&src, &replica_root).await;
275
276 // 2. The REAL binary restores our tree.
277 litestream_restore(&replica_root, &restored);
278
279 // 3. Oracle A: real-restored == source.
280 db_equal("A", &src, &restored)
281 .expect("D1: real `litestream restore` of our replica must equal the source (Oracle A)");
282}
283
284// ──────────────────────────── D2 (restore path) ────────────────────────────
285
286/// **D2 — real `litestream replicate` → our restore → Oracle A vs source.**
287///
288/// The real binary replicates the workload; rustyriver restores that tree; the
289/// restored DB must be logically identical to the source. Proves our LTX *reader*
290/// + restore algorithm correctly consume real-Litestream-produced bytes.
291#[tokio::test(flavor = "multi_thread")]
292async fn d2_real_write_our_restore_oracle_a() {
293 if skip_if_tools_missing("d2_real_write_our_restore_oracle_a") {
294 return;
295 }
296
297 let dir = tempfile::tempdir().unwrap();
298 let src = dir.path().join("source.db");
299 let replica_root = dir.path().join("replica");
300 let restored = dir.path().join("restored-by-rustyriver.db");
301
302 // 1. The REAL binary writes the replica.
303 litestream_replicate(&src, &replica_root);
304
305 // 2. rustyriver restores it (client-only restore; no Db needed).
306 let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned());
307 replica::restore(&client, &restored, TXID(0))
308 .await
309 .expect("D2: rustyriver restore of a real-Litestream replica");
310
311 // 3. Oracle A: our-restored == source.
312 db_equal("A", &src, &restored)
313 .expect("D2: our restore of a real `litestream` replica must equal the source (Oracle A)");
314}
315
316// ─────────────────────────── D3 (format cross-check) ───────────────────────
317
318/// **D3 (over a rustyriver-written replica) — both tools restore the SAME tree →
319/// byte-identical (Oracle B).**
320///
321/// rustyriver writes the replica, then BOTH rustyriver and the real binary restore
322/// it; after a TRUNCATE checkpoint the two output main-DB files must be
323/// byte-for-byte identical. Because both restorers replay the *same* page images,
324/// any byte difference is pure format/restore-algorithm divergence — the most
325/// sensitive format-fidelity check (Risk R-1/R-2). This direction additionally
326/// proves our *writer* emits page images the real decoder reconstructs bit-exactly.
327#[tokio::test(flavor = "multi_thread")]
328async fn d3_byte_identical_over_our_replica() {
329 if skip_if_tools_missing("d3_byte_identical_over_our_replica") {
330 return;
331 }
332
333 let dir = tempfile::tempdir().unwrap();
334 let src = dir.path().join("source.db");
335 let replica_root = dir.path().join("replica");
336 let ours = dir.path().join("ours.db");
337 let theirs = dir.path().join("theirs.db");
338
339 // rustyriver writes the replica.
340 rustyriver_replicate(&src, &replica_root).await;
341
342 // Our restore.
343 let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned());
344 replica::restore(&client, &ours, TXID(0))
345 .await
346 .expect("D3: our restore of our replica");
347
348 // The real binary's restore of the SAME tree.
349 litestream_restore(&replica_root, &theirs);
350
351 // Oracle B: byte-identical main DB files after a TRUNCATE checkpoint.
352 db_equal("B", &theirs, &ours).expect(
353 "D3: our restore and `litestream restore` of our replica must be byte-identical (Oracle B)",
354 );
355}
356
357/// **D3 (over a real-Litestream-written replica) — both tools restore the SAME
358/// tree → byte-identical (Oracle B).**
359///
360/// The mirror of `d3_byte_identical_over_our_replica`: the real binary writes the
361/// replica, then both tools restore it, and the outputs must be byte-identical.
362/// Running D3 in both write-directions catches an asymmetry where one tool's
363/// *writer* and the other's *reader* happen to agree only on self-produced bytes.
364#[tokio::test(flavor = "multi_thread")]
365async fn d3_byte_identical_over_real_replica() {
366 if skip_if_tools_missing("d3_byte_identical_over_real_replica") {
367 return;
368 }
369
370 let dir = tempfile::tempdir().unwrap();
371 let src = dir.path().join("source.db");
372 let replica_root = dir.path().join("replica");
373 let ours = dir.path().join("ours.db");
374 let theirs = dir.path().join("theirs.db");
375
376 // The real binary writes the replica.
377 litestream_replicate(&src, &replica_root);
378
379 // Our restore.
380 let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned());
381 replica::restore(&client, &ours, TXID(0))
382 .await
383 .expect("D3: our restore of a real replica");
384
385 // The real binary's restore of the SAME tree.
386 litestream_restore(&replica_root, &theirs);
387
388 // Oracle B: byte-identical main DB files after a TRUNCATE checkpoint.
389 db_equal("B", &theirs, &ours).expect(
390 "D3: our restore and `litestream restore` of a real replica must be byte-identical (Oracle B)",
391 );
392}
393
394/// **D2 at a TARGET TXID — real write → our point-in-time restore → Oracle A.**
395///
396/// Exercises the `-txid`-equivalent restore path against real-Litestream bytes:
397/// the real binary replicates the full workload, rustyriver restores up to an
398/// intermediate TXID, and the result must equal what the *real* binary restores at
399/// that same `-txid`. Both restorers consume the identical real replica, so this
400/// confirms our `calc_restore_plan` selects the same chain the real tool does for
401/// a point-in-time target. (Uses Oracle A because a partial restore stops at a
402/// mid-stream TXID; the comparison is real-vs-ours at the same target.)
403#[tokio::test(flavor = "multi_thread")]
404async fn d2_real_write_our_restore_at_target_txid() {
405 if skip_if_tools_missing("d2_real_write_our_restore_at_target_txid") {
406 return;
407 }
408
409 let dir = tempfile::tempdir().unwrap();
410 let src = dir.path().join("source.db");
411 let replica_root = dir.path().join("replica");
412 let ours = dir.path().join("ours-at-txid.db");
413 let theirs = dir.path().join("theirs-at-txid.db");
414
415 // The real binary writes the full workload.
416 litestream_replicate(&src, &replica_root);
417
418 // Pick an intermediate target: the count of statement-groups gives the max
419 // TXID; restore to roughly the middle of the chain.
420 let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned());
421 let files = {
422 use celld_ltx::client::ReplicaClient;
423 client.ltx_files(0, TXID(0)).await.unwrap()
424 };
425 let max_txid = files.iter().map(|f| f.max_txid.0).max().unwrap();
426 assert!(
427 max_txid >= 4,
428 "need a multi-file chain (got max {max_txid})"
429 );
430 let target = TXID(max_txid - 2); // a mid-stream point-in-time target
431
432 // Our restore up to `target`.
433 replica::restore(&client, &ours, target)
434 .await
435 .expect("D2(txid): our restore to target");
436
437 // The real binary's restore up to the same `-txid`.
438 let url = file_url(&replica_root);
439 let txid_hex = format!("{:016x}", target.0);
440 run_litestream(&[
441 "restore",
442 "-txid",
443 &txid_hex,
444 "-o",
445 &theirs.to_string_lossy(),
446 &url,
447 ]);
448 assert!(theirs.exists(), "litestream restore -txid produced no file");
449
450 // Oracle A: our point-in-time restore == the real tool's at the same TXID.
451 db_equal("A", &theirs, &ours).expect(
452 "D2(txid): our restore@target must equal real `litestream restore -txid` at the same TXID (Oracle A)",
453 );
454}