mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
When the WAL is fully checkpointed, a new read transaction skips the WAL and reads pages only from the database file. In multiprocess mode, other processes could not see such a reader: it held read lock 0, but that lock exists only inside its own process, and the reader did not register in the shared reader table in the .tshm file. A checkpoint in another process could therefore copy newer WAL frames into the database file while the reader was still using its older snapshot, and the reader saw a mix of old and new pages. The concurrent simulator hit this as FTS index corruption. Preston Thorpe's commit121d5e5db, which added multiprocess WAL support, did register these readers in the shared reader table, one slot per reader. The follow-up commit94c912fb0removed the registration a day later because many concurrent readers used up all the slots and new connections failed with Busy. The test for that case was changed to assert that these readers register nothing, so the missing protection went unnoticed. This change registers them again, but all such readers in one process share a single slot, so they no longer run out of slots. While any process has one registered, checkpoints in every process stop at the current backfill point. This is the cross-process version of the read lock 0 that a checkpoint already takes within one process, and it matches SQLite. WAL restarts are still allowed, as in SQLite, because these readers never read the WAL. Blocking restarts as well would make the WAL grow without bound, because the restart before a write only runs when the writer itself is one of these readers. A failed registration now also releases the local read lock, which the WAL reader path used to leak. tlaplus/multiprocess/MultiprocessWal.tla models this coordination: the local read locks, the shared reader table, the snapshot recheck when a read begins, checkpoints that copy frames one at a time, and the restart before a write. TLC checks every state of two processes with two connections each and up to three commits (32 million states) and finds no case where the database file holds a newer version than an active reader's snapshot or where the WAL restarts under a WAL reader. With database file readers left out of the shared reader table, TLC finds this bug in 13 steps. Aristo intents on the coordinator state the same rules at the code sites that enforce them: the checkpoint safe frame stays below every reader in every process, database file readers register in the shared table and recheck the snapshot afterwards, the restart ignores database file readers, and frame zero in a reader slot marks a database file reader. One assume records that the tshm mapping is shared by every process on the host. testing/antithesis/multiprocess is a new Antithesis workload where every driver is its own process and opens the database with the multiprocess WAL feature. Writers stamp every row with the commit's generation, so every commit rewrites every page. Readers pin a snapshot by reading one row, then spawn a child process that commits and runs a passive checkpoint under that snapshot, and then scan the whole table, so the later pages come from the database file instead of the reader's page cache. The child makes the cross-process overlap happen on every read instead of waiting for the test composer to schedule it, which it rarely does because it throttles parallel drivers on CPU use. A checkpoint that copies newer frames under the snapshot shows up as rows from two generations in one scan. Without the fix a local 30 second run reports torn reads dozens of times; with the fix a 60 second run is clean. Tests: core/multiprocess_tests.rs - subprocess_db_file_reader_stops_checkpoint_in_other_process - subprocess_db_file_reader_allows_wal_restart_but_stops_backfill - write_after_full_checkpoint_restarts_wal Tests: testing/antithesis/multiprocess Fixes #8648
3044 lines
112 KiB
Rust
3044 lines
112 KiB
Rust
use super::*;
|
|
use crate::storage::database::DatabaseFile;
|
|
use crate::sync::atomic::Ordering;
|
|
use std::process::Command;
|
|
use std::time::Duration;
|
|
|
|
#[cfg(all(target_os = "windows", feature = "experimental_win_iocp"))]
|
|
use crate::WindowsIOCP;
|
|
#[cfg(unix)]
|
|
use std::os::unix::process::ExitStatusExt;
|
|
|
|
const MULTIPROCESS_SEQUENCE_NEXTVAL_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_sequence_nextval_child_process";
|
|
|
|
const MULTIPROCESS_SEQUENCE_NEXTVAL_BURST_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_sequence_nextval_burst_child_process";
|
|
|
|
const MULTIPROCESS_AUTOINC_BURST_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_autoinc_burst_child_process";
|
|
|
|
const MULTIPROCESS_SHM_INSERT_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_insert_child_process";
|
|
const MULTIPROCESS_SHM_COUNT_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_count_child_process";
|
|
const MULTIPROCESS_SHM_HOLD_READ_TX_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_hold_read_tx_child_process";
|
|
const MULTIPROCESS_SHM_DB_FILE_READER_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_db_file_reader_child_process";
|
|
const MULTIPROCESS_SHM_SCHEMA_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_schema_child_process";
|
|
const MULTIPROCESS_SHM_INSERT_AND_CLOSE_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_insert_and_close_child_process";
|
|
const MULTIPROCESS_SHM_EXPECT_OPEN_FAILURE_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_shm_expect_open_failure_child_process";
|
|
const DEFAULT_LOCKED_DB_CHILD_TEST: &str = "multiprocess_tests::default_locked_db_child_process";
|
|
const MULTIPROCESS_ASYNC_OPEN_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_async_open_child_process";
|
|
const MULTIPROCESS_HOLD_OPEN_CHILD_TEST: &str =
|
|
"multiprocess_tests::multiprocess_hold_open_child_process";
|
|
|
|
fn multiprocess_test_io() -> Arc<dyn IO> {
|
|
#[cfg(all(target_os = "windows", feature = "experimental_win_iocp"))]
|
|
{
|
|
Arc::new(WindowsIOCP::new().unwrap())
|
|
}
|
|
|
|
#[cfg(not(all(target_os = "windows", feature = "experimental_win_iocp")))]
|
|
{
|
|
Arc::new(PlatformIO::new().unwrap())
|
|
}
|
|
}
|
|
|
|
fn count_test_rows(conn: &Arc<Connection>) -> i64 {
|
|
let mut stmt = conn.prepare("select count(*) from test").unwrap();
|
|
let mut count = 0;
|
|
stmt.run_with_row_callback(|row| {
|
|
count = row.get(0).unwrap();
|
|
Ok(())
|
|
})
|
|
.unwrap();
|
|
count
|
|
}
|
|
|
|
fn get_rows(conn: &Arc<Connection>, query: &str) -> Vec<Vec<Value>> {
|
|
for _attempt in 0..3 {
|
|
let mut stmt = match conn.prepare(query) {
|
|
Ok(s) => s,
|
|
Err(LimboError::SchemaUpdated) => {
|
|
conn.maybe_reparse_schema().unwrap();
|
|
continue;
|
|
}
|
|
Err(e) => panic!("prepare failed: {e}"),
|
|
};
|
|
let mut rows = Vec::new();
|
|
match stmt.run_with_row_callback(|row| {
|
|
rows.push(row.get_values().cloned().collect::<Vec<_>>());
|
|
Ok(())
|
|
}) {
|
|
Ok(()) => return rows,
|
|
Err(LimboError::SchemaUpdated) => {
|
|
drop(stmt);
|
|
conn.maybe_reparse_schema().unwrap();
|
|
continue;
|
|
}
|
|
Err(e) => panic!("run_with_row_callback failed: {e}"),
|
|
}
|
|
}
|
|
panic!("get_rows: exhausted SchemaUpdated retries for: {query}");
|
|
}
|
|
|
|
fn get_rows_without_schema_retry(conn: &Arc<Connection>, query: &str) -> Vec<Vec<Value>> {
|
|
let mut stmt = conn.prepare(query).unwrap();
|
|
let mut rows = Vec::new();
|
|
stmt.run_with_row_callback(|row| {
|
|
rows.push(row.get_values().cloned().collect::<Vec<_>>());
|
|
Ok(())
|
|
})
|
|
.unwrap();
|
|
rows
|
|
}
|
|
|
|
fn run_checkpoint(conn: &Arc<Connection>, mode: CheckpointMode) -> CheckpointResult {
|
|
let pager = conn.pager.load();
|
|
pager
|
|
.io
|
|
.block(|| pager.checkpoint(mode, SyncMode::Full, true))
|
|
.unwrap()
|
|
}
|
|
|
|
fn wal_max_frame(conn: &Arc<Connection>) -> u64 {
|
|
conn.pager
|
|
.load()
|
|
.wal
|
|
.as_ref()
|
|
.expect("wal should be present")
|
|
.get_max_frame_in_wal()
|
|
}
|
|
|
|
fn wait_for_file(path: &std::path::Path) {
|
|
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
|
while std::time::Instant::now() < deadline {
|
|
if path.exists() {
|
|
return;
|
|
}
|
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
|
}
|
|
panic!("timed out waiting for {}", path.display());
|
|
}
|
|
|
|
fn multiprocess_wal_db_opts() -> DatabaseOpts {
|
|
DatabaseOpts::new().with_multiprocess_wal(true)
|
|
}
|
|
|
|
fn open_multiprocess_db(io: Arc<dyn IO>, path: &str) -> Result<Arc<Database>> {
|
|
Database::open_file_with_flags(
|
|
io,
|
|
path,
|
|
OpenFlags::default(),
|
|
multiprocess_wal_db_opts(),
|
|
None,
|
|
Arc::new(SqliteDialect),
|
|
)
|
|
}
|
|
|
|
/// Mimic the sdk-kit async open path: the caller pre-opens the DB file with
|
|
/// NoLock but hands `OpenFlags::default()` to `open_async`, so the async
|
|
/// entrypoint itself must re-derive the multiprocess lock mode before the WAL
|
|
/// file is opened.
|
|
fn open_multiprocess_db_async(io: Arc<dyn IO>, path: &str) -> Result<Arc<Database>> {
|
|
let file = io.open_file(path, OpenFlags::default() | OpenFlags::NoLock, true)?;
|
|
let db_file = Arc::new(DatabaseFile::new(file));
|
|
let options = OpenOptions::new(Arc::new(SqliteDialect))
|
|
.storage(db_file)
|
|
.db_opts(multiprocess_wal_db_opts());
|
|
let mut state = OpenDbAsyncState::new();
|
|
loop {
|
|
match Database::open_async(&mut state, io.clone(), path, &options)? {
|
|
IOResult::Done(db) => return Ok(db),
|
|
IOResult::IO(io_completion) => io_completion.wait(&*io)?,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn open_multiprocess_db_with_flags(
|
|
io: Arc<dyn IO>,
|
|
path: &str,
|
|
flags: OpenFlags,
|
|
) -> Result<Arc<Database>> {
|
|
Database::open_file_with_flags(
|
|
io,
|
|
path,
|
|
flags,
|
|
multiprocess_wal_db_opts(),
|
|
None,
|
|
Arc::new(SqliteDialect),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn open_db_async_state_drop_clears_opening_registry_entry() {
|
|
let key = DatabaseKey::SharedMemory(
|
|
"open-db-async-state-drop-clears-opening-registry-entry".to_string(),
|
|
);
|
|
{
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
manager.insert(key.clone(), RegistryEntry::Opening);
|
|
}
|
|
|
|
let mut state = OpenDbAsyncState::new();
|
|
state.registry_key = Some(key.clone());
|
|
drop(state);
|
|
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
assert!(
|
|
!manager.contains_key(&key),
|
|
"dropping an incomplete async open must clear the Opening sentinel"
|
|
);
|
|
manager.clear();
|
|
}
|
|
|
|
fn flip_db_header_reserved_byte(path: &std::path::Path) {
|
|
use std::io::{Read, Seek, SeekFrom, Write};
|
|
|
|
let mut file = std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(path)
|
|
.unwrap();
|
|
|
|
#[cfg(feature = "checksum")]
|
|
{
|
|
let mut page = vec![0u8; 4096];
|
|
file.read_exact(&mut page).unwrap();
|
|
page[72] ^= 0x01;
|
|
crate::storage::checksum::ChecksumContext::new()
|
|
.add_checksum_to_page(&mut page, 1)
|
|
.unwrap();
|
|
file.seek(SeekFrom::Start(0)).unwrap();
|
|
file.write_all(&page).unwrap();
|
|
file.sync_all().unwrap();
|
|
}
|
|
|
|
#[cfg(not(feature = "checksum"))]
|
|
{
|
|
file.seek(SeekFrom::Start(72)).unwrap();
|
|
let mut byte = [0u8; 1];
|
|
file.read_exact(&mut byte).unwrap();
|
|
byte[0] ^= 0x01;
|
|
file.seek(SeekFrom::Start(72)).unwrap();
|
|
file.write_all(&byte).unwrap();
|
|
file.sync_all().unwrap();
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
fn shared_wal_coordination_rejects_remote_filesystem_magic_values() {
|
|
assert!(!Database::filesystem_magic_allows_shared_wal(0x6969));
|
|
assert!(!Database::filesystem_magic_allows_shared_wal(
|
|
0xFF53_4D42u32 as libc::c_long,
|
|
));
|
|
assert!(!Database::filesystem_magic_allows_shared_wal(0x0102_1997));
|
|
assert!(Database::filesystem_magic_allows_shared_wal(0xEF53));
|
|
assert!(Database::filesystem_magic_allows_shared_wal(0x0102_1994));
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(host_shared_wal)]
|
|
fn shared_wal_coordination_path_probe_accepts_nonexistent_relative_paths() {
|
|
let result = Database::path_allows_shared_wal_coordination(std::path::Path::new(
|
|
"nonexistent-relative-multiprocess-wal.db",
|
|
));
|
|
assert!(
|
|
result.is_ok(),
|
|
"nonexistent relative paths should probe the current directory instead of erroring: {result:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_without_experimental_multiprocess_wal_uses_in_process_backend() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-default-off.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = Database::open_file(io, db_path_str, Arc::new(SqliteDialect)).unwrap();
|
|
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "in_process");
|
|
assert!(db.shared_wal_coordination().unwrap().is_none());
|
|
|
|
let shm_path = storage::wal::coordination_path_for_wal_path(&format!("{db_path_str}-wal"));
|
|
assert!(!std::path::Path::new(&shm_path).exists());
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_without_experimental_multiprocess_wal_rejects_second_process() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-default-locked.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let _db = Database::open_file(io, db_path_str, Arc::new(SqliteDialect)).unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let child_output = Command::new(¤t_exe)
|
|
.arg(DEFAULT_LOCKED_DB_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
child_output.status.success(),
|
|
"second default-open child process unexpectedly succeeded: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&child_output.stdout),
|
|
String::from_utf8_lossy(&child_output.stderr)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_with_experimental_multiprocess_wal_rejects_unsupported_io_backend() {
|
|
let io: Arc<dyn IO> = Arc::new(MemoryIO::new());
|
|
let err = Database::open_file_with_flags(
|
|
io,
|
|
"unsupported-multiprocess.db",
|
|
OpenFlags::default(),
|
|
multiprocess_wal_db_opts(),
|
|
None,
|
|
Arc::new(SqliteDialect),
|
|
)
|
|
.expect_err("multiprocess WAL should reject IO backends without shared coordination");
|
|
assert!(
|
|
matches!(err, LimboError::InvalidArgument(ref message) if message.contains("active IO backend")),
|
|
"expected InvalidArgument about unsupported IO backend, got {err:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_wal_rejects_journal_mode_mvcc_pragma() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("multiprocess-rejects-mvcc-pragma.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
let err = conn
|
|
.execute("PRAGMA journal_mode = mvcc")
|
|
.expect_err("switching a multiprocess-coordinated database to MVCC must be rejected");
|
|
assert!(
|
|
matches!(err, LimboError::InvalidArgument(ref message) if message.contains("multiprocess")),
|
|
"expected InvalidArgument about multiprocess WAL, got {err:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_wal_rejects_opening_mvcc_database() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("multiprocess-rejects-mvcc-open.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
{
|
|
let db = Database::open_file(io.clone(), db_path_str, Arc::new(SqliteDialect)).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("PRAGMA journal_mode = mvcc").unwrap();
|
|
conn.execute("insert into test(value) values ('mvcc-row')")
|
|
.unwrap();
|
|
}
|
|
|
|
let err = open_multiprocess_db(io, db_path_str)
|
|
.expect_err("opening an MVCC-marked database with multiprocess WAL must be rejected");
|
|
assert!(
|
|
matches!(err, LimboError::InvalidArgument(ref message) if message.contains("MVCC")),
|
|
"expected InvalidArgument about MVCC, got {err:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn readonly_open_with_experimental_multiprocess_wal_allows_missing_coordination_file() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("readonly-multiprocess-no-tshm.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
{
|
|
let db = Database::open_file(io.clone(), db_path_str, Arc::new(SqliteDialect)).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
}
|
|
|
|
let readonly = open_multiprocess_db_with_flags(io, db_path_str, OpenFlags::ReadOnly)
|
|
.expect("read-only open should degrade gracefully when no .tshm exists");
|
|
assert!(readonly.shared_wal_coordination().unwrap().is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_with_experimental_multiprocess_wal_rejects_second_default_process() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-multiprocess-parent-default-child.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let _db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let child_output = Command::new(¤t_exe)
|
|
.arg(DEFAULT_LOCKED_DB_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
child_output.status.success(),
|
|
"default-open child process unexpectedly succeeded against multiprocess parent: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&child_output.stdout),
|
|
String::from_utf8_lossy(&child_output.stderr)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_without_experimental_multiprocess_wal_rejects_second_multiprocess_process() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-default-parent-multiprocess-child.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let _db = Database::open_file(io, db_path_str, Arc::new(SqliteDialect)).unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let child_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_EXPECT_OPEN_FAILURE_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
child_output.status.success(),
|
|
"multiprocess child process unexpectedly opened against default parent: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&child_output.stdout),
|
|
String::from_utf8_lossy(&child_output.stderr)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_async_with_default_flags_allows_second_multiprocess_process() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-async-open.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db_async(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('parent')")
|
|
.unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let child_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_ASYNC_OPEN_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
child_output.status.success(),
|
|
"second async multiprocess open must not be blocked by a WAL file lock: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&child_output.stdout),
|
|
String::from_utf8_lossy(&child_output.stderr)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_async_open_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db_async(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
assert_eq!(count_test_rows(&conn), 1);
|
|
}
|
|
|
|
/// Child half of `reject_live_multiprocess_probe_uses_configured_wal_path`:
|
|
/// open the multiprocess database, hold it open (keeping the authority in
|
|
/// multiprocess mode), signal readiness, and wait for release before exiting.
|
|
#[test]
|
|
fn multiprocess_hold_open_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let ready_file = std::env::var_os("TURSO_MULTIPROCESS_READY_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
let release_file = std::env::var_os("TURSO_MULTIPROCESS_RELEASE_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let last = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db.build_wal(last, db.buffer_pool.clone()).unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
|
|
std::fs::write(&ready_file, b"ready").unwrap();
|
|
wait_for_file(&release_file);
|
|
}
|
|
|
|
/// The legacy/multiprocess probe keys the coordination file off the configured
|
|
/// WAL path, not a hard-coded `{path}-wal`. With a live multiprocess authority
|
|
/// held open by a child process, the probe rejects a legacy open only when it
|
|
/// inspects the WAL path that actually backs the authority; a probe pointed at
|
|
/// a different WAL path finds nothing. Before the fix, the probe hard-coded
|
|
/// `{path}-wal` and so missed the authority whenever a custom WAL path was in
|
|
/// use.
|
|
#[test]
|
|
fn reject_live_multiprocess_probe_uses_configured_wal_path() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("probe-wal-path.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
// Parent keeps the multiprocess database open so a second (child) opener
|
|
// flips the authority into multiprocess mode.
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_HOLD_OPEN_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.spawn()
|
|
.unwrap();
|
|
wait_for_file(&ready_file);
|
|
|
|
// Probing the WAL path that actually backs the authority finds it and
|
|
// rejects a legacy open.
|
|
let default_wal = format!("{db_path_str}-wal");
|
|
let err = Database::reject_live_multiprocess_wal_for_legacy_open(
|
|
&io,
|
|
db_path_str,
|
|
Some(&default_wal),
|
|
DatabaseOpts::new(),
|
|
)
|
|
.expect_err("legacy open over a live multiprocess authority must be rejected");
|
|
assert!(
|
|
matches!(err, LimboError::LockingError(_)),
|
|
"expected LockingError from the multiprocess probe, got {err:?}"
|
|
);
|
|
|
|
// Probing an unrelated WAL path must NOT reject: the coordination file is
|
|
// keyed on the WAL path, so the probe must honor its argument.
|
|
let other_wal = format!("{db_path_str}-other-wal");
|
|
Database::reject_live_multiprocess_wal_for_legacy_open(
|
|
&io,
|
|
db_path_str,
|
|
Some(&other_wal),
|
|
DatabaseOpts::new(),
|
|
)
|
|
.expect("probe over an unrelated wal path must not reject");
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
assert!(
|
|
child.wait().unwrap().success(),
|
|
"hold-open child should exit cleanly after release"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_selects_shm_wal_backend() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
|
|
let shm_path = storage::wal::coordination_path_for_wal_path(&format!("{db_path_str}-wal"));
|
|
assert!(std::path::Path::new(&shm_path).exists());
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_rebuilds_from_disk_scan_when_exclusive_shm_snapshot_is_stale() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-stale-reopen.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db_a = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn_a = db_a.connect().unwrap();
|
|
conn_a
|
|
.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn_a
|
|
.execute("insert into test(value) values ('before-stale')")
|
|
.unwrap();
|
|
|
|
let authority = db_a.shared_wal_coordination().unwrap().unwrap();
|
|
let stale_snapshot = authority.snapshot();
|
|
|
|
conn_a
|
|
.execute("insert into test(value) values ('after-stale')")
|
|
.unwrap();
|
|
|
|
authority.install_snapshot(stale_snapshot);
|
|
|
|
drop(conn_a);
|
|
drop(db_a);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let db_b = open_multiprocess_db(io, db_path_str).unwrap();
|
|
assert!(
|
|
db_b.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"cold reopen should fall back to a WAL disk scan when tshm snapshot is stale"
|
|
);
|
|
|
|
let conn_b = db_b.connect().unwrap();
|
|
let rows = get_rows(&conn_b, "select id, value from test order by id");
|
|
assert_eq!(rows.len(), 2);
|
|
assert_eq!(rows[0][0].as_int().unwrap(), 1);
|
|
assert_eq!(rows[0][1].to_string(), "before-stale");
|
|
assert_eq!(rows[1][0].as_int().unwrap(), 2);
|
|
assert_eq!(rows[1][1].to_string(), "after-stale");
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_reuses_trusted_tshm_snapshot_without_disk_scan_when_no_backfill_proof_is_needed() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-trusted-tail-reopen.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('before-reopen')")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('after-reopen')")
|
|
.unwrap();
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_before = authority.snapshot();
|
|
assert!(
|
|
snapshot_before.max_frame > 0,
|
|
"trusted-tail reopen coverage requires committed WAL frames before reopen"
|
|
);
|
|
assert_eq!(
|
|
snapshot_before.nbackfills, 0,
|
|
"this coverage only applies when no positive backfill proof is required"
|
|
);
|
|
let frames_before = authority.iter_latest_frames(0, snapshot_before.max_frame);
|
|
assert!(
|
|
!frames_before.is_empty(),
|
|
"trusted-tail reopen coverage requires a populated durable frame index"
|
|
);
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
assert!(
|
|
!reopened
|
|
.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"reopen should trust the persisted tshm snapshot when no backfill-proof validation is needed"
|
|
);
|
|
|
|
let reopened_authority = reopened.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(
|
|
reopened_authority.snapshot(),
|
|
snapshot_before,
|
|
"trusted reopen must preserve the authoritative WAL snapshot"
|
|
);
|
|
assert_eq!(
|
|
reopened_authority.iter_latest_frames(0, snapshot_before.max_frame),
|
|
frames_before,
|
|
"trusted reopen must preserve durable frame-index content"
|
|
);
|
|
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(count_test_rows(&reopened_conn), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_rebuilds_from_disk_scan_after_partial_checkpoint_without_backfill_proof() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-partial-checkpoint-reopen-no-proof.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
assert!(
|
|
wal_max_frame(&conn) > 1,
|
|
"partial-checkpoint reopen coverage requires more than one WAL frame before checkpointing"
|
|
);
|
|
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: Some(1),
|
|
},
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_before = authority.snapshot();
|
|
assert!(
|
|
snapshot_before.nbackfills > 0,
|
|
"partial-checkpoint reopen coverage requires persisted positive nbackfills"
|
|
);
|
|
assert!(
|
|
snapshot_before.max_frame > snapshot_before.nbackfills,
|
|
"partial-checkpoint reopen coverage requires live WAL frames beyond the backfill point"
|
|
);
|
|
authority.clear_backfill_proof();
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let mut expected_snapshot = snapshot_before;
|
|
expected_snapshot.nbackfills = 0;
|
|
assert!(
|
|
reopened
|
|
.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"reopen must rebuild shared WAL state from disk when positive nbackfills are not durably provable"
|
|
);
|
|
|
|
let reopened_authority = reopened.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(
|
|
reopened_authority.snapshot(),
|
|
expected_snapshot,
|
|
"disk-scan reopen must preserve the WAL generation while clearing untrusted positive nbackfills"
|
|
);
|
|
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
32,
|
|
"partial-checkpoint reopen should preserve committed rows after the conservative disk scan"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_rebuilds_from_disk_scan_after_wal_append_invalidates_backfill_proof() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-partial-checkpoint-reopen-stale-proof.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: Some(1),
|
|
},
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_after_checkpoint = authority.snapshot();
|
|
assert!(
|
|
snapshot_after_checkpoint.nbackfills > 0,
|
|
"stale-proof coverage requires a partial checkpoint that publishes positive nbackfills"
|
|
);
|
|
assert!(
|
|
snapshot_after_checkpoint.max_frame > snapshot_after_checkpoint.nbackfills,
|
|
"stale-proof coverage requires live WAL frames beyond the backfill point"
|
|
);
|
|
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
let snapshot_after_append = authority.snapshot();
|
|
assert!(
|
|
snapshot_after_append.max_frame > snapshot_after_checkpoint.max_frame,
|
|
"stale-proof coverage requires a WAL append after proof installation"
|
|
);
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
assert!(
|
|
reopened
|
|
.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"reopen must rebuild from disk after a WAL append invalidates the tshm backfill proof"
|
|
);
|
|
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
33,
|
|
"stale-proof reopen should preserve rows committed after the partial checkpoint"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_rebuilds_from_disk_scan_after_db_header_mismatch_invalidates_backfill_proof() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-partial-checkpoint-reopen-db-header-mismatch.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: Some(1),
|
|
},
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_before = authority.snapshot();
|
|
assert!(
|
|
snapshot_before.nbackfills > 0,
|
|
"DB-header mismatch coverage requires a partial checkpoint that publishes positive nbackfills"
|
|
);
|
|
assert!(
|
|
snapshot_before.max_frame > snapshot_before.nbackfills,
|
|
"DB-header mismatch coverage requires live WAL frames beyond the backfill point"
|
|
);
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
flip_db_header_reserved_byte(&db_path);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let mut expected_snapshot = snapshot_before;
|
|
expected_snapshot.nbackfills = 0;
|
|
assert!(
|
|
reopened
|
|
.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"reopen must rebuild from disk when the DB header fingerprint no longer matches the tshm backfill proof"
|
|
);
|
|
|
|
let reopened_authority = reopened.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(
|
|
reopened_authority.snapshot(),
|
|
expected_snapshot,
|
|
"disk-scan reopen must preserve the WAL generation while clearing untrusted positive nbackfills"
|
|
);
|
|
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
32,
|
|
"DB-header-mismatch reopen should preserve committed rows after the conservative disk scan"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn default_locked_db_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let err = Database::open_file(io, db_path.to_str().unwrap(), Arc::new(SqliteDialect))
|
|
.expect_err("default non-multiprocess open should stay DB-file locked across processes");
|
|
assert!(
|
|
matches!(err, LimboError::LockingError(_)),
|
|
"expected LockingError from second default open, got {err:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_expect_open_failure_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let err = open_multiprocess_db(io, db_path.to_str().unwrap())
|
|
.expect_err("multiprocess open should fail when a legacy opener already owns the DB");
|
|
assert!(
|
|
matches!(err, LimboError::LockingError(_)),
|
|
"expected LockingError from incompatible multiprocess open, got {err:?}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_insert_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("insert into test(value) values ('child')")
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_insert_and_close_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("insert into test(value) values ('child-close')")
|
|
.unwrap();
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_count_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let expected_count = std::env::var("TURSO_MULTIPROCESS_EXPECTED_COUNT")
|
|
.unwrap()
|
|
.parse::<i64>()
|
|
.unwrap();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
|
|
let conn = db.connect().unwrap();
|
|
assert_eq!(count_test_rows(&conn), expected_count);
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_hold_read_tx_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let ready_file = std::env::var_os("TURSO_MULTIPROCESS_READY_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
let release_file = std::env::var_os("TURSO_MULTIPROCESS_RELEASE_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
let readonly = std::env::var_os("TURSO_MULTIPROCESS_READONLY").is_some();
|
|
let expect_disk_scan = std::env::var_os("TURSO_MULTIPROCESS_EXPECT_DISK_SCAN").is_some();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = if readonly {
|
|
open_multiprocess_db_with_flags(io, db_path.to_str().unwrap(), OpenFlags::ReadOnly).unwrap()
|
|
} else {
|
|
open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap()
|
|
};
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
assert_eq!(
|
|
db.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
expect_disk_scan,
|
|
"child reopen path did not match expected disk-scan behavior"
|
|
);
|
|
|
|
let conn = db.connect().unwrap();
|
|
let pager = conn.pager.load();
|
|
let wal = pager.wal.as_ref().unwrap();
|
|
wal.begin_read_tx().unwrap();
|
|
std::fs::write(&ready_file, b"ready").unwrap();
|
|
wait_for_file(&release_file);
|
|
wal.end_read_tx();
|
|
}
|
|
|
|
/// Opens a read transaction while the WAL is fully backfilled, so the
|
|
/// snapshot reads the database file directly, then reports what it sees in
|
|
/// a table it has not touched yet after the parent has changed and
|
|
/// checkpointed that table.
|
|
#[test]
|
|
fn multiprocess_shm_db_file_reader_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let ready_file = std::env::var_os("TURSO_MULTIPROCESS_READY_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
let release_file = std::env::var_os("TURSO_MULTIPROCESS_RELEASE_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
let result_file = std::env::var_os("TURSO_MULTIPROCESS_RESULT_FILE")
|
|
.map(std::path::PathBuf::from)
|
|
.unwrap();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("begin").unwrap();
|
|
assert_eq!(count_test_rows(&conn), 1);
|
|
std::fs::write(&ready_file, b"ready").unwrap();
|
|
wait_for_file(&release_file);
|
|
let rows = get_rows(&conn, "select value from other where id = 1");
|
|
let Value::Text(seen) = &rows[0][0] else {
|
|
panic!("unexpected row: {rows:?}");
|
|
};
|
|
std::fs::write(&result_file, seen.as_str()).unwrap();
|
|
conn.execute("commit").unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn multiprocess_shm_schema_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("multiprocess"));
|
|
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table child_table(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into child_table(value) values ('child-schema')")
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_selects_multiprocess_shm_backend() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-subprocess.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "tshm");
|
|
assert_eq!(wal_file.coordination_open_mode_name(), Some("exclusive"));
|
|
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('parent')")
|
|
.unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let insert_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_INSERT_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
insert_output.status.success(),
|
|
"child process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&insert_output.stdout),
|
|
String::from_utf8_lossy(&insert_output.stderr)
|
|
);
|
|
|
|
let count_output = Command::new(current_exe)
|
|
.arg(MULTIPROCESS_SHM_COUNT_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_EXPECTED_COUNT", "2")
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
count_output.status.success(),
|
|
"count child process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&count_output.stdout),
|
|
String::from_utf8_lossy(&count_output.stderr)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn plain_vacuum_rejects_multiprocess_wal_database() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("vacuum-multiprocess.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = Database::open_file_with_flags(
|
|
io,
|
|
db_path_str,
|
|
OpenFlags::default(),
|
|
multiprocess_wal_db_opts().with_vacuum(true),
|
|
None,
|
|
Arc::new(SqliteDialect),
|
|
)
|
|
.unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('parent')")
|
|
.unwrap();
|
|
|
|
let err = conn
|
|
.execute("VACUUM")
|
|
.expect_err("VACUUM should reject on a multiprocess-WAL database");
|
|
assert!(
|
|
matches!(err, LimboError::ParseError(ref msg) if msg.contains("experimental multiprocess WAL")),
|
|
"expected explicit multiprocess VACUUM rejection, got {err:?}"
|
|
);
|
|
assert_eq!(
|
|
count_test_rows(&conn),
|
|
1,
|
|
"rejecting VACUUM on a multiprocess-WAL database must not disturb the existing connection"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_child_close_skips_shutdown_checkpoint_in_multiprocess_wal_mode() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("close-skip-shutdown-checkpoint.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
},
|
|
);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let child_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_INSERT_AND_CLOSE_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
child_output.status.success(),
|
|
"child process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&child_output.stdout),
|
|
String::from_utf8_lossy(&child_output.stderr)
|
|
);
|
|
|
|
let wal_path = format!("{db_path_str}-wal");
|
|
let wal_len = std::fs::metadata(&wal_path)
|
|
.unwrap_or_else(|_| panic!("expected WAL file at {wal_path}"))
|
|
.len();
|
|
assert!(
|
|
wal_len > 0,
|
|
"child close should not run shutdown checkpoint while another process still has the DB open"
|
|
);
|
|
|
|
assert_eq!(
|
|
count_test_rows(&conn),
|
|
1,
|
|
"parent connection should still see the child commit via WAL"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_survives_truncate_rewrite_cycles() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-truncate-rewrite.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('parent-0')")
|
|
.unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
for expected_count in [2_i64, 3_i64] {
|
|
let insert_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_INSERT_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
insert_output.status.success(),
|
|
"child insert failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&insert_output.stdout),
|
|
String::from_utf8_lossy(&insert_output.stderr)
|
|
);
|
|
assert_eq!(count_test_rows(&conn), expected_count);
|
|
|
|
let checkpoint = run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
},
|
|
);
|
|
assert!(
|
|
checkpoint.everything_backfilled(),
|
|
"truncate checkpoint should fully backfill before WAL rewrite"
|
|
);
|
|
|
|
let count_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_COUNT_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_EXPECTED_COUNT",
|
|
expected_count.to_string(),
|
|
)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
count_output.status.success(),
|
|
"child count after truncate failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&count_output.stdout),
|
|
String::from_utf8_lossy(&count_output.stderr)
|
|
);
|
|
}
|
|
|
|
assert_eq!(count_test_rows(&conn), 3);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_peer_refreshes_remote_schema_without_reopen() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-peer-schema-refresh.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table t(value integer, next_value integer)")
|
|
.unwrap();
|
|
|
|
let series_rows = get_rows(&conn, "select value from generate_series(1, 3)");
|
|
assert_eq!(series_rows.len(), 3);
|
|
assert_eq!(series_rows[0][0].to_string(), "1");
|
|
assert_eq!(series_rows[1][0].to_string(), "2");
|
|
assert_eq!(series_rows[2][0].to_string(), "3");
|
|
|
|
let initial_schema_rows = get_rows(
|
|
&conn,
|
|
"select name, type from sqlite_schema where name = 'child_table'",
|
|
);
|
|
assert!(
|
|
initial_schema_rows.is_empty(),
|
|
"fresh parent connection should not see child_table before child creates it"
|
|
);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let schema_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_SCHEMA_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
schema_output.status.success(),
|
|
"child schema process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&schema_output.stdout),
|
|
String::from_utf8_lossy(&schema_output.stderr)
|
|
);
|
|
|
|
let schema_rows = get_rows_without_schema_retry(
|
|
&conn,
|
|
"select name, type from sqlite_schema where name = 'child_table'",
|
|
);
|
|
assert_eq!(schema_rows.len(), 1);
|
|
assert_eq!(schema_rows[0][0].to_string(), "child_table");
|
|
assert_eq!(schema_rows[0][1].to_string(), "table");
|
|
|
|
let child_rows = get_rows_without_schema_retry(&conn, "select value from child_table");
|
|
assert_eq!(child_rows.len(), 1);
|
|
assert_eq!(child_rows[0][0].to_string(), "child-schema");
|
|
|
|
conn.execute("insert into t select value, value + 1 from generate_series(1, 3)")
|
|
.unwrap();
|
|
let inserted_rows = get_rows(&conn, "select value, next_value from t order by value");
|
|
assert_eq!(inserted_rows.len(), 3);
|
|
assert_eq!(inserted_rows[0][0].to_string(), "1");
|
|
assert_eq!(inserted_rows[0][1].to_string(), "2");
|
|
assert_eq!(inserted_rows[2][0].to_string(), "3");
|
|
assert_eq!(inserted_rows[2][1].to_string(), "4");
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_parent_directly_uses_child_created_table() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-direct-child-table-use.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table t(value integer)").unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let schema_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_SCHEMA_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
schema_output.status.success(),
|
|
"child schema process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&schema_output.stdout),
|
|
String::from_utf8_lossy(&schema_output.stderr)
|
|
);
|
|
|
|
let mut stmt = conn
|
|
.prepare("insert into child_table(value) values ('parent-schema')")
|
|
.unwrap();
|
|
stmt.run_ignore_rows().unwrap();
|
|
|
|
let child_rows =
|
|
get_rows_without_schema_retry(&conn, "select value from child_table order by rowid");
|
|
assert_eq!(child_rows.len(), 2);
|
|
assert_eq!(child_rows[0][0].to_string(), "child-schema");
|
|
assert_eq!(child_rows[1][0].to_string(), "parent-schema");
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_parent_translated_stmt_uses_child_created_table() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-translated-child-table-use.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table t(value integer)").unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let schema_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_SCHEMA_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
schema_output.status.success(),
|
|
"child schema process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&schema_output.stdout),
|
|
String::from_utf8_lossy(&schema_output.stderr)
|
|
);
|
|
|
|
let input = "insert into child_table(value) values ('parent-schema')";
|
|
let (cmd, _) = crate::dialect::sqlite::parse(input).unwrap();
|
|
let Some(turso_parser::ast::Cmd::Stmt(stmt)) = cmd else {
|
|
panic!("translated statement input did not parse as a statement");
|
|
};
|
|
conn.prepare_translated_stmt(stmt, input)
|
|
.unwrap()
|
|
.run_ignore_rows()
|
|
.unwrap();
|
|
|
|
let child_rows =
|
|
get_rows_without_schema_retry(&conn, "select value from child_table order by rowid");
|
|
assert_eq!(child_rows.len(), 2);
|
|
assert_eq!(child_rows[0][0].to_string(), "child-schema");
|
|
assert_eq!(child_rows[1][0].to_string(), "parent-schema");
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_open_parent_execute_uses_child_created_table() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-execute-child-table-use.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table t(value integer)").unwrap();
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let schema_output = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_SCHEMA_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
schema_output.status.success(),
|
|
"child schema process failed: stdout={}; stderr={}",
|
|
String::from_utf8_lossy(&schema_output.stdout),
|
|
String::from_utf8_lossy(&schema_output.stderr)
|
|
);
|
|
|
|
conn.execute("insert into child_table(value) values ('parent-schema')")
|
|
.unwrap();
|
|
|
|
let child_rows =
|
|
get_rows_without_schema_retry(&conn, "select value from child_table order by rowid");
|
|
assert_eq!(child_rows.len(), 2);
|
|
assert_eq!(child_rows[0][0].to_string(), "child-schema");
|
|
assert_eq!(child_rows[1][0].to_string(), "parent-schema");
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_readonly_child_reader_blocks_restart_and_truncate_checkpoints() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-readonly-reader-blocks-checkpoint.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
assert!(
|
|
wal_max_frame(&conn) > 0,
|
|
"read-only reader coverage requires committed WAL frames"
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(
|
|
authority.min_active_reader_frame(),
|
|
None,
|
|
"setup should start without active shared readers"
|
|
);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_HOLD_READ_TX_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.env("TURSO_MULTIPROCESS_READONLY", "1")
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
let reader_frame = authority
|
|
.min_active_reader_frame()
|
|
.expect("read-only child should publish an active shared reader slot");
|
|
assert!(
|
|
reader_frame > 0,
|
|
"read-only child should pin a positive WAL frame while its read transaction is active"
|
|
);
|
|
|
|
let restart_err = conn.checkpoint(CheckpointMode::Restart).unwrap_err();
|
|
assert!(
|
|
matches!(restart_err, LimboError::Busy),
|
|
"restart checkpoint should fail with Busy while the read-only child holds a WAL snapshot: {restart_err:?}",
|
|
);
|
|
|
|
let truncate_err = conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(truncate_err, LimboError::Busy),
|
|
"truncate checkpoint should fail with Busy while the read-only child holds a WAL snapshot: {truncate_err:?}",
|
|
);
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
assert!(
|
|
child_status.success(),
|
|
"read-only child should exit cleanly after releasing its read transaction: {child_status:?}"
|
|
);
|
|
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert!(
|
|
checkpoint.everything_backfilled(),
|
|
"truncate checkpoint should succeed once the read-only child releases its WAL snapshot"
|
|
);
|
|
assert_eq!(
|
|
authority.min_active_reader_frame(),
|
|
None,
|
|
"shared reader state should clear once the read-only child releases its WAL snapshot"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_db_file_reader_stops_checkpoint_in_other_process() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-db-file-reader.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let result_file = dir.path().join("child-result");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("create table other(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(id, value) values (1, 'x')")
|
|
.unwrap();
|
|
conn.execute("insert into other(id, value) values (1, 'old')")
|
|
.unwrap();
|
|
let checkpoint = run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
},
|
|
);
|
|
assert!(
|
|
checkpoint.everything_backfilled(),
|
|
"the child must start its snapshot with nothing left in the WAL"
|
|
);
|
|
let backfilled_frame = checkpoint.wal_total_backfilled;
|
|
assert!(backfilled_frame > 0);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(authority.min_active_reader_frame(), None);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_DB_FILE_READER_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.env("TURSO_MULTIPROCESS_RESULT_FILE", &result_file)
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
assert!(
|
|
authority.has_active_db_file_reader(),
|
|
"a reader that bypasses the WAL must still be visible to other processes"
|
|
);
|
|
assert_eq!(authority.min_active_reader_frame(), None);
|
|
|
|
conn.execute("update other set value = 'new' where id = 1")
|
|
.unwrap();
|
|
assert!(wal_max_frame(&conn) > backfilled_frame);
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert_eq!(
|
|
checkpoint.wal_checkpoint_backfilled, 0,
|
|
"no frame past the child's snapshot may reach the database file while it reads"
|
|
);
|
|
assert_eq!(checkpoint.wal_total_backfilled, backfilled_frame);
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
assert!(child_status.success(), "child failed: {child_status:?}");
|
|
assert_eq!(
|
|
std::fs::read_to_string(&result_file).unwrap(),
|
|
"old",
|
|
"the child's snapshot must not see the update committed after it began"
|
|
);
|
|
|
|
assert!(!authority.has_active_db_file_reader());
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert!(checkpoint.everything_backfilled());
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_db_file_reader_allows_wal_restart_but_stops_backfill() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-db-file-reader-restart.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let result_file = dir.path().join("child-result");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("create table other(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(id, value) values (1, 'x')")
|
|
.unwrap();
|
|
conn.execute("insert into other(id, value) values (1, 'old')")
|
|
.unwrap();
|
|
let checkpoint = run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
},
|
|
);
|
|
assert!(checkpoint.everything_backfilled());
|
|
let backfilled_frame = checkpoint.wal_total_backfilled;
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_DB_FILE_READER_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.env("TURSO_MULTIPROCESS_RESULT_FILE", &result_file)
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
assert!(authority.has_active_db_file_reader());
|
|
|
|
conn.execute("update other set value = 'new' where id = 1")
|
|
.unwrap();
|
|
let max_frame = wal_max_frame(&conn);
|
|
assert!(
|
|
max_frame < backfilled_frame,
|
|
"a database file reader in another process must not stop the WAL restart, \
|
|
but the write appended at frame {max_frame} after frame {backfilled_frame}"
|
|
);
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert_eq!(
|
|
checkpoint.wal_checkpoint_backfilled, 0,
|
|
"no frame of the restarted WAL may reach the database file while the child reads"
|
|
);
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
assert!(child_status.success(), "child failed: {child_status:?}");
|
|
assert_eq!(
|
|
std::fs::read_to_string(&result_file).unwrap(),
|
|
"old",
|
|
"the child's snapshot must not see the update committed after it began"
|
|
);
|
|
|
|
assert!(!authority.has_active_db_file_reader());
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert!(checkpoint.everything_backfilled());
|
|
let rows = get_rows(&conn, "select value from other where id = 1");
|
|
assert_eq!(rows[0][0].to_string(), "new");
|
|
}
|
|
|
|
#[test]
|
|
fn write_after_full_checkpoint_restarts_wal() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-restart-after-checkpoint.db");
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
for _ in 0..20 {
|
|
conn.execute("insert into test(value) values ('x')")
|
|
.unwrap();
|
|
}
|
|
let checkpoint = run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: None,
|
|
},
|
|
);
|
|
assert!(checkpoint.everything_backfilled());
|
|
let backfilled_frame = checkpoint.wal_total_backfilled;
|
|
|
|
conn.execute("insert into test(value) values ('after')")
|
|
.unwrap();
|
|
let max_frame = wal_max_frame(&conn);
|
|
assert!(
|
|
max_frame < backfilled_frame,
|
|
"a write that starts after a full checkpoint must restart the WAL from frame 1, \
|
|
but it appended at frame {max_frame} after frame {backfilled_frame}"
|
|
);
|
|
assert_eq!(count_test_rows(&conn), 21);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_readonly_disk_scan_child_reader_stays_in_shared_coordination() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-readonly-disk-scan-reader-blocks-checkpoint.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
assert!(
|
|
wal_max_frame(&conn) > 1,
|
|
"disk-scan read-only coverage requires more than one WAL frame before partial checkpoint"
|
|
);
|
|
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: Some(1),
|
|
},
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_before = authority.snapshot();
|
|
assert!(
|
|
snapshot_before.nbackfills > 0,
|
|
"disk-scan read-only coverage requires persisted positive nbackfills before proof removal"
|
|
);
|
|
assert!(
|
|
snapshot_before.max_frame > snapshot_before.nbackfills,
|
|
"disk-scan read-only coverage requires a live WAL tail beyond the backfill point"
|
|
);
|
|
authority.clear_backfill_proof();
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_HOLD_READ_TX_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.env("TURSO_MULTIPROCESS_READONLY", "1")
|
|
.env("TURSO_MULTIPROCESS_EXPECT_DISK_SCAN", "1")
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
let reader_frame = authority
|
|
.min_active_reader_frame()
|
|
.expect("disk-scan read-only child should publish an active shared reader slot");
|
|
assert!(
|
|
reader_frame > snapshot_before.nbackfills,
|
|
"disk-scan read-only child should protect the live WAL tail, not the checkpointed prefix"
|
|
);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
|
|
let restart_err = reopened_conn
|
|
.checkpoint(CheckpointMode::Restart)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(restart_err, LimboError::Busy),
|
|
"restart checkpoint should fail with Busy while the disk-scan read-only child holds a WAL snapshot: {restart_err:?}",
|
|
);
|
|
|
|
let truncate_err = reopened_conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(truncate_err, LimboError::Busy),
|
|
"truncate checkpoint should fail with Busy while the disk-scan read-only child holds a WAL snapshot: {truncate_err:?}",
|
|
);
|
|
|
|
drop(reopened_conn);
|
|
drop(reopened);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let wal_len = std::fs::metadata(format!("{db_path_str}-wal"))
|
|
.unwrap_or_else(|_| panic!("expected WAL file at {db_path_str}-wal"))
|
|
.len();
|
|
assert!(
|
|
wal_len > 0,
|
|
"closing the other process must not run shutdown checkpoint while the disk-scan read-only child still holds a shared reader slot"
|
|
);
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
assert!(
|
|
child_status.success(),
|
|
"disk-scan read-only child should exit cleanly after releasing its read transaction: {child_status:?}"
|
|
);
|
|
|
|
let reopened = open_multiprocess_db(multiprocess_test_io(), db_path_str).unwrap();
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
let checkpoint = reopened_conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert!(
|
|
checkpoint.everything_backfilled(),
|
|
"truncate checkpoint should succeed once the disk-scan read-only child releases its WAL snapshot"
|
|
);
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
32,
|
|
"disk-scan read-only reopen should preserve committed rows"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn subprocess_database_truncate_checkpoint_reclaims_dead_child_reader_slot() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-dead-reader-slot.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn.execute("insert into test(value) values ('before-reader')")
|
|
.unwrap();
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(
|
|
authority.min_active_reader_frame(),
|
|
None,
|
|
"setup should start without active shared reader slots"
|
|
);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_HOLD_READ_TX_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
let reader_frame = authority
|
|
.min_active_reader_frame()
|
|
.expect("child read transaction should publish an active shared reader slot");
|
|
|
|
conn.execute("insert into test(value) values ('after-reader')")
|
|
.unwrap();
|
|
assert!(
|
|
wal_max_frame(&conn) > reader_frame,
|
|
"parent should append newer WAL frames after the child pins its read snapshot"
|
|
);
|
|
|
|
let err = conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, LimboError::Busy),
|
|
"truncate checkpoint should fail with Busy while child process holds a shared reader slot: {err:?}",
|
|
);
|
|
|
|
child.kill().unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
#[cfg(unix)]
|
|
assert_eq!(
|
|
child_status.signal(),
|
|
Some(libc::SIGKILL),
|
|
"expected killed child process to exit via SIGKILL, got {child_status:?}"
|
|
);
|
|
#[cfg(windows)]
|
|
assert!(
|
|
!child_status.success(),
|
|
"expected killed child process to exit unsuccessfully on Windows, got {child_status:?}"
|
|
);
|
|
|
|
let checkpoint = conn
|
|
.checkpoint(CheckpointMode::Truncate {
|
|
upper_bound_inclusive: None,
|
|
})
|
|
.unwrap();
|
|
assert!(
|
|
checkpoint.everything_backfilled(),
|
|
"truncate checkpoint should succeed after reclaiming the dead child shared reader slot"
|
|
);
|
|
assert_eq!(
|
|
authority.min_active_reader_frame(),
|
|
None,
|
|
"successful checkpoint should reclaim the dead child shared reader slot"
|
|
);
|
|
|
|
let wal_len = std::fs::metadata(format!("{db_path_str}-wal"))
|
|
.map(|meta| meta.len())
|
|
.unwrap_or(0);
|
|
assert_eq!(wal_len, 0, "truncate checkpoint should leave the WAL empty");
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
2,
|
|
"cold reopen after reader-slot reclamation should preserve committed rows"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_reopen_with_live_child_reader_does_not_clobber_authority() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("coordination-live-reader-reopen.db");
|
|
let ready_file = dir.path().join("child-ready");
|
|
let release_file = dir.path().join("child-release");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.wal_auto_actions_disable();
|
|
conn.execute("create table test(id integer primary key, value blob)")
|
|
.unwrap();
|
|
conn.execute("begin immediate").unwrap();
|
|
for _ in 0..32 {
|
|
conn.execute("insert into test(value) values (randomblob(2048))")
|
|
.unwrap();
|
|
}
|
|
conn.execute("commit").unwrap();
|
|
assert!(
|
|
wal_max_frame(&conn) > 1,
|
|
"disk-scan reopen coverage requires more than one WAL frame before partial checkpoint"
|
|
);
|
|
|
|
run_checkpoint(
|
|
&conn,
|
|
CheckpointMode::Passive {
|
|
upper_bound_inclusive: Some(1),
|
|
},
|
|
);
|
|
|
|
let authority = db.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot_before = authority.snapshot();
|
|
assert!(
|
|
snapshot_before.nbackfills > 0,
|
|
"disk-scan reopen coverage requires a persisted authority snapshot with positive nbackfills"
|
|
);
|
|
assert!(
|
|
snapshot_before.max_frame > snapshot_before.nbackfills,
|
|
"disk-scan reopen coverage requires live WAL frames beyond the backfill point"
|
|
);
|
|
let frames_before = authority.iter_latest_frames(0, snapshot_before.max_frame);
|
|
assert!(
|
|
!frames_before.is_empty(),
|
|
"setup should publish durable frame-index entries before reopen repair"
|
|
);
|
|
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SHM_HOLD_READ_TX_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env("TURSO_MULTIPROCESS_READY_FILE", &ready_file)
|
|
.env("TURSO_MULTIPROCESS_RELEASE_FILE", &release_file)
|
|
.spawn()
|
|
.unwrap();
|
|
|
|
wait_for_file(&ready_file);
|
|
let reader_frame = authority
|
|
.min_active_reader_frame()
|
|
.expect("child read transaction should publish an active shared reader slot");
|
|
|
|
drop(conn);
|
|
drop(db);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let reopened = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let reopened_authority = reopened.shared_wal_coordination().unwrap().unwrap();
|
|
assert_eq!(reopened_authority.snapshot(), snapshot_before);
|
|
assert_eq!(
|
|
reopened_authority.iter_latest_frames(0, snapshot_before.max_frame),
|
|
frames_before,
|
|
"reopen repair must preserve durable frame-index content while the child reader is still alive"
|
|
);
|
|
assert_eq!(
|
|
reopened_authority.min_active_reader_frame(),
|
|
Some(reader_frame),
|
|
"reopen repair must not reclaim the live child reader slot"
|
|
);
|
|
|
|
std::fs::write(&release_file, b"release").unwrap();
|
|
let child_status = child.wait().unwrap();
|
|
assert!(
|
|
child_status.success(),
|
|
"child reader should exit cleanly after reopen repair: {child_status:?}"
|
|
);
|
|
|
|
let reopened_conn = reopened.connect().unwrap();
|
|
assert_eq!(
|
|
count_test_rows(&reopened_conn),
|
|
32,
|
|
"reopen repair should preserve committed rows while leaving the child reader intact"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn database_open_rebuilds_from_disk_scan_when_shared_frame_index_overflowed() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir
|
|
.path()
|
|
.join("coordination-overflowed-frame-index-reopen.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
|
|
let db_a = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn_a = db_a.connect().unwrap();
|
|
conn_a
|
|
.execute("create table test(id integer primary key, value text)")
|
|
.unwrap();
|
|
conn_a
|
|
.execute("insert into test(value) values ('before-overflow')")
|
|
.unwrap();
|
|
conn_a
|
|
.execute("insert into test(value) values ('after-overflow')")
|
|
.unwrap();
|
|
|
|
let authority = db_a.shared_wal_coordination().unwrap().unwrap();
|
|
let snapshot = authority.snapshot();
|
|
assert!(
|
|
snapshot.max_frame > 0,
|
|
"overflow reopen coverage requires committed WAL frames before the authority is marked incomplete"
|
|
);
|
|
assert!(
|
|
!authority
|
|
.iter_latest_frames(0, snapshot.max_frame)
|
|
.is_empty(),
|
|
"overflow reopen coverage requires a populated durable frame index before it is discarded"
|
|
);
|
|
|
|
authority.discard_durable_frame_index_for_exclusive_rebuild();
|
|
authority.mark_frame_index_overflowed_for_tests();
|
|
|
|
assert!(
|
|
authority
|
|
.iter_latest_frames(0, snapshot.max_frame)
|
|
.is_empty(),
|
|
"test setup should clear durable frame-index entries before reopen"
|
|
);
|
|
assert!(
|
|
authority.frame_index_overflowed(),
|
|
"test setup should mark the shared frame index incomplete before reopen"
|
|
);
|
|
|
|
drop(conn_a);
|
|
drop(db_a);
|
|
let mut manager = DATABASE_MANAGER.lock();
|
|
manager.clear();
|
|
drop(manager);
|
|
|
|
let db_b = open_multiprocess_db(io, db_path_str).unwrap();
|
|
assert!(
|
|
db_b.shared_wal
|
|
.read()
|
|
.metadata
|
|
.loaded_from_disk_scan
|
|
.load(Ordering::Acquire),
|
|
"overflowed shared frame index must force a conservative WAL disk scan on reopen"
|
|
);
|
|
|
|
let reopened_authority = db_b.shared_wal_coordination().unwrap().unwrap();
|
|
assert!(
|
|
!reopened_authority.frame_index_overflowed(),
|
|
"disk-scan reopen should rebuild the durable frame index instead of leaving it overflowed"
|
|
);
|
|
assert!(
|
|
!reopened_authority
|
|
.iter_latest_frames(0, snapshot.max_frame)
|
|
.is_empty(),
|
|
"disk-scan reopen should repopulate the durable frame index from the WAL"
|
|
);
|
|
|
|
let conn_b = db_b.connect().unwrap();
|
|
let rows = get_rows(&conn_b, "select value from test order by id");
|
|
assert_eq!(rows.len(), 2);
|
|
assert_eq!(rows[0][0].to_string(), "before-overflow");
|
|
assert_eq!(rows[1][0].to_string(), "after-overflow");
|
|
}
|
|
|
|
#[test]
|
|
fn memory_database_keeps_in_process_wal_backend() {
|
|
let io: Arc<dyn IO> = Arc::new(MemoryIO::new());
|
|
let db = Database::open_file(io, ":memory:", Arc::new(SqliteDialect)).unwrap();
|
|
|
|
let last_checksum_and_max_frame = db.shared_wal.read().last_checksum_and_max_frame();
|
|
let wal = db
|
|
.build_wal(last_checksum_and_max_frame, db.buffer_pool.clone())
|
|
.unwrap();
|
|
let wal_file = wal.as_any().downcast_ref::<WalFile>().unwrap();
|
|
assert_eq!(wal_file.coordination_backend_name(), "in_process");
|
|
}
|
|
|
|
#[test]
|
|
fn memory_database_query_can_close_without_checkpointing() {
|
|
let io: Arc<dyn IO> = Arc::new(MemoryIO::new());
|
|
let db = Database::open_file(io, ":memory:", Arc::new(SqliteDialect)).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
|
|
conn.query("VALUES ('ok')").unwrap();
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
// ============================================================================
|
|
// Multi-process sequence tests.
|
|
//
|
|
// Sequences are disk-only: each `nextval` reads the latest committed
|
|
// watermark from the backing table under the WAL write lock and writes
|
|
// the next value back. Cross-process synchronization is therefore the
|
|
// pager's WAL lock plus MVCC's commit-validation path; there is no
|
|
// in-memory atomic to keep in sync.
|
|
//
|
|
// These tests pin the cross-process contract:
|
|
//
|
|
// 1. `test_multiprocess_concurrent_nextval_returns_distinct_values`
|
|
// Two processes open the DB before either commits and each calls
|
|
// nextval. The WAL-locked RMW guarantees the second writer reads
|
|
// the first writer's committed row, so the two emissions must be
|
|
// distinct.
|
|
//
|
|
// 2. `test_multiprocess_nextval_after_other_process_committed_is_monotonic`
|
|
// Process A opens, calls nextval, commits, stays open. Process B
|
|
// opens (sees A's commit), then A does another nextval. B's next
|
|
// nextval must observe both of A's commits and emit a strictly
|
|
// greater value.
|
|
//
|
|
// 3. `test_multiprocess_setval_visible_to_other_process_nextval`
|
|
// Process A calls `setval('s', 100, true)` and commits. Process B
|
|
// (already open before A's setval) calls nextval — must return
|
|
// 101, picking up A's committed setval from disk.
|
|
|
|
/// Coordinates child processes via a wall-clock barrier. Children open the
|
|
/// DB *before* the barrier (so all of them have their atomics initialized
|
|
/// from the same disk state) and only call nextval *after* the barrier, so
|
|
/// the in-memory writes overlap.
|
|
#[test]
|
|
fn multiprocess_sequence_nextval_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let result_path = std::env::var("TURSO_MULTIPROCESS_RESULT_PATH")
|
|
.expect("TURSO_MULTIPROCESS_RESULT_PATH must be set for sequence child");
|
|
let ready_path = std::env::var("TURSO_MULTIPROCESS_READY_PATH")
|
|
.expect("TURSO_MULTIPROCESS_READY_PATH must be set for sequence child");
|
|
let go_path = std::env::var("TURSO_MULTIPROCESS_GO_PATH")
|
|
.expect("TURSO_MULTIPROCESS_GO_PATH must be set for sequence child");
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
|
|
// Signal that the connection is open (atomic loaded from disk). This is
|
|
// what we need to overlap across all participating children.
|
|
std::fs::write(&ready_path, b"").expect("write ready marker");
|
|
|
|
// Wait for the parent's go signal. Bounded wait so a buggy parent
|
|
// doesn't hang CI.
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
|
while !std::path::Path::new(&go_path).exists() {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("child timed out waiting for go signal at {go_path}");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
|
|
// Retry on Busy: in WAL multiprocess mode the write lock is held by
|
|
// whichever process is committing right now; that's expected, not a
|
|
// sequence bug. The bug we're hunting is in-memory atomic divergence,
|
|
// which only matters once each process actually gets to commit. Cap
|
|
// the retry loop so a real hang doesn't disguise itself as flakiness.
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(15);
|
|
let value = loop {
|
|
let mut stmt = conn.prepare("SELECT nextval('s')").unwrap();
|
|
let mut got: Option<i64> = None;
|
|
let step_result = stmt.run_with_row_callback(|row| {
|
|
got = Some(row.get::<i64>(0).unwrap());
|
|
Ok(())
|
|
});
|
|
match step_result {
|
|
Ok(()) => break got.expect("nextval must produce a row"),
|
|
Err(LimboError::Busy) => {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("child kept hitting Busy on nextval for 15s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
Err(e) => panic!("unexpected nextval error: {e:?}"),
|
|
}
|
|
};
|
|
|
|
std::fs::write(&result_path, value.to_string()).expect("write result");
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
/// Spawn `n` child processes that each call `SELECT nextval('s')` after a
|
|
/// shared wall-clock barrier (so all children's atomics start from the same
|
|
/// pre-nextval disk state and their nextval calls overlap in time). Return
|
|
/// the values they emitted. Helper for the parent tests below.
|
|
fn spawn_concurrent_nextval_children(db_path: &str, n: usize) -> Vec<i64> {
|
|
let coord_dir = tempfile::tempdir().expect("coord tempdir");
|
|
let go_path = coord_dir.path().join("go");
|
|
let go_path_str = go_path.to_str().unwrap().to_string();
|
|
|
|
let mut children = Vec::with_capacity(n);
|
|
let mut result_paths = Vec::with_capacity(n);
|
|
let mut ready_paths = Vec::with_capacity(n);
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
|
|
for i in 0..n {
|
|
let result_path = coord_dir.path().join(format!("result-{i}"));
|
|
let ready_path = coord_dir.path().join(format!("ready-{i}"));
|
|
let child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SEQUENCE_NEXTVAL_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_RESULT_PATH",
|
|
result_path.to_str().unwrap(),
|
|
)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_READY_PATH",
|
|
ready_path.to_str().unwrap(),
|
|
)
|
|
.env("TURSO_MULTIPROCESS_GO_PATH", &go_path_str)
|
|
.spawn()
|
|
.expect("spawn child");
|
|
children.push(child);
|
|
result_paths.push(result_path);
|
|
ready_paths.push(ready_path);
|
|
// Brief stagger: the multiprocess-WAL open path runs a probe-open
|
|
// (without the multiproc flag) to detect a stale legacy holder.
|
|
// When several children race the open they trip each other's
|
|
// probes — that's a test-infra artifact, not a sequence bug. The
|
|
// bug the suite hunts (atomic divergence under concurrent calls)
|
|
// is preserved because the children still hit the barrier at the
|
|
// same wall-clock moment and call nextval concurrently.
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
|
|
// Wait for every child to signal ready (atomic loaded, waiting at
|
|
// barrier). Bounded so a failing child doesn't hang the parent.
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
|
loop {
|
|
if ready_paths.iter().all(|p| p.exists()) {
|
|
break;
|
|
}
|
|
if std::time::Instant::now() >= deadline {
|
|
for child in &mut children {
|
|
let _ = child.kill();
|
|
}
|
|
panic!("not all children became ready within 30s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
|
|
// Release the barrier — all children now race to nextval.
|
|
std::fs::write(&go_path, b"").expect("write go signal");
|
|
|
|
let mut values = Vec::with_capacity(n);
|
|
for (i, mut child) in children.into_iter().enumerate() {
|
|
let status = child.wait().expect("wait child");
|
|
let result_path = &result_paths[i];
|
|
assert!(
|
|
status.success(),
|
|
"child {i} failed (status={status:?}); no result at {result_path:?}",
|
|
);
|
|
let raw = std::fs::read_to_string(result_path)
|
|
.unwrap_or_else(|e| panic!("read child {i} result at {result_path:?}: {e}"));
|
|
values.push(raw.trim().parse::<i64>().expect("parse i64 result"));
|
|
}
|
|
values
|
|
}
|
|
|
|
#[test]
|
|
fn test_multiprocess_concurrent_nextval_returns_distinct_values() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("mp-seq-nextval.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
|
|
{
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("CREATE SEQUENCE s START 1 INCREMENT 1")
|
|
.unwrap();
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
let values = spawn_concurrent_nextval_children(db_path_str, 3);
|
|
|
|
let mut sorted = values.clone();
|
|
sorted.sort_unstable();
|
|
let unique: std::collections::HashSet<_> = sorted.iter().copied().collect();
|
|
assert_eq!(
|
|
unique.len(),
|
|
sorted.len(),
|
|
"expected 3 distinct nextval results across processes, got {values:?}",
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_multiprocess_nextval_after_other_process_committed_is_monotonic() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("mp-seq-monotonic.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn_a = db.connect().unwrap();
|
|
conn_a
|
|
.execute("CREATE SEQUENCE s START 1 INCREMENT 1")
|
|
.unwrap();
|
|
|
|
// Process A first nextval: returns 1 (start value).
|
|
let mut stmt = conn_a.prepare("SELECT nextval('s')").unwrap();
|
|
let mut a_first: Option<i64> = None;
|
|
stmt.run_with_row_callback(|row| {
|
|
a_first = Some(row.get::<i64>(0).unwrap());
|
|
Ok(())
|
|
})
|
|
.unwrap();
|
|
drop(stmt);
|
|
assert_eq!(a_first, Some(1));
|
|
|
|
// Now spawn a child (B). B opens AFTER A's commit, so its atomic is
|
|
// loaded from the up-to-date disk state. B should see at least 2.
|
|
// But the child runs in parallel with another nextval on A below.
|
|
let values = spawn_concurrent_nextval_children(db_path_str, 1);
|
|
let b_value = values[0];
|
|
|
|
// A's second nextval: should NOT collide with B.
|
|
let mut stmt = conn_a.prepare("SELECT nextval('s')").unwrap();
|
|
let mut a_second: Option<i64> = None;
|
|
stmt.run_with_row_callback(|row| {
|
|
a_second = Some(row.get::<i64>(0).unwrap());
|
|
Ok(())
|
|
})
|
|
.unwrap();
|
|
let a_second = a_second.expect("A's second nextval must produce a row");
|
|
|
|
let all = [1, b_value, a_second];
|
|
let unique: std::collections::HashSet<_> = all.iter().copied().collect();
|
|
assert_eq!(
|
|
unique.len(),
|
|
3,
|
|
"expected 3 distinct nextval results (A1={}, B={}, A2={}), got {all:?}",
|
|
1,
|
|
b_value,
|
|
a_second,
|
|
);
|
|
|
|
conn_a.close().unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn test_multiprocess_setval_visible_to_other_process_nextval() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("mp-seq-setval.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io.clone(), db_path_str).unwrap();
|
|
let conn_a = db.connect().unwrap();
|
|
conn_a
|
|
.execute("CREATE SEQUENCE s START 1 INCREMENT 1")
|
|
.unwrap();
|
|
|
|
// Spawn the child *before* setval so its atomic is loaded from the
|
|
// pre-setval disk state. The child waits at the barrier, then does
|
|
// nextval after we move the watermark.
|
|
let coord_dir = tempfile::tempdir().expect("coord tempdir");
|
|
let go_path = coord_dir.path().join("go");
|
|
let ready_path = coord_dir.path().join("ready");
|
|
let result_path = coord_dir.path().join("result");
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
let mut child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SEQUENCE_NEXTVAL_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_RESULT_PATH",
|
|
result_path.to_str().unwrap(),
|
|
)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_READY_PATH",
|
|
ready_path.to_str().unwrap(),
|
|
)
|
|
.env("TURSO_MULTIPROCESS_GO_PATH", go_path.to_str().unwrap())
|
|
.spawn()
|
|
.expect("spawn child");
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
|
while !ready_path.exists() {
|
|
if std::time::Instant::now() >= deadline {
|
|
let _ = child.kill();
|
|
panic!("child not ready within 30s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
|
|
// Now move the watermark while the child is parked at the barrier.
|
|
let mut stmt = conn_a.prepare("SELECT setval('s', 100, 1)").unwrap();
|
|
stmt.run_with_row_callback(|_| Ok(())).unwrap();
|
|
drop(stmt);
|
|
|
|
// Release the barrier — child does nextval against a stale atomic.
|
|
std::fs::write(&go_path, b"").expect("write go signal");
|
|
|
|
let status = child.wait().expect("wait child");
|
|
assert!(status.success(), "child failed: {status:?}");
|
|
let value: i64 = std::fs::read_to_string(&result_path)
|
|
.expect("read child result")
|
|
.trim()
|
|
.parse()
|
|
.expect("parse i64");
|
|
|
|
assert_eq!(
|
|
value, 101,
|
|
"child opened before setval(100, true) must still produce 101 after barrier release, got {value}",
|
|
);
|
|
|
|
conn_a.close().unwrap();
|
|
}
|
|
|
|
/// Burst child: opens the DB, waits at the barrier, then loops
|
|
/// `TURSO_MULTIPROCESS_NEXTVAL_COUNT` times calling `SELECT nextval('s')`.
|
|
/// Retries on Busy (WAL multiproc write lock contention is expected — the
|
|
/// bug we're hunting is duplicate-value emission, not Busy). Writes all
|
|
/// emitted values to the result file, one per line.
|
|
#[test]
|
|
fn multiprocess_sequence_nextval_burst_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let result_path = std::env::var("TURSO_MULTIPROCESS_RESULT_PATH")
|
|
.expect("TURSO_MULTIPROCESS_RESULT_PATH must be set for burst child");
|
|
let ready_path = std::env::var("TURSO_MULTIPROCESS_READY_PATH")
|
|
.expect("TURSO_MULTIPROCESS_READY_PATH must be set for burst child");
|
|
let go_path = std::env::var("TURSO_MULTIPROCESS_GO_PATH")
|
|
.expect("TURSO_MULTIPROCESS_GO_PATH must be set for burst child");
|
|
let count: usize = std::env::var("TURSO_MULTIPROCESS_NEXTVAL_COUNT")
|
|
.expect("TURSO_MULTIPROCESS_NEXTVAL_COUNT must be set for burst child")
|
|
.parse()
|
|
.expect("parse count");
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
|
|
std::fs::write(&ready_path, b"").expect("write ready marker");
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
|
while !std::path::Path::new(&go_path).exists() {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("child timed out waiting for go signal at {go_path}");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
|
|
let mut values: Vec<i64> = Vec::with_capacity(count);
|
|
for _ in 0..count {
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
|
let value = loop {
|
|
let mut stmt = match conn.prepare("SELECT nextval('s')") {
|
|
Ok(s) => s,
|
|
Err(LimboError::Busy) => {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("child timed out preparing nextval after 30s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
continue;
|
|
}
|
|
Err(e) => panic!("unexpected prepare error: {e:?}"),
|
|
};
|
|
let mut got: Option<i64> = None;
|
|
let step_result = stmt.run_with_row_callback(|row| {
|
|
got = Some(row.get::<i64>(0).unwrap());
|
|
Ok(())
|
|
});
|
|
match step_result {
|
|
Ok(()) => break got.expect("nextval must produce a row"),
|
|
Err(LimboError::Busy) | Err(LimboError::WriteWriteConflict) => {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("child timed out on nextval after 30s of contention");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
}
|
|
Err(e) => panic!("unexpected nextval error: {e:?}"),
|
|
}
|
|
};
|
|
values.push(value);
|
|
}
|
|
|
|
let body = values
|
|
.iter()
|
|
.map(|v| v.to_string())
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
std::fs::write(&result_path, body).expect("write result");
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
/// Volume stress: many processes each pull many values from the same sequence
|
|
/// in parallel. Every returned value across the entire pool must be distinct.
|
|
///
|
|
/// Failure mode under the old atomic design: each process initialized its
|
|
/// atomic from the same disk state at open. Once the barrier releases,
|
|
/// the first burst of nextvals from each process all emit values they
|
|
/// computed against that same starting watermark — yielding the same
|
|
/// integer from multiple processes.
|
|
///
|
|
/// After disk-only RMW: each nextval reads the latest committed watermark
|
|
/// from the backing table under WAL write-lock serialization; concurrent
|
|
/// processes naturally observe each other's commits and never collide.
|
|
#[test]
|
|
fn test_multiprocess_nextval_burst_no_duplicates() {
|
|
const PROCESSES: usize = 4;
|
|
const PER_PROCESS: usize = 25;
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("mp-seq-burst.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
|
|
{
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("CREATE SEQUENCE s START 1 INCREMENT 1")
|
|
.unwrap();
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
let coord_dir = tempfile::tempdir().expect("coord tempdir");
|
|
let go_path = coord_dir.path().join("go");
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
|
|
let mut children = Vec::with_capacity(PROCESSES);
|
|
let mut result_paths = Vec::with_capacity(PROCESSES);
|
|
let mut ready_paths = Vec::with_capacity(PROCESSES);
|
|
|
|
for i in 0..PROCESSES {
|
|
let result_path = coord_dir.path().join(format!("result-{i}"));
|
|
let ready_path = coord_dir.path().join(format!("ready-{i}"));
|
|
let child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_SEQUENCE_NEXTVAL_BURST_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_RESULT_PATH",
|
|
result_path.to_str().unwrap(),
|
|
)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_READY_PATH",
|
|
ready_path.to_str().unwrap(),
|
|
)
|
|
.env("TURSO_MULTIPROCESS_GO_PATH", go_path.to_str().unwrap())
|
|
.env("TURSO_MULTIPROCESS_NEXTVAL_COUNT", PER_PROCESS.to_string())
|
|
.spawn()
|
|
.expect("spawn burst child");
|
|
children.push(child);
|
|
result_paths.push(result_path);
|
|
ready_paths.push(ready_path);
|
|
// Stagger spawn — see comment in spawn_concurrent_nextval_children.
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
|
loop {
|
|
if ready_paths.iter().all(|p| p.exists()) {
|
|
break;
|
|
}
|
|
if std::time::Instant::now() >= deadline {
|
|
for child in &mut children {
|
|
let _ = child.kill();
|
|
}
|
|
panic!("not all burst children became ready within 60s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
|
|
std::fs::write(&go_path, b"").expect("write go signal");
|
|
|
|
let mut all_values: Vec<i64> = Vec::with_capacity(PROCESSES * PER_PROCESS);
|
|
for (i, mut child) in children.into_iter().enumerate() {
|
|
let status = child.wait().expect("wait burst child");
|
|
let result_path = &result_paths[i];
|
|
assert!(
|
|
status.success(),
|
|
"burst child {i} failed (status={status:?})",
|
|
);
|
|
let raw = std::fs::read_to_string(result_path)
|
|
.unwrap_or_else(|e| panic!("read burst child {i} result: {e}"));
|
|
for line in raw.lines() {
|
|
let trimmed = line.trim();
|
|
if trimmed.is_empty() {
|
|
continue;
|
|
}
|
|
all_values.push(trimmed.parse::<i64>().expect("parse i64 result line"));
|
|
}
|
|
}
|
|
|
|
assert_eq!(
|
|
all_values.len(),
|
|
PROCESSES * PER_PROCESS,
|
|
"expected {} total values across {} processes, got {}",
|
|
PROCESSES * PER_PROCESS,
|
|
PROCESSES,
|
|
all_values.len()
|
|
);
|
|
|
|
let unique: std::collections::HashSet<_> = all_values.iter().copied().collect();
|
|
assert_eq!(
|
|
unique.len(),
|
|
all_values.len(),
|
|
"expected all {} multiprocess nextvals to be distinct; \
|
|
duplicates present (atomic divergence)",
|
|
all_values.len()
|
|
);
|
|
}
|
|
|
|
/// Child process for the AUTOINCREMENT burst test.
|
|
///
|
|
/// Waits for the coordination "go" signal, then issues
|
|
/// `INSERT INTO t(payload) VALUES('...') RETURNING id` repeatedly,
|
|
/// recording each assigned rowid. Mirrors the structure of
|
|
/// `multiprocess_sequence_nextval_burst_child_process` but targets
|
|
/// the AUTOINCREMENT code path (implicit
|
|
/// `__turso_internal_autoincrement_t` sequence + `sqlite_sequence`
|
|
/// sync), which is structurally distinct from explicit
|
|
/// `nextval('s')` and has its own multiprocess race window:
|
|
/// the per-INSERT WAL-locked RMW against the backing table AND
|
|
/// the sqlite_sequence update must both serialize against
|
|
/// concurrent writers in other processes.
|
|
#[test]
|
|
fn multiprocess_autoinc_burst_child_process() {
|
|
let Some(db_path) = std::env::var_os("TURSO_MULTIPROCESS_DB_PATH") else {
|
|
return;
|
|
};
|
|
let result_path = std::env::var("TURSO_MULTIPROCESS_RESULT_PATH")
|
|
.expect("TURSO_MULTIPROCESS_RESULT_PATH must be set for autoinc burst child");
|
|
let ready_path = std::env::var("TURSO_MULTIPROCESS_READY_PATH")
|
|
.expect("TURSO_MULTIPROCESS_READY_PATH must be set for autoinc burst child");
|
|
let go_path = std::env::var("TURSO_MULTIPROCESS_GO_PATH")
|
|
.expect("TURSO_MULTIPROCESS_GO_PATH must be set for autoinc burst child");
|
|
let count: usize = std::env::var("TURSO_MULTIPROCESS_AUTOINC_COUNT")
|
|
.expect("TURSO_MULTIPROCESS_AUTOINC_COUNT must be set for autoinc burst child")
|
|
.parse()
|
|
.expect("parse count");
|
|
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path.to_str().unwrap()).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
|
|
std::fs::write(&ready_path, b"").expect("write ready marker");
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
|
while !std::path::Path::new(&go_path).exists() {
|
|
if std::time::Instant::now() >= deadline {
|
|
panic!("autoinc child timed out waiting for go signal at {go_path}");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
|
|
let mut ids: Vec<i64> = Vec::with_capacity(count);
|
|
for _ in 0..count {
|
|
let insert_deadline = std::time::Instant::now() + Duration::from_secs(30);
|
|
let assigned = loop {
|
|
let mut stmt = match conn.prepare("INSERT INTO t(payload) VALUES('x') RETURNING id") {
|
|
Ok(s) => s,
|
|
Err(LimboError::Busy) | Err(LimboError::WriteWriteConflict) => {
|
|
if std::time::Instant::now() >= insert_deadline {
|
|
panic!("autoinc child timed out preparing INSERT after 30s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
continue;
|
|
}
|
|
Err(e) => panic!("unexpected prepare error: {e:?}"),
|
|
};
|
|
let mut got: Option<i64> = None;
|
|
let step_result = stmt.run_with_row_callback(|row| {
|
|
got = Some(row.get::<i64>(0).unwrap());
|
|
Ok(())
|
|
});
|
|
match step_result {
|
|
Ok(()) => break got.expect("INSERT RETURNING must yield a rowid"),
|
|
Err(LimboError::Busy) | Err(LimboError::WriteWriteConflict) => {
|
|
if std::time::Instant::now() >= insert_deadline {
|
|
panic!("autoinc child timed out on INSERT after 30s of contention");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
}
|
|
Err(e) => panic!("unexpected INSERT error: {e:?}"),
|
|
}
|
|
};
|
|
ids.push(assigned);
|
|
}
|
|
|
|
let body = ids
|
|
.iter()
|
|
.map(|v| v.to_string())
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
std::fs::write(&result_path, body).expect("write result");
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
/// Multiprocess AUTOINCREMENT stress: many processes each pull many
|
|
/// rowids from a single AUTOINCREMENT table in parallel, then verify
|
|
/// global invariants from a fresh observer:
|
|
///
|
|
/// 1. Every assigned rowid is distinct across the entire cohort
|
|
/// (no duplicate primary keys — a hard SQLite invariant).
|
|
/// 2. `sqlite_sequence.seq` for the table equals the maximum
|
|
/// assigned rowid, which equals `processes * per_process`
|
|
/// (the engine's high-water mark stayed in sync with what was
|
|
/// actually written across processes).
|
|
/// 3. `sqlite_sequence` has exactly one row for the table (no
|
|
/// duplicate watermark rows from cross-process flushes — that
|
|
/// was a real bug class fixed during this PR).
|
|
/// 4. The table contains exactly the expected row count with
|
|
/// contiguous ids 1..=N (no gaps in autoinc allocation).
|
|
///
|
|
/// Why this test exists separately from
|
|
/// `test_multiprocess_nextval_burst_no_duplicates`: AUTOINCREMENT
|
|
/// goes through the implicit
|
|
/// `__turso_internal_autoincrement_<table>` sequence path, which
|
|
/// has different bytecode (`sqlite_sequence` sync, the per-INSERT
|
|
/// advance-past) than explicit `nextval('s')`. Any cross-process
|
|
/// regression in that path (sqlite_sequence dup rows, missed
|
|
/// watermark advance, stale read of the backing-table row) would
|
|
/// be invisible to the nextval burst test.
|
|
#[test]
|
|
fn test_multiprocess_autoinc_burst_no_duplicates() {
|
|
const PROCESSES: usize = 4;
|
|
const PER_PROCESS: usize = 25;
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let db_path = dir.path().join("mp-autoinc-burst.db");
|
|
let db_path_str = db_path.to_str().unwrap();
|
|
|
|
{
|
|
let io: Arc<dyn IO> = multiprocess_test_io();
|
|
let db = open_multiprocess_db(io, db_path_str).unwrap();
|
|
let conn = db.connect().unwrap();
|
|
conn.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT)")
|
|
.unwrap();
|
|
conn.close().unwrap();
|
|
}
|
|
|
|
let coord_dir = tempfile::tempdir().expect("coord tempdir");
|
|
let go_path = coord_dir.path().join("go");
|
|
let current_exe = std::env::current_exe().unwrap();
|
|
|
|
let mut children = Vec::with_capacity(PROCESSES);
|
|
let mut result_paths = Vec::with_capacity(PROCESSES);
|
|
let mut ready_paths = Vec::with_capacity(PROCESSES);
|
|
|
|
for i in 0..PROCESSES {
|
|
let result_path = coord_dir.path().join(format!("result-{i}"));
|
|
let ready_path = coord_dir.path().join(format!("ready-{i}"));
|
|
let child = Command::new(¤t_exe)
|
|
.arg(MULTIPROCESS_AUTOINC_BURST_CHILD_TEST)
|
|
.arg("--exact")
|
|
.arg("--nocapture")
|
|
.env("TURSO_MULTIPROCESS_DB_PATH", db_path_str)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_RESULT_PATH",
|
|
result_path.to_str().unwrap(),
|
|
)
|
|
.env(
|
|
"TURSO_MULTIPROCESS_READY_PATH",
|
|
ready_path.to_str().unwrap(),
|
|
)
|
|
.env("TURSO_MULTIPROCESS_GO_PATH", go_path.to_str().unwrap())
|
|
.env("TURSO_MULTIPROCESS_AUTOINC_COUNT", PER_PROCESS.to_string())
|
|
.spawn()
|
|
.expect("spawn autoinc burst child");
|
|
children.push(child);
|
|
result_paths.push(result_path);
|
|
ready_paths.push(ready_path);
|
|
// Stagger spawn so children don't all race the same coordination
|
|
// file-system events at startup — same idiom as the nextval burst.
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(60);
|
|
loop {
|
|
if ready_paths.iter().all(|p| p.exists()) {
|
|
break;
|
|
}
|
|
if std::time::Instant::now() >= deadline {
|
|
for child in &mut children {
|
|
let _ = child.kill();
|
|
}
|
|
panic!("not all autoinc burst children became ready within 60s");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
|
|
std::fs::write(&go_path, b"").expect("write go signal");
|
|
|
|
let mut all_ids: Vec<i64> = Vec::with_capacity(PROCESSES * PER_PROCESS);
|
|
for (i, mut child) in children.into_iter().enumerate() {
|
|
let status = child.wait().expect("wait autoinc burst child");
|
|
let result_path = &result_paths[i];
|
|
assert!(
|
|
status.success(),
|
|
"autoinc burst child {i} failed (status={status:?})",
|
|
);
|
|
let raw = std::fs::read_to_string(result_path)
|
|
.unwrap_or_else(|e| panic!("read autoinc burst child {i} result: {e}"));
|
|
for line in raw.lines() {
|
|
let trimmed = line.trim();
|
|
if trimmed.is_empty() {
|
|
continue;
|
|
}
|
|
all_ids.push(trimmed.parse::<i64>().expect("parse i64 result line"));
|
|
}
|
|
}
|
|
|
|
assert_eq!(
|
|
all_ids.len(),
|
|
PROCESSES * PER_PROCESS,
|
|
"expected {} total inserts across {} processes, got {}",
|
|
PROCESSES * PER_PROCESS,
|
|
PROCESSES,
|
|
all_ids.len()
|
|
);
|
|
|
|
// Invariant 1: every assigned rowid is unique.
|
|
let unique: std::collections::HashSet<_> = all_ids.iter().copied().collect();
|
|
assert_eq!(
|
|
unique.len(),
|
|
all_ids.len(),
|
|
"expected all {} multiprocess AUTOINCREMENT rowids to be distinct; \
|
|
duplicates present (cross-process watermark divergence)",
|
|
all_ids.len()
|
|
);
|
|
|
|
// Invariants 2-4: open a fresh observer and read the persisted state.
|
|
let observer_io: Arc<dyn IO> = multiprocess_test_io();
|
|
let observer_db =
|
|
open_multiprocess_db(observer_io, db_path_str).expect("reopen db for fresh observer");
|
|
let observer_conn = observer_db.connect().expect("connect fresh observer");
|
|
|
|
let count_rows = get_rows(&observer_conn, "SELECT COUNT(*) FROM t");
|
|
let total_rows = count_rows[0][0]
|
|
.as_int()
|
|
.expect("COUNT(*) should be integer");
|
|
assert_eq!(
|
|
total_rows,
|
|
(PROCESSES * PER_PROCESS) as i64,
|
|
"expected {} rows in autoinc table, got {}",
|
|
PROCESSES * PER_PROCESS,
|
|
total_rows,
|
|
);
|
|
|
|
let max_id_rows = get_rows(&observer_conn, "SELECT MAX(id), MIN(id) FROM t");
|
|
let max_id = max_id_rows[0][0]
|
|
.as_int()
|
|
.expect("MAX(id) should be integer");
|
|
let min_id = max_id_rows[0][1]
|
|
.as_int()
|
|
.expect("MIN(id) should be integer");
|
|
assert_eq!(
|
|
max_id,
|
|
(PROCESSES * PER_PROCESS) as i64,
|
|
"AUTOINCREMENT should have assigned rowids contiguously up to {}",
|
|
PROCESSES * PER_PROCESS,
|
|
);
|
|
assert_eq!(min_id, 1, "AUTOINCREMENT should start at 1");
|
|
|
|
let seq_rows = get_rows(
|
|
&observer_conn,
|
|
"SELECT seq FROM sqlite_sequence WHERE name='t'",
|
|
);
|
|
assert_eq!(
|
|
seq_rows.len(),
|
|
1,
|
|
"sqlite_sequence must have exactly one row for the AUTOINCREMENT table; \
|
|
duplicate rows indicate cross-process flush divergence",
|
|
);
|
|
let persisted_seq = seq_rows[0][0]
|
|
.as_int()
|
|
.expect("sqlite_sequence.seq should be integer");
|
|
assert_eq!(
|
|
persisted_seq, max_id,
|
|
"sqlite_sequence.seq ({persisted_seq}) must match max assigned rowid \
|
|
({max_id}); engine watermark drifted from actual table state across processes",
|
|
);
|
|
|
|
observer_conn.close().unwrap();
|
|
}
|