mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
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:
committed by
copyberry
parent
c028016428
commit
45bdafbda0
@@ -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<bool> {
|
||||
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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user