| 1 | //! integration_file — the **G2 round-trip gate** (PLAN.md §6.4) against the |
| 2 | //! file `ReplicaClient`. |
| 3 | //! |
| 4 | //! Proves T10: open a fresh SQLite DB, apply several transactions, capture them |
| 5 | //! into L0 LTX files (the `Db` capture loop), replicate them to a file replica |
| 6 | //! (`Replica::sync` → `FileReplicaClient`), restore to a NEW path |
| 7 | //! (`celld_ltx::replica::restore`), and assert the restored DB equals the |
| 8 | //! source via **Oracle A** (`scripts/db_equal.sh A` — identical |
| 9 | //! `PRAGMA integrity_check` + schema + per-table content hash, PLAN.md §6.1). |
| 10 | //! |
| 11 | //! The source DB is written through an ordinary `rusqlite` connection (the |
| 12 | //! "application"); the managed `Db` holds the read lock and captures the WAL, |
| 13 | //! exactly as a host process would embed the library. A second test restores the |
| 14 | //! committed golden replica (captured from the real `litestream` binary) and |
| 15 | //! checks it against the **real `litestream restore`** output (a differential |
| 16 | //! anchor for the reader, prefiguring G3/D2) — skipped only if the binary or |
| 17 | //! `sqlite3` is absent from PATH. |
| 18 | |
| 19 | use rusqlite::Connection; |
| 20 | use celld_ltx::client::file::FileReplicaClient; |
| 21 | use celld_ltx::client::ReplicaClient; |
| 22 | use celld_ltx::db::Db; |
| 23 | use celld_ltx::replica::{self, Replica}; |
| 24 | use celld_ltx::TXID; |
| 25 | use std::path::Path; |
| 26 | use std::process::Command; |
| 27 | |
| 28 | /// Absolute path to the `db_equal.sh` oracle. |
| 29 | fn db_equal_script() -> String { |
| 30 | format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR")) |
| 31 | } |
| 32 | |
| 33 | /// Runs `db_equal.sh <mode> <a> <b>`; returns Ok(()) on exit 0, else the |
| 34 | /// captured stderr/stdout for the failure message. Requires `sqlite3` on PATH. |
| 35 | fn db_equal(mode: &str, a: &Path, b: &Path) -> Result<(), String> { |
| 36 | let out = Command::new("bash") |
| 37 | .arg(db_equal_script()) |
| 38 | .arg(mode) |
| 39 | .arg(a) |
| 40 | .arg(b) |
| 41 | .output() |
| 42 | .map_err(|e| format!("spawn db_equal.sh: {e}"))?; |
| 43 | if out.status.success() { |
| 44 | Ok(()) |
| 45 | } else { |
| 46 | Err(format!( |
| 47 | "db_equal {mode} failed:\nstdout: {}\nstderr: {}", |
| 48 | String::from_utf8_lossy(&out.stdout), |
| 49 | String::from_utf8_lossy(&out.stderr), |
| 50 | )) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | |
| 55 | /// The real binary under test: `$LITESTREAM_BIN`, or `litestream` on PATH. |
| 56 | /// The oracle is pinned to the v0.5 replica format (v0.5.11); a v0.3-era |
| 57 | /// binary knows nothing of LTX and fails as a baffling "no matching |
| 58 | /// backups found", so a wrong-era binary skips loudly instead. |
| 59 | fn litestream_bin() -> String { |
| 60 | std::env::var("LITESTREAM_BIN").unwrap_or_else(|_| "litestream".into()) |
| 61 | } |
| 62 | |
| 63 | /// True when the resolved binary exists AND speaks the pinned replica era. |
| 64 | fn litestream_usable(test: &str) -> bool { |
| 65 | let out = Command::new(litestream_bin()).arg("version").output(); |
| 66 | match out { |
| 67 | Err(_) => { |
| 68 | eprintln!( |
| 69 | "skipping {test}: `{}` not runnable; set LITESTREAM_BIN or \ |
| 70 | put litestream on PATH", |
| 71 | litestream_bin() |
| 72 | ); |
| 73 | false |
| 74 | } |
| 75 | Ok(o) => { |
| 76 | let v = String::from_utf8_lossy(&o.stdout).trim().to_string(); |
| 77 | if v.starts_with("v0.5") { |
| 78 | true |
| 79 | } else { |
| 80 | eprintln!( |
| 81 | "skipping {test}: litestream {v:?} is the wrong era \ |
| 82 | (pinned v0.5.11); point LITESTREAM_BIN at a v0.5 binary" |
| 83 | ); |
| 84 | false |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /// True if `bin` resolves on PATH. |
| 91 | fn has_bin(bin: &str) -> bool { |
| 92 | Command::new(bin) |
| 93 | .arg("--help") |
| 94 | .output() |
| 95 | .map(|o| o.status.success() || o.status.code().is_some()) |
| 96 | .unwrap_or(false) |
| 97 | } |
| 98 | |
| 99 | /// Opens an application writer connection in WAL mode (the analog of the host's |
| 100 | /// own SQLite handle writing alongside the managed `Db`). |
| 101 | fn open_writer(path: &Path) -> Connection { |
| 102 | let c = Connection::open(path).unwrap(); |
| 103 | c.busy_timeout(std::time::Duration::from_secs(5)).unwrap(); |
| 104 | let mode: String = c |
| 105 | .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0)) |
| 106 | .unwrap(); |
| 107 | assert_eq!(mode, "wal"); |
| 108 | c |
| 109 | } |
| 110 | |
| 111 | /// THE G2 GATE: open → write txns → capture → replicate (file) → restore → equal. |
| 112 | #[tokio::test(flavor = "multi_thread")] |
| 113 | async fn round_trip_file_client_reproduces_source() { |
| 114 | if !has_bin("sqlite3") { |
| 115 | eprintln!("skipping: sqlite3 not on PATH (required for the db_equal Oracle A)"); |
| 116 | return; |
| 117 | } |
| 118 | |
| 119 | let dir = tempfile::tempdir().unwrap(); |
| 120 | let src_path = dir.path().join("source.db"); |
| 121 | let replica_root = dir.path().join("replica"); |
| 122 | let restored_path = dir.path().join("restored.db"); |
| 123 | |
| 124 | // ── 1. Open the managed Db (takes the read lock) + an app writer conn. ── |
| 125 | let db = Db::open(&src_path).unwrap(); |
| 126 | let writer = open_writer(&src_path); |
| 127 | |
| 128 | // ── 2. Apply several transactions, capturing each into an L0 LTX file. ── |
| 129 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 130 | let mut replica = Replica::new(db, client); |
| 131 | |
| 132 | // Helper that runs SQL on the app connection, then drives the capture loop |
| 133 | // (db.sync) and the replica upload (replica.sync) — the SyncAndWait ordering |
| 134 | // (db.go:500-512). |
| 135 | macro_rules! commit_and_replicate { |
| 136 | ($sql:expr) => {{ |
| 137 | writer.execute_batch($sql).unwrap(); |
| 138 | replica.db_mut().unwrap().sync().unwrap(); |
| 139 | replica.sync().await.unwrap(); |
| 140 | }}; |
| 141 | } |
| 142 | |
| 143 | commit_and_replicate!("CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL)"); |
| 144 | commit_and_replicate!("INSERT INTO kv (k, v) VALUES ('a','1'),('b','2'),('c','3')"); |
| 145 | commit_and_replicate!("UPDATE kv SET v='updated' WHERE k='a'"); |
| 146 | commit_and_replicate!("INSERT INTO kv (k, v) VALUES ('d','4'),('e','5')"); |
| 147 | commit_and_replicate!("DELETE FROM kv WHERE k='b'"); |
| 148 | // A larger transaction to exercise multi-page WAL frames. |
| 149 | commit_and_replicate!( |
| 150 | "CREATE TABLE big (id INTEGER PRIMARY KEY, blob TEXT);\ |
| 151 | INSERT INTO big (id, blob) SELECT value, hex(randomblob(200)) \ |
| 152 | FROM (WITH RECURSIVE c(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM c WHERE value<500) SELECT value FROM c);" |
| 153 | ); |
| 154 | |
| 155 | // The replicated position now matches the database position. |
| 156 | let dpos = replica.db_mut().unwrap().pos().unwrap(); |
| 157 | assert_eq!(replica.pos().txid, dpos.txid, "replica caught up to the DB"); |
| 158 | assert!(dpos.txid.0 >= 6, "at least 6 transactions captured"); |
| 159 | |
| 160 | // Verify the replica tree actually holds the L0 files. |
| 161 | let files = replica.client.ltx_files(0, TXID(0), false).await.unwrap(); |
| 162 | assert!( |
| 163 | files.len() as u64 >= dpos.txid.0, |
| 164 | "every captured TXID is on the replica (got {} files, txid={})", |
| 165 | files.len(), |
| 166 | dpos.txid |
| 167 | ); |
| 168 | |
| 169 | // ── 3. Restore from the replica into a brand-new path. ── |
| 170 | replica.restore(&restored_path).await.expect("restore"); |
| 171 | assert!(restored_path.exists(), "restored DB file created"); |
| 172 | |
| 173 | // Drop the managed Db so the source WAL is released before the oracle reads |
| 174 | // it (the oracle checkpoints both DBs). |
| 175 | drop(replica); |
| 176 | drop(writer); |
| 177 | |
| 178 | // ── 4. Oracle A: restored DB is logically identical to the source. ── |
| 179 | db_equal("A", &src_path, &restored_path).expect("Oracle A: restored == source"); |
| 180 | } |
| 181 | |
| 182 | /// A second G2-style check at a TARGET TXID: restoring to an intermediate TXID |
| 183 | /// reproduces the database as it was at that transaction (point-in-time). |
| 184 | #[tokio::test(flavor = "multi_thread")] |
| 185 | async fn restore_to_target_txid_reproduces_point_in_time() { |
| 186 | if !has_bin("sqlite3") { |
| 187 | eprintln!("skipping: sqlite3 not on PATH"); |
| 188 | return; |
| 189 | } |
| 190 | |
| 191 | let dir = tempfile::tempdir().unwrap(); |
| 192 | let src_path = dir.path().join("source.db"); |
| 193 | let snapshot_path = dir.path().join("at_txid.db"); |
| 194 | let restored_path = dir.path().join("restored.db"); |
| 195 | let replica_root = dir.path().join("replica"); |
| 196 | |
| 197 | let db = Db::open(&src_path).unwrap(); |
| 198 | let writer = open_writer(&src_path); |
| 199 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 200 | let mut replica = Replica::new(db, client); |
| 201 | |
| 202 | macro_rules! step { |
| 203 | ($sql:expr) => {{ |
| 204 | writer.execute_batch($sql).unwrap(); |
| 205 | replica.db_mut().unwrap().sync().unwrap(); |
| 206 | replica.sync().await.unwrap(); |
| 207 | }}; |
| 208 | } |
| 209 | |
| 210 | step!("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)"); |
| 211 | step!("INSERT INTO t (v) VALUES ('one'),('two')"); |
| 212 | // Capture the database state at THIS point (the target TXID). |
| 213 | let target = replica.db_mut().unwrap().pos().unwrap().txid; |
| 214 | // Make a verbatim copy of the source DB as-of the target by checkpointing a |
| 215 | // fresh connection's view. Easiest: VACUUM INTO at this moment. |
| 216 | writer |
| 217 | .execute( |
| 218 | "VACUUM INTO ?1", |
| 219 | [snapshot_path.to_string_lossy().to_string()], |
| 220 | ) |
| 221 | .unwrap(); |
| 222 | |
| 223 | // Continue mutating after the snapshot point. |
| 224 | step!("UPDATE t SET v='TWO' WHERE id=2"); |
| 225 | step!("INSERT INTO t (v) VALUES ('three')"); |
| 226 | |
| 227 | // Restore at the target TXID into a new path. |
| 228 | replica::restore(&replica.client, &restored_path, target) |
| 229 | .await |
| 230 | .expect("restore at target txid"); |
| 231 | |
| 232 | drop(replica); |
| 233 | drop(writer); |
| 234 | |
| 235 | // The restored-at-target DB equals the VACUUM INTO snapshot taken at that |
| 236 | // exact point (Oracle A). |
| 237 | db_equal("A", &snapshot_path, &restored_path) |
| 238 | .expect("Oracle A: restore@target == point-in-time snapshot"); |
| 239 | } |
| 240 | |
| 241 | /// Differential anchor for the RESTORE READER (prefigures G3/D2): restoring the |
| 242 | /// committed golden replica (real-`litestream`-produced bytes) must yield a DB |
| 243 | /// logically identical to what the real `litestream restore` produces from the |
| 244 | /// same tree. Skipped if `litestream`/`sqlite3` are not on PATH. |
| 245 | #[tokio::test(flavor = "multi_thread")] |
| 246 | async fn restore_golden_replica_matches_real_litestream() { |
| 247 | if !has_bin("sqlite3") { |
| 248 | eprintln!("skipping: sqlite3 not on PATH"); |
| 249 | return; |
| 250 | } |
| 251 | if !litestream_usable("restore_golden_replica_matches_real_litestream") { |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | let golden_root = format!( |
| 256 | "{}/tests/fixtures/golden/replica", |
| 257 | env!("CARGO_MANIFEST_DIR") |
| 258 | ); |
| 259 | |
| 260 | let dir = tempfile::tempdir().unwrap(); |
| 261 | let ours = dir.path().join("ours.db"); |
| 262 | let theirs = dir.path().join("theirs.db"); |
| 263 | |
| 264 | // Our restore. |
| 265 | let client = FileReplicaClient::new(golden_root.clone()); |
| 266 | replica::restore(&client, &ours, TXID(0)) |
| 267 | .await |
| 268 | .expect("our restore of the golden replica"); |
| 269 | |
| 270 | // Real litestream's restore of the same tree. |
| 271 | let status = Command::new(litestream_bin()) |
| 272 | .arg("restore") |
| 273 | .arg("-o") |
| 274 | .arg(&theirs) |
| 275 | .arg(format!("file://{golden_root}")) |
| 276 | .status() |
| 277 | .expect("spawn litestream restore"); |
| 278 | assert!(status.success(), "litestream restore failed"); |
| 279 | |
| 280 | // Oracle A: both restores are logically identical. |
| 281 | db_equal("A", &theirs, &ours).expect("Oracle A: our restore == litestream restore"); |
| 282 | } |