Defer paginated thread history updates on NFS (#63456)

## Why

Live rollout writes also update SQLite, so lock contention in rollback
journal mode can delay recording thread activity.

## What changed

For local threads with paginated history on NFS, defer SQLite updates on
the live write path and materialize rollout history when serving history
pages. For pools configured to prefer rollback journaling, cap the pool
at two connections and allow 60 seconds for SQLite locks and 120 seconds
to acquire a connection.

Skip work already committed by another history reader. Remove rollout
files before clearing their history checkpoints and reject stale batches
that would recreate deleted history.

## Testing

Extend the thread deletion test to verify that applying a stale batch
after deletion returns `ThreadNotFound`. Check SQLite settings on every
connection using the configured pool size.

GitOrigin-RevId: e2a3c19bc8fec0a97075d468767929ce396b65e3
This commit is contained in:
Dmitriy Kovalenko
2026-11-23 22:14:21 +00:00
committed by copyberry
parent c028016428
commit 45bdafbda0
11 changed files with 207 additions and 69 deletions
+27
View File
@@ -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::<LocalThreadStore>()
{
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()
@@ -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
@@ -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.
@@ -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.
@@ -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,
@@ -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<Option<&sqlx::SqlitePool>> {
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()
@@ -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<ProjectionMessage>,
@@ -87,6 +99,7 @@ pub(super) async fn apply_batches(
apply_projection(
store,
thread_id,
Some(rollout_path),
start_offset,
next_offset,
initial_ordinal,
@@ -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,