simulator: correct MVCC rowid assumptions and validation

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.
This commit is contained in:
Glauber Costa
2026-10-04 19:15:00 -05:00
parent 809c89b1c4
commit e6f0981b43
6 changed files with 219 additions and 17 deletions

View File

@@ -215,6 +215,8 @@ pub struct InsertOpts {
pub max_rows: NonZeroU32, pub max_rows: NonZeroU32,
#[garde(range(min = 0.0, max = 1.0))] #[garde(range(min = 0.0, max = 1.0))]
pub upsert_prob: f64, pub upsert_prob: f64,
#[garde(skip)]
pub allow_implicit_rowids: bool,
} }
impl Default for InsertOpts { impl Default for InsertOpts {
@@ -223,6 +225,7 @@ impl Default for InsertOpts {
min_rows: NonZero::new(1).unwrap(), min_rows: NonZero::new(1).unwrap(),
max_rows: NonZero::new(10).unwrap(), max_rows: NonZero::new(10).unwrap(),
upsert_prob: 0.15, upsert_prob: 0.15,
allow_implicit_rowids: true,
} }
} }
} }

View File

@@ -431,7 +431,10 @@ fn gen_insert_values<R: Rng + ?Sized, C: GenerationContext>(
.iter() .iter()
.enumerate() .enumerate()
.map(|(col_idx, c)| { .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; return SimValue::NULL;
} }
if c.has_unique_or_pk() { if c.has_unique_or_pk() {
@@ -473,7 +476,6 @@ fn gen_insert_upsert_values<R: Rng + ?Sized, C: GenerationContext>(
const UNIQUE_COL_STRIDE: i64 = 10_000_000; const UNIQUE_COL_STRIDE: i64 = 10_000_000;
const FRESH_ID_JITTER: i64 = 5; const FRESH_ID_JITTER: i64 = 5;
const PAYLOAD_OFFSET_BUMP: i64 = 42; const PAYLOAD_OFFSET_BUMP: i64 = 42;
const UPSERT_INTEGER_PK_NULL_PROB: f64 = 0.25;
if !rng.random_bool(insert_opts.upsert_prob) { if !rng.random_bool(insert_opts.upsert_prob) {
return None; return None;
@@ -604,7 +606,7 @@ fn gen_insert_upsert_values<R: Rng + ?Sized, C: GenerationContext>(
); );
} }
row[pk_idx] = SimValue::unique_for_type(&pk_col.column_type, new_id); 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; 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()));
}
}
}

View File

@@ -136,3 +136,15 @@ Notes:
- [(video) "Testing Distributed Systems w/ Deterministic Simulation" by Will Wilson](https://www.youtube.com/watch?v=4fFDFbi3toc) - [(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) - [(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) - [(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.

View File

@@ -11,7 +11,6 @@ use std::any::Any;
use std::backtrace::Backtrace; use std::backtrace::Backtrace;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::{IsTerminal, Write}; use std::io::{IsTerminal, Write};
use std::path::Path;
use std::rc::Rc; use std::rc::Rc;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
@@ -531,7 +530,7 @@ fn run_simulation_default(
if env.opts.disable_integrity_check { if env.opts.disable_integrity_check {
tracing::info!("skipping integrity check (disabled by configuration)"); tracing::info!("skipping integrity check (disabled by configuration)");
} else { } else {
let ic = integrity_check(&env.get_db_path()); let ic = simulation_integrity_check(&env);
if let Err(err) = ic { if let Err(err) = ic {
tracing::error!("integrity check failed: {}", err); tracing::error!("integrity check failed: {}", err);
result.error = Some(turso_core::LimboError::InternalError(err.to_string())); 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<()> { fn simulation_integrity_check(env: &SimulatorEnv) -> 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(())?;
let mut result: Vec<String> = Vec::new(); let mut result: Vec<String> = Vec::new();
if env.profile.mvcc {
while let Some(row) = rows.next()? { let connection = env
result.push(row.get(0)?); .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::<String>(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() { if result.is_empty() {
anyhow::bail!("simulation failed: integrity_check should return `ok` or a list of problems") anyhow::bail!("simulation failed: integrity_check should return `ok` or a list of problems")
} }
if !result[0].eq_ignore_ascii_case("ok") { if result.len() != 1 || !result[0].eq_ignore_ascii_case("ok") {
// Build a list of problems
result.iter_mut().for_each(|row| *row = format!("- {row}"));
anyhow::bail!("simulation failed: {}", result.join("\n")) anyhow::bail!("simulation failed: {}", result.join("\n"))
} }
Ok(()) 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(())
}
}

View File

@@ -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] #[test]
fn savepoint_outside_transaction_commits_on_release() { fn savepoint_outside_transaction_commits_on_release() {
let mut commited_tables = Vec::new(); let mut commited_tables = Vec::new();
@@ -1462,6 +1493,9 @@ impl SimulatorEnv {
if let Some(mvcc) = cli_opts.mvcc { if let Some(mvcc) = cli_opts.mvcc {
profile.mvcc = 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 { if let Some(latency_prob) = cli_opts.latency_probability {
profile.io.latency.latency_probability = latency_prob; profile.io.latency.latency_probability = latency_prob;
} }

View File

@@ -352,7 +352,10 @@ impl SimIO for MemorySimIO {
fn persist_files(&self) -> anyhow::Result<()> { fn persist_files(&self) -> anyhow::Result<()> {
let files = self.files.borrow(); let files = self.files.borrow();
for (file_path, file) in files.iter() { 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 state = file.state.borrow();
let mut output = BufWriter::new(std::fs::File::create(file_path)?); let mut output = BufWriter::new(std::fs::File::create(file_path)?);