The boot sweeps every school database to the school-schema head
Browse files at this commitee72900e361aa197b163143e5d80f525f54067ffParent: c2ac4f8- fix
- the boot sweeps every school database to the school-schema head
4 changed files +226 -12
- src/database.rs +53 -6
- src/main.rs +4 -2
- src/tenant.rs +95 -1
- tests/persistence.rs +74 -3
src/database.rsmodified+53 -6
| @@ -40,7 +40,9 @@ pub type Database = sqlx::PgPool; | ||
| 40 | 40 | |
| 41 | 41 | /// Connect to the **control** database, apply the control schema, seed the |
| 42 | 42 | /// builder account and ensure the school-template database. School databases |
| 43 | -/// are brought up separately, one per school, by [`crate::tenant::Tenants`]. | |
| 43 | +/// are brought up separately, one per school, by [`crate::tenant::Tenants`] — | |
| 44 | +/// which also sweeps every registered one to the school-schema head before | |
| 45 | +/// this returns. | |
| 44 | 46 | /// |
| 45 | 47 | /// The dial is retried forever (one-second cadence): the database is normally |
| 46 | 48 | /// a sibling container booting in parallel, and a process that exits on the |
| @@ -88,6 +90,12 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { | ||
| 88 | 90 | // Schools a previous boot left half-made (its registry row committed, its |
| 89 | 91 | // database not yet there) are finished before this one serves anything. |
| 90 | 92 | tenants.reconcile_provisioning().await?; |
| 93 | + // Then every school database in the registry is brought to the school | |
| 94 | + // schema head — the one step that keeps a school minted under an older | |
| 95 | + // head from serving `500`s on whatever a later migration added, a re-dial | |
| 96 | + // applying no migrations of its own. A school that fails is logged and | |
| 97 | + // skipped, never fatal: see [`Tenants::sweep_school_schemas`]. | |
| 98 | + tenants.sweep_school_schemas().await; | |
| 91 | 99 | |
| 92 | 100 | Ok(tenants) |
| 93 | 101 | } |
| @@ -125,8 +133,9 @@ fn pool_options(max_connections: u32) -> PgPoolOptions { | ||
| 125 | 133 | } |
| 126 | 134 | |
| 127 | 135 | /// A pool over one school database with the school pool sizing. The schema is |
| 128 | -/// the caller's business — [`migrate_school`] for a mint, nothing for a | |
| 129 | -/// re-dial of an existing school. | |
| 136 | +/// the caller's business — [`migrate_school`] for a mint or the boot's | |
| 137 | +/// [`crate::tenant::Tenants::sweep_school_schemas`], nothing for a re-dial of | |
| 138 | +/// a school being served. | |
| 130 | 139 | pub(crate) async fn school_pool( |
| 131 | 140 | base: &PgConnectOptions, |
| 132 | 141 | db_name: &str, |
| @@ -271,9 +280,10 @@ pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> { | ||
| 271 | 280 | } |
| 272 | 281 | |
| 273 | 282 | /// Apply the school schema to a school database — the template at boot, every |
| 274 | -/// newly minted school at create — then sweep the chatbot and RAG turns the | |
| 275 | -/// previous process owed an answer. Idempotent: an already-migrated database | |
| 276 | -/// runs only the sweep. | |
| 283 | +/// newly minted school at create, and every registered school in the boot's | |
| 284 | +/// [`crate::tenant::Tenants::sweep_school_schemas`] — then sweep the chatbot | |
| 285 | +/// and RAG turns the previous process owed an answer. Idempotent: an | |
| 286 | +/// already-migrated database runs only the sweep. | |
| 277 | 287 | pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { |
| 278 | 288 | migrator("school") |
| 279 | 289 | .await? |
| @@ -315,6 +325,34 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { | ||
| 315 | 325 | Ok(()) |
| 316 | 326 | } |
| 317 | 327 | |
| 328 | +/// The migration versions a database records as applied, off sqlx's own | |
| 329 | +/// `_sqlx_migrations`. A database that has never run a migration has no | |
| 330 | +/// tracking table at all, and that is "nothing applied", not a failure: the | |
| 331 | +/// boot sweep reads this of every school database, a database whose create | |
| 332 | +/// died before its first migration included. | |
| 333 | +pub(crate) async fn applied_versions(pool: &PgPool) -> Result<HashSet<i64>, sqlx::Error> { | |
| 334 | + match sqlx::query_scalar::<_, i64>("SELECT version FROM _sqlx_migrations") | |
| 335 | + .fetch_all(pool) | |
| 336 | + .await | |
| 337 | + { | |
| 338 | + Ok(versions) => Ok(versions.into_iter().collect()), | |
| 339 | + Err(err) if is_undefined_table(&err) => Ok(HashSet::new()), | |
| 340 | + Err(err) => Err(err), | |
| 341 | + } | |
| 342 | +} | |
| 343 | + | |
| 344 | +/// How many of the school schema's migrations `applied` does not carry — the | |
| 345 | +/// boot sweep's "does this school need anything" read, and the count its | |
| 346 | +/// per-school line reports. Zero means the database is at head, so the | |
| 347 | +/// [`migrate_school`] run that follows is a pure no-op. | |
| 348 | +pub(crate) async fn pending_school_migrations(applied: &HashSet<i64>) -> Result<usize, AppError> { | |
| 349 | + let migrator = migrator("school").await?; | |
| 350 | + Ok(migrator | |
| 351 | + .iter() | |
| 352 | + .filter(|migration| !applied.contains(&migration.version)) | |
| 353 | + .count()) | |
| 354 | +} | |
| 355 | + | |
| 318 | 356 | /// The advisory-lock key [`ensure_template`] holds while it creates and |
| 319 | 357 | /// migrates the template: one name for one control database, contended only |
| 320 | 358 | /// by concurrent boots of the same deployment. Distinct from |
| @@ -391,6 +429,15 @@ pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool { | ||
| 391 | 429 | is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index") |
| 392 | 430 | } |
| 393 | 431 | |
| 432 | +/// `42P01` — the relation is not there. The one catalogue miss the boot's | |
| 433 | +/// school sweep reads as an answer rather than a failure: a database that has | |
| 434 | +/// never run a migration carries no `_sqlx_migrations` at all, which is | |
| 435 | +/// "nothing applied", not a broken school. | |
| 436 | +pub(crate) fn is_undefined_table(err: &sqlx::Error) -> bool { | |
| 437 | + err.as_database_error() | |
| 438 | + .is_some_and(|db| db.code().as_deref() == Some("42P01")) | |
| 439 | +} | |
| 440 | + | |
| 394 | 441 | /// The violated `UNIQUE` constraint's name, when `err` is a unique violation |
| 395 | 442 | /// (`23505`). The constraint name is the stable handle call sites map |
| 396 | 443 | /// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is |
src/main.rsmodified+4 -2
| @@ -25,8 +25,10 @@ async fn main() -> anyhow::Result<()> { | ||
| 25 | 25 | // one request that pays for it (see `PasswordHash::prewarm_decoy`). |
| 26 | 26 | hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); |
| 27 | 27 | // Connects to the control database, migrates it and seeds the builder — |
| 28 | - // all of it idempotent and unconditional on every boot. School databases | |
| 29 | - // come up lazily, one connection each, on first use. | |
| 28 | + // all of it idempotent and unconditional on every boot. Every registered | |
| 29 | + // school is brought to the school-schema head here too (see | |
| 30 | + // `Tenants::sweep_school_schemas`); school pools themselves come up | |
| 31 | + // lazily, one connection each, on first use. | |
| 30 | 32 | let tenants = database::init(&cfg).await?; |
| 31 | 33 | tokio::fs::create_dir_all(&cfg.files_path) |
| 32 | 34 | .await |
src/tenant.rsmodified+95 -1
| @@ -26,7 +26,8 @@ use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; | ||
| 26 | 26 | use uuid::Uuid; |
| 27 | 27 | |
| 28 | 28 | use crate::database::{ |
| 29 | - Database, create_database_sql, ensure_database, migrate_school, school_pool, unique_violation, | |
| 29 | + Database, applied_versions, create_database_sql, ensure_database, migrate_school, | |
| 30 | + pending_school_migrations, school_pool, unique_violation, | |
| 30 | 31 | }; |
| 31 | 32 | use crate::domain::monotonic_id::next_uuid; |
| 32 | 33 | use crate::domain::timestamp::Timestamp; |
| @@ -713,6 +714,99 @@ impl Tenants { | ||
| 713 | 714 | Ok(()) |
| 714 | 715 | } |
| 715 | 716 | |
| 717 | + /// Apply the school schema to every school database in the registry. | |
| 718 | + /// | |
| 719 | + /// The invariant this restores: **every school database in the control | |
| 720 | + /// database is at the school-schema head after boot**, because a school | |
| 721 | + /// database is only ever migrated at mint or at boot. A school is minted | |
| 722 | + /// through `bring_up` — the create path and | |
| 723 | + /// [`Tenants::reconcile_provisioning`] both — with whatever schema head | |
| 724 | + /// the process that minted it carried, and nothing afterwards ever touches | |
| 725 | + /// its schema: a re-dial applies no migrations (see | |
| 726 | + /// `crate::database::school_pool`), and `reconcile_provisioning` only | |
| 727 | + /// reaches rows still marked `provisioning`. A school minted before a | |
| 728 | + /// migration landed therefore keeps yesterday's tables for good, and its | |
| 729 | + /// routes answer `500` on whatever that migration added — the live | |
| 730 | + /// deployment served `relation "podcast_job" does not exist` on | |
| 731 | + /// `POST /podcast/jobs` for exactly this reason. | |
| 732 | + /// | |
| 733 | + /// Failure policy: **one school must never take the boot down.** A school | |
| 734 | + /// that fails to migrate is logged at ERROR with its id and slug and left | |
| 735 | + /// exactly as it stood — no registry row and no status is written here, so | |
| 736 | + /// a failed school stays as usable (or unusable) as it was before the | |
| 737 | + /// sweep, and the next boot retries it. sqlx's tracking table is what | |
| 738 | + /// makes the retry safe: a migration that died mid-flight is re-run, not | |
| 739 | + /// half-believed. | |
| 740 | + pub async fn sweep_school_schemas(&self) { | |
| 741 | + let rows: Vec<(Uuid, String)> = | |
| 742 | + match sqlx::query_as("SELECT id, slug FROM school ORDER BY created_at") | |
| 743 | + .fetch_all(&self.control) | |
| 744 | + .await | |
| 745 | + { | |
| 746 | + Ok(rows) => rows, | |
| 747 | + // The control database was migrated moments ago in this same | |
| 748 | + // boot, so this is a surprise and not a state — but a boot | |
| 749 | + // that refuses to serve over it would be down for every school | |
| 750 | + // at once, which the failure policy above will not have. | |
| 751 | + Err(err) => { | |
| 752 | + tracing::error!("school schema sweep could not list the registry: {err}"); | |
| 753 | + return; | |
| 754 | + } | |
| 755 | + }; | |
| 756 | + let total = rows.len(); | |
| 757 | + let mut migrated = 0usize; | |
| 758 | + for (id, slug) in rows { | |
| 759 | + let id = SchoolId(id); | |
| 760 | + match self.sweep_school(id).await { | |
| 761 | + Ok(pending) if pending > 0 => { | |
| 762 | + migrated += 1; | |
| 763 | + tracing::info!( | |
| 764 | + school = %id.uuid(), | |
| 765 | + slug = %slug, | |
| 766 | + "school schema sweep applied {pending} migration(s) to a school behind the head" | |
| 767 | + ); | |
| 768 | + } | |
| 769 | + Ok(_) => {} | |
| 770 | + Err(err) => tracing::error!( | |
| 771 | + school = %id.uuid(), | |
| 772 | + slug = %slug, | |
| 773 | + "school schema sweep failed — this school is left as it was and the next boot \ | |
| 774 | + retries it: {err}" | |
| 775 | + ), | |
| 776 | + } | |
| 777 | + } | |
| 778 | + tracing::info!("school schema sweep: {total} schools, {migrated} migrated"); | |
| 779 | + } | |
| 780 | + | |
| 781 | + /// One school's step of [`Tenants::sweep_school_schemas`]: dial it, bring | |
| 782 | + /// it to head, close the pool. The pool is made and closed inside this | |
| 783 | + /// call — a school this boot never serves must not leave one behind (the | |
| 784 | + /// cache is what keeps a served school's pool, and the sweep is not a | |
| 785 | + /// serve), and the close has to sit outside [`Tenants::bring_to_head`] so | |
| 786 | + /// no `?` on its error path can skip it. | |
| 787 | + async fn sweep_school(&self, id: SchoolId) -> Result<usize, AppError> { | |
| 788 | + let db_name = school_db_name(&self.control_db, id.uuid()); | |
| 789 | + let pool = school_pool(&self.base, &db_name).await?; | |
| 790 | + let swept = Self::bring_to_head(&pool).await; | |
| 791 | + pool.close().await; | |
| 792 | + swept | |
| 793 | + } | |
| 794 | + | |
| 795 | + /// Apply whatever the school schema has that `pool` has not — idempotent, | |
| 796 | + /// so a school already at head costs one `_sqlx_migrations` read and a | |
| 797 | + /// no-op migrator run. Returns how many migrations were pending, which is | |
| 798 | + /// what the sweep's per-school line reports. | |
| 799 | + /// | |
| 800 | + /// [`crate::database::migrate_school`], not the bare migrator: it also | |
| 801 | + /// sweeps the chatbot and RAG turns the previous process owed an answer, | |
| 802 | + /// which is exactly as due on a school being swept as on one being minted. | |
| 803 | + async fn bring_to_head(pool: &Database) -> Result<usize, AppError> { | |
| 804 | + let applied = applied_versions(pool).await?; | |
| 805 | + let pending = pending_school_migrations(&applied).await?; | |
| 806 | + migrate_school(pool).await?; | |
| 807 | + Ok(pending) | |
| 808 | + } | |
| 809 | + | |
| 716 | 810 | /// Forget a school's pool and close it. The next request dials a fresh |
| 717 | 811 | /// one. |
| 718 | 812 | /// |
tests/persistence.rsmodified+74 -3
| @@ -18,11 +18,12 @@ use hezarfen_backend::tenant::{Slug, Tenants}; | ||
| 18 | 18 | use hezarfen_backend::{build_router, database}; |
| 19 | 19 | use serde_json::json; |
| 20 | 20 | |
| 21 | -/// Re-apply the school schema to the live school database and hand back a | |
| 22 | -/// fresh router over the same deployment — a second boot in every way that | |
| 23 | -/// matters to these tests. | |
| 21 | +/// Re-apply the school schema to the live school database, run the boot's | |
| 22 | +/// sweep over every registered school, and hand back a fresh router over the | |
| 23 | +/// same deployment — a second boot in every way that matters to these tests. | |
| 24 | 24 | async fn reboot(db: &Database, tenants: &Tenants) -> Router { |
| 25 | 25 | database::migrate_school(db).await.expect("re-migration"); |
| 26 | + tenants.sweep_school_schemas().await; | |
| 26 | 27 | build_router(AppState { |
| 27 | 28 | db: tenants.control().clone(), |
| 28 | 29 | tenants: tenants.clone(), |
| @@ -990,6 +991,76 @@ async fn a_half_made_school_is_finished_by_the_next_boot() { | ||
| 990 | 991 | .expect("clean up the minted school"); |
| 991 | 992 | } |
| 992 | 993 | |
| 994 | +/// A school database that is behind the school-schema head is brought forward | |
| 995 | +/// by the next boot — the invariant `sweep_school_schemas` exists for: a | |
| 996 | +/// school database is migrated at mint and never again, so one minted before | |
| 997 | +/// a migration landed keeps yesterday's tables for good unless the boot | |
| 998 | +/// re-applies the schema to it. | |
| 999 | +/// | |
| 1000 | +/// The drift is the live deployment's, simulated end to end: a school created | |
| 1001 | +/// through the normal path (registry row, database, schema at head), then | |
| 1002 | +/// rolled back to what an older head left behind — the table a later | |
| 1003 | +/// migration created is dropped and that migration's tracking row is deleted, | |
| 1004 | +/// so sqlx believes it was never applied. Before the sweep that school stayed | |
| 1005 | +/// exactly like that: the row is `active`, which is past | |
| 1006 | +/// `reconcile_provisioning`, and a re-dial applies no migrations. Its podcast | |
| 1007 | +/// routes answered `500` (`relation "podcast_job" does not exist`), which is | |
| 1008 | +/// why this asserts on a query over the table and not on the catalogue alone. | |
| 1009 | +#[tokio::test] | |
| 1010 | +async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() { | |
| 1011 | + let tenants = database::init_test_tenants().await; | |
| 1012 | + let slug = Slug::try_new("behind-the-head").unwrap(); | |
| 1013 | + let school = tenants | |
| 1014 | + .create( | |
| 1015 | + hezarfen_backend::tenant::SchoolId::generate(), | |
| 1016 | + &slug, | |
| 1017 | + "Behind The Head", | |
| 1018 | + ModuleSet::all(), | |
| 1019 | + ) | |
| 1020 | + .await | |
| 1021 | + .expect("a school through the normal path — its database is at head"); | |
| 1022 | + | |
| 1023 | + // The drift: exactly what a school minted before the podcast migration | |
| 1024 | + // carries — no table and no tracking row for it. | |
| 1025 | + sqlx::query("DROP TABLE podcast_job") | |
| 1026 | + .execute(&school) | |
| 1027 | + .await | |
| 1028 | + .expect("drop the table a later school migration created"); | |
| 1029 | + sqlx::query("DELETE FROM _sqlx_migrations WHERE version = 20260917000003") | |
| 1030 | + .execute(&school) | |
| 1031 | + .await | |
| 1032 | + .expect("forget the migration that created it"); | |
| 1033 | + let err = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM podcast_job") | |
| 1034 | + .fetch_one(&school) | |
| 1035 | + .await | |
| 1036 | + .expect_err("a school behind the head cannot read the table yet"); | |
| 1037 | + assert!( | |
| 1038 | + err.to_string().contains("does not exist"), | |
| 1039 | + "the drift is the missing relation, not something else: {err}" | |
| 1040 | + ); | |
| 1041 | + | |
| 1042 | + // The boot: the sweep `database::init` runs before the server serves. | |
| 1043 | + tenants.sweep_school_schemas().await; | |
| 1044 | + | |
| 1045 | + let jobs: i64 = sqlx::query_scalar("SELECT count(*) FROM podcast_job") | |
| 1046 | + .fetch_one(&school) | |
| 1047 | + .await | |
| 1048 | + .expect("the boot swept the school up to the schema head"); | |
| 1049 | + assert_eq!(jobs, 0, "the re-created table starts empty"); | |
| 1050 | + | |
| 1051 | + // And the pending migration is recorded as applied, so the next boot's | |
| 1052 | + // sweep is a no-op rather than a re-run. | |
| 1053 | + let applied: i64 = | |
| 1054 | + sqlx::query_scalar("SELECT count(*) FROM _sqlx_migrations WHERE version = 20260917000003") | |
| 1055 | + .fetch_one(&school) | |
| 1056 | + .await | |
| 1057 | + .expect("the tracking table"); | |
| 1058 | + assert_eq!( | |
| 1059 | + applied, 1, | |
| 1060 | + "the swept migration is recorded, keeping the next boot a no-op" | |
| 1061 | + ); | |
| 1062 | +} | |
| 1063 | + | |
| 993 | 1064 | /// One school's stored status, straight off the registry row. |
| 994 | 1065 | async fn status_of(control: &Database, slug: &str) -> String { |
| 995 | 1066 | sqlx::query_scalar("SELECT status FROM school WHERE slug = $1") |