Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/webcodex-workflow-session/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
13 changes: 11 additions & 2 deletions crates/webcodex-workflow-session/src/persistence/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -116,7 +116,11 @@ impl SessionDatabase {

pub(crate) fn write(&self, writes: &[SessionWrite]) -> io::Result<u64> {
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)?);
Expand All @@ -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
Expand Down
60 changes: 60 additions & 0 deletions crates/webcodex-workflow-session/src/store/writer/sqlite_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Loading