Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

fix(state): track schema version and stop discarding migration errors

FABIOTESS5795e9959f94
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8e25d7e..59decc81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,36 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
+### Fixed
+- **SQLite migrations discarded every error and tracked no schema version.**
+ `StateDb::open` upgraded old databases with two `let _ = conn.execute_batch(...)`
+ calls. Discarding the result swallowed the expected "duplicate column name" on
+ an already-upgraded database, but it swallowed a locked file, an I/O error and
+ a partially-applied batch with it, and `open` returned `Ok` regardless.
+
+ `PRAGMA user_version` now records the schema version, and each migration
+ applies inside a transaction that commits the DDL and the version bump
+ together. Columns are checked individually with `PRAGMA table_info` before
+ being added, so only the genuine already-exists case is tolerated and every
+ other error propagates.
+
+ Per-column checking also heals the state the old code could produce and not
+ detect. `execute_batch` stops at its first error, so a database whose first
+ `ALTER` committed and whose second did not was left with `webhook_url` and no
+ `webhook_headers` — and re-running the pair would fail on the column that was
+ already there, permanently. Verified against real rusqlite semantics, not
+ assumed: the old idiom leaves the column missing and still returns `Ok`.
+
+ Databases predating the tracker all report `user_version = 0` whether they
+ carry the columns or not, which is why the version alone cannot decide what to
+ do and the column probe is the thing that establishes truth.
+
+ `tests/state_migration_test.rs` covers this against hand-built binary fixtures
+ in `tests/fixtures/state/`: a pre-migration database, and a half-applied one.
+ The fixtures are committed rather than generated, because a fixture built by
+ the code under test would agree with a broken migration by construction.
+ Reported in #75.
+
### Added
- **Versioned SQL type → XSD datatype contract.** `docs/data-pipeline.md` now
documents what `SchemaIntrospector::sql_to_xsd` produces for every SQL type it
diff --git a/src/state.rs b/src/state.rs
index 4aa05167..66f27f00 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -133,6 +133,123 @@ CREATE TABLE IF NOT EXISTS ontology_cache (
);
";
+/// A column an upgrade adds to an existing table.
+///
+/// `CREATE TABLE IF NOT EXISTS` in [`SCHEMA`] already declares every column, so
+/// a database created today needs none of these. They exist only for databases
+/// created before the column was introduced.
+struct ColumnAddition {
+ table: &'static str,
+ column: &'static str,
+ ddl: &'static str,
+}
+
+/// One schema upgrade step. Applied inside a single transaction, after which
+/// `PRAGMA user_version` is set to `version`.
+struct Migration {
+ version: i64,
+ description: &'static str,
+ columns: &'static [ColumnAddition],
+}
+
+/// Ordered schema migrations. Append only, never renumber: the version is
+/// recorded in every `open-ontologies.db` in the field.
+const MIGRATIONS: &[Migration] = &[
+ Migration {
+ version: 1,
+ description: "monitor webhook delivery columns",
+ columns: &[
+ ColumnAddition {
+ table: "monitor_watchers",
+ column: "webhook_url",
+ ddl: "ALTER TABLE monitor_watchers ADD COLUMN webhook_url TEXT",
+ },
+ ColumnAddition {
+ table: "monitor_watchers",
+ column: "webhook_headers",
+ ddl: "ALTER TABLE monitor_watchers ADD COLUMN webhook_headers TEXT",
+ },
+ ],
+ },
+ Migration {
+ version: 2,
+ description: "align feedback signal payload",
+ columns: &[ColumnAddition {
+ table: "align_feedback",
+ column: "signals_json",
+ ddl: "ALTER TABLE align_feedback ADD COLUMN signals_json TEXT",
+ }],
+ },
+];
+
+/// Schema version a freshly-opened database is brought up to.
+pub const SCHEMA_VERSION: i64 = 2;
+
+/// Is `column` present on `table`?
+///
+/// This is the `PRAGMA table_info` probe that replaces the old
+/// discard-the-error idiom. Asking whether the column is there lets a genuine
+/// failure (locked file, I/O error, corrupt page) propagate, where
+/// `let _ = execute_batch(...)` swallowed it alongside the expected
+/// "duplicate column name".
+fn column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool> {
+ let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
+ let mut rows = stmt.query([])?;
+ while let Some(row) = rows.next()? {
+ let name: String = row.get(1)?;
+ if name == column {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
+/// Bring the schema up to [`SCHEMA_VERSION`], recording progress in
+/// `PRAGMA user_version`.
+///
+/// Two properties matter here, and the previous implementation had neither.
+///
+/// **Errors propagate.** Only the expected "column already exists" case is
+/// tolerated, and it is handled by asking first rather than by discarding the
+/// result, so everything else surfaces.
+///
+/// **Each column is applied independently, inside a transaction.** Databases
+/// predating the tracker all report `user_version = 0` whether they have the
+/// columns or not, so the version alone cannot decide what to do — and a
+/// database can be *half* migrated, because the old code ran two `ALTER`s in
+/// one batch where the first could commit and the second fail. Checking per
+/// column heals that state instead of tripping over it: the applied column is
+/// skipped, the missing one is added.
+fn run_migrations(conn: &mut Connection) -> Result<()> {
+ let current: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
+ if current >= SCHEMA_VERSION {
+ return Ok(());
+ }
+
+ for migration in MIGRATIONS.iter().filter(|m| m.version > current) {
+ let tx = conn.transaction()?;
+ for col in migration.columns {
+ if !column_exists(&tx, col.table, col.column)? {
+ tx.execute_batch(col.ddl).map_err(|e| {
+ anyhow::anyhow!(
+ "migration {} ({}) failed adding {}.{}: {e}",
+ migration.version,
+ migration.description,
+ col.table,
+ col.column
+ )
+ })?;
+ }
+ }
+ // Inside the same transaction as the DDL: SQLite DDL is transactional,
+ // so the version bump and the columns it describes commit together or
+ // not at all. That is what makes a half-applied state unreachable.
+ tx.pragma_update(None, "user_version", migration.version)?;
+ tx.commit()?;
+ }
+ Ok(())
+}
+
/// Minimal SQLite state store for ontology versioning.
#[derive(Clone)]
pub struct StateDb {
@@ -141,25 +258,23 @@ pub struct StateDb {
impl StateDb {
pub fn open(path: &Path) -> Result<Self> {
- let conn = Connection::open(path)?;
+ let mut conn = Connection::open(path)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.execute_batch(SCHEMA)?;
- // Safe migration: add webhook columns if upgrading from older schema
- let _ = conn.execute_batch(
- "ALTER TABLE monitor_watchers ADD COLUMN webhook_url TEXT;
- ALTER TABLE monitor_watchers ADD COLUMN webhook_headers TEXT;"
- );
- // Safe migration: add signals_json column for feedback-based weight learning
- let _ = conn.execute_batch(
- "ALTER TABLE align_feedback ADD COLUMN signals_json TEXT;"
- );
+ run_migrations(&mut conn)?;
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
}
+ /// Schema version recorded in this database's `PRAGMA user_version`.
+ pub fn schema_version(&self) -> Result<i64> {
+ let conn = self.conn.lock().unwrap();
+ Ok(conn.query_row("PRAGMA user_version", [], |r| r.get(0))?)
+ }
+
pub fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
self.conn.lock().unwrap()
}
diff --git a/tests/fixtures/state/v0-half-migrated.db b/tests/fixtures/state/v0-half-migrated.db
new file mode 100644
index 00000000..30e6271d
Binary files /dev/null and b/tests/fixtures/state/v0-half-migrated.db differ
diff --git a/tests/fixtures/state/v0-pre-migrations.db b/tests/fixtures/state/v0-pre-migrations.db
new file mode 100644
index 00000000..c833f4ba
Binary files /dev/null and b/tests/fixtures/state/v0-pre-migrations.db differ
diff --git a/tests/state_migration_test.rs b/tests/state_migration_test.rs
new file mode 100644
index 00000000..350072c7
--- /dev/null
+++ b/tests/state_migration_test.rs
@@ -0,0 +1,201 @@
+//! Upgrade-in-place tests for the `StateDb` schema.
+//!
+//! These open **checked-in binary fixtures** under `tests/fixtures/state/`, not
+//! databases produced by the code under test. That distinction is the whole
+//! point: a fixture generated from the current schema would agree with a broken
+//! migration by construction, and the bug this guards against is precisely a
+//! migration that silently does not apply.
+//!
+//! They live under `tests/fixtures/` rather than `tests/data/` because
+//! `.gitignore` ignores `data/` repo-wide. A fixture that is not committed is
+//! not a fixture, and the failure would be silent on a fresh clone.
+//!
+//! Each test copies its fixture to a tempdir first. `StateDb::open` sets
+//! `journal_mode = WAL`, which writes to the file, so opening a fixture in place
+//! would mutate the committed artefact.
+
+use std::path::{Path, PathBuf};
+
+use open_ontologies::state::{StateDb, SCHEMA_VERSION};
+use rusqlite::Connection;
+use tempfile::TempDir;
+
+fn fixture(name: &str) -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/state")
+ .join(name)
+}
+
+/// Copy a fixture into a fresh tempdir and return (dir, path). The dir must
+/// stay alive for the lifetime of the database.
+fn staged(name: &str) -> (TempDir, PathBuf) {
+ let dir = TempDir::new().unwrap();
+ let dst = dir.path().join(name);
+ std::fs::copy(fixture(name), &dst)
+ .unwrap_or_else(|e| panic!("fixture {name} missing or unreadable: {e}"));
+ (dir, dst)
+}
+
+fn columns(conn: &Connection, table: &str) -> Vec<String> {
+ let mut stmt = conn
+ .prepare(&format!("PRAGMA table_info({table})"))
+ .unwrap();
+ stmt.query_map([], |r| r.get::<_, String>(1))
+ .unwrap()
+ .map(Result::unwrap)
+ .collect()
+}
+
+/// The baseline case: a database predating both migrations. It reports
+/// `user_version = 0` and has neither column.
+#[test]
+fn upgrades_a_pre_migration_database_and_preserves_rows() {
+ let (_dir, path) = staged("v0-pre-migrations.db");
+
+ // Establish the starting state from the fixture itself, so this test fails
+ // loudly if the fixture is ever regenerated into something else.
+ {
+ let raw = Connection::open(&path).unwrap();
+ let v: i64 = raw.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
+ assert_eq!(v, 0, "fixture should start at user_version 0");
+ let cols = columns(&raw, "monitor_watchers");
+ assert!(!cols.contains(&"webhook_url".to_string()));
+ assert!(!cols.contains(&"webhook_headers".to_string()));
+ assert!(!columns(&raw, "align_feedback").contains(&"signals_json".to_string()));
+ }
+
+ let db = StateDb::open(&path).unwrap();
+ assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION);
+
+ let conn = db.conn();
+ let watchers = columns(&conn, "monitor_watchers");
+ assert!(watchers.contains(&"webhook_url".to_string()));
+ assert!(watchers.contains(&"webhook_headers".to_string()));
+ assert!(columns(&conn, "align_feedback").contains(&"signals_json".to_string()));
+
+ // Pre-existing rows survive, with their values intact and the new column
+ // NULL rather than defaulted over the top of anything.
+ let (id, threshold, message, hook): (String, f64, String, Option<String>) = conn
+ .query_row(
+ "SELECT id, threshold, message, webhook_url FROM monitor_watchers WHERE id = 'w-legacy'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(id, "w-legacy");
+ assert_eq!(threshold, 42.0);
+ assert_eq!(message, "pre-migration watcher");
+ assert_eq!(hook, None);
+
+ let (src, signals): (String, Option<String>) = conn
+ .query_row(
+ "SELECT source_iri, signals_json FROM align_feedback WHERE source_iri = 'http://ex.org/A'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(src, "http://ex.org/A");
+ assert_eq!(signals, None);
+}
+
+/// The sharp case. The old code ran two `ALTER`s in one `execute_batch` and
+/// discarded the result, so the first could commit while the second failed,
+/// leaving a database with `webhook_url` but not `webhook_headers`. Re-running
+/// migration 1 wholesale against that state fails on "duplicate column name",
+/// which is why the check is per column rather than per migration.
+#[test]
+fn heals_a_half_applied_migration() {
+ let (_dir, path) = staged("v0-half-migrated.db");
+
+ {
+ let raw = Connection::open(&path).unwrap();
+ let cols = columns(&raw, "monitor_watchers");
+ assert!(
+ cols.contains(&"webhook_url".to_string()),
+ "fixture should already have webhook_url"
+ );
+ assert!(
+ !cols.contains(&"webhook_headers".to_string()),
+ "fixture should be missing webhook_headers"
+ );
+ }
+
+ let db = StateDb::open(&path).unwrap();
+ assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION);
+
+ let conn = db.conn();
+ let cols = columns(&conn, "monitor_watchers");
+ assert!(cols.contains(&"webhook_url".to_string()));
+ assert!(cols.contains(&"webhook_headers".to_string()));
+
+ // The value already stored in the half-applied column is not clobbered by
+ // the completing migration.
+ let hook: String = conn
+ .query_row(
+ "SELECT webhook_url FROM monitor_watchers WHERE id = 'w-half'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(hook, "https://hooks.example.org/x");
+}
+
+/// A database created today is already at the current version and needs no
+/// upgrade on the next open.
+#[test]
+fn fresh_database_is_stamped_at_current_version() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("fresh.db");
+
+ let db = StateDb::open(&path).unwrap();
+ assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION);
+ drop(db);
+
+ let reopened = StateDb::open(&path).unwrap();
+ assert_eq!(reopened.schema_version().unwrap(), SCHEMA_VERSION);
+}
+
+/// Opening repeatedly is a no-op after the first upgrade, and does not disturb
+/// data written between opens.
+#[test]
+fn reopening_an_upgraded_database_is_idempotent() {
+ let (_dir, path) = staged("v0-pre-migrations.db");
+
+ let db = StateDb::open(&path).unwrap();
+ assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION);
+ db.conn()
+ .execute(
+ "UPDATE monitor_watchers SET webhook_url = ?1 WHERE id = 'w-legacy'",
+ ["https://hooks.example.org/after-upgrade"],
+ )
+ .unwrap();
+ drop(db);
+
+ let again = StateDb::open(&path).unwrap();
+ assert_eq!(again.schema_version().unwrap(), SCHEMA_VERSION);
+ let hook: String = again
+ .conn()
+ .query_row(
+ "SELECT webhook_url FROM monitor_watchers WHERE id = 'w-legacy'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(hook, "https://hooks.example.org/after-upgrade");
+}
+
+/// A real failure must surface rather than be swallowed. The old
+/// `let _ = execute_batch(...)` discarded every error, not just the expected
+/// duplicate-column one; pointing `open` at a file that is not a database is
+/// the cheapest way to assert that errors now propagate.
+#[test]
+fn a_genuine_open_failure_is_an_error_not_a_silent_pass() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("not-a-database.db");
+ std::fs::write(&path, b"this is definitely not a SQLite file").unwrap();
+
+ assert!(
+ StateDb::open(&path).is_err(),
+ "opening a non-database must return Err, not succeed silently"
+ );
+}