| 1 | // This external-oracle test inspects files produced by two independent tools. |
| 2 | #![allow(clippy::disallowed_methods)] |
| 3 | |
| 4 | //! differential_xtool — cross-tool differential tests against the real |
| 5 | //! `litestream` binary, pinned by |
| 6 | //! [`PINNED_LITESTREAM_VERSION`]. |
| 7 | //! |
| 8 | //! This is the strongest correctness oracle in the project. The expected value |
| 9 | //! comes from the real Litestream binary, not from the implementation under test. |
| 10 | //! |
| 11 | //! * **D1 (write path):** rustyriver replicates a DB into a file replica, then the |
| 12 | //! **real `litestream restore`** reproduces it → **Oracle A** vs the source. |
| 13 | //! Proves our *written* LTX format is real-Litestream-readable. If this passes, |
| 14 | //! our serializer is wire-compatible with upstream. |
| 15 | //! * **D2 (restore path):** the **real `litestream replicate`** writes a replica, |
| 16 | //! then **rustyriver restores** it → **Oracle A** vs the source. Proves our |
| 17 | //! *reader* handles real-Litestream output. |
| 18 | //! * **D3 (format cross-check):** both tools restore the **same** replica → the two |
| 19 | //! output DB files are **byte-identical** (**Oracle B**, after a TRUNCATE |
| 20 | //! checkpoint). Isolates format fidelity from SQLite-version noise because both |
| 21 | //! replay identical page images. Run in both directions (over a |
| 22 | //! rustyriver-written replica AND a real-Litestream-written replica). |
| 23 | //! * **D4 (compaction write path):** celld compacts L0 into an L1 object, then the |
| 24 | //! **real `litestream restore`** reads that object → **Oracle A** vs the source. |
| 25 | //! D1 only covers the L0 writer, which still emits the pre-v0.5.2 frame |
| 26 | //! representation; the compactor emits the v0.5.2 block representation, and D4 |
| 27 | //! is the only case where a real reader sees one. |
| 28 | //! |
| 29 | //! ## Skip policy |
| 30 | //! Every test self-skips (logs + `return`, never a silent pass and never a |
| 31 | //! failure) when the `litestream` binary or `sqlite3` is absent from PATH. The |
| 32 | //! skip is a runtime guard, not a compile-time ignore attribute, and it does not |
| 33 | //! weaken an assertion. |
| 34 | //! |
| 35 | //! A skip is also how this gate goes vacuous, so `CELLD_LTX_LITESTREAM_REQUIRED=1` |
| 36 | //! turns every skip into a failure. CI installs the pinned binary and sets that |
| 37 | //! variable, so a broken install reds the run instead of passing an empty gate. |
| 38 | //! |
| 39 | //! ## Why a file replica (not S3) |
| 40 | //! D1–D3 exercise the *format* and the *restore algorithm*, which are transport |
| 41 | //! agnostic. The file `ReplicaClient` is byte-for-byte the same object layout the |
| 42 | //! S3 client uses (`<root>/ltx/<level>/<min>-<max>.ltx`), and the real binary's |
| 43 | //! `file://` backend reads/writes that identical tree — so a file replica is the |
| 44 | //! cleanest, hermetic way to put both tools on the *same* bytes. The S3 |
| 45 | //! transport is separately proven end-to-end by T7 (`integration_s3.rs`). |
| 46 | |
| 47 | use celld_ltx::client::file::FileReplicaClient; |
| 48 | use celld_ltx::db::Db; |
| 49 | use celld_ltx::ltx::{HEADER_SIZE, PAGE_HEADER_FLAG_SIZE}; |
| 50 | use celld_ltx::replica::{self, Replica}; |
| 51 | use celld_ltx::replica_compactor::ReplicaCompactor; |
| 52 | use celld_ltx::{ltx_file_path, TXID}; |
| 53 | use rusqlite::Connection; |
| 54 | use std::path::Path; |
| 55 | use std::process::Command; |
| 56 | |
| 57 | /// Absolute path to the `db_equal.sh` oracle. |
| 58 | fn db_equal_script() -> String { |
| 59 | format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR")) |
| 60 | } |
| 61 | |
| 62 | /// Runs `db_equal.sh <mode> <a> <b>`; `Ok(())` on exit 0, else the captured |
| 63 | /// stdout+stderr so a failure pinpoints the mismatch. Requires `sqlite3`. |
| 64 | /// |
| 65 | /// `mode` is `"A"` (logical equality) or `"B"` (byte-identical main file). |
| 66 | fn db_equal(mode: &str, a: &Path, b: &Path) -> Result<(), String> { |
| 67 | let out = Command::new("bash") |
| 68 | .arg(db_equal_script()) |
| 69 | .arg(mode) |
| 70 | .arg(a) |
| 71 | .arg(b) |
| 72 | .output() |
| 73 | .map_err(|e| format!("spawn db_equal.sh: {e}"))?; |
| 74 | if out.status.success() { |
| 75 | Ok(()) |
| 76 | } else { |
| 77 | Err(format!( |
| 78 | "db_equal {mode} failed:\nstdout: {}\nstderr: {}", |
| 79 | String::from_utf8_lossy(&out.stdout), |
| 80 | String::from_utf8_lossy(&out.stderr), |
| 81 | )) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// The pinned oracle version, and the single place this repository records it. |
| 86 | /// The CI workflow derives the release it downloads from this constant, so the |
| 87 | /// pin cannot drift between the test and the job that feeds it. |
| 88 | /// |
| 89 | /// Litestream v0.5.16 uses superfly/ltx v0.5.2. An older v0.5 binary cannot read |
| 90 | /// the size-prefixed block representation that the compactor publishes, so the |
| 91 | /// test must not accept any v0.5 binary as an equivalent oracle. |
| 92 | pub const PINNED_LITESTREAM_VERSION: &str = "0.5.16"; |
| 93 | |
| 94 | /// The real binary under test: `$LITESTREAM_BIN`, or `litestream` on PATH. |
| 95 | fn litestream_bin() -> String { |
| 96 | std::env::var("LITESTREAM_BIN").unwrap_or_else(|_| "litestream".into()) |
| 97 | } |
| 98 | |
| 99 | /// `CELLD_LTX_LITESTREAM_REQUIRED=1` forbids every skip in this file. A job that |
| 100 | /// installs the oracle and then skips the whole gate is green for the wrong |
| 101 | /// reason, so CI sets this and a failed install reds the run. This mirrors |
| 102 | /// `CELLD_LTX_S3_REQUIRED` in `integration_s3.rs`. |
| 103 | fn required() -> bool { |
| 104 | std::env::var("CELLD_LTX_LITESTREAM_REQUIRED").as_deref() == Ok("1") |
| 105 | } |
| 106 | |
| 107 | /// Records a missing prerequisite: a panic in required mode, a logged skip |
| 108 | /// otherwise. |
| 109 | fn unavailable(test: &str, reason: &str) { |
| 110 | assert!( |
| 111 | !required(), |
| 112 | "{test}: {reason} (CELLD_LTX_LITESTREAM_REQUIRED=1 forbids the skip)" |
| 113 | ); |
| 114 | eprintln!("skipping {test}: {reason}"); |
| 115 | } |
| 116 | |
| 117 | /// True when the resolved binary exists AND speaks the pinned replica era. |
| 118 | fn litestream_usable(test: &str) -> bool { |
| 119 | let out = Command::new(litestream_bin()).arg("version").output(); |
| 120 | match out { |
| 121 | Err(_) => { |
| 122 | unavailable( |
| 123 | test, |
| 124 | &format!( |
| 125 | "`{}` is not runnable; set LITESTREAM_BIN or put litestream on PATH", |
| 126 | litestream_bin() |
| 127 | ), |
| 128 | ); |
| 129 | false |
| 130 | } |
| 131 | Ok(o) => { |
| 132 | let v = String::from_utf8_lossy(&o.stdout).trim().to_string(); |
| 133 | // The release prints the bare version; a source build can prefix a |
| 134 | // `v`. Both name the same pin, so both are accepted. |
| 135 | let pinned = PINNED_LITESTREAM_VERSION; |
| 136 | if v == pinned || v.strip_prefix('v') == Some(pinned) { |
| 137 | true |
| 138 | } else { |
| 139 | unavailable( |
| 140 | test, |
| 141 | &format!( |
| 142 | "litestream {v:?} is not the pinned v{pinned} oracle; \ |
| 143 | point LITESTREAM_BIN at v{pinned}" |
| 144 | ), |
| 145 | ); |
| 146 | false |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// True if `bin` resolves on PATH (exits with any status code when run with a |
| 153 | /// help-ish flag). Mirrors the probe used by the other integration suites. |
| 154 | fn has_bin(bin: &str) -> bool { |
| 155 | Command::new(bin) |
| 156 | .arg("--help") |
| 157 | .output() |
| 158 | .map(|o| o.status.success() || o.status.code().is_some()) |
| 159 | .unwrap_or(false) |
| 160 | } |
| 161 | |
| 162 | /// Returns `true` and logs a skip note if either required tool is missing or |
| 163 | /// the wrong era. The differential gate is meaningless without BOTH the real |
| 164 | /// binary and `sqlite3`. |
| 165 | fn skip_if_tools_missing(test: &str) -> bool { |
| 166 | if !litestream_usable(test) { |
| 167 | return true; |
| 168 | } |
| 169 | if !has_bin("sqlite3") { |
| 170 | unavailable( |
| 171 | test, |
| 172 | "`sqlite3` is not on PATH (the db_equal oracle needs it)", |
| 173 | ); |
| 174 | return true; |
| 175 | } |
| 176 | false |
| 177 | } |
| 178 | |
| 179 | /// A `file://<abs-path>` URL for the real binary's `file:` backend. The path must |
| 180 | /// be absolute (litestream rejects a relative `file://` host segment). |
| 181 | fn file_url(root: &Path) -> String { |
| 182 | let abs = root |
| 183 | .canonicalize() |
| 184 | .unwrap_or_else(|_| root.to_path_buf()) |
| 185 | .to_string_lossy() |
| 186 | .into_owned(); |
| 187 | format!("file://{abs}") |
| 188 | } |
| 189 | |
| 190 | /// Opens an application writer connection in WAL mode — the host's own SQLite |
| 191 | /// handle writing alongside the managed `Db`, exactly as a library embedder does. |
| 192 | fn open_writer(path: &Path) -> Connection { |
| 193 | let c = Connection::open(path).unwrap(); |
| 194 | c.busy_timeout(std::time::Duration::from_secs(5)).unwrap(); |
| 195 | let mode: String = c |
| 196 | .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0)) |
| 197 | .unwrap(); |
| 198 | assert_eq!(mode, "wal", "test DB must be in WAL mode"); |
| 199 | c |
| 200 | } |
| 201 | |
| 202 | /// The deterministic multi-transaction workload shared by the directions, so each |
| 203 | /// case exercises a snapshot + several incremental L0 files (mixed |
| 204 | /// insert/update/delete/DDL + a multi-page transaction). `apply` receives each |
| 205 | /// SQL statement-group in order; the caller decides what to do after each |
| 206 | /// (rustyriver capture+upload, or a real `litestream replicate -once`). |
| 207 | fn workload() -> &'static [&'static str] { |
| 208 | &[ |
| 209 | "CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL)", |
| 210 | "INSERT INTO kv (k, v) VALUES ('a','1'),('b','2'),('c','3')", |
| 211 | "UPDATE kv SET v='updated' WHERE k='a'", |
| 212 | "INSERT INTO kv (k, v) VALUES ('d','4'),('e','5')", |
| 213 | "DELETE FROM kv WHERE k='b'", |
| 214 | // A larger multi-page transaction to exercise multi-frame WAL capture. |
| 215 | "CREATE TABLE big (id INTEGER PRIMARY KEY, blob TEXT);\ |
| 216 | INSERT INTO big (id, blob) SELECT value, hex(randomblob(200)) \ |
| 217 | FROM (WITH RECURSIVE c(value) AS (SELECT 1 UNION ALL SELECT value+1 \ |
| 218 | FROM c WHERE value<500) SELECT value FROM c);", |
| 219 | ] |
| 220 | } |
| 221 | |
| 222 | /// Drives rustyriver's write path over `workload()`: opens a managed `Db`, an app |
| 223 | /// writer, applies each statement-group, then captures (`db.sync`) and uploads |
| 224 | /// (`replica.sync`) it. Leaves a replica tree at `replica_root` and the source DB |
| 225 | /// at `src_path`. Returns the final captured TXID. |
| 226 | async fn rustyriver_replicate(src_path: &Path, replica_root: &Path) -> TXID { |
| 227 | let db = Db::open(src_path).unwrap(); |
| 228 | let writer = open_writer(src_path); |
| 229 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 230 | let mut replica = Replica::new(db, client); |
| 231 | |
| 232 | for sql in workload() { |
| 233 | writer.execute_batch(sql).unwrap(); |
| 234 | replica.db_mut().unwrap().sync().unwrap(); |
| 235 | replica.sync().await.unwrap(); |
| 236 | } |
| 237 | |
| 238 | let pos = replica.db_mut().unwrap().pos().unwrap(); |
| 239 | assert!( |
| 240 | pos.txid.0 >= workload().len() as u64, |
| 241 | "expected at least {} captured TXIDs, got {}", |
| 242 | workload().len(), |
| 243 | pos.txid |
| 244 | ); |
| 245 | |
| 246 | // Clean shutdown so the source WAL is released before the real binary or the |
| 247 | // oracle reads the source file. |
| 248 | let db = replica.into_db().unwrap(); |
| 249 | db.close().unwrap(); |
| 250 | drop(writer); |
| 251 | pos.txid |
| 252 | } |
| 253 | |
| 254 | /// Drives the REAL binary's write path over `workload()`: seeds WAL mode, then for |
| 255 | /// each statement-group writes via plain `sqlite3` and runs `litestream replicate |
| 256 | /// -once` to flush exactly one sync (no background timing races — the same |
| 257 | /// deterministic method `capture-golden.sh` uses). Leaves a replica tree at |
| 258 | /// `replica_root` and the source DB at `src_path`. |
| 259 | fn litestream_replicate(src_path: &Path, replica_root: &Path) { |
| 260 | // Seed WAL mode + the first statement-group on a plain connection, then take |
| 261 | // the initial snapshot. |
| 262 | let url = file_url(replica_root); |
| 263 | { |
| 264 | let c = open_writer(src_path); |
| 265 | c.execute_batch(workload()[0]).unwrap(); |
| 266 | } |
| 267 | run_litestream(&["replicate", "-once", &src_path.to_string_lossy(), &url]); |
| 268 | |
| 269 | for sql in &workload()[1..] { |
| 270 | { |
| 271 | let c = open_writer(src_path); |
| 272 | c.execute_batch(sql).unwrap(); |
| 273 | } |
| 274 | run_litestream(&["replicate", "-once", &src_path.to_string_lossy(), &url]); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | /// Runs `litestream <args...>`, asserting success and surfacing stderr on failure. |
| 279 | fn run_litestream(args: &[&str]) { |
| 280 | let out = Command::new(litestream_bin()) |
| 281 | .args(args) |
| 282 | .output() |
| 283 | .unwrap_or_else(|e| panic!("spawn litestream {args:?}: {e}")); |
| 284 | assert!( |
| 285 | out.status.success(), |
| 286 | "litestream {args:?} failed (status {:?}):\nstdout: {}\nstderr: {}", |
| 287 | out.status.code(), |
| 288 | String::from_utf8_lossy(&out.stdout), |
| 289 | String::from_utf8_lossy(&out.stderr), |
| 290 | ); |
| 291 | } |
| 292 | |
| 293 | /// Runs the real `litestream restore -o <out> <file-url>` for a replica tree. |
| 294 | fn litestream_restore(replica_root: &Path, out: &Path) { |
| 295 | let url = file_url(replica_root); |
| 296 | run_litestream(&["restore", "-o", &out.to_string_lossy(), &url]); |
| 297 | assert!(out.exists(), "litestream restore did not produce {out:?}"); |
| 298 | } |
| 299 | |
| 300 | // ───────────────────────────── D1 (write path) ───────────────────────────── |
| 301 | |
| 302 | /// **D1 — our write → real `litestream restore` → Oracle A vs source.** |
| 303 | /// |
| 304 | /// rustyriver replicates the workload into a file replica; the *real* binary |
| 305 | /// restores that tree; the restored DB must be logically identical to the source. |
| 306 | /// This is the load-bearing proof that rustyriver's LTX serializer is byte-format |
| 307 | /// compatible with upstream Litestream — if the real tool can read what we wrote, |
| 308 | /// our format is correct because the independent binary is the oracle. |
| 309 | #[tokio::test(flavor = "multi_thread")] |
| 310 | async fn d1_our_write_real_restore_oracle_a() { |
| 311 | if skip_if_tools_missing("d1_our_write_real_restore_oracle_a") { |
| 312 | return; |
| 313 | } |
| 314 | |
| 315 | let dir = tempfile::tempdir().unwrap(); |
| 316 | let src = dir.path().join("source.db"); |
| 317 | let replica_root = dir.path().join("replica"); |
| 318 | let restored = dir.path().join("restored-by-litestream.db"); |
| 319 | |
| 320 | // 1. rustyriver writes the replica. |
| 321 | rustyriver_replicate(&src, &replica_root).await; |
| 322 | |
| 323 | // 2. The REAL binary restores our tree. |
| 324 | litestream_restore(&replica_root, &restored); |
| 325 | |
| 326 | // 3. Oracle A: real-restored == source. |
| 327 | db_equal("A", &src, &restored) |
| 328 | .expect("D1: real `litestream restore` of our replica must equal the source (Oracle A)"); |
| 329 | } |
| 330 | |
| 331 | // ──────────────────────────── D2 (restore path) ──────────────────────────── |
| 332 | |
| 333 | /// **D2 — real `litestream replicate` → our restore → Oracle A vs source.** |
| 334 | /// |
| 335 | /// The real binary replicates the workload; rustyriver restores that tree; the |
| 336 | /// restored DB must be logically identical to the source. Proves our LTX *reader* |
| 337 | /// + restore algorithm correctly consume real-Litestream-produced bytes. |
| 338 | #[tokio::test(flavor = "multi_thread")] |
| 339 | async fn d2_real_write_our_restore_oracle_a() { |
| 340 | if skip_if_tools_missing("d2_real_write_our_restore_oracle_a") { |
| 341 | return; |
| 342 | } |
| 343 | |
| 344 | let dir = tempfile::tempdir().unwrap(); |
| 345 | let src = dir.path().join("source.db"); |
| 346 | let replica_root = dir.path().join("replica"); |
| 347 | let restored = dir.path().join("restored-by-rustyriver.db"); |
| 348 | |
| 349 | // 1. The REAL binary writes the replica. |
| 350 | litestream_replicate(&src, &replica_root); |
| 351 | |
| 352 | // 2. rustyriver restores it (client-only restore; no Db needed). |
| 353 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 354 | replica::restore(&client, &restored, TXID(0)) |
| 355 | .await |
| 356 | .expect("D2: rustyriver restore of a real-Litestream replica"); |
| 357 | |
| 358 | // 3. Oracle A: our-restored == source. |
| 359 | db_equal("A", &src, &restored) |
| 360 | .expect("D2: our restore of a real `litestream` replica must equal the source (Oracle A)"); |
| 361 | } |
| 362 | |
| 363 | // ─────────────────────────── D3 (format cross-check) ─────────────────────── |
| 364 | |
| 365 | /// **D3 (over a rustyriver-written replica) — both tools restore the SAME tree → |
| 366 | /// byte-identical (Oracle B).** |
| 367 | /// |
| 368 | /// rustyriver writes the replica, then BOTH rustyriver and the real binary restore |
| 369 | /// it; after a TRUNCATE checkpoint the two output main-DB files must be |
| 370 | /// byte-for-byte identical. Because both restorers replay the *same* page images, |
| 371 | /// any byte difference is pure format/restore-algorithm divergence — the most |
| 372 | /// sensitive format-fidelity check (Risk R-1/R-2). This direction additionally |
| 373 | /// proves our *writer* emits page images the real decoder reconstructs bit-exactly. |
| 374 | #[tokio::test(flavor = "multi_thread")] |
| 375 | async fn d3_byte_identical_over_our_replica() { |
| 376 | if skip_if_tools_missing("d3_byte_identical_over_our_replica") { |
| 377 | return; |
| 378 | } |
| 379 | |
| 380 | let dir = tempfile::tempdir().unwrap(); |
| 381 | let src = dir.path().join("source.db"); |
| 382 | let replica_root = dir.path().join("replica"); |
| 383 | let ours = dir.path().join("ours.db"); |
| 384 | let theirs = dir.path().join("theirs.db"); |
| 385 | |
| 386 | // rustyriver writes the replica. |
| 387 | rustyriver_replicate(&src, &replica_root).await; |
| 388 | |
| 389 | // Our restore. |
| 390 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 391 | replica::restore(&client, &ours, TXID(0)) |
| 392 | .await |
| 393 | .expect("D3: our restore of our replica"); |
| 394 | |
| 395 | // The real binary's restore of the SAME tree. |
| 396 | litestream_restore(&replica_root, &theirs); |
| 397 | |
| 398 | // Oracle B: byte-identical main DB files after a TRUNCATE checkpoint. |
| 399 | db_equal("B", &theirs, &ours).expect( |
| 400 | "D3: our restore and `litestream restore` of our replica must be byte-identical (Oracle B)", |
| 401 | ); |
| 402 | } |
| 403 | |
| 404 | /// **D3 (over a real-Litestream-written replica) — both tools restore the SAME |
| 405 | /// tree → byte-identical (Oracle B).** |
| 406 | /// |
| 407 | /// The mirror of `d3_byte_identical_over_our_replica`: the real binary writes the |
| 408 | /// replica, then both tools restore it, and the outputs must be byte-identical. |
| 409 | /// Running D3 in both write-directions catches an asymmetry where one tool's |
| 410 | /// *writer* and the other's *reader* happen to agree only on self-produced bytes. |
| 411 | #[tokio::test(flavor = "multi_thread")] |
| 412 | async fn d3_byte_identical_over_real_replica() { |
| 413 | if skip_if_tools_missing("d3_byte_identical_over_real_replica") { |
| 414 | return; |
| 415 | } |
| 416 | |
| 417 | let dir = tempfile::tempdir().unwrap(); |
| 418 | let src = dir.path().join("source.db"); |
| 419 | let replica_root = dir.path().join("replica"); |
| 420 | let ours = dir.path().join("ours.db"); |
| 421 | let theirs = dir.path().join("theirs.db"); |
| 422 | |
| 423 | // The real binary writes the replica. |
| 424 | litestream_replicate(&src, &replica_root); |
| 425 | |
| 426 | // Our restore. |
| 427 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 428 | replica::restore(&client, &ours, TXID(0)) |
| 429 | .await |
| 430 | .expect("D3: our restore of a real replica"); |
| 431 | |
| 432 | // The real binary's restore of the SAME tree. |
| 433 | litestream_restore(&replica_root, &theirs); |
| 434 | |
| 435 | // Oracle B: byte-identical main DB files after a TRUNCATE checkpoint. |
| 436 | db_equal("B", &theirs, &ours).expect( |
| 437 | "D3: our restore and `litestream restore` of a real replica must be byte-identical (Oracle B)", |
| 438 | ); |
| 439 | } |
| 440 | |
| 441 | /// **D2 at a TARGET TXID — real write → our point-in-time restore → Oracle A.** |
| 442 | /// |
| 443 | /// Exercises the `-txid`-equivalent restore path against real-Litestream bytes: |
| 444 | /// the real binary replicates the full workload, rustyriver restores up to an |
| 445 | /// intermediate TXID, and the result must equal what the *real* binary restores at |
| 446 | /// that same `-txid`. Both restorers consume the identical real replica, so this |
| 447 | /// confirms our `calc_restore_plan` selects the same chain the real tool does for |
| 448 | /// a point-in-time target. (Uses Oracle A because a partial restore stops at a |
| 449 | /// mid-stream TXID; the comparison is real-vs-ours at the same target.) |
| 450 | #[tokio::test(flavor = "multi_thread")] |
| 451 | async fn d2_real_write_our_restore_at_target_txid() { |
| 452 | if skip_if_tools_missing("d2_real_write_our_restore_at_target_txid") { |
| 453 | return; |
| 454 | } |
| 455 | |
| 456 | let dir = tempfile::tempdir().unwrap(); |
| 457 | let src = dir.path().join("source.db"); |
| 458 | let replica_root = dir.path().join("replica"); |
| 459 | let ours = dir.path().join("ours-at-txid.db"); |
| 460 | let theirs = dir.path().join("theirs-at-txid.db"); |
| 461 | |
| 462 | // The real binary writes the full workload. |
| 463 | litestream_replicate(&src, &replica_root); |
| 464 | |
| 465 | // Pick an intermediate target: the count of statement-groups gives the max |
| 466 | // TXID; restore to roughly the middle of the chain. |
| 467 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 468 | let files = { |
| 469 | use celld_ltx::client::ReplicaClient; |
| 470 | client.ltx_files(0, TXID(0)).await.unwrap() |
| 471 | }; |
| 472 | let max_txid = files.iter().map(|f| f.max_txid.0).max().unwrap(); |
| 473 | assert!( |
| 474 | max_txid >= 4, |
| 475 | "need a multi-file chain (got max {max_txid})" |
| 476 | ); |
| 477 | let target = TXID(max_txid - 2); // a mid-stream point-in-time target |
| 478 | |
| 479 | // Our restore up to `target`. |
| 480 | replica::restore(&client, &ours, target) |
| 481 | .await |
| 482 | .expect("D2(txid): our restore to target"); |
| 483 | |
| 484 | // The real binary's restore up to the same `-txid`. |
| 485 | let url = file_url(&replica_root); |
| 486 | let txid_hex = format!("{:016x}", target.0); |
| 487 | run_litestream(&[ |
| 488 | "restore", |
| 489 | "-txid", |
| 490 | &txid_hex, |
| 491 | "-o", |
| 492 | &theirs.to_string_lossy(), |
| 493 | &url, |
| 494 | ]); |
| 495 | assert!(theirs.exists(), "litestream restore -txid produced no file"); |
| 496 | |
| 497 | // Oracle A: our point-in-time restore == the real tool's at the same TXID. |
| 498 | db_equal("A", &theirs, &ours).expect( |
| 499 | "D2(txid): our restore@target must equal real `litestream restore -txid` at the same TXID (Oracle A)", |
| 500 | ); |
| 501 | } |
| 502 | |
| 503 | // ─────────────────────── D4 (compaction write path) ─────────────────────── |
| 504 | |
| 505 | /// Reads the raw bytes of one published LTX object from a file replica tree. |
| 506 | fn read_replica_object(replica_root: &Path, info: &celld_ltx::FileInfo) -> Vec<u8> { |
| 507 | let path = ltx_file_path( |
| 508 | &replica_root.to_string_lossy(), |
| 509 | info.level as u32, |
| 510 | info.min_txid, |
| 511 | info.max_txid, |
| 512 | ); |
| 513 | std::fs::read(path).expect("read the published LTX object") |
| 514 | } |
| 515 | |
| 516 | /// **D4 — our L1 compaction → real `litestream restore` → Oracle A vs source.** |
| 517 | /// |
| 518 | /// D1 covers the L0 writer, and that writer still emits the pre-v0.5.2 frame |
| 519 | /// representation. The compactor emits the v0.5.2 block representation instead, |
| 520 | /// and until this case nothing made a real reader look at one: the crate |
| 521 | /// compared its encoder output with bytes from Go, then decoded its own |
| 522 | /// compaction output with its own decoder. "Litestream v0.5.16 reads our block |
| 523 | /// files" was therefore a claim and not a test, and the compaction scheduler is |
| 524 | /// on by default, so the claim is load-bearing. |
| 525 | /// |
| 526 | /// The replica deliberately keeps both representations. One L1 object covers a |
| 527 | /// prefix of the L0 objects and the remaining L0 objects cover the tail, so the |
| 528 | /// real binary must interleave a block file with frame files. `CalcRestorePlan` |
| 529 | /// takes the file that extends the longest contiguous TXID range, so the plan |
| 530 | /// prefers the L1 object over the L0 objects it covers. |
| 531 | #[tokio::test(flavor = "multi_thread")] |
| 532 | async fn d4_our_compaction_real_restore_oracle_a() { |
| 533 | if skip_if_tools_missing("d4_our_compaction_real_restore_oracle_a") { |
| 534 | return; |
| 535 | } |
| 536 | |
| 537 | let dir = tempfile::tempdir().unwrap(); |
| 538 | let src = dir.path().join("source.db"); |
| 539 | let replica_root = dir.path().join("replica"); |
| 540 | let restored = dir.path().join("restored-by-litestream.db"); |
| 541 | |
| 542 | // 1. rustyriver writes the L0 tree. |
| 543 | let max_txid = rustyriver_replicate(&src, &replica_root).await; |
| 544 | |
| 545 | // 2. rustyriver compacts a PREFIX of that tree into one L1 object. The |
| 546 | // limit leaves a tail at L0 on purpose, so the restore plan has to mix |
| 547 | // the two page representations rather than read the L1 object alone. |
| 548 | const PREFIX_FILES: usize = 4; |
| 549 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 550 | let output = ReplicaCompactor::new(&client) |
| 551 | .with_limits(PREFIX_FILES, u64::MAX) |
| 552 | .compact(1) |
| 553 | .await |
| 554 | .expect("compact L0 into L1") |
| 555 | .expect("the L0 level must hold objects to compact"); |
| 556 | assert_eq!(output.info.level, 1, "the destination level must be L1"); |
| 557 | assert!( |
| 558 | output.info.max_txid < max_txid, |
| 559 | "the L0 tail must survive the compaction so the plan mixes representations: \ |
| 560 | L1 covers up to {}, the L0 tree reaches {max_txid}", |
| 561 | output.info.max_txid |
| 562 | ); |
| 563 | |
| 564 | // 3. The published object must really carry the v0.5.2 block layout. |
| 565 | // Without this the case passes even if the compactor silently falls back |
| 566 | // to the frame representation, which is the very thing D4 exists to |
| 567 | // prove a real reader accepts. The first page header follows the file |
| 568 | // header; its flags carry the compressed-size prefix bit. |
| 569 | let published = read_replica_object(&replica_root, &output.info); |
| 570 | let first_page_flags = |
| 571 | u16::from_be_bytes([published[HEADER_SIZE + 4], published[HEADER_SIZE + 5]]); |
| 572 | assert_eq!( |
| 573 | first_page_flags & PAGE_HEADER_FLAG_SIZE, |
| 574 | PAGE_HEADER_FLAG_SIZE, |
| 575 | "the compactor must publish the v0.5.2 block representation, not frames" |
| 576 | ); |
| 577 | |
| 578 | // 4. The REAL binary restores the mixed tree. |
| 579 | litestream_restore(&replica_root, &restored); |
| 580 | |
| 581 | // 5. Oracle A: real-restored == source. |
| 582 | db_equal("A", &src, &restored).expect( |
| 583 | "D4: real `litestream restore` over our compacted L1 object must equal the source (Oracle A)", |
| 584 | ); |
| 585 | } |