mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Add managed enforcement of DELETE journaling on NFS (#57225)
## Why Existing databases retain their journal mode, so selecting `DELETE` for new NFS databases leaves existing WAL databases unchanged. ## What changed - Add the managed `unsafe_enforce_sqlite_journal_mode` requirement to migrate existing NFS databases before opening writable pools and require `DELETE` on each connection. - Share migration code between startup and `codex migrate-nfs-db`, preserving WAL backups and resuming interrupted replacements, including lazily opened databases. - Hold the migration lock through pool initialization and keep migration failures out of automatic corruption recovery. - Preserve local logs behavior and skip legacy NFS logs cleanup when enforcement is enabled. ## Testing Add coverage for requirement precedence, database settings, data and backup preservation across restarts, interrupted replacement recovery, refusal of active WAL databases, migration lock waiting, and local logs remaining in WAL mode. GitOrigin-RevId: da41ec1b58b1ee8092591cdf8b358280928ff9d4
This commit is contained in:
committed by
copyberry
parent
964aeda627
commit
480ab2d006
+46
-102
@@ -1,6 +1,6 @@
|
||||
//! Shared SQLite connection configuration.
|
||||
//! New databases use DELETE on NFS and WAL elsewhere.
|
||||
//! Writable pools preserve the journal and vacuum modes of initialized databases.
|
||||
//! Writable pools preserve existing settings unless managed policy requires DELETE on NFS.
|
||||
//! Startup retries SQLITE_BUSY and reports other errors to callers.
|
||||
//! The configured logs directory is created and locked only when opening its database.
|
||||
|
||||
@@ -32,11 +32,15 @@ use std::time::Instant;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
mod busy_retry;
|
||||
mod connection;
|
||||
mod nfs;
|
||||
mod validation;
|
||||
|
||||
pub use busy_retry::SqlitePoolWriteExt;
|
||||
pub(crate) use busy_retry::SqliteWriteQueryExt;
|
||||
pub(crate) use busy_retry::retry_on_busy;
|
||||
use connection::JournalModePolicy;
|
||||
use connection::connect_once;
|
||||
use validation::SqliteQuickCheckManager;
|
||||
|
||||
const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
@@ -171,6 +175,7 @@ pub struct SqliteConfig {
|
||||
local_logs_dir: Option<LocalLogsDir>,
|
||||
is_nfs: Arc<OnceCell<bool>>,
|
||||
logs_is_nfs: Arc<OnceCell<bool>>,
|
||||
enforce_delete_on_nfs: bool,
|
||||
quick_check_manager: SqliteQuickCheckManager,
|
||||
}
|
||||
|
||||
@@ -179,6 +184,7 @@ pub struct SqliteConfig {
|
||||
impl PartialEq for SqliteConfig {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.sqlite_home == other.sqlite_home
|
||||
&& self.enforce_delete_on_nfs == other.enforce_delete_on_nfs
|
||||
&& self.local_logs_dir.as_ref().map(LocalLogsDir::path)
|
||||
== other.local_logs_dir.as_ref().map(LocalLogsDir::path)
|
||||
}
|
||||
@@ -187,18 +193,42 @@ impl PartialEq for SqliteConfig {
|
||||
impl Eq for SqliteConfig {}
|
||||
|
||||
impl SqliteConfig {
|
||||
#[deprecated(
|
||||
note = "Use SqliteConfig::from_sqlite_home_with_nfs_enforcement with the managed unsafe_enforce_sqlite_journal_mode requirement, or SqliteConfig::new_for_testing in tests"
|
||||
)]
|
||||
pub fn from_sqlite_home(sqlite_home: AbsolutePathBuf) -> Self {
|
||||
Self::from_sqlite_home_with_nfs_enforcement(
|
||||
sqlite_home,
|
||||
/*enforce_delete_on_nfs*/ false,
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct the configuration with the resolved `unsafe_enforce_sqlite_journal_mode` requirement.
|
||||
pub fn from_sqlite_home_with_nfs_enforcement(
|
||||
sqlite_home: AbsolutePathBuf,
|
||||
enforce_delete_on_nfs: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
sqlite_home,
|
||||
local_logs_dir: None,
|
||||
is_nfs: Arc::new(OnceCell::new()),
|
||||
logs_is_nfs: Arc::new(OnceCell::new()),
|
||||
enforce_delete_on_nfs,
|
||||
quick_check_manager: SqliteQuickCheckManager::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// When enforcement is enabled, migrate existing WAL databases on NFS before opening them.
|
||||
pub fn enable_delete_mode_on_nfs(mut self, enabled: bool) -> Self {
|
||||
self.enforce_delete_on_nfs = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn new_for_testing(sqlite_home: AbsolutePathBuf) -> Self {
|
||||
Self::from_sqlite_home(sqlite_home)
|
||||
Self::from_sqlite_home_with_nfs_enforcement(
|
||||
sqlite_home,
|
||||
/*enforce_delete_on_nfs*/ false,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn home(&self) -> &Path {
|
||||
@@ -428,7 +458,16 @@ impl SqliteConfig {
|
||||
} else {
|
||||
probe_nfs(directory, &OnceCell::new()).await?
|
||||
};
|
||||
let journal_mode_policy = if is_nfs {
|
||||
// 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 {
|
||||
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
|
||||
@@ -506,6 +545,7 @@ impl SqliteConfig {
|
||||
}
|
||||
|
||||
/// Open old logs for cleanup without creating, migrating, or rebuilding the database.
|
||||
/// Skip legacy NFS logs when managed DELETE enforcement is active.
|
||||
pub(crate) async fn open_legacy_logs_for_cleanup(&self) -> anyhow::Result<Option<SqlitePool>> {
|
||||
let Some(path) = self.legacy_logs_db_path() else {
|
||||
return Ok(None);
|
||||
@@ -513,6 +553,9 @@ impl SqliteConfig {
|
||||
if !tokio::fs::try_exists(&path).await? {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.enforce_delete_on_nfs && self.is_nfs().await? {
|
||||
return Ok(None);
|
||||
}
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(false)
|
||||
@@ -539,105 +582,6 @@ impl SqliteConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum JournalModePolicy {
|
||||
InitializeWal,
|
||||
InitializeDelete,
|
||||
}
|
||||
|
||||
async fn connect_once(
|
||||
options: &SqliteConnectOptions,
|
||||
journal_mode_policy: JournalModePolicy,
|
||||
) -> Result<SqlitePool, Error> {
|
||||
// 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 == "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,
|
||||
}?;
|
||||
// Database settings persist on disk.
|
||||
// Initialize these settings once before callers can use the pool.
|
||||
// Connections that open later need only settings that apply to each connection.
|
||||
let initialized: Result<(), Error> = async {
|
||||
let mut connection = pool.acquire().await?;
|
||||
// Auto-vacuum alone can write a header to disk.
|
||||
// If creation stops before the schema exists, startup must initialize the file.
|
||||
let empty =
|
||||
sqlx::query_scalar::<_, bool>("SELECT NOT EXISTS (SELECT 1 FROM sqlite_schema)")
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
if empty {
|
||||
let mode: i64 = sqlx::query_scalar("PRAGMA auto_vacuum")
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
if mode == 0 {
|
||||
sqlx::query("PRAGMA auto_vacuum = INCREMENTAL")
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
}
|
||||
let pragma = match journal_mode_policy {
|
||||
JournalModePolicy::InitializeWal => "PRAGMA journal_mode = WAL",
|
||||
JournalModePolicy::InitializeDelete => "PRAGMA journal_mode = DELETE",
|
||||
};
|
||||
sqlx::query(pragma).execute(&mut *connection).await?;
|
||||
}
|
||||
// Initialization or another process can change the journal mode after after_connect.
|
||||
// Match this connection's synchronization setting to the resulting journal mode.
|
||||
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
if journal == "wal" {
|
||||
sqlx::query("PRAGMA synchronous = NORMAL")
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
} else if journal == "delete" {
|
||||
sqlx::query("PRAGMA synchronous = EXTRA")
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
}
|
||||
// Wait for the connection to return to the pool before startup requests it again.
|
||||
// An asynchronous drop can otherwise cause the pool to open a second connection.
|
||||
connection.return_to_pool().await;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = initialized {
|
||||
pool.close().await;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
async fn probe_nfs(home: &Path, probe: &OnceCell<bool>) -> anyhow::Result<bool> {
|
||||
probe
|
||||
.get_or_try_init(|| async {
|
||||
|
||||
Reference in New Issue
Block a user