| 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 | |
| 24 | use celld_ltx::client::file::FileReplicaClient; |
| 25 | use celld_ltx::client::ReplicaClient; |
| 26 | use celld_ltx::db::Db; |
| 27 | use celld_ltx::ltx::{self, FileInfo}; |
| 28 | use celld_ltx::replica::{self, Replica, SNAPSHOT_LEVEL}; |
| 29 | use celld_ltx::{ltx_file_path, Error, TXID}; |
| 30 | use rusqlite::Connection; |
| 31 | use std::path::{Path, PathBuf}; |
| 32 | use std::process::Command; |
| 33 | |
| 34 | // ── oracle / env helpers ──────────────────────────────────────────────────── |
| 35 | |
| 36 | fn db_equal_script() -> String { |
| 37 | format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR")) |
| 38 | } |
| 39 | |
| 40 | fn 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 | |
| 59 | fn 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 | |
| 67 | fn 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). |
| 80 | fn 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). |
| 91 | fn 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). |
| 102 | struct 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. |
| 116 | async 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. |
| 171 | fn 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). |
| 183 | struct BadSizeClient { |
| 184 | size: i64, |
| 185 | } |
| 186 | |
| 187 | #[async_trait::async_trait] |
| 188 | impl ReplicaClient for BadSizeClient { |
| 189 | fn type_name(&self) -> &str { |
| 190 | "bad-size-mock" |
| 191 | } |
| 192 | async fn ltx_files( |
| 193 | &self, |
| 194 | level: i32, |
| 195 | _seek: TXID, |
| 196 | _md: bool, |
| 197 | ) -> celld_ltx::Result<Vec<FileInfo>> { |
| 198 | if level == SNAPSHOT_LEVEL { |
| 199 | Ok(vec![FileInfo { |
| 200 | level: SNAPSHOT_LEVEL, |
| 201 | min_txid: TXID(1), |
| 202 | max_txid: TXID(10), |
| 203 | size: self.size, |
| 204 | ..Default::default() |
| 205 | }]) |
| 206 | } else { |
| 207 | Ok(Vec::new()) |
| 208 | } |
| 209 | } |
| 210 | async fn open_ltx_file( |
| 211 | &self, |
| 212 | _level: i32, |
| 213 | _min: TXID, |
| 214 | _max: TXID, |
| 215 | _off: i64, |
| 216 | _size: i64, |
| 217 | ) -> celld_ltx::Result<Vec<u8>> { |
| 218 | Ok(Vec::new()) |
| 219 | } |
| 220 | async fn write_ltx_file( |
| 221 | &self, |
| 222 | level: i32, |
| 223 | min_txid: TXID, |
| 224 | max_txid: TXID, |
| 225 | data: &[u8], |
| 226 | ) -> celld_ltx::Result<FileInfo> { |
| 227 | Ok(FileInfo { |
| 228 | level, |
| 229 | min_txid, |
| 230 | max_txid, |
| 231 | size: data.len() as i64, |
| 232 | ..Default::default() |
| 233 | }) |
| 234 | } |
| 235 | async fn delete_ltx_files(&self, _files: &[FileInfo]) -> celld_ltx::Result<()> { |
| 236 | Ok(()) |
| 237 | } |
| 238 | async fn delete_all(&self) -> celld_ltx::Result<()> { |
| 239 | Ok(()) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// Port of `TestReplica_Restore_InvalidFileSize/EmptyFile`: a snapshot file with |
| 244 | /// `Size == 0` must make restore fail with an "invalid ltx file" error. |
| 245 | #[tokio::test] |
| 246 | async fn restore_empty_snapshot_file_errors() { |
| 247 | let dir = tempfile::tempdir().unwrap(); |
| 248 | let out = dir.path().join("restored.db"); |
| 249 | |
| 250 | let client = BadSizeClient { size: 0 }; |
| 251 | let err = replica::restore(&client, &out, TXID(0)) |
| 252 | .await |
| 253 | .expect_err("empty file must be rejected"); |
| 254 | assert!( |
| 255 | err.to_string().contains("invalid ltx file"), |
| 256 | "expected 'invalid ltx file', got: {err}" |
| 257 | ); |
| 258 | assert!( |
| 259 | !out.exists(), |
| 260 | "no output DB is produced on a rejected restore" |
| 261 | ); |
| 262 | } |
| 263 | |
| 264 | /// Port of `TestReplica_Restore_InvalidFileSize/TruncatedFile`: a snapshot file |
| 265 | /// smaller than the LTX header (`Size == 50 < HEADER_SIZE`) must make restore |
| 266 | /// fail with an "invalid ltx file" error. |
| 267 | #[tokio::test] |
| 268 | async fn restore_truncated_snapshot_file_errors() { |
| 269 | // Precondition (compile-time): 50 is below the LTX header size, so the size |
| 270 | // guard — not a decode — is what rejects it. Matches the upstream mock's 50. |
| 271 | const _: () = assert!(50 < ltx::HEADER_SIZE); |
| 272 | let dir = tempfile::tempdir().unwrap(); |
| 273 | let out = dir.path().join("restored.db"); |
| 274 | |
| 275 | let client = BadSizeClient { size: 50 }; |
| 276 | let err = replica::restore(&client, &out, TXID(0)) |
| 277 | .await |
| 278 | .expect_err("truncated file must be rejected"); |
| 279 | assert!( |
| 280 | err.to_string().contains("invalid ltx file"), |
| 281 | "expected 'invalid ltx file', got: {err}" |
| 282 | ); |
| 283 | assert!( |
| 284 | !out.exists(), |
| 285 | "no output DB is produced on a rejected restore" |
| 286 | ); |
| 287 | } |
| 288 | |
| 289 | // ── On-disk byte-level fault injection against a real chain ────────────────── |
| 290 | |
| 291 | /// CORRUPT BYTES in a mid-chain L0 file: a latest-state restore must fail via a |
| 292 | /// checksum/corruption error (decode_file verifies every input), never panic, |
| 293 | /// and never write a corrupt output DB. |
| 294 | #[tokio::test(flavor = "multi_thread")] |
| 295 | async fn corrupt_midchain_ltx_fails_cleanly() { |
| 296 | let fx = build_fixture().await; |
| 297 | let dir = tempfile::tempdir().unwrap(); |
| 298 | let out = dir.path().join("restored.db"); |
| 299 | |
| 300 | // Flip a byte in the data region of the snapshot (TXID 1) file. |
| 301 | let victim = l0_path(&fx.replica_root, TXID(1)); |
| 302 | let mut bytes = std::fs::read(&victim).unwrap(); |
| 303 | let mid = ltx::HEADER_SIZE + (bytes.len() - ltx::HEADER_SIZE) / 2; |
| 304 | bytes[mid] ^= 0xFF; |
| 305 | std::fs::write(&victim, &bytes).unwrap(); |
| 306 | |
| 307 | let client = FileReplicaClient::new(fx.replica_root.clone()); |
| 308 | let err = replica::restore(&client, &out, TXID(0)) |
| 309 | .await |
| 310 | .expect_err("corrupt LTX must be rejected"); |
| 311 | assert!( |
| 312 | matches!( |
| 313 | err, |
| 314 | Error::ChecksumMismatch | Error::LTXCorrupted | Error::Other(_) |
| 315 | ), |
| 316 | "corrupt LTX rejected with a clean error, got {err:?}" |
| 317 | ); |
| 318 | // The atomic temp-rename means a failed restore leaves no output DB. |
| 319 | assert!(!out.exists(), "no corrupt output DB is produced"); |
| 320 | } |
| 321 | |
| 322 | /// TRUNCATED final upload (partial PUT): the newest L0 file is cut to below the |
| 323 | /// LTX header size on disk. A latest restore must fail with "invalid ltx file", |
| 324 | /// while a restore targeted at the last *intact* TXID still yields a valid DB at |
| 325 | /// that TXID — the "valid DB at a TXID ≤ last durable" guarantee. |
| 326 | #[tokio::test(flavor = "multi_thread")] |
| 327 | async fn truncated_final_upload_recovers_to_prior_txid() { |
| 328 | let fx = build_fixture().await; |
| 329 | let dir = tempfile::tempdir().unwrap(); |
| 330 | |
| 331 | // Truncate the LAST L0 file to 40 bytes (< HEADER_SIZE): a partial upload. |
| 332 | let victim = l0_path(&fx.replica_root, fx.last_txid); |
| 333 | let orig = std::fs::read(&victim).unwrap(); |
| 334 | assert!(orig.len() > 40); |
| 335 | std::fs::write(&victim, &orig[..40]).unwrap(); |
| 336 | |
| 337 | let client = FileReplicaClient::new(fx.replica_root.clone()); |
| 338 | |
| 339 | // 1) A latest restore must be rejected ("invalid ltx file"), never panic. |
| 340 | let out_latest = dir.path().join("latest.db"); |
| 341 | let err = replica::restore(&client, &out_latest, TXID(0)) |
| 342 | .await |
| 343 | .expect_err("a sub-header tail file must be rejected"); |
| 344 | assert!( |
| 345 | err.to_string().contains("invalid ltx file"), |
| 346 | "expected 'invalid ltx file', got: {err}" |
| 347 | ); |
| 348 | assert!(!out_latest.exists()); |
| 349 | |
| 350 | // 2) Restore to the last intact TXID (one before the damaged tail) → valid DB. |
| 351 | let target = TXID(fx.last_txid.0 - 1); |
| 352 | let out_prior = dir.path().join("prior.db"); |
| 353 | replica::restore(&client, &out_prior, target) |
| 354 | .await |
| 355 | .expect("restore to the last intact TXID must succeed"); |
| 356 | assert!( |
| 357 | restored_db_is_valid(&out_prior), |
| 358 | "restored DB at the prior TXID is a valid SQLite database" |
| 359 | ); |
| 360 | assert!(count_rows(&out_prior, "t") >= 1, "restored DB has data"); |
| 361 | } |
| 362 | |
| 363 | /// MISSING / MISSED FRAMES: a mid-chain L0 file is deleted entirely (a dropped |
| 364 | /// segment). A latest restore must fail cleanly (non-contiguous chain), and a |
| 365 | /// restore targeted before the gap must still reproduce the point-in-time DB |
| 366 | /// (Oracle A vs. the `VACUUM INTO` snapshot taken at `safe_txid`). |
| 367 | #[tokio::test(flavor = "multi_thread")] |
| 368 | async fn missing_midchain_segment_recovers_before_the_gap() { |
| 369 | let fx = build_fixture().await; |
| 370 | let dir = tempfile::tempdir().unwrap(); |
| 371 | |
| 372 | // Delete an L0 file in the damaged tail (right after the safe point), opening |
| 373 | // a gap in the chain. |
| 374 | let gap_txid = TXID(fx.safe_txid.0 + 1); |
| 375 | assert!( |
| 376 | gap_txid < fx.last_txid, |
| 377 | "the gap is strictly inside the tail" |
| 378 | ); |
| 379 | std::fs::remove_file(l0_path(&fx.replica_root, gap_txid)).unwrap(); |
| 380 | |
| 381 | let client = FileReplicaClient::new(fx.replica_root.clone()); |
| 382 | |
| 383 | // 1) A latest restore must fail cleanly (the chain is non-contiguous) — never |
| 384 | // panic, never silently skip the gap. |
| 385 | let out_latest = dir.path().join("latest.db"); |
| 386 | let res = replica::restore(&client, &out_latest, TXID(0)).await; |
| 387 | assert!( |
| 388 | res.is_err(), |
| 389 | "a latest restore across a chain gap must fail, got Ok" |
| 390 | ); |
| 391 | assert!(!out_latest.exists(), "no output DB on a failed restore"); |
| 392 | |
| 393 | // 2) A restore targeted at the safe TXID (before the gap) still works. |
| 394 | if !has_bin("sqlite3") { |
| 395 | eprintln!("skipping the Oracle-A half: sqlite3 not on PATH"); |
| 396 | return; |
| 397 | } |
| 398 | let out_safe = dir.path().join("safe_restored.db"); |
| 399 | replica::restore(&client, &out_safe, fx.safe_txid) |
| 400 | .await |
| 401 | .expect("restore before the gap must succeed"); |
| 402 | assert!(restored_db_is_valid(&out_safe), "valid DB before the gap"); |
| 403 | db_equal_a(&fx.safe_snapshot, &out_safe) |
| 404 | .expect("Oracle A: restore@safe_txid == the point-in-time snapshot"); |
| 405 | } |
| 406 | |
| 407 | /// MISSING SNAPSHOT ANCHOR: deleting the very first L0 file (TXID 1, the snapshot |
| 408 | /// anchor) must make even a latest restore fail cleanly (no anchor → no plan), |
| 409 | /// never panic. |
| 410 | #[tokio::test(flavor = "multi_thread")] |
| 411 | async fn missing_snapshot_anchor_fails_cleanly() { |
| 412 | let fx = build_fixture().await; |
| 413 | let dir = tempfile::tempdir().unwrap(); |
| 414 | let out = dir.path().join("restored.db"); |
| 415 | |
| 416 | std::fs::remove_file(l0_path(&fx.replica_root, TXID(1))).unwrap(); |
| 417 | |
| 418 | let client = FileReplicaClient::new(fx.replica_root.clone()); |
| 419 | let res = replica::restore(&client, &out, TXID(0)).await; |
| 420 | assert!( |
| 421 | res.is_err(), |
| 422 | "restore without the snapshot anchor must fail, got Ok" |
| 423 | ); |
| 424 | assert!(!out.exists(), "no output DB is produced"); |
| 425 | } |
| 426 | |
| 427 | /// EMPTY (zero-length) tail file on disk via the real file client: listing |
| 428 | /// reports `size == 0`, so the restore size guard rejects it with |
| 429 | /// "invalid ltx file" — the on-disk analog of the ported EmptyFile mock case. |
| 430 | #[tokio::test(flavor = "multi_thread")] |
| 431 | async fn empty_ondisk_tail_file_errors() { |
| 432 | let fx = build_fixture().await; |
| 433 | let dir = tempfile::tempdir().unwrap(); |
| 434 | let out = dir.path().join("restored.db"); |
| 435 | |
| 436 | // Zero out the last L0 file in place. |
| 437 | std::fs::write(l0_path(&fx.replica_root, fx.last_txid), b"").unwrap(); |
| 438 | |
| 439 | let client = FileReplicaClient::new(fx.replica_root.clone()); |
| 440 | let err = replica::restore(&client, &out, TXID(0)) |
| 441 | .await |
| 442 | .expect_err("an empty tail file must be rejected"); |
| 443 | assert!( |
| 444 | err.to_string().contains("invalid ltx file"), |
| 445 | "expected 'invalid ltx file', got: {err}" |
| 446 | ); |
| 447 | assert!(!out.exists()); |
| 448 | } |