diff --git a/codex-rs/state/src/migrations.rs b/codex-rs/state/src/migrations.rs index 33eed1bb96..7098a2702f 100644 --- a/codex-rs/state/src/migrations.rs +++ b/codex-rs/state/src/migrations.rs @@ -1,8 +1,13 @@ -use std::borrow::Cow; +use std::collections::HashMap; -use crate::sqlite::SqliteWriteQueryExt; +use crate::telemetry::DbKind; +use sqlx::AssertSqlSafe; +use sqlx::SqlSafeStr; +use sqlx::migrate::Migrate; +use sqlx::migrate::MigrateError; +use sqlx::migrate::Migration; use sqlx::migrate::Migrator; -use sqlx_sqlite::SqlitePool; +use sqlx_sqlite::SqliteConnection; pub(crate) static STATE_MIGRATOR: Migrator = sqlx_macros::migrate!("./migrations"); pub(crate) static LOGS_MIGRATOR: Migrator = sqlx_macros::migrate!("./logs_migrations"); @@ -18,9 +23,9 @@ pub(crate) static THREAD_HISTORY_MIGRATOR: Migrator = /// We intentionally ignore applied migration versions that are newer than the /// embedded migration set. Known migration versions are still validated by /// checksum, so this only relaxes the "database is ahead of me" case. -fn runtime_migrator(base: &'static Migrator) -> Migrator { +fn runtime_migrator(base: &Migrator) -> Migrator { Migrator { - migrations: Cow::Borrowed(base.migrations.as_ref()), + migrations: base.migrations.clone(), ignore_missing: true, locking: base.locking, no_tx: base.no_tx, @@ -55,67 +60,82 @@ pub(crate) fn runtime_thread_history_migrator() -> Migrator { runtime_migrator(&THREAD_HISTORY_MIGRATOR) } -pub(crate) async fn repair_legacy_recency_migration_version( - pool: &SqlitePool, +/// Run inside the caller's migration transaction. Only mismatched histories +/// need a second pass, with checksums selected for this database snapshot. +pub(crate) async fn run_migrations( + conn: &mut SqliteConnection, migrator: &Migrator, -) -> anyhow::Result<()> { - let Some(recency_migration) = migrator - .migrations - .iter() - .find(|migration| migration.version == 39) - else { - return Ok(()); + kind: DbKind, +) -> Result<(), MigrateError> { + match migrator + .run_direct(/*target*/ None, conn, /*skip*/ false) + .await + { + Err(MigrateError::VersionMismatch(_)) => {} + result => return result, + } + + let mut applied: HashMap<_, _> = conn + .list_applied_migrations(&migrator.table_name) + .await? + .into_iter() + .map(|row| (row.version, row.checksum)) + .collect(); + + // Some state databases recorded the recency migration as 38 before it + // moved to 39. Keep its original checksum and let SQLx apply the real 38. + if matches!(kind, DbKind::State) + && !applied.contains_key(&39) + && let Some(recency) = migrator.iter().find(|m| m.version == 39) + && let Some(checksum) = applied.get(&38) + && matches_checksum(recency, checksum) + { + sqlx::query("UPDATE _sqlx_migrations SET version = 39, description = ? WHERE version = 38") + .bind(recency.description.as_ref()) + .execute(&mut *conn) + .await?; + applied.insert(39, checksum.clone()); + applied.remove(&38); + } + + let mut compatible = Migrator { + ignore_missing: migrator.ignore_missing, + ..runtime_migrator(migrator) }; - let migrations_table_exists = sqlx::query_scalar::<_, i64>( - "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '_sqlx_migrations'", - ) - .fetch_optional(pool) - .await? - .is_some(); - if !migrations_table_exists { - return Ok(()); + for migration in compatible.migrations.to_mut() { + if let Some(checksum) = applied.remove(&migration.version) { + if !matches_checksum(migration, &checksum) { + return Err(MigrateError::VersionMismatch(migration.version)); + } + migration.checksum = checksum; + } } + compatible + .run_direct(/*target*/ None, conn, /*skip*/ false) + .await +} - let legacy_recency_needs_repair = sqlx::query_scalar::<_, i64>( - r#" -SELECT 1 -FROM _sqlx_migrations -WHERE version = ? - AND checksum = ? - AND NOT EXISTS ( - SELECT 1 FROM _sqlx_migrations WHERE version = ? - ) - "#, - ) - .bind(38_i64) - .bind(recency_migration.checksum.as_ref()) - .bind(recency_migration.version) - .fetch_optional(pool) - .await? - .is_some(); - if !legacy_recency_needs_repair { - return Ok(()); - } +/// SQLx hashes the raw SQL. Windows and Linux builds have embedded the +/// same migrations with CRLF and LF respectively. +fn matches_checksum(migration: &Migration, checksum: &[u8]) -> bool { + migration.checksum.as_ref() == checksum + || with_opposite_line_endings(migration).checksum.as_ref() == checksum +} - sqlx::query( - r#" -UPDATE _sqlx_migrations -SET version = ?, description = ? -WHERE version = ? - AND checksum = ? - AND NOT EXISTS ( - SELECT 1 FROM _sqlx_migrations WHERE version = ? - ) - "#, +fn with_opposite_line_endings(migration: &Migration) -> Migration { + let sql = migration.sql.as_str(); + let alternate = if sql.contains("\r\n") { + sql.replace("\r\n", "\n") + } else { + sql.replace('\n', "\r\n") + }; + Migration::new( + migration.version, + migration.description.clone(), + migration.migration_type, + AssertSqlSafe(alternate).into_sql_str(), + migration.no_tx, ) - .bind(recency_migration.version) - .bind(recency_migration.description.as_ref()) - .bind(38_i64) - .bind(recency_migration.checksum.as_ref()) - .bind(recency_migration.version) - .execute_with_busy_retry(pool) - .await?; - Ok(()) } #[cfg(test)] diff --git a/codex-rs/state/src/migrations_tests.rs b/codex-rs/state/src/migrations_tests.rs index d8e14b752b..649c826937 100644 --- a/codex-rs/state/src/migrations_tests.rs +++ b/codex-rs/state/src/migrations_tests.rs @@ -2,13 +2,13 @@ use codex_utils_absolute_path::test_support::PathExt; use pretty_assertions::assert_eq; use sqlx::Connection; use sqlx::Row; -use sqlx::migrate::Migration; +use sqlx::migrate::MigrateError; use sqlx::migrate::Migrator; use std::borrow::Cow; use super::STATE_MIGRATOR; use super::THREAD_HISTORY_MIGRATOR; -use super::repair_legacy_recency_migration_version; +use super::with_opposite_line_endings; use crate::PINNED_THREAD_SECTION_ID; use crate::PINNED_THREAD_SECTION_NAME; @@ -918,121 +918,132 @@ INSERT INTO threads ( } #[tokio::test] -async fn repairs_recency_migration_that_was_applied_as_version_38() { - let sqlite_home = crate::runtime::test_support::unique_temp_dir(); - tokio::fs::create_dir_all(&sqlite_home) - .await - .expect("sqlite home should be created"); - let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| { - let _ = std::fs::remove_dir_all(sqlite_home); - }); - let sqlite = crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs()); - let state_path = sqlite.state_db_path(); - let pool = sqlite - .open_read_write_pool(&state_path) - .await - .expect("sqlite database should open"); - migrator_through(/*version*/ 37) - .run(&pool) - .await - .expect("pre-recency migrations should apply"); - - let recency_migration = STATE_MIGRATOR - .migrations +async fn repairs_recency_migration_that_was_applied_as_version_38() -> anyhow::Result<()> { + let recency = STATE_MIGRATOR .iter() .find(|migration| migration.version == 39) .expect("recency migration should exist"); - let mut legacy_migrations = STATE_MIGRATOR - .migrations - .iter() - .filter(|migration| migration.version <= 37) - .cloned() - .collect::>(); - legacy_migrations.push(Migration::new( - 38, - recency_migration.description.clone(), - recency_migration.migration_type, - recency_migration.sql.clone(), - recency_migration.no_tx, - )); - let legacy_recency_migrator = Migrator::with_migrations(legacy_migrations); - legacy_recency_migrator - .run(&pool) - .await - .expect("legacy recency migration should apply as version 38"); + for mut legacy in [recency.clone(), with_opposite_line_endings(recency)] { + let home = tempfile::tempdir()?; + let sqlite = crate::SqliteConfig::new_for_testing(home.path().abs()); + let mut migrations = migrator_through(/*version*/ 37).migrations.into_owned(); + let recency_checksum = legacy.checksum.clone(); + legacy.version = 38; + migrations.push(legacy); + let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?; + Migrator::with_migrations(migrations).run(&pool).await?; + pool.close().await; - repair_legacy_recency_migration_version(&pool, &STATE_MIGRATOR) - .await - .expect("legacy migration history should be repaired"); - STATE_MIGRATOR - .run(&pool) - .await - .expect("current migrations should apply after repair"); - - let applied = sqlx::query( - "SELECT version, checksum FROM _sqlx_migrations WHERE version >= 38 ORDER BY version", - ) - .fetch_all(&pool) - .await - .expect("applied migrations should load") - .into_iter() - .map(|row| { - ( - row.get::("version"), - row.get::, _>("checksum"), + let pool = sqlite + .open_state_db( + &super::runtime_state_migrator(), + /*telemetry_override*/ None, + ) + .await?; + let applied: Vec<(i64, Vec)> = sqlx::query_as( + "SELECT version, checksum FROM _sqlx_migrations WHERE version >= 38 ORDER BY version", ) - }) - .collect::>(); - let expected = STATE_MIGRATOR - .migrations + .fetch_all(&pool) + .await?; + let expected = STATE_MIGRATOR + .iter() + .filter(|migration| migration.version >= 38) + .map(|migration| { + let checksum = if migration.version == 39 { + &recency_checksum + } else { + &migration.checksum + }; + (migration.version, checksum.to_vec()) + }) + .collect::>(); + assert_eq!(applied, expected); + pool.close().await; + } + Ok(()) +} + +#[tokio::test] +async fn opposite_line_endings_survive_upgrade_and_reopen_with_an_active_writer() +-> anyhow::Result<()> { + let home = tempfile::tempdir()?; + let sqlite = crate::SqliteConfig::new_for_testing(home.path().abs()); + let old = Migrator::with_migrations( + migrator_through(/*version*/ 2) + .iter() + .map(with_opposite_line_endings) + .collect(), + ); + let current = super::runtime_state_migrator(); + assert_ne!(old.migrations[0].checksum, current.migrations[0].checksum); + let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?; + old.run(&pool).await?; + pool.close().await; + + let pool = sqlite + .open_state_db(¤t, /*telemetry_override*/ None) + .await?; + let mut connection = pool.acquire().await?; + let writer = connection.begin_with("BEGIN IMMEDIATE").await?; + let reopened = sqlite + .open_state_db(¤t, /*telemetry_override*/ None) + .await?; + let applied: Vec<(i64, Vec)> = + sqlx::query_as("SELECT version, checksum FROM _sqlx_migrations ORDER BY version") + .fetch_all(&reopened) + .await?; + let expected = old .iter() - .filter(|migration| migration.version >= 38) + .chain(current.iter().skip(2)) .map(|migration| (migration.version, migration.checksum.to_vec())) .collect::>(); assert_eq!(applied, expected); + writer.rollback().await?; + drop(connection); + reopened.close().await; pool.close().await; + Ok(()) } #[tokio::test] -async fn repair_recency_migration_succeeds_while_another_connection_holds_writer_slot() { - let sqlite_home = crate::runtime::test_support::unique_temp_dir(); - tokio::fs::create_dir_all(&sqlite_home) +async fn opposite_line_endings_do_not_hide_other_migration_errors() -> anyhow::Result<()> { + let home = tempfile::tempdir()?; + let sqlite = crate::SqliteConfig::new_for_testing(home.path().abs()); + let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?; + let mut old = migrator_through(/*version*/ 2); + let first = &mut old.migrations.to_mut()[0]; + *first = with_opposite_line_endings(first); + old.run(&pool).await?; + // A recognized checksum for one version is invalid for a different version. + sqlx::query("UPDATE _sqlx_migrations SET checksum = ? WHERE version = 2") + .bind(old.migrations[0].checksum.as_ref()) + .execute(&pool) + .await?; + let current = super::runtime_state_migrator(); + let error = sqlite + .open_state_db(¤t, /*telemetry_override*/ None) .await - .expect("sqlite home should be created"); - let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| { - let _ = std::fs::remove_dir_all(sqlite_home); - }); - let sqlite = crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs()); - let state_path = sqlite.state_db_path(); - let pool = sqlite - .open_read_write_pool(&state_path) - .await - .expect("database should open"); - STATE_MIGRATOR - .run(&pool) - .await - .expect("current migrations should apply"); - let read_pool = sqlite - .open_read_only_pool(&state_path, /*busy_timeout*/ None) - .await - .expect("read-only pool should open"); - let mut write_connection = pool.acquire().await.expect("write connection should open"); - let write_transaction = write_connection - .begin_with("BEGIN IMMEDIATE") - .await - .expect("write transaction should acquire the writer slot"); + .unwrap_err(); + assert!(matches!( + error.root_cause().downcast_ref::(), + Some(MigrateError::VersionMismatch(2)) + )); - let repair_result = repair_legacy_recency_migration_version(&read_pool, &STATE_MIGRATOR).await; - - write_transaction - .rollback() + sqlx::query("UPDATE _sqlx_migrations SET checksum = ?, success = 0 WHERE version = 2") + .bind(old.migrations[1].checksum.as_ref()) + .execute(&pool) + .await?; + let error = sqlite + .open_state_db(¤t, /*telemetry_override*/ None) .await - .expect("write transaction should roll back"); - drop(write_connection); - read_pool.close().await; + .unwrap_err(); + assert!(matches!( + error.root_cause().downcast_ref::(), + Some(MigrateError::Dirty(2)) + )); pool.close().await; - repair_result.expect("current migration history should not need the writer slot"); + Ok(()) } #[tokio::test] diff --git a/codex-rs/state/src/sqlite.rs b/codex-rs/state/src/sqlite.rs index e968981702..ec78a94af9 100644 --- a/codex-rs/state/src/sqlite.rs +++ b/codex-rs/state/src/sqlite.rs @@ -11,7 +11,7 @@ )] use crate::DbTelemetry; -use crate::migrations::repair_legacy_recency_migration_version; +use crate::migrations::run_migrations; use crate::runtime::recovery::RuntimeDbInitError; use crate::telemetry; use crate::telemetry::DbKind; @@ -427,26 +427,17 @@ impl SqliteConfig { RuntimeDbInitError::new(spec.label, "open", path.as_path(), source) })?; let started = Instant::now(); - let migrate_result = async { - if matches!(spec.kind, DbKind::State) { - repair_legacy_recency_migration_version(&pool, migrator).await?; + // SQLx's SQLite migration lock is a no-op. Keep version checks and changes in + // one transaction, retrying from a fresh snapshot after a concurrent migration. + // A current schema needs only a read lock, including when opened on NFS. + let migrate_result = retry_on_busy(|| async { + let mut transaction = pool.begin().await?; + if let Err(error) = run_migrations(&mut transaction, migrator, spec.kind).await { + transaction.rollback().await?; + return Err(error.into()); } - // SQLx's SQLite migration lock is a no-op. Keep version checks and changes in - // one transaction, retrying from a fresh snapshot after a concurrent migration. - // A current schema needs only a read lock, including when opened on NFS. - retry_on_busy(|| async { - let mut transaction = pool.begin().await?; - if let Err(error) = migrator - .run_direct(/*target*/ None, &mut *transaction, /*skip*/ false) - .await - { - transaction.rollback().await?; - return Err(error.into()); - } - transaction.commit().await.map_err(anyhow::Error::from) - }) - .await - } + transaction.commit().await.map_err(anyhow::Error::from) + }) .await; telemetry::record_init_result( telemetry_override,