forge
Explore
Log in

Don't you dare go Hollow

The boot sweeps every school database to the school-schema head

Browse files at this commit

ee72900e361aa197b163143e5d80f525f54067ffAhmet Kaan GümüşParent: c2ac4f8
  • fix
    • the boot sweeps every school database to the school-schema head
Show full message
🐛 fix(tenant): the boot sweeps every school database to the school-schema head

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.rsmodified+53 -6
@@ -40,7 +40,9 @@ pub type Database = sqlx::PgPool;
4040
4141 /// Connect to the **control** database, apply the control schema, seed the
4242 /// 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.
4446 ///
4547 /// The dial is retried forever (one-second cadence): the database is normally
4648 /// 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> {
8890 // Schools a previous boot left half-made (its registry row committed, its
8991 // database not yet there) are finished before this one serves anything.
9092 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;
9199
92100 Ok(tenants)
93101 }
@@ -125,8 +133,9 @@ fn pool_options(max_connections: u32) -> PgPoolOptions {
125133 }
126134
127135 /// 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.
130139 pub(crate) async fn school_pool(
131140 base: &PgConnectOptions,
132141 db_name: &str,
@@ -271,9 +280,10 @@ pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> {
271280 }
272281
273282 /// 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.
277287 pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
278288 migrator("school")
279289 .await?
@@ -315,6 +325,34 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
315325 Ok(())
316326 }
317327
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+
318356 /// The advisory-lock key [`ensure_template`] holds while it creates and
319357 /// migrates the template: one name for one control database, contended only
320358 /// by concurrent boots of the same deployment. Distinct from
@@ -391,6 +429,15 @@ pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool {
391429 is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index")
392430 }
393431
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+
394441 /// The violated `UNIQUE` constraint's name, when `err` is a unique violation
395442 /// (`23505`). The constraint name is the stable handle call sites map
396443 /// 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<()> {
2525 // one request that pays for it (see `PasswordHash::prewarm_decoy`).
2626 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
2727 // 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.
3032 let tenants = database::init(&cfg).await?;
3133 tokio::fs::create_dir_all(&cfg.files_path)
3234 .await
src/tenant.rsmodified+95 -1
@@ -26,7 +26,8 @@ use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
2626 use uuid::Uuid;
2727
2828 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,
3031 };
3132 use crate::domain::monotonic_id::next_uuid;
3233 use crate::domain::timestamp::Timestamp;
@@ -713,6 +714,99 @@ impl Tenants {
713714 Ok(())
714715 }
715716
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+
716810 /// Forget a school's pool and close it. The next request dials a fresh
717811 /// one.
718812 ///
tests/persistence.rsmodified+74 -3
@@ -18,11 +18,12 @@ use hezarfen_backend::tenant::{Slug, Tenants};
1818 use hezarfen_backend::{build_router, database};
1919 use serde_json::json;
2020
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.
2424 async fn reboot(db: &Database, tenants: &Tenants) -> Router {
2525 database::migrate_school(db).await.expect("re-migration");
26+ tenants.sweep_school_schemas().await;
2627 build_router(AppState {
2728 db: tenants.control().clone(),
2829 tenants: tenants.clone(),
@@ -990,6 +991,76 @@ async fn a_half_made_school_is_finished_by_the_next_boot() {
990991 .expect("clean up the minted school");
991992 }
992993
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+
9931064 /// One school's stored status, straight off the registry row.
9941065 async fn status_of(control: &Database, slug: &str) -> String {
9951066 sqlx::query_scalar("SELECT status FROM school WHERE slug = $1")