core/wal: fix multiprocess database file reader race

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 commit 121d5e5db, which added multiprocess WAL support,
did register these readers in the shared reader table, one slot per
reader. The follow-up commit 94c912fb0 removed 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
This commit is contained in:
Pekka Enberg
2026-09-14 10:43:01 +03:00
parent a9a8779c19
commit 50f3a217fb
19 changed files with 1144 additions and 16 deletions

View File

@@ -77,6 +77,7 @@ RUN pip install --break-system-packages /tmp/*.whl
WORKDIR /app
COPY ./testing/antithesis/bank-test/*.py /opt/antithesis/test/v1/bank-test/
COPY ./testing/antithesis/stress-composer/*.py /opt/antithesis/test/v1/stress-composer/
COPY ./testing/antithesis/multiprocess/*.py /opt/antithesis/test/v1/multiprocess/
COPY ./testing/antithesis/stress /opt/antithesis/test/v1/stress
COPY ./testing/antithesis/stress-memory_yield /opt/antithesis/test/v1/stress-memory_yield
COPY ./testing/antithesis/stress-io_uring /opt/antithesis/test/v1/stress-io_uring
@@ -84,9 +85,11 @@ COPY ./testing/antithesis/stress-mvcc /opt/antithesis/test/v1/stress-mvcc
COPY ./testing/antithesis/stress-io_uring-mvcc /opt/antithesis/test/v1/stress-io_uring-mvcc
COPY ./testing/antithesis/stress-unreliable /opt/antithesis/test/v1/stress-unreliable
RUN chmod 777 -R /opt/antithesis/test/v1
RUN chmod -x /opt/antithesis/test/v1/multiprocess/helper_*.py /opt/antithesis/test/v1/stress-composer/helper_utils.py
RUN mkdir /opt/antithesis/catalog
RUN ln -s /opt/antithesis/test/v1/bank-test/*.py /opt/antithesis/catalog
RUN for f in /opt/antithesis/test/v1/multiprocess/*.py; do ln -s "$f" "/opt/antithesis/catalog/multiprocess_$(basename "$f")"; done
COPY testing/stress/targeted_coverage.jso[n] /opt/antithesis/

View File

@@ -24,6 +24,8 @@ 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 =
@@ -1067,6 +1069,40 @@ fn multiprocess_shm_hold_read_tx_child_process() {
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 {
@@ -1563,6 +1599,211 @@ fn subprocess_readonly_child_reader_blocks_restart_and_truncate_checkpoints() {
);
}
#[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(&current_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(&current_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();

View File

@@ -43,6 +43,10 @@ const SHARED_WAL_COORDINATION_VERSION: u32 = 1;
const SHARED_WAL_BACKFILL_PROOF_VERSION: u32 = 1;
/// Sentinel meaning a reader slot is not currently pinning any WAL frame.
const UNUSED_READER_FRAME: u64 = u64::MAX;
/// Frame stored in the reader slot of readers that read only the database
/// file. A reader that uses the WAL always sees at least one frame, so no WAL
/// reader stores this value.
const DB_FILE_READER_FRAME: u64 = 0;
/// Sentinel meaning a shared owner slot is unclaimed.
const UNOWNED_LOCK: u64 = 0;
/// Mmap alignment for the fixed `.tshm` header region.
@@ -652,6 +656,12 @@ enum SharedWalOwnershipMode {
/// | 1 | Writer lock
/// | 2 | Checkpoint lock
/// | 3..3+N | Reader slot locks (one byte per slot)
#[aristo::assume(
"Every process maps the tshm file with a shared mapping on one host, so a store to \
a reader slot is visible to every other process as soon as it is visible to this \
one. Registering a reader before rechecking the shared snapshot relies on this \
ordering; a private copy of the table or a machine boundary would hide the reader."
)]
pub(crate) struct MappedSharedWalCoordination {
file: Arc<dyn File>,
/// Mapping containing the fixed header and reader arrays.
@@ -2110,6 +2120,24 @@ impl MappedSharedWalCoordination {
Some(slot)
}
/// Register a reader that reads only the database file. All such readers
/// in this process share one slot. While any of them is active, checkpoints
/// in every process stop at the current backfill point. They do not stop a
/// WAL restart, because they never read the WAL.
#[aristo::intent(
"Every database file reader in one process shares a single slot, so any number \
of them occupy one entry in the reader table. One slot per reader exhausts the \
table under many concurrent readers and new readers fail with Busy.",
verify = "test",
id = "db_file_readers_share_one_slot_per_process"
)]
pub(crate) fn register_db_file_reader(
&self,
owner: SharedOwnerRecord,
) -> Option<SharedReaderSlot> {
self.register_reader_for_snapshot(owner, DB_FILE_READER_FRAME)
}
/// Release a reader slot previously acquired by `register_reader`.
///
/// Asserts that the current shared-memory owner matches `slot.owner` —
@@ -2176,21 +2204,43 @@ impl MappedSharedWalCoordination {
)
}
/// Return the smallest `max_frame` across all live reader slots, or `None`
/// if no readers are active.
/// Return the smallest `max_frame` across live readers that read from the
/// WAL, or `None` if there are none. Readers that read only the database
/// file are left out; see `has_active_db_file_reader`.
///
/// Checkpoints use this to determine the safe backfill boundary: frames
/// above the minimum active reader's mark cannot be checkpointed because
/// that reader may still need to read the old page from the DB file.
#[aristo::intent(
"Frame zero in a live reader slot means a database file reader and never a WAL \
reader. A WAL reader always registers a frame above the backfill point, so its \
frame is at least one, and the two kinds are told apart by the frame alone.",
verify = "test",
id = "reader_slot_frame_zero_means_db_file_reader"
)]
pub(crate) fn min_active_reader_frame(&self) -> Option<u64> {
self.live_reader_frames()
.filter(|frame| *frame != DB_FILE_READER_FRAME)
.min()
}
/// Whether a reader in any process reads only the database file.
/// Checkpoints must not backfill any new frame while one is active.
pub(crate) fn has_active_db_file_reader(&self) -> bool {
self.live_reader_frames()
.any(|frame| frame == DB_FILE_READER_FRAME)
}
/// Frames stored in all live reader slots.
///
/// **Side-effect**: for each slot whose owner is detected as dead (OFD
/// lock can be acquired, or PID is no longer alive), the slot is reclaimed
/// inline and excluded from the result.
pub(crate) fn min_active_reader_frame(&self) -> Option<u64> {
fn live_reader_frames(&self) -> impl Iterator<Item = u64> + '_ {
self.reader_frames()
.iter()
.enumerate()
.filter_map(|(slot_index, frame)| {
.filter_map(move |(slot_index, frame)| {
if !self.uses_linux_ofd_locking() {
let owner = self.reader_owner(slot_index as u32)?;
let frame = frame.load(Ordering::Acquire);
@@ -2241,7 +2291,6 @@ impl MappedSharedWalCoordination {
Err(err) => panic!("failed probing shared WAL reader slot lock: {err}"),
}
})
.min()
}
/// Append a (page_id, frame_id) entry to the shared frame index.

View File

@@ -2055,6 +2055,9 @@ impl WalCoordination for ShmWalCoordination {
read_locks[0].unlock();
return None;
}
if !self.publish_shared_reader(read_locks, snapshot, 0) {
return None;
}
return Some(ReadGuardKind::DbFile);
}
@@ -2093,18 +2096,9 @@ impl WalCoordination for ShmWalCoordination {
let read_mark_index =
NonZeroUsize::new(best_idx as usize).expect("best_idx checked to be positive");
let reader = self
.authority
.register_reader_for_snapshot(self.owner, snapshot.max_frame)?;
if self.load_snapshot() != snapshot {
self.authority.unregister_reader_for_snapshot(reader);
read_locks[best_idx as usize].unlock();
if !self.publish_shared_reader(read_locks, snapshot, best_idx as usize) {
return None;
}
let mut active_reader = self.active_reader.lock();
turso_assert!(active_reader.is_none(), "shared reader registration leaked");
*active_reader = Some(reader);
Some(ReadGuardKind::ReadMark(read_mark_index))
}
@@ -2226,6 +2220,17 @@ impl WalCoordination for ShmWalCoordination {
}
}
#[aristo::intent(
"The returned frame is at most the snapshot frame of every active reader in \
every process: the read marks held in this process, every WAL reader in the \
shared reader table, and the current backfill point while any process has a \
database file reader registered. Dropping the database file reader term lets \
a checkpoint copy past a reader in another process that holds only read lock \
0, which is invisible outside its process.",
verify = "test",
id = "checkpoint_safe_frame_below_every_reader",
parent = "wal_protocol_correctness"
)]
fn determine_max_safe_checkpoint_frame(&self, max_frame: u64) -> u64 {
turso_assert!(
max_frame <= u32::MAX as u64,
@@ -2250,6 +2255,9 @@ impl WalCoordination for ShmWalCoordination {
}
}
}
if self.authority.has_active_db_file_reader() {
max_safe_frame = max_safe_frame.min(self.load_snapshot().nbackfills);
}
match self.authority.min_active_reader_frame() {
Some(shared_min) => max_safe_frame.min(shared_min),
None => max_safe_frame,
@@ -2267,6 +2275,16 @@ impl WalCoordination for ShmWalCoordination {
}
}
#[aristo::intent(
"A restart is blocked by WAL readers in any process and never by database file \
readers, including the writer's own registration. This is intentional, not \
incomplete: counting database file readers here makes the restart impossible, \
because the writer that restarts is itself one, and the WAL then grows without \
bound.",
verify = "test",
id = "restart_ignores_db_file_readers",
parent = "wal_protocol_correctness"
)]
fn begin_restart(&self, io: &dyn IO) -> Result<WalSnapshot> {
for idx in 1..5 {
if !self.fallback.try_read_mark_exclusive(idx) {
@@ -2280,7 +2298,7 @@ impl WalCoordination for ShmWalCoordination {
// memory), not with fallback OFD byte-range locks. We must also check for
// active cross-process readers before proceeding with the WAL restart,
// otherwise we reset the shared WAL state while another process still has
// an active read transaction, leading to data loss.
// an active read transaction that reads from the WAL, leading to data loss.
if self.authority.min_active_reader_frame().is_some() {
for idx in 1..5 {
self.fallback.unlock_read_mark(idx);
@@ -2419,6 +2437,70 @@ impl WalCoordination for ShmWalCoordination {
}
}
#[cfg(host_shared_wal)]
impl ShmWalCoordination {
/// Register this connection's snapshot in the shared reader table so a
/// checkpoint in another process never backfills frames past it. This
/// covers readers that bypass the WAL as well: the local read lock 0 they
/// hold is invisible to other processes. Such a reader is registered as a
/// database file reader instead of at its snapshot frame: it stops every
/// backfill but lets the WAL restart, and after a restart a frame number
/// from the old WAL would mean nothing. The snapshot is checked again after the registration
/// because a commit in between could have let a checkpoint pick its safe
/// frame before the slot was visible. On failure the local read lock at
/// `read_lock_idx` is released and the caller retries.
fn publish_shared_reader(
&self,
read_locks: &[TursoRwLock; 5],
snapshot: WalSnapshot,
read_lock_idx: usize,
) -> bool {
aristo::intent_stmt!(
"A reader that reads only the database file registers in the shared reader \
table before its read begins, even though it holds no WAL frame. Read lock \
0 is local to the process, so without the registration a checkpoint in \
another process is free to copy past its snapshot. Removing the \
registration to save reader slots reintroduces that race.",
verify = "test",
id = "db_file_reader_registers_in_shared_table",
parent = "checkpoint_safe_frame_below_every_reader"
);
let reader = if read_lock_idx == 0 {
self.authority.register_db_file_reader(self.owner)
} else {
turso_assert!(
snapshot.max_frame > snapshot.nbackfills,
"a reader that uses the WAL must see at least one frame that is not backfilled"
);
self.authority
.register_reader_for_snapshot(self.owner, snapshot.max_frame)
};
let Some(reader) = reader else {
read_locks[read_lock_idx].unlock();
return false;
};
aristo::intent_stmt!(
"After the slot is registered, the shared snapshot is compared again, and any \
difference releases both the slot and the local read lock. A checkpoint that \
chose its safe frame before the slot was visible is not stopped by that \
slot, so a reader whose snapshot moved must start over. The earlier check \
before the local lock does not make this one redundant.",
verify = "neural",
id = "reader_rechecks_snapshot_after_registration",
parent = "checkpoint_safe_frame_below_every_reader"
);
if self.load_snapshot() != snapshot {
self.authority.unregister_reader_for_snapshot(reader);
read_locks[read_lock_idx].unlock();
return false;
}
let mut active_reader = self.active_reader.lock();
turso_assert!(active_reader.is_none(), "shared reader registration leaked");
*active_reader = Some(reader);
true
}
}
#[derive(Debug, Clone)]
pub enum CheckpointState {
Start,

View File

@@ -0,0 +1,18 @@
#!/usr/bin/env -S python3 -u
from antithesis.assertions import always
from helper_common import check_snapshot, connect, read_snapshot
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
num_accts, total = cur.execute("SELECT num_accts, total FROM initial_state").fetchone()
cur.execute("BEGIN")
check_snapshot(read_snapshot(cur), num_accts, total, "Anytime")
cur.execute("COMMIT")
row = cur.execute("PRAGMA integrity_check").fetchone()
always(row == ("ok",), "[Anytime] integrity_check passes", {"result": row})

View File

@@ -0,0 +1,18 @@
#!/usr/bin/env -S python3 -u
from antithesis.assertions import always
from helper_common import check_snapshot, connect, read_snapshot
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
num_accts, total = cur.execute("SELECT num_accts, total FROM initial_state").fetchone()
cur.execute("BEGIN")
check_snapshot(read_snapshot(cur), num_accts, total, "Finally")
cur.execute("COMMIT")
row = cur.execute("PRAGMA integrity_check").fetchone()
always(row == ("ok",), "[Finally] integrity_check passes", {"result": row})

View File

@@ -0,0 +1,40 @@
#!/usr/bin/env -S python3 -u
from antithesis.random import get_random
from helper_common import connect
NUM_ACCOUNTS = 2000
PAD = "x" * 64
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS accounts")
cur.execute("DROP TABLE IF EXISTS initial_state")
cur.execute(
"""
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
balance INTEGER NOT NULL,
generation INTEGER NOT NULL,
pad TEXT NOT NULL
)
"""
)
cur.execute("CREATE TABLE initial_state (num_accts INTEGER, total INTEGER)")
cur.execute("BEGIN")
total = 0
for _ in range(NUM_ACCOUNTS):
balance = get_random() % 1_000_000
total += balance
cur.execute(f"INSERT INTO accounts (balance, generation, pad) VALUES ({balance}, 0, '{PAD}')")
cur.execute(f"INSERT INTO initial_state (num_accts, total) VALUES ({NUM_ACCOUNTS}, {total})")
cur.execute("COMMIT")
cur.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()
print(f"created {NUM_ACCOUNTS} accounts with total {total}")

View File

@@ -0,0 +1,33 @@
import sys
from antithesis.assertions import sometimes
from antithesis.random import get_random
from helper_common import connect, execute_with_busy_retry
def commit_and_checkpoint():
con = connect()
cur = con.cursor()
num_accts = cur.execute("SELECT num_accts FROM initial_state").fetchone()[0]
sender = get_random() % num_accts + 1
recipient = (sender % num_accts) + 1
value = get_random() % 1000
if execute_with_busy_retry(cur, "BEGIN IMMEDIATE") is None:
print("child: could not start a write transaction")
return
cur.execute(f"UPDATE accounts SET balance = balance - {value} WHERE id = {sender}")
cur.execute(f"UPDATE accounts SET balance = balance + {value} WHERE id = {recipient}")
cur.execute("UPDATE accounts SET generation = generation + 1")
cur.execute("COMMIT")
busy, log, checkpointed = cur.execute("PRAGMA wal_checkpoint(PASSIVE)").fetchone()
print(f"child: committed, then wal_checkpoint(PASSIVE): busy={busy} log={log} checkpointed={checkpointed}")
sometimes(
busy == 0 and checkpointed < log,
"a reader in another process stopped a checkpoint before the end of the WAL",
{"mode": "PASSIVE", "log": log, "checkpointed": checkpointed},
)
if __name__ == "__main__":
if sys.argv[1:] == ["commit-and-checkpoint"]:
commit_and_checkpoint()

View File

@@ -0,0 +1,56 @@
import time
import turso
from antithesis.assertions import always
DB_PATH = "multiprocess.db"
BUSY_RETRIES = 50
BUSY_SLEEP_SECONDS = 0.01
def connect():
return turso.connect(DB_PATH, experimental_features="multiprocess_wal", isolation_level=None)
def is_busy(exc):
text = str(exc).lower()
return "busy" in text or "locked" in text
def execute_with_busy_retry(cur, sql):
for _ in range(BUSY_RETRIES):
try:
return cur.execute(sql)
except turso.OperationalError as exc:
if not is_busy(exc):
raise
if cur.connection.in_transaction:
print(f"{sql} failed with busy but left a transaction open; rolling back")
cur.execute("ROLLBACK")
time.sleep(BUSY_SLEEP_SECONDS)
return None
def read_snapshot(cur):
rows = cur.execute("SELECT id, balance, generation FROM accounts ORDER BY id").fetchall()
return [tuple(row) for row in rows]
def check_snapshot(rows, expected_count, expected_total, label):
generations = {row[2] for row in rows}
total = sum(row[1] for row in rows)
always(
len(rows) == expected_count,
f"[{label}] every account is visible",
{"seen": len(rows), "expected": expected_count},
)
always(
len(generations) == 1,
f"[{label}] every row comes from the same commit",
{"generations": sorted(generations)[:10], "count": len(generations)},
)
always(
total == expected_total,
f"[{label}] total balance is preserved",
{"total": total, "expected": expected_total},
)

View File

@@ -0,0 +1,46 @@
#!/usr/bin/env -S python3 -u
import time
from antithesis.assertions import always, sometimes
from antithesis.random import get_random
from helper_common import connect
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
modes = ["PASSIVE", "FULL", "RESTART", "TRUNCATE"]
iterations = get_random() % 30 + 1
for _ in range(iterations):
mode = modes[get_random() % len(modes)]
try:
row = cur.execute(f"PRAGMA wal_checkpoint({mode})").fetchone()
except Exception as e:
print(f"wal_checkpoint({mode}) failed: {e}")
continue
busy, log, checkpointed = row
print(f"wal_checkpoint({mode}): busy={busy} log={log} checkpointed={checkpointed}")
always(busy in (0, 1), "wal_checkpoint reports busy as 0 or 1", {"busy": busy})
if busy == 0:
always(
0 <= checkpointed <= log,
"wal_checkpoint never reports more frames copied than logged",
{"log": log, "checkpointed": checkpointed},
)
sometimes(
log > 0 and checkpointed == log,
"a checkpoint copied every WAL frame into the database file",
{"mode": mode, "log": log},
)
sometimes(
checkpointed < log,
"a reader in another process stopped a checkpoint before the end of the WAL",
{"mode": mode, "log": log, "checkpointed": checkpointed},
)
time.sleep((get_random() % 200) / 1000.0)

View File

@@ -0,0 +1,14 @@
#!/usr/bin/env -S python3 -u
from antithesis.assertions import always
from helper_common import connect
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
row = cur.execute("PRAGMA integrity_check").fetchone()
always(row == ("ok",), "[Parallel] integrity_check passes while other processes run", {"result": row})

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env -S python3 -u
import os
import subprocess
import sys
import time
from antithesis.assertions import always, sometimes
from antithesis.random import get_random
from helper_common import check_snapshot, connect, execute_with_busy_retry, read_snapshot
CHILD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "helper_child.py")
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
num_accts, total = cur.execute("SELECT num_accts, total FROM initial_state").fetchone()
iterations = get_random() % 5 + 1
for _ in range(iterations):
if get_random() % 2 == 0:
try:
busy, log, checkpointed = cur.execute("PRAGMA wal_checkpoint(PASSIVE)").fetchone()
sometimes(
busy == 0 and log == checkpointed,
"[Reader] a read transaction begins right after the WAL was fully checkpointed",
{"log": log},
)
except Exception as e:
print(f"checkpoint before read failed: {e}")
if execute_with_busy_retry(cur, "BEGIN") is None:
continue
try:
pinned_id = get_random() % num_accts + 1
pinned_generation = cur.execute(f"SELECT generation FROM accounts WHERE id = {pinned_id}").fetchone()[0]
if get_random() % 2 == 0:
subprocess.run([sys.executable, CHILD, "commit-and-checkpoint"], check=False)
time.sleep((get_random() % 1000) / 1000.0)
rows = read_snapshot(cur)
check_snapshot(rows, num_accts, total, "Reader")
always(
all(row[2] == pinned_generation for row in rows),
"[Reader] pages read later in a transaction come from the same commit as the first page",
{"pinned_generation": pinned_generation, "seen": sorted({row[2] for row in rows})[:10]},
)
again = read_snapshot(cur)
always(
rows == again,
"[Reader] a read transaction sees the same rows for its whole lifetime",
{"first_generation": rows[0][2] if rows else None, "second_generation": again[0][2] if again else None},
)
finally:
cur.execute("COMMIT")
latest = cur.execute("SELECT max(generation) FROM accounts").fetchone()[0]
sometimes(
latest > pinned_generation,
"[Reader] another process committed while a read transaction was open",
{"snapshot_generation": pinned_generation, "latest": latest},
)

View File

@@ -0,0 +1,40 @@
#!/usr/bin/env -S python3 -u
from antithesis.assertions import sometimes
from antithesis.random import get_random
from helper_common import connect, execute_with_busy_retry
try:
con = connect()
except Exception as e:
print(f"Error connecting to database: {e}")
exit(0)
cur = con.cursor()
num_accts = cur.execute("SELECT num_accts FROM initial_state").fetchone()[0]
committed = 0
iterations = get_random() % 20 + 1
for _ in range(iterations):
sender = get_random() % num_accts + 1
recipient = get_random() % num_accts + 1
if sender == recipient:
continue
value = get_random() % 1000
if execute_with_busy_retry(cur, "BEGIN IMMEDIATE") is None:
continue
try:
cur.execute(f"UPDATE accounts SET balance = balance - {value} WHERE id = {sender}")
cur.execute(f"UPDATE accounts SET balance = balance + {value} WHERE id = {recipient}")
cur.execute("UPDATE accounts SET generation = generation + 1")
cur.execute("COMMIT")
committed += 1
except Exception as e:
print(f"write failed, rolling back: {e}")
try:
cur.execute("ROLLBACK")
except Exception as rollback_error:
print(f"rollback failed: {rollback_error}")
sometimes(committed > 0, "a writer process committed a transaction", {"committed": committed})
print(f"committed {committed} of {iterations} transactions")

0
testing/antithesis/stress-composer/helper_utils.py Executable file → Normal file
View File

4
tlaplus/multiprocess/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
MultiprocessWal.pdf
tla2tools.jar
states/
MultiprocessWal_TTrace_*

View File

@@ -0,0 +1,26 @@
# Makefile for MultiprocessWal TLA+ Model Checking
TLA2TOOLS ?= tla2tools.jar
JAVA_OPTS ?= -XX:+UseParallelGC -Xmx4g
TLC_OPTS ?= -workers auto -cleanup
SPEC = MultiprocessWal.tla
CFG ?= MultiprocessWal.cfg
all: check MultiprocessWal.pdf
check: $(TLA2TOOLS)
java $(JAVA_OPTS) -cp $(TLA2TOOLS) tlc2.TLC $(TLC_OPTS) -config $(CFG) $(SPEC)
MultiprocessWal.pdf: $(TLA2TOOLS) $(SPEC)
java -cp $(TLA2TOOLS) tla2tex.TLA -shade -latexCommand pdflatex $(SPEC)
pdflatex MultiprocessWal.tex
rm -f MultiprocessWal.tex MultiprocessWal.aux MultiprocessWal.log
$(TLA2TOOLS):
curl -LO https://github.com/tlaplus/tlaplus/releases/download/v1.8.0/tla2tools.jar
clean:
rm -rf states/ MultiprocessWal.pdf
.PHONY: all check clean

View File

@@ -0,0 +1,25 @@
\* TLC Configuration for MultiprocessWal
SPECIFICATION Spec
\* Model values
CONSTANTS
p1 = p1
p2 = p2
NOCONN = NOCONN
\* Bind constants
CONSTANTS
Processes = {p1, p2}
ConnsPerProcess = 2
MaxVersion = 3
NoConn = NOCONN
\* Invariants
INVARIANT TypeOK
INVARIANT DatabaseFileNotAheadOfReaders
INVARIANT DatabaseFileNotBehindReaders
INVARIANT WalNotRestartedUnderWalReaders
INVARIANT SingleWriter
INVARIANT RegistrationsMatchTransactions
INVARIANT WriterCanRestartWhenAlone

View File

@@ -0,0 +1,352 @@
--------------------------- MODULE MultiprocessWal ---------------------------
(*
`^\textbf{\large Turso Multiprocess WAL Coordination Specification}^'
This specification models how Turso coordinates readers, the writer, and
checkpoints when several processes open the same database in WAL mode.
The coordination code is `^{\tt ShmWalCoordination}^' in
`^{\tt core/storage/wal.rs}^' and `^{\tt MappedSharedWalCoordination}^'
in `^{\tt core/storage/shared\_wal\_coordination.rs}^'.
`^\textbf{Two layers of locks.}^' SQLite keeps all WAL locks in the
`^{\tt -shm}^' file, so every process sees every lock. Turso keeps the
read locks inside each process. Read lock 0 and the read marks are
visible only to connections in the same process. Other processes learn
about a reader only through the shared reader table in the
`^{\tt -tshm}^' file. The writer lock and the checkpoint lock are shared
by all processes.
`^\textbf{Database file readers.}^' A read transaction that begins when
the WAL is fully backfilled (`mxFrame' = `nBackfill') reads every page
from the database file and holds read lock 0. It registers in the shared
reader table without a frame number. While one is registered, a
checkpoint in any process copies nothing past the current `nBackfill'.
These readers do not stop a WAL restart, because they never read the WAL.
`^\textbf{WAL readers.}^' A read transaction that begins when the WAL
has frames that are not backfilled reads frames up to its snapshot's
`mxFrame' from the WAL and the other pages from the database file. It
holds a read mark in its process and registers its `mxFrame' in the
shared reader table. Checkpoints in every process stop at that frame,
and the WAL cannot restart until it ends.
`^\textbf{Versions.}^' Every commit appends one frame and creates one new
database version. `walBase' is the version the database file had when the
current WAL generation started, so frame $i$ of the current generation
holds version `walBase' $+\,i$. The database file holds version
`walBase' $+$ `dbFrames'.
`^\textbf{What is not modeled.}^' Process crashes and reclaiming slots of
dead processes, running out of reader slots, the shared frame index and
its overflow, RESTART and TRUNCATE checkpoints, and rollbacks.
*)
EXTENDS Naturals, FiniteSets
CONSTANTS
Processes, \* Set of processes that open the database
ConnsPerProcess, \* Number of connections in each process
MaxVersion, \* Upper bound on the number of commits
NoConn \* Sentinel for "no connection"
Conns == Processes \X (1..ConnsPerProcess)
Proc(c) == c[1]
VARIABLES
mode, \* `mode'[c]: where connection c is in its transaction
snap, \* `snap'[c]: the WAL snapshot connection c loaded
reg, \* `reg'[c]: connection c's entry in the shared reader table
walGen, \* WAL generation, increased by every restart
walBase, \* Database version when the current WAL generation started
mxFrame, \* Last committed frame in the current WAL generation
nBackfill, \* Frames of the current generation published as backfilled
dbFrames, \* Frames of the current generation copied to the database file
writer, \* Connection holding the shared writer lock, or `NoConn'
ckpt \* The running checkpoint: its connection and safe frame
vars == <<mode, snap, reg, walGen, walBase, mxFrame, nBackfill, dbFrames,
writer, ckpt>>
Modes == {"Idle", "Loaded", "Locked", "Registered", "Reading", "Writing",
"Checkpointing"}
Snapshots == [gen : 0..MaxVersion, mx : 0..MaxVersion, nb : 0..MaxVersion,
ver : 0..MaxVersion]
Registrations == [kind : {"none", "dbfile", "wal"}, frame : 0..MaxVersion]
NoRegistration == [kind |-> "none", frame |-> 0]
NoCheckpoint == [owner |-> NoConn, safe |-> 0]
Min(S) == CHOOSE x \in S : \A y \in S : x <= y
DbVersion == walBase + dbFrames
--------------------------------------------------------------------------------
(* `^\textbf{Local locks.}^' A connection holds a local read lock from the
moment it takes one until its transaction ends. Which lock it holds
depends on the snapshot it loaded. *)
HoldsLocalLock(c) == mode[c] \in {"Locked", "Registered", "Reading", "Writing"}
ReadsDatabaseFile(c) == snap[c].mx = snap[c].nb
HoldsReadLock0(c) == HoldsLocalLock(c) /\ ReadsDatabaseFile(c)
HoldsReadMark(c) == HoldsLocalLock(c) /\ ~ReadsDatabaseFile(c)
LocalCheckpointRunning(p) == ckpt.owner # NoConn /\ Proc(ckpt.owner) = p
(* `^\textbf{Shared reader table.}^' Registrations of connections in one
process share a slot, which does not change what other processes see. *)
SharedWalReaderFrames == {reg[c].frame : c \in {d \in Conns : reg[d].kind = "wal"}}
HasDatabaseFileReader == \E c \in Conns : reg[c].kind = "dbfile"
--------------------------------------------------------------------------------
(* `^\textbf{Type Invariant.}^' *)
TypeOK ==
/\ mode \in [Conns -> Modes]
/\ snap \in [Conns -> Snapshots]
/\ reg \in [Conns -> Registrations]
/\ walGen \in 0..MaxVersion
/\ walBase \in 0..MaxVersion
/\ mxFrame \in 0..MaxVersion
/\ nBackfill \in 0..mxFrame
/\ dbFrames \in nBackfill..mxFrame
/\ writer \in Conns \cup {NoConn}
/\ ckpt.owner \in Conns \cup {NoConn}
/\ ckpt.safe \in 0..MaxVersion
--------------------------------------------------------------------------------
(* `^\textbf{Database File Not Ahead Of Readers.}^' The database file never
holds a version newer than the snapshot of an active transaction.
Otherwise a reader that reads a page from the database file would see a
page from a later commit next to pages from its own snapshot. *)
DatabaseFileNotAheadOfReaders ==
\A c \in Conns :
mode[c] \in {"Reading", "Writing"} => DbVersion <= snap[c].ver
(* `^\textbf{Database File Not Behind Readers.}^' The database file holds
every frame that a transaction expects to find there instead of in the
WAL. *)
DatabaseFileNotBehindReaders ==
\A c \in Conns :
mode[c] \in {"Reading", "Writing"} =>
DbVersion >= snap[c].ver - snap[c].mx + snap[c].nb
(* `^\textbf{WAL Not Restarted Under WAL Readers.}^' A restart makes new
commits overwrite the WAL from frame 1, so it must not happen while a
transaction still reads frames of the old generation. *)
WalNotRestartedUnderWalReaders ==
\A c \in Conns :
mode[c] \in {"Reading", "Writing"} /\ ~ReadsDatabaseFile(c) =>
snap[c].gen = walGen
(* `^\textbf{Single Writer.}^' Only the connection holding the writer lock
writes. *)
SingleWriter ==
\A c \in Conns : mode[c] = "Writing" <=> writer = c
(* `^\textbf{Registrations Match Transactions.}^' A connection has an entry
in the shared reader table only while it is in a read transaction. *)
RegistrationsMatchTransactions ==
\A c \in Conns :
mode[c] \in {"Idle", "Loaded", "Locked", "Checkpointing"} =>
reg[c] = NoRegistration
--------------------------------------------------------------------------------
(* `^\textbf{Restart Conditions.}^' A writer restarts the WAL before
writing when its read transaction reads the database file and every
frame is backfilled. In its own process it needs read lock 0 for itself
and no read mark in use. In the shared reader table it needs no WAL
reader. Database file readers, including the writer itself, do not block
the restart. *)
CanRestart(c) ==
/\ mode[c] = "Writing"
/\ ReadsDatabaseFile(c)
/\ nBackfill > 0
/\ mxFrame = nBackfill
/\ \A d \in Conns \ {c} :
Proc(d) = Proc(c) => ~HoldsReadLock0(d) /\ ~HoldsReadMark(d)
/\ \A d \in Conns : reg[d].kind # "wal"
(* `^\textbf{Writer Can Restart When Alone.}^' A writer that is the only
connection in a transaction can always restart a fully backfilled WAL.
If its own entry in the shared reader table blocked the restart, the WAL
would never restart and would grow without bound. *)
WriterCanRestartWhenAlone ==
\A c \in Conns :
/\ mode[c] = "Writing"
/\ ReadsDatabaseFile(c)
/\ nBackfill > 0
/\ mxFrame = nBackfill
/\ \A d \in Conns \ {c} : mode[d] = "Idle"
=> CanRestart(c)
--------------------------------------------------------------------------------
(* `^\textbf{Checkpoint Safe Frame.}^' The last frame a checkpoint may copy.
It stops at the read marks in its own process, at every WAL reader in the
shared reader table, and at the current `nBackfill' while any database
file reader is registered. *)
SafeFrame(c) ==
Min({mxFrame}
\cup {snap[d].mx : d \in {e \in Conns : Proc(e) = Proc(c) /\ HoldsReadMark(e)}}
\cup SharedWalReaderFrames
\cup (IF HasDatabaseFileReader THEN {nBackfill} ELSE {}))
--------------------------------------------------------------------------------
(* `^\textbf{Initial State.}^' An empty WAL and no transactions. *)
Init ==
/\ mode = [c \in Conns |-> "Idle"]
/\ snap = [c \in Conns |-> [gen |-> 0, mx |-> 0, nb |-> 0, ver |-> 0]]
/\ reg = [c \in Conns |-> NoRegistration]
/\ walGen = 0
/\ walBase = 0
/\ mxFrame = 0
/\ nBackfill = 0
/\ dbFrames = 0
/\ writer = NoConn
/\ ckpt = NoCheckpoint
--------------------------------------------------------------------------------
(* `^\textbf{Beginning a read transaction}^' takes four steps, and other
connections may act between any two of them. *)
(* `^\textbf{LoadSnapshot}^' --- read the shared WAL snapshot. *)
LoadSnapshot(c) ==
/\ mode[c] = "Idle"
/\ mode' = [mode EXCEPT ![c] = "Loaded"]
/\ snap' = [snap EXCEPT ![c] = [gen |-> walGen, mx |-> mxFrame,
nb |-> nBackfill, ver |-> walBase + mxFrame]]
/\ UNCHANGED <<reg, walGen, walBase, mxFrame, nBackfill, dbFrames, writer, ckpt>>
(* `^\textbf{TakeLocalLock}^' --- take read lock 0 for a database file
reader, or a read mark for a WAL reader. Read lock 0 is not available
while a checkpoint in the same process holds it exclusively. *)
TakeLocalLock(c) ==
/\ mode[c] = "Loaded"
/\ ReadsDatabaseFile(c) => ~LocalCheckpointRunning(Proc(c))
/\ mode' = [mode EXCEPT ![c] = "Locked"]
/\ UNCHANGED <<snap, reg, walGen, walBase, mxFrame, nBackfill, dbFrames, writer, ckpt>>
(* `^\textbf{Register}^' --- add the reader to the shared reader table. *)
Register(c) ==
/\ mode[c] = "Locked"
/\ mode' = [mode EXCEPT ![c] = "Registered"]
/\ reg' = [reg EXCEPT ![c] =
IF ReadsDatabaseFile(c) THEN [kind |-> "dbfile", frame |-> 0]
ELSE [kind |-> "wal", frame |-> snap[c].mx]]
/\ UNCHANGED <<snap, walGen, walBase, mxFrame, nBackfill, dbFrames, writer, ckpt>>
(* `^\textbf{Validate}^' --- check that the shared snapshot has not changed
since it was loaded. A commit, a checkpoint, or a restart in between
could have happened before the registration was visible, so the
connection gives up its lock and registration and starts over. *)
Validate(c) ==
/\ mode[c] = "Registered"
/\ IF snap[c].gen = walGen /\ snap[c].mx = mxFrame /\ snap[c].nb = nBackfill
THEN /\ mode' = [mode EXCEPT ![c] = "Reading"]
/\ UNCHANGED reg
ELSE /\ mode' = [mode EXCEPT ![c] = "Idle"]
/\ reg' = [reg EXCEPT ![c] = NoRegistration]
/\ UNCHANGED <<snap, walGen, walBase, mxFrame, nBackfill, dbFrames, writer, ckpt>>
(* `^\textbf{EndRead}^' --- end the read transaction. *)
EndRead(c) ==
/\ mode[c] = "Reading"
/\ mode' = [mode EXCEPT ![c] = "Idle"]
/\ reg' = [reg EXCEPT ![c] = NoRegistration]
/\ UNCHANGED <<snap, walGen, walBase, mxFrame, nBackfill, dbFrames, writer, ckpt>>
--------------------------------------------------------------------------------
(* `^\textbf{BeginWrite}^' --- upgrade a read transaction to a write
transaction. The snapshot must still be the latest one. *)
BeginWrite(c) ==
/\ mode[c] = "Reading"
/\ writer = NoConn
/\ snap[c].gen = walGen
/\ snap[c].mx = mxFrame
/\ mode' = [mode EXCEPT ![c] = "Writing"]
/\ writer' = c
/\ UNCHANGED <<snap, reg, walGen, walBase, mxFrame, nBackfill, dbFrames, ckpt>>
(* `^\textbf{RestartWal}^' --- start a new WAL generation before writing.
The database file already holds every frame, so the new generation
starts from the database file's version. The writer's snapshot moves to
the new generation. *)
RestartWal(c) ==
/\ CanRestart(c)
/\ walGen' = walGen + 1
/\ walBase' = walBase + mxFrame
/\ mxFrame' = 0
/\ nBackfill' = 0
/\ dbFrames' = 0
/\ snap' = [snap EXCEPT ![c] = [gen |-> walGen + 1, mx |-> 0, nb |-> 0,
ver |-> snap[c].ver]]
/\ UNCHANGED <<mode, reg, writer, ckpt>>
(* `^\textbf{Commit}^' --- append one frame and end the transaction. *)
Commit(c) ==
/\ mode[c] = "Writing"
/\ walBase + mxFrame < MaxVersion
/\ mxFrame' = mxFrame + 1
/\ mode' = [mode EXCEPT ![c] = "Idle"]
/\ reg' = [reg EXCEPT ![c] = NoRegistration]
/\ writer' = NoConn
/\ UNCHANGED <<snap, walGen, walBase, nBackfill, dbFrames, ckpt>>
--------------------------------------------------------------------------------
(* `^\textbf{Checkpoint.}^' A PASSIVE checkpoint takes the shared checkpoint
lock and read lock 0 in its own process, computes the safe frame once,
copies frames one at a time, and publishes the new `nBackfill' at the
end. Readers may register while it copies. *)
CheckpointBegin(c) ==
/\ mode[c] = "Idle"
/\ ckpt.owner = NoConn
/\ mxFrame > nBackfill
/\ \A d \in Conns : Proc(d) = Proc(c) => ~HoldsReadLock0(d)
/\ mode' = [mode EXCEPT ![c] = "Checkpointing"]
/\ ckpt' = [owner |-> c, safe |-> SafeFrame(c)]
/\ UNCHANGED <<snap, reg, walGen, walBase, mxFrame, nBackfill, dbFrames, writer>>
CheckpointCopyFrame ==
/\ ckpt.owner # NoConn
/\ dbFrames < ckpt.safe
/\ dbFrames' = dbFrames + 1
/\ UNCHANGED <<mode, snap, reg, walGen, walBase, mxFrame, nBackfill, writer, ckpt>>
CheckpointEnd ==
/\ ckpt.owner # NoConn
/\ dbFrames >= ckpt.safe
/\ nBackfill' = dbFrames
/\ mode' = [mode EXCEPT ![ckpt.owner] = "Idle"]
/\ ckpt' = NoCheckpoint
/\ UNCHANGED <<snap, reg, walGen, walBase, mxFrame, dbFrames, writer>>
--------------------------------------------------------------------------------
Next ==
\/ \E c \in Conns :
\/ LoadSnapshot(c)
\/ TakeLocalLock(c)
\/ Register(c)
\/ Validate(c)
\/ EndRead(c)
\/ BeginWrite(c)
\/ RestartWal(c)
\/ Commit(c)
\/ CheckpointBegin(c)
\/ CheckpointCopyFrame
\/ CheckpointEnd
Spec == Init /\ [][Next]_vars
================================================================================

View File

@@ -0,0 +1,16 @@
# Turso Multiprocess WAL Coordination Specification
TLA+ specification for how Turso coordinates readers, the writer, and
checkpoints when several processes open the same database in WAL mode.
The specification itself (`MultiprocessWal.tla`) is the primary
documentation — generate the PDF for a typeset version.
## Quick Start
```bash
# Model check (about 32 million distinct states, a few minutes)
make check
# Generate PDF
make MultiprocessWal.pdf
```