| 1 | //! property_roundtrip — T12: a property test (proptest) that replicate→restore |
| 2 | //! reproduces the source database for *random* transaction sequences. |
| 3 | //! |
| 4 | //! This is **Oracle A** (`scripts/db_equal.sh A`, PLAN.md §6.1) lifted to a |
| 5 | //! generative setting: for each randomly-generated sequence of SQL transactions, |
| 6 | //! we open a managed [`Db`], capture every transaction into L0 LTX files, upload |
| 7 | //! them to a file replica, restore into a fresh path, and assert the restored DB |
| 8 | //! is logically identical to the source. The invariant under test — *a restore |
| 9 | //! of a fully-synced replica reproduces the source* — is the heart of the whole |
| 10 | //! system, and random operation mixes (insert / update / delete / DDL / occasional |
| 11 | //! checkpoints) exercise WAL shapes the hand-written integration tests don't. |
| 12 | //! |
| 13 | //! ## Determinism / speed |
| 14 | //! proptest needs deterministic, reasonably-fast cases. The pipeline is async and |
| 15 | //! the oracle is a subprocess, so each case builds a small current-thread Tokio |
| 16 | //! runtime and `block_on`s the upload/restore. The seed budget is bounded |
| 17 | //! (`PROPTEST_CASES` cases, ≤ `MAX_OPS` operations each) to keep `cargo test` |
| 18 | //! fast while still covering a wide operation space. Values are drawn from the |
| 19 | //! proptest RNG only (no `randomblob`/time), so a failing case is reproducible |
| 20 | //! from its seed. |
| 21 | //! |
| 22 | //! The whole suite self-skips (never fails) if `sqlite3` is not on PATH, since |
| 23 | //! the oracle requires it. |
| 24 | |
| 25 | use proptest::prelude::*; |
| 26 | use rusqlite::Connection; |
| 27 | use celld_ltx::client::file::FileReplicaClient; |
| 28 | use celld_ltx::db::{CheckpointMode, Db}; |
| 29 | use celld_ltx::replica::Replica; |
| 30 | use std::path::Path; |
| 31 | use std::process::Command; |
| 32 | |
| 33 | /// Number of random sequences to try. Bounded for a fast suite (each case opens a |
| 34 | /// real SQLite DB, runs the full capture→upload→restore pipeline, and shells out |
| 35 | /// to the oracle twice). |
| 36 | const PROPTEST_CASES: u32 = 24; |
| 37 | /// Maximum number of transactions per generated sequence. |
| 38 | const MAX_OPS: usize = 14; |
| 39 | |
| 40 | /// Absolute path to the `db_equal.sh` oracle. |
| 41 | fn db_equal_script() -> String { |
| 42 | format!("{}/scripts/db_equal.sh", env!("CARGO_MANIFEST_DIR")) |
| 43 | } |
| 44 | |
| 45 | /// Runs `db_equal.sh A <a> <b>`; Ok on exit 0, else the captured output. |
| 46 | fn db_equal_a(a: &Path, b: &Path) -> Result<(), String> { |
| 47 | let out = Command::new("bash") |
| 48 | .arg(db_equal_script()) |
| 49 | .arg("A") |
| 50 | .arg(a) |
| 51 | .arg(b) |
| 52 | .output() |
| 53 | .map_err(|e| format!("spawn db_equal.sh: {e}"))?; |
| 54 | if out.status.success() { |
| 55 | Ok(()) |
| 56 | } else { |
| 57 | Err(format!( |
| 58 | "db_equal A failed:\nstdout: {}\nstderr: {}", |
| 59 | String::from_utf8_lossy(&out.stdout), |
| 60 | String::from_utf8_lossy(&out.stderr), |
| 61 | )) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// True if `bin` resolves on PATH. |
| 66 | fn has_bin(bin: &str) -> bool { |
| 67 | Command::new(bin) |
| 68 | .arg("--help") |
| 69 | .output() |
| 70 | .map(|o| o.status.success() || o.status.code().is_some()) |
| 71 | .unwrap_or(false) |
| 72 | } |
| 73 | |
| 74 | /// Opens an application writer connection in WAL mode. |
| 75 | fn open_writer(path: &Path) -> Connection { |
| 76 | let c = Connection::open(path).unwrap(); |
| 77 | c.busy_timeout(std::time::Duration::from_secs(5)).unwrap(); |
| 78 | let mode: String = c |
| 79 | .query_row("PRAGMA journal_mode=WAL", [], |r| r.get(0)) |
| 80 | .unwrap(); |
| 81 | assert_eq!(mode, "wal"); |
| 82 | c |
| 83 | } |
| 84 | |
| 85 | /// One generated transaction against a fixed `kv(k INTEGER PRIMARY KEY, v TEXT)` |
| 86 | /// schema plus occasional structural events. Keeping the schema fixed makes value |
| 87 | /// generation simple while the *operation mix* (and thus the WAL frame shapes, |
| 88 | /// page growth, and checkpoint interleaving) stays random. |
| 89 | #[derive(Debug, Clone)] |
| 90 | enum Op { |
| 91 | /// `INSERT OR REPLACE` a key with a text value. |
| 92 | Upsert { key: i64, val: String }, |
| 93 | /// `DELETE` a key (may match nothing — still a valid, empty-ish txn). |
| 94 | Delete { key: i64 }, |
| 95 | /// `UPDATE` all rows whose key is below a bound (range write). |
| 96 | UpdateBelow { bound: i64, val: String }, |
| 97 | /// Insert `n` rows in a single transaction (multi-page growth). |
| 98 | BulkInsert { start: i64, n: i64, val: String }, |
| 99 | /// Create an extra table and seed one row (DDL + schema change). |
| 100 | CreateAux { idx: u8 }, |
| 101 | /// Force a `PRAGMA wal_checkpoint(TRUNCATE)` (continuity break / salt reset). |
| 102 | CheckpointTruncate, |
| 103 | } |
| 104 | |
| 105 | /// proptest strategy for a single `Op`. Weighted toward data mutations. |
| 106 | fn op_strategy() -> impl Strategy<Value = Op> { |
| 107 | let val = "[a-zA-Z0-9]{0,24}"; |
| 108 | prop_oneof![ |
| 109 | 6 => (0i64..40, val).prop_map(|(key, v)| Op::Upsert { key, val: v }), |
| 110 | 3 => (0i64..40).prop_map(|key| Op::Delete { key }), |
| 111 | 3 => (0i64..40, val).prop_map(|(bound, v)| Op::UpdateBelow { bound, val: v }), |
| 112 | 3 => (0i64..30, 1i64..8, val).prop_map(|(start, n, v)| Op::BulkInsert { start, n, val: v }), |
| 113 | 1 => (0u8..3).prop_map(|idx| Op::CreateAux { idx }), |
| 114 | 2 => Just(Op::CheckpointTruncate), |
| 115 | ] |
| 116 | } |
| 117 | |
| 118 | /// Applies one `Op`. DDL/data ops run on the application `writer` connection; |
| 119 | /// `CheckpointTruncate` drives the managed `Db`. |
| 120 | fn apply_op(op: &Op, writer: &Connection, db: &mut Db) { |
| 121 | match op { |
| 122 | Op::Upsert { key, val } => { |
| 123 | writer |
| 124 | .execute( |
| 125 | "INSERT OR REPLACE INTO kv (k, v) VALUES (?1, ?2)", |
| 126 | (key, val), |
| 127 | ) |
| 128 | .unwrap(); |
| 129 | } |
| 130 | Op::Delete { key } => { |
| 131 | writer |
| 132 | .execute("DELETE FROM kv WHERE k = ?1", [key]) |
| 133 | .unwrap(); |
| 134 | } |
| 135 | Op::UpdateBelow { bound, val } => { |
| 136 | writer |
| 137 | .execute("UPDATE kv SET v = ?2 WHERE k < ?1", (bound, val)) |
| 138 | .unwrap(); |
| 139 | } |
| 140 | Op::BulkInsert { start, n, val } => { |
| 141 | let tx_sql: String = (0..*n) |
| 142 | .map(|i| { |
| 143 | format!( |
| 144 | "INSERT OR REPLACE INTO kv (k, v) VALUES ({}, '{}');", |
| 145 | start + i, |
| 146 | val |
| 147 | ) |
| 148 | }) |
| 149 | .collect(); |
| 150 | // Wrap as a single transaction so it is one captured TXID. |
| 151 | writer |
| 152 | .execute_batch(&format!("BEGIN; {tx_sql} COMMIT;")) |
| 153 | .unwrap(); |
| 154 | } |
| 155 | Op::CreateAux { idx } => { |
| 156 | let i = (*idx % 3) as usize; |
| 157 | writer |
| 158 | .execute_batch(&format!( |
| 159 | "CREATE TABLE IF NOT EXISTS aux{i} (id INTEGER PRIMARY KEY, label TEXT);\ |
| 160 | INSERT INTO aux{i} (id, label) VALUES (1, 'seed-{i}') \ |
| 161 | ON CONFLICT(id) DO UPDATE SET label='seed-{i}';" |
| 162 | )) |
| 163 | .unwrap(); |
| 164 | } |
| 165 | Op::CheckpointTruncate => { |
| 166 | db.checkpoint(CheckpointMode::Truncate).unwrap(); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | proptest! { |
| 172 | #![proptest_config(ProptestConfig { |
| 173 | cases: PROPTEST_CASES, |
| 174 | // Shrinking re-runs the (heavy) pipeline; cap it so a failure still |
| 175 | // reports quickly. The seed alone reproduces any case. |
| 176 | max_shrink_iters: 24, |
| 177 | failure_persistence: None, |
| 178 | ..ProptestConfig::default() |
| 179 | })] |
| 180 | |
| 181 | /// For a random sequence of transactions, a fully-synced replica restores to |
| 182 | /// a database logically identical to the source (Oracle A). |
| 183 | #[test] |
| 184 | fn random_txns_roundtrip_restores_source(ops in prop::collection::vec(op_strategy(), 1..=MAX_OPS)) { |
| 185 | // Skip (don't fail) when the oracle's sqlite3 is unavailable. |
| 186 | if !has_bin("sqlite3") { |
| 187 | return Ok(()); |
| 188 | } |
| 189 | |
| 190 | let dir = tempfile::tempdir().unwrap(); |
| 191 | let src_path = dir.path().join("source.db"); |
| 192 | let replica_root = dir.path().join("replica"); |
| 193 | let restored_path = dir.path().join("restored.db"); |
| 194 | |
| 195 | // A current-thread runtime: proptest bodies are synchronous, and the |
| 196 | // upload/restore halves are async. block_on keeps each case deterministic. |
| 197 | let rt = tokio::runtime::Builder::new_current_thread() |
| 198 | .enable_all() |
| 199 | .build() |
| 200 | .unwrap(); |
| 201 | |
| 202 | let db = Db::open(&src_path).unwrap(); |
| 203 | let writer = open_writer(&src_path); |
| 204 | let client = FileReplicaClient::new(replica_root.to_string_lossy().into_owned()); |
| 205 | let mut replica = Replica::new(db, client); |
| 206 | |
| 207 | // Base schema (one captured TXID). |
| 208 | writer |
| 209 | .execute_batch("CREATE TABLE kv (k INTEGER PRIMARY KEY, v TEXT)") |
| 210 | .unwrap(); |
| 211 | replica.db_mut().unwrap().sync().unwrap(); |
| 212 | rt.block_on(replica.sync()).unwrap(); |
| 213 | |
| 214 | for op in &ops { |
| 215 | apply_op(op, &writer, replica.db_mut().unwrap()); |
| 216 | // Capture then upload after every op (SyncAndWait ordering). Syncing |
| 217 | // an idle transaction is a valid no-op (db.rs covers it). |
| 218 | replica.db_mut().unwrap().sync().unwrap(); |
| 219 | rt.block_on(replica.sync()).unwrap(); |
| 220 | } |
| 221 | |
| 222 | // The replica must have caught up to the database position. |
| 223 | let dpos = replica.db_mut().unwrap().pos().unwrap(); |
| 224 | prop_assert_eq!( |
| 225 | replica.pos().txid, dpos.txid, |
| 226 | "replica caught up to the DB (txid {})", dpos.txid.0 |
| 227 | ); |
| 228 | |
| 229 | // Restore into a fresh path. |
| 230 | rt.block_on(replica.restore(&restored_path)).expect("restore"); |
| 231 | |
| 232 | // Release the source WAL before the oracle checkpoints it. |
| 233 | drop(replica); |
| 234 | drop(writer); |
| 235 | |
| 236 | // Oracle A: restored == source. |
| 237 | if let Err(e) = db_equal_a(&src_path, &restored_path) { |
| 238 | return Err(TestCaseError::fail(format!( |
| 239 | "Oracle A mismatch for ops {ops:?}: {e}" |
| 240 | ))); |
| 241 | } |
| 242 | } |
| 243 | } |