Reproduce bug regarding materialized views and btree balancing

This commit is contained in:
Martin Mauch
2025-12-04 00:12:41 +01:00
parent b70e64b1b0
commit d7070669a7
3 changed files with 106 additions and 1 deletions

View File

@@ -36,6 +36,7 @@ impl<T: ToTokens> ToTokens for SpannedType<T> {
struct Args {
path: Option<SpannedType<String>>,
mvcc: Option<SpannedType<()>>,
views: Option<SpannedType<()>>,
init_sql: Option<Expr>,
}
@@ -78,6 +79,14 @@ impl Args {
};
}
// Enable views if requested
if self.views.is_some() {
builder = quote! {
#builder
.with_views(true)
};
}
// Add init_sql if provided
if let Some(user_sql) = &self.init_sql {
builder = quote! {
@@ -99,6 +108,7 @@ impl Parse for Args {
let mut path = None;
let mut mvcc = None;
let mut views = None;
let mut init_sql = None;
let errors = args
@@ -144,6 +154,9 @@ impl Parse for Args {
if p.is_ident("mvcc") {
mvcc = Some(SpannedType((), p.span()));
seen_args.insert(ident.unwrap().clone());
} else if p.is_ident("views") {
views = Some(SpannedType((), p.span()));
seen_args.insert(ident.unwrap().clone());
} else {
return Some(syn::Error::new_spanned(p, "unexpected flag"));
}
@@ -166,6 +179,7 @@ impl Parse for Args {
Ok(Args {
path,
mvcc,
views,
init_sql,
})
}

View File

@@ -30,6 +30,7 @@ pub struct TempDatabaseBuilder {
init_sql: Option<String>,
enable_mvcc: bool,
io_uring: bool,
enable_views: bool,
}
struct TestIo {
@@ -105,6 +106,7 @@ impl TempDatabaseBuilder {
init_sql: None,
enable_mvcc: false,
io_uring: false,
enable_views: false,
}
}
@@ -156,11 +158,20 @@ impl TempDatabaseBuilder {
self
}
pub fn with_views(mut self, enable: bool) -> Self {
self.enable_views = enable;
self
}
pub fn build(self) -> TempDatabase {
let opts = self
let mut opts = self
.opts
.unwrap_or_else(|| turso_core::DatabaseOpts::new().with_encryption(true));
if self.enable_views {
opts = opts.with_views(true);
}
let flags = self.flags.unwrap_or_default();
let db_path = match self.db_path {

View File

@@ -1598,3 +1598,83 @@ pub fn test_mvcc_stale_snapshot_after_schema_updated() {
conn1.execute("COMMIT").unwrap();
}
/// Test materialized view population with enough rows to trigger btree page splits.
///
/// This test exposes a bug where the matview code doesn't properly handle
/// btree operations during page splits, causing rows to be silently lost.
/// The bug triggers around row 193 with 500-byte content - the matview stops
/// accepting new rows and freezes at 192.
///
/// Key conditions:
/// - TEXT PRIMARY KEY (not INTEGER)
/// - 500+ byte content column
/// - Each INSERT in a separate connection (simulating CLI usage)
#[turso_macros::test(views)]
fn test_matview_row_loss_during_btree_split(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
// Create table with TEXT PRIMARY KEY and content column
common::run_query(
&tmp_db,
&conn,
"CREATE TABLE t (id TEXT PRIMARY KEY, title TEXT, content TEXT)",
)?;
common::run_query(
&tmp_db,
&conn,
"CREATE MATERIALIZED VIEW v AS SELECT id, title FROM t",
)?;
// Insert 250 rows with 500-byte content
// Each insert uses a fresh connection to simulate CLI behavior
let content = "x".repeat(500);
for i in 1..=250 {
let insert_conn = tmp_db.connect_limbo();
let insert_sql = format!("INSERT INTO t VALUES ('id{i}', 'title {i}', '{content}')");
common::run_query(&tmp_db, &insert_conn, &insert_sql)?;
}
// Check counts with fresh connection
let check_conn = tmp_db.connect_limbo();
let mut table_count = 0i64;
match check_conn.query("SELECT COUNT(*) FROM t") {
Ok(Some(ref mut rows)) => loop {
match rows.step()? {
StepResult::Row => {
table_count = rows.row().unwrap().get::<i64>(0).unwrap();
}
StepResult::IO => rows._io().step()?,
StepResult::Done => break,
_ => {}
}
},
Ok(None) => {}
Err(e) => return Err(e.into()),
}
let mut view_count = 0i64;
match check_conn.query("SELECT COUNT(*) FROM v") {
Ok(Some(ref mut rows)) => loop {
match rows.step()? {
StepResult::Row => {
view_count = rows.row().unwrap().get::<i64>(0).unwrap();
}
StepResult::IO => rows._io().step()?,
StepResult::Done => break,
_ => {}
}
},
Ok(None) => {}
Err(e) => return Err(e.into()),
}
assert_eq!(
table_count, view_count,
"Materialized view row count ({view_count}) doesn't match table row count ({table_count}). \
Rows were lost during btree page splits.",
);
Ok(())
}