diff --git a/crates/rhema-claw/src/turn_store.rs b/crates/rhema-claw/src/turn_store.rs index 4ef694f..2b3ba78 100644 --- a/crates/rhema-claw/src/turn_store.rs +++ b/crates/rhema-claw/src/turn_store.rs @@ -15,7 +15,7 @@ use std::path::Path; use std::sync::{Mutex, PoisonError}; -use rusqlite::params; +use rusqlite::{TransactionBehavior, params}; use serde_json::Value; use crate::hub::TurnEvent; @@ -99,7 +99,16 @@ impl TurnStore { return Ok(()); } let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner); - let tx = conn.transaction().map_err(TurnStoreError::from)?; + // Immediate, not deferred. The append reads the next sequence + // and then writes, and a deferred transaction that reads first + // and upgrades to a writer later is the shape SQLite answers + // with SQLITE_BUSY_SNAPSHOT — "database is locked", straight + // past the busy timeout — as soon as the dispatcher's checkpoint + // commits in between. Taking the write lock up front is what + // makes the timeout cover the wait. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(TurnStoreError::from)?; let next: i64 = tx .query_row( "SELECT COALESCE(MAX(seq) + 1, 0) FROM turn_events WHERE key = ?1", @@ -308,6 +317,40 @@ mod tests { } } + /// The dispatcher checkpoints on the same file while a turn streams, + /// so an append can find the write lock taken. It has to wait for it + /// — a lost append is a hole in the replay — and a deferred + /// transaction that reads the next sequence first answers + /// "database is locked" instead of waiting. + #[test] + fn an_append_waits_for_another_connections_write_lock() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("turns.db"); + let store = TurnStore::open(&path).expect("store opens"); + let holder = rusqlite::Connection::open(&path).expect("second connection opens"); + holder + .execute_batch("BEGIN IMMEDIATE") + .expect("the other connection takes the write lock"); + let release = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(200)); + holder + .execute_batch("COMMIT") + .expect("the other connection releases it"); + }); + + store + .append("interactive:web", &[text_delta("hi")]) + .expect("the append waits out the lock"); + release.join().unwrap(); + assert_eq!( + store + .events_from("interactive:web", -1, usize::MAX) + .expect("the events read back") + .len(), + 1 + ); + } + #[test] fn an_appended_history_round_trips_through_events() { let store = TurnStore::in_memory().expect("store opens");