From ee72900e361aa197b163143e5d80f525f54067ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 18 Sep 2026 02:14:55 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(tenant):=20the=20boot=20swee?= =?UTF-8?q?ps=20every=20school=20database=20to=20the=20school-schema=20hea?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A school database is migrated exactly twice in its life — at mint (`bring_up`, through the create path and the provisioning finish) and at boot (the template, and now this sweep). Nothing else ever touches its schema: a re-dial applies no migrations, and the boot's reconcile only reaches rows still marked `provisioning`. A school minted before a migration landed therefore kept yesterday's tables for good — which is how the live deployment answered relation "podcast_job" does not exist on POST /podcast/jobs while the template already carried the podcast migration. The missing half of the boot is now there: after the control database and the template are ensured, every school database in the registry is dialled, brought to the school-schema head and closed again. Nothing about a school no request has reached is cached, so no pool for an unserved school survives the sweep. The invariant it restores: **every school database in the control database is at the school-schema head after boot.** - Failure policy: one school failing never takes the boot down. It is logged at ERROR with its id and slug and left exactly as it stood — the sweep writes no registry row and no status, so a failed school is as usable (or unusable) as it was and the next boot retries it; sqlx's tracking table is what makes a retry of a half-applied migration safe. - Observability: one INFO line per boot (`school schema sweep: N schools, M migrated`) plus one line per school, only when it actually applied something — the pending count comes off `_sqlx_migrations` before the migrator runs, so a school already at head costs one connection and no line. - `migrate_school`, not the bare migrator: the chatbot/RAG interrupted-turn sweep is exactly as due on a school being swept as on one being minted. The witness is in tests/persistence.rs: a school created through the normal path, then rolled back to what an older head left behind — the table a later migration created dropped and its `_sqlx_migrations` row deleted — reads `relation "podcast_job" does not exist` before the sweep, and after it the table is back, empty and recorded as applied, so the next boot is a no-op. Every persistence test's second boot runs the sweep too (reboot()). cargo check --all-targets and clippy -D warnings clean; persistence 11/11. Local-Gate: 05ce93b5c478baa9a9ae80dd0bc8f99044a31f53 (1470 passed, 450s) --- src/database.rs | 59 ++++++++++++++++++++++++--- src/main.rs | 6 ++- src/tenant.rs | 96 +++++++++++++++++++++++++++++++++++++++++++- tests/persistence.rs | 77 +++++++++++++++++++++++++++++++++-- 4 files changed, 226 insertions(+), 12 deletions(-) diff --git a/src/database.rs b/src/database.rs index 3e85c3e..3ca5871 100644 --- a/src/database.rs +++ b/src/database.rs @@ -40,7 +40,9 @@ pub type Database = sqlx::PgPool; /// Connect to the **control** database, apply the control schema, seed the /// builder account and ensure the school-template database. School databases -/// are brought up separately, one per school, by [`crate::tenant::Tenants`]. +/// are brought up separately, one per school, by [`crate::tenant::Tenants`] — +/// which also sweeps every registered one to the school-schema head before +/// this returns. /// /// The dial is retried forever (one-second cadence): the database is normally /// a sibling container booting in parallel, and a process that exits on the @@ -88,6 +90,12 @@ pub async fn init(cfg: &Config) -> Result { // Schools a previous boot left half-made (its registry row committed, its // database not yet there) are finished before this one serves anything. tenants.reconcile_provisioning().await?; + // Then every school database in the registry is brought to the school + // schema head — the one step that keeps a school minted under an older + // head from serving `500`s on whatever a later migration added, a re-dial + // applying no migrations of its own. A school that fails is logged and + // skipped, never fatal: see [`Tenants::sweep_school_schemas`]. + tenants.sweep_school_schemas().await; Ok(tenants) } @@ -125,8 +133,9 @@ fn pool_options(max_connections: u32) -> PgPoolOptions { } /// A pool over one school database with the school pool sizing. The schema is -/// the caller's business — [`migrate_school`] for a mint, nothing for a -/// re-dial of an existing school. +/// the caller's business — [`migrate_school`] for a mint or the boot's +/// [`crate::tenant::Tenants::sweep_school_schemas`], nothing for a re-dial of +/// a school being served. pub(crate) async fn school_pool( base: &PgConnectOptions, db_name: &str, @@ -271,9 +280,10 @@ pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> { } /// Apply the school schema to a school database — the template at boot, every -/// newly minted school at create — then sweep the chatbot and RAG turns the -/// previous process owed an answer. Idempotent: an already-migrated database -/// runs only the sweep. +/// newly minted school at create, and every registered school in the boot's +/// [`crate::tenant::Tenants::sweep_school_schemas`] — then sweep the chatbot +/// and RAG turns the previous process owed an answer. Idempotent: an +/// already-migrated database runs only the sweep. pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { migrator("school") .await? @@ -315,6 +325,34 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { Ok(()) } +/// The migration versions a database records as applied, off sqlx's own +/// `_sqlx_migrations`. A database that has never run a migration has no +/// tracking table at all, and that is "nothing applied", not a failure: the +/// boot sweep reads this of every school database, a database whose create +/// died before its first migration included. +pub(crate) async fn applied_versions(pool: &PgPool) -> Result, sqlx::Error> { + match sqlx::query_scalar::<_, i64>("SELECT version FROM _sqlx_migrations") + .fetch_all(pool) + .await + { + Ok(versions) => Ok(versions.into_iter().collect()), + Err(err) if is_undefined_table(&err) => Ok(HashSet::new()), + Err(err) => Err(err), + } +} + +/// How many of the school schema's migrations `applied` does not carry — the +/// boot sweep's "does this school need anything" read, and the count its +/// per-school line reports. Zero means the database is at head, so the +/// [`migrate_school`] run that follows is a pure no-op. +pub(crate) async fn pending_school_migrations(applied: &HashSet) -> Result { + let migrator = migrator("school").await?; + Ok(migrator + .iter() + .filter(|migration| !applied.contains(&migration.version)) + .count()) +} + /// The advisory-lock key [`ensure_template`] holds while it creates and /// migrates the template: one name for one control database, contended only /// by concurrent boots of the same deployment. Distinct from @@ -391,6 +429,15 @@ pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool { is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index") } +/// `42P01` — the relation is not there. The one catalogue miss the boot's +/// school sweep reads as an answer rather than a failure: a database that has +/// never run a migration carries no `_sqlx_migrations` at all, which is +/// "nothing applied", not a broken school. +pub(crate) fn is_undefined_table(err: &sqlx::Error) -> bool { + err.as_database_error() + .is_some_and(|db| db.code().as_deref() == Some("42P01")) +} + /// The violated `UNIQUE` constraint's name, when `err` is a unique violation /// (`23505`). The constraint name is the stable handle call sites map /// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is diff --git a/src/main.rs b/src/main.rs index c71756e..344ec70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,8 +25,10 @@ async fn main() -> anyhow::Result<()> { // one request that pays for it (see `PasswordHash::prewarm_decoy`). hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); // Connects to the control database, migrates it and seeds the builder — - // all of it idempotent and unconditional on every boot. School databases - // come up lazily, one connection each, on first use. + // all of it idempotent and unconditional on every boot. Every registered + // school is brought to the school-schema head here too (see + // `Tenants::sweep_school_schemas`); school pools themselves come up + // lazily, one connection each, on first use. let tenants = database::init(&cfg).await?; tokio::fs::create_dir_all(&cfg.files_path) .await diff --git a/src/tenant.rs b/src/tenant.rs index 2c2ec0f..9415d2b 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -26,7 +26,8 @@ use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; use uuid::Uuid; use crate::database::{ - Database, create_database_sql, ensure_database, migrate_school, school_pool, unique_violation, + Database, applied_versions, create_database_sql, ensure_database, migrate_school, + pending_school_migrations, school_pool, unique_violation, }; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; @@ -713,6 +714,99 @@ impl Tenants { Ok(()) } + /// Apply the school schema to every school database in the registry. + /// + /// The invariant this restores: **every school database in the control + /// database is at the school-schema head after boot**, because a school + /// database is only ever migrated at mint or at boot. A school is minted + /// through `bring_up` — the create path and + /// [`Tenants::reconcile_provisioning`] both — with whatever schema head + /// the process that minted it carried, and nothing afterwards ever touches + /// its schema: a re-dial applies no migrations (see + /// `crate::database::school_pool`), and `reconcile_provisioning` only + /// reaches rows still marked `provisioning`. A school minted before a + /// migration landed therefore keeps yesterday's tables for good, and its + /// routes answer `500` on whatever that migration added — the live + /// deployment served `relation "podcast_job" does not exist` on + /// `POST /podcast/jobs` for exactly this reason. + /// + /// Failure policy: **one school must never take the boot down.** A school + /// that fails to migrate is logged at ERROR with its id and slug and left + /// exactly as it stood — no registry row and no status is written here, so + /// a failed school stays as usable (or unusable) as it was before the + /// sweep, and the next boot retries it. sqlx's tracking table is what + /// makes the retry safe: a migration that died mid-flight is re-run, not + /// half-believed. + pub async fn sweep_school_schemas(&self) { + let rows: Vec<(Uuid, String)> = + match sqlx::query_as("SELECT id, slug FROM school ORDER BY created_at") + .fetch_all(&self.control) + .await + { + Ok(rows) => rows, + // The control database was migrated moments ago in this same + // boot, so this is a surprise and not a state — but a boot + // that refuses to serve over it would be down for every school + // at once, which the failure policy above will not have. + Err(err) => { + tracing::error!("school schema sweep could not list the registry: {err}"); + return; + } + }; + let total = rows.len(); + let mut migrated = 0usize; + for (id, slug) in rows { + let id = SchoolId(id); + match self.sweep_school(id).await { + Ok(pending) if pending > 0 => { + migrated += 1; + tracing::info!( + school = %id.uuid(), + slug = %slug, + "school schema sweep applied {pending} migration(s) to a school behind the head" + ); + } + Ok(_) => {} + Err(err) => tracing::error!( + school = %id.uuid(), + slug = %slug, + "school schema sweep failed — this school is left as it was and the next boot \ + retries it: {err}" + ), + } + } + tracing::info!("school schema sweep: {total} schools, {migrated} migrated"); + } + + /// One school's step of [`Tenants::sweep_school_schemas`]: dial it, bring + /// it to head, close the pool. The pool is made and closed inside this + /// call — a school this boot never serves must not leave one behind (the + /// cache is what keeps a served school's pool, and the sweep is not a + /// serve), and the close has to sit outside [`Tenants::bring_to_head`] so + /// no `?` on its error path can skip it. + async fn sweep_school(&self, id: SchoolId) -> Result { + let db_name = school_db_name(&self.control_db, id.uuid()); + let pool = school_pool(&self.base, &db_name).await?; + let swept = Self::bring_to_head(&pool).await; + pool.close().await; + swept + } + + /// Apply whatever the school schema has that `pool` has not — idempotent, + /// so a school already at head costs one `_sqlx_migrations` read and a + /// no-op migrator run. Returns how many migrations were pending, which is + /// what the sweep's per-school line reports. + /// + /// [`crate::database::migrate_school`], not the bare migrator: it also + /// sweeps the chatbot and RAG turns the previous process owed an answer, + /// which is exactly as due on a school being swept as on one being minted. + async fn bring_to_head(pool: &Database) -> Result { + let applied = applied_versions(pool).await?; + let pending = pending_school_migrations(&applied).await?; + migrate_school(pool).await?; + Ok(pending) + } + /// Forget a school's pool and close it. The next request dials a fresh /// one. /// diff --git a/tests/persistence.rs b/tests/persistence.rs index 60dd3a5..201c311 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -18,11 +18,12 @@ use hezarfen_backend::tenant::{Slug, Tenants}; use hezarfen_backend::{build_router, database}; use serde_json::json; -/// Re-apply the school schema to the live school database and hand back a -/// fresh router over the same deployment — a second boot in every way that -/// matters to these tests. +/// Re-apply the school schema to the live school database, run the boot's +/// sweep over every registered school, and hand back a fresh router over the +/// same deployment — a second boot in every way that matters to these tests. async fn reboot(db: &Database, tenants: &Tenants) -> Router { database::migrate_school(db).await.expect("re-migration"); + tenants.sweep_school_schemas().await; build_router(AppState { db: tenants.control().clone(), tenants: tenants.clone(), @@ -990,6 +991,76 @@ async fn a_half_made_school_is_finished_by_the_next_boot() { .expect("clean up the minted school"); } +/// A school database that is behind the school-schema head is brought forward +/// by the next boot — the invariant `sweep_school_schemas` exists for: a +/// school database is migrated at mint and never again, so one minted before +/// a migration landed keeps yesterday's tables for good unless the boot +/// re-applies the schema to it. +/// +/// The drift is the live deployment's, simulated end to end: a school created +/// through the normal path (registry row, database, schema at head), then +/// rolled back to what an older head left behind — the table a later +/// migration created is dropped and that migration's tracking row is deleted, +/// so sqlx believes it was never applied. Before the sweep that school stayed +/// exactly like that: the row is `active`, which is past +/// `reconcile_provisioning`, and a re-dial applies no migrations. Its podcast +/// routes answered `500` (`relation "podcast_job" does not exist`), which is +/// why this asserts on a query over the table and not on the catalogue alone. +#[tokio::test] +async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() { + let tenants = database::init_test_tenants().await; + let slug = Slug::try_new("behind-the-head").unwrap(); + let school = tenants + .create( + hezarfen_backend::tenant::SchoolId::generate(), + &slug, + "Behind The Head", + ModuleSet::all(), + ) + .await + .expect("a school through the normal path — its database is at head"); + + // The drift: exactly what a school minted before the podcast migration + // carries — no table and no tracking row for it. + sqlx::query("DROP TABLE podcast_job") + .execute(&school) + .await + .expect("drop the table a later school migration created"); + sqlx::query("DELETE FROM _sqlx_migrations WHERE version = 20260917000003") + .execute(&school) + .await + .expect("forget the migration that created it"); + let err = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM podcast_job") + .fetch_one(&school) + .await + .expect_err("a school behind the head cannot read the table yet"); + assert!( + err.to_string().contains("does not exist"), + "the drift is the missing relation, not something else: {err}" + ); + + // The boot: the sweep `database::init` runs before the server serves. + tenants.sweep_school_schemas().await; + + let jobs: i64 = sqlx::query_scalar("SELECT count(*) FROM podcast_job") + .fetch_one(&school) + .await + .expect("the boot swept the school up to the schema head"); + assert_eq!(jobs, 0, "the re-created table starts empty"); + + // And the pending migration is recorded as applied, so the next boot's + // sweep is a no-op rather than a re-run. + let applied: i64 = + sqlx::query_scalar("SELECT count(*) FROM _sqlx_migrations WHERE version = 20260917000003") + .fetch_one(&school) + .await + .expect("the tracking table"); + assert_eq!( + applied, 1, + "the swept migration is recorded, keeping the next boot a no-op" + ); +} + /// One school's stored status, straight off the registry row. async fn status_of(control: &Database, slug: &str) -> String { sqlx::query_scalar("SELECT status FROM school WHERE slug = $1")