Diffinery

homeflare/celldpublic

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