diff --git a/codex-rs/state/src/sqlite.rs b/codex-rs/state/src/sqlite.rs index 58dbfafba9..e968981702 100644 --- a/codex-rs/state/src/sqlite.rs +++ b/codex-rs/state/src/sqlite.rs @@ -256,6 +256,22 @@ impl SqliteConfig { probe_nfs(self.home(), &self.is_nfs).await } + pub async fn prefers_rollback_journal(&self) -> bool { + self.is_nfs() + .await + .is_ok_and(|is_nfs| self.journal_mode_policy(is_nfs).prefers_rollback()) + } + + fn journal_mode_policy(&self, is_nfs: bool) -> JournalModePolicy { + if !is_nfs { + JournalModePolicy::InitializeWal + } else if self.enforce_delete_on_nfs { + JournalModePolicy::RequireDelete + } else { + JournalModePolicy::InitializeDelete + } + } + pub(crate) async fn logs_are_on_nfs(&self) -> anyhow::Result { probe_nfs(self.logs_home(), &self.logs_is_nfs).await } @@ -505,24 +521,17 @@ impl SqliteConfig { }; // Keep the migration lock through pool initialization so another managed startup // cannot open the old inode or initialize a database during cutover. - let migration = if self.enforce_delete_on_nfs && is_nfs { + let journal_mode_policy = self.journal_mode_policy(is_nfs); + let _migration = if journal_mode_policy == JournalModePolicy::RequireDelete { Some(nfs::prepare_database(self, path).await?) } else { None }; - let journal_mode_policy = if migration.is_some() { - JournalModePolicy::RequireDelete - } else if is_nfs { - JournalModePolicy::InitializeDelete - } else { - JournalModePolicy::InitializeWal - }; let recovery = recover_spec.map_or(RecoveryMode::Unavailable, |spec| spec.recovery); let options = SqliteConnectOptions::new() .filename(path) .create_if_missing(true) .synchronous(SqliteSynchronous::Normal) - .busy_timeout(DEFAULT_BUSY_TIMEOUT) .log_statements(LevelFilter::Off); // Each failed attempt closes its pool before initialization is retried. let connect = || async { diff --git a/codex-rs/state/src/sqlite/connection.rs b/codex-rs/state/src/sqlite/connection.rs index 0d74e91532..46f5dce73b 100644 --- a/codex-rs/state/src/sqlite/connection.rs +++ b/codex-rs/state/src/sqlite/connection.rs @@ -7,11 +7,16 @@ reason = "centralized SQLite connection initialization" )] +use std::time::Duration; + use sqlx::Error; use sqlx::SqlitePool; use sqlx::sqlite::SqliteConnectOptions; use sqlx::sqlite::SqlitePoolOptions; +const ROLLBACK_JOURNAL_BUSY_TIMEOUT: Duration = Duration::from_secs(60); +const ROLLBACK_JOURNAL_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(120); + #[derive(Clone, Copy, Eq, PartialEq)] pub(super) enum JournalModePolicy { InitializeWal, @@ -19,6 +24,12 @@ pub(super) enum JournalModePolicy { RequireDelete, } +impl JournalModePolicy { + pub(super) fn prefers_rollback(self) -> bool { + matches!(self, Self::InitializeDelete | Self::RequireDelete) + } +} + pub(super) async fn connect_once( options: &SqliteConnectOptions, journal_mode_policy: JournalModePolicy, @@ -26,45 +37,54 @@ pub(super) async fn connect_once( // SQLx retries after_connect errors, eventually replacing them with PoolTimedOut. // Return the first initialization error directly while opening this pool. let (init_error_tx, mut init_error_rx) = tokio::sync::mpsc::channel(/*buffer*/ 1); - let pool_options = - SqlitePoolOptions::new() - .max_connections(5) - .after_connect(move |connection, _metadata| { - let init_error_tx = init_error_tx.clone(); - Box::pin(async move { - let result = async { - let journal: String = sqlx::query_scalar("PRAGMA journal_mode") - .fetch_one(&mut *connection) - .await?; - if journal_mode_policy == JournalModePolicy::RequireDelete - && journal != "delete" - { - return Err(Error::Protocol(format!( - "NFS database requires DELETE journaling, found {journal}" - ))); - } - if journal == "delete" { - // If the filesystem honors sync requests, EXTRA syncs the directory - // after SQLite deletes a rollback journal. - sqlx::query("PRAGMA synchronous = EXTRA") - .execute(connection) - .await?; - } - Ok(()) - } - .await; - result.map_err(|error| match init_error_tx.try_send(error) { - // The opener owns the original error and cancels connection retries. - Ok(()) => Error::PoolClosed, - // After opening, lazy connections retain SQLx's normal error handling. - Err(error) => error.into_inner(), - }) - }) - }); + let (busy_timeout, pool_options) = if journal_mode_policy.prefers_rollback() { + ( + ROLLBACK_JOURNAL_BUSY_TIMEOUT, + SqlitePoolOptions::new() + .max_connections(2) + .acquire_timeout(ROLLBACK_JOURNAL_ACQUIRE_TIMEOUT), + ) + } else { + ( + super::DEFAULT_BUSY_TIMEOUT, + SqlitePoolOptions::new().max_connections(5), + ) + }; + let options = options.clone().busy_timeout(busy_timeout); + let pool_options = pool_options.after_connect(move |connection, _metadata| { + let init_error_tx = init_error_tx.clone(); + Box::pin(async move { + let result = async { + let journal: String = sqlx::query_scalar("PRAGMA journal_mode") + .fetch_one(&mut *connection) + .await?; + if journal_mode_policy == JournalModePolicy::RequireDelete && journal != "delete" { + return Err(Error::Protocol(format!( + "NFS database requires DELETE journaling, found {journal}" + ))); + } + if journal == "delete" { + // If the filesystem honors sync requests, EXTRA syncs the directory + // after SQLite deletes a rollback journal. + sqlx::query("PRAGMA synchronous = EXTRA") + .execute(connection) + .await?; + } + Ok(()) + } + .await; + result.map_err(|error| match init_error_tx.try_send(error) { + // The opener owns the original error and cancels connection retries. + Ok(()) => Error::PoolClosed, + // After opening, lazy connections retain SQLx's normal error handling. + Err(error) => error.into_inner(), + }) + }) + }); let pool = tokio::select! { biased; Some(error) = init_error_rx.recv() => Err(error), - result = pool_options.connect_with(options.clone()) => result, + result = pool_options.connect_with(options) => result, }?; // Database settings persist on disk. // Initialize these settings once before callers can use the pool. diff --git a/codex-rs/state/src/sqlite_tests.rs b/codex-rs/state/src/sqlite_tests.rs index f850ceb7fb..eb1cc6dc73 100644 --- a/codex-rs/state/src/sqlite_tests.rs +++ b/codex-rs/state/src/sqlite_tests.rs @@ -272,7 +272,8 @@ async fn open_read_write_pool_initializes_fresh_database_settings() -> anyhow::R // Hold connections open so the assertions cover lazy pool connections too. let mut connections = Vec::new(); let mut settings = Vec::new(); - for _ in 0..5 { + let connection_count = usize::try_from(pool.options().get_max_connections())?; + for _ in 0..connection_count { let mut connection = pool.acquire().await?; let current: (String, i64, i64) = sqlx::query_as( "SELECT journal_mode, auto_vacuum, synchronous @@ -291,7 +292,7 @@ async fn open_read_write_pool_initializes_fresh_database_settings() -> anyhow::R SqliteAutoVacuum::Incremental as i64, if nfs { 3 } else { 1 }, ); - 5 + connection_count ] ); drop(connections); @@ -411,7 +412,8 @@ async fn open_read_write_pool_preserves_delete_under_write_lock() -> anyhow::Res // Keep each acquired connection open to test connections that the pool initializes later. let mut connections = Vec::new(); let mut settings = Vec::new(); - for _ in 0..5 { + let connection_count = usize::try_from(pool.options().get_max_connections())?; + for _ in 0..connection_count { let mut connection = pool.acquire().await?; let journal: String = sqlx::query_scalar("PRAGMA journal_mode") .fetch_one(&mut *connection) @@ -422,7 +424,7 @@ async fn open_read_write_pool_preserves_delete_under_write_lock() -> anyhow::Res settings.push((journal, synchronous)); connections.push(connection); } - assert_eq!(settings, vec![("delete".to_string(), 3); 5]); + assert_eq!(settings, vec![("delete".to_string(), 3); connection_count]); drop(connections); sqlx::query("ROLLBACK").execute(&mut *lock_holder).await?; drop(lock_holder); diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index 6d0d267ba2..31367084f7 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -248,6 +248,14 @@ impl LiveThread { if items.is_empty() { return Ok(()); } + if self.should_defer_rollout_metadata().await { + let _ = self + .metadata_sync + .lock() + .await + .observe_appended_items(items.as_slice()); + return Ok(()); + } self.observe_appended_metadata(&items).await } @@ -277,8 +285,27 @@ impl LiveThread { })) } + async fn should_defer_rollout_metadata(&self) -> bool { + if self.history_mode == ThreadHistoryMode::Paginated + && let Some(store) = self + .thread_store + .as_any() + .downcast_ref::() + { + store.config.sqlite.prefers_rollback_journal().await + } else { + false + } + } + pub async fn persist(&self, context: PersistContext) -> ThreadStoreResult<()> { if context.allows_background_persistence() { + if self.should_defer_rollout_metadata().await { + return self + .thread_store + .persist_thread(self.thread_id, context) + .await; + } let update = self .metadata_sync .lock() diff --git a/codex-rs/thread-store/src/local/delete_thread.rs b/codex-rs/thread-store/src/local/delete_thread.rs index cc2cb664f5..2548f7d88a 100644 --- a/codex-rs/thread-store/src/local/delete_thread.rs +++ b/codex-rs/thread-store/src/local/delete_thread.rs @@ -284,9 +284,8 @@ async fn delete_thread_after_reference_check( } } thread_rollouts.rollout_ids.insert(thread_id); - for rollout_id in thread_rollouts.rollout_ids { - super::thread_history::delete_thread(store, rollout_id).await?; - } + // An existing history database must be accessible before any rollout is removed. + let _ = super::thread_history::history_db_for_delete(store).await?; // Stop queued file work before removing files, retaining ownership until cleanup finishes. let live_entry = store.live_recorders.lock().await.remove(&thread_id); @@ -304,6 +303,11 @@ async fn delete_thread_after_reference_check( for rollout_path in thread_rollouts.paths { delete_rollout_file(store, rollout_path.as_path())?; } + // History readers can project while a thread is live. Unlink the rollouts before + // clearing the projection checkpoint so queued batches cannot recreate deleted rows. + for rollout_id in thread_rollouts.rollout_ids { + super::thread_history::delete_thread(store, rollout_id).await?; + } remove_thread_name_entries(store.config.codex_home.as_path(), thread_id) .await .map_err(|err| ThreadStoreError::Internal { @@ -844,7 +848,7 @@ SELECT .resume_thread(ResumeThreadParams { history_revision: None, thread_id, - rollout_path: Some(rollout_path), + rollout_path: Some(rollout_path.clone()), history: None, include_archived: false, metadata: ThreadPersistenceMetadata { @@ -867,6 +871,21 @@ SELECT .expect("delete thread"); assert!(!lock_path.exists()); + let stale_projection = super::super::thread_history::apply_projection( + &store, + thread_id, + Some(rollout_path.as_path()), + /*start_offset*/ 0, + /*next_offset*/ 3, + /*initial_ordinal*/ 0, + Vec::new(), + ) + .await; + assert!(matches!( + stale_projection, + Err(ThreadStoreError::ThreadNotFound { thread_id: deleted }) if deleted == thread_id + )); + let counts = sqlx::query_as::<_, (i64, i64, i64, i64)>( r#" SELECT diff --git a/codex-rs/thread-store/src/local/live_writer.rs b/codex-rs/thread-store/src/local/live_writer.rs index c408b9630d..bf8037cd1d 100644 --- a/codex-rs/thread-store/src/local/live_writer.rs +++ b/codex-rs/thread-store/src/local/live_writer.rs @@ -566,7 +566,9 @@ async fn write_and_project( RolloutWriteOp::Persist => recorder.persist().await.map_err(thread_store_io_error)?, RolloutWriteOp::Flush => recorder.flush().await.map_err(thread_store_io_error)?, } - if matches!(history_mode, ThreadHistoryMode::Paginated) { + if matches!(history_mode, ThreadHistoryMode::Paginated) + && !store.config.sqlite.prefers_rollback_journal().await + { // SQLite is a rebuildable view and must never get ahead of canonical history. let rollout_path = recorder.rollout_path(); // Only the plain file's length is a decoded JSONL byte offset. diff --git a/codex-rs/thread-store/src/local/rollout_lineage/walk.rs b/codex-rs/thread-store/src/local/rollout_lineage/walk.rs index 52932f8908..fafe4227e2 100644 --- a/codex-rs/thread-store/src/local/rollout_lineage/walk.rs +++ b/codex-rs/thread-store/src/local/rollout_lineage/walk.rs @@ -152,7 +152,13 @@ impl<'a> LineageWalk<'a> { LineageResolutionMode::HistoryPage => { bounds .read_history_page_bounds(&path, requested_thread_id) - .await? + .await?; + if store.config.sqlite.prefers_rollback_journal().await { + super::super::thread_history_materialization::materialize_to_sqlite( + store, rollout_id, &path, + ) + .await?; + } } LineageResolutionMode::PlainForReference if bounds.parent.is_none() => { // A newly shared standalone source must remain readable by older binaries. diff --git a/codex-rs/thread-store/src/local/rollout_migration.rs b/codex-rs/thread-store/src/local/rollout_migration.rs index da9243e35b..9c4c847cdf 100644 --- a/codex-rs/thread-store/src/local/rollout_migration.rs +++ b/codex-rs/thread-store/src/local/rollout_migration.rs @@ -1233,6 +1233,7 @@ impl LocalThreadStore { thread_history::apply_projection( self, thread_id, + /*rollout_path*/ None, batch_start, offset, /*initial_ordinal*/ 0, @@ -1247,6 +1248,7 @@ impl LocalThreadStore { thread_history::apply_projection( self, thread_id, + /*rollout_path*/ None, batch_start, offset, /*initial_ordinal*/ 0, diff --git a/codex-rs/thread-store/src/local/thread_history.rs b/codex-rs/thread-store/src/local/thread_history.rs index 5d4884be58..2c7ea701bf 100644 --- a/codex-rs/thread-store/src/local/thread_history.rs +++ b/codex-rs/thread-store/src/local/thread_history.rs @@ -1,3 +1,5 @@ +use std::path::Path; + use codex_app_server_protocol::ThreadHistoryChangeSet; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::TurnStatus; @@ -111,6 +113,7 @@ WHERE thread_id = ? pub(super) async fn apply_projection( store: &LocalThreadStore, thread_id: ThreadId, + rollout_path: Option<&Path>, start_offset: u64, next_offset: u64, initial_ordinal: u64, @@ -126,7 +129,7 @@ pub(super) async fn apply_projection( .await .map_err(thread_history_error)?; let mut transaction = pool.begin_immediate().await.map_err(thread_history_error)?; - let thread_id = thread_id.to_string(); + let thread_id_string = thread_id.to_string(); let projection_state = sqlx::query_as::<_, (i64, i64)>( r#" SELECT next_rollout_byte_offset, next_rollout_ordinal @@ -134,22 +137,44 @@ FROM thread_history_projection_state WHERE thread_id = ? "#, ) - .bind(thread_id.as_str()) + .bind(thread_id_string.as_str()) .fetch_optional(&mut *transaction) .await .map_err(thread_history_error)?; - let (expected_offset, mut next_ordinal) = + // Deletion removes the rollout before clearing this checkpoint. Once the checkpoint + // is gone, a batch already read from the deleted file must not recreate history. + if projection_state.is_none() + && let Some(rollout_path) = rollout_path + && codex_rollout::existing_rollout_path(rollout_path) + .await + .is_none() + { + return Err(ThreadStoreError::ThreadNotFound { thread_id }); + } + let thread_id = thread_id_string; + let (expected_offset, committed_ordinal) = projection_state.unwrap_or((0, sqlite_integer(initial_ordinal, "rollout ordinal")?)); let start_offset = sqlite_integer(start_offset, "rollout byte offset")?; - if expected_offset != start_offset { + let next_offset = sqlite_integer(next_offset, "rollout byte offset")?; + if expected_offset < start_offset { return Err(ThreadStoreError::Internal { message: format!("thread history projection for {thread_id} is behind durable rollout"), }); } + let replaying = expected_offset > start_offset; + if replaying && expected_offset >= next_offset { + return transaction.rollback().await.map_err(thread_history_error); + } + + let mut next_ordinal = committed_ordinal; for projection in projections { match projection { RolloutProjectionStep::Line(projection) => { + let line_end = sqlite_integer(projection.end_byte_offset, "rollout byte offset")?; + if replaying && line_end <= expected_offset { + continue; + } let ordinal = sqlite_integer(projection.ordinal, "rollout ordinal")?; if ordinal != next_ordinal { return Err(ThreadStoreError::Internal { @@ -163,7 +188,7 @@ WHERE thread_id = ? thread_id.as_str(), ordinal, sqlite_integer(projection.start_byte_offset, "rollout byte offset")?, - sqlite_integer(projection.end_byte_offset, "rollout byte offset")?, + line_end, projection.fallback_created_at_ms, projection.changes, ) @@ -209,6 +234,12 @@ ON CONFLICT(thread_id, item_id) DO NOTHING end_ordinal_exclusive, } => { let start_ordinal = sqlite_integer(start_ordinal, "rollout ordinal")?; + let end_ordinal_exclusive = + sqlite_integer(end_ordinal_exclusive, "rollout ordinal")?; + // skip ranges that the checkpoint already covers + if replaying && end_ordinal_exclusive <= committed_ordinal { + continue; + } if start_ordinal != next_ordinal { return Err(ThreadStoreError::Internal { message: format!( @@ -216,8 +247,6 @@ ON CONFLICT(thread_id, item_id) DO NOTHING ), }); } - let end_ordinal_exclusive = - sqlite_integer(end_ordinal_exclusive, "rollout ordinal")?; if end_ordinal_exclusive <= start_ordinal { return Err(ThreadStoreError::Internal { message: format!( @@ -243,7 +272,7 @@ ON CONFLICT(thread_id) DO UPDATE SET "#, ) .bind(thread_id.as_str()) - .bind(sqlite_integer(next_offset, "rollout byte offset")?) + .bind(next_offset) .bind(next_ordinal) .execute(&mut *transaction) .await @@ -251,19 +280,26 @@ ON CONFLICT(thread_id) DO UPDATE SET transaction.commit().await.map_err(thread_history_error) } -pub(super) async fn delete_thread( +pub(super) async fn history_db_for_delete( store: &LocalThreadStore, - thread_id: ThreadId, -) -> ThreadStoreResult<()> { +) -> ThreadStoreResult> { let db_path = store.config.sqlite.thread_history_db_path(); if !tokio::fs::try_exists(db_path.as_path()) .await .map_err(thread_history_delete_error)? { - return Ok(()); + return Ok(None); } + store.thread_history_db().await.map(Some) +} - let pool = store.thread_history_db().await?; +pub(super) async fn delete_thread( + store: &LocalThreadStore, + thread_id: ThreadId, +) -> ThreadStoreResult<()> { + let Some(pool) = history_db_for_delete(store).await? else { + return Ok(()); + }; let _writer = store .thread_history_writer .acquire() diff --git a/codex-rs/thread-store/src/local/thread_history_materialization_pipeline.rs b/codex-rs/thread-store/src/local/thread_history_materialization_pipeline.rs index a1be656681..97574b2727 100644 --- a/codex-rs/thread-store/src/local/thread_history_materialization_pipeline.rs +++ b/codex-rs/thread-store/src/local/thread_history_materialization_pipeline.rs @@ -1,5 +1,7 @@ //! Pipes bounded rollout batches into short SQLite transactions, committing each checkpoint. +use std::path::Path; + use codex_protocol::ThreadId; use super::super::LocalThreadStore; @@ -34,6 +36,7 @@ pub(super) async fn read_and_apply( // source bytes and step count; an oversized individual record remains indivisible. let (sender, receiver) = tokio::sync::mpsc::channel(QUEUED_BATCHES); let (stop, keep_running) = tokio::sync::oneshot::channel::<()>(); + let rollout_path = rollout.path.clone(); let span = tracing::Span::current(); let worker = tokio::task::spawn_blocking(move || { let _entered = span.enter(); @@ -61,7 +64,15 @@ pub(super) async fn read_and_apply( }; let _ = sender.blocking_send(completion); }); - let result = apply_batches(store, thread_id, start_offset, initial_ordinal, receiver).await; + let result = apply_batches( + store, + thread_id, + &rollout_path, + start_offset, + initial_ordinal, + receiver, + ) + .await; // apply_batches drops the receiver on error, unblocking any pending producer send. drop(keep_running); worker.await.map_err(|err| ThreadStoreError::Internal { @@ -73,6 +84,7 @@ pub(super) async fn read_and_apply( pub(super) async fn apply_batches( store: &LocalThreadStore, thread_id: ThreadId, + rollout_path: &Path, mut start_offset: u64, initial_ordinal: u64, mut receiver: tokio::sync::mpsc::Receiver, @@ -87,6 +99,7 @@ pub(super) async fn apply_batches( apply_projection( store, thread_id, + Some(rollout_path), start_offset, next_offset, initial_ordinal, diff --git a/codex-rs/thread-store/src/local/thread_history_materialization_tests.rs b/codex-rs/thread-store/src/local/thread_history_materialization_tests.rs index 7a18b45b8d..4f08b46a24 100644 --- a/codex-rs/thread-store/src/local/thread_history_materialization_tests.rs +++ b/codex-rs/thread-store/src/local/thread_history_materialization_tests.rs @@ -2624,10 +2624,12 @@ async fn paused_projection_releases_writer_and_retains_progress_when_stopped() { ) .expect("read batch"); let consumer_store = Arc::clone(&store); + let consumer_path = rollout_path.clone(); let consumer = tokio::spawn(async move { super::pipeline::apply_batches( &consumer_store, thread_id, + consumer_path.as_path(), before.0 as u64, /*initial_ordinal*/ 0, receiver,