Classify SQLite corruption using typed error codes (#49710)

## What changed

Preserve the underlying error in `LocalStateDbStartupError` and use its error chain to decide whether CLI startup failures qualify for automatic database backup and recovery.

Replace corruption checks against error-message text with SQLite result-code classification, including SQLx extended result codes and directly wrapped `SqliteError` values.

## Testing

Update the embedded startup corruption test to verify that the startup error retains a detectable SQLite corruption cause and the failed database path.

GitOrigin-RevId: 6e8ecd0ee67f3c239183ddea3fc75c4e4cd5744a
This commit is contained in:
Dmitriy Kovalenko
2026-09-30 19:00:00 +00:00
committed by copyberry
parent 4f699cd642
commit 596ae94fb0
7 changed files with 35 additions and 51 deletions
+3 -7
View File
@@ -17,12 +17,8 @@ pub(crate) fn is_locked(detail: &str) -> bool {
codex_state::sqlite_error_detail_is_lock(detail)
}
pub(crate) fn is_corruption(detail: &str) -> bool {
codex_state::sqlite_error_detail_is_corruption(detail)
}
pub(crate) fn is_auto_backup_recoverable(startup_error: &LocalStateDbStartupError) -> bool {
is_corruption(startup_error.detail()) || sqlite_home_is_blocking_file(startup_error)
startup_error.is_corruption() || sqlite_home_is_blocking_file(startup_error)
}
fn sqlite_home_is_blocking_file(startup_error: &LocalStateDbStartupError) -> bool {
@@ -111,7 +107,7 @@ mod tests {
tokio::fs::write(failed_db_path.as_path(), b"logs").await?;
let startup_error =
LocalStateDbStartupError::new(failed_db_path.clone(), "corrupt".to_string());
LocalStateDbStartupError::new(failed_db_path.clone(), anyhow::anyhow!("corrupt"));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(
@@ -134,7 +130,7 @@ mod tests {
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
let sqlite = codex_state::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let startup_error =
LocalStateDbStartupError::new(sqlite.state_db_path(), "File exists".to_string());
LocalStateDbStartupError::new(sqlite.state_db_path(), anyhow::anyhow!("File exists"));
assert!(is_auto_backup_recoverable(&startup_error));
let backups = backup_files_for_fresh_start(&startup_error).await?;
-1
View File
@@ -91,7 +91,6 @@ pub use runtime::is_sqlite_corruption_error;
pub use runtime::open_thread_history_db;
pub use runtime::recovery::RuntimeDbBackup;
pub use runtime::runtime_db_path_for_corruption_error;
pub use runtime::sqlite_error_detail_is_corruption;
pub use runtime::sqlite_error_detail_is_lock;
pub use runtime::sqlite_integrity_check;
pub use sqlite::RuntimeDbPath;
-1
View File
@@ -74,7 +74,6 @@ pub use recovery::backup_runtime_db_for_fresh_start;
pub use recovery::collect_runtime_db_backups;
pub use recovery::is_sqlite_corruption_error;
pub use recovery::runtime_db_path_for_corruption_error;
pub use recovery::sqlite_error_detail_is_corruption;
pub use recovery::sqlite_error_detail_is_lock;
pub use remote_control::RemoteControlEnrollmentRecord;
pub use threads::ThreadFilterOptions;
+20 -29
View File
@@ -7,7 +7,7 @@
//! task-local scope to notify users after recovery; backup behavior is unchanged
//! outside that scope.
use std::borrow::Cow;
use sqlx::error::DatabaseError;
use std::cell::RefCell;
use std::future::Future;
use std::path::Path;
@@ -139,37 +139,28 @@ fn sqlite_error_source_is_corruption(source: &(dyn std::error::Error + 'static))
);
}
let Some(err) = source.downcast_ref::<sqlx::Error>() else {
let sqlite_error = source
.downcast_ref::<sqlx::sqlite::SqliteError>()
.or_else(|| {
source
.downcast_ref::<sqlx::Error>()?
.as_database_error()?
.try_downcast_ref::<sqlx::sqlite::SqliteError>()
});
let Some(err) = sqlite_error else {
return false;
};
let sqlx::Error::Database(database_error) = err else {
return false;
};
sqlite_error_detail_is_corruption(database_error.message())
|| database_error
.code()
.is_some_and(sqlite_database_code_is_corruption)
}
fn sqlite_database_code_is_corruption(code: Cow<'_, str>) -> bool {
matches!(
code.as_ref().to_ascii_lowercase().as_str(),
"11" | "26" | "sqlite_corrupt" | "sqlite_notadb"
)
}
pub fn sqlite_error_detail_is_corruption(detail: &str) -> bool {
let detail = detail.to_ascii_lowercase();
detail.contains("database disk image is malformed")
|| detail.contains("database schema is malformed")
|| detail.contains("database is corrupt")
|| detail.contains("file is not a database")
|| detail.contains("sqlite_corrupt")
|| detail.contains("sqlite_notadb")
|| detail.contains("(code: 11)")
|| detail.contains("(code: 26)")
// SQLx exposes SQLite's extended result code as a decimal string.
err.code()
.and_then(|code| code.parse::<i32>().ok())
.is_some_and(|code| {
matches!(
libsqlite3_sys::Error::new(code).code,
libsqlite3_sys::ErrorCode::DatabaseCorrupt
| libsqlite3_sys::ErrorCode::NotADatabase
)
})
}
pub fn sqlite_error_detail_is_lock(detail: &str) -> bool {
+1 -6
View File
@@ -72,12 +72,7 @@ async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
}
#[test]
fn sqlite_error_detail_classifies_corruption_and_lock_errors() {
assert!(sqlite_error_detail_is_corruption("file is not a database"));
assert!(sqlite_error_detail_is_corruption(
"error returned from database: (code: 11) database disk image is malformed"
));
assert!(!sqlite_error_detail_is_corruption("database is locked"));
fn sqlite_error_detail_classifies_lock_errors() {
assert!(sqlite_error_detail_is_lock("database is locked"));
assert!(sqlite_error_detail_is_lock("database is busy"));
}
+2 -5
View File
@@ -388,10 +388,7 @@ async fn init_state_db_for_app_server_target(
AppServerTarget::Embedded => state_db::try_init(config).await.map(Some).map_err(|err| {
let database_path = codex_state::runtime_db_path_for_corruption_error(&err)
.unwrap_or_else(|| config.sqlite_config().state_db_path());
std::io::Error::other(LocalStateDbStartupError::new(
database_path,
format!("{err:#}"),
))
std::io::Error::other(LocalStateDbStartupError::new(database_path, err))
}),
AppServerTarget::LocalDaemon { .. } | AppServerTarget::Remote { .. } => {
Ok(state_db::get_state_db(config).await)
@@ -3893,7 +3890,7 @@ requires_openai_auth = {requires_openai_auth}
assert_eq!(startup_error.database_path(), logs_db_path.as_path());
assert!(
codex_state::sqlite_error_detail_is_corruption(startup_error.detail()),
startup_error.is_corruption(),
"startup error should preserve the SQLite corruption cause, got: {}",
startup_error.detail()
);
+9 -2
View File
@@ -9,16 +9,23 @@ use std::path::PathBuf;
pub struct LocalStateDbStartupError {
database_path: PathBuf,
detail: String,
#[source]
source: anyhow::Error,
}
impl LocalStateDbStartupError {
pub fn new(database_path: PathBuf, detail: String) -> Self {
pub fn new(database_path: PathBuf, source: anyhow::Error) -> Self {
Self {
database_path,
detail,
detail: format!("{source:#}"),
source,
}
}
pub fn is_corruption(&self) -> bool {
codex_state::is_sqlite_corruption_error(&self.source)
}
pub fn database_path(&self) -> &Path {
self.database_path.as_path()
}