Diffinery

homeflare/celldpublic

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