Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Classify SQLite corruption using typed error codes (#49710)

Dmitriy Kovalenko596ae94fb00f
diff --git a/codex-rs/cli/src/state_db_recovery.rs b/codex-rs/cli/src/state_db_recovery.rs
index 34acbb5104..5549f429da 100644
--- a/codex-rs/cli/src/state_db_recovery.rs
+++ b/codex-rs/cli/src/state_db_recovery.rs
@@ -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?;
diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs
index 5dbf2a80ec..232b6f766c 100644
--- a/codex-rs/state/src/lib.rs
+++ b/codex-rs/state/src/lib.rs
@@ -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;
diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs
index 2178378082..a145dfc451 100644
--- a/codex-rs/state/src/runtime.rs
+++ b/codex-rs/state/src/runtime.rs
@@ -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;
diff --git a/codex-rs/state/src/runtime/recovery.rs b/codex-rs/state/src/runtime/recovery.rs
index 72b47a0253..da81fc81a5 100644
--- a/codex-rs/state/src/runtime/recovery.rs
+++ b/codex-rs/state/src/runtime/recovery.rs
@@ -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 {
diff --git a/codex-rs/state/src/runtime/recovery_tests.rs b/codex-rs/state/src/runtime/recovery_tests.rs
index 6caca58d85..0e7acccdfa 100644
--- a/codex-rs/state/src/runtime/recovery_tests.rs
+++ b/codex-rs/state/src/runtime/recovery_tests.rs
@@ -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"));
}
diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs
index b72a33c776..5397fcea43 100644
--- a/codex-rs/tui/src/lib.rs
+++ b/codex-rs/tui/src/lib.rs
@@ -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()
);
diff --git a/codex-rs/tui/src/startup_error.rs b/codex-rs/tui/src/startup_error.rs
index 585cec4b23..3cbbcb4992 100644
--- a/codex-rs/tui/src/startup_error.rs
+++ b/codex-rs/tui/src/startup_error.rs
@@ -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()
}