From b228f1d9c48fe64d3395683e0632da71a8e6fcda Mon Sep 17 00:00:00 2001 From: yyjeqhc <1772413353@qq.com> Date: Sat, 28 Nov 2026 09:58:23 +0800 Subject: [PATCH] fix(session): reserve the WAL writer before reading revisions --- crates/webcodex-workflow-session/Cargo.toml | 1 + .../src/persistence/database.rs | 13 +++- .../src/store/writer/sqlite_tests.rs | 60 +++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/webcodex-workflow-session/Cargo.toml b/crates/webcodex-workflow-session/Cargo.toml index dd1809db8..7e3cacd0b 100644 --- a/crates/webcodex-workflow-session/Cargo.toml +++ b/crates/webcodex-workflow-session/Cargo.toml @@ -21,5 +21,6 @@ tracing = "0.1" uuid = { version = "1", features = ["v4"] } [dev-dependencies] +rusqlite = { version = "0.40.2", features = ["hooks"] } tempfile = "3" tokio = { version = "1", features = ["sync", "time", "macros", "rt-multi-thread"] } diff --git a/crates/webcodex-workflow-session/src/persistence/database.rs b/crates/webcodex-workflow-session/src/persistence/database.rs index f8c895d5e..bcdeaa98f 100644 --- a/crates/webcodex-workflow-session/src/persistence/database.rs +++ b/crates/webcodex-workflow-session/src/persistence/database.rs @@ -3,7 +3,7 @@ //! The database is authoritative backing for clean cache entries, never a replay //! engine. Loading history cannot dispatch a tool or change Session authority. use super::*; -use rusqlite::{params, Connection, OptionalExtension}; +use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior}; use std::path::Path; use std::sync::Mutex; @@ -116,7 +116,11 @@ impl SessionDatabase { pub(crate) fn write(&self, writes: &[SessionWrite]) -> io::Result { let mut connection = self.connection.lock().map_err(error)?; - let transaction = connection.transaction().map_err(error)?; + // Reserve the writer before reading revisions. An intervening WAL commit + // would leave a deferred transaction with a snapshot it cannot promote. + let transaction = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(error)?; let mut bytes = 0_u64; for write in writes { bytes = bytes.saturating_add(write_row(&transaction, write)?); @@ -140,6 +144,11 @@ impl SessionDatabase { Ok(result) } + #[cfg(test)] + pub(crate) fn connection_for_test(&self) -> std::sync::MutexGuard<'_, Connection> { + self.connection.lock().unwrap() + } + #[cfg(any(test, feature = "root-test-support"))] pub(crate) fn fail_writes(&self, fail: bool) { self.connection diff --git a/crates/webcodex-workflow-session/src/store/writer/sqlite_tests.rs b/crates/webcodex-workflow-session/src/store/writer/sqlite_tests.rs index 1375cee34..df96836a8 100644 --- a/crates/webcodex-workflow-session/src/store/writer/sqlite_tests.rs +++ b/crates/webcodex-workflow-session/src/store/writer/sqlite_tests.rs @@ -138,6 +138,66 @@ fn latest_instruction_and_closed_identity_survive_history_and_session_churn() { assert_eq!(restored.status().retained_sessions, 151); } +#[test] +fn unrelated_wal_write_cannot_invalidate_the_session_revision_read() { + use rusqlite::hooks::{AuthAction, AuthContext, Authorization}; + + let (temporary, store) = persistent_fixture(Duration::from_secs(60)); + let id = store.start_session(None, None).session_id; + store.flush_persistence(); + let path = temporary.path().join("sessions.sqlite3"); + let audit = rusqlite::Connection::open(&path).unwrap(); + audit + .execute("CREATE TABLE audit_fixture (id INTEGER PRIMARY KEY)", []) + .unwrap(); + audit.busy_timeout(Duration::ZERO).unwrap(); + const INSERT_AUDIT: &str = "INSERT INTO audit_fixture VALUES (1)"; + + // Preparing the Session upsert happens after the revision SELECT has run. + // Attempt the independent commit at precisely that point on a second connection. + let (attempt, result) = std::sync::mpsc::channel(); + let database = store + .inner + .lock() + .unwrap() + .persistence + .as_ref() + .unwrap() + .database + .clone(); + database + .connection_for_test() + .authorizer(Some(move |context: AuthContext<'_>| { + if let AuthAction::Insert { + table_name: "workflow_sessions", + } = context.action + { + let _ = attempt.send(audit.execute(INSERT_AUDIT, [])); + } + Authorization::Allow + })) + .unwrap(); + + append_read_fixture(&store, &id, 1); + store.flush_persistence(); + assert_eq!(store.status().last_persist_error, None); + assert_eq!( + result.try_recv().unwrap().unwrap_err().sqlite_error_code(), + Some(rusqlite::ErrorCode::DatabaseBusy) + ); + + let connection = rusqlite::Connection::open(&path).unwrap(); + assert_eq!(connection.execute(INSERT_AUDIT, []).unwrap(), 1); + let events: i64 = connection + .query_row( + "SELECT count(*) FROM workflow_session_events WHERE session_id=?1", + [&id], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(events, 2); +} + #[test] fn stale_second_writer_fails_closed_instead_of_overwriting_a_newer_commit() { let (temporary, store) = persistent_fixture(Duration::from_secs(60));