| 1 | // This file-backend integration test deletes and inspects crash fixtures. |
| 2 | #![allow(clippy::disallowed_methods)] |
| 3 | |
| 4 | //! integration_resilience — T11: the resilience half of the round-trip gate. |
| 5 | //! |
| 6 | //! Where `integration_file.rs` proves the happy-path G2 round-trip, this file |
| 7 | //! proves replicate↔restore survives the messy cases the real world throws at a |
| 8 | //! replication system, using the file `ReplicaClient` + the **Oracle A** |
| 9 | //! (`scripts/db_equal.sh A`) logical-equality check: |
| 10 | //! |
| 11 | //! * **crash-in-the-middle** — the managed `Db` is dropped without a clean |
| 12 | //! shutdown (simulating a process kill), a fresh `Db` reopens the same file and |
| 13 | //! continues capturing, and a restore still reproduces the final source. |
| 14 | //! * **restore-and-replicate-after-data-loss** — the issue #781 scenario, ported |
| 15 | //! from `replica_test.go:111-255 TestReplica_RestoreAndReplicateAfterDataLoss`: |
| 16 | //! replicate, hard-recover from backup to an *earlier* state, write new data, |
| 17 | //! replicate again, restore again, and verify the new data survived. This is |
| 18 | //! the canonical snapshot-on-continuity-break integration test and exercises |
| 19 | //! `Replica::check_database_behind_replica`. |
| 20 | //! * **snapshot-on-continuity-break via a TRUNCATE checkpoint** — drive a real |
| 21 | //! `PRAGMA wal_checkpoint(TRUNCATE)` between writes (the salt-reset path through |
| 22 | //! `Db::verify`) and confirm every captured TXID still restores cleanly. |
| 23 | //! |
| 24 | //! Each test self-skips (never fails) when `sqlite3` is not on PATH, since the |
| 25 | //! Oracle needs it; the capture/replicate/restore code is exercised regardless. |
| 26 | |
| 27 | use celld_ltx::client::file::FileReplicaClient; |
| 28 | use celld_ltx::client::ReplicaClient; |
| 29 | use celld_ltx::db::{CheckpointMode, Db}; |
| 30 | use celld_ltx::replica::{self, Replica}; |
| 31 | use celld_ltx::TXID; |
| 32 | use rusqlite::Connection; |
| 33 | use std::path::Path; |
| 34 | use std::process::Command; |
| 35 | |
| 36 | /// Absolute path to the `db_equal.sh` oracle. |
| 37 | fn db_equal_script() -> String { |
| 38 | format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR")) |
| 39 | } |
| 40 | |
| 41 | /// Runs `db_equal.sh <mode> <a> <b>`; Ok on exit 0, else the captured output. |
| 42 | fn db_equal(mode: &str, a: &Path, b: &Path) -> Result<(), String> { |
| 43 | let out = Command::new("bash") |
| 44 | .arg(db_equal_script()) |
| 45 | .arg(mode) |
| 46 | .arg(a) |
| 47 | .arg(b) |
| 48 | .output() |
| 49 | .map_err(|e| format!("spawn db_equal.sh: {e}"))?; |
| 50 | if out.status.success() { |
| 51 | Ok(()) |
| 52 | } else { |
| 53 | Err(format!( |
| 54 | "db_equal {mode} failed:\nstdout: {}\nstderr: {}", |
| 55 | String::from_utf8_lossy(&out.stdout), |
| 56 | String::from_utf8_lossy(&out.stderr), |
| 57 | )) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// True if `bin` resolves on PATH. |
| 62 | fn 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 | |
| 70 | /// Opens an application writer connection in WAL mode (the host's own handle). |
| 71 | fn open_writer(path: &Path) -> Connection { |
| 72 | let c = Connection::open(path).unwrap(); |
| 73 | c.busy_timeout(std::time::Duration::from_secs(5)).unwrap(); |
| 74 | let mode: String = c |
| 75 | .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0)) |
| 76 | .unwrap(); |
| 77 | assert_eq!(mode, "wal"); |
| 78 | c |
| 79 | } |
| 80 | |
| 81 | /// CRASH IN THE MIDDLE: drop the managed `Db` with no clean shutdown partway |
| 82 | /// through replication, reopen a fresh `Db` on the same file, keep writing & |
| 83 | /// replicating, then restore — the result must still equal the final source. |
| 84 | /// |
| 85 | /// This mirrors a process kill: the read lock and connections vanish, a new |
| 86 | /// process re-`open`s the database, and `Db::open`'s `ensure_wal_exists` + |
| 87 | /// `verify`'s continuity-break detection recover the capture stream. The first |
| 88 | /// `sync()` on the reopened `Db` writes a fresh snapshot (no local LTX state |
| 89 | /// survives a meta-dir-less reopen view of pos), so the chain stays restorable. |
| 90 | #[tokio::test(flavor = "multi_thread")] |
| 91 | async fn crash_in_the_middle_then_reopen_and_restore() { |
| 92 | if !has_bin("sqlite3") { |
| 93 | eprintln!("skipping: sqlite3 not on PATH (required for Oracle A)"); |
| 94 | return; |
| 95 | } |
| 96 | |
| 97 | let dir = tempfile::tempdir().unwrap(); |
| 98 | let src_path = dir.path().join("source.db"); |
| 99 | let replica_root = dir.path().join("replica"); |
| 100 | let restored_path = dir.path().join("restored.db"); |
| 101 | |
| 102 | let writer = open_writer(&src_path); |
| 103 | |
| 104 | // ── Phase 1: open a managed Db, capture & replicate a few txns. ── |
| 105 | { |
| 106 | let db = Db::open(&src_path).unwrap(); |
| 107 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 108 | let mut replica = Replica::new(db, client); |
| 109 | |
| 110 | writer |
| 111 | .execute_batch("CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL)") |
| 112 | .unwrap(); |
| 113 | replica.db_mut().unwrap().sync().unwrap(); |
| 114 | replica.sync().await.unwrap(); |
| 115 | |
| 116 | writer |
| 117 | .execute_batch("INSERT INTO kv (k,v) VALUES ('a','1'),('b','2'),('c','3')") |
| 118 | .unwrap(); |
| 119 | replica.db_mut().unwrap().sync().unwrap(); |
| 120 | replica.sync().await.unwrap(); |
| 121 | |
| 122 | // ── CRASH: drop the replica (and its Db) WITHOUT calling close(). ── |
| 123 | // No clean shutdown: the read lock + connections are abandoned, exactly |
| 124 | // as if the process were killed here. |
| 125 | drop(replica); |
| 126 | } |
| 127 | |
| 128 | // ── Phase 2: a fresh process reopens the same database file. ── |
| 129 | // The application connection survived (a separate handle); reopen the |
| 130 | // managed Db and continue. The replica position is recomputed from the |
| 131 | // remote on the next sync (Replica::sync clears+recomputes pos). |
| 132 | { |
| 133 | let db = Db::open(&src_path).unwrap(); |
| 134 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 135 | let mut replica = Replica::new(db, client); |
| 136 | |
| 137 | // Heal any continuity break left by the crash before resuming uploads |
| 138 | // (the same call a host makes after open; issue #781 path). |
| 139 | replica.check_database_behind_replica().await.unwrap(); |
| 140 | |
| 141 | writer |
| 142 | .execute_batch("UPDATE kv SET v='updated' WHERE k='a'") |
| 143 | .unwrap(); |
| 144 | replica.db_mut().unwrap().sync().unwrap(); |
| 145 | replica.sync().await.unwrap(); |
| 146 | |
| 147 | writer |
| 148 | .execute_batch( |
| 149 | "INSERT INTO kv (k,v) VALUES ('d','4'),('e','5'); DELETE FROM kv WHERE k='b';", |
| 150 | ) |
| 151 | .unwrap(); |
| 152 | replica.db_mut().unwrap().sync().unwrap(); |
| 153 | replica.sync().await.unwrap(); |
| 154 | |
| 155 | // Restore from the replica into a brand-new path. |
| 156 | replica.restore(&restored_path).await.expect("restore"); |
| 157 | assert!(restored_path.exists(), "restored DB file created"); |
| 158 | |
| 159 | drop(replica); |
| 160 | } |
| 161 | drop(writer); |
| 162 | |
| 163 | // Oracle A: the restored DB is logically identical to the (final) source. |
| 164 | db_equal("A", &src_path, &restored_path) |
| 165 | .expect("Oracle A: restored == source after crash-in-the-middle"); |
| 166 | } |
| 167 | |
| 168 | /// ISSUE #781 — restore to an earlier state, write new data, replicate, restore |
| 169 | /// again: the new data must survive. Faithful port of |
| 170 | /// `TestReplica_RestoreAndReplicateAfterDataLoss` (replica_test.go:111-255). |
| 171 | /// |
| 172 | /// Without `check_database_behind_replica`, step 3's new write is silently |
| 173 | /// dropped: the fresh post-restore DB snapshots at TXID 1, but the replica's |
| 174 | /// recomputed position sits at the remote's higher MaxTXID, so the upload loop |
| 175 | /// (`pos+1 ..= db.pos`) never runs. The fix seeds the remote baseline so the |
| 176 | /// next sync snapshots forward and uploads. |
| 177 | #[tokio::test(flavor = "multi_thread")] |
| 178 | async fn restore_and_replicate_after_data_loss() { |
| 179 | if !has_bin("sqlite3") { |
| 180 | eprintln!("skipping: sqlite3 not on PATH"); |
| 181 | return; |
| 182 | } |
| 183 | |
| 184 | let replica_dir = tempfile::tempdir().unwrap(); |
| 185 | let replica_root = replica_dir.path().to_string_lossy().into_owned(); |
| 186 | |
| 187 | let db_dir = tempfile::tempdir().unwrap(); |
| 188 | let db_path = db_dir.path().join("db.sqlite"); |
| 189 | |
| 190 | // ── Step 1: create initial data and replicate. ── |
| 191 | { |
| 192 | // The application writes the initial rows (mirrors the Go test opening a |
| 193 | // plain *sql.DB first), then litestream takes over and snapshots them. |
| 194 | let writer = open_writer(&db_path); |
| 195 | writer |
| 196 | .execute_batch("CREATE TABLE test(col1 INTEGER); INSERT INTO test VALUES (1);") |
| 197 | .unwrap(); |
| 198 | |
| 199 | let db = Db::open(&db_path).unwrap(); |
| 200 | let client = FileReplicaClient::new(replica_root.clone()); |
| 201 | let mut replica = Replica::new(db, client); |
| 202 | |
| 203 | replica.db_mut().unwrap().sync().unwrap(); |
| 204 | replica.sync().await.unwrap(); |
| 205 | |
| 206 | // Clean shutdown of the managed Db + drop the writer handle. |
| 207 | let db = replica.into_db().unwrap(); |
| 208 | db.close().unwrap(); |
| 209 | drop(writer); |
| 210 | } |
| 211 | |
| 212 | // ── Step 2: hard recovery — wipe the db + meta dir, restore from backup. ── |
| 213 | let meta_path = Db::meta_path_for_path(&db_path); |
| 214 | std::fs::remove_file(&db_path).ok(); |
| 215 | std::fs::remove_file(format!("{}-wal", db_path.display())).ok(); |
| 216 | std::fs::remove_file(format!("{}-shm", db_path.display())).ok(); |
| 217 | std::fs::remove_dir_all(&meta_path).ok(); |
| 218 | |
| 219 | { |
| 220 | let client = FileReplicaClient::new(replica_root.clone()); |
| 221 | replica::restore(&client, &db_path, TXID(0)) |
| 222 | .await |
| 223 | .expect("restore from backup"); |
| 224 | } |
| 225 | |
| 226 | // ── Step 3: reopen, insert new data (value=2), replicate. ── |
| 227 | { |
| 228 | let db = Db::open(&db_path).unwrap(); |
| 229 | let client = FileReplicaClient::new(replica_root.clone()); |
| 230 | let mut replica = Replica::new(db, client); |
| 231 | |
| 232 | // Issue #781 detection: the DB is behind the replica (fresh local L0 vs. |
| 233 | // the remote's TXID). Seed the baseline so the next sync snapshots |
| 234 | // forward. |
| 235 | replica.check_database_behind_replica().await.unwrap(); |
| 236 | |
| 237 | let writer = open_writer(&db_path); |
| 238 | writer |
| 239 | .execute_batch("INSERT INTO test VALUES (2);") |
| 240 | .unwrap(); |
| 241 | |
| 242 | replica.db_mut().unwrap().sync().unwrap(); |
| 243 | replica.sync().await.unwrap(); |
| 244 | |
| 245 | let db = replica.into_db().unwrap(); |
| 246 | db.close().unwrap(); |
| 247 | drop(writer); |
| 248 | } |
| 249 | |
| 250 | // ── Step 4: second hard recovery, restore to a path whose parent is absent. ── |
| 251 | std::fs::remove_file(&db_path).ok(); |
| 252 | std::fs::remove_file(format!("{}-wal", db_path.display())).ok(); |
| 253 | std::fs::remove_file(format!("{}-shm", db_path.display())).ok(); |
| 254 | std::fs::remove_dir_all(&meta_path).ok(); |
| 255 | |
| 256 | let restored_path = db_dir.path().join("restored").join("db.sqlite"); |
| 257 | { |
| 258 | let client = FileReplicaClient::new(replica_root.clone()); |
| 259 | replica::restore(&client, &restored_path, TXID(0)) |
| 260 | .await |
| 261 | .expect("second restore (parent dir must be created)"); |
| 262 | } |
| 263 | |
| 264 | // ── Step 5: verify the new data (value=2) survived. ── |
| 265 | let conn = Connection::open(&restored_path).unwrap(); |
| 266 | let count: i64 = conn |
| 267 | .query_row("SELECT COUNT(*) FROM test", [], |r| r.get(0)) |
| 268 | .unwrap(); |
| 269 | assert_eq!(count, 2, "expected 2 rows (1 and 2) in restored database"); |
| 270 | let exists: bool = conn |
| 271 | .query_row( |
| 272 | "SELECT EXISTS(SELECT 1 FROM test WHERE col1 = 2)", |
| 273 | [], |
| 274 | |r| r.get(0), |
| 275 | ) |
| 276 | .unwrap(); |
| 277 | assert!( |
| 278 | exists, |
| 279 | "new data (value=2) was not replicated — this is the bug in issue #781" |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | /// SNAPSHOT-ON-CONTINUITY-BREAK: force a real `PRAGMA wal_checkpoint(TRUNCATE)` |
| 284 | /// between writes (which resets the WAL salts, the salt-reset branch of |
| 285 | /// `Db::verify`) and confirm the full chain still restores to the final source |
| 286 | /// under Oracle A. The capture loop must either continue incrementally or |
| 287 | /// re-snapshot — either way the restore stays correct. |
| 288 | #[tokio::test(flavor = "multi_thread")] |
| 289 | async fn checkpoint_truncate_continuity_break_still_restores() { |
| 290 | if !has_bin("sqlite3") { |
| 291 | eprintln!("skipping: sqlite3 not on PATH"); |
| 292 | return; |
| 293 | } |
| 294 | |
| 295 | let dir = tempfile::tempdir().unwrap(); |
| 296 | let src_path = dir.path().join("source.db"); |
| 297 | let replica_root = dir.path().join("replica"); |
| 298 | let restored_path = dir.path().join("restored.db"); |
| 299 | |
| 300 | let db = Db::open(&src_path).unwrap(); |
| 301 | let writer = open_writer(&src_path); |
| 302 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 303 | let mut replica = Replica::new(db, client); |
| 304 | |
| 305 | macro_rules! step { |
| 306 | ($sql:expr) => {{ |
| 307 | writer.execute_batch($sql).unwrap(); |
| 308 | replica.db_mut().unwrap().sync().unwrap(); |
| 309 | replica.sync().await.unwrap(); |
| 310 | }}; |
| 311 | } |
| 312 | |
| 313 | step!("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)"); |
| 314 | step!("INSERT INTO t (v) VALUES ('one'),('two')"); |
| 315 | |
| 316 | // Force a TRUNCATE checkpoint: this restarts the WAL and rotates the salts, |
| 317 | // a continuity break the next verify() must detect. |
| 318 | replica |
| 319 | .db_mut() |
| 320 | .unwrap() |
| 321 | .checkpoint(CheckpointMode::Truncate) |
| 322 | .unwrap(); |
| 323 | |
| 324 | step!("INSERT INTO t (v) VALUES ('three')"); |
| 325 | step!("UPDATE t SET v='TWO' WHERE id=2"); |
| 326 | // A second checkpoint mid-stream for good measure. |
| 327 | replica |
| 328 | .db_mut() |
| 329 | .unwrap() |
| 330 | .checkpoint(CheckpointMode::Truncate) |
| 331 | .unwrap(); |
| 332 | step!("INSERT INTO t (v) VALUES ('four'),('five')"); |
| 333 | |
| 334 | let dpos = replica.db_mut().unwrap().pos().unwrap(); |
| 335 | assert!(dpos.txid.0 >= 5, "at least 5 transactions captured"); |
| 336 | |
| 337 | // Every captured TXID is on the replica. |
| 338 | let files = replica.client.ltx_files(0, TXID(0)).await.unwrap(); |
| 339 | assert!( |
| 340 | files.len() as u64 >= dpos.txid.0, |
| 341 | "every captured TXID is on the replica (got {} files, txid={})", |
| 342 | files.len(), |
| 343 | dpos.txid |
| 344 | ); |
| 345 | |
| 346 | replica.restore(&restored_path).await.expect("restore"); |
| 347 | drop(replica); |
| 348 | drop(writer); |
| 349 | |
| 350 | db_equal("A", &src_path, &restored_path) |
| 351 | .expect("Oracle A: restored == source across TRUNCATE checkpoints"); |
| 352 | } |
| 353 | |
| 354 | /// CELLD #150: a passive checkpoint must seal the WAL before SQLite backfills |
| 355 | /// it. The restored replica must contain every transaction that completed while |
| 356 | /// the checkpoint loop and the application writer ran concurrently. |
| 357 | #[tokio::test(flavor = "multi_thread")] |
| 358 | async fn passive_checkpoint_with_concurrent_growth_restores_every_row() { |
| 359 | let dir = tempfile::tempdir().unwrap(); |
| 360 | let src_path = dir.path().join("source.db"); |
| 361 | let replica_root = dir.path().join("replica"); |
| 362 | let restored_path = dir.path().join("restored.db"); |
| 363 | |
| 364 | let writer = open_writer(&src_path); |
| 365 | writer |
| 366 | .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB NOT NULL)") |
| 367 | .unwrap(); |
| 368 | |
| 369 | let db = Db::open(&src_path).unwrap(); |
| 370 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 371 | let mut replica = Replica::new(db, client); |
| 372 | replica.db_mut().unwrap().sync().unwrap(); |
| 373 | replica.sync().await.unwrap(); |
| 374 | drop(writer); |
| 375 | |
| 376 | let writer_path = src_path.clone(); |
| 377 | let (started_tx, started_rx) = std::sync::mpsc::sync_channel(0); |
| 378 | let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); |
| 379 | let writer = std::thread::spawn(move || { |
| 380 | let writer = open_writer(&writer_path); |
| 381 | for id in 0..120i64 { |
| 382 | writer |
| 383 | .execute( |
| 384 | "INSERT INTO t VALUES (?, ?)", |
| 385 | rusqlite::params![id, vec![id as u8; 4000]], |
| 386 | ) |
| 387 | .unwrap(); |
| 388 | if id == 0 { |
| 389 | started_tx.send(()).unwrap(); |
| 390 | } |
| 391 | std::thread::sleep(std::time::Duration::from_millis(1)); |
| 392 | } |
| 393 | done_tx.send(()).unwrap(); |
| 394 | }); |
| 395 | started_rx.recv().unwrap(); |
| 396 | |
| 397 | let mut checkpoint_n = 0; |
| 398 | loop { |
| 399 | match done_rx.try_recv() { |
| 400 | Ok(()) => break, |
| 401 | Err(std::sync::mpsc::TryRecvError::Empty) => {} |
| 402 | Err(std::sync::mpsc::TryRecvError::Disconnected) => { |
| 403 | panic!("writer completion channel disconnected") |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | match replica |
| 408 | .db_mut() |
| 409 | .unwrap() |
| 410 | .checkpoint(CheckpointMode::Passive) |
| 411 | { |
| 412 | Ok(()) => checkpoint_n += 1, |
| 413 | Err(error) |
| 414 | if error.to_string().contains("database is locked") |
| 415 | || error.to_string().contains("SQLITE_BUSY") => {} |
| 416 | Err(error) => panic!("passive checkpoint failed: {error}"), |
| 417 | } |
| 418 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 419 | } |
| 420 | writer.join().unwrap(); |
| 421 | assert!( |
| 422 | checkpoint_n > 0, |
| 423 | "the concurrent checkpoint loop made no progress" |
| 424 | ); |
| 425 | |
| 426 | replica.db_mut().unwrap().sync().unwrap(); |
| 427 | replica.sync().await.unwrap(); |
| 428 | replica.restore(&restored_path).await.expect("restore"); |
| 429 | |
| 430 | let source = Connection::open(&src_path).unwrap(); |
| 431 | let restored = Connection::open(&restored_path).unwrap(); |
| 432 | let summary = |conn: &Connection| { |
| 433 | conn.query_row( |
| 434 | "SELECT count(*), min(id), max(id), sum(length(data)) FROM t", |
| 435 | [], |
| 436 | |row| { |
| 437 | Ok(( |
| 438 | row.get::<_, i64>(0)?, |
| 439 | row.get::<_, i64>(1)?, |
| 440 | row.get::<_, i64>(2)?, |
| 441 | row.get::<_, i64>(3)?, |
| 442 | )) |
| 443 | }, |
| 444 | ) |
| 445 | .unwrap() |
| 446 | }; |
| 447 | assert_eq!(summary(&source), (120, 0, 119, 480_000)); |
| 448 | assert_eq!(summary(&restored), summary(&source)); |
| 449 | } |