Diffinery

homeflare/celldpublic

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