forge
Explore
Log in

Don't you dare go Hollow

Idempotent school-template create across boots

Browse files at this commit

331ae9366784c826687e5c5d8043ab6b8c5b929dAhmet Kaan GümüşParent: 5ea87b2
  • fix
    • idempotent school-template create across boots
Show full message
🐛 fix: idempotent school-template create across boots

The boot template was created by an unconditional `CREATE DATABASE` whose
`already exists` refusal was swallowed, so every restart logged a server-side
`ERROR: database "…" already exists`. Worse, two boots racing on a missing
template killed each other: Postgres reports the *losing* create as
`23505 duplicate key value violates unique constraint
"pg_database_datname_index"`, never `42P04`, and the guard matched only
`42P04` (measured: four boots racing, three died).

`CREATE DATABASE` has no `IF NOT EXISTS` in Postgres (syntax error), so the
create now probes `pg_database` first, the swallow accepts both SQLSTATEs
(`is_database_exists`), and the boot's create-and-migrate runs under its own
advisory lock — the pattern the test harness already uses for its template.
`scripts/boot_race.sh` is the reproduction.

Local: cargo nextest run --no-fail-fast → 1373 passed. clippy clean.
N=8 bash scripts/boot_race.sh → 8/8 boots up, 0 create-refusal lines.
scripts/boot_race.shadded+72 -0
@@ -0,0 +1,72 @@
1+#!/usr/bin/env bash
2+# Boot N copies of the backend at once against a Postgres whose school
3+# template has just been dropped, and report what each boot did.
4+#
5+# This is the reproduction for the concurrent-boot class. Two things are being
6+# watched:
7+# * every boot must reach `listening` — overlapping `CREATE DATABASE`s used
8+# to kill the losers, because Postgres reports the losing side as a
9+# `pg_database_datname_index` unique violation (`23505`) rather than the
10+# `42P04` duplicate-database error, and the swallow only matched `42P04`;
11+# * the server log must stay clean *of create refusals* — a create that is
12+# issued and refused is logged by the server even when the client swallows
13+# the error, which is why the create now runs behind a probe and under an
14+# advisory lock. The assertion is scoped to those lines so that a test
15+# suite sharing the server (its deliberate foreign-key violations) does
16+# not read as a boot failure.
17+# Exit status is non-zero if any boot failed or the server logged a create
18+# refusal.
19+#
20+# The template of the control database is dropped first; the next boot (this
21+# script, or your usual `podman compose up -d backend`) rebuilds and migrates
22+# it, so a dev database is the only thing this may disturb.
23+#
24+# Needs the compose Postgres up (`podman compose up -d postgres`) and a built
25+# binary (`cargo build`).
26+set -euo pipefail
27+
28+CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen_backend_postgres}"
29+CONTROL_DB="${HEZARFEN_CONTROL_DB:-hezarfen_control}"
30+N="${N:-8}"
31+BASE_PORT="${BASE_PORT:-7800}"
32+OUT="${OUT:-$(mktemp -d)}"
33+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
34+BIN="${BIN:-$HERE/target/debug/hezarfen_backend}"
35+
36+psql() { podman exec -i "$CONTAINER" psql -U hezarfen -v ON_ERROR_STOP=1 "$@"; }
37+
38+echo "== dropping ${CONTROL_DB}_school_template (the next boot rebuilds it)"
39+psql -d postgres -q -c "DROP DATABASE IF EXISTS \"${CONTROL_DB}_school_template\""
40+before=$(podman logs "$CONTAINER" 2>&1 | wc -l)
41+
42+echo "== racing $N boots on ports $BASE_PORT..$((BASE_PORT + N - 1))"
43+for i in $(seq 0 $((N - 1))); do
44+ (
45+ HOST=127.0.0.1 PORT=$((BASE_PORT + i)) \
46+ DATABASE_URL="postgres://hezarfen:hezarfen@127.0.0.1:5432/${CONTROL_DB}" \
47+ FILES_PATH="${FILES_PATH:-/tmp/hez-files}" RUST_LOG=info \
48+ timeout 30 "$BIN" >"$OUT/boot$i.log" 2>&1
49+ ) &
50+done
51+wait
52+
53+fail=0
54+for i in $(seq 0 $((N - 1))); do
55+ if grep -q "listening on" "$OUT/boot$i.log"; then
56+ echo " boot$i (port $((BASE_PORT + i))): up"
57+ else
58+ echo " boot$i (port $((BASE_PORT + i))): FAILED"
59+ tail -3 "$OUT/boot$i.log"
60+ fail=1
61+ fi
62+done
63+
64+errors=$(podman logs "$CONTAINER" 2>&1 | tail -n +$((before + 1)) |
65+ grep -E 'pg_database_datname_index|already exists' | grep -cE 'ERROR|FATAL' || true)
66+echo "== server log since the race: $errors create-refusal line(s)"
67+[ "$errors" -eq 0 ] || fail=1
68+
69+echo "== templates now on the server"
70+psql -d postgres -Atc "SELECT datname FROM pg_database WHERE datname LIKE '%_school_template'"
71+echo "== boot logs: $OUT"
72+exit "$fail"
src/database.rsmodified+91 -11
@@ -79,7 +79,7 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
79 // outside any transaction (`CREATE DATABASE` cannot run inside one —79 // outside any transaction (`CREATE DATABASE` cannot run inside one —
80 // `Pool::execute` runs bare autocommit statements), migrated once, then80 // `Pool::execute` runs bare autocommit statements), migrated once, then
81 // closed. A first boot lost to a concurrent boot of the same deployment81 // closed. A first boot lost to a concurrent boot of the same deployment
82- // adopts the winner's template via the duplicate-database swallow.82+ // adopts the winner's template — see [`ensure_database`].
83 let template = format!("{control_db}_school_template");83 let template = format!("{control_db}_school_template");
84 ensure_template(&control, &base, &template).await?;84 ensure_template(&control, &base, &template).await?;
85 85
@@ -144,6 +144,43 @@ pub(crate) fn create_database_sql(statement: &str, name: &str) -> String {
144 format!("{statement} \"{}\"", name.replace('"', "\"\""))144 format!("{statement} \"{}\"", name.replace('"', "\"\""))
145 }145 }
146 146
147+/// Create `name` unless the server already has it.
148+///
149+/// Postgres has no `IF NOT EXISTS` for `CREATE DATABASE` — the clause is a
150+/// syntax error there — so the "already there" case can only be settled by a
151+/// probe or by swallowing the refusal. Swallowing alone is not enough: a
152+/// refused create is *not* quiet, the server logs it as
153+/// `ERROR: database "…" already exists`, and a boot that finds its template in
154+/// place would print that line on every restart. The probe handles the common
155+/// case; the [`is_database_exists`] swallow stays as the backstop for the
156+/// window between probe and create, where rival boots win the race and the
157+/// statement is issued anyway.
158+pub(crate) async fn ensure_database(pool: &PgPool, name: &str) -> Result<(), sqlx::Error> {
159+ let present =
160+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM pg_database WHERE datname = $1")
161+ .bind(name)
162+ .fetch_one(pool)
163+ .await?;
164+ if present > 0 {
165+ tracing::debug!("database {name} already exists — adopting it");
166+ return Ok(());
167+ }
168+ match sqlx::query(sqlx::AssertSqlSafe(create_database_sql(
169+ "CREATE DATABASE",
170+ name,
171+ )))
172+ .execute(pool)
173+ .await
174+ {
175+ Ok(_) => Ok(()),
176+ Err(err) if is_database_exists(&err) => {
177+ tracing::debug!("database {name} was created by a rival boot — adopting it");
178+ Ok(())
179+ }
180+ Err(err) => Err(err),
181+ }
182+}
183+
147 async fn boot_control(base: &PgConnectOptions) -> Result<PgPool, sqlx::Error> {184 async fn boot_control(base: &PgConnectOptions) -> Result<PgPool, sqlx::Error> {
148 let pool = pool_options(10).connect_with(base.clone()).await?;185 let pool = pool_options(10).connect_with(base.clone()).await?;
149 // The migrator is built here rather than in [`migrator`]: its resolution186 // The migrator is built here rather than in [`migrator`]: its resolution
@@ -259,23 +296,55 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
259 Ok(())296 Ok(())
260 }297 }
261 298
299+/// The advisory-lock key [`ensure_template`] holds while it creates and
300+/// migrates the template: one name for one control database, contended only
301+/// by concurrent boots of the same deployment. Distinct from
302+/// [`TEST_TEMPLATE_LOCK_KEY`], which guards a different database.
303+const TEMPLATE_LOCK_KEY: i64 = 0x6865_7A74_6D70_0001;
304+
262 /// Ensure the school-template database exists and carries the current school305 /// Ensure the school-template database exists and carries the current school
263 /// schema. `CREATE DATABASE` runs on the control pool outside any306 /// schema. `CREATE DATABASE` runs on the control pool outside any
264-/// transaction; the loser of a race adopts the winner's database.307+/// transaction; a template another boot already made is adopted.
308+///
309+/// Boots of one deployment can overlap (a rolling restart, two replicas), and
310+/// this pair is a critical section across processes for the same reasons the
311+/// test harness's is (see [`ensure_test_template`]): unsynchronized, the
312+/// creates collide — the loser's `pg_database_datname_index` violation is
313+/// logged as a server-side `ERROR` even though [`ensure_database`] swallows
314+/// it — and two migrators interleave their DDL on the same fresh database and
315+/// kill each other on a duplicate table.
265 async fn ensure_template(316 async fn ensure_template(
266 control: &PgPool,317 control: &PgPool,
267 base: &PgConnectOptions,318 base: &PgConnectOptions,
268 name: &str,319 name: &str,
269 ) -> Result<(), AppError> {320 ) -> Result<(), AppError> {
270- if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(321+ // A connection of its own, held for the section: an advisory lock is a
271- "CREATE DATABASE",322+ // server-wide name, so which connection issues the `CREATE` and the
272- name,323+ // migrations inside the section does not matter — only that every boot
273- )))324+ // takes the lock first.
274- .execute(control)325+ let mut session = control.acquire().await?;
275- .await326+ sqlx::query("SELECT pg_advisory_lock($1)")
276- && !is_duplicate_database(&err) {327+ .bind(TEMPLATE_LOCK_KEY)
277- return Err(err.into());328+ .execute(&mut *session)
278- }329+ .await?;
330+ let ensured = ensure_template_locked(control, base, name).await;
331+ // Unlocked before anything is returned: the lock is session-scoped and the
332+ // connection goes back to the pool, so skipping this on the error path
333+ // would wedge every later boot.
334+ sqlx::query("SELECT pg_advisory_unlock($1)")
335+ .bind(TEMPLATE_LOCK_KEY)
336+ .execute(&mut *session)
337+ .await?;
338+ ensured
339+}
340+
341+/// The template's create-and-migrate, under [`ensure_template`]'s lock.
342+async fn ensure_template_locked(
343+ control: &PgPool,
344+ base: &PgConnectOptions,
345+ name: &str,
346+) -> Result<(), AppError> {
347+ ensure_database(control, name).await?;
279 // One migrator connection, made and closed: the template is never served.348 // One migrator connection, made and closed: the template is never served.
280 let pool = pool_options(1)349 let pool = pool_options(1)
281 .connect_with(base.clone().database(name))350 .connect_with(base.clone().database(name))
@@ -292,6 +361,17 @@ pub(crate) fn is_duplicate_database(err: &sqlx::Error) -> bool {
292 .is_some_and(|db| db.code().as_deref() == Some("42P04"))361 .is_some_and(|db| db.code().as_deref() == Some("42P04"))
293 }362 }
294 363
364+/// Is this error "the database is already there"? Two SQLSTATEs say yes:
365+/// `42P04`, the duplicate-database check `CREATE DATABASE` runs against the
366+/// catalog, and `23505` on `pg_database_datname_index` — how Postgres reports
367+/// the *losing* side of two concurrent creates, the name check and the
368+/// catalog insert not being one atomic step. Measured on 18.6: four boots
369+/// racing on an absent template, three of them got `23505` and died, so a
370+/// `42P04`-only guard is too narrow for the very race it exists for.
371+pub(crate) fn is_database_exists(err: &sqlx::Error) -> bool {
372+ is_duplicate_database(err) || unique_violation(err) == Some("pg_database_datname_index")
373+}
374+
295 /// The violated `UNIQUE` constraint's name, when `err` is a unique violation375 /// The violated `UNIQUE` constraint's name, when `err` is a unique violation
296 /// (`23505`). The constraint name is the stable handle call sites map376 /// (`23505`). The constraint name is the stable handle call sites map
297 /// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is377 /// refusals onto — `unique_violation(&e) == Some("school_pkey")` — and it is
src/tenant.rsmodified+2 -11
@@ -26,8 +26,7 @@ use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
26 use uuid::Uuid;26 use uuid::Uuid;
27 27
28 use crate::database::{28 use crate::database::{
29- Database, create_database_sql, is_duplicate_database, migrate_school, school_pool,29+ Database, create_database_sql, ensure_database, migrate_school, school_pool, unique_violation,
30- unique_violation,
31 };30 };
32 use crate::domain::monotonic_id::next_uuid;31 use crate::domain::monotonic_id::next_uuid;
33 use crate::domain::timestamp::Timestamp;32 use crate::domain::timestamp::Timestamp;
@@ -496,15 +495,7 @@ impl Tenants {
496 // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute`495 // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute`
497 // sends it as a bare autocommit statement. A name left over by a496 // sends it as a bare autocommit statement. A name left over by a
498 // create that died before its rollback is adopted, not fought.497 // create that died before its rollback is adopted, not fought.
499- if let Err(err) = sqlx::query(sqlx::AssertSqlSafe(create_database_sql(498+ ensure_database(&self.control, &db_name).await?;
500- "CREATE DATABASE",
501- &db_name,
502- )))
503- .execute(&self.control)
504- .await
505- && !is_duplicate_database(&err) {
506- return Err(err.into());
507- }
508 let pool = school_pool(&self.base, &db_name).await?;499 let pool = school_pool(&self.base, &db_name).await?;
509 let migrated = migrate_school(&pool).await;500 let migrated = migrate_school(&pool).await;
510 if migrated.is_err() {501 if migrated.is_err() {