From e6f0981b43c88c4efcd9d1c813a595b8ffb6ab4f Mon Sep 17 00:00:00 2001 From: Glauber Costa Date: Sun, 4 Oct 2026 19:15:00 -0500 Subject: [PATCH] simulator: correct MVCC rowid assumptions and validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under MVCC, implicit rowid allocation behaves like a sequence: the next value comes from a high-water mark that a rollback does not lower, so an aborted insert consumes its rowid for good and the next insert skips past it. This is deliberate — we do not guarantee that a rolled-back allocation is handed back, matching PostgreSQL sequences, where nextval is never rolled back and aborted transactions leave permanent gaps. (AUTOINCREMENT already behaved this way; the same rule now covers plain INTEGER PRIMARY KEY rowids.) WAL mode, like SQLite, reuses the freed value. The simulator makes exact-row assertions, and it cannot predict a post-rollback rowid without modeling that watermark. Rather than model it, generate explicit integer primary keys in MVCC INSERT and UPSERT workloads, so the assertions no longer assume rolled-back allocations come back. WAL mode keeps generating implicit keys. Check MVCC integrity with Turso, which can read the logical-log state SQLite cannot, and keep the SQLite integrity check for WAL. Export the logical log from the in-memory I/O so a retained failure artifact includes committed state. Tests: 21 generator tests, the MVCC profile regression, and deterministic integrity and export regressions pass. --- sql_generation/generation/opts.rs | 3 + sql_generation/generation/query.rs | 72 ++++++++++++++++- testing/simulator/README.md | 12 +++ testing/simulator/main.rs | 110 +++++++++++++++++++++++--- testing/simulator/runner/env.rs | 34 ++++++++ testing/simulator/runner/memory/io.rs | 5 +- 6 files changed, 219 insertions(+), 17 deletions(-) diff --git a/sql_generation/generation/opts.rs b/sql_generation/generation/opts.rs index ef76ba1ff..7bf8c1ad3 100644 --- a/sql_generation/generation/opts.rs +++ b/sql_generation/generation/opts.rs @@ -215,6 +215,8 @@ pub struct InsertOpts { pub max_rows: NonZeroU32, #[garde(range(min = 0.0, max = 1.0))] pub upsert_prob: f64, + #[garde(skip)] + pub allow_implicit_rowids: bool, } impl Default for InsertOpts { @@ -223,6 +225,7 @@ impl Default for InsertOpts { min_rows: NonZero::new(1).unwrap(), max_rows: NonZero::new(10).unwrap(), upsert_prob: 0.15, + allow_implicit_rowids: true, } } } diff --git a/sql_generation/generation/query.rs b/sql_generation/generation/query.rs index 5e38debdd..342ee22e2 100644 --- a/sql_generation/generation/query.rs +++ b/sql_generation/generation/query.rs @@ -431,7 +431,10 @@ fn gen_insert_values( .iter() .enumerate() .map(|(col_idx, c)| { - if integer_pk_idx == Some(col_idx) && rng.random_bool(INTEGER_PK_NULL_PROB) { + if integer_pk_idx == Some(col_idx) + && insert_opts.allow_implicit_rowids + && rng.random_bool(INTEGER_PK_NULL_PROB) + { return SimValue::NULL; } if c.has_unique_or_pk() { @@ -473,7 +476,6 @@ fn gen_insert_upsert_values( const UNIQUE_COL_STRIDE: i64 = 10_000_000; const FRESH_ID_JITTER: i64 = 5; const PAYLOAD_OFFSET_BUMP: i64 = 42; - const UPSERT_INTEGER_PK_NULL_PROB: f64 = 0.25; if !rng.random_bool(insert_opts.upsert_prob) { return None; @@ -604,7 +606,7 @@ fn gen_insert_upsert_values( ); } row[pk_idx] = SimValue::unique_for_type(&pk_col.column_type, new_id); - if rng.random_bool(UPSERT_INTEGER_PK_NULL_PROB) { + if insert_opts.allow_implicit_rowids && rng.random_bool(0.25) { row[pk_idx] = SimValue::NULL; } @@ -1055,3 +1057,67 @@ impl Arbitrary for DropIndex { } } } + +#[cfg(test)] +mod insert_tests { + use super::*; + use crate::generation::tests::TestContext; + use rand::SeedableRng; + + #[test] + fn insert_generation_can_require_explicit_rowids() { + let mut context = TestContext::default(); + context.opts.query.insert.upsert_prob = 1.0; + context.opts.query.insert.allow_implicit_rowids = false; + context.tables.push(Table { + name: "t".into(), + columns: vec![ + Column { + name: "id".into(), + column_type: ColumnType::Integer, + constraints: vec![ColumnConstraint::PrimaryKey { + order: None, + conflict_clause: None, + auto_increment: false, + }], + }, + Column { + name: "name".into(), + column_type: ColumnType::Text, + constraints: vec![ColumnConstraint::Unique(None)], + }, + ], + rows: vec![ + vec![ + SimValue(turso_core::Value::from_i64(1)), + SimValue(turso_core::Value::build_text("a")), + ], + vec![ + SimValue(turso_core::Value::from_i64(2)), + SimValue(turso_core::Value::build_text("b")), + ], + ], + indexes: vec![], + }); + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + for _ in 0..100 { + let insert = + gen_insert_upsert_values(&mut rng, &context, &context.opts.query.insert).unwrap(); + let Insert::Values { + values, + on_conflict, + .. + } = insert + else { + panic!("expected UPSERT"); + }; + assert!(on_conflict.is_some()); + assert!(values[0][0].0.as_int().is_some()); + let insert = gen_insert_values(&mut rng, &context, &context.opts.query.insert).unwrap(); + let Insert::Values { values, .. } = insert else { + panic!("expected INSERT VALUES"); + }; + assert!(values.iter().all(|row| row[0].0.as_int().is_some())); + } + } +} diff --git a/testing/simulator/README.md b/testing/simulator/README.md index b3c93e00a..a5cb5f16a 100644 --- a/testing/simulator/README.md +++ b/testing/simulator/README.md @@ -136,3 +136,15 @@ Notes: - [(video) "Testing Distributed Systems w/ Deterministic Simulation" by Will Wilson](https://www.youtube.com/watch?v=4fFDFbi3toc) - [(video) FF meetup #4 - Deterministic simulation testing](https://www.youtube.com/live/29Vz5wkoUR8) - [(code) Hiisi: a proof of concept libSQL written in Rust following TigerBeetle-style with deterministic simulation testing](https://github.com/penberg/hiisi) + +## MVCC validation + +MVCC generation uses explicit INTEGER PRIMARY KEY values in INSERTs and UPSERTs. +Its row model predicts implicit keys from the currently visible maximum, but +MVCC allocation can retain reservations after rollback. Comparing those +predicted keys would report a false failure. WAL generation retains implicit-key +generation. + +The final integrity check uses Turso for MVCC and SQLite for WAL. Memory-I/O +exports include the MVCC logical log so retained failure artifacts can be +reopened with their committed state. diff --git a/testing/simulator/main.rs b/testing/simulator/main.rs index 6191da6a3..4b24ae709 100644 --- a/testing/simulator/main.rs +++ b/testing/simulator/main.rs @@ -11,7 +11,6 @@ use std::any::Any; use std::backtrace::Backtrace; use std::fs::OpenOptions; use std::io::{IsTerminal, Write}; -use std::path::Path; use std::rc::Rc; use std::sync::{Arc, Mutex}; use tracing_subscriber::EnvFilter; @@ -531,7 +530,7 @@ fn run_simulation_default( if env.opts.disable_integrity_check { tracing::info!("skipping integrity check (disabled by configuration)"); } else { - let ic = integrity_check(&env.get_db_path()); + let ic = simulation_integrity_check(&env); if let Err(err) = ic { tracing::error!("integrity check failed: {}", err); result.error = Some(turso_core::LimboError::InternalError(err.to_string())); @@ -603,23 +602,108 @@ const BANNER: &str = r#" "#; -fn integrity_check(db_path: &Path) -> anyhow::Result<()> { - assert!(db_path.exists()); - let conn = rusqlite::Connection::open(db_path)?; - let mut stmt = conn.prepare("SELECT * FROM pragma_integrity_check;")?; - let mut rows = stmt.query(())?; +fn simulation_integrity_check(env: &SimulatorEnv) -> anyhow::Result<()> { let mut result: Vec = Vec::new(); - - while let Some(row) = rows.next()? { - result.push(row.get(0)?); + if env.profile.mvcc { + let connection = env + .db + .as_ref() + .expect("simulation database exists") + .connect(turso_core::ConnectOpts::new())?; + let mut statement = connection.prepare("PRAGMA integrity_check")?; + statement.run_with_row_callback(|row| { + result.push(row.get::(0)?); + Ok(()) + })?; + } else { + let db_path = env.get_db_path(); + assert!(db_path.exists()); + let connection = rusqlite::Connection::open(db_path)?; + let mut statement = connection.prepare("SELECT * FROM pragma_integrity_check")?; + let mut rows = statement.query(())?; + while let Some(row) = rows.next()? { + result.push(row.get(0)?); + } } if result.is_empty() { anyhow::bail!("simulation failed: integrity_check should return `ok` or a list of problems") } - if !result[0].eq_ignore_ascii_case("ok") { - // Build a list of problems - result.iter_mut().for_each(|row| *row = format!("- {row}")); + if result.len() != 1 || !result[0].eq_ignore_ascii_case("ok") { anyhow::bail!("simulation failed: {}", result.join("\n")) } Ok(()) } + +#[cfg(test)] +mod integrity_tests { + use super::*; + + #[test] + fn wal_integrity_check_uses_exported_database() -> anyhow::Result<()> { + let output = tempfile::tempdir()?; + let args = SimulatorCLI::parse_from(["limbo_sim", "--io-backend", "memory"]); + let env = SimulatorEnv::new( + 1, + &args, + Paths::new(output.path()), + SimulationType::Default, + &Profile::faultless(), + ); + let connection = env + .db + .as_ref() + .unwrap() + .connect(turso_core::ConnectOpts::new())?; + connection.execute("CREATE TABLE checked(id INTEGER PRIMARY KEY)")?; + connection.execute("INSERT INTO checked VALUES (42)")?; + env.io.persist_files()?; + simulation_integrity_check(&env)?; + Ok(()) + } + + #[test] + fn mvcc_integrity_check_and_export_include_committed_log() -> anyhow::Result<()> { + let output = tempfile::tempdir()?; + let args = SimulatorCLI::parse_from(["limbo_sim", "--io-backend", "memory"]); + let env = SimulatorEnv::new( + 1, + &args, + Paths::new(output.path()), + SimulationType::Default, + &Profile { + mvcc: true, + ..Profile::faultless() + }, + ); + let connection = env + .db + .as_ref() + .unwrap() + .connect(turso_core::ConnectOpts::new())?; + connection.execute("CREATE TABLE checked(id INTEGER PRIMARY KEY)")?; + connection.execute("INSERT INTO checked VALUES (42)")?; + connection.execute("CREATE SEQUENCE checked_seq START 10")?; + connection.execute("SELECT nextval('checked_seq')")?; + env.io.persist_files()?; + simulation_integrity_check(&env)?; + assert!(env.get_db_path().with_extension("db-log").metadata()?.len() > 0); + let path = env.get_db_path(); + drop(connection); + drop(env); + let reopened = turso_core::Database::open_file( + Arc::new(turso_core::PlatformIO::new()?), + path.to_str().unwrap(), + Arc::new(turso_core::SqliteDialect), + )? + .connect(turso_core::ConnectOpts::new())?; + let rows = reopened + .prepare("SELECT id FROM checked")? + .run_collect_rows()?; + assert_eq!(rows[0][0].as_int(), Some(42)); + let rows = reopened + .prepare("SELECT nextval('checked_seq')")? + .run_collect_rows()?; + assert_eq!(rows[0][0].as_int(), Some(11)); + Ok(()) + } +} diff --git a/testing/simulator/runner/env.rs b/testing/simulator/runner/env.rs index 62a160f6c..22ad8016f 100644 --- a/testing/simulator/runner/env.rs +++ b/testing/simulator/runner/env.rs @@ -949,6 +949,37 @@ mod tests { } } + #[test] + fn mvcc_generation_requires_explicit_rowids() { + use clap::Parser; + for mvcc in [false, true] { + let output = tempfile::tempdir().unwrap(); + let args = SimulatorCLI::parse_from([ + "limbo_sim", + "--io-backend", + "memory", + "--mvcc", + if mvcc { "true" } else { "false" }, + ]); + let env = SimulatorEnv::new( + 1, + &args, + Paths::new(output.path()), + SimulationType::Default, + &Profile::default(), + ); + assert_eq!( + env.profile + .query + .gen_opts + .query + .insert + .allow_implicit_rowids, + !mvcc + ); + } + } + #[test] fn savepoint_outside_transaction_commits_on_release() { let mut commited_tables = Vec::new(); @@ -1462,6 +1493,9 @@ impl SimulatorEnv { if let Some(mvcc) = cli_opts.mvcc { profile.mvcc = mvcc; } + if profile.mvcc { + profile.query.gen_opts.query.insert.allow_implicit_rowids = false; + } if let Some(latency_prob) = cli_opts.latency_probability { profile.io.latency.latency_probability = latency_prob; } diff --git a/testing/simulator/runner/memory/io.rs b/testing/simulator/runner/memory/io.rs index bd8c09051..d3111aaa9 100644 --- a/testing/simulator/runner/memory/io.rs +++ b/testing/simulator/runner/memory/io.rs @@ -352,7 +352,10 @@ impl SimIO for MemorySimIO { fn persist_files(&self) -> anyhow::Result<()> { let files = self.files.borrow(); for (file_path, file) in files.iter() { - if file_path.ends_with(".db") || file_path.ends_with("wal") || file_path.ends_with("lg") + if file_path.ends_with(".db") + || file_path.ends_with("wal") + || file_path.ends_with("lg") + || file_path.ends_with(".db-log") { let state = file.state.borrow(); let mut output = BufWriter::new(std::fs::File::create(file_path)?);