Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/faults_inject.rs
441 lines · 16.2 KBRaw History
1// This integration test damages and inspects fixture files by design.
2#![allow(clippy::disallowed_methods)]
3
4//! faults_inject — T14: fault injection on the replica, then restore.
5//!
6//! The contract under test is that, when the replica is
7//! damaged — a **truncated LTX file**, an **empty (partial) upload**, **corrupt
8//! bytes**, or **missing/missed frames** (a deleted mid-chain L0 file) — a
9//! restore must *always* either
10//! * yield a **valid SQLite database at a valid TXID ≤ the last durable TXID**, or
11//! * fail with a **clean error**.
12//!
13//! In every case it must **never panic** and never produce a corrupt output
14//! database.
15//!
16//! Two of the cases are direct ports of upstream `TestReplica_Restore_InvalidFileSize`
17//! (replica_test.go:797-858): an empty snapshot file and a sub-header-sized
18//! ("truncated") snapshot file must both make `Restore` fail with an
19//! "invalid ltx file" error. The rest inject byte-level corruption and chain gaps
20//! against a real replicated L0 chain and assert the recovery contract, using the
21//! **Oracle A** (`scripts/db_equal.sh A`) where a successful restore is expected.
22//!
23//! The fault-injection cases that do not need the oracle run unconditionally
24//! (they assert error/typing/no-panic); the recovery cases that compare DB
25//! contents self-skip (never fail) when `sqlite3` is not on PATH.
26
27use celld_ltx::client::file::FileReplicaClient;
28use celld_ltx::client::ReplicaClient;
29use celld_ltx::db::Db;
30use celld_ltx::ltx::{self, FileInfo};
31use celld_ltx::replica::{self, Replica, SNAPSHOT_LEVEL};
32use celld_ltx::{ltx_file_path, Error, TXID};
33use rusqlite::Connection;
34use std::path::{Path, PathBuf};
35use std::process::Command;
36
37// ── oracle / env helpers ────────────────────────────────────────────────────
38
39fn db_equal_script() -> String {
40 format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR"))
41}
42
43fn db_equal_a(a: &Path, b: &Path) -> Result<(), String> {
44 let out = Command::new("bash")
45 .arg(db_equal_script())
46 .arg("A")
47 .arg(a)
48 .arg(b)
49 .output()
50 .map_err(|e| format!("spawn db_equal.sh: {e}"))?;
51 if out.status.success() {
52 Ok(())
53 } else {
54 Err(format!(
55 "db_equal A failed:\nstdout: {}\nstderr: {}",
56 String::from_utf8_lossy(&out.stdout),
57 String::from_utf8_lossy(&out.stderr),
58 ))
59 }
60}
61
62fn has_bin(bin: &str) -> bool {
63 Command::new(bin)
64 .arg("--help")
65 .output()
66 .map(|o| o.status.success() || o.status.code().is_some())
67 .unwrap_or(false)
68}
69
70fn open_writer(path: &Path) -> Connection {
71 let c = Connection::open(path).unwrap();
72 c.busy_timeout(std::time::Duration::from_secs(5)).unwrap();
73 let mode: String = c
74 .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0))
75 .unwrap();
76 assert_eq!(mode, "wal");
77 c
78}
79
80/// True if the restored file at `path` is a valid SQLite database (opens and
81/// passes `PRAGMA integrity_check`). Used to assert the "valid DB" half of the
82/// contract directly in-process (no sqlite3 binary needed).
83fn restored_db_is_valid(path: &Path) -> bool {
84 let Ok(conn) = Connection::open(path) else {
85 return false;
86 };
87 match conn.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0)) {
88 Ok(s) => s == "ok",
89 Err(_) => false,
90 }
91}
92
93/// Returns the user-table row count of a restored DB (asserts a non-trivial DB).
94fn count_rows(path: &Path, table: &str) -> i64 {
95 let conn = Connection::open(path).unwrap();
96 conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))
97 .unwrap()
98}
99
100// ── a real replicated L0 chain to damage ────────────────────────────────────
101
102/// Holds a TempDir-rooted replica with a known-good L0 chain plus the
103/// point-in-time `VACUUM INTO` snapshot taken at `safe_txid` (a TXID strictly
104/// before the tail we will damage).
105struct Fixture {
106 _dir: tempfile::TempDir,
107 replica_root: String,
108 /// Database position (TXID) after all writes — the last durable TXID.
109 last_txid: TXID,
110 /// A safe earlier TXID whose tail we keep intact for point-in-time recovery.
111 safe_txid: TXID,
112 /// VACUUM INTO snapshot of the source exactly at `safe_txid`.
113 safe_snapshot: PathBuf,
114}
115
116/// Builds a real replicated database: a `t(id,v)` table with several
117/// transactions, each captured + uploaded through the file client. Captures a
118/// point-in-time snapshot of the source at `safe_txid` for later comparison.
119async fn build_fixture() -> Fixture {
120 let dir = tempfile::tempdir().unwrap();
121 let src_path = dir.path().join("source.db");
122 let replica_root = dir.path().join("replica").to_string_lossy().into_owned();
123 let safe_snapshot = dir.path().join("safe.db");
124
125 let db = Db::open(&src_path).unwrap();
126 let writer = open_writer(&src_path);
127 let client = FileReplicaClient::new(replica_root.clone());
128 let mut replica = Replica::new(db, client);
129
130 macro_rules! step {
131 ($sql:expr) => {{
132 writer.execute_batch($sql).unwrap();
133 replica.db_mut().unwrap().sync().unwrap();
134 replica.sync().await.unwrap();
135 }};
136 }
137
138 step!("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)");
139 step!("INSERT INTO t (v) VALUES ('one'),('two')");
140 step!("INSERT INTO t (v) VALUES ('three')");
141 // Snapshot the source as-of this point — the "safe" recovery target.
142 let safe_txid = replica.db_mut().unwrap().pos().unwrap().txid;
143 writer
144 .execute(
145 "VACUUM INTO ?1",
146 [safe_snapshot.to_string_lossy().to_string()],
147 )
148 .unwrap();
149
150 // More transactions whose tail we will damage.
151 step!("UPDATE t SET v='TWO' WHERE id=2");
152 step!("INSERT INTO t (v) VALUES ('four'),('five')");
153 step!("DELETE FROM t WHERE id=1");
154
155 let last_txid = replica.db_mut().unwrap().pos().unwrap().txid;
156 assert!(
157 last_txid > safe_txid,
158 "tail TXIDs exist past the safe point"
159 );
160
161 drop(replica);
162 drop(writer);
163
164 Fixture {
165 _dir: dir,
166 replica_root,
167 last_txid,
168 safe_txid,
169 safe_snapshot,
170 }
171}
172
173/// On-disk path of an L0 file in a fixture replica.
174fn l0_path(root: &str, txid: TXID) -> String {
175 ltx_file_path(root, 0, txid, txid)
176}
177
178// ── Ported: TestReplica_Restore_InvalidFileSize (replica_test.go:797-858) ────
179
180/// A `ReplicaClient` whose snapshot listing reports a single file at
181/// `SNAPSHOT_LEVEL` with a caller-chosen `size`, mirroring the upstream
182/// `mock.ReplicaClient` used by `TestReplica_Restore_InvalidFileSize`. All other
183/// levels are empty. `open_ltx_file` returns whatever bytes were stored (used
184/// only by the empty-file case, which never reaches a read because the size
185/// guard fires first).
186struct BadSizeClient {
187 size: i64,
188}
189
190#[async_trait::async_trait]
191impl ReplicaClient for BadSizeClient {
192 async fn ltx_files(&self, level: i32, _seek: TXID) -> celld_ltx::Result<Vec<FileInfo>> {
193 if level == SNAPSHOT_LEVEL {
194 Ok(vec![FileInfo {
195 level: SNAPSHOT_LEVEL,
196 min_txid: TXID(1),
197 max_txid: TXID(10),
198 size: self.size,
199 ..Default::default()
200 }])
201 } else {
202 Ok(Vec::new())
203 }
204 }
205 async fn open_ltx_file(
206 &self,
207 _level: i32,
208 _min: TXID,
209 _max: TXID,
210 ) -> celld_ltx::Result<Vec<u8>> {
211 Ok(Vec::new())
212 }
213 async fn write_ltx_file(
214 &self,
215 level: i32,
216 min_txid: TXID,
217 max_txid: TXID,
218 data: &[u8],
219 ) -> celld_ltx::Result<FileInfo> {
220 Ok(FileInfo {
221 level,
222 min_txid,
223 max_txid,
224 size: data.len() as i64,
225 ..Default::default()
226 })
227 }
228 async fn delete_ltx_files(&self, _files: &[FileInfo]) -> celld_ltx::Result<()> {
229 Ok(())
230 }
231 async fn delete_all(&self) -> celld_ltx::Result<()> {
232 Ok(())
233 }
234}
235
236/// Port of `TestReplica_Restore_InvalidFileSize/EmptyFile`: a snapshot file with
237/// `Size == 0` must make restore fail with an "invalid ltx file" error.
238#[tokio::test]
239async fn restore_empty_snapshot_file_errors() {
240 let dir = tempfile::tempdir().unwrap();
241 let out = dir.path().join("restored.db");
242
243 let client = BadSizeClient { size: 0 };
244 let err = replica::restore(&client, &out, TXID(0))
245 .await
246 .expect_err("empty file must be rejected");
247 assert!(
248 err.to_string().contains("invalid ltx file"),
249 "expected 'invalid ltx file', got: {err}"
250 );
251 assert!(
252 !out.exists(),
253 "no output DB is produced on a rejected restore"
254 );
255}
256
257/// Port of `TestReplica_Restore_InvalidFileSize/TruncatedFile`: a snapshot file
258/// smaller than the LTX header (`Size == 50 < HEADER_SIZE`) must make restore
259/// fail with an "invalid ltx file" error.
260#[tokio::test]
261async fn restore_truncated_snapshot_file_errors() {
262 // Precondition (compile-time): 50 is below the LTX header size, so the size
263 // guard — not a decode — is what rejects it. Matches the upstream mock's 50.
264 const _: () = assert!(50 < ltx::HEADER_SIZE);
265 let dir = tempfile::tempdir().unwrap();
266 let out = dir.path().join("restored.db");
267
268 let client = BadSizeClient { size: 50 };
269 let err = replica::restore(&client, &out, TXID(0))
270 .await
271 .expect_err("truncated file must be rejected");
272 assert!(
273 err.to_string().contains("invalid ltx file"),
274 "expected 'invalid ltx file', got: {err}"
275 );
276 assert!(
277 !out.exists(),
278 "no output DB is produced on a rejected restore"
279 );
280}
281
282// ── On-disk byte-level fault injection against a real chain ──────────────────
283
284/// CORRUPT BYTES in a mid-chain L0 file: a latest-state restore must fail via a
285/// checksum/corruption error (decode_file verifies every input), never panic,
286/// and never write a corrupt output DB.
287#[tokio::test(flavor = "multi_thread")]
288async fn corrupt_midchain_ltx_fails_cleanly() {
289 let fx = build_fixture().await;
290 let dir = tempfile::tempdir().unwrap();
291 let out = dir.path().join("restored.db");
292
293 // Flip a byte in the data region of the snapshot (TXID 1) file.
294 let victim = l0_path(&fx.replica_root, TXID(1));
295 let mut bytes = std::fs::read(&victim).unwrap();
296 let mid = ltx::HEADER_SIZE + (bytes.len() - ltx::HEADER_SIZE) / 2;
297 bytes[mid] ^= 0xFF;
298 std::fs::write(&victim, &bytes).unwrap();
299
300 let client = FileReplicaClient::new(fx.replica_root.clone());
301 let err = replica::restore(&client, &out, TXID(0))
302 .await
303 .expect_err("corrupt LTX must be rejected");
304 assert!(
305 matches!(
306 err,
307 Error::ChecksumMismatch | Error::LTXCorrupted | Error::Other(_)
308 ),
309 "corrupt LTX rejected with a clean error, got {err:?}"
310 );
311 // The atomic temp-rename means a failed restore leaves no output DB.
312 assert!(!out.exists(), "no corrupt output DB is produced");
313}
314
315/// TRUNCATED final upload (partial PUT): the newest L0 file is cut to below the
316/// LTX header size on disk. A latest restore must fail with "invalid ltx file",
317/// while a restore targeted at the last *intact* TXID still yields a valid DB at
318/// that TXID — the "valid DB at a TXID ≤ last durable" guarantee.
319#[tokio::test(flavor = "multi_thread")]
320async fn truncated_final_upload_recovers_to_prior_txid() {
321 let fx = build_fixture().await;
322 let dir = tempfile::tempdir().unwrap();
323
324 // Truncate the LAST L0 file to 40 bytes (< HEADER_SIZE): a partial upload.
325 let victim = l0_path(&fx.replica_root, fx.last_txid);
326 let orig = std::fs::read(&victim).unwrap();
327 assert!(orig.len() > 40);
328 std::fs::write(&victim, &orig[..40]).unwrap();
329
330 let client = FileReplicaClient::new(fx.replica_root.clone());
331
332 // 1) A latest restore must be rejected ("invalid ltx file"), never panic.
333 let out_latest = dir.path().join("latest.db");
334 let err = replica::restore(&client, &out_latest, TXID(0))
335 .await
336 .expect_err("a sub-header tail file must be rejected");
337 assert!(
338 err.to_string().contains("invalid ltx file"),
339 "expected 'invalid ltx file', got: {err}"
340 );
341 assert!(!out_latest.exists());
342
343 // 2) Restore to the last intact TXID (one before the damaged tail) → valid DB.
344 let target = TXID(fx.last_txid.0 - 1);
345 let out_prior = dir.path().join("prior.db");
346 replica::restore(&client, &out_prior, target)
347 .await
348 .expect("restore to the last intact TXID must succeed");
349 assert!(
350 restored_db_is_valid(&out_prior),
351 "restored DB at the prior TXID is a valid SQLite database"
352 );
353 assert!(count_rows(&out_prior, "t") >= 1, "restored DB has data");
354}
355
356/// MISSING / MISSED FRAMES: a mid-chain L0 file is deleted entirely (a dropped
357/// segment). A latest restore must fail cleanly (non-contiguous chain), and a
358/// restore targeted before the gap must still reproduce the point-in-time DB
359/// (Oracle A vs. the `VACUUM INTO` snapshot taken at `safe_txid`).
360#[tokio::test(flavor = "multi_thread")]
361async fn missing_midchain_segment_recovers_before_the_gap() {
362 let fx = build_fixture().await;
363 let dir = tempfile::tempdir().unwrap();
364
365 // Delete an L0 file in the damaged tail (right after the safe point), opening
366 // a gap in the chain.
367 let gap_txid = TXID(fx.safe_txid.0 + 1);
368 assert!(
369 gap_txid < fx.last_txid,
370 "the gap is strictly inside the tail"
371 );
372 std::fs::remove_file(l0_path(&fx.replica_root, gap_txid)).unwrap();
373
374 let client = FileReplicaClient::new(fx.replica_root.clone());
375
376 // 1) A latest restore must fail cleanly (the chain is non-contiguous) — never
377 // panic, never silently skip the gap.
378 let out_latest = dir.path().join("latest.db");
379 let res = replica::restore(&client, &out_latest, TXID(0)).await;
380 assert!(
381 res.is_err(),
382 "a latest restore across a chain gap must fail, got Ok"
383 );
384 assert!(!out_latest.exists(), "no output DB on a failed restore");
385
386 // 2) A restore targeted at the safe TXID (before the gap) still works.
387 if !has_bin("sqlite3") {
388 eprintln!("skipping the Oracle-A half: sqlite3 not on PATH");
389 return;
390 }
391 let out_safe = dir.path().join("safe_restored.db");
392 replica::restore(&client, &out_safe, fx.safe_txid)
393 .await
394 .expect("restore before the gap must succeed");
395 assert!(restored_db_is_valid(&out_safe), "valid DB before the gap");
396 db_equal_a(&fx.safe_snapshot, &out_safe)
397 .expect("Oracle A: restore@safe_txid == the point-in-time snapshot");
398}
399
400/// MISSING SNAPSHOT ANCHOR: deleting the very first L0 file (TXID 1, the snapshot
401/// anchor) must make even a latest restore fail cleanly (no anchor → no plan),
402/// never panic.
403#[tokio::test(flavor = "multi_thread")]
404async fn missing_snapshot_anchor_fails_cleanly() {
405 let fx = build_fixture().await;
406 let dir = tempfile::tempdir().unwrap();
407 let out = dir.path().join("restored.db");
408
409 std::fs::remove_file(l0_path(&fx.replica_root, TXID(1))).unwrap();
410
411 let client = FileReplicaClient::new(fx.replica_root.clone());
412 let res = replica::restore(&client, &out, TXID(0)).await;
413 assert!(
414 res.is_err(),
415 "restore without the snapshot anchor must fail, got Ok"
416 );
417 assert!(!out.exists(), "no output DB is produced");
418}
419
420/// EMPTY (zero-length) tail file on disk via the real file client: listing
421/// reports `size == 0`, so the restore size guard rejects it with
422/// "invalid ltx file" — the on-disk analog of the ported EmptyFile mock case.
423#[tokio::test(flavor = "multi_thread")]
424async fn empty_ondisk_tail_file_errors() {
425 let fx = build_fixture().await;
426 let dir = tempfile::tempdir().unwrap();
427 let out = dir.path().join("restored.db");
428
429 // Zero out the last L0 file in place.
430 std::fs::write(l0_path(&fx.replica_root, fx.last_txid), b"").unwrap();
431
432 let client = FileReplicaClient::new(fx.replica_root.clone());
433 let err = replica::restore(&client, &out, TXID(0))
434 .await
435 .expect_err("an empty tail file must be rejected");
436 assert!(
437 err.to_string().contains("invalid ltx file"),
438 "expected 'invalid ltx file', got: {err}"
439 );
440 assert!(!out.exists());
441}