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